aboutsummaryrefslogtreecommitdiffstats
path: root/camel/camel-mime-utils.c
blob: a6488c231b304bca7d871b5090a26c8cfe92ed3e (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
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
/*
 *  Copyright (C) 2000 Ximian Inc.
 *
 *  Authors: Michael Zucchi <notzed@ximian.com>
 *           Jeffrey Stedfast <fejj@ximian.com>
 *
 *  This program is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Library 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 Library General Public License for more details.
 *
 *  You should have received a copy of the GNU Library General Public
 *  License along with this program; if not, write to the Free Software
 *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

/* dont touch this file without my permission - Michael */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/param.h>  /* for MAXHOSTNAMELEN */
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#ifndef MAXHOSTNAMELEN
#define MAXHOSTNAMELEN 1024
#endif

#include <iconv.h>

#include <time.h>

#include <ctype.h>
#include <errno.h>
#include <regex.h>

#include <glib.h>
#include <gal/unicode/gunicode.h>

#include "camel-mime-utils.h"
#include "camel-charset-map.h"

#ifdef ENABLE_THREADS
#include <pthread.h>
#endif

#ifndef CLEAN_DATE
#include "broken-date-parser.h"
#endif

#if 0
int strdup_count = 0;
int malloc_count = 0;
int free_count = 0;

#define g_strdup(x) (strdup_count++, g_strdup(x))
#define g_malloc(x) (malloc_count++, g_malloc(x))
#define g_free(x) (free_count++, g_free(x))
#endif

/* for all warnings ... */
#define w(x) x

#define d(x)
#define d2(x)

#define CAMEL_UUDECODE_CHAR(c)  (((c) - ' ') & 077)

static char *base64_alphabet =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

static unsigned char tohex[16] = {
    '0', '1', '2', '3', '4', '5', '6', '7',
    '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
};

static unsigned short camel_mime_special_table[256] = {
      5,  5,  5,  5,  5,  5,  5,  5,  5,231,  7,  5,  5, 39,  5,  5,
      5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,
    242,448, 76,192,192,192,192,192, 76, 76,448,448, 76,448, 72,324,
    448,448,448,448,448,448,448,448,448,448, 76, 76, 76,  4, 76, 68,
     76,448,448,448,448,448,448,448,448,448,448,448,448,448,448,448,
    448,448,448,448,448,448,448,448,448,448,448,108,236,108,192, 64,
    192,448,448,448,448,448,448,448,448,448,448,448,448,448,448,448,
    448,448,448,448,448,448,448,448,448,448,448,192,192,192,192,  5,
      0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
      0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
      0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
      0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
      0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
      0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
      0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
      0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
};

static unsigned char camel_mime_base64_rank[256] = {
    255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
    255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
    255,255,255,255,255,255,255,255,255,255,255, 62,255,255,255, 63,
     52, 53, 54, 55, 56, 57, 58, 59, 60, 61,255,255,255,  0,255,255,
    255,  0,  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,255,255,255,255,255,
    255, 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,255,255,255,255,255,
    255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
    255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
    255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
    255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
    255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
    255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
    255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
    255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
};

/*
  if any of these change, then the tables above should be regenerated
  by compiling this with -DBUILD_TABLE, and running.

  gcc -DCLEAN_DATE -o buildtable -I.. `gnome-config --cflags --libs gal` -DBUILD_TABLE camel-mime-utils.c camel-charset-map.c
  ./buildtable

*/
enum {
    IS_CTRL     = 1<<0,
    IS_LWSP     = 1<<1,
    IS_TSPECIAL = 1<<2,
    IS_SPECIAL  = 1<<3,
    IS_SPACE    = 1<<4,
    IS_DSPECIAL = 1<<5,
    IS_QPSAFE   = 1<<6,
    IS_ESAFE    = 1<<7, /* encoded word safe */
    IS_PSAFE    = 1<<8, /* encoded word in phrase safe */
};

#define is_ctrl(x) ((camel_mime_special_table[(unsigned char)(x)] & IS_CTRL) != 0)
#define is_lwsp(x) ((camel_mime_special_table[(unsigned char)(x)] & IS_LWSP) != 0)
#define is_tspecial(x) ((camel_mime_special_table[(unsigned char)(x)] & IS_TSPECIAL) != 0)
#define is_type(x, t) ((camel_mime_special_table[(unsigned char)(x)] & (t)) != 0)
#define is_ttoken(x) ((camel_mime_special_table[(unsigned char)(x)] & (IS_TSPECIAL|IS_LWSP|IS_CTRL)) == 0)
#define is_atom(x) ((camel_mime_special_table[(unsigned char)(x)] & (IS_SPECIAL|IS_SPACE|IS_CTRL)) == 0)
#define is_dtext(x) ((camel_mime_special_table[(unsigned char)(x)] & IS_DSPECIAL) == 0)
#define is_fieldname(x) ((camel_mime_special_table[(unsigned char)(x)] & (IS_CTRL|IS_SPACE)) == 0)
#define is_qpsafe(x) ((camel_mime_special_table[(unsigned char)(x)] & IS_QPSAFE) != 0)
#define is_especial(x) ((camel_mime_special_table[(unsigned char)(x)] & IS_ESPECIAL) != 0)
#define is_psafe(x) ((camel_mime_special_table[(unsigned char)(x)] & IS_PSAFE) != 0)

/* only needs to be run to rebuild the tables above */
#ifdef BUILD_TABLE

#define CHARS_LWSP " \t\n\r"
#define CHARS_TSPECIAL "()<>@,;:\\\"/[]?="
#define CHARS_SPECIAL "()<>@,;:\\\".[]"
#define CHARS_CSPECIAL "()\\\r" /* not in comments */
#define CHARS_DSPECIAL "[]\\\r \t"  /* not in domains */
#define CHARS_ESPECIAL "()<>@,;:\"/[]?.=_" /* list of characters that must be encoded.
                          encoded word in text specials: rfc 2047 5(1)*/
#define CHARS_PSPECIAL "!*+-/" /* list of additional characters that can be left unencoded.
                  encoded word in phrase specials: rfc 2047 5(3) */

static void
header_remove_bits(unsigned short bit, unsigned char *vals)
{
    int i;

    for (i=0;vals[i];i++)
        camel_mime_special_table[vals[i]] &= ~ bit;
}

static void
header_init_bits(unsigned short bit, unsigned short bitcopy, int remove, unsigned char *vals)
{
    int i;
    int len = strlen(vals);

    if (!remove) {
        for (i=0;i<len;i++) {
            camel_mime_special_table[vals[i]] |= bit;
        }
        if (bitcopy) {
            for (i=0;i<256;i++) {
                if (camel_mime_special_table[i] & bitcopy)
                    camel_mime_special_table[i] |= bit;
            }
        }
    } else {
        for (i=0;i<256;i++)
            camel_mime_special_table[i] |= bit;
        for (i=0;i<len;i++) {
            camel_mime_special_table[vals[i]] &= ~bit;
        }
        if (bitcopy) {
            for (i=0;i<256;i++) {
                if (camel_mime_special_table[i] & bitcopy)
                    camel_mime_special_table[i] &= ~bit;
            }
        }
    }
}

static void
header_decode_init(void)
{
    int i;

    for (i=0;i<256;i++) {
        camel_mime_special_table[i] = 0;
        if (i<32)
            camel_mime_special_table[i] |= IS_CTRL;
        if ((i>=33 && i<=60) || (i>=62 && i<=126) || i==32 || i==9)
            camel_mime_special_table[i] |= (IS_QPSAFE|IS_ESAFE);
        if ((i>='0' && i<='9') || (i>='a' && i<='z') || (i>='A' && i<= 'Z'))
            camel_mime_special_table[i] |= IS_PSAFE;
    }
    camel_mime_special_table[127] |= IS_CTRL;
    camel_mime_special_table[' '] |= IS_SPACE;
    header_init_bits(IS_LWSP, 0, 0, CHARS_LWSP);
    header_init_bits(IS_TSPECIAL, IS_CTRL, 0, CHARS_TSPECIAL);
    header_init_bits(IS_SPECIAL, 0, 0, CHARS_SPECIAL);
    header_init_bits(IS_DSPECIAL, 0, FALSE, CHARS_DSPECIAL);
    header_remove_bits(IS_ESAFE, CHARS_ESPECIAL);
    header_init_bits(IS_PSAFE, 0, 0, CHARS_PSPECIAL);
}

void
base64_init(void)
{
    int i;

    memset(camel_mime_base64_rank, 0xff, sizeof(camel_mime_base64_rank));
    for (i=0;i<64;i++) {
        camel_mime_base64_rank[(unsigned int)base64_alphabet[i]] = i;
    }
    camel_mime_base64_rank['='] = 0;
}

int main(int argc, char **argv)
{
    int i;
    void run_test(void);

    header_decode_init();
    base64_init();

    printf("static unsigned short camel_mime_special_table[256] = {\n\t");
    for (i=0;i<256;i++) {
        printf("%3d,", camel_mime_special_table[i]);
        if ((i&15) == 15) {
            printf("\n");
            if (i!=255) {
                printf("\t");
            }
        }
    }
    printf("};\n");

    printf("static unsigned char camel_mime_base64_rank[256] = {\n\t");
    for (i=0;i<256;i++) {
        printf("%3d,", camel_mime_base64_rank[i]);
        if ((i&15) == 15) {
            printf("\n");
            if (i!=255) {
                printf("\t");
            }
        }
    }
    printf("};\n");

    run_test();

    return 0;
}

#endif


/* call this when finished encoding everything, to
   flush off the last little bit */
int
base64_encode_close(unsigned char *in, int inlen, gboolean break_lines, unsigned char *out, int *state, int *save)
{
    int c1, c2;
    unsigned char *outptr = out;

    if (inlen>0)
        outptr += base64_encode_step(in, inlen, break_lines, outptr, state, save);

    c1 = ((unsigned char *)save)[1];
    c2 = ((unsigned char *)save)[2];
    
    d(printf("mode = %d\nc1 = %c\nc2 = %c\n",
         (int)((char *)save)[0],
         (int)((char *)save)[1],
         (int)((char *)save)[2]));

    switch (((char *)save)[0]) {
    case 2:
        outptr[2] = base64_alphabet[ ( (c2 &0x0f) << 2 ) ];
        g_assert(outptr[2] != 0);
        goto skip;
    case 1:
        outptr[2] = '=';
    skip:
        outptr[0] = base64_alphabet[ c1 >> 2 ];
        outptr[1] = base64_alphabet[ c2 >> 4 | ( (c1&0x3) << 4 )];
        outptr[3] = '=';
        outptr += 4;
        break;
    }
    if (break_lines)
        *outptr++ = '\n';

    *save = 0;
    *state = 0;

    return outptr-out;
}

/*
  performs an 'encode step', only encodes blocks of 3 characters to the
  output at a time, saves left-over state in state and save (initialise to
  0 on first invocation).
*/
int
base64_encode_step(unsigned char *in, int len, gboolean break_lines, unsigned char *out, int *state, int *save)
{
    register unsigned char *inptr, *outptr;

    if (len<=0)
        return 0;

    inptr = in;
    outptr = out;

    d(printf("we have %d chars, and %d saved chars\n", len, ((char *)save)[0]));

    if (len + ((char *)save)[0] > 2) {
        unsigned char *inend = in+len-2;
        register int c1, c2, c3;
        register int already;

        already = *state;

        switch (((char *)save)[0]) {
        case 1: c1 = ((unsigned char *)save)[1]; goto skip1;
        case 2: c1 = ((unsigned char *)save)[1];
            c2 = ((unsigned char *)save)[2]; goto skip2;
        }
        
        /* yes, we jump into the loop, no i'm not going to change it, it's beautiful! */
        while (inptr < inend) {
            c1 = *inptr++;
        skip1:
            c2 = *inptr++;
        skip2:
            c3 = *inptr++;
            *outptr++ = base64_alphabet[ c1 >> 2 ];
            *outptr++ = base64_alphabet[ c2 >> 4 | ( (c1&0x3) << 4 ) ];
            *outptr++ = base64_alphabet[ ( (c2 &0x0f) << 2 ) | (c3 >> 6) ];
            *outptr++ = base64_alphabet[ c3 & 0x3f ];
            /* this is a bit ugly ... */
            if (break_lines && (++already)>=19) {
                *outptr++='\n';
                already = 0;
            }
        }

        ((char *)save)[0] = 0;
        len = 2-(inptr-inend);
        *state = already;
    }

    d(printf("state = %d, len = %d\n",
         (int)((char *)save)[0],
         len));

    if (len>0) {
        register char *saveout;

        /* points to the slot for the next char to save */
        saveout = & (((char *)save)[1]) + ((char *)save)[0];

        /* len can only be 0 1 or 2 */
        switch(len) {
        case 2: *saveout++ = *inptr++;
        case 1: *saveout++ = *inptr++;
        }
        ((char *)save)[0]+=len;
    }

    d(printf("mode = %d\nc1 = %c\nc2 = %c\n",
         (int)((char *)save)[0],
         (int)((char *)save)[1],
         (int)((char *)save)[2]));

    return outptr-out;
}


/**
 * base64_decode_step: decode a chunk of base64 encoded data
 * @in: input stream
 * @len: max length of data to decode
 * @out: output stream
 * @state: holds the number of bits that are stored in @save
 * @save: leftover bits that have not yet been decoded
 *
 * Decodes a chunk of base64 encoded data
 **/
int
base64_decode_step(unsigned char *in, int len, unsigned char *out, int *state, unsigned int *save)
{
    register unsigned char *inptr, *outptr;
    unsigned char *inend, c;
    register unsigned int v;
    int i;

    inend = in+len;
    outptr = out;

    /* convert 4 base64 bytes to 3 normal bytes */
    v=*save;
    i=*state;
    inptr = in;
    while (inptr<inend) {
        c = camel_mime_base64_rank[*inptr++];
        if (c != 0xff) {
            v = (v<<6) | c;
            i++;
            if (i==4) {
                *outptr++ = v>>16;
                *outptr++ = v>>8;
                *outptr++ = v;
                i=0;
            }
        }
    }

    *save = v;
    *state = i;

    /* quick scan back for '=' on the end somewhere */
    /* fortunately we can drop 1 output char for each trailing = (upto 2) */
    i=2;
    while (inptr>in && i) {
        inptr--;
        if (camel_mime_base64_rank[*inptr] != 0xff) {
            if (*inptr == '=')
                outptr--;
            i--;
        }
    }

    /* if i!= 0 then there is a truncation error! */
    return outptr-out;
}

char *
base64_encode_simple (const char *data, int len)
{
    unsigned char *out;
    int state = 0, outlen;
    unsigned int save = 0;
    
    out = g_malloc (len * 4 / 3 + 5);
    outlen = base64_encode_close ((unsigned char *)data, len, FALSE,
                      out, &state, &save);
    out[outlen] = '\0';
    return (char *)out;
}

int
base64_decode_simple (char *data, int len)
{
    int state = 0;
    unsigned int save = 0;

    return base64_decode_step ((unsigned char *)data, len,
                   (unsigned char *)data, &state, &save);
}


/**
 * uudecode_step: uudecode a chunk of data
 * @in: input stream
 * @len: max length of data to decode ( normally strlen(in) ??)
 * @out: output stream
 * @state: holds the number of bits that are stored in @save
 * @save: leftover bits that have not yet been decoded
 * @uulen: holds the value of the length-char which is used to calculate
 *         how many more chars need to be decoded for that 'line'
 *
 * uudecodes a chunk of data. Assumes the "begin <mode> <file name>" line
 * has been stripped off.
 **/
int
uudecode_step (unsigned char *in, int len, unsigned char *out, int *state, guint32 *save, char *uulen)
{
    register unsigned char *inptr, *outptr;
    unsigned char *inend, ch;
    register guint32 saved;
    gboolean last_was_eoln;
    int i;

    if (*uulen <= 0)
        last_was_eoln = TRUE;
    else
        last_was_eoln = FALSE;
    
    inend = in + len;
    outptr = out;
    saved = *save;
    i = *state;
    inptr = in;
    while (inptr < inend && *inptr) {
        if (*inptr == '\n' || last_was_eoln) {
            if (last_was_eoln) {
                *uulen = CAMEL_UUDECODE_CHAR (*inptr);
                last_was_eoln = FALSE;
            } else {
                last_was_eoln = TRUE;
            }

            inptr++;
            continue;
        }

        ch = *inptr++;
        
        if (*uulen > 0) {
            /* save the byte */
            saved = (saved << 8) | ch;
            i++;
            if (i == 4) {
                /* convert 4 uuencoded bytes to 3 normal bytes */
                unsigned char b0, b1, b2, b3;

                b0 = saved >> 24;
                b1 = saved >> 16 & 0xff;
                b2 = saved >> 8 & 0xff;
                b3 = saved & 0xff;

                if (*uulen >= 3) {
                    *outptr++ = CAMEL_UUDECODE_CHAR (b0) << 2 | CAMEL_UUDECODE_CHAR (b1) >> 4;
                    *outptr++ = CAMEL_UUDECODE_CHAR (b1) << 4 | CAMEL_UUDECODE_CHAR (b2) >> 2;
                        *outptr++ = CAMEL_UUDECODE_CHAR (b2) << 6 | CAMEL_UUDECODE_CHAR (b3);
                } else {
                    if (*uulen >= 1) {
                        *outptr++ = CAMEL_UUDECODE_CHAR (b0) << 2 | CAMEL_UUDECODE_CHAR (b1) >> 4;
                    }
                    if (*uulen >= 2) {
                        *outptr++ = CAMEL_UUDECODE_CHAR (b1) << 4 | CAMEL_UUDECODE_CHAR (b2) >> 2;
                    }
                }

                i = 0;
                saved = 0;
                *uulen -= 3;
            }
        } else {
            break;
        }
    }

    *save = saved;
    *state = i;

    return outptr - out;
}

/* complete qp encoding */
int
quoted_encode_close(unsigned char *in, int len, unsigned char *out, int *state, int *save)
{
    register unsigned char *outptr = out;
    int last;

    if (len>0)
        outptr += quoted_encode_step(in, len, outptr, state, save);

    last = *state;
    if (last != -1) {
        /* space/tab must be encoded if it's the last character on
           the line */
        if (is_qpsafe(last) && last!=' ' && last!=9) {
            *outptr++ = last;
        } else {
            *outptr++ = '=';
            *outptr++ = tohex[(last>>4) & 0xf];
            *outptr++ = tohex[last & 0xf];
        }
    }

    *save = 0;
    *state = -1;

    return outptr-out;
}

/* perform qp encoding, initialise state to -1 and save to 0 on first invocation */
int
quoted_encode_step (unsigned char *in, int len, unsigned char *out, int *statep, int *save)
{
    register guchar *inptr, *outptr, *inend;
    guchar c;
    register int sofar = *save;  /* keeps track of how many chars on a line */
    register int last = *statep; /* keeps track if last char to end was a space cr etc */
    
    inptr = in;
    inend = in + len;
    outptr = out;
    while (inptr < inend) {
        c = *inptr++;
        if (c == '\r') {
            if (last != -1) {
                *outptr++ = '=';
                *outptr++ = tohex[(last >> 4) & 0xf];
                *outptr++ = tohex[last & 0xf];
                sofar += 3;
            }
            last = c;
        } else if (c == '\n') {
            if (last != -1 && last != '\r') {
                *outptr++ = '=';
                *outptr++ = tohex[(last >> 4) & 0xf];
                *outptr++ = tohex[last & 0xf];
            }
            *outptr++ = '\n';
            sofar = 0;
            last = -1;
        } else {
            if (last != -1) {
                if (is_qpsafe(last)) {
                    *outptr++ = last;
                    sofar++;
                } else {
                    *outptr++ = '=';
                    *outptr++ = tohex[(last >> 4) & 0xf];
                    *outptr++ = tohex[last & 0xf];
                    sofar += 3;
                }
            }
            
            if (is_qpsafe(c)) {
                if (sofar > 74) {
                    *outptr++ = '=';
                    *outptr++ = '\n';
                    sofar = 0;
                }
                
                /* delay output of space char */
                if (c==' ' || c=='\t') {
                    last = c;
                } else {
                    *outptr++ = c;
                    sofar++;
                    last = -1;
                }
            } else {
                if (sofar > 72) {
                    *outptr++ = '=';
                    *outptr++ = '\n';
                    sofar = 3;
                } else
                    sofar += 3;
                
                *outptr++ = '=';
                *outptr++ = tohex[(c >> 4) & 0xf];
                *outptr++ = tohex[c & 0xf];
                last = -1;
            }
        }
    }
    *save = sofar;
    *statep = last;
    
    return (outptr - out);
}

/*
  FIXME: this does not strip trailing spaces from lines (as it should, rfc 2045, section 6.7)
  Should it also canonicalise the end of line to CR LF??

  Note: Trailing rubbish (at the end of input), like = or =x or =\r will be lost.
*/ 

int
quoted_decode_step(unsigned char *in, int len, unsigned char *out, int *savestate, int *saveme)
{
    register unsigned char *inptr, *outptr;
    unsigned char *inend, c;
    int state, save;

    inend = in+len;
    outptr = out;

    d(printf("quoted-printable, decoding text '%.*s'\n", len, in));

    state = *savestate;
    save = *saveme;
    inptr = in;
    while (inptr<inend) {
        switch (state) {
        case 0:
            while (inptr<inend) {
                c = *inptr++;
                if (c=='=') { 
                    state = 1;
                    break;
                }
#ifdef CANONICALISE_EOL
                /*else if (c=='\r') {
                    state = 3;
                } else if (c=='\n') {
                    *outptr++ = '\r';
                    *outptr++ = c;
                    } */
#endif
                else {
                    *outptr++ = c;
                }
            }
            break;
        case 1:
            c = *inptr++;
            if (c=='\n') {
                /* soft break ... unix end of line */
                state = 0;
            } else {
                save = c;
                state = 2;
            }
            break;
        case 2:
            c = *inptr++;
            if (isxdigit(c) && isxdigit(save)) {
                c = toupper(c);
                save = toupper(save);
                *outptr++ = (((save>='A'?save-'A'+10:save-'0')&0x0f) << 4)
                    | ((c>='A'?c-'A'+10:c-'0')&0x0f);
            } else if (c=='\n' && save == '\r') {
                /* soft break ... canonical end of line */
            } else {
                /* just output the data */
                *outptr++ = '=';
                *outptr++ = save;
                *outptr++ = c;
            }
            state = 0;
            break;
#ifdef CANONICALISE_EOL
        case 3:
            /* convert \r -> to \r\n, leaves \r\n alone */
            c = *inptr++;
            if (c=='\n') {
                *outptr++ = '\r';
                *outptr++ = c;
            } else {
                *outptr++ = '\r';
                *outptr++ = '\n';
                *outptr++ = c;
            }
            state = 0;
            break;
#endif
        }
    }

    *savestate = state;
    *saveme = save;

    return outptr-out;
}

/*
  this is for the "Q" encoding of international words,
  which is slightly different than plain quoted-printable (mainly by allowing 0x20 <> _)
*/
static int
quoted_decode(const unsigned char *in, int len, unsigned char *out)
{
    register const unsigned char *inptr;
    register unsigned char *outptr;
    unsigned const char *inend;
    unsigned char c, c1;
    int ret = 0;

    inend = in+len;
    outptr = out;

    d(printf("decoding text '%.*s'\n", len, in));

    inptr = in;
    while (inptr<inend) {
        c = *inptr++;
        if (c=='=') {
            /* silently ignore truncated data? */
            if (inend-in>=2) {
                c = toupper(*inptr++);
                c1 = toupper(*inptr++);
                *outptr++ = (((c>='A'?c-'A'+10:c-'0')&0x0f) << 4)
                    | ((c1>='A'?c1-'A'+10:c1-'0')&0x0f);
            } else {
                ret = -1;
                break;
            }
        } else if (c=='_') {
            *outptr++ = 0x20;
        } else if (c==' ' || c==0x09) {
            /* FIXME: this is an error! ignore for now ... */
            ret = -1;
            break;
        } else {
            *outptr++ = c;
        }
    }
    if (ret==0) {
        return outptr-out;
    }
    return -1;
}

/* rfc2047 version of quoted-printable */
/* safemask is the mask to apply to the camel_mime_special_table to determine what
   characters can safely be included without encoding */
static int
quoted_encode(const unsigned char *in, int len, unsigned char *out, unsigned short safemask)
{
    register const unsigned char *inptr, *inend;
    unsigned char *outptr;
    unsigned char c;

    inptr = in;
    inend = in + len;
    outptr = out;
    while (inptr < inend) {
        c = *inptr++;
        if (c==' ') {
            *outptr++ = '_';
        } else if (camel_mime_special_table[c] & safemask) {
            *outptr++ = c;
        } else {
            *outptr++ = '=';
            *outptr++ = tohex[(c >> 4) & 0xf];
            *outptr++ = tohex[c & 0xf];
        }
    }

    d(printf("encoding '%.*s' = '%.*s'\n", len, in, outptr-out, out));

    return (outptr - out);
}


static void
header_decode_lwsp(const char **in)
{
    const char *inptr = *in;
    char c;

    d2(printf("is ws: '%s'\n", *in));

    while (is_lwsp(*inptr) || (*inptr =='(' && *inptr != '\0')) {
        while (is_lwsp(*inptr) && inptr != '\0') {
            d2(printf("(%c)", *inptr));
            inptr++;
        }
        d2(printf("\n"));

        /* check for comments */
        if (*inptr == '(') {
            int depth = 1;
            inptr++;
            while (depth && (c=*inptr) && *inptr != '\0') {
                if (c=='\\' && inptr[1]) {
                    inptr++;
                } else if (c=='(') {
                    depth++;
                } else if (c==')') {
                    depth--;
                }
                inptr++;
            }
        }
    }
    *in = inptr;
}

/* decode rfc 2047 encoded string segment */
static char *
rfc2047_decode_word(const char *in, int len)
{
    const char *inptr = in+2;
    const char *inend = in+len-2;
    const char *inbuf;
    const char *charset;
    char *encname;
    int tmplen;
    int ret;
    char *decword = NULL;
    char *decoded = NULL;
    char *outbase = NULL;
    char *outbuf;
    int inlen, outlen;
    iconv_t ic;

    d(printf("rfc2047: decoding '%.*s'\n", len, in));

    /* quick check to see if this could possibly be a real encoded word */
    if (len < 8 || !(in[0] == '=' && in[1] == '?' && in[len-1] == '=' && in[len-2] == '?')) {
        d(printf("invalid\n"));
        return NULL;
    }
    
    /* skip past the charset to the encoding type */
    inptr = memchr (inptr, '?', inend-inptr);
    if (inptr != NULL && inptr < inend + 2 && inptr[2] == '?') {
        d(printf("found ?, encoding is '%c'\n", inptr[0]));
        inptr++;
        tmplen = inend-inptr-2;
        decword = alloca(tmplen); /* this will always be more-than-enough room */
        switch(toupper(inptr[0])) {
        case 'Q':
            inlen = quoted_decode(inptr+2, tmplen, decword);
            break;
        case 'B': {
            int state = 0;
            unsigned int save = 0;
            
            inlen = base64_decode_step((char *)inptr+2, tmplen, decword, &state, &save);
            /* if state != 0 then error? */
            break;
        }
        default:
            /* uhhh, unknown encoding type - probably an invalid encoded word string */
            return NULL;
        }
        d(printf("The encoded length = %d\n", inlen));
        if (inlen > 0) {
            /* yuck, all this snot is to setup iconv! */
            tmplen = inptr - in - 3;
            encname = alloca (tmplen + 1);
            memcpy (encname, in + 2, tmplen);
            encname[tmplen] = '\0';
            
            charset = camel_charset_to_iconv (encname);
            
            inbuf = decword;
            
            outlen = inlen * 6 + 16;
            outbase = alloca (outlen);
            outbuf = outbase;
            
            /* TODO: Should this cache iconv converters? */
            ic = iconv_open ("UTF-8", charset);
            if (ic != (iconv_t)-1) {
                ret = iconv (ic, &inbuf, &inlen, &outbuf, &outlen);
                if (ret >= 0) {
                    iconv (ic, NULL, 0, &outbuf, &outlen);
                    *outbuf = 0;
                    decoded = g_strdup (outbase);
                }
                iconv_close (ic);
            } else {
                w(g_warning ("Cannot decode charset, header display may be corrupt: %s: %s",
                         charset, g_strerror (errno)));
                /* TODO: Should this do this, or just leave the encoded strings? */
                decword[inlen] = 0;
                decoded = g_strdup (decword);
            }
        }
    }
    
    d(printf("decoded '%s'\n", decoded));
    
    return decoded;
}

/* grrr, glib should have this ! */
static GString *
g_string_append_len(GString *st, const char *s, int l)
{
    char *tmp;

    tmp = alloca(l+1);
    tmp[l]=0;
    memcpy(tmp, s, l);
    return g_string_append(st, tmp);
}

/* ok, a lot of mailers are BROKEN, and send iso-latin1 encoded
   headers, when they should just be sticking to US-ASCII
   according to the rfc's.  Anyway, since the conversion to utf-8
   is trivial, just do it here without iconv */
static GString *
append_latin1 (GString *out, const char *in, int len)
{
    unsigned int c;
    
    while (len) {
        c = (unsigned int)*in++;
        len--;
        if (c & 0x80) {
            out = g_string_append_c (out, 0xc0 | ((c >> 6) & 0x3));  /* 110000xx */
            out = g_string_append_c (out, 0x80 | (c & 0x3f));        /* 10xxxxxx */
        } else {
            out = g_string_append_c (out, c);
        }
    }
    return out;
}

static void
append_8bit (GString *out, const char *inbuf, int inlen, const char *default_charset)
{
    char *outbase, *outbuf;
    int outlen;
    iconv_t ic;
    
    ic = iconv_open ("UTF-8", default_charset);
    if (ic != (iconv_t) -1) {
        int ret;
        
        outlen = inlen * 6 + 16;
        outbuf = outbase = g_malloc (outlen);
        
        ret = iconv (ic, &inbuf, &inlen, &outbuf, &outlen);
        if (ret >= 0) {
            iconv (ic, NULL, 0, &outbuf, &outlen);
            *outbuf = '\0';
        }
        
        iconv_close (ic);
        
        /* FIXME: is outlen == strlen (outbuf) ?? */
        g_string_append_len (out, outbase, strlen (outbase));
    } else {
        /* bah, completely broken...just append as raw text */
        g_string_append_len (out, inbuf, inlen);
    }
}

/* decodes a simple text, rfc822 */
static char *
header_decode_text (const char *in, int inlen, const char *default_charset)
{
    GString *out;
    char *inptr, *inend, *start, *word_start;
    char *decoded;
    gboolean wasdword = FALSE;
    gboolean wasspace = FALSE;
    gboolean islatin1 = FALSE;
    
    out = g_string_new ("");
    start = inptr = (char *) in;
    inend = inptr + inlen;
    
    word_start = NULL;
    while (inptr && inptr < inend) {
        unsigned char c = *inptr++;
        
        if (is_lwsp (c) && !wasspace) {
            char *word, *dword;
            
            if (word_start)
                word = word_start;
            else
                word = start;
            
            dword = rfc2047_decode_word (word, inptr - word - 1);
            
            if (dword) {
                if (!wasdword && word_start)
                    g_string_append_len (out, start, word_start - start);
                
                g_string_append (out, dword);
                g_free (dword);
                wasdword = TRUE;
            } else if (islatin1 || !default_charset) {
                /* append_latin1 is safe for 7bit ascii too */
                append_latin1 (out, start, inptr - start - 1);
                wasdword = FALSE;
            } else {
                append_8bit (out, start, inptr - start - 1, default_charset);
                wasdword = FALSE;
            }
            
            start = inptr - 1;
            word_start = NULL;
            wasspace = TRUE;
        } else if (!is_lwsp (c)) {
            wasspace = FALSE;
            if (!word_start)
                word_start = inptr - 1;
            
            if (c & 0x80 || c <= 127)
                islatin1 = TRUE;
            else
                islatin1 = FALSE;
        }
    }
    
    if (inptr - start) {
        char *word, *dword;
        
        if (word_start)
            word = word_start;
        else
            word = start;
        
        dword = rfc2047_decode_word (word, inptr - word);
        
        if (dword) {
            if (!wasdword && word_start)
                g_string_append_len (out, start, word_start - start);
            
            g_string_append (out, dword);
            g_free (dword);
        } else if (islatin1 || !default_charset) {
            /* append_latin1 is safe for 7bit ascii too */
            append_latin1 (out, start, inptr - start);
        } else {
            append_8bit (out, start, inptr - start, default_charset);
        }
    }
    
    decoded = out->str;
    g_string_free (out, FALSE);
    
    return decoded;
}

char *
header_decode_string (const char *in, const char *default_charset)
{
    if (in == NULL)
        return NULL;
    return header_decode_text (in, strlen (in), default_charset);
}

/* how long a sequence of pre-encoded words should be less than, to attempt to 
   fit into a properly folded word.  Only a guide. */
#define CAMEL_FOLD_PREENCODED (24)

/* FIXME: needs a way to cache iconv opens for different charsets? */
static void
rfc2047_encode_word(GString *outstring, const char *in, int len, const char *type, unsigned short safemask)
{
    iconv_t ic = (iconv_t *)-1;
    char *buffer, *out, *ascii;
    size_t inlen, outlen, enclen, bufflen;
    const char *inptr, *p;
    int first = 1;

    d(printf("Converting [%d] '%.*s' to %s\n", len, len, in, type));

    /* convert utf8->encoding */
    bufflen = len * 6 + 16;
    buffer = alloca (bufflen);
    inlen = len;
    inptr = in;
    
    ascii = alloca (bufflen);
    
    if (g_strcasecmp (type, "UTF-8") != 0)
        ic = iconv_open (type, "UTF-8");
    
    while (inlen) {
        int convlen, i, proclen;

        /* break up words into smaller bits, what we really want is encoded + overhead < 75,
           but we'll just guess what that means in terms of input chars, and assume its good enough */

        out = buffer;
        outlen = bufflen;

        if (ic == (iconv_t) -1) {
            /* native encoding case, the easy one (?) */
            /* we work out how much we can convert, and still be in length */
            /* proclen will be the result of input characters that we can convert, to the nearest
               (approximated) valid utf8 char */
            convlen = 0;
            proclen = 0;
            p = inptr;
            i = 0;
            while (p < (in+len) && convlen < (75 - strlen("=?utf-8?q??="))) {
                unsigned char c = *p++;

                if (c >= 0xc0)
                    proclen = i;
                i++;
                if (c < 0x80)
                    proclen = i;
                if (camel_mime_special_table[c] & safemask)
                    convlen += 1;
                else
                    convlen += 3;
            }
            /* well, we probably have broken utf8, just copy it anyway what the heck */
            if (proclen == 0) {
                w(g_warning("Appear to have truncated utf8 sequence"));
                proclen = inlen;
            }
            memcpy(out, inptr, proclen);
            inptr += proclen;
            inlen -= proclen;
            out += proclen;
        } else {
            /* well we could do similar, but we can't (without undue effort), we'll just break it up into
               hopefully-small-enough chunks, and leave it at that */
            convlen = MIN(inlen, CAMEL_FOLD_PREENCODED);
            p = inptr;
            if (iconv(ic, &inptr, &convlen, &out, &outlen) == -1) {
                w(g_warning("Conversion problem: conversion truncated: %s", strerror(errno)));
                /* blah, we include it anyway, better than infinite loop ... */
                inptr = p + convlen;
            } else {
                /* make sure we flush out any shift state */
                iconv(ic, NULL, 0, &out, &outlen);
            }
            inlen -= (inptr - p);
        }
        
        enclen = out-buffer;
        
        if (enclen) {
            /* create token */
            out = ascii;
            if (first)
                first = 0;
            else
                *out++ = ' ';
            out += sprintf (out, "=?%s?Q?", type);
            out += quoted_encode (buffer, enclen, out, safemask);
            sprintf (out, "?=");
            
            d(printf("converted part = %s\n", ascii));
            
            g_string_append (outstring, ascii);
        }
    }

    if (ic != (iconv_t) -1) {
        iconv_close(ic);
    }
}


/* TODO: Should this worry about quotes?? */
char *
header_encode_string (const unsigned char *in)
{
    const unsigned char *inptr = in, *start, *word;
    gboolean last_was_encoded = FALSE;
    gboolean last_was_space = FALSE;
    int encoding;
    GString *out;
    char *outstr;

    g_return_val_if_fail (g_utf8_validate (in, -1, NULL), NULL);
    
    if (in == NULL)
        return NULL;
    
    /* do a quick us-ascii check (the common case?) */
    while (*inptr) {
        if (*inptr > 127)
            break;
        inptr++;
    }
    if (*inptr == '\0')
        return g_strdup (in);
    
    /* This gets each word out of the input, and checks to see what charset
       can be used to encode it. */
    /* TODO: Work out when to merge subsequent words, or across word-parts */
    out = g_string_new ("");
    inptr = in;
    encoding = 0;
    word = NULL;
    start = inptr;
    while (inptr && *inptr) {
        gunichar c;
        const char *newinptr;
        
        newinptr = g_utf8_next_char (inptr);
        c = g_utf8_get_char (inptr);
        if (newinptr == NULL || !g_unichar_validate (c)) {
            w(g_warning ("Invalid UTF-8 sequence encountered (pos %d, char '%c'): %s",
                     (inptr-in), inptr[0], in));
            inptr++;
            continue;
        }

        
        if (g_unichar_isspace (c) && !last_was_space) {
            /* we've reached the end of a 'word' */
            if (word && !(last_was_encoded && encoding)) {
                g_string_append_len (out, start, word - start);
                start = word;
            }
            
            switch (encoding) {
            case 0:
                out = g_string_append_len (out, word, inptr - start);
                last_was_encoded = FALSE;
                break;
            case 1:
                if (last_was_encoded)
                    g_string_append_c (out, ' ');
                
                rfc2047_encode_word (out, start, inptr - start, "ISO-8859-1", IS_ESAFE);
                last_was_encoded = TRUE;
                break;
            case 2:
                if (last_was_encoded)
                    g_string_append_c (out, ' ');
                
                rfc2047_encode_word (out, start, inptr - start,
                             camel_charset_best (start, inptr - start), IS_ESAFE);
                last_was_encoded = TRUE;
                break;
            }
            
            last_was_space = TRUE;
            start = inptr;
            word = NULL;
            encoding = 0;
        } else if (c > 127 && c < 256) {
            encoding = MAX (encoding, 1);
            last_was_space = FALSE;
        } else if (c >= 256) {
            encoding = MAX (encoding, 2);
            last_was_space = FALSE;
        } else if (!g_unichar_isspace (c)) {
            last_was_space = FALSE;
        }
        
        if (!g_unichar_isspace (c) && !word)
            word = inptr;
        
        inptr = newinptr;
    }
    
    if (inptr - start) {
        if (word && !(last_was_encoded && encoding)) {
            g_string_append_len (out, start, word - start);
            start = word;
        }
        
        switch (encoding) {
        case 0:
            out = g_string_append_len (out, start, inptr - start);
            break;
        case 1:
            if (last_was_encoded)
                g_string_append_c (out, ' ');
            
            rfc2047_encode_word (out, start, inptr - start, "ISO-8859-1", IS_ESAFE);
            break;
        case 2:
            if (last_was_encoded)
                g_string_append_c (out, ' ');
            
            rfc2047_encode_word (out, start, inptr - start,
                         camel_charset_best (start, inptr - start - 1), IS_ESAFE);
            break;
        }
    }
    
    outstr = out->str;
    g_string_free (out, FALSE);
    
    return outstr;
}

/* apply quoted-string rules to a string */
static void
quote_word(GString *out, gboolean do_quotes, const char *start, int len)
{
    int i, c;

    /* TODO: What about folding on long lines? */
    if (do_quotes)
        g_string_append_c(out, '"');
    for (i=0;i<len;i++) {
        c = *start++;
        if (c == '\"' || c=='\\' || c=='\r')
            g_string_append_c(out, '\\');
        g_string_append_c(out, c);
    }
    if (do_quotes)
        g_string_append_c(out, '"');
}

/* incrementing possibility for the word type */
enum _phrase_word_t {
    WORD_ATOM,
    WORD_QSTRING,
    WORD_2047
};

struct _phrase_word {
    const unsigned char *start, *end;
    enum _phrase_word_t type;
    int encoding;
};

static gboolean
word_types_compatable (enum _phrase_word_t type1, enum _phrase_word_t type2)
{
    switch (type1) {
    case WORD_ATOM:
        return type2 == WORD_QSTRING;
    case WORD_QSTRING:
        return type2 != WORD_2047;
    case WORD_2047:
        return type2 == WORD_2047;
    default:
        return FALSE;
    }
}

/* split the input into words with info about each word
 * merge common word types clean up */
static GList *
header_encode_phrase_get_words (const unsigned char *in)
{
    const unsigned char *inptr = in, *start, *last;
    struct _phrase_word *word;
    enum _phrase_word_t type;
    int encoding, count = 0;
    GList *words = NULL;
    
    /* break the input into words */
    type = WORD_ATOM;
    last = inptr;
    start = inptr;
    encoding = 0;
    while (inptr && *inptr) {
        gunichar c;
        const char *newinptr;
        
        newinptr = g_utf8_next_char (inptr);
        c = g_utf8_get_char (inptr);
        
        if (!g_unichar_validate (c)) {
            w(g_warning ("Invalid UTF-8 sequence encountered (pos %d, char '%c'): %s",
                     (inptr - in), inptr[0], in));
            inptr++;
            continue;
        }
        
        inptr = newinptr;
        if (g_unichar_isspace (c)) {
            if (count > 0) {
                word = g_new0 (struct _phrase_word, 1);
                word->start = start;
                word->end = last;
                word->type = type;
                word->encoding = encoding;
                words = g_list_append (words, word);
                count = 0;
            }
            
            start = inptr;
            type = WORD_ATOM;
            encoding = 0;
        } else {
            count++;
            if (c < 128) {
                if (!is_atom (c))
                    type = MAX (type, WORD_QSTRING);
            } else if (c > 127 && c < 256) {
                type = WORD_2047;
                encoding = MAX (encoding, 1);
            } else if (c >= 256) {
                type = WORD_2047;
                encoding = MAX (encoding, 2);
            }
        }
        
        last = inptr;
    }
    
    if (count > 0) {
        word = g_new0 (struct _phrase_word, 1);
        word->start = start;
        word->end = last;
        word->type = type;
        word->encoding = encoding;
        words = g_list_append (words, word);
    }
    
    return words;
}

static gboolean
header_encode_phrase_merge_words (GList **wordsp)
{
    GList *wordl, *nextl, *words = *wordsp;
    struct _phrase_word *word, *next;
    gboolean merged = FALSE;
    
    /* scan the list, checking for words of similar types that can be merged */
    wordl = words;
    while (wordl) {
        word = wordl->data;
        nextl = g_list_next (wordl);
        
        while (nextl) {
            next = nextl->data;
            /* merge nodes of the same type AND we are not creating too long a string */
            if (word_types_compatable (word->type, next->type)) {
                if (next->end - word->start < CAMEL_FOLD_PREENCODED) {
                    /* the resulting word type is the MAX of the 2 types */
                    word->type = MAX(word->type, next->type);
                    
                    word->end = next->end;
                    words = g_list_remove_link (words, nextl);
                    g_free (next);
                    nextl = g_list_next (wordl);
                    
                    merged = TRUE;
                } else {
                    /* if it is going to be too long, make sure we include the
                       separating whitespace */
                    word->end = next->start;
                    break;
                }
            } else {
                break;
            }
        }
        
        wordl = g_list_next (wordl);
    }
    
    *wordsp = words;
    
    return merged;
}

/* encodes a phrase sequence (different quoting/encoding rules to strings) */
char *
header_encode_phrase (const unsigned char *in)
{
    struct _phrase_word *word = NULL, *last_word = NULL;
    GList *words, *wordl;
    GString *out;
    char *outstr;
    
    if (in == NULL)
        return NULL;
    
    words = header_encode_phrase_get_words (in);
    if (!words)
        return NULL;
    
    while (header_encode_phrase_merge_words (&words));
    
    out = g_string_new ("");
    
    /* output words now with spaces between them */
    wordl = words;
    while (wordl) {
        const char *start;
        int len;
        
        word = wordl->data;
        
        /* append correct number of spaces between words */
        if (last_word && !(last_word->type == WORD_2047 && word->type == WORD_2047)) {
            /* one or both of the words are not encoded so we write the spaces out untouched */
            len = word->start - last_word->end;
            out = g_string_append_len (out, last_word->end, len);
        }
        
        switch (word->type) {
        case WORD_ATOM:
            out = g_string_append_len (out, word->start, word->end - word->start);
            break;
        case WORD_QSTRING:
            quote_word (out, TRUE, word->start, word->end - word->start);
            break;
        case WORD_2047:
            if (last_word && last_word->type == WORD_2047) {
                /* include the whitespace chars between these 2 words in the
                                   resulting rfc2047 encoded word. */
                len = word->end - last_word->end;
                start = last_word->end;
                
                /* encoded words need to be separated by linear whitespace */
                g_string_append_c (out, ' ');
            } else {
                len = word->end - word->start;
                start = word->start;
            }
            
            if (word->encoding == 1)
                rfc2047_encode_word (out, start, len, "ISO-8859-1", IS_PSAFE);
            else
                rfc2047_encode_word (out, start, len,
                             camel_charset_best (start, len), IS_PSAFE);
            break;
        }
        
        g_free (last_word);
        wordl = g_list_next (wordl);
        
        last_word = word;
    }
    
    /* and we no longer need the list */
    g_free (word);
    g_list_free (words);
    
    outstr = out->str;
    g_string_free (out, FALSE);
    
    return outstr;
}


/* these are all internal parser functions */

static char *
decode_token (const char **in)
{
    const char *inptr = *in;
    const char *start;
    
    header_decode_lwsp (&inptr);
    start = inptr;
    while (is_ttoken (*inptr))
        inptr++;
    if (inptr > start) {
        *in = inptr;
        return g_strndup (start, inptr - start);
    } else {
        return NULL;
    }
}

char *
header_token_decode(const char *in)
{
    if (in == NULL)
        return NULL;

    return decode_token(&in);
}

/*
   <"> * ( <any char except <"> \, cr  /  \ <any char> ) <">
*/
static char *
header_decode_quoted_string(const char **in)
{
    const char *inptr = *in;
    char *out = NULL, *outptr;
    int outlen;
    int c;

    header_decode_lwsp(&inptr);
    if (*inptr == '"') {
        const char *intmp;
        int skip = 0;

        /* first, calc length */
        inptr++;
        intmp = inptr;
        while ( (c = *intmp++) && c!= '"') {
            if (c=='\\' && *intmp) {
                intmp++;
                skip++;
            }
        }
        outlen = intmp-inptr-skip;
        out = outptr = g_malloc(outlen+1);
        while ( (c = *inptr++) && c!= '"') {
            if (c=='\\' && *inptr) {
                c = *inptr++;
            }
            *outptr++ = c;
        }
        *outptr = '\0';
    }
    *in = inptr;
    return out;
}

static char *
header_decode_atom(const char **in)
{
    const char *inptr = *in, *start;

    header_decode_lwsp(&inptr);
    start = inptr;
    while (is_atom(*inptr))
        inptr++;
    *in = inptr;
    if (inptr > start)
        return g_strndup(start, inptr-start);
    else
        return NULL;
}

static char *
header_decode_word(const char **in)
{
    const char *inptr = *in;

    header_decode_lwsp(&inptr);
    if (*inptr == '"') {
        *in = inptr;
        return header_decode_quoted_string(in);
    } else {
        *in = inptr;
        return header_decode_atom(in);
    }
}

static char *
header_decode_value(const char **in)
{
    const char *inptr = *in;

    header_decode_lwsp(&inptr);
    if (*inptr == '"') {
        d(printf("decoding quoted string\n"));
        return header_decode_quoted_string(in);
    } else if (is_ttoken(*inptr)) {
        d(printf("decoding token\n"));
        /* this may not have the right specials for all params? */
        return decode_token(in);
    }
    return NULL;
}

/* shoudl this return -1 for no int? */
static int
header_decode_int(const char **in)
{
    const char *inptr = *in;
    int c, v=0;

    header_decode_lwsp(&inptr);
    while ( (c=*inptr++ & 0xff)
        && isdigit(c) ) {
        v = v*10+(c-'0');
    }
    *in = inptr-1;
    return v;
}

#define HEXVAL(c) (isdigit (c) ? (c) - '0' : tolower (c) - 'a' + 10)

static char *
hex_decode (const char *in, int len)
{
    const guchar *inend = (const guchar *) in + len;
    guchar *inptr, *outptr;
    char *outbuf;
    
    outptr = outbuf = g_malloc (len);
    
    inptr = (guchar *) in;
    while (inptr < inend) {
        if (*inptr == '%') {
            if (isxdigit (inptr[1]) && isxdigit (inptr[2])) {
                *outptr++ = HEXVAL (inptr[1]) * 16 + HEXVAL (inptr[2]);
                inptr += 3;
            } else
                *outptr++ = *inptr++;
        } else
            *outptr++ = *inptr++;
    }
    
    *outptr = '\0';
    
    return outbuf;
}

/* an rfc2184 encoded string looks something like:
 * us-ascii'en'This%20is%20even%20more%20
 */

static char *
rfc2184_decode (const char *in, int len)
{
    const char *inptr = in;
    const char *inend = in + len;
    const char *charset;
    char *decoded = NULL;
    char *encoding;
    
    inptr = memchr (inptr, '\'', len);
    if (!inptr)
        return NULL;
    
    encoding = g_strndup (in, inptr - in);
    charset = camel_charset_to_iconv (encoding);
    g_free (encoding);
    
    inptr = memchr (inptr + 1, '\'', inend - inptr - 1);
    if (!inptr)
        return NULL;
    
    inptr++;
    if (inptr < inend) {
        char *decword, *outbase, *outbuf;
        const char *inbuf;
        int inlen, outlen;
        iconv_t ic;
        
        inbuf = decword = hex_decode (inptr, inend - inptr);
        inlen = strlen (inbuf);
        
        ic = iconv_open ("UTF-8", charset);
        if (ic != (iconv_t) -1) {
            int ret;
            
            outlen = inlen * 6 + 16;
            outbuf = outbase = g_malloc (outlen);
            
            ret = iconv (ic, &inbuf, &inlen, &outbuf, &outlen);
            if (ret >= 0) {
                iconv (ic, NULL, 0, &outbuf, &outlen);
                *outbuf = '\0';
                g_free (decoded);
                decoded = outbase;
            }
            
            iconv_close (ic);
        } else {
            decoded = decword;
        }
    }
    
    return decoded;
}

/* This function is basically the same as decode_token()
 * except that it will not accept *'s which have a special
 * meaning for rfc2184 params */
static char *
decode_param_token (const char **in)
{
    const char *inptr = *in;
    const char *start;
    
    header_decode_lwsp (&inptr);
    start = inptr;
    while (is_ttoken (*inptr) && *inptr != '*')
        inptr++;
    if (inptr > start) {
        *in = inptr;
        return g_strndup (start, inptr-start);
    } else {
        return NULL;
    }
}

static gboolean
header_decode_rfc2184_param (const char **in, char **paramp, int *part, gboolean *value_is_encoded)
{
    gboolean is_rfc2184 = FALSE;
    const char *inptr = *in;
    char *param;
    
    *value_is_encoded = FALSE;
    *part = -1;
    
    param = decode_param_token (&inptr);
    header_decode_lwsp (&inptr);
    
    if (*inptr == '*') {
        is_rfc2184 = TRUE;
        inptr++;
        header_decode_lwsp (&inptr);
        if (*inptr == '=') {
            /* form := param*=value */
            if (value_is_encoded)
                *value_is_encoded = TRUE;
        } else {
            /* form := param*#=value or param*#*=value */
            *part = header_decode_int (&inptr);
            header_decode_lwsp (&inptr);
            if (*inptr == '*') {
                /* form := param*#*=value */
                if (value_is_encoded)
                    *value_is_encoded = TRUE;
                inptr++;
                header_decode_lwsp (&inptr);
            }
        }
    }
    
    if (paramp)
        *paramp = param;
    
    if (param)
        *in = inptr;
    
    return is_rfc2184;
}

static int
header_decode_param (const char **in, char **paramp, char **valuep, int *is_rfc2184_param)
{
    gboolean is_rfc2184_encoded = FALSE;
    gboolean is_rfc2184 = FALSE;
    const char *inptr = *in;
    char *param, *value = NULL;
    int rfc2184_part = -1;
    
    *is_rfc2184_param = FALSE;
    
    is_rfc2184 = header_decode_rfc2184_param (&inptr, &param, &rfc2184_part,
                          &is_rfc2184_encoded);
    
    if (*inptr == '=') {
        inptr++;
        value = header_decode_value (&inptr);
        if (is_rfc2184) {
            /* We have ourselves an rfc2184 parameter */
            
            if (rfc2184_part == -1) {
                /* rfc2184 allows the value to be broken into
                 * multiple parts - this isn't one of them so
                 * it is safe to decode it.
                 */
                char *val;
                
                val = rfc2184_decode (value, strlen (value));
                if (val) {
                    g_free (value);
                    value = val;
                }
            } else {
                /* Since we are expecting to find the rest of
                 * this paramter value later, let our caller know.
                 */
                *is_rfc2184_param = TRUE;
            }
        } else if (value && !strcmp (value, "=?")) {
            /* We have a broken param value that is rfc2047 encoded.
             * Since both Outlook and Netscape/Mozilla do this, we
             * should handle this case.
             */
            char *val;
            
            val = rfc2047_decode_word (value, strlen (value));
            if (val) {
                g_free (value);
                value = val;
            }
        }
    }
    
    if (value && !g_utf8_validate (value, -1, NULL)) {
        /* The (broken) mailer sent us an unencoded 8bit value
         * attempt to save it by assuming it's in the user's
         * locale and converting to utf8 */
        char *outbase, *outbuf, *p;
        const char *charset, *inbuf;
        int inlen, outlen;
        iconv_t ic;
        
        inbuf = value;
        inlen = strlen (inbuf);
        
        charset = camel_charset_locale_name ();
        ic = iconv_open ("UTF-8", charset ? charset : "ISO-8859-1");
        if (ic != (iconv_t) -1) {
            int ret;
            
            outlen = inlen * 6 + 16;
            outbuf = outbase = g_malloc (outlen);
            
            ret = iconv (ic, &inbuf, &inlen, &outbuf, &outlen);
            if (ret >= 0) {
                iconv (ic, NULL, 0, &outbuf, &outlen);
                *outbuf = '\0';
            }
            
            iconv_close (ic);
            
            g_free (value);
            value = outbase;
        } else {
            /* Okay, so now what? I guess we convert invalid chars to _'s? */
            for (p = value; *p; p++)
                if (!isascii ((unsigned) *p))
                    *p = '_';
        }
    }
    
    if (param && value) {
        *paramp = param;
        *valuep = value;
        *in = inptr;
        return 0;
    } else {
        g_free (param);
        g_free (value);
        return 1;
    }
}

char *
header_param (struct _header_param *p, const char *name)
{
    while (p && g_strcasecmp (p->name, name) != 0)
        p = p->next;
    if (p)
        return p->value;
    return NULL;
}

struct _header_param *
header_set_param (struct _header_param **l, const char *name, const char *value)
{
    struct _header_param *p = (struct _header_param *)l, *pn;

    while (p->next) {
        pn = p->next;
        if (!g_strcasecmp (pn->name, name)) {
            g_free (pn->value);
            if (value) {
                pn->value = g_strdup (value);
                return pn;
            } else {
                p->next = pn->next;
                g_free (pn->name);
                g_free (pn);
                return NULL;
            }
        }
        p = pn;
    }

    if (value == NULL)
        return NULL;

    pn = g_malloc (sizeof (*pn));
    pn->next = 0;
    pn->name = g_strdup (name);
    pn->value = g_strdup (value);
    p->next = pn;

    return pn;
}

const char *
header_content_type_param (struct _header_content_type *t, const char *name)
{
    if (t==NULL)
        return NULL;
    return header_param (t->params, name);
}

void
header_content_type_set_param (struct _header_content_type *t, const char *name, const char *value)
{
    header_set_param (&t->params, name, value);
}

/**
 * header_content_type_is:
 * @ct: A content type specifier, or #NULL.
 * @type: A type to check against.
 * @subtype: A subtype to check against, or "*" to match any subtype.
 * 
 * Returns #TRUE if the content type @ct is of type @type/@subtype.
 * The subtype of "*" will match any subtype.  If @ct is #NULL, then
 * it will match the type "text/plain".
 * 
 * Return value: #TRUE or #FALSE depending on the matching of the type.
 **/
int
header_content_type_is(struct _header_content_type *ct, const char *type, const char *subtype)
{
    /* no type == text/plain or text/"*" */
    if (ct==NULL || (ct->type == NULL && ct->subtype == NULL)) {
        return (!strcasecmp(type, "text")
            && (!strcasecmp(subtype, "plain")
                || !strcasecmp(subtype, "*")));
    }

    return (ct->type != NULL
        && (!strcasecmp(ct->type, type)
            && ((ct->subtype != NULL
             && !strcasecmp(ct->subtype, subtype))
            || !strcasecmp("*", subtype))));
}

void
header_param_list_free(struct _header_param *p)
{
    struct _header_param *n;

    while (p) {
        n = p->next;
        g_free(p->name);
        g_free(p->value);
        g_free(p);
        p = n;
    }
}

struct _header_content_type *
header_content_type_new(const char *type, const char *subtype)
{
    struct _header_content_type *t = g_malloc(sizeof(*t));

    t->type = g_strdup(type);
    t->subtype = g_strdup(subtype);
    t->params = NULL;
    t->refcount = 1;
    return t;
}

void
header_content_type_ref(struct _header_content_type *ct)
{
    if (ct)
        ct->refcount++;
}


void
header_content_type_unref(struct _header_content_type *ct)
{
    if (ct) {
        if (ct->refcount <= 1) {
            header_param_list_free(ct->params);
            g_free(ct->type);
            g_free(ct->subtype);
            g_free(ct);
        } else {
            ct->refcount--;
        }
    }
}

/* for decoding email addresses, canonically */
static char *
header_decode_domain(const char **in)
{
    const char *inptr = *in, *start;
    int go = TRUE;
    char *ret;
    GString *domain = g_string_new("");

                /* domain ref | domain literal */
    header_decode_lwsp(&inptr);
    while (go) {
        if (*inptr == '[') { /* domain literal */
            domain = g_string_append(domain, "[ ");
            inptr++;
            header_decode_lwsp(&inptr);
            start = inptr;
            while (is_dtext(*inptr)) {
                domain = g_string_append_c(domain, *inptr);
                inptr++;
            }
            if (*inptr == ']') {
                domain = g_string_append(domain, " ]");
                inptr++;
            } else {
                w(g_warning("closing ']' not found in domain: %s", *in));
            }
        } else {
            char *a = header_decode_atom(&inptr);
            if (a) {
                domain = g_string_append(domain, a);
                g_free(a);
            } else {
                w(g_warning("missing atom from domain-ref"));
                break;
            }
        }
        header_decode_lwsp(&inptr);
        if (*inptr == '.') { /* next sub-domain? */
            domain = g_string_append_c(domain, '.');
            inptr++;
            header_decode_lwsp(&inptr);
        } else
            go = FALSE;
    }

    *in = inptr;

    ret = domain->str;
    g_string_free(domain, FALSE);
    return ret;
}

static char *
header_decode_addrspec(const char **in)
{
    const char *inptr = *in;
    char *word;
    GString *addr = g_string_new("");

    header_decode_lwsp(&inptr);

    /* addr-spec */
    word = header_decode_word(&inptr);
    if (word) {
        addr = g_string_append(addr, word);
        header_decode_lwsp(&inptr);
        g_free(word);
        while (*inptr == '.' && word) {
            inptr++;
            addr = g_string_append_c(addr, '.');
            word = header_decode_word(&inptr);
            if (word) {
                addr = g_string_append(addr, word);
                header_decode_lwsp(&inptr);
                g_free(word);
            } else {
                w(g_warning("Invalid address spec: %s", *in));
            }
        }
        if (*inptr == '@') {
            inptr++;
            addr = g_string_append_c(addr, '@');
            word = header_decode_domain(&inptr);
            if (word) {
                addr = g_string_append(addr, word);
                g_free(word);
            } else {
                w(g_warning("Invalid address, missing domain: %s", *in));
            }
        } else {
            w(g_warning("Invalid addr-spec, missing @: %s", *in));
        }
    } else {
        w(g_warning("invalid addr-spec, no local part"));
    }

    /* FIXME: return null on error? */

    *in = inptr;
    word = addr->str;
    g_string_free(addr, FALSE);
    return word;
}

/*
  address:
   word *('.' word) @ domain |
   *(word) '<' [ *('@' domain ) ':' ] word *( '.' word) @ domain |

   1*word ':' [ word ... etc (mailbox, as above) ] ';'
 */

/* mailbox:
   word *( '.' word ) '@' domain
   *(word) '<' [ *('@' domain ) ':' ] word *( '.' word) @ domain
   */

static struct _header_address *
header_decode_mailbox(const char **in)
{
    const char *inptr = *in;
    char *pre;
    int closeme = FALSE;
    GString *addr;
    GString *name = NULL;
    struct _header_address *address = NULL;
    const char *comment = NULL;

    addr = g_string_new("");

    /* for each address */
    pre = header_decode_word(&inptr);
    header_decode_lwsp(&inptr);
    if (!(*inptr == '.' || *inptr == '@' || *inptr==',' || *inptr=='\0')) {
        /* ',' and '\0' required incase it is a simple address, no @ domain part (buggy writer) */
        name = g_string_new ("");
        while (pre) {
            char *text, *last;

            /* perform internationalised decoding, and append */
            text = header_decode_string (pre, NULL);
            g_string_append (name, text);
            last = pre;
            g_free(text);

            pre = header_decode_word(&inptr);
            if (pre) {
                int l = strlen(last);
                int p = strlen(pre);
                /* dont append ' ' between sucsessive encoded words */
                if ((l>6 && last[l-2] == '?' && last[l-1] == '=')
                    && (p>6 && pre[0] == '=' && pre[1] == '?')) {
                    /* dont append ' ' */
                } else {
                    name = g_string_append_c(name, ' ');
                }
            }
            g_free(last);
        }
        header_decode_lwsp(&inptr);
        if (*inptr == '<') {
            closeme = TRUE;
            inptr++;
            header_decode_lwsp(&inptr);
            if (*inptr == '@') {
                while (*inptr == '@') {
                    inptr++;
                    header_decode_domain(&inptr);
                    header_decode_lwsp(&inptr);
                    if (*inptr == ',') {
                        inptr++;
                        header_decode_lwsp(&inptr);
                    }
                }
                if (*inptr == ':') {
                    inptr++;
                } else {
                    w(g_warning("broken route-address, missing ':': %s", *in));
                }
            }
            pre = header_decode_word(&inptr);
            header_decode_lwsp(&inptr);
        } else {
            w(g_warning("broken address? %s", *in));
        }
    }

    if (pre) {
        addr = g_string_append(addr, pre);
    } else {
        w(g_warning("No local-part for email address: %s", *in));
    }

    /* should be at word '.' localpart */
    while (*inptr == '.' && pre) {
        inptr++;
        g_free(pre);
        pre = header_decode_word(&inptr);
        if (pre) {
            addr = g_string_append_c(addr, '.');
            addr = g_string_append(addr, pre);
        }
        comment = inptr;
        header_decode_lwsp(&inptr);
    }
    g_free(pre);

    /* now at '@' domain part */
    if (*inptr == '@') {
        char *dom;

        inptr++;
        addr = g_string_append_c(addr, '@');
        comment = inptr;
        dom = header_decode_domain(&inptr);
        addr = g_string_append(addr, dom);
        g_free(dom);
    } else {
        w(g_warning("invalid address, no '@' domain part at %c: %s", *inptr, *in));
    }

    if (closeme) {
        header_decode_lwsp(&inptr);
        if (*inptr == '>') {
            inptr++;
        } else {
            w(g_warning("invalid route address, no closing '>': %s", *in));
        } 
    } else if (name == NULL && comment != NULL && inptr>comment) { /* check for comment after address */
        char *text, *tmp;
        const char *comstart, *comend;

        /* this is a bit messy, we go from the last known position, because
           decode_domain/etc skip over any comments on the way */
        /* FIXME: This wont detect comments inside the domain itself,
           but nobody seems to use that feature anyway ... */

        d(printf("checking for comment from '%s'\n", comment));

        comstart = strchr(comment, '(');
        if (comstart) {
            comstart++;
            header_decode_lwsp(&inptr);
            comend = inptr-1;
            while (comend > comstart && comend[0] != ')')
                comend--;
            
            if (comend > comstart) {
                d(printf("  looking at subset '%.*s'\n", comend-comstart, comstart));
                tmp = g_strndup (comstart, comend-comstart);
                text = header_decode_string (tmp, NULL);
                name = g_string_new (text);
                g_free (tmp);
                g_free (text);
            }
        }
    }
    
    *in = inptr;
    
    if (addr->len > 0) {
        address = header_address_new_name(name ? name->str : "", addr->str);
    }

    g_string_free(addr, TRUE);
    if (name)
        g_string_free(name, TRUE);

    d(printf("got mailbox: %s\n", addr->str));
    return address;
}

static struct _header_address *
header_decode_address(const char **in)
{
    const char *inptr = *in;
    char *pre;
    GString *group = g_string_new("");
    struct _header_address *addr = NULL, *member;

    /* pre-scan, trying to work out format, discard results */
    header_decode_lwsp(&inptr);
    while ( (pre = header_decode_word(&inptr)) ) {
        group = g_string_append(group, pre);
        group = g_string_append(group, " ");
        g_free(pre);
    }
    header_decode_lwsp(&inptr);
    if (*inptr == ':') {
        d(printf("group detected: %s\n", group->str));
        addr = header_address_new_group(group->str);
        /* that was a group spec, scan mailbox's */
        inptr++;
        /* FIXME: check rfc 2047 encodings of words, here or above in the loop */
        header_decode_lwsp(&inptr);
        if (*inptr != ';') {
            int go = TRUE;
            do {
                member = header_decode_mailbox(&inptr);
                if (member)
                    header_address_add_member(addr, member);
                header_decode_lwsp(&inptr);
                if (*inptr == ',')
                    inptr++;
                else
                    go = FALSE;
            } while (go);
            if (*inptr == ';') {
                inptr++;
            } else {
                w(g_warning("Invalid group spec, missing closing ';': %s", *in));
            }
        } else {
            inptr++;
        }
        *in = inptr;
    } else {
        addr = header_decode_mailbox(in);
    }

    g_string_free(group, TRUE);

    return addr;
}

static char *
header_msgid_decode_internal(const char **in)
{
    const char *inptr = *in;
    char *msgid = NULL;

    d(printf("decoding Message-ID: '%s'\n", *in));

    header_decode_lwsp(&inptr);
    if (*inptr == '<') {
        inptr++;
        header_decode_lwsp(&inptr);
        msgid = header_decode_addrspec(&inptr);
        if (msgid) {
            header_decode_lwsp(&inptr);
            if (*inptr == '>') {
                inptr++;
            } else {
                w(g_warning("Missing closing '>' on message id: %s", *in));
            }
        } else {
            w(g_warning("Cannot find message id in: %s", *in));
        }
    } else {
        w(g_warning("missing opening '<' on message id: %s", *in));
    }
    *in = inptr;

    return msgid;
}

char *
header_msgid_decode(const char *in)
{
    if (in == NULL)
        return NULL;

    return header_msgid_decode_internal(&in);
}

void
header_references_list_append_asis(struct _header_references **list, char *ref)
{
    struct _header_references *w = (struct _header_references *)list, *n;
    while (w->next)
        w = w->next;
    n = g_malloc(sizeof(*n));
    n->id = ref;
    n->next = 0;
    w->next = n;
}

int
header_references_list_size(struct _header_references **list)
{
    int count = 0;
    struct _header_references *w = *list;
    while (w) {
        count++;
        w = w->next;
    }
    return count;
}

void
header_references_list_clear(struct _header_references **list)
{
    struct _header_references *w = *list, *n;
    while (w) {
        n = w->next;
        g_free(w->id);
        g_free(w);
        w = n;
    }
    *list = NULL;
}

/* generate a list of references, from most recent up */
struct _header_references *
header_references_decode(const char *in)
{
    const char *inptr = in;
    struct _header_references *head = NULL, *node;
    char *id, *word;

    if (in == NULL || in[0] == '\0')
        return NULL;

    while (*inptr) {
        header_decode_lwsp(&inptr);
        if (*inptr == '<') {
            id = header_msgid_decode_internal(&inptr);
            if (id) {
                node = g_malloc(sizeof(*node));
                node->next = head;
                head = node;
                node->id = id;
            }
        } else {
            word = header_decode_word(&inptr);
            if (word)
                g_free (word);
            else if (*inptr != '\0')
                inptr++; /* Stupid mailer tricks */
        }
    }

    return head;
}

struct _header_references *
header_references_dup(const struct _header_references *list)
{
    struct _header_references *new = NULL, *tmp;

    while (list) {
        tmp = g_new(struct _header_references, 1);
        tmp->next = new;
        tmp->id = g_strdup(list->id);
        new = tmp;
        list = list->next;
    }
    return new;
}

struct _header_address *
header_mailbox_decode(const char *in)
{
    if (in == NULL)
        return NULL;

    return header_decode_mailbox(&in);
}

struct _header_address *
header_address_decode(const char *in)
{
    const char *inptr = in, *last;
    struct _header_address *list = NULL, *addr;

    d(printf("decoding To: '%s'\n", in));

    if (in == NULL)
        return NULL;

    do {
        last = inptr;
        addr = header_decode_address(&inptr);
        if (addr)
            header_address_list_append(&list, addr);
        header_decode_lwsp(&inptr);
        if (*inptr == ',')
            inptr++;
        else
            break;
    } while (inptr != last);

    if (*inptr) {
        w(g_warning("Invalid input detected at %c (%d): %s\n or at: %s", *inptr, inptr-in, in, inptr));
    }

    if (inptr == last) {
        w(g_warning("detected invalid input loop at : %s", last));
    }

    return list;
}

void
header_mime_decode(const char *in, int *maj, int *min)
{
    const char *inptr = in;
    int major=-1, minor=-1;

    d(printf("decoding MIME-Version: '%s'\n", in));

    if (in != NULL) {
        header_decode_lwsp(&inptr);
        if (isdigit(*inptr)) {
            major = header_decode_int(&inptr);
            header_decode_lwsp(&inptr);
            if (*inptr == '.') {
                inptr++;
                header_decode_lwsp(&inptr);
                if (isdigit(*inptr))
                    minor = header_decode_int(&inptr);
            }
        }
    }

    if (maj)
        *maj = major;
    if (min)
        *min = minor;

    d(printf("major = %d, minor = %d\n", major, minor));
}

static struct _header_param *
header_decode_param_list(const char **in)
{
    const char *inptr = *in;
    struct _header_param *head = NULL, *tail = NULL;
    gboolean last_was_rfc2184 = FALSE;
    gboolean is_rfc2184 = FALSE;
    
    header_decode_lwsp (&inptr);
    
    while (*inptr == ';') {
        struct _header_param *param;
        char *name, *value;
        
        inptr++;
        /* invalid format? */
        if (header_decode_param (&inptr, &name, &value, &is_rfc2184) != 0)
            break;
        
        if (is_rfc2184 && tail && !g_strcasecmp (name, tail->name)) {
            /* rfc2184 allows a parameter to be broken into multiple parts
             * and it looks like we've found one. Append this value to the
             * last value.
             */
            GString *gvalue;
            
            gvalue = g_string_new (tail->value);
            g_string_append (gvalue, value);
            g_free (tail->value);
            g_free (value);
            g_free (name);
            
            tail->value = gvalue->str;
            g_string_free (gvalue, FALSE);
        } else {
            if (last_was_rfc2184) {
                /* We've finished gathering the values for the last param
                 * so it is now safe to decode it.
                 */
                char *val;
                
                val = rfc2184_decode (tail->value, strlen (tail->value));
                if (val) {
                    g_free (tail->value);
                    tail->value = val;
                }
            }
            
            param = g_malloc (sizeof (struct _header_param));
            param->name = name;
            param->value = value;
            param->next = NULL;
            if (head == NULL)
                head = param;
            if (tail)
                tail->next = param;
            tail = param;
        }
        
        last_was_rfc2184 = is_rfc2184;
        
        header_decode_lwsp (&inptr);
    }
    
    if (last_was_rfc2184) {
        /* We've finished gathering the values for the last param
         * so it is now safe to decode it.
         */
        char *val;
        
        val = rfc2184_decode (tail->value, strlen (tail->value));
        if (val) {
            g_free (tail->value);
            tail->value = val;
        }
    }
    
    *in = inptr;
    
    return head;
}

struct _header_param *
header_param_list_decode(const char *in)
{
    if (in == NULL)
        return NULL;

    return header_decode_param_list(&in);
}

/* FIXME: I wrote this in a quick & dirty fasion - it may not be 100% correct */
static char *
header_encode_param (const unsigned char *in, gboolean *encoded)
{
    const unsigned char *inptr = in;
    char *outstr, *charset;
    int encoding;
    GString *out;
    
    *encoded = FALSE;
    
    g_return_val_if_fail (in != NULL, NULL);
    g_return_val_if_fail (g_utf8_validate (in, -1, NULL), NULL);
    
    /* do a quick us-ascii check (the common case?) */
    while (*inptr) {
        if (*inptr > 127)
            break;
        inptr++;
    }
    
    if (*inptr == '\0')
        return g_strdup (in);
    
    out = g_string_new ("");
    inptr = in;
    encoding = 0;
    while (inptr && *inptr) {
        gunichar c;
        const char *newinptr;
        
        newinptr = g_utf8_next_char (inptr);
        c = g_utf8_get_char (inptr);
        if (newinptr == NULL || !g_unichar_validate (c)) {
            w(g_warning ("Invalid UTF-8 sequence encountered (pos %d, char '%c'): %s",
                     (inptr-in), inptr[0], in));
            inptr++;
            continue;
        }
        
        if (c > 127 && c < 256) {
            encoding = MAX (encoding, 1);
            g_string_sprintfa (out, "%%%c%c", tohex[(c >> 4) & 0xf], tohex[c & 0xf]);
        } else if (c >= 256) {
            encoding = MAX (encoding, 2);
            g_string_sprintfa (out, "%%%c%c", tohex[(c >> 4) & 0xf], tohex[c & 0xf]);
        } else if (is_lwsp (c) || camel_mime_special_table[c] & IS_ESAFE) {
            g_string_sprintfa (out, "%%%c%c", tohex[(c >> 4) & 0xf], tohex[c & 0xf]);
        } else {
            g_string_append_c (out, c);
        }
        
        inptr = newinptr;
    }
    
    switch (encoding) {
    default:
        g_string_prepend (out, "iso-8859-1''");
        break;
    case 2:
        charset = g_strdup_printf ("%s''", camel_charset_best (in, inptr - in));
        g_string_prepend (out, charset);
        g_free (charset);
        break;
    }
    
    outstr = out->str;
    g_string_free (out, FALSE);
    *encoded = TRUE;
    
    return outstr;
}

void
header_param_list_format_append (GString *out, struct _header_param *p)
{
    int used = out->len;
    
    while (p) {
        gboolean encoded = FALSE;
        gboolean quote = FALSE;
        int here = out->len;
        int nlen, vlen;
        char *value;
        
        if (!p->value) {
            p = p->next;
            continue;
        }
        
        value = header_encode_param (p->value, &encoded);
        if (!value) {
            g_warning ("appending parameter %s=%s violates rfc2184", p->name, p->value);
            value = g_strdup (p->value);
        }
        
        if (!encoded) {
            char *ch;
            
            for (ch = value; *ch; ch++) {
                if (is_tspecial (*ch) || is_lwsp (*ch))
                    break;
            }
            
            quote = ch && *ch;
        }
        
        nlen = strlen (p->name);
        vlen = strlen (value);
        
        if (used + nlen + vlen > CAMEL_FOLD_SIZE - 8) {
            out = g_string_append (out, ";\n\t");
            here = out->len;
            used = 0;
        } else
            out = g_string_append (out, "; ");
        
        if (nlen + vlen > CAMEL_FOLD_SIZE - 8) {
            /* we need to do special rfc2184 parameter wrapping */
            int maxlen = CAMEL_FOLD_SIZE - (nlen + 8);
            char *inptr, *inend;
            int i = 0;
            
            inptr = value;
            inend = value + vlen;
            
            while (inptr < inend) {
                char *ptr = inptr + MIN (inend - inptr, maxlen);
                
                if (encoded && ptr < inend) {
                    /* be careful not to break an encoded char (ie %20) */
                    char *q = ptr;
                    int j = 2;
                    
                    for ( ; j > 0 && q > inptr && *q != '%'; j--, q--);
                    if (*q == '%')
                        ptr = q;
                }
                
                if (i != 0) {
                    g_string_append (out, ";\n\t");
                    here = out->len;
                    used = 0;
                }
                
                g_string_sprintfa (out, "%s*%d%s=", p->name, i++, encoded ? "*" : "");
                if (encoded || !quote)
                    g_string_append_len (out, inptr, ptr - inptr);
                else
                    quote_word (out, TRUE, inptr, ptr - inptr);
                
                printf ("wrote: %s\n", out->str + here);
                
                used += (out->len - here);
                
                inptr = ptr;
            }
        } else {
            g_string_sprintfa (out, "%s%s=", p->name, encoded ? "*" : "");
            
            if (encoded || !quote)
                g_string_append (out, value);
            else
                quote_word (out, TRUE, value, vlen);
            
            used += (out->len - here);
        }
        
        g_free (value);
        
        p = p->next;
    }
}

char *
header_param_list_format(struct _header_param *p)
{
    GString *out = g_string_new("");
    char *ret;

    header_param_list_format_append(out, p);
    ret = out->str;
    g_string_free(out, FALSE);
    return ret;
}

struct _header_content_type *
header_content_type_decode(const char *in)
{
    const char *inptr = in;
    char *type, *subtype = NULL;
    struct _header_content_type *t = NULL;

    if (in==NULL)
        return NULL;

    type = decode_token(&inptr);
    header_decode_lwsp(&inptr);
    if (type) {
        if  (*inptr == '/') {
            inptr++;
            subtype = decode_token(&inptr);
        }
        if (subtype == NULL && (!strcasecmp(type, "text"))) {
            w(g_warning("text type with no subtype, resorting to text/plain: %s", in));
            subtype = g_strdup("plain");
        }
        if (subtype == NULL) {
            w(g_warning("MIME type with no subtype: %s", in));
        }

        t = header_content_type_new(type, subtype);
        t->params = header_decode_param_list(&inptr);
        g_free(type);
        g_free(subtype);
    } else {
        g_free(type);
        d(printf("cannot find MIME type in header (2) '%s'", in));
    }
    return t;
}

void
header_content_type_dump(struct _header_content_type *ct)
{
    struct _header_param *p;

    printf("Content-Type: ");
    if (ct==NULL) {
        printf("<NULL>\n");
        return;
    }
    printf("%s / %s", ct->type, ct->subtype);
    p = ct->params;
    if (p) {
        while (p) {
            printf(";\n\t%s=\"%s\"", p->name, p->value);
            p = p->next;
        }
    }
    printf("\n");
}

char *
header_content_type_format(struct _header_content_type *ct)
{
    GString *out;
    char *ret;

    if (ct==NULL)
        return NULL;

    out = g_string_new("");
    if (ct->type == NULL) {
        g_string_sprintfa(out, "text/plain");
        w(g_warning("Content-Type with no main type"));
    } else if (ct->subtype == NULL) {
        w(g_warning("Content-Type with no sub type: %s", ct->type));
        if (!strcasecmp(ct->type, "multipart"))
            g_string_sprintfa(out, "%s/mixed", ct->type);
        else
            g_string_sprintfa(out, "%s", ct->type);
    } else {
        g_string_sprintfa(out, "%s/%s", ct->type, ct->subtype);
    }
    header_param_list_format_append(out, ct->params);

    ret = out->str;
    g_string_free(out, FALSE);
    return ret;
}

char *
header_content_type_simple(struct _header_content_type *ct)
{
    return g_strdup_printf("%s/%s", ct->type, ct->subtype);
}

char *
header_content_encoding_decode(const char *in)
{
    if (in)
        return decode_token(&in);
    return NULL;
}

CamelMimeDisposition *
header_disposition_decode(const char *in)
{
    CamelMimeDisposition *d = NULL;
    const char *inptr = in;

    if (in == NULL)
        return NULL;

    d = g_malloc(sizeof(*d));
    d->refcount = 1;
    d->disposition = decode_token(&inptr);
    if (d->disposition == NULL)
        w(g_warning("Empty disposition type"));
    d->params = header_decode_param_list(&inptr);
    return d;
}

void
header_disposition_ref(CamelMimeDisposition *d)
{
    if (d)
        d->refcount++;
}

void
header_disposition_unref(CamelMimeDisposition *d)
{
    if (d) {
        if (d->refcount<=1) {
            header_param_list_free(d->params);
            g_free(d->disposition);
            g_free(d);
        } else {
            d->refcount--;
        }
    }
}

char *
header_disposition_format(CamelMimeDisposition *d)
{
    GString *out;
    char *ret;

    if (d==NULL)
        return NULL;

    out = g_string_new("");
    if (d->disposition)
        out = g_string_append(out, d->disposition);
    else
        out = g_string_append(out, "attachment");
    header_param_list_format_append(out, d->params);

    ret = out->str;
    g_string_free(out, FALSE);
    return ret;
}

/* hrm, is there a library for this shit? */
static struct {
    char *name;
    int offset;
} tz_offsets [] = {
    { "UT", 0 },
    { "GMT", 0 },
    { "EST", -500 },    /* these are all US timezones.  bloody yanks */
    { "EDT", -400 },
    { "CST", -600 },
    { "CDT", -500 },
    { "MST", -700 },
    { "MDT", -600 },
    { "PST", -800 },
    { "PDT", -700 },
    { "Z", 0 },
    { "A", -100 },
    { "M", -1200 },
    { "N", 100 },
    { "Y", 1200 },
};

static char *tz_months [] = {
    "Jan", "Feb", "Mar", "Apr", "May", "Jun",
    "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};

char *
header_format_date(time_t time, int offset)
{
    struct tm tm;

    d(printf("offset = %d\n", offset));

    d(printf("converting date %s", ctime(&time)));

    time += ((offset / 100) * (60*60)) + (offset % 100)*60;

    d(printf("converting date %s", ctime(&time)));

    memcpy(&tm, gmtime(&time), sizeof(tm));

    return g_strdup_printf("%02d %s %04d %02d:%02d:%02d %+05d",
                   tm.tm_mday, tz_months[tm.tm_mon],
                   tm.tm_year + 1900,
                   tm.tm_hour, tm.tm_min, tm.tm_sec,
                   offset);
}

/* convert a date to time_t representation */
/* this is an awful mess oh well */
time_t
header_decode_date(const char *in, int *saveoffset)
{
    const char *inptr = in;
    char *monthname;
    int year, offset = 0;
    struct tm tm;
    int i;
    time_t t;

    if (in == NULL) {
        if (saveoffset)
            *saveoffset = 0;
        return 0;
    }

    d(printf ("\ndecoding date '%s'\n", inptr));

    memset (&tm, 0, sizeof(tm));

    header_decode_lwsp (&inptr);
    if (!isdigit (*inptr)) {
        char *day = decode_token (&inptr);
        /* we dont really care about the day, it's only for display */
        if (day) {
            d(printf ("got day: %s\n", day));
            g_free (day);
            header_decode_lwsp (&inptr);
            if (*inptr == ',') {
                inptr++;
            } else {
#ifndef CLEAN_DATE
                char *newdate;

                w(g_warning("day not followed by ',' it's probably a broken mail client, so we'll ignore its date entirely"));
                w(printf ("Giving it one last chance...\n"));
                newdate = parse_broken_date (in);
                if (newdate) {
                    w(printf ("Got: %s\n", newdate));
                    t = header_decode_date (newdate, saveoffset);
                    g_free (newdate);
                    return t;
                }
#endif
                if (saveoffset)
                    *saveoffset = 0;
                return 0;
            }
        }
    }
    tm.tm_mday = header_decode_int(&inptr);
    monthname = decode_token(&inptr);
    if (monthname) {
        for (i=0;i<sizeof(tz_months)/sizeof(tz_months[0]);i++) {
            if (!strcasecmp(tz_months[i], monthname)) {
                tm.tm_mon = i;
                break;
            }
        }
        g_free(monthname);
    }
    year = header_decode_int(&inptr);
    if (year < 69 || (year >= 100 && year < 1900)) {
        tm.tm_year = 100 + year;
    } else if (year < 100) {
        tm.tm_year = year;
    } else {
        tm.tm_year = year - 1900;
    }
    /* get the time ... yurck */
    tm.tm_hour = header_decode_int(&inptr);
    header_decode_lwsp(&inptr);
    if (*inptr == ':')
        inptr++;
    tm.tm_min = header_decode_int(&inptr);
    header_decode_lwsp(&inptr);
    if (*inptr == ':')
        inptr++;
    tm.tm_sec = header_decode_int(&inptr);
    header_decode_lwsp(&inptr);
    if (*inptr == '+'
        || *inptr == '-') {
        offset = (*inptr++)=='-'?-1:1;
        offset = offset * header_decode_int(&inptr);
        d(printf("abs signed offset = %d\n", offset));
    } else if (isdigit(*inptr)) {
        offset = header_decode_int(&inptr);
        d(printf("abs offset = %d\n", offset));
    } else {
        char *tz = decode_token(&inptr);

        if (tz) {
            for (i=0;i<sizeof(tz_offsets)/sizeof(tz_offsets[0]);i++) {
                if (!strcasecmp(tz_offsets[i].name, tz)) {
                    offset = tz_offsets[i].offset;
                    break;
                }
            }
            g_free(tz);
        }
        /* some broken mailers seem to put in things like GMT+1030 instead of just +1030 */
        header_decode_lwsp(&inptr);
        if (*inptr == '+' || *inptr == '-') {
            int sign = (*inptr++)=='-'?-1:1;
            offset = offset + (header_decode_int(&inptr)*sign);
        }
        d(printf("named offset = %d\n", offset));
    }

    t = mktime(&tm);
#if defined(HAVE_TIMEZONE)
    t -= timezone;
#elif defined(HAVE_TM_GMTOFF)
    t += tm.tm_gmtoff;
#else
#error Neither HAVE_TIMEZONE nor HAVE_TM_GMTOFF defined. Rerun autoheader, autoconf, etc.
#endif

    /* t is now GMT of the time we want, but not offset by the timezone ... */

    d(printf(" gmt normalized? = %s\n", ctime(&t)));

    /* this should convert the time to the GMT equiv time */
    t -= ( (offset/100) * 60*60) + (offset % 100)*60;

    d(printf(" gmt normalized for timezone? = %s\n", ctime(&t)));

    d({
        char *tmp;
        tmp = header_format_date(t, offset);
        printf(" encoded again: %s\n", tmp);
        g_free(tmp);
    });

    if (saveoffset)
        *saveoffset = offset;

    return t;
}

char *
header_location_decode(const char *in)
{
    const char *p;

    /* Sigh. RFC2557 says:
     *   content-location =   "Content-Location:" [CFWS] URI [CFWS]
     *      where URI is restricted to the syntax for URLs as
     *      defined in Uniform Resource Locators [URL] until
     *      IETF specifies other kinds of URIs.
     *
     * But Netscape puts quotes around the URI when sending web
     * pages.
     */

    header_decode_lwsp(&in);
    if (*in == '"')
        return header_decode_quoted_string(&in);
    else {
        for (p = in; *p && !is_lwsp(*p); p++)
            ;
        return g_strndup(in, p - in);
    }
}


/* extra rfc checks */
#define CHECKS

#ifdef CHECKS
static void
check_header(struct _header_raw *h)
{
    unsigned char *p;

    p = h->value;
    while (p && *p) {
        if (!isascii(*p)) {
            w(g_warning("Appending header violates rfc: %s: %s", h->name, h->value));
            return;
        }
        p++;
    }
}
#endif

void
header_raw_append_parse(struct _header_raw **list, const char *header, int offset)
{
    register const char *in;
    int fieldlen;
    char *name;

    in = header;
    while (is_fieldname(*in) || *in==':')
        in++;
    fieldlen = in-header-1;
    while (is_lwsp(*in))
        in++;
    if (fieldlen == 0 || header[fieldlen] != ':') {
        printf("Invalid header line: '%s'\n", header);
        return;
    }
    name = alloca(fieldlen+1);
    memcpy(name, header, fieldlen);
    name[fieldlen] = 0;

    header_raw_append(list, name, in, offset);
}

void
header_raw_append(struct _header_raw **list, const char *name, const char *value, int offset)
{
    struct _header_raw *l, *n;

    d(printf("Header: %s: %s\n", name, value));

    n = g_malloc(sizeof(*n));
    n->next = NULL;
    n->name = g_strdup(name);
    n->value = g_strdup(value);
    n->offset = offset;
#ifdef CHECKS
    check_header(n);
#endif
    l = (struct _header_raw *)list;
    while (l->next) {
        l = l->next;
    }
    l->next = n;

    /* debug */
#if 0
    if (!strcasecmp(name, "To")) {
        printf("- Decoding To\n");
        header_to_decode(value);
    } else if (!strcasecmp(name, "Content-type")) {
        printf("- Decoding content-type\n");
        header_content_type_dump(header_content_type_decode(value));        
    } else if (!strcasecmp(name, "MIME-Version")) {
        printf("- Decoding mime version\n");
        header_mime_decode(value);
    }
#endif
}

static struct _header_raw *
header_raw_find_node(struct _header_raw **list, const char *name)
{
    struct _header_raw *l;

    l = *list;
    while (l) {
        if (!strcasecmp(l->name, name))
            break;
        l = l->next;
    }
    return l;
}

const char *
header_raw_find(struct _header_raw **list, const char *name, int *offset)
{
    struct _header_raw *l;

    l = header_raw_find_node(list, name);
    if (l) {
        if (offset)
            *offset = l->offset;
        return l->value;
    } else
        return NULL;
}

const char *
header_raw_find_next(struct _header_raw **list, const char *name, int *offset, const char *last)
{
    struct _header_raw *l;

    if (last == NULL || name == NULL)
        return NULL;

    l = *list;
    while (l && l->value != last)
        l = l->next;
    return header_raw_find(&l, name, offset);
}

static void
header_raw_free(struct _header_raw *l)
{
    g_free(l->name);
    g_free(l->value);
    g_free(l);
}

void
header_raw_remove(struct _header_raw **list, const char *name)
{
    struct _header_raw *l, *p;

    /* the next pointer is at the head of the structure, so this is safe */
    p = (struct _header_raw *)list;
    l = *list;
    while (l) {
        if (!strcasecmp(l->name, name)) {
            p->next = l->next;
            header_raw_free(l);
            l = p->next;
        } else {
            p = l;
            l = l->next;
        }
    }
}

void
header_raw_replace(struct _header_raw **list, const char *name, const char *value, int offset)
{
    header_raw_remove(list, name);
    header_raw_append(list, name, value, offset);
}

void
header_raw_clear(struct _header_raw **list)
{
    struct _header_raw *l, *n;
    l = *list;
    while (l) {
        n = l->next;
        header_raw_free(l);
        l = n;
    }
    *list = NULL;
}

char *
header_msgid_generate (void)
{
    char host[MAXHOSTNAMELEN];
#ifdef ENABLE_THREADS
    static pthread_mutex_t count_lock = PTHREAD_MUTEX_INITIALIZER;
#define COUNT_LOCK() pthread_mutex_lock (&count_lock)
#define COUNT_UNLOCK() pthread_mutex_unlock (&count_lock)
#else
#define COUNT_LOCK()
#define COUNT_UNLOCK()
#endif /* ENABLE_THREADS */
    static gint count = 0;
    gint hrv;
    char *ret;
    
    hrv = gethostname (host, sizeof (host));
    
    COUNT_LOCK ();
    ret = g_strdup_printf ("%d.%d.%d.camel@%s", (gint) time (NULL), getpid (), count++,
                   (hrv == 0 && host && *host) ? host : "unknown.host");
    COUNT_UNLOCK ();
    
    return ret;
}


static struct {
    char *name;
    char *pattern;
} mail_list_magic[] = {
    { "Sender", " *owner-([^@]+)" },
    { "Sender", " *([^@]+)-owner" },
    { "Return-Path", " *owner-([^@]+)" },
    { "X-BeenThere", " *([^@]+)" },
    { "Delivered-To", " *mailing list ([^@]+)" },
    { "X-Mailing-List", " *([^@]+)" },
    { "X-Loop", " *([^@]+)" },
    { "List-Id", " *([^<]+)" },
    { "Mailing-List", " *list ([^@]+)" },
    { "Originator", " *([^@]+)" },
};

char *
header_raw_check_mailing_list(struct _header_raw **list)
{
    const char *v;
    regex_t pattern;
    regmatch_t match[2];
    int i, errcode;
    
    for (i = 0; i < sizeof (mail_list_magic) / sizeof (mail_list_magic[0]); i++) {
        if ((errcode = regcomp (&pattern, mail_list_magic[i].pattern, REG_EXTENDED|REG_ICASE)) != 0) {
            char *errstr;
            size_t len;
            
            len = regerror (errcode, &pattern, NULL, 0);
            errstr = g_malloc0 (len + 1);
            regerror (errcode, &pattern, errstr, len);
            regfree (&pattern);
            
            g_warning ("Internal error, compiling regex failed: %s: %s",
                   mail_list_magic[i].pattern, errstr);
            g_free (errstr);
            
            continue;
        }
        
        v = header_raw_find (list, mail_list_magic[i].name, NULL);
        if (v != NULL && regexec (&pattern, v, 2, match, 0) == 0 && match[1].rm_so != -1) {
            const char *mlist, *mlend;
            
            regfree (&pattern);
            mlist = v + match[1].rm_so;
            mlend = v + match[1].rm_eo;
            if (*mlist == '<')
                mlist++;
            
            return g_strndup (mlist, mlend - mlist);
        }
        regfree (&pattern);
    }

    return NULL;
}

/* ok, here's the address stuff, what a mess ... */
struct _header_address *header_address_new(void)
{
    struct _header_address *h;
    h = g_malloc0(sizeof(*h));
    h->type = HEADER_ADDRESS_NONE;
    h->refcount = 1;
    return h;
}

struct _header_address *header_address_new_name(const char *name, const char *addr)
{
    struct _header_address *h;

    h = header_address_new();
    h->type = HEADER_ADDRESS_NAME;
    h->name = g_strdup(name);
    h->v.addr = g_strdup(addr);
    return h;
}

struct _header_address *header_address_new_group(const char *name)
{
    struct _header_address *h;

    h = header_address_new();
    h->type = HEADER_ADDRESS_GROUP;
    h->name = g_strdup(name);
    return h;
}

void header_address_ref(struct _header_address *h)
{
    if (h)
        h->refcount++;
}

void header_address_unref(struct _header_address *h)
{
    if (h) {
        if (h->refcount <= 1) {
            if (h->type == HEADER_ADDRESS_GROUP) {
                header_address_list_clear(&h->v.members);
            } else if (h->type == HEADER_ADDRESS_NAME) {
                g_free(h->v.addr);
            }
            g_free(h->name);
            g_free(h);
        } else {
            h->refcount--;
        }
    }
}

void header_address_set_name(struct _header_address *h, const char *name)
{
    if (h) {
        g_free(h->name);
        h->name = g_strdup(name);
    }
}

void header_address_set_addr(struct _header_address *h, const char *addr)
{
    if (h) {
        if (h->type == HEADER_ADDRESS_NAME
            || h->type == HEADER_ADDRESS_NONE) {
            h->type = HEADER_ADDRESS_NAME;
            g_free(h->v.addr);
            h->v.addr = g_strdup(addr);
        } else {
            g_warning("Trying to set the address on a group");
        }
    }
}

void header_address_set_members(struct _header_address *h, struct _header_address *group)
{
    if (h) {
        if (h->type == HEADER_ADDRESS_GROUP
            || h->type == HEADER_ADDRESS_NONE) {
            h->type = HEADER_ADDRESS_GROUP;
            header_address_list_clear(&h->v.members);
            /* should this ref them? */
            h->v.members = group;
        } else {
            g_warning("Trying to set the members on a name, not group");
        }
    }
}

void header_address_add_member(struct _header_address *h, struct _header_address *member)
{
    if (h) {
        if (h->type == HEADER_ADDRESS_GROUP
            || h->type == HEADER_ADDRESS_NONE) {
            h->type = HEADER_ADDRESS_GROUP;
            header_address_list_append(&h->v.members, member);
        }           
    }
}

void header_address_list_append_list(struct _header_address **l, struct _header_address **h)
{
    if (l) {
        struct _header_address *n = (struct _header_address *)l;

        while (n->next)
            n = n->next;
        n->next = *h;
    }
}


void header_address_list_append(struct _header_address **l, struct _header_address *h)
{
    if (h) {
        header_address_list_append_list(l, &h);
        h->next = NULL;
    }
}

void header_address_list_clear(struct _header_address **l)
{
    struct _header_address *a, *n;
    a = *l;
    while (a) {
        n = a->next;
        header_address_unref(a);
        a = n;
    }
    *l = NULL;
}

/* if encode is true, then the result is suitable for mailing, otherwise
   the result is suitable for display only (and may not even be re-parsable) */
static void
header_address_list_encode_append(GString *out, int encode, struct _header_address *a)
{
    char *text;

    while (a) {
        switch (a->type) {
        case HEADER_ADDRESS_NAME:
            if (encode)
                text = header_encode_phrase (a->name);
            else
                text = a->name;
            if (text && *text)
                g_string_sprintfa(out, "%s <%s>", text, a->v.addr);
            else
                g_string_append(out, a->v.addr);
            if (encode)
                g_free(text);
            break;
        case HEADER_ADDRESS_GROUP:
            if (encode)
                text = header_encode_phrase(a->name);
            else
                text = a->name;
            g_string_sprintfa(out, "%s: ", text);
            header_address_list_encode_append(out, encode, a->v.members);
            g_string_sprintfa(out, ";");
            if (encode)
                g_free(text);
            break;
        default:
            g_warning("Invalid address type");
            break;
        }
        a = a->next;
        if (a)
            g_string_append(out, ", ");
    }
}

char *
header_address_list_encode(struct _header_address *a)
{
    GString *out;
    char *ret;

    if (a == NULL)
        return NULL;

    out = g_string_new("");

    header_address_list_encode_append(out, TRUE, a);
    ret = out->str;
    g_string_free(out, FALSE);
    return ret;
}

char *
header_address_list_format(struct _header_address *a)
{
    GString *out;
    char *ret;

    if (a == NULL)
        return NULL;

    out = g_string_new("");

    header_address_list_encode_append(out, FALSE, a);
    ret = out->str;
    g_string_free(out, FALSE);
    return ret;
}

char *
header_address_fold (const char *in, int headerlen)
{
    int len, outlen, i;
    const char *inptr = in, *space, *p, *n;
    GString *out;
    char *ret;
    int needunfold = FALSE;
    
    if (in == NULL)
        return NULL;
    
    /* first, check to see if we even need to fold */
    len = headerlen + 2;
    p = in;
    while (*p) {
        n = strchr (p, '\n');
        if (n == NULL) {
            len += strlen (p);
            break;
        }
        
        needunfold = TRUE;
        len += n-p;
        
        if (len >= CAMEL_FOLD_SIZE)
            break;
        len = 0;
        p = n + 1;
    }
    if (len < CAMEL_FOLD_SIZE)
        return g_strdup (in);
    
    /* we need to fold, so first unfold (if we need to), then process */
    if (needunfold)
        inptr = in = header_unfold (in);
    
    out = g_string_new ("");
    outlen = headerlen + 2;
    while (*inptr) {
        space = strchr (inptr, ' ');
        if (space) {
            len = space - inptr + 1;
        } else {
            len = strlen (inptr);
        }
        
        d(printf("next word '%.*s'\n", len, inptr));
        
        if (outlen + len > CAMEL_FOLD_SIZE) {
            d(printf("outlen = %d wordlen = %d\n", outlen, len));
            /* strip trailing space */
            if (out->len > 0 && out->str[out->len-1] == ' ')
                g_string_truncate (out, out->len-1);
            g_string_append (out, "\n\t");
            outlen = 1;
        }
        
        outlen += len;
        for (i = 0; i < len; i++) {
            g_string_append_c (out, inptr[i]);
        }
        
        inptr += len;
    }
    ret = out->str;
    g_string_free (out, FALSE);
    
    if (needunfold)
        g_free ((char *)in);
    
    return ret; 
}

/* simple header folding */
/* will work even if the header is already folded */
char *
header_fold(const char *in, int headerlen)
{
    int len, outlen, i;
    const char *inptr = in, *space, *p, *n;
    GString *out;
    char *ret;
    int needunfold = FALSE;

    if (in == NULL)
        return NULL;

    /* first, check to see if we even need to fold */
    len = headerlen + 2;
    p = in;
    while (*p) {
        n = strchr(p, '\n');
        if (n == NULL) {
            len += strlen (p);
            break;
        }

        needunfold = TRUE;
        len += n-p;
        
        if (len >= CAMEL_FOLD_SIZE)
            break;
        len = 0;
        p = n + 1;
    }
    if (len < CAMEL_FOLD_SIZE)
        return g_strdup(in);

    /* we need to fold, so first unfold (if we need to), then process */
    if (needunfold)
        inptr = in = header_unfold(in);

    out = g_string_new("");
    outlen = headerlen+2;
    while (*inptr) {
        space = strchr(inptr, ' ');
        if (space) {
            len = space-inptr+1;
        } else {
            len = strlen(inptr);
        }
        d(printf("next word '%.*s'\n", len, inptr));
        if (outlen + len > CAMEL_FOLD_SIZE) {
            d(printf("outlen = %d wordlen = %d\n", outlen, len));
            /* strip trailing space */
            if (out->len > 0 && out->str[out->len-1] == ' ')
                g_string_truncate(out, out->len-1);
            g_string_append(out, "\n\t");
            outlen = 1;
            /* check for very long words, just cut them up */
            while (outlen+len > CAMEL_FOLD_SIZE) {
                for (i=0;i<CAMEL_FOLD_SIZE-outlen;i++)
                    g_string_append_c(out, inptr[i]);
                inptr += CAMEL_FOLD_SIZE-outlen;
                len -= CAMEL_FOLD_SIZE-outlen;
                g_string_append(out, "\n\t");
                outlen = 1;
            }
        }
        outlen += len;
        for (i=0;i<len;i++) {
            g_string_append_c(out, inptr[i]);
        }
        inptr += len;
    }
    ret = out->str;
    g_string_free(out, FALSE);

    if (needunfold)
        g_free((char *)in);

    return ret; 
}

char *
header_unfold(const char *in)
{
    char *out = g_malloc(strlen(in)+1);
    const char *inptr = in;
    char c, *o = out;

    o = out;
    while ((c = *inptr++)) {
        if (c == '\n') {
            if (is_lwsp(*inptr)) {
                do {
                    inptr++;
                } while (is_lwsp(*inptr));
                *o++ = ' ';
            } else {
                *o++ = c;
            }
        } else {
            *o++ = c;
        }
    }
    *o = 0;

    return out;
}

#ifdef BUILD_TABLE

/* for debugging tests */
/* should also have some regression tests somewhere */

void test_phrase(const char *in)
{
    printf("'%s' -> '%s'\n", in, header_encode_phrase(in));
}

void test_fold(const char *in)
{
    printf("'%s'\n ->\n '%s'\n", in, header_fold(in));
}

void run_test(void)
{
    char *to = "gnome hacker dudes: license-discuss@opensource.org,
        \"Richard M. Stallman\" <rms@gnu.org>,
        Barry Chester <barry_che@antdiv.gov.au>,
        Michael Zucchi <zucchi.michael(this (is a nested) comment)@zedzone.mmc.com.au>,
        Miguel de Icaza <miguel@gnome.org>;,
    zucchi@zedzone.mmc.com.au, \"Foo bar\" <zed@zedzone>,
    <frob@frobzone>";

#if 0
    header_to_decode(to);

    header_mime_decode("1.0", 0, 0);
    header_mime_decode("1.3 (produced by metasend V1.0)", 0, 0);
    header_mime_decode("(produced by metasend V1.0) 5.2", 0, 0);
    header_mime_decode("7(produced by metasend 1.0) . (produced by helix/send/1.0) 9 . 5", 0, 0);
    header_mime_decode("3.", 0, 0);
    header_mime_decode(".", 0, 0);
    header_mime_decode(".5", 0, 0);
    header_mime_decode("c.d", 0, 0);
    header_mime_decode("", 0, 0);

    header_msgid_decode(" <\"L3x2i1.0.Nm5.Xd-Wu\"@lists.redhat.com>");
    header_msgid_decode("<200001180446.PAA02065@beaker.htb.com.au>");
#endif

    test_fold("Header: This is a long header that should be folded properly at the right place, or so i hope.  I should probably set the fold value to something lower for testing");
    test_fold("Header: nowletstryfoldingsomethingthatistoolongtofold,iwonderwhatitshoulddointsteadtofoldit?hmm,iguessicanjusttruncateitatsomepointortrytorefoldthepreviousstuff(yuck)tofit");
    test_phrase("Michael Zucchi (NotZed)");
    test_phrase("Zucchi, ( \\ NotZed \\ ) Michael");
    {
        int ic;
        char *outbuf, *inbuf, buffer[256];
        int inlen, outlen;

        outlen = 256;
        inbuf = "Dra¾en Kaèar";
        inlen = strlen(inbuf);
        outbuf = buffer;
        ic = iconv_open("UTF-8", "ISO-8859-1");
        iconv(ic, &inbuf, &inlen, &outbuf, &outlen);
        test_phrase(buffer);

        outlen = 256;
        inbuf = "This is an encoded phrase Tomasz K³oczko";
        inlen = strlen(inbuf);
        outbuf = buffer;
        ic = iconv_open("UTF-8", "ISO-8859-2");
        iconv(ic, &inbuf, &inlen, &outbuf, &outlen);
        test_phrase(buffer);

    }

    {
        char *str = "Blah blah\n\t = ? =? ?= This is a TEST For quoted-printable-encoding-encoding-of
    long lines, and lines that end in spaces                                                                       
    and line sthat end in tabs                      
    And lines that just end.";

        char encoded[256];
        int state=-1,save=0;
        int len;

        len = quoted_encode_step(str, strlen(str), encoded, &state, &save);
        len += quoted_encode_close("", 0, encoded+len, &state, &save);
        printf("encoded = '%.*s'\n", len, encoded);
    }
}

#endif /* BUILD_TABLE */