aboutsummaryrefslogtreecommitdiffstats
path: root/calendar/cal-util/cal-recur.c
blob: 99e4991323668d2bc9d2e9a3c2ffc6e6976cc500 (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
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
/*
 * Evolution calendar recurrence rule functions
 *
 * Copyright (C) 2000 Helix Code, Inc.
 *
 * Author: Damon Chaplin <damon@helixcode.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
 */

#include <config.h>
#include <stdlib.h>
#include <string.h>
#include <cal-util/cal-recur.h>
#include <cal-util/timeutil.h>


/*
 * Introduction to The Recurrence Generation Functions:
 *
 * Note: This is pretty complicated. See the iCalendar spec (RFC 2445) for
 *       the specification of the recurrence rules and lots of examples
 *   (sections 4.3.10 & 4.8.5). We also want to support the older
 *   vCalendar spec, though this should be easy since it is basically a
 *   subset of iCalendar.
 *
 * o An iCalendar event can have any number of recurrence rules specifying
 *   occurrences of the event, as well as dates & times of specific
 *   occurrences. It can also have any number of recurrence rules and
 *   specific dates & times specifying exceptions to the occurrences.
 *   So we first merge all the occurrences generated, eliminating any
 *   duplicates, then we generate all the exceptions and remove these to
 *   form the final set of occurrences.
 *
 * o There are 7 frequencies of occurrences: YEARLY, MONTHLY, WEEKLY, DAILY,
 *   HOURLY, MINUTELY & SECONDLY. The 'interval' property specifies the
 *   multiples of the frequency which we step by. We generate a 'set' of
 *   occurrences for each period defined by the frequency & interval.
 *   So for a YEARLY frequency with an interval of 3, we generate a set of
 *   occurrences for every 3rd year. We use complete years here -  any
 *   generated occurrences that occur before the event's start (or after its
 *   end) are just discarded.
 *
 * o There are 8 frequency modifiers: BYMONTH, BYWEEKNO, BYYEARDAY, BYMONTHDAY,
 *   BYDAY, BYHOUR, BYMINUTE & BYSECOND. These can either add extra occurrences
 *   or filter out occurrences. For example 'FREQ=YEARLY;BYMONTH=1,2' produces
 *   2 occurrences for each year rather than the default 1. And
 *   'FREQ=DAILY;BYMONTH=1' filters out all occurrences except those in Jan.
 *   If the modifier works on periods which are less than the recurrence
 *   frequency, then extra occurrences are added, otherwise occurrences are
 *   filtered. So we have 2 functions for each modifier - one to expand events
 *   and the other to filter. We use a table of functions for each frequency
 *   which points to the appropriate function to use for each modifier.
 *
 * o Any number of frequency modifiers can be used in a recurrence rule.
 *   (Though the iCalendar spec says that BYWEEKNO can only be used in a YEARLY
 *   rule, and some modifiers aren't appropriate for some frequencies - e.g.
 *   BYMONTHDAY is not really useful in a WEEKLY frequency, and BYYEARDAY is
 *   not useful in a MONTHLY or WEEKLY frequency).
 *   The frequency modifiers are applied in the order given above. The first 5
 *   modifier rules (BYMONTH, BYWEEKNO, BYYEARDAY, BYMONTHDAY & BYDAY) all
 *   produce the days on which the occurrences take place, and so we have to
 *   compute some of these in parallel rather than sequentially, or we may end
 *   up with too many days.
 *
 * o Note that some expansion functions may produce days which are invalid,
 *   e.g. 31st September, 30th Feb. These invalid days are removed before the
 *   BYHOUR, BYMINUTE & BYSECOND modifier functions are applied.
 *
 * o After the set of occurrences for the frequency interval are generated,
 *   the BYSETPOS property is used to select which of the occurrences are
 *   finally output. If BYSETPOS is not specified then all the occurrences are
 *   output.
 */

/* Define this for some debugging output. */
#if 0
#define CAL_OBJ_DEBUG   1
#endif

/* We will use icalrecurrencetype instead of this eventually. */
typedef struct {
    icalrecurrencetype_frequency freq;

    int            interval;

    /* Specifies the end of the recurrence. No occurrences are generated
       after this date. If it is 0, the event recurs forever. */
    time_t         enddate;

    /* WKST property - the week start day: 0 = Monday to 6 = Sunday. */
    gint           week_start_day;


    /* NOTE: I've used GList's here, but it doesn't matter if we use
       other data structures like arrays. The code should be easy to
       change. So long as it is easy to see if the modifier is set. */

    /* For BYMONTH modifier. A list of GINT_TO_POINTERs, 0-11. */
    GList         *bymonth;

    /* For BYWEEKNO modifier. A list of GINT_TO_POINTERs, [+-]1-53. */
    GList         *byweekno;

    /* For BYYEARDAY modifier. A list of GINT_TO_POINTERs, [+-]1-366. */
    GList         *byyearday;

    /* For BYMONTHDAY modifier. A list of GINT_TO_POINTERs, [+-]1-31. */
    GList         *bymonthday;

    /* For BYDAY modifier. A list of GINT_TO_POINTERs, in pairs.
       The first of each pair is the weekday, 0 = Monday to 6 = Sunday.
       The second of each pair is the week number [+-]0-53. */
    GList         *byday;

    /* For BYHOUR modifier. A list of GINT_TO_POINTERs, 0-23. */
    GList         *byhour;

    /* For BYMINUTE modifier. A list of GINT_TO_POINTERs, 0-59. */
    GList         *byminute;

    /* For BYSECOND modifier. A list of GINT_TO_POINTERs, 0-60. */
    GList         *bysecond;

    /* For BYSETPOS modifier. A list of GINT_TO_POINTERs, +ve or -ve. */
    GList         *bysetpos;
} CalRecurrence;

/* This is what we use to pass to all the filter functions. */
typedef struct _RecurData RecurData;
struct _RecurData {
    CalRecurrence *recur;

    /* This is used for the WEEKLY frequency. It is the offset from the
       week_start_day. */
    gint weekday_offset;

    /* This is used for fast lookup in BYMONTH filtering. */
    guint8 months[12];

    /* This is used for fast lookup in BYYEARDAY filtering. */
    guint8 yeardays[367], neg_yeardays[367]; /* Days are 1 - 366. */

    /* This is used for fast lookup in BYMONTHDAY filtering. */
    guint8 monthdays[32], neg_monthdays[32]; /* Days are 1 to 31. */

    /* This is used for fast lookup in BYDAY filtering. */
    guint8 weekdays[7];

    /* This is used for fast lookup in BYHOUR filtering. */
    guint8 hours[24];

    /* This is used for fast lookup in BYMINUTE filtering. */
    guint8 minutes[60];

    /* This is used for fast lookup in BYSECOND filtering. */
    guint8 seconds[62];
};

/* This is what we use to represent a date & time. */
typedef struct _CalObjTime CalObjTime;
struct _CalObjTime {
    guint16 year;
    guint8 month;       /* 0 - 11 */
    guint8 day;     /* 1 - 31 */
    guint8 hour;        /* 0 - 23 */
    guint8 minute;      /* 0 - 59 */
    guint8 second;      /* 0 - 59 (maybe up to 61 for leap seconds) */
    guint8 is_rdate;    /* TRUE if this is an RDATE, which may have an
                   end or duration set. */
};

/* This is what we use to represent specific recurrence dates.
   Note that we assume it starts with a CalObjTime when sorting. */
typedef struct _CalObjRecurrenceDate CalObjRecurrenceDate;
struct _CalObjRecurrenceDate {
    CalObjTime start;
    CalComponentPeriod *period;
};

/* The paramter we use to store the enddate in RRULE and EXRULE properties. */
#define EVOLUTION_END_DATE_PARAMETER    "X-EVOLUTION-ENDDATE"

typedef gboolean (*CalObjFindStartFn) (CalObjTime *event_start,
                       CalObjTime *event_end,
                       RecurData  *recur_data,
                       CalObjTime *interval_start,
                       CalObjTime *interval_end,
                       CalObjTime *cotime);
typedef gboolean (*CalObjFindNextFn)  (CalObjTime *cotime,
                       CalObjTime *event_end,
                       RecurData  *recur_data,
                       CalObjTime *interval_end);
typedef GArray*  (*CalObjFilterFn)    (RecurData  *recur_data,
                       GArray     *occs);

typedef struct _CalRecurVTable CalRecurVTable;
struct _CalRecurVTable {
    CalObjFindStartFn find_start_position;
    CalObjFindNextFn find_next_position;

    CalObjFilterFn bymonth_filter;
    CalObjFilterFn byweekno_filter;
    CalObjFilterFn byyearday_filter;
    CalObjFilterFn bymonthday_filter;
    CalObjFilterFn byday_filter;
    CalObjFilterFn byhour_filter;
    CalObjFilterFn byminute_filter;
    CalObjFilterFn bysecond_filter;
};


/* This is used to specify which parts of the CalObjTime to compare in
   cal_obj_time_compare(). */
typedef enum {
    CALOBJ_YEAR,
    CALOBJ_MONTH,
    CALOBJ_DAY,
    CALOBJ_HOUR,
    CALOBJ_MINUTE,
    CALOBJ_SECOND
} CalObjTimeComparison;

static void cal_recur_generate_instances_of_rule (CalComponent  *comp,
                          icalproperty  *prop,
                          time_t     start,
                          time_t     end,
                          CalRecurInstanceFn cb,
                          gpointer       cb_data);

static CalRecurrence * cal_recur_from_icalproperty (icalproperty *prop,
                            gboolean exception);
static gint cal_recur_ical_weekday_to_weekday   (enum icalrecurrencetype_weekday day);
static void cal_recur_free          (CalRecurrence  *r);


static gboolean cal_object_get_rdate_end    (CalObjTime *occ,
                         GArray     *rdate_periods);
static void cal_object_compute_duration (CalObjTime *start,
                         CalObjTime *end,
                         gint       *days,
                         gint       *seconds);

static gboolean generate_instances_for_chunk    (CalComponent       *comp,
                         time_t          comp_dtstart,
                         GSList         *rrules,
                         GSList         *rdates,
                         GSList         *exrules,
                         GSList         *exdates,
                         CalObjTime     *event_start,
                         CalObjTime     *chunk_start,
                         CalObjTime     *chunk_end,
                         time_t          interval_start_time,
                         time_t          interval_end_time,
                         gint            duration_days,
                         gint            duration_seconds,
                         CalRecurInstanceFn  cb,
                         gpointer        cb_data);

static GArray* cal_obj_expand_recurrence    (CalObjTime   *event_start,
                         CalRecurrence    *recur,
                         CalObjTime   *interval_start,
                         CalObjTime   *interval_end,
                         gboolean     *finished);

static GArray*  cal_obj_generate_set_yearly (RecurData  *recur_data,
                         CalRecurVTable *vtable,
                         CalObjTime *occ);
static GArray*  cal_obj_generate_set_monthly    (RecurData  *recur_data,
                         CalRecurVTable *vtable,
                         CalObjTime *occ);
static GArray*  cal_obj_generate_set_default    (RecurData  *recur_data,
                         CalRecurVTable *vtable,
                         CalObjTime *occ);


static CalRecurVTable* cal_obj_get_vtable   (icalrecurrencetype_frequency recur_type);
static void cal_obj_initialize_recur_data   (RecurData  *recur_data,
                         CalRecurrence  *recur,
                         CalObjTime *event_start);
static void cal_obj_sort_occurrences    (GArray     *occs);
static gint cal_obj_time_compare_func   (const void *arg1,
                         const void *arg2);
static void cal_obj_remove_duplicates_and_invalid_dates (GArray *occs);
static void cal_obj_remove_exceptions   (GArray     *occs,
                         GArray     *ex_occs);
static GArray*  cal_obj_bysetpos_filter     (CalRecurrence  *recur,
                         GArray     *occs);


static gboolean cal_obj_yearly_find_start_position (CalObjTime *event_start,
                            CalObjTime *event_end,
                            RecurData  *recur_data,
                            CalObjTime *interval_start,
                            CalObjTime *interval_end,
                            CalObjTime *cotime);
static gboolean cal_obj_yearly_find_next_position  (CalObjTime *cotime,
                            CalObjTime *event_end,
                            RecurData  *recur_data,
                            CalObjTime *interval_end);

static gboolean cal_obj_monthly_find_start_position (CalObjTime *event_start,
                             CalObjTime *event_end,
                             RecurData  *recur_data,
                             CalObjTime *interval_start,
                             CalObjTime *interval_end,
                             CalObjTime *cotime);
static gboolean cal_obj_monthly_find_next_position  (CalObjTime *cotime,
                             CalObjTime *event_end,
                             RecurData  *recur_data,
                             CalObjTime *interval_end);

static gboolean cal_obj_weekly_find_start_position (CalObjTime *event_start,
                            CalObjTime *event_end,
                            RecurData  *recur_data,
                            CalObjTime *interval_start,
                            CalObjTime *interval_end,
                            CalObjTime *cotime);
static gboolean cal_obj_weekly_find_next_position  (CalObjTime *cotime,
                            CalObjTime *event_end,
                            RecurData  *recur_data,
                            CalObjTime *interval_end);

static gboolean cal_obj_daily_find_start_position  (CalObjTime *event_start,
                            CalObjTime *event_end,
                            RecurData  *recur_data,
                            CalObjTime *interval_start,
                            CalObjTime *interval_end,
                            CalObjTime *cotime);
static gboolean cal_obj_daily_find_next_position   (CalObjTime *cotime,
                            CalObjTime *event_end,
                            RecurData  *recur_data,
                            CalObjTime *interval_end);

static gboolean cal_obj_hourly_find_start_position (CalObjTime *event_start,
                            CalObjTime *event_end,
                            RecurData  *recur_data,
                            CalObjTime *interval_start,
                            CalObjTime *interval_end,
                            CalObjTime *cotime);
static gboolean cal_obj_hourly_find_next_position  (CalObjTime *cotime,
                            CalObjTime *event_end,
                            RecurData  *recur_data,
                            CalObjTime *interval_end);

static gboolean cal_obj_minutely_find_start_position (CalObjTime *event_start,
                              CalObjTime *event_end,
                              RecurData  *recur_data,
                              CalObjTime *interval_start,
                              CalObjTime *interval_end,
                              CalObjTime *cotime);
static gboolean cal_obj_minutely_find_next_position  (CalObjTime *cotime,
                              CalObjTime *event_end,
                              RecurData  *recur_data,
                              CalObjTime *interval_end);

static gboolean cal_obj_secondly_find_start_position (CalObjTime *event_start,
                              CalObjTime *event_end,
                              RecurData  *recur_data,
                              CalObjTime *interval_start,
                              CalObjTime *interval_end,
                              CalObjTime *cotime);
static gboolean cal_obj_secondly_find_next_position  (CalObjTime *cotime,
                              CalObjTime *event_end,
                              RecurData  *recur_data,
                              CalObjTime *interval_end);

static GArray* cal_obj_bymonth_expand       (RecurData  *recur_data,
                         GArray     *occs);
static GArray* cal_obj_bymonth_filter       (RecurData  *recur_data,
                         GArray     *occs);
static GArray* cal_obj_byweekno_expand      (RecurData  *recur_data,
                         GArray     *occs);
#if 0
/* This isn't used at present. */
static GArray* cal_obj_byweekno_filter      (RecurData  *recur_data,
                         GArray     *occs);
#endif
static GArray* cal_obj_byyearday_expand     (RecurData  *recur_data,
                         GArray     *occs);
static GArray* cal_obj_byyearday_filter     (RecurData  *recur_data,
                         GArray     *occs);
static GArray* cal_obj_bymonthday_expand    (RecurData  *recur_data,
                         GArray     *occs);
static GArray* cal_obj_bymonthday_filter    (RecurData  *recur_data,
                         GArray     *occs);
static GArray* cal_obj_byday_expand_yearly  (RecurData  *recur_data,
                         GArray     *occs);
static GArray* cal_obj_byday_expand_monthly (RecurData  *recur_data,
                         GArray     *occs);
static GArray* cal_obj_byday_expand_weekly  (RecurData  *recur_data,
                         GArray     *occs);
static GArray* cal_obj_byday_filter     (RecurData  *recur_data,
                         GArray     *occs);
static GArray* cal_obj_byhour_expand        (RecurData  *recur_data,
                         GArray     *occs);
static GArray* cal_obj_byhour_filter        (RecurData  *recur_data,
                         GArray     *occs);
static GArray* cal_obj_byminute_expand      (RecurData  *recur_data,
                         GArray     *occs);
static GArray* cal_obj_byminute_filter      (RecurData  *recur_data,
                         GArray     *occs);
static GArray* cal_obj_bysecond_expand      (RecurData  *recur_data,
                         GArray     *occs);
static GArray* cal_obj_bysecond_filter      (RecurData  *recur_data,
                         GArray     *occs);

static void cal_obj_time_add_months     (CalObjTime *cotime,
                         gint        months);
static void cal_obj_time_add_days       (CalObjTime *cotime,
                         gint        days);
static void cal_obj_time_add_hours      (CalObjTime *cotime,
                         gint        hours);
static void cal_obj_time_add_minutes        (CalObjTime *cotime,
                         gint        minutes);
static void cal_obj_time_add_seconds        (CalObjTime *cotime,
                         gint        seconds);
static gint cal_obj_time_compare        (CalObjTime *cotime1,
                         CalObjTime *cotime2,
                         CalObjTimeComparison type);
static gint cal_obj_time_weekday        (CalObjTime *cotime,
                         CalRecurrence *recur);
static gint cal_obj_time_weekday_offset     (CalObjTime *cotime,
                         CalRecurrence *recur);
static gint cal_obj_time_day_of_year        (CalObjTime *cotime);
static void cal_obj_time_find_first_week    (CalObjTime *cotime,
                         RecurData  *recur_data);
static void cal_object_time_from_time       (CalObjTime *cotime,
                         time_t      t);
static gint cal_obj_date_only_compare_func (const void *arg1,
                        const void *arg2);



static gboolean cal_recur_ensure_end_dates  (CalComponent   *comp,
                         gboolean    refresh);
static gboolean cal_recur_ensure_rule_end_date  (CalComponent   *comp,
                         icalproperty   *prop,
                         gboolean    exception,
                         gboolean    refresh);
static gboolean cal_recur_ensure_rule_end_date_cb   (CalComponent   *comp,
                             time_t      instance_start,
                             time_t      instance_end,
                             gpointer    data);
static time_t cal_recur_get_rule_end_date   (icalproperty   *prop);
static void cal_recur_set_rule_end_date     (icalproperty   *prop,
                         time_t      end_date);


#ifdef CAL_OBJ_DEBUG
static char* cal_obj_time_to_string     (CalObjTime *cotime,
                         RecurData  *recur_data);
#endif


CalRecurVTable cal_obj_yearly_vtable = {
    cal_obj_yearly_find_start_position,
    cal_obj_yearly_find_next_position,

    cal_obj_bymonth_expand,
    cal_obj_byweekno_expand,
    cal_obj_byyearday_expand,
    cal_obj_bymonthday_expand,
    cal_obj_byday_expand_yearly,
    cal_obj_byhour_expand,
    cal_obj_byminute_expand,
    cal_obj_bysecond_expand
};

CalRecurVTable cal_obj_monthly_vtable = {
    cal_obj_monthly_find_start_position,
    cal_obj_monthly_find_next_position,

    cal_obj_bymonth_filter,
    NULL, /* BYWEEKNO is only applicable to YEARLY frequency. */
    NULL, /* BYYEARDAY is not useful in a MONTHLY frequency. */
    cal_obj_bymonthday_expand,
    cal_obj_byday_expand_monthly,
    cal_obj_byhour_expand,
    cal_obj_byminute_expand,
    cal_obj_bysecond_expand
};

CalRecurVTable cal_obj_weekly_vtable = {
    cal_obj_weekly_find_start_position,
    cal_obj_weekly_find_next_position,

    cal_obj_bymonth_filter,
    NULL, /* BYWEEKNO is only applicable to YEARLY frequency. */
    NULL, /* BYYEARDAY is not useful in a WEEKLY frequency. */
    NULL, /* BYMONTHDAY is not useful in a WEEKLY frequency. */
    cal_obj_byday_expand_weekly,
    cal_obj_byhour_expand,
    cal_obj_byminute_expand,
    cal_obj_bysecond_expand
};

CalRecurVTable cal_obj_daily_vtable = {
    cal_obj_daily_find_start_position,
    cal_obj_daily_find_next_position,

    cal_obj_bymonth_filter,
    NULL, /* BYWEEKNO is only applicable to YEARLY frequency. */
    cal_obj_byyearday_filter,
    cal_obj_bymonthday_filter,
    cal_obj_byday_filter,
    cal_obj_byhour_expand,
    cal_obj_byminute_expand,
    cal_obj_bysecond_expand
};

CalRecurVTable cal_obj_hourly_vtable = {
    cal_obj_hourly_find_start_position,
    cal_obj_hourly_find_next_position,

    cal_obj_bymonth_filter,
    NULL, /* BYWEEKNO is only applicable to YEARLY frequency. */
    cal_obj_byyearday_filter,
    cal_obj_bymonthday_filter,
    cal_obj_byday_filter,
    cal_obj_byhour_filter,
    cal_obj_byminute_expand,
    cal_obj_bysecond_expand
};

CalRecurVTable cal_obj_minutely_vtable = {
    cal_obj_minutely_find_start_position,
    cal_obj_minutely_find_next_position,

    cal_obj_bymonth_filter,
    NULL, /* BYWEEKNO is only applicable to YEARLY frequency. */
    cal_obj_byyearday_filter,
    cal_obj_bymonthday_filter,
    cal_obj_byday_filter,
    cal_obj_byhour_filter,
    cal_obj_byminute_filter,
    cal_obj_bysecond_expand
};

CalRecurVTable cal_obj_secondly_vtable = {
    cal_obj_secondly_find_start_position,
    cal_obj_secondly_find_next_position,

    cal_obj_bymonth_filter,
    NULL, /* BYWEEKNO is only applicable to YEARLY frequency. */
    cal_obj_byyearday_filter,
    cal_obj_bymonthday_filter,
    cal_obj_byday_filter,
    cal_obj_byhour_filter,
    cal_obj_byminute_filter,
    cal_obj_bysecond_filter
};

/*
 * Calls the given callback function for each occurrence of the event that
 * intersects the range between the given start and end times (the end time is
 * not included). Note that the occurrences may start before the given start
 * time.
 *
 * If the callback routine returns FALSE the occurrence generation stops.
 *
 * Both start and end can be -1, in which case we start at the events first
 * instance and continue until it ends, or forever if it has no enddate.
 */
void
cal_recur_generate_instances (CalComponent      *comp,
                  time_t             start,
                  time_t             end,
                  CalRecurInstanceFn     cb,
                  gpointer                   cb_data)
{
#if 0
    g_print ("In cal_recur_generate_instances comp: %p\n", comp);
    g_print ("  start: %li - %s", start, ctime (&start));
    g_print ("  end  : %li - %s", end, ctime (&end));
#endif
    cal_recur_generate_instances_of_rule (comp, NULL, start, end,
                          cb, cb_data);
}


/*
 * Calls the given callback function for each occurrence of the given
 * recurrence rule between the given start and end times. If the rule is NULL
 * it uses all the rules from the component.
 *
 * If the callback routine returns FALSE the occurrence generation stops.
 *
 * The use of the specific rule is for determining the end of a rule when
 * COUNT is set. The callback will count instances and store the enddata
 * when COUNT is reached.
 *
 * Both start and end can be -1, in which case we start at the events first
 * instance and continue until it ends, or forever if it has no enddate.
 */
static void
cal_recur_generate_instances_of_rule (CalComponent   *comp,
                      icalproperty   *prop,
                      time_t          start,
                      time_t          end,
                      CalRecurInstanceFn  cb,
                      gpointer            cb_data)
{
    CalComponentDateTime dtstart, dtend;
    time_t dtstart_time, dtend_time;
    GSList *rrules = NULL, *rdates = NULL, elem;
    GSList *exrules = NULL, *exdates = NULL;
    CalObjTime interval_start, interval_end, event_start, event_end;
    CalObjTime chunk_start, chunk_end;
    gint days, seconds, year;

    g_return_if_fail (comp != NULL);
    g_return_if_fail (cb != NULL);
    g_return_if_fail (start >= -1);
    g_return_if_fail (end >= -1);

    /* Get dtstart, dtend, recurrences, and exceptions */

    cal_component_get_dtstart (comp, &dtstart);
    cal_component_get_dtend (comp, &dtend);

    if (!dtstart.value) {
        g_message ("cal_recur_generate_instances_of_rule(): bogus "
               "component, does not have DTSTART.  Skipping...");
        goto out;
    }

    dtstart_time = icaltime_as_timet (*dtstart.value);
    if (start == -1)
        start = dtstart_time;

    /* FIXME: DURATION could be used instead, couldn't it? - Damon */
    if (dtend.value)
        dtend_time = icaltime_as_timet (*dtend.value);
    else
        dtend_time = time_day_end (dtstart_time);

    /* If there is no recurrence, just call the callback if the event
       intersects the given interval. */
    if (!(cal_component_has_recurrences (comp)
          || cal_component_has_exceptions (comp))) {
        if ((end == -1 || dtstart_time < end) && dtend_time > start) {
            (* cb) (comp, dtstart_time, dtend_time, cb_data);
        }

        goto out;
    }

    /* If a specific recurrence rule is being used, set up a simple list,
       else get the recurrence rules from the component. */
    if (prop) {
        elem.data = prop;
        elem.next = NULL;
        rrules = &elem;
    } else {
        /* Make sure all the enddates for the rules are set. */
        cal_recur_ensure_end_dates (comp, FALSE);

        cal_component_get_rrule_property_list (comp, &rrules);
        cal_component_get_rdate_list (comp, &rdates);
        cal_component_get_exrule_property_list (comp, &exrules);
        cal_component_get_exdate_list (comp, &exdates);
    }

    /* Convert the interval start & end to CalObjTime. Note that if end
       is -1 interval_end won't be set, so don't use it!
       Also note that we use end - 1 since we want the interval to be
       inclusive as it makes the code simpler. */
    cal_object_time_from_time (&interval_start, start);
    if (end != -1)
        cal_object_time_from_time (&interval_end, end - 1);

    cal_object_time_from_time (&event_start, dtstart_time);
    cal_object_time_from_time (&event_end, dtend_time);
    
    /* Calculate the duration of the event, which we use for all
       occurrences. We can't just subtract start from end since that may
       be affected by daylight-saving time. So we want a value of days
       + seconds. */
    cal_object_compute_duration (&event_start, &event_end,
                     &days, &seconds);

    /* Take off the duration from interval_start, so we get occurrences
       that start just before the start time but overlap it. But only do
       that if the interval is after the event's start time. */
    if (start > dtstart_time) {
        cal_obj_time_add_days (&interval_start, -days);
        cal_obj_time_add_seconds (&interval_start, -seconds);
    }

    /* Expand the recurrence for each year between start & end, or until
       the callback returns 0 if end is 0. We do a year at a time to
       give the callback function a chance to break out of the loop, and
       so we don't get into problems with infinite recurrences. Since we
       have to work on complete sets of occurrences, if there is a yearly
       frequency it wouldn't make sense to break it into smaller chunks,
       since we would then be calculating the same sets several times.
       Though this does mean that we sometimes do a lot more work than
       is necessary, e.g. if COUNT is set to something quite low. */
    for (year = interval_start.year;
         end == -1 || year <= interval_end.year;
         year++) {
        chunk_start = interval_start;
        chunk_start.year = year;
        if (end != -1)
            chunk_end = interval_end;
        chunk_end.year = year;

        if (year != interval_start.year) {
            chunk_start.month  = 0;
            chunk_start.day    = 1;
            chunk_start.hour   = 0;
            chunk_start.minute = 0;
            chunk_start.second = 0;
        }
        if (end == -1 || year != interval_end.year) {
            chunk_end.month  = 11;
            chunk_end.day    = 31;
            chunk_end.hour   = 23;
            chunk_end.minute = 59;
            chunk_end.second = 61;
            chunk_end.is_rdate = FALSE;
        }

        if (!generate_instances_for_chunk (comp, dtstart_time,
                           rrules, rdates,
                           exrules, exdates,
                           &event_start,
                           &chunk_start, &chunk_end,
                           start, end,
                           days, seconds,
                           cb, cb_data))
            break;
    }

    if (!prop) {
        cal_component_free_period_list (rdates);
        cal_component_free_exdate_list (exdates);
    }

 out:
    cal_component_free_datetime (&dtstart);
    cal_component_free_datetime (&dtend);
}

/* Builds a list of GINT_TO_POINTER() elements out of a short array from a
 * struct icalrecurrencetype.
 */
static GList *
array_to_list (short *array, int max_elements)
{
    GList *l;
    int i;

    l = NULL;

    for (i = 0; i < max_elements && array[i] != ICAL_RECURRENCE_ARRAY_MAX; i++)
        l = g_list_prepend (l, GINT_TO_POINTER ((int) (array[i])));
    return g_list_reverse (l);
}

/**
 * cal_recur_from_icalproperty:
 * @ir: An RRULE or EXRULE #icalproperty.
 * 
 * Converts an #icalproperty to a #CalRecurrence.  This should be
 * freed using the cal_recur_free() function.
 * 
 * Return value: #CalRecurrence structure.
 **/
static CalRecurrence *
cal_recur_from_icalproperty (icalproperty *prop, gboolean exception)
{
    struct icalrecurrencetype ir;
    CalRecurrence *r;
    gint max_elements, i;

    g_return_val_if_fail (prop != NULL, NULL);

    r = g_new (CalRecurrence, 1);

    if (exception)
        ir = icalproperty_get_exrule (prop);
    else
        ir = icalproperty_get_rrule (prop);

    r->freq = ir.freq;
    r->interval = ir.interval;

    if (ir.count != 0) {
        r->enddate = cal_recur_get_rule_end_date (prop);
    } else {
        /* FIXME: icaltime_as_timet() seems to return -1 if UNTIL isn't
           set, but a simpler test would be better. */
        r->enddate = icaltime_as_timet (ir.until);
        if (r->enddate == -1)
            r->enddate = 0;
        else if (ir.until.is_date)
            /* FIXME: Decide what to do here. */
            r->enddate = time_add_day (r->enddate, 1) - 1;
    }

    r->week_start_day = cal_recur_ical_weekday_to_weekday (ir.week_start);

    r->bymonth = array_to_list (ir.by_month,
                    sizeof (ir.by_month) / sizeof (ir.by_month[0]));

    r->byweekno = array_to_list (ir.by_week_no,
                     sizeof (ir.by_week_no) / sizeof (ir.by_week_no[0]));

    r->byyearday = array_to_list (ir.by_year_day,
                      sizeof (ir.by_year_day) / sizeof (ir.by_year_day[0]));

    r->bymonthday = array_to_list (ir.by_month_day,
                       sizeof (ir.by_month_day) / sizeof (ir.by_month_day[0]));

    /* FIXME: libical only supports 8 values, out of possible 107 * 7. */
    r->byday = NULL;
    max_elements = sizeof (ir.by_day) / sizeof (ir.by_day[0]);
    for (i = 0; i < max_elements && ir.by_day[i] != ICAL_RECURRENCE_ARRAY_MAX; i++) {
        enum icalrecurrencetype_weekday day;
        gint weeknum, weekday;

        day = icalrecurrencetype_day_day_of_week (ir.by_day[i]);
        weeknum = icalrecurrencetype_day_position (ir.by_day[i]);

        weekday = cal_recur_ical_weekday_to_weekday (day);

        r->byday = g_list_prepend (r->byday,
                       GINT_TO_POINTER (weeknum));
        r->byday = g_list_prepend (r->byday,
                       GINT_TO_POINTER (weekday));
    }

    r->byhour = array_to_list (ir.by_hour,
                   sizeof (ir.by_hour) / sizeof (ir.by_hour[0]));

    r->byminute = array_to_list (ir.by_minute,
                     sizeof (ir.by_minute) / sizeof (ir.by_minute[0]));

    r->bysecond = array_to_list (ir.by_second,
                     sizeof (ir.by_second) / sizeof (ir.by_second[0]));

    r->bysetpos = array_to_list (ir.by_set_pos,
                     sizeof (ir.by_set_pos) / sizeof (ir.by_set_pos[0]));

    return r;
}


static gint
cal_recur_ical_weekday_to_weekday   (enum icalrecurrencetype_weekday day)
{
    gint weekday;

    switch (day) {
    case ICAL_NO_WEEKDAY:       /* Monday is the default in RFC2445. */
    case ICAL_MONDAY_WEEKDAY:
        weekday = 0;
        break;
    case ICAL_TUESDAY_WEEKDAY:
        weekday = 1;
        break;
    case ICAL_WEDNESDAY_WEEKDAY:
        weekday = 2;
        break;
    case ICAL_THURSDAY_WEEKDAY:
        weekday = 3;
        break;
    case ICAL_FRIDAY_WEEKDAY:
        weekday = 4;
        break;
    case ICAL_SATURDAY_WEEKDAY:
        weekday = 5;
        break;
    case ICAL_SUNDAY_WEEKDAY:
        weekday = 6;
        break;
    default:
        g_warning ("cal_recur_ical_weekday_to_weekday(): Unknown week day %d",
               day);
        weekday = 0;
    }

    return weekday;
}


/**
 * cal_recur_free:
 * @r: A #CalRecurrence structure.
 * 
 * Frees a #CalRecurrence structure.
 **/
static void
cal_recur_free (CalRecurrence *r)
{
    g_return_if_fail (r != NULL);

    g_list_free (r->bymonth);
    g_list_free (r->byweekno);
    g_list_free (r->byyearday);
    g_list_free (r->bymonthday);
    g_list_free (r->byday);
    g_list_free (r->byhour);
    g_list_free (r->byminute);
    g_list_free (r->bysecond);
    g_list_free (r->bysetpos);

    g_free (r);
}

/* Generates one year's worth of recurrence instances.  Returns TRUE if all the
 * callback invocations returned TRUE, or FALSE when any one of them returns
 * FALSE, i.e. meaning that the instance generation should be stopped.
 */
static gboolean
generate_instances_for_chunk (CalComponent  *comp,
                  time_t             comp_dtstart,
                  GSList        *rrules,
                  GSList        *rdates,
                  GSList        *exrules,
                  GSList        *exdates,
                  CalObjTime    *event_start,
                  CalObjTime    *chunk_start,
                  CalObjTime    *chunk_end,
                  time_t         interval_start_time,
                  time_t         interval_end_time,
                  gint       duration_days,
                  gint       duration_seconds,
                  CalRecurInstanceFn cb,
                  gpointer           cb_data)
{
    GArray *occs, *ex_occs, *tmp_occs, *rdate_periods;
    CalObjTime cotime, *occ;
    GSList *elem;
    gint i;
    time_t start_time, end_time;
    struct tm start_tm, end_tm;
    gboolean cb_status = TRUE, rule_finished, finished = TRUE;

#if 0
    g_print ("In generate_instances_for_chunk rrules: %p\n"
         "  %i/%i/%i %02i:%02i:%02i - %i/%i/%i %02i:%02i:%02i\n",
         rrules,
         chunk_start->day, chunk_start->month + 1,
         chunk_start->year, chunk_start->hour,
         chunk_start->minute, chunk_start->second,
         chunk_end->day, chunk_end->month + 1,
         chunk_end->year, chunk_end->hour,
         chunk_end->minute, chunk_end->second);
#endif

    occs = g_array_new (FALSE, FALSE, sizeof (CalObjTime));
    ex_occs = g_array_new (FALSE, FALSE, sizeof (CalObjTime));
    rdate_periods = g_array_new (FALSE, FALSE,
                     sizeof (CalObjRecurrenceDate));

    /* The original DTSTART property is included in the occurrence set.
       So we add it if it is in this chunk. If it is after this chunk
       we set finished to FALSE. */
    if (cal_obj_time_compare_func (event_start, chunk_end) >= 0)
        finished = FALSE;
    else if (cal_obj_time_compare_func (event_start, chunk_start) >= 0)
        g_array_append_vals (occs, event_start, 1);
    
    /* Expand each of the recurrence rules. */
    for (elem = rrules; elem; elem = elem->next) {
        icalproperty *prop;
        CalRecurrence *r;

        prop = elem->data;
        r = cal_recur_from_icalproperty (prop, FALSE);

        tmp_occs = cal_obj_expand_recurrence (event_start, r,
                              chunk_start,
                              chunk_end,
                              &rule_finished);
        cal_recur_free (r);

        /* If any of the rules return FALSE for finished, we know we
           have to carry on so we set finished to FALSE. */
        if (!rule_finished)
            finished = FALSE;

        g_array_append_vals (occs, tmp_occs->data, tmp_occs->len);
        g_array_free (tmp_occs, TRUE);
    }

    /* Add on specific occurrence dates, flag them as RDATEs, and store
       a pointer to the period in the rdate_periods array. */
    for (elem = rdates; elem; elem = elem->next) {
        CalComponentPeriod *p;
        CalObjRecurrenceDate rdate;
        time_t t;

        p = elem->data;
        t = icaltime_as_timet (p->start);
        cal_object_time_from_time (&cotime, t);

        /* If the rdate is after the current chunk we set finished
           to FALSE, and we skip it. */
        if (cal_obj_time_compare_func (&cotime, chunk_end) >= 0) {
            finished = FALSE;
            continue;
        }

        /* Check if the end date or duration is set. If it is we need
           to store it so we can get it later. (libical seems to set
           second to -1 to denote an unset time. See icalvalue.c) */
        if (p->type != CAL_COMPONENT_PERIOD_DATETIME
            || p->u.end.second != -1) {
            cotime.is_rdate = TRUE;

            rdate.start = cotime;
            rdate.period = p;
            g_array_append_val (rdate_periods, rdate);
        }

        g_array_append_val (occs, cotime);
    }

    /* Expand each of the exception rules. */
    for (elem = exrules; elem; elem = elem->next) {
        icalproperty *prop;
        CalRecurrence *r;

        prop = elem->data;
        r = cal_recur_from_icalproperty (prop, FALSE);

        tmp_occs = cal_obj_expand_recurrence (event_start, r,
                              chunk_start,
                              chunk_end,
                              &rule_finished);
        cal_recur_free (r);

        g_array_append_vals (ex_occs, tmp_occs->data, tmp_occs->len);
        g_array_free (tmp_occs, TRUE);
    }

    /* Add on specific exception dates. */
    for (elem = exdates; elem; elem = elem->next) {
        CalComponentDateTime *cdt;
        time_t t;

        /* FIXME we should only be dealing with dates, not times too.

           No, I think it is supposed to be dates & times - Damon.
           I'm not sure what the semantics of just a date would be,
           since the event could recur several times each day. */
        cdt = elem->data;
        t = icaltime_as_timet (*cdt->value);
        cal_object_time_from_time (&cotime, t);

        g_array_append_val (ex_occs, cotime);
    }


    /* Sort all the arrays. */
    cal_obj_sort_occurrences (occs);
    cal_obj_sort_occurrences (ex_occs);

    qsort (rdate_periods->data, rdate_periods->len,
           sizeof (CalObjRecurrenceDate), cal_obj_time_compare_func);

    /* Create the final array, by removing the exceptions from the
       occurrences, and removing any duplicates. */
    cal_obj_remove_exceptions (occs, ex_occs);

    /* Call the callback for each occurrence. If it returns 0 we break
       out of the loop. */
    for (i = 0; i < occs->len; i++) {
        /* Convert each CalObjTime into a start & end time_t, and
           check it is within the bounds of the event & interval. */
        occ = &g_array_index (occs, CalObjTime, i);

        start_tm.tm_year  = occ->year - 1900;
        start_tm.tm_mon   = occ->month;
        start_tm.tm_mday  = occ->day;
        start_tm.tm_hour  = occ->hour;
        start_tm.tm_min   = occ->minute;
        start_tm.tm_sec   = occ->second;
        start_tm.tm_isdst = -1;
        start_time = mktime (&start_tm);

        if (start_time == -1) {
            g_warning ("mktime failed - time_t out of range?");
            finished = TRUE;
            break;
        }

        if (start_time < comp_dtstart
            || (interval_end_time != -1
            && start_time >= interval_end_time))
            continue;

        if (occ->is_rdate) {
            if (!cal_object_get_rdate_end (occ, rdate_periods)) {
                cal_obj_time_add_days (occ, duration_days);
                cal_obj_time_add_seconds (occ,
                              duration_seconds);
            }
        } else {
            cal_obj_time_add_days (occ, duration_days);
            cal_obj_time_add_seconds (occ, duration_seconds);
        }

        end_tm.tm_year  = occ->year - 1900;
        end_tm.tm_mon   = occ->month;
        end_tm.tm_mday  = occ->day;
        end_tm.tm_hour  = occ->hour;
        end_tm.tm_min   = occ->minute;
        end_tm.tm_sec   = occ->second;
        end_tm.tm_isdst = -1;
        end_time = mktime (&end_tm);

        if (end_time == -1) {
            g_warning ("mktime failed - time_t out of range?");
            finished = TRUE;
            break;
        }

        if (end_time <= interval_start_time)
            continue;

        cb_status = (*cb) (comp, start_time, end_time, cb_data);
        if (!cb_status)
            break;
    }

    g_array_free (occs, TRUE);
    g_array_free (ex_occs, TRUE);
    g_array_free (rdate_periods, TRUE);

    /* We return TRUE (i.e. carry on) only if the callback has always
       returned TRUE and we know that we have more occurrences to generate
       (i.e. finished is FALSE). */
    return cb_status && !finished;
}


/* This looks up the occurrence time in the sorted rdate_periods array, and
   tries to compute the end time of the occurrence. If no end time or duration
   is set it returns FALSE and the default duration will be used. */
static gboolean
cal_object_get_rdate_end    (CalObjTime *occ,
                 GArray     *rdate_periods)
{
    CalObjRecurrenceDate *rdate;
    CalComponentPeriod *p;
    gint lower, upper, middle, cmp = 0;
    time_t t;

    lower = 0;
    upper = rdate_periods->len;

    while (lower < upper) {
        middle = (lower + upper) >> 1;
      
        rdate = &g_array_index (rdate_periods, CalObjRecurrenceDate,
                    middle);

        cmp = cal_obj_time_compare_func (occ, &rdate->start);
      
        if (cmp == 0)
            break;
        else if (cmp < 0)
            upper = middle;
        else
            lower = middle + 1;
    }

    /* This should never happen. */
    if (cmp == 0) {
        g_warning ("Recurrence date not found");
        return FALSE;
    }

    p = rdate->period;
    if (p->type == CAL_COMPONENT_PERIOD_DATETIME) {
        t = icaltime_as_timet (p->u.end);
        cal_object_time_from_time (occ, t);
    } else {
        cal_obj_time_add_days (occ, p->u.duration.weeks * 7
                       + p->u.duration.days);
        cal_obj_time_add_hours (occ, p->u.duration.hours);
        cal_obj_time_add_minutes (occ, p->u.duration.minutes);
        cal_obj_time_add_seconds (occ, p->u.duration.seconds);
    }

    return TRUE;
}


static void
cal_object_compute_duration (CalObjTime *start,
                 CalObjTime *end,
                 gint   *days,
                 gint   *seconds)
{
    GDate start_date, end_date;
    gint start_seconds, end_seconds;

    g_date_clear (&start_date, 1);
    g_date_clear (&end_date, 1);
    g_date_set_dmy (&start_date, start->day, start->month + 1,
            start->year);
    g_date_set_dmy (&end_date, end->day, end->month + 1,
            end->year);

    *days = g_date_julian (&end_date) - g_date_julian (&start_date);
    start_seconds = start->hour * 3600 + start->minute * 60
        + start->second;
    end_seconds = end->hour * 3600 + end->minute * 60 + end->second;

    *seconds = end_seconds - start_seconds;
    if (*seconds < 0) {
        *days = *days - 1;
        *seconds += 24 * 60 * 60;
    }
}


/* Returns an unsorted GArray of CalObjTime's resulting from expanding the
   given recurrence rule within the given interval. Note that it doesn't
   clip the generated occurrences to the interval, i.e. if the interval
   starts part way through the year this function still returns all the
   occurrences for the year. Clipping is done later.
   The finished flag is set to FALSE if there are more occurrences to generate
   after the given interval.*/
static GArray*
cal_obj_expand_recurrence       (CalObjTime   *event_start,
                     CalRecurrence    *recur,
                     CalObjTime   *interval_start,
                     CalObjTime   *interval_end,
                     gboolean     *finished)
{
    CalRecurVTable *vtable;
    CalObjTime *event_end = NULL, event_end_cotime;
    RecurData recur_data;
    CalObjTime occ, *cotime;
    GArray *all_occs, *occs;
    gint len;

    /* This is the resulting array of CalObjTime elements. */
    all_occs = g_array_new (FALSE, FALSE, sizeof (CalObjTime));

    *finished = TRUE;

    vtable = cal_obj_get_vtable (recur->freq);
    if (!vtable)
        return all_occs;

    /* Calculate some useful data such as some fast lookup tables. */
    cal_obj_initialize_recur_data (&recur_data, recur, event_start);

    /* Compute the event_end, if the recur's enddate is set. */
    if (recur->enddate > 0) {
        cal_object_time_from_time (&event_end_cotime,
                       recur->enddate);
        event_end = &event_end_cotime;

        /* If the enddate is before the requested interval return. */
        if (cal_obj_time_compare_func (event_end, interval_start) < 0)
            return all_occs;
    }

    /* Set finished to FALSE if we know there will be more occurrences to
       do after this interval. */
    if (!interval_end || !event_end
        || cal_obj_time_compare_func (event_end, interval_end) > 0)
        *finished = FALSE;

    /* Get the first period based on the frequency and the interval that
       intersects the interval between start and end. */
    if ((*vtable->find_start_position) (event_start, event_end,
                        &recur_data,
                        interval_start, interval_end,
                        &occ))
        return all_occs;

    /* Loop until the event ends or we go past the end of the required
       interval. */
    for (;;) {
        /* Generate the set of occurrences for this period. */
        switch (recur->freq) {
        case ICAL_YEARLY_RECURRENCE:
            occs = cal_obj_generate_set_yearly (&recur_data,
                                vtable, &occ);
            break;
        case ICAL_MONTHLY_RECURRENCE:
            occs = cal_obj_generate_set_monthly (&recur_data,
                                 vtable, &occ);
            break;
        default:
            occs = cal_obj_generate_set_default (&recur_data,
                                 vtable, &occ);
            break;
        }

        /* Sort the occurrences and remove duplicates. */
        cal_obj_sort_occurrences (occs);
        cal_obj_remove_duplicates_and_invalid_dates (occs);

        /* Apply the BYSETPOS property. */
        occs = cal_obj_bysetpos_filter (recur, occs);

        /* Remove any occs after event_end. */
        len = occs->len - 1;
        if (event_end) {
            while (len >= 0) {
                cotime = &g_array_index (occs, CalObjTime,
                             len);
                if (cal_obj_time_compare_func (cotime,
                                   event_end) <= 0)
                    break;
                len--;
            }
        }

        /* Add the occurrences onto the main array. */
        if (len >= 0)
            g_array_append_vals (all_occs, occs->data, len + 1);

        g_array_free (occs, TRUE);

        /* Skip to the next period, or exit the loop if finished. */
        if ((*vtable->find_next_position) (&occ, event_end,
                           &recur_data, interval_end))
            break;
    }

    return all_occs;
}


static GArray*
cal_obj_generate_set_yearly (RecurData *recur_data,
                 CalRecurVTable *vtable,
                 CalObjTime *occ)
{
    CalRecurrence *recur = recur_data->recur;
    GArray *occs_arrays[4], *occs, *occs2;
    gint num_occs_arrays = 0, i;

    /* This is a bit complicated, since the iCalendar spec says that
       several BYxxx modifiers can be used simultaneously. So we have to
       be quite careful when determining the days of the occurrences.
       The BYHOUR, BYMINUTE & BYSECOND modifiers are no problem at all.

       The modifiers we have to worry about are: BYMONTH, BYWEEKNO,
       BYYEARDAY, BYMONTHDAY & BYDAY. We can't do these sequentially
       since each filter will mess up the results of the previous one.
       But they aren't all completely independant, e.g. BYMONTHDAY and
       BYDAY are related to BYMONTH, and BYDAY is related to BYWEEKNO.

       BYDAY & BYMONTHDAY can also be applied independently, which makes
       it worse. So we assume that if BYMONTH or BYWEEKNO is used, then
       the BYDAY modifier applies to those, else it is applied
       independantly.

       We expand the occurrences in parallel into the occs_arrays[] array,
       and then merge them all into one GArray before expanding BYHOUR,
       BYMINUTE & BYSECOND. */

    if (recur->bymonth) {
        occs = g_array_new (FALSE, FALSE, sizeof (CalObjTime));
        g_array_append_vals (occs, occ, 1);

        occs = (*vtable->bymonth_filter) (recur_data, occs);

        /* If BYMONTHDAY & BYDAY are both set we need to expand them
           in parallel and add the results. */
        if (recur->bymonthday && recur->byday) {
            /* Copy the occs array. */
            occs2 = g_array_new (FALSE, FALSE,
                         sizeof (CalObjTime));
            g_array_append_vals (occs2, occs->data, occs->len);

            occs = (*vtable->bymonthday_filter) (recur_data, occs);
            /* Note that we explicitly call the monthly version
               of the BYDAY expansion filter. */
            occs2 = cal_obj_byday_expand_monthly (recur_data,
                                  occs2);

            /* Add the 2 resulting arrays together. */
            g_array_append_vals (occs, occs2->data, occs2->len);
            g_array_free (occs2, TRUE);
        } else {
            occs = (*vtable->bymonthday_filter) (recur_data, occs);
            /* Note that we explicitly call the monthly version
               of the BYDAY expansion filter. */
            occs = cal_obj_byday_expand_monthly (recur_data, occs);
        }

        occs_arrays[num_occs_arrays++] = occs;
    }

    if (recur->byweekno) {
        occs = g_array_new (FALSE, FALSE, sizeof (CalObjTime));
        g_array_append_vals (occs, occ, 1);

        occs = (*vtable->byweekno_filter) (recur_data, occs);
        /* Note that we explicitly call the weekly version of the
           BYDAY expansion filter. */
        occs = cal_obj_byday_expand_weekly (recur_data, occs);

        occs_arrays[num_occs_arrays++] = occs;
    }

    if (recur->byyearday) {
        occs = g_array_new (FALSE, FALSE, sizeof (CalObjTime));
        g_array_append_vals (occs, occ, 1);

        occs = (*vtable->byyearday_filter) (recur_data, occs);

        occs_arrays[num_occs_arrays++] = occs;
    }

    /* If BYMONTHDAY is set, and BYMONTH is not set, we need to
       expand BYMONTHDAY independantly. */
    if (recur->bymonthday && !recur->bymonth) {
        occs = g_array_new (FALSE, FALSE, sizeof (CalObjTime));
        g_array_append_vals (occs, occ, 1);

        occs = (*vtable->bymonthday_filter) (recur_data, occs);

        occs_arrays[num_occs_arrays++] = occs;
    }

    /* If BYDAY is set, and BYMONTH and BYWEEKNO are not set, we need to
       expand BYDAY independantly. */
    if (recur->byday && !recur->bymonth && !recur->byweekno) {
        occs = g_array_new (FALSE, FALSE, sizeof (CalObjTime));
        g_array_append_vals (occs, occ, 1);

        occs = (*vtable->byday_filter) (recur_data, occs);

        occs_arrays[num_occs_arrays++] = occs;
    }

    /* Add all the arrays together. If no filters were used we just
       create an array with one element. */
    if (num_occs_arrays > 0) {
        occs = occs_arrays[0];
        for (i = 1; i < num_occs_arrays; i++) {
            occs2 = occs_arrays[i];
            g_array_append_vals (occs, occs2->data, occs2->len);
            g_array_free (occs2, TRUE);
        }
    } else {
        occs = g_array_new (FALSE, FALSE, sizeof (CalObjTime));
        g_array_append_vals (occs, occ, 1);
    }

    /* Now expand BYHOUR, BYMINUTE & BYSECOND. */
    occs = (*vtable->byhour_filter) (recur_data, occs);
    occs = (*vtable->byminute_filter) (recur_data, occs);
    occs = (*vtable->bysecond_filter) (recur_data, occs);

    return occs;
}


static GArray*
cal_obj_generate_set_monthly    (RecurData *recur_data,
                 CalRecurVTable *vtable,
                 CalObjTime *occ)
{
    GArray *occs, *occs2;

    /* We start with just the one time in each set. */
    occs = g_array_new (FALSE, FALSE, sizeof (CalObjTime));
    g_array_append_vals (occs, occ, 1);

    occs = (*vtable->bymonth_filter) (recur_data, occs);

    /* We need to combine the output of BYMONTHDAY & BYDAY, by doing them
       in parallel rather than sequentially. If we did them sequentially
       then we would lose the occurrences generated by BYMONTHDAY, and
       instead have repetitions of the occurrences from BYDAY. */
    if (recur_data->recur->bymonthday && recur_data->recur->byday) {
        occs2 = g_array_new (FALSE, FALSE, sizeof (CalObjTime));
        g_array_append_vals (occs2, occs->data, occs->len);

        occs = (*vtable->bymonthday_filter) (recur_data, occs);
        occs2 = (*vtable->byday_filter) (recur_data, occs2);

        g_array_append_vals (occs, occs2->data, occs2->len);
        g_array_free (occs2, TRUE);
    } else {
        occs = (*vtable->bymonthday_filter) (recur_data, occs);
        occs = (*vtable->byday_filter) (recur_data, occs);
    }

    occs = (*vtable->byhour_filter) (recur_data, occs);
    occs = (*vtable->byminute_filter) (recur_data, occs);
    occs = (*vtable->bysecond_filter) (recur_data, occs);

    return occs;
}


static GArray*
cal_obj_generate_set_default    (RecurData *recur_data,
                 CalRecurVTable *vtable,
                 CalObjTime *occ)
{
    GArray *occs;

#if 0
    g_print ("Generating set for %i/%i/%i %02i:%02i:%02i\n",
         occ->day, occ->month + 1, occ->year, occ->hour, occ->minute,
         occ->second);
#endif

    /* We start with just the one time in the set. */
    occs = g_array_new (FALSE, FALSE, sizeof (CalObjTime));
    g_array_append_vals (occs, occ, 1);

    occs = (*vtable->bymonth_filter) (recur_data, occs);
    if (vtable->byweekno_filter)
        occs = (*vtable->byweekno_filter) (recur_data, occs);
    if (vtable->byyearday_filter)
        occs = (*vtable->byyearday_filter) (recur_data, occs);
    if (vtable->bymonthday_filter)
        occs = (*vtable->bymonthday_filter) (recur_data, occs);
    occs = (*vtable->byday_filter) (recur_data, occs);

    occs = (*vtable->byhour_filter) (recur_data, occs);
    occs = (*vtable->byminute_filter) (recur_data, occs);
    occs = (*vtable->bysecond_filter) (recur_data, occs);

    return occs;
}



/* Returns the function table corresponding to the recurrence frequency. */
static CalRecurVTable* cal_obj_get_vtable (icalrecurrencetype_frequency recur_type)
{
    CalRecurVTable* vtable;

    switch (recur_type) {
    case ICAL_YEARLY_RECURRENCE:
        vtable = &cal_obj_yearly_vtable;
        break;
    case ICAL_MONTHLY_RECURRENCE:
        vtable = &cal_obj_monthly_vtable;
        break;
    case ICAL_WEEKLY_RECURRENCE:
        vtable = &cal_obj_weekly_vtable;
        break;
    case ICAL_DAILY_RECURRENCE:
        vtable = &cal_obj_daily_vtable;
        break;
    case ICAL_HOURLY_RECURRENCE:
        vtable = &cal_obj_hourly_vtable;
        break;
    case ICAL_MINUTELY_RECURRENCE:
        vtable = &cal_obj_minutely_vtable;
        break;
    case ICAL_SECONDLY_RECURRENCE:
        vtable = &cal_obj_secondly_vtable;
        break;
    default:
        g_warning ("Unknown recurrence frequenct");
        vtable = NULL;
    }

    return vtable;
}


/* This creates a number of fast lookup tables used when filtering with the
   modifier properties BYMONTH, BYYEARDAY etc. */
static void
cal_obj_initialize_recur_data (RecurData  *recur_data,
                   CalRecurrence *recur,
                   CalObjTime *event_start)
{
    GList *elem;
    gint month, yearday, monthday, weekday, week_num, hour, minute, second;

    /* Clear the entire RecurData. */
    memset (recur_data, 0, sizeof (RecurData));

    recur_data->recur = recur;

    /* Set the weekday, used for the WEEKLY frequency and the BYWEEKNO
       modifier. */
    recur_data->weekday_offset = cal_obj_time_weekday_offset (event_start,
                                  recur);

    /* Create an array of months from bymonths for fast lookup. */
    elem = recur->bymonth;
    while (elem) {
        month = GPOINTER_TO_INT (elem->data);
        recur_data->months[month] = 1;
        elem = elem->next;
    }

    /* Create an array of yeardays from byyearday for fast lookup.
       We create a second array to handle the negative values. The first
       element there corresponds to the last day of the year. */
    elem = recur->byyearday;
    while (elem) {
        yearday = GPOINTER_TO_INT (elem->data);
        if (yearday >= 0)
            recur_data->yeardays[yearday] = 1;
        else
            recur_data->neg_yeardays[-yearday] = 1;
        elem = elem->next;
    }

    /* Create an array of monthdays from bymonthday for fast lookup.
       We create a second array to handle the negative values. The first
       element there corresponds to the last day of the month. */
    elem = recur->bymonthday;
    while (elem) {
        monthday = GPOINTER_TO_INT (elem->data);
        if (monthday >= 0)
            recur_data->monthdays[monthday] = 1;
        else
            recur_data->neg_monthdays[-monthday] = 1;
        elem = elem->next;
    }

    /* Create an array of weekdays from byday for fast lookup. */
    elem = recur->byday;
    while (elem) {
        weekday = GPOINTER_TO_INT (elem->data);
        elem = elem->next;
        /* The week number is not used when filtering. */
        week_num = GPOINTER_TO_INT (elem->data);
        elem = elem->next;

        recur_data->weekdays[weekday] = 1;
    }

    /* Create an array of hours from byhour for fast lookup. */
    elem = recur->byhour;
    while (elem) {
        hour = GPOINTER_TO_INT (elem->data);
        recur_data->hours[hour] = 1;
        elem = elem->next;
    }

    /* Create an array of minutes from byminutes for fast lookup. */
    elem = recur->byminute;
    while (elem) {
        minute = GPOINTER_TO_INT (elem->data);
        recur_data->minutes[minute] = 1;
        elem = elem->next;
    }

    /* Create an array of seconds from byseconds for fast lookup. */
    elem = recur->bysecond;
    while (elem) {
        second = GPOINTER_TO_INT (elem->data);
        recur_data->seconds[second] = 1;
        elem = elem->next;
    }
}


static void
cal_obj_sort_occurrences (GArray *occs)
{
    qsort (occs->data, occs->len, sizeof (CalObjTime),
           cal_obj_time_compare_func);
}


static void
cal_obj_remove_duplicates_and_invalid_dates (GArray *occs)
{
    static const int days_in_month[12] = {
        31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
    };

    CalObjTime *occ, *prev_occ = NULL;
    gint len, i, j = 0, year, month, days;
    gboolean keep_occ;

    len = occs->len;
    for (i = 0; i < len; i++) {
        occ = &g_array_index (occs, CalObjTime, i);
        keep_occ = TRUE;

        if (prev_occ && cal_obj_time_compare_func (occ,
                               prev_occ) == 0)
            keep_occ = FALSE;

        year = occ->year;
        month = occ->month;
        days = days_in_month[occ->month];
        /* If it is february and a leap year, add a day. */
        if (month == 1 && (year % 4 == 0
                   && (year % 100 != 0
                       || year % 400 == 0)))
            days++;
        if (occ->day > days)
            keep_occ = FALSE;

        if (keep_occ) {
            if (i != j)
                g_array_index (occs, CalObjTime, j)
                    = g_array_index (occs, CalObjTime, i);
            j++;
        }

        prev_occ = occ;
    }

    g_array_set_size (occs, j);
}


/* Removes the exceptions from the ex_occs array from the occurrences in the
   occs array, and removes any duplicates. Both arrays are sorted. */
static void
cal_obj_remove_exceptions (GArray *occs,
               GArray *ex_occs)
{
    CalObjTime *occ, *prev_occ = NULL, *ex_occ = NULL, *last_occ_kept;
    gint i, j = 0, cmp, ex_index, occs_len, ex_occs_len;
    gboolean keep_occ, current_time_is_exception = FALSE;

    if (occs->len == 0)
        return;

    ex_index = 0;
    occs_len = occs->len;
    ex_occs_len = ex_occs->len;

    if (ex_occs_len > 0)
        ex_occ = &g_array_index (ex_occs, CalObjTime, ex_index);

    for (i = 0; i < occs_len; i++) {
        occ = &g_array_index (occs, CalObjTime, i);
        keep_occ = TRUE;

        /* If the occurrence is a duplicate of the previous one, skip
           it. */
        if (prev_occ
            && cal_obj_time_compare_func (occ, prev_occ) == 0) {
            keep_occ = FALSE;

            /* If this occurrence is an RDATE, and the previous
               occurrence in the array was kept, set the RDATE flag
               of the last one, so we still use the end date
               or duration. */
            if (occ->is_rdate && !current_time_is_exception) {
                last_occ_kept = &g_array_index (occs,
                                CalObjTime,
                                j - 1);
                last_occ_kept->is_rdate = TRUE;
            }
        } else {
            /* We've found a new occurrence time. Reset the flag
               to indicate that it hasn't been found in the
               exceptions array (yet). */
            current_time_is_exception = FALSE;

            if (ex_occ) {
                /* Step through the exceptions until we come
                   to one that matches or follows this
                   occurrence. */
                while (ex_occ) {
                    cmp = cal_obj_time_compare_func (ex_occ, occ);
                    /* I'm pretty sure this is wrong. */
                    /*cmp = cal_obj_date_only_compare_func (ex_occ, occ);*/
                    if (cmp > 0)
                        break;

                    /* Move to the next exception, or set
                       ex_occ to NULL when we reach the
                       end of array. */
                    ex_index++;
                    if (ex_index < ex_occs_len)
                        ex_occ = &g_array_index (ex_occs, CalObjTime, ex_index);
                    else
                        ex_occ = NULL;

                    /* If the exception did match this
                       occurrence we remove it, and set the
                       flag to indicate that the current
                       time is an exception. */
                    if (cmp == 0) {
                        current_time_is_exception = TRUE;
                        keep_occ = FALSE;
                        break;
                    }
                }
            }
        }

        if (keep_occ) {
            if (i != j)
                g_array_index (occs, CalObjTime, j)
                    = g_array_index (occs, CalObjTime, i);
            j++;
        }

        prev_occ = occ;
    }

    g_array_set_size (occs, j);
}



static GArray*
cal_obj_bysetpos_filter (CalRecurrence *recur,
             GArray     *occs)
{
    GArray *new_occs;
    CalObjTime *occ;
    GList *elem;
    gint len, pos;

    /* If BYSETPOS has not been specified, or the array is empty, just
       return the array. */
    elem = recur->bysetpos;
    if (!elem || occs->len == 0)
        return occs;

    new_occs = g_array_new (FALSE, FALSE, sizeof (CalObjTime));

    /* Iterate over the indices given in bysetpos, adding the corresponding
       element from occs to new_occs. */
    len = occs->len;
    while (elem) {
        pos = GPOINTER_TO_INT (elem->data);

        /* Negative values count back from the end of the array. */
        if (pos < 0)
            pos += len;

        if (pos >= 0 && pos < len) {
            occ = &g_array_index (occs, CalObjTime, pos);
            g_array_append_vals (new_occs, occ, 1);
        }
        elem = elem->next;
    }

    g_array_free (occs, TRUE);

    return new_occs;
}




/* Finds the first year from the event_start, counting in multiples of the
   recurrence interval, that intersects the given interval. It returns TRUE
   if there is no intersection. */
static gboolean
cal_obj_yearly_find_start_position (CalObjTime *event_start,
                    CalObjTime *event_end,
                    RecurData  *recur_data,
                    CalObjTime *interval_start,
                    CalObjTime *interval_end,
                    CalObjTime *cotime)
{
    *cotime = *event_start;

    /* Move on to the next interval, if the event starts before the
       given interval. */
    if (cotime->year < interval_start->year) {
        gint years = interval_start->year - cotime->year
            + recur_data->recur->interval - 1;
        years -= years % recur_data->recur->interval;
        /* NOTE: The day may now be invalid, e.g. 29th Feb. */
        cotime->year += years;
    }

    if ((event_end && cotime->year > event_end->year)
        || (interval_end && cotime->year > interval_end->year))
        return TRUE;

    return FALSE;
}


static gboolean
cal_obj_yearly_find_next_position (CalObjTime *cotime,
                   CalObjTime *event_end,
                   RecurData  *recur_data,
                   CalObjTime *interval_end)
{
    /* NOTE: The day may now be invalid, e.g. 29th Feb. */
    cotime->year += recur_data->recur->interval;

    if ((event_end && cotime->year > event_end->year)
        || (interval_end && cotime->year > interval_end->year))
        return TRUE;

    return FALSE;
}



static gboolean
cal_obj_monthly_find_start_position (CalObjTime *event_start,
                     CalObjTime *event_end,
                     RecurData  *recur_data,
                     CalObjTime *interval_start,
                     CalObjTime *interval_end,
                     CalObjTime *cotime)
{
    *cotime = *event_start;

    /* Move on to the next interval, if the event starts before the
       given interval. */
    if (cal_obj_time_compare (cotime, interval_start, CALOBJ_MONTH) < 0) {
        gint months = (interval_start->year - cotime->year) * 12
            + interval_start->month - cotime->month
            + recur_data->recur->interval - 1;
        months -= months % recur_data->recur->interval;
        /* NOTE: The day may now be invalid, e.g. 31st Sep. */
        cal_obj_time_add_months (cotime, months);
    }

    if (event_end && cal_obj_time_compare (cotime, event_end,
                           CALOBJ_MONTH) > 0)
        return TRUE;
    if (interval_end && cal_obj_time_compare (cotime, interval_end,
                          CALOBJ_MONTH) > 0)
        return TRUE;

    return FALSE;
}


static gboolean
cal_obj_monthly_find_next_position (CalObjTime *cotime,
                    CalObjTime *event_end,
                    RecurData  *recur_data,
                    CalObjTime *interval_end)
{
    /* NOTE: The day may now be invalid, e.g. 31st Sep. */
    cal_obj_time_add_months (cotime, recur_data->recur->interval);

    if (event_end && cal_obj_time_compare (cotime, event_end,
                           CALOBJ_MONTH) > 0)
        return TRUE;
    if (interval_end && cal_obj_time_compare (cotime, interval_end,
                          CALOBJ_MONTH) > 0)
        return TRUE;

    return FALSE;
}



static gboolean
cal_obj_weekly_find_start_position (CalObjTime *event_start,
                    CalObjTime *event_end,
                    RecurData  *recur_data,
                    CalObjTime *interval_start,
                    CalObjTime *interval_end,
                    CalObjTime *cotime)
{
    GDate event_start_date, interval_start_date;
    guint32 event_start_julian, interval_start_julian;
    gint interval_start_weekday_offset;
    CalObjTime week_start;

    if (event_end && cal_obj_time_compare (event_end, interval_start,
                           CALOBJ_DAY) < 0)
        return TRUE;
    if (interval_end && cal_obj_time_compare (event_start, interval_end,
                          CALOBJ_DAY) > 0)
        return TRUE;

    *cotime = *event_start;

    /* Convert the event start and interval start to GDates, so we can
       easily find the number of days between them. */
    g_date_clear (&event_start_date, 1);
    g_date_set_dmy (&event_start_date, event_start->day,
            event_start->month + 1, event_start->year);
    g_date_clear (&interval_start_date, 1);
    g_date_set_dmy (&interval_start_date, interval_start->day,
            interval_start->month + 1, interval_start->year);

    /* Calculate the start of the weeks corresponding to the event start
       and interval start. */
    event_start_julian = g_date_julian (&event_start_date);
    event_start_julian -= recur_data->weekday_offset;

    interval_start_julian = g_date_julian (&interval_start_date);
    interval_start_weekday_offset = cal_obj_time_weekday_offset (interval_start, recur_data->recur);
    interval_start_julian -= interval_start_weekday_offset;

    /* We want to find the first full week using the recurrence interval
       that intersects the given interval dates. */
    if (event_start_julian < interval_start_julian) {
        gint weeks = (interval_start_julian - event_start_julian) / 7;
        weeks += recur_data->recur->interval - 1;
        weeks -= weeks % recur_data->recur->interval;
        cal_obj_time_add_days (cotime, weeks * 7);
    }

    week_start = *cotime;
    cal_obj_time_add_days (&week_start, -recur_data->weekday_offset);

    if (event_end && cal_obj_time_compare (&week_start, event_end,
                           CALOBJ_DAY) > 0)
        return TRUE;
    if (interval_end && cal_obj_time_compare (&week_start, interval_end,
                          CALOBJ_DAY) > 0)
        return TRUE;

    return FALSE;
}


static gboolean
cal_obj_weekly_find_next_position (CalObjTime *cotime,
                   CalObjTime *event_end,
                   RecurData  *recur_data,
                   CalObjTime *interval_end)
{
    CalObjTime week_start;

    cal_obj_time_add_days (cotime, recur_data->recur->interval * 7);

    /* Return TRUE if the start of this week is after the event finishes
       or is after the end of the required interval. */
    week_start = *cotime;
    cal_obj_time_add_days (&week_start, -recur_data->weekday_offset);

#ifdef CAL_OBJ_DEBUG
    g_print ("Next  day: %s\n",
         cal_obj_time_to_string (cotime, recur_data));
    g_print ("Week Start: %s\n",
         cal_obj_time_to_string (&week_start, recur_data));
#endif

    if (event_end && cal_obj_time_compare (&week_start, event_end,
                           CALOBJ_DAY) > 0)
        return TRUE;
    if (interval_end && cal_obj_time_compare (&week_start, interval_end,
                          CALOBJ_DAY) > 0) {
#ifdef CAL_OBJ_DEBUG
        g_print ("Interval end reached: %s\n",
             cal_obj_time_to_string (interval_end, recur_data));
#endif
        return TRUE;
    }

    return FALSE;
}


static gboolean
cal_obj_daily_find_start_position  (CalObjTime *event_start,
                    CalObjTime *event_end,
                    RecurData  *recur_data,
                    CalObjTime *interval_start,
                    CalObjTime *interval_end,
                    CalObjTime *cotime)
{
    GDate event_start_date, interval_start_date;
    guint32 event_start_julian, interval_start_julian, days;

    if (interval_end && cal_obj_time_compare (event_start, interval_end,
                          CALOBJ_DAY) > 0)
        return TRUE;
    if (event_end && cal_obj_time_compare (event_end, interval_start,
                           CALOBJ_DAY) < 0)
        return TRUE;

    *cotime = *event_start;

    /* Convert the event start and interval start to GDates, so we can
       easily find the number of days between them. */
    g_date_clear (&event_start_date, 1);
    g_date_set_dmy (&event_start_date, event_start->day,
            event_start->month + 1, event_start->year);
    g_date_clear (&interval_start_date, 1);
    g_date_set_dmy (&interval_start_date, interval_start->day,
            interval_start->month + 1, interval_start->year);

    event_start_julian = g_date_julian (&event_start_date);
    interval_start_julian = g_date_julian (&interval_start_date);

    if (event_start_julian < interval_start_julian) {
        days = interval_start_julian - event_start_julian
            + recur_data->recur->interval - 1;
        days -= days % recur_data->recur->interval;
        cal_obj_time_add_days (cotime, days);
    }

    if (event_end && cal_obj_time_compare (cotime, event_end,
                           CALOBJ_DAY) > 0)
        return TRUE;
    if (interval_end && cal_obj_time_compare (cotime, interval_end,
                          CALOBJ_DAY) > 0)
        return TRUE;

    return FALSE;
}


static gboolean
cal_obj_daily_find_next_position  (CalObjTime *cotime,
                   CalObjTime *event_end,
                   RecurData  *recur_data,
                   CalObjTime *interval_end)
{
    cal_obj_time_add_days (cotime, recur_data->recur->interval);

    if (event_end && cal_obj_time_compare (cotime, event_end,
                           CALOBJ_DAY) > 0)
        return TRUE;
    if (interval_end && cal_obj_time_compare (cotime, interval_end,
                          CALOBJ_DAY) > 0)
        return TRUE;

    return FALSE;
}


static gboolean
cal_obj_hourly_find_start_position (CalObjTime *event_start,
                    CalObjTime *event_end,
                    RecurData  *recur_data,
                    CalObjTime *interval_start,
                    CalObjTime *interval_end,
                    CalObjTime *cotime)
{
    GDate event_start_date, interval_start_date;
    guint32 event_start_julian, interval_start_julian, hours;

    if (interval_end && cal_obj_time_compare (event_start, interval_end,
                          CALOBJ_HOUR) > 0)
        return TRUE;
    if (event_end && cal_obj_time_compare (event_end, interval_start,
                           CALOBJ_HOUR) < 0)
        return TRUE;

    *cotime = *event_start;

    if (cal_obj_time_compare (event_start, interval_start,
                  CALOBJ_HOUR) < 0) {
        /* Convert the event start and interval start to GDates, so we
           can easily find the number of days between them. */
        g_date_clear (&event_start_date, 1);
        g_date_set_dmy (&event_start_date, event_start->day,
                event_start->month + 1, event_start->year);
        g_date_clear (&interval_start_date, 1);
        g_date_set_dmy (&interval_start_date, interval_start->day,
                interval_start->month + 1,
                interval_start->year);

        event_start_julian = g_date_julian (&event_start_date);
        interval_start_julian = g_date_julian (&interval_start_date);

        hours = (interval_start_julian - event_start_julian) * 24;
        hours += interval_start->hour - event_start->hour;
        hours += recur_data->recur->interval - 1;
        hours -= hours % recur_data->recur->interval;
        cal_obj_time_add_hours (cotime, hours);
    }

    if (event_end && cal_obj_time_compare (cotime, event_end,
                           CALOBJ_HOUR) > 0)
        return TRUE;
    if (interval_end && cal_obj_time_compare (cotime, interval_end,
                          CALOBJ_HOUR) > 0)
        return TRUE;

    return FALSE;
}


static gboolean
cal_obj_hourly_find_next_position (CalObjTime *cotime,
                   CalObjTime *event_end,
                   RecurData  *recur_data,
                   CalObjTime *interval_end)
{
    cal_obj_time_add_hours (cotime, recur_data->recur->interval);

    if (event_end && cal_obj_time_compare (cotime, event_end,
                           CALOBJ_HOUR) > 0)
        return TRUE;
    if (interval_end && cal_obj_time_compare (cotime, interval_end,
                          CALOBJ_HOUR) > 0)
        return TRUE;

    return FALSE;
}


static gboolean
cal_obj_minutely_find_start_position (CalObjTime *event_start,
                      CalObjTime *event_end,
                      RecurData  *recur_data,
                      CalObjTime *interval_start,
                      CalObjTime *interval_end,
                      CalObjTime *cotime)
{
    GDate event_start_date, interval_start_date;
    guint32 event_start_julian, interval_start_julian, minutes;

    if (interval_end && cal_obj_time_compare (event_start, interval_end,
                          CALOBJ_MINUTE) > 0)
        return TRUE;
    if (event_end && cal_obj_time_compare (event_end, interval_start,
                           CALOBJ_MINUTE) < 0)
        return TRUE;

    *cotime = *event_start;

    if (cal_obj_time_compare (event_start, interval_start,
                  CALOBJ_MINUTE) < 0) {
        /* Convert the event start and interval start to GDates, so we
           can easily find the number of days between them. */
        g_date_clear (&event_start_date, 1);
        g_date_set_dmy (&event_start_date, event_start->day,
                event_start->month + 1, event_start->year);
        g_date_clear (&interval_start_date, 1);
        g_date_set_dmy (&interval_start_date, interval_start->day,
                interval_start->month + 1,
                interval_start->year);

        event_start_julian = g_date_julian (&event_start_date);
        interval_start_julian = g_date_julian (&interval_start_date);

        minutes = (interval_start_julian - event_start_julian)
            * 24 * 60;
        minutes += (interval_start->hour - event_start->hour) * 24;
        minutes += interval_start->minute - event_start->minute;
        minutes += recur_data->recur->interval - 1;
        minutes -= minutes % recur_data->recur->interval;
        cal_obj_time_add_minutes (cotime, minutes);
    }

    if (event_end && cal_obj_time_compare (cotime, event_end,
                           CALOBJ_MINUTE) > 0)
        return TRUE;
    if (interval_end && cal_obj_time_compare (cotime, interval_end,
                          CALOBJ_MINUTE) > 0)
        return TRUE;

    return FALSE;
}


static gboolean
cal_obj_minutely_find_next_position (CalObjTime *cotime,
                     CalObjTime *event_end,
                     RecurData  *recur_data,
                     CalObjTime *interval_end)
{
    cal_obj_time_add_minutes (cotime, recur_data->recur->interval);

    if (event_end && cal_obj_time_compare (cotime, event_end,
                           CALOBJ_MINUTE) > 0)
        return TRUE;
    if (interval_end && cal_obj_time_compare (cotime, interval_end,
                          CALOBJ_MINUTE) > 0)
        return TRUE;

    return FALSE;
}


static gboolean
cal_obj_secondly_find_start_position (CalObjTime *event_start,
                      CalObjTime *event_end,
                      RecurData  *recur_data,
                      CalObjTime *interval_start,
                      CalObjTime *interval_end,
                      CalObjTime *cotime)
{
    GDate event_start_date, interval_start_date;
    guint32 event_start_julian, interval_start_julian, seconds;

    if (interval_end && cal_obj_time_compare (event_start, interval_end,
                          CALOBJ_SECOND) > 0)
        return TRUE;
    if (event_end && cal_obj_time_compare (event_end, interval_start,
                           CALOBJ_SECOND) < 0)
        return TRUE;

    *cotime = *event_start;

    if (cal_obj_time_compare (event_start, interval_start,
                  CALOBJ_SECOND) < 0) {
        /* Convert the event start and interval start to GDates, so we
           can easily find the number of days between them. */
        g_date_clear (&event_start_date, 1);
        g_date_set_dmy (&event_start_date, event_start->day,
                event_start->month + 1, event_start->year);
        g_date_clear (&interval_start_date, 1);
        g_date_set_dmy (&interval_start_date, interval_start->day,
                interval_start->month + 1,
                interval_start->year);

        event_start_julian = g_date_julian (&event_start_date);
        interval_start_julian = g_date_julian (&interval_start_date);

        seconds = (interval_start_julian - event_start_julian)
            * 24 * 60 * 60;
        seconds += (interval_start->hour - event_start->hour)
            * 24 * 60;
        seconds += (interval_start->minute - event_start->minute) * 60;
        seconds += interval_start->second - event_start->second;
        seconds += recur_data->recur->interval - 1;
        seconds -= seconds % recur_data->recur->interval;
        cal_obj_time_add_seconds (cotime, seconds);
    }

    if (event_end && cal_obj_time_compare (cotime, event_end,
                           CALOBJ_SECOND) >= 0)
        return TRUE;
    if (interval_end && cal_obj_time_compare (cotime, interval_end,
                          CALOBJ_SECOND) >= 0)
        return TRUE;

    return FALSE;
}


static gboolean
cal_obj_secondly_find_next_position (CalObjTime *cotime,
                     CalObjTime *event_end,
                     RecurData  *recur_data,
                     CalObjTime *interval_end)
{
    cal_obj_time_add_seconds (cotime, recur_data->recur->interval);

    if (event_end && cal_obj_time_compare (cotime, event_end,
                           CALOBJ_SECOND) >= 0)
        return TRUE;
    if (interval_end && cal_obj_time_compare (cotime, interval_end,
                          CALOBJ_SECOND) >= 0)
        return TRUE;

    return FALSE;
}





/* If the BYMONTH rule is specified it expands each occurrence in occs, by
   using each of the months in the bymonth list. */
static GArray*
cal_obj_bymonth_expand      (RecurData  *recur_data,
                 GArray     *occs)
{
    GArray *new_occs;
    CalObjTime *occ;
    GList *elem;
    gint len, i;

    /* If BYMONTH has not been specified, or the array is empty, just
       return the array. */
    if (!recur_data->recur->bymonth || occs->len == 0)
        return occs;

    new_occs = g_array_new (FALSE, FALSE, sizeof (CalObjTime));

    len = occs->len;
    for (i = 0; i < len; i++) {
        occ = &g_array_index (occs, CalObjTime, i);

        elem = recur_data->recur->bymonth;
        while (elem) {
            /* NOTE: The day may now be invalid, e.g. 31st Feb. */
            occ->month = GPOINTER_TO_INT (elem->data);
            g_array_append_vals (new_occs, occ, 1);
            elem = elem->next;
        }
    }

    g_array_free (occs, TRUE);

    return new_occs;
}


/* If the BYMONTH rule is specified it filters out all occurrences in occs
   which do not match one of the months in the bymonth list. */
static GArray*
cal_obj_bymonth_filter      (RecurData  *recur_data,
                 GArray     *occs)
{
    GArray *new_occs;
    CalObjTime *occ;
    gint len, i;

    /* If BYMONTH has not been specified, or the array is empty, just
       return the array. */
    if (!recur_data->recur->bymonth || occs->len == 0)
        return occs;

    new_occs = g_array_new (FALSE, FALSE, sizeof (CalObjTime));

    len = occs->len;
    for (i = 0; i < len; i++) {
        occ = &g_array_index (occs, CalObjTime, i);
        if (recur_data->months[occ->month])
            g_array_append_vals (new_occs, occ, 1);
    }

    g_array_free (occs, TRUE);

    return new_occs;
}



static GArray*
cal_obj_byweekno_expand     (RecurData  *recur_data,
                 GArray     *occs)
{
    GArray *new_occs;
    CalObjTime *occ, year_start_cotime, year_end_cotime, cotime;
    GList *elem;
    gint len, i, weekno;

    /* If BYWEEKNO has not been specified, or the array is empty, just
       return the array. */
    if (!recur_data->recur->byweekno || occs->len == 0)
        return occs;

    new_occs = g_array_new (FALSE, FALSE, sizeof (CalObjTime));

    len = occs->len;
    for (i = 0; i < len; i++) {
        occ = &g_array_index (occs, CalObjTime, i);

        /* Find the day that would correspond to week 1 (note that
           week 1 is the first week starting from the specified week
           start day that has 4 days in the new year). */
        year_start_cotime = *occ;
        cal_obj_time_find_first_week (&year_start_cotime,
                          recur_data);

        /* Find the day that would correspond to week 1 of the next
           year, which we use for -ve week numbers. */
        year_end_cotime = *occ;
        year_end_cotime.year++;
        cal_obj_time_find_first_week (&year_end_cotime,
                          recur_data);

        /* Now iterate over the week numbers in byweekno, generating a
           new occurrence for each one. */
        elem = recur_data->recur->byweekno;
        while (elem) {
            weekno = GPOINTER_TO_INT (elem->data);
            if (weekno > 0) {
                cotime = year_start_cotime;
                cal_obj_time_add_days (&cotime,
                               (weekno - 1) * 7);
            } else {
                cotime = year_end_cotime;
                cal_obj_time_add_days (&cotime, weekno * 7);
            }

            /* Skip occurrences if they fall outside the year. */
            if (cotime.year == occ->year)
                g_array_append_val (new_occs, cotime);
            elem = elem->next;
        }
    }

    g_array_free (occs, TRUE);

    return new_occs;
}


#if 0
/* This isn't used at present. */
static GArray*
cal_obj_byweekno_filter     (RecurData  *recur_data,
                 GArray     *occs)
{

    return occs;
}
#endif


static GArray*
cal_obj_byyearday_expand    (RecurData  *recur_data,
                 GArray     *occs)
{
    GArray *new_occs;
    CalObjTime *occ, year_start_cotime, year_end_cotime, cotime;
    GList *elem;
    gint len, i, dayno;

    /* If BYYEARDAY has not been specified, or the array is empty, just
       return the array. */
    if (!recur_data->recur->byyearday || occs->len == 0)
        return occs;

    new_occs = g_array_new (FALSE, FALSE, sizeof (CalObjTime));

    len = occs->len;
    for (i = 0; i < len; i++) {
        occ = &g_array_index (occs, CalObjTime, i);

        /* Find the day that would correspond to day 1. */
        year_start_cotime = *occ;
        year_start_cotime.month = 0;
        year_start_cotime.day = 1;

        /* Find the day that would correspond to day 1 of the next
           year, which we use for -ve day numbers. */
        year_end_cotime = *occ;
        year_end_cotime.year++;
        year_end_cotime.month = 0;
        year_end_cotime.day = 1;

        /* Now iterate over the day numbers in byyearday, generating a
           new occurrence for each one. */
        elem = recur_data->recur->byyearday;
        while (elem) {
            dayno = GPOINTER_TO_INT (elem->data);
            if (dayno > 0) {
                cotime = year_start_cotime;
                cal_obj_time_add_days (&cotime, dayno - 1);
            } else {
                cotime = year_end_cotime;
                cal_obj_time_add_days (&cotime, dayno);
            }

            /* Skip occurrences if they fall outside the year. */
            if (cotime.year == occ->year)
                g_array_append_val (new_occs, cotime);
            elem = elem->next;
        }
    }

    g_array_free (occs, TRUE);

    return new_occs;
}


/* Note: occs must not contain invalid dates, e.g. 31st September. */
static GArray*
cal_obj_byyearday_filter    (RecurData  *recur_data,
                 GArray     *occs)
{
    GArray *new_occs;
    CalObjTime *occ;
    gint yearday, len, i, days_in_year;

    /* If BYYEARDAY has not been specified, or the array is empty, just
       return the array. */
    if (!recur_data->recur->byyearday || occs->len == 0)
        return occs;

    new_occs = g_array_new (FALSE, FALSE, sizeof (CalObjTime));

    len = occs->len;
    for (i = 0; i < len; i++) {
        occ = &g_array_index (occs, CalObjTime, i);
        yearday = cal_obj_time_day_of_year (occ);
        if (recur_data->yeardays[yearday]) {
            g_array_append_vals (new_occs, occ, 1);
        } else {
            days_in_year = g_date_is_leap_year (occ->year)
                ? 366 : 365;
            if (recur_data->neg_yeardays[days_in_year + 1
                            - yearday])
                g_array_append_vals (new_occs, occ, 1);
        }
    }

    g_array_free (occs, TRUE);

    return new_occs;
}



static GArray*
cal_obj_bymonthday_expand   (RecurData  *recur_data,
                 GArray     *occs)
{
    GArray *new_occs;
    CalObjTime *occ, month_start_cotime, month_end_cotime, cotime;
    GList *elem;
    gint len, i, dayno;

    /* If BYMONTHDAY has not been specified, or the array is empty, just
       return the array. */
    if (!recur_data->recur->bymonthday || occs->len == 0)
        return occs;

    new_occs = g_array_new (FALSE, FALSE, sizeof (CalObjTime));

    len = occs->len;
    for (i = 0; i < len; i++) {
        occ = &g_array_index (occs, CalObjTime, i);

        /* Find the day that would correspond to day 1. */
        month_start_cotime = *occ;
        month_start_cotime.day = 1;

        /* Find the day that would correspond to day 1 of the next
           month, which we use for -ve day numbers. */
        month_end_cotime = *occ;
        month_end_cotime.month++;
        month_end_cotime.day = 1;

        /* Now iterate over the day numbers in bymonthday, generating a
           new occurrence for each one. */
        elem = recur_data->recur->bymonthday;
        while (elem) {
            dayno = GPOINTER_TO_INT (elem->data);
            if (dayno > 0) {
                cotime = month_start_cotime;
                cal_obj_time_add_days (&cotime, dayno - 1);
            } else {
                cotime = month_end_cotime;
                cal_obj_time_add_days (&cotime, dayno);
            }

            /* Skip occurrences if they fall outside the month. */
            if (cotime.month == occ->month)
                g_array_append_val (new_occs, cotime);
            elem = elem->next;
        }
    }

    g_array_free (occs, TRUE);

    return new_occs;
}


static GArray*
cal_obj_bymonthday_filter   (RecurData  *recur_data,
                 GArray     *occs)
{
    GArray *new_occs;
    CalObjTime *occ;
    gint len, i, days_in_month;

    /* If BYMONTHDAY has not been specified, or the array is empty, just
       return the array. */
    if (!recur_data->recur->bymonthday || occs->len == 0)
        return occs;

    new_occs = g_array_new (FALSE, FALSE, sizeof (CalObjTime));

    len = occs->len;
    for (i = 0; i < len; i++) {
        occ = &g_array_index (occs, CalObjTime, i);
        if (recur_data->monthdays[occ->day]) {
            g_array_append_vals (new_occs, occ, 1);
        } else {
            days_in_month = time_days_in_month (occ->year,
                                occ->month);
            if (recur_data->neg_monthdays[days_in_month + 1
                             - occ->day])
                g_array_append_vals (new_occs, occ, 1);
        }
    }

    g_array_free (occs, TRUE);

    return new_occs;
}



static GArray*
cal_obj_byday_expand_yearly (RecurData  *recur_data,
                 GArray     *occs)
{
    GArray *new_occs;
    CalObjTime *occ;
    GList *elem;
    gint len, i, weekday, week_num;
    gint first_weekday, last_weekday, offset;
    guint16 year;

    /* If BYDAY has not been specified, or the array is empty, just
       return the array. */
    if (!recur_data->recur->byday || occs->len == 0)
        return occs;

    new_occs = g_array_new (FALSE, FALSE, sizeof (CalObjTime));

    len = occs->len;
    for (i = 0; i < len; i++) {
        occ = &g_array_index (occs, CalObjTime, i);

        elem = recur_data->recur->byday;
        while (elem) {
            weekday = GPOINTER_TO_INT (elem->data);
            elem = elem->next;
            week_num = GPOINTER_TO_INT (elem->data);
            elem = elem->next;

            year = occ->year;
            if (week_num == 0) {
                /* Expand to every Mon/Tue/etc. in the year. */
                occ->month = 0;
                occ->day = 1;
                first_weekday = cal_obj_time_weekday (occ, recur_data->recur);
                offset = (weekday + 7 - first_weekday) % 7;
                cal_obj_time_add_days (occ, offset);

                while (occ->year == year) {
                    g_array_append_vals (new_occs, occ, 1);
                    cal_obj_time_add_days (occ, 7);
                }

            } else if (week_num > 0) {
                /* Add the nth Mon/Tue/etc. in the year. */
                occ->month = 0;
                occ->day = 1;
                first_weekday = cal_obj_time_weekday (occ, recur_data->recur);
                offset = (weekday + 7 - first_weekday) % 7;
                offset += (week_num - 1) * 7;
                cal_obj_time_add_days (occ, offset);
                if (occ->year == year)
                    g_array_append_vals (new_occs, occ, 1);

            } else {
                /* Add the -nth Mon/Tue/etc. in the year. */
                occ->month = 11;
                occ->day = 31;
                last_weekday = cal_obj_time_weekday (occ, recur_data->recur);
                offset = (last_weekday + 7 - weekday) % 7;
                offset += (week_num - 1) * 7;
                cal_obj_time_add_days (occ, -offset);
                if (occ->year == year)
                    g_array_append_vals (new_occs, occ, 1);
            }

            /* Reset the year, as we may have gone past the end. */
            occ->year = year;
        }
    }

    g_array_free (occs, TRUE);

    return new_occs;
}


static GArray*
cal_obj_byday_expand_monthly    (RecurData  *recur_data,
                 GArray     *occs)
{
    GArray *new_occs;
    CalObjTime *occ;
    GList *elem;
    gint len, i, weekday, week_num;
    gint first_weekday, last_weekday, offset;
    guint16 year;
    guint8 month;

    /* If BYDAY has not been specified, or the array is empty, just
       return the array. */
    if (!recur_data->recur->byday || occs->len == 0)
        return occs;

    new_occs = g_array_new (FALSE, FALSE, sizeof (CalObjTime));

    len = occs->len;
    for (i = 0; i < len; i++) {
        occ = &g_array_index (occs, CalObjTime, i);

        elem = recur_data->recur->byday;
        while (elem) {
            weekday = GPOINTER_TO_INT (elem->data);
            elem = elem->next;
            week_num = GPOINTER_TO_INT (elem->data);
            elem = elem->next;

            year = occ->year;
            month = occ->month;
            if (week_num == 0) {
                /* Expand to every Mon/Tue/etc. in the month.*/
                occ->day = 1;
                first_weekday = cal_obj_time_weekday (occ, recur_data->recur);
                offset = (weekday + 7 - first_weekday) % 7;
                cal_obj_time_add_days (occ, offset);

                while (occ->year == year
                       && occ->month == month) {
                    g_array_append_vals (new_occs, occ, 1);
                    cal_obj_time_add_days (occ, 7);
                }

            } else if (week_num > 0) {
                /* Add the nth Mon/Tue/etc. in the month. */
                occ->day = 1;
                first_weekday = cal_obj_time_weekday (occ, recur_data->recur);
                offset = (weekday + 7 - first_weekday) % 7;
                offset += (week_num - 1) * 7;
                cal_obj_time_add_days (occ, offset);
                if (occ->year == year && occ->month == month)
                    g_array_append_vals (new_occs, occ, 1);

            } else {
                /* Add the -nth Mon/Tue/etc. in the month. */
                occ->day = time_days_in_month (occ->year,
                                   occ->month);
                last_weekday = cal_obj_time_weekday (occ, recur_data->recur);
                offset = (last_weekday + 7 - weekday) % 7;
                offset += (week_num - 1) * 7;
                cal_obj_time_add_days (occ, -offset);
                if (occ->year == year && occ->month == month)
                    g_array_append_vals (new_occs, occ, 1);
            }

            /* Reset the year & month, as we may have gone past
               the end. */
            occ->year = year;
            occ->month = month;
        }
    }

    g_array_free (occs, TRUE);

    return new_occs;
}


/* Note: occs must not contain invalid dates, e.g. 31st September. */
static GArray*
cal_obj_byday_expand_weekly (RecurData  *recur_data,
                 GArray     *occs)
{
    GArray *new_occs;
    CalObjTime *occ;
    GList *elem;
    gint len, i, weekday, week_num;
    gint weekday_offset, new_weekday_offset;

    /* If BYDAY has not been specified, or the array is empty, just
       return the array. */
    if (!recur_data->recur->byday || occs->len == 0)
        return occs;

    new_occs = g_array_new (FALSE, FALSE, sizeof (CalObjTime));

    len = occs->len;
    for (i = 0; i < len; i++) {
        occ = &g_array_index (occs, CalObjTime, i);

        elem = recur_data->recur->byday;
        while (elem) {
            weekday = GPOINTER_TO_INT (elem->data);
            elem = elem->next;

            /* FIXME: Currently we just ignore this, but maybe we
               should skip all elements where week_num != 0.
               The spec isn't clear about this. */
            week_num = GPOINTER_TO_INT (elem->data);
            elem = elem->next;

            weekday_offset = cal_obj_time_weekday_offset (occ, recur_data->recur);
            new_weekday_offset = (weekday + 7 - recur_data->recur->week_start_day) % 7;
            cal_obj_time_add_days (occ, new_weekday_offset - weekday_offset);
            g_array_append_vals (new_occs, occ, 1);
        }
    }

    g_array_free (occs, TRUE);

    return new_occs;
}


/* Note: occs must not contain invalid dates, e.g. 31st September. */
static GArray*
cal_obj_byday_filter        (RecurData  *recur_data,
                 GArray     *occs)
{
    GArray *new_occs;
    CalObjTime *occ;
    gint len, i, weekday;

    /* If BYDAY has not been specified, or the array is empty, just
       return the array. */
    if (!recur_data->recur->byday || occs->len == 0)
        return occs;

    new_occs = g_array_new (FALSE, FALSE, sizeof (CalObjTime));

    len = occs->len;
    for (i = 0; i < len; i++) {
        occ = &g_array_index (occs, CalObjTime, i);
        weekday = cal_obj_time_weekday (occ, recur_data->recur);

        /* See if the weekday on its own is set. */
        if (recur_data->weekdays[weekday])
            g_array_append_vals (new_occs, occ, 1);
    }

    g_array_free (occs, TRUE);

    return new_occs;
}



/* If the BYHOUR rule is specified it expands each occurrence in occs, by
   using each of the hours in the byhour list. */
static GArray*
cal_obj_byhour_expand       (RecurData  *recur_data,
                 GArray     *occs)
{
    GArray *new_occs;
    CalObjTime *occ;
    GList *elem;
    gint len, i;

    /* If BYHOUR has not been specified, or the array is empty, just
       return the array. */
    if (!recur_data->recur->byhour || occs->len == 0)
        return occs;

    new_occs = g_array_new (FALSE, FALSE, sizeof (CalObjTime));

    len = occs->len;
    for (i = 0; i < len; i++) {
        occ = &g_array_index (occs, CalObjTime, i);

        elem = recur_data->recur->byhour;
        while (elem) {
            occ->hour = GPOINTER_TO_INT (elem->data);
            g_array_append_vals (new_occs, occ, 1);
            elem = elem->next;
        }
    }

    g_array_free (occs, TRUE);

    return new_occs;
}


/* If the BYHOUR rule is specified it filters out all occurrences in occs
   which do not match one of the hours in the byhour list. */
static GArray*
cal_obj_byhour_filter       (RecurData  *recur_data,
                 GArray     *occs)
{
    GArray *new_occs;
    CalObjTime *occ;
    gint len, i;

    /* If BYHOUR has not been specified, or the array is empty, just
       return the array. */
    if (!recur_data->recur->byhour || occs->len == 0)
        return occs;

    new_occs = g_array_new (FALSE, FALSE, sizeof (CalObjTime));

    len = occs->len;
    for (i = 0; i < len; i++) {
        occ = &g_array_index (occs, CalObjTime, i);
        if (recur_data->hours[occ->hour])
            g_array_append_vals (new_occs, occ, 1);
    }

    g_array_free (occs, TRUE);

    return new_occs;
}



/* If the BYMINUTE rule is specified it expands each occurrence in occs, by
   using each of the minutes in the byminute list. */
static GArray*
cal_obj_byminute_expand     (RecurData  *recur_data,
                 GArray     *occs)
{
    GArray *new_occs;
    CalObjTime *occ;
    GList *elem;
    gint len, i;

    /* If BYMINUTE has not been specified, or the array is empty, just
       return the array. */
    if (!recur_data->recur->byminute || occs->len == 0)
        return occs;

    new_occs = g_array_new (FALSE, FALSE, sizeof (CalObjTime));

    len = occs->len;
    for (i = 0; i < len; i++) {
        occ = &g_array_index (occs, CalObjTime, i);

        elem = recur_data->recur->byminute;
        while (elem) {
            occ->minute = GPOINTER_TO_INT (elem->data);
            g_array_append_vals (new_occs, occ, 1);
            elem = elem->next;
        }
    }

    g_array_free (occs, TRUE);

    return new_occs;
}


/* If the BYMINUTE rule is specified it filters out all occurrences in occs
   which do not match one of the minutes in the byminute list. */
static GArray*
cal_obj_byminute_filter     (RecurData  *recur_data,
                 GArray     *occs)
{
    GArray *new_occs;
    CalObjTime *occ;
    gint len, i;

    /* If BYMINUTE has not been specified, or the array is empty, just
       return the array. */
    if (!recur_data->recur->byminute || occs->len == 0)
        return occs;

    new_occs = g_array_new (FALSE, FALSE, sizeof (CalObjTime));

    len = occs->len;
    for (i = 0; i < len; i++) {
        occ = &g_array_index (occs, CalObjTime, i);
        if (recur_data->minutes[occ->minute])
            g_array_append_vals (new_occs, occ, 1);
    }

    g_array_free (occs, TRUE);

    return new_occs;
}



/* If the BYSECOND rule is specified it expands each occurrence in occs, by
   using each of the seconds in the bysecond list. */
static GArray*
cal_obj_bysecond_expand     (RecurData  *recur_data,
                 GArray     *occs)
{
    GArray *new_occs;
    CalObjTime *occ;
    GList *elem;
    gint len, i;

    /* If BYSECOND has not been specified, or the array is empty, just
       return the array. */
    if (!recur_data->recur->bysecond || occs->len == 0)
        return occs;

    new_occs = g_array_new (FALSE, FALSE, sizeof (CalObjTime));

    len = occs->len;
    for (i = 0; i < len; i++) {
        occ = &g_array_index (occs, CalObjTime, i);

        elem = recur_data->recur->bysecond;
        while (elem) {
            occ->second = GPOINTER_TO_INT (elem->data);
            g_array_append_vals (new_occs, occ, 1);
            elem = elem->next;
        }
    }

    g_array_free (occs, TRUE);

    return new_occs;
}


/* If the BYSECOND rule is specified it filters out all occurrences in occs
   which do not match one of the seconds in the bysecond list. */
static GArray*
cal_obj_bysecond_filter     (RecurData  *recur_data,
                 GArray     *occs)
{
    GArray *new_occs;
    CalObjTime *occ;
    gint len, i;

    /* If BYSECOND has not been specified, or the array is empty, just
       return the array. */
    if (!recur_data->recur->bysecond || occs->len == 0)
        return occs;

    new_occs = g_array_new (FALSE, FALSE, sizeof (CalObjTime));

    len = occs->len;
    for (i = 0; i < len; i++) {
        occ = &g_array_index (occs, CalObjTime, i);
        if (recur_data->seconds[occ->second])
            g_array_append_vals (new_occs, occ, 1);
    }

    g_array_free (occs, TRUE);

    return new_occs;
}





/* Adds a positive or negative number of months to the given CalObjTime,
   updating the year appropriately so we end up with a valid month.
   Note that the day may be invalid, e.g. 30th Feb. */
static void
cal_obj_time_add_months     (CalObjTime *cotime,
                 gint        months)
{
    guint month, years;

    /* We use a guint to avoid overflow on the guint8. */
    month = cotime->month + months;
    cotime->month = month % 12;
    if (month > 0) {
        cotime->year += month / 12;
    } else {
        years = month / 12;
        if (cotime->month != 0) {
            cotime->month += 12;
            years -= 1;
        }
        cotime->year += years;
    }
}


/* Adds a positive or negative number of days to the given CalObjTime,
   updating the month and year appropriately so we end up with a valid day. */
static void
cal_obj_time_add_days       (CalObjTime *cotime,
                 gint        days)
{
    gint day, days_in_month;

    /* We use a guint to avoid overflow on the guint8. */
    day = cotime->day;
    day += days;

    if (days >= 0) {
        for (;;) {
            days_in_month = time_days_in_month (cotime->year,
                                cotime->month);
            if (day <= days_in_month)
                break;

            cotime->month++;
            if (cotime->month >= 12) {
                cotime->year++;
                cotime->month = 0;
            }

            day -= days_in_month;
        }

        cotime->day = (guint8) day;
    } else {
        while (day <= 0) {
            if (cotime->month == 0) {
                cotime->year--;
                cotime->month = 11;
            } else {
                cotime->month--;
            }

            days_in_month = time_days_in_month (cotime->year,
                                cotime->month);
            day += days_in_month;
        }

        cotime->day = (guint8) day;
    }
}


/* Adds a positive or negative number of hours to the given CalObjTime,
   updating the day, month & year appropriately so we end up with a valid
   time. */
static void
cal_obj_time_add_hours      (CalObjTime *cotime,
                 gint        hours)
{
    gint hour, days;

    /* We use a gint to avoid overflow on the guint8. */
    hour = cotime->hour + hours;
    cotime->hour = hour % 24;
    if (hour >= 0) {
        if (hour >= 24)
            cal_obj_time_add_days (cotime, hour / 24);
    } else {
        days = hour / 24;
        if (cotime->hour != 0) {
            cotime->hour += 24;
            days -= 1;
        }
        cal_obj_time_add_days (cotime, days);
    }
}


/* Adds a positive or negative number of minutes to the given CalObjTime,
   updating the rest of the CalObjTime appropriately. */
static void
cal_obj_time_add_minutes    (CalObjTime *cotime,
                 gint        minutes)
{
    gint minute, hours;

    /* We use a gint to avoid overflow on the guint8. */
    minute = cotime->minute + minutes;
    cotime->minute = minute % 60;
    if (minute >= 0) {
        if (minute >= 60)
            cal_obj_time_add_hours (cotime, minute / 60);
    } else {
        hours = minute / 60;
        if (cotime->minute != 0) {
            cotime->minute += 60;
            hours -= 1;
        }
        cal_obj_time_add_hours (cotime, hours);
    }
}


/* Adds a positive or negative number of seconds to the given CalObjTime,
   updating the rest of the CalObjTime appropriately. */
static void
cal_obj_time_add_seconds    (CalObjTime *cotime,
                 gint        seconds)
{
    gint second, minutes;

    /* We use a gint to avoid overflow on the guint8. */
    second = cotime->second + seconds;
    cotime->second = second % 60;
    if (second >= 0) {
        if (second >= 60)
            cal_obj_time_add_minutes (cotime, second / 60);
    } else {
        minutes = second / 60;
        if (cotime->second != 0) {
            cotime->second += 60;
            minutes -= 1;
        }
        cal_obj_time_add_minutes (cotime, minutes);
    }
}


/* Compares 2 CalObjTimes. Returns -1 if the cotime1 is before cotime2, 0 if
   they are the same, or 1 if cotime1 is after cotime2. The comparison type
   specifies which parts of the times we are interested in, e.g. if CALOBJ_DAY
   is used we only want to know if the days are different. */
static gint
cal_obj_time_compare        (CalObjTime *cotime1,
                 CalObjTime *cotime2,
                 CalObjTimeComparison type)
{
    if (cotime1->year < cotime2->year)
        return -1;
    if (cotime1->year > cotime2->year)
        return 1;

    if (type == CALOBJ_YEAR)
        return 0;

    if (cotime1->month < cotime2->month)
        return -1;
    if (cotime1->month > cotime2->month)
        return 1;

    if (type == CALOBJ_MONTH)
        return 0;

    if (cotime1->day < cotime2->day)
        return -1;
    if (cotime1->day > cotime2->day)
        return 1;

    if (type == CALOBJ_DAY)
        return 0;

    if (cotime1->hour < cotime2->hour)
        return -1;
    if (cotime1->hour > cotime2->hour)
        return 1;

    if (type == CALOBJ_HOUR)
        return 0;

    if (cotime1->minute < cotime2->minute)
        return -1;
    if (cotime1->minute > cotime2->minute)
        return 1;

    if (type == CALOBJ_MINUTE)
        return 0;

    if (cotime1->second < cotime2->second)
        return -1;
    if (cotime1->second > cotime2->second)
        return 1;

    return 0;
}


/* This is the same as the above function, but without the comparison type.
   It is used for qsort(). */
static gint
cal_obj_time_compare_func (const void *arg1,
               const void *arg2)
{
    CalObjTime *cotime1, *cotime2;
    gint retval;

    cotime1 = (CalObjTime*) arg1;
    cotime2 = (CalObjTime*) arg2;

    if (cotime1->year < cotime2->year)
        retval = -1;
    else if (cotime1->year > cotime2->year)
        retval = 1;

    else if (cotime1->month < cotime2->month)
        retval = -1;
    else if (cotime1->month > cotime2->month)
        retval = 1;

    else if (cotime1->day < cotime2->day)
        retval = -1;
    else if (cotime1->day > cotime2->day)
        retval = 1;

    else if (cotime1->hour < cotime2->hour)
        retval = -1;
    else if (cotime1->hour > cotime2->hour)
        retval = 1;

    else if (cotime1->minute < cotime2->minute)
        retval = -1;
    else if (cotime1->minute > cotime2->minute)
        retval = 1;

    else if (cotime1->second < cotime2->second)
        retval = -1;
    else if (cotime1->second > cotime2->second)
        retval = 1;

    else
        retval = 0;

#if 0
    g_print ("%s - ", cal_obj_time_to_string (cotime1, NULL));
    g_print ("%s : %i\n", cal_obj_time_to_string (cotime2, NULL), retval);
#endif

    return retval;
}

static gint
cal_obj_date_only_compare_func (const void *arg1,
                const void *arg2)
{
    CalObjTime *cotime1, *cotime2;

    cotime1 = (CalObjTime*) arg1;
    cotime2 = (CalObjTime*) arg2;

    if (cotime1->year < cotime2->year)
        return -1;
    if (cotime1->year > cotime2->year)
        return 1;

    if (cotime1->month < cotime2->month)
        return -1;
    if (cotime1->month > cotime2->month)
        return 1;

    if (cotime1->day < cotime2->day)
        return -1;
    if (cotime1->day > cotime2->day)
        return 1;

    return 0;
}

/* Returns the weekday of the given CalObjTime, from 0 (Mon) - 6 (Sun). */
static gint
cal_obj_time_weekday        (CalObjTime *cotime,
                 CalRecurrence *recur)
{
    GDate date;
    gint weekday;

    g_date_clear (&date, 1);
    g_date_set_dmy (&date, cotime->day, cotime->month + 1, cotime->year);

    /* This results in a value of 0 (Monday) - 6 (Sunday). */
    weekday = g_date_weekday (&date) - 1;

    return weekday;
}


/* Returns the weekday of the given CalObjTime, from 0 - 6. The week start
   day is Monday by default, but can be set in the recurrence rule. */
static gint
cal_obj_time_weekday_offset (CalObjTime *cotime,
                 CalRecurrence *recur)
{
    GDate date;
    gint weekday, offset;

    g_date_clear (&date, 1);
    g_date_set_dmy (&date, cotime->day, cotime->month + 1, cotime->year);

    /* This results in a value of 0 (Monday) - 6 (Sunday). */
    weekday = g_date_weekday (&date) - 1;

    /* This calculates the offset of our day from the start of the week.
       We just add on a week (to avoid any possible negative values) and
       then subtract the specified week start day, then convert it into a
       value from 0-6. */
    offset = (weekday + 7 - recur->week_start_day) % 7;

    return offset;
}


/* Returns the day of the year of the given CalObjTime, from 1 - 366. */
static gint
cal_obj_time_day_of_year        (CalObjTime *cotime)
{
    GDate date;

    g_date_clear (&date, 1);
    g_date_set_dmy (&date, cotime->day, cotime->month + 1, cotime->year);

    return g_date_day_of_year (&date);
}


/* Finds the first week in the given CalObjTime's year, using the same weekday
   as the event start day (i.e. from the RecurData).
   The first week of the year is the first week starting from the specified
   week start day that has 4 days in the new year. It may be in the previous
   year. */
static void
cal_obj_time_find_first_week    (CalObjTime *cotime,
                 RecurData  *recur_data)
{
    GDate date;
    gint weekday, week_start_day, first_full_week_start_offset, offset;

    /* Find out the weekday of the 1st of the year, 0 (Mon) - 6 (Sun). */
    g_date_clear (&date, 1);
    g_date_set_dmy (&date, 1, 1, cotime->year);
    weekday = g_date_weekday (&date) - 1;

    /* Calculate the first day of the year that starts a new week, i.e. the
       first week_start_day after weekday, using 0 = 1st Jan.
       e.g. if the 1st Jan is a Tuesday (1) and week_start_day is a
       Monday (0), the result will be (0 + 7 - 1) % 7 = 6 (7th Jan). */
    week_start_day = recur_data->recur->week_start_day;
    first_full_week_start_offset = (week_start_day + 7 - weekday) % 7;

    /* Now see if we have to move backwards 1 week, i.e. if the week
       starts on or after Jan 5th (since the previous week has 4 days in
       this year and so will be the first week of the year). */
    if (first_full_week_start_offset >= 4)
        first_full_week_start_offset -= 7;

    /* Now add the days to get to the event's weekday. */
    offset = first_full_week_start_offset + recur_data->weekday_offset;

    /* Now move the cotime to the appropriate day. */
    cotime->month = 0;
    cotime->day = 1;
    cal_obj_time_add_days (cotime, offset);
}


static void
cal_object_time_from_time (CalObjTime *cotime,
               time_t      t)
{
    struct tm *tmp_tm;
    time_t tmp_time_t;

    tmp_time_t = t;
    tmp_tm = localtime (&tmp_time_t);

    cotime->year     = tmp_tm->tm_year + 1900;
    cotime->month    = tmp_tm->tm_mon;
    cotime->day      = tmp_tm->tm_mday;
    cotime->hour     = tmp_tm->tm_hour;
    cotime->minute   = tmp_tm->tm_min;
    cotime->second   = tmp_tm->tm_sec;
    cotime->is_rdate = FALSE;
}


/* Debugging function to convert a CalObjTime to a string. It uses a static
   buffer so beware. */
#ifdef CAL_OBJ_DEBUG
static char*
cal_obj_time_to_string      (CalObjTime *cotime,
                 RecurData  *recur_data)
{
    static char buffer[20];
    char *weekdays[] = { "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun",
                 "   " };
    gint weekday = 7;

    if (recur_data)
        weekday = cal_obj_time_weekday (cotime, recur_data->recur);

    sprintf (buffer, "%s %02i/%02i/%04i %02i:%02i:%02i",
         weekdays[weekday],
         cotime->day, cotime->month + 1, cotime->year,
         cotime->hour, cotime->minute, cotime->second);
    return buffer;
}
#endif


/* This recalculates the end dates for recurrence & exception rules which use
   the COUNT property. If refresh is TRUE it will recalculate all enddates
   for rules which use COUNT. If refresh is FALSE, it will only calculate
   the enddate if it hasn't already been set. It returns TRUE if the component
   was changed, i.e. if the component should be saved at some point.
   We store the enddate in the "X-EVOLUTION-ENDDATE" parameter of the RRULE
   or EXRULE. */
static gboolean
cal_recur_ensure_end_dates (CalComponent    *comp,
                gboolean         refresh)
{
    GSList *rrules, *exrules, *elem;
    gboolean changed = FALSE;

    /* Do the RRULEs. */
    cal_component_get_rrule_property_list (comp, &rrules);
    for (elem = rrules; elem; elem = elem->next) {
        changed |= cal_recur_ensure_rule_end_date (comp, elem->data,
                               FALSE, refresh);
    }

    /* Do the EXRULEs. */
    cal_component_get_exrule_property_list (comp, &exrules);
    for (elem = exrules; elem; elem = elem->next) {
        changed |= cal_recur_ensure_rule_end_date (comp, elem->data,
                               TRUE, refresh);
    }

    return changed;
}


typedef struct _CalRecurEnsureEndDateData CalRecurEnsureEndDateData;
struct _CalRecurEnsureEndDateData {
    gint count;
    gint instances;
    time_t end_date;
};


static gboolean
cal_recur_ensure_rule_end_date (CalComponent            *comp,
                icalproperty            *prop,
                gboolean             exception,
                gboolean             refresh)
{
    struct icalrecurrencetype rule;
    CalRecurEnsureEndDateData cb_data;

    if (exception)
        rule = icalproperty_get_exrule (prop);
    else
        rule = icalproperty_get_rrule (prop);

    /* If the rule doesn't use COUNT just return. */
    if (rule.count == 0)
        return FALSE;

    /* If refresh is FALSE, we check if the enddate is already set, and
       if it is we just return. */
    if (!refresh) {
        if (cal_recur_get_rule_end_date (prop) != -1)
            return FALSE;
    }

    /* Calculate the end date. */
    cb_data.count = rule.count;
    cb_data.instances = 0;
    cal_recur_generate_instances_of_rule (comp, prop, -1, -1,
                          cal_recur_ensure_rule_end_date_cb,
                          &cb_data);

    /* Store the end date in the "X-EVOLUTION-ENDDATE" parameter of the
       rule. */
    cal_recur_set_rule_end_date (prop, cb_data.end_date);
        
    return TRUE;
}


static gboolean
cal_recur_ensure_rule_end_date_cb   (CalComponent   *comp,
                     time_t      instance_start,
                     time_t      instance_end,
                     gpointer    data)
{
    CalRecurEnsureEndDateData *cb_data;

    cb_data = (CalRecurEnsureEndDateData*) data;

    cb_data->instances++;

    if (cb_data->instances == cb_data->count) {
        cb_data->end_date = instance_start;
        return FALSE;
    }

    return TRUE;
}


static time_t
cal_recur_get_rule_end_date (icalproperty   *prop)
{
    icalparameter *param;
    char *xname, *xvalue;
    icalvalue *value;
    struct icaltimetype icaltime;

    param = icalproperty_get_first_parameter (prop, ICAL_X_PARAMETER);
    while (param) {
        xname = icalparameter_get_xname (param);
        if (xname && !strcmp (xname, EVOLUTION_END_DATE_PARAMETER)) {
            xvalue = icalparameter_get_x (param);
            value = icalvalue_new_from_string (ICAL_DATETIME_VALUE,
                               xvalue);
            if (value) {
                icaltime = icalvalue_get_datetime (value);
                icalvalue_free (value);

                return icaltime_as_timet (icaltime);
            }
        }

        param = icalproperty_get_next_parameter (prop,
                             ICAL_X_PARAMETER);
    }

    return -1;
}


static void
cal_recur_set_rule_end_date (icalproperty   *prop,
                 time_t      end_date)
{
    icalparameter *param;
    icalvalue *value;
    struct icaltimetype icaltime;
    char *end_date_string, *xname;

    icaltime = icaltime_from_timet (end_date, FALSE, FALSE);
    value = icalvalue_new_datetime (icaltime);
    end_date_string = icalvalue_as_ical_string (value);
    icalvalue_free (value);

    /* If we already have an X-EVOLUTION-ENDDATE parameter, set the value
       to the new date-time. */
    param = icalproperty_get_first_parameter (prop, ICAL_X_PARAMETER);
    while (param) {
        xname = icalparameter_get_xname (param);
        if (xname && !strcmp (xname, EVOLUTION_END_DATE_PARAMETER)) {
            icalparameter_set_x (param, end_date_string);
            return;
        }
        param = icalproperty_get_next_parameter (prop, ICAL_X_PARAMETER);
    }

    /* Create a new X-EVOLUTION-ENDDATE and add it to the property. */
    param = icalparameter_new_x (end_date_string);
    icalparameter_set_xname (param, EVOLUTION_END_DATE_PARAMETER);
    icalproperty_add_parameter (prop, param);
}