File: results.c

package info (click to toggle)
4store 1.1.6+20151109-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid, stretch
  • size: 82,388 kB
  • sloc: ansic: 65,689; sh: 2,916; perl: 2,245; makefile: 281; python: 213
file content (3194 lines) | stat: -rw-r--r-- 101,516 bytes parent folder | download
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
/*
    4store - a clustered RDF storage and query engine

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

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

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
/*
 *  Copyright (C) 2006 Steve Harris for Garlik
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>

#include "4store-config.h"
#include "results.h"
#include "order.h"
#include "query-datatypes.h"
#include "query.h"
#include "query-intl.h"
#include "filter.h"
#include "debug.h"
#include "../common/bit_arr.h"
#include "../common/4s-hash.h"
#include "../common/error.h"
#include "../common/rdf-constants.h"
#include "../common/4s-internals.h"

#define CACHE_SIZE 65536
#define CACHE_MASK (CACHE_SIZE-1)

#define RESOURCE_LOOKUP_BUFFER 1800

/* glib 2.x headers must match the architecture we're building. If the size of a pointer
 * is smaller in the provided glibconfig.h than in our target architecture, the resulting typedef
 * should be invalid, preventing the user from building a 4store that won't work properly at runtime
 * we can't use the pre-processor to detect this problem because it doesn't grok sizeof() */
typedef char wrong_glib_headers[1 + GLIB_SIZEOF_VOID_P - sizeof(void *)];

/* used for sorting */
static const char *NULL_PROXY = " ";
static const char *BNODE_PROXY = "*";

static GStaticMutex cache_mutex = G_STATIC_MUTEX_INIT;
pthread_mutex_t rasqal_ser_mutex = PTHREAD_MUTEX_INITIALIZER;

static fs_resource res_l2_cache[CACHE_SIZE];

static GHashTable *res_l1_cache = NULL;

/* must hold mutex to call this function */
static void setup_l1_cache()
{
    res_l1_cache = g_hash_table_new_full(fs_rid_hash, fs_rid_equal, NULL, NULL);
}

static int resolve(fs_query *q, fs_rid rid, fs_resource *res)
{
    res->rid = FS_RID_GONE;
    res->attr = FS_RID_GONE;
    res->lex = NULL;

    if (rid == FS_RID_NULL) {
        res->rid = rid;
        res->attr = FS_RID_NULL;
        res->lex = "NULL";

        return 0;
    }
    if (FS_IS_BNODE(rid)) {
        res->rid = rid;
        res->attr = FS_RID_NULL;
        res->lex = g_strdup_printf("_:b%llx", FS_BNODE_NUM(rid));
        fs_query_add_row_freeable(q, res->lex);

        return 0;
    }

    fs_resource *hit;

    /* doesn't require a mutex as it's not shared by multiple queries */

    if ((hit = g_hash_table_lookup(q->tmp_resources, &rid))) {
#if DEBUG_FILTER
        printf("fetching %016llx from tmp_resources\n", rid);
#endif
        /* don't need deep copy as the hash grows monotonically until query is
         * complete */
        memcpy(res, hit, sizeof(fs_resource));

        return 0;
    }

    const char *lex_constant = fs_hash_predefined_uri(rid);
    if (!lex_constant)
        lex_constant = fs_hash_predefined_literal(rid);
    if (lex_constant) {
        res->lex = strdup(lex_constant);
        res->rid = rid;
        res->attr = FS_RID_NULL;
        fs_query_add_row_freeable(q, res->lex);

        return 0;
    }

    q->qs->cache_hits++;
    g_static_mutex_lock(&cache_mutex);

    if (res_l2_cache[rid & CACHE_MASK].rid == rid) {
        q->qs->cache_success_l2++;
        /* deep copy resource */
        res->rid = res_l2_cache[rid & CACHE_MASK].rid;
        res->attr = res_l2_cache[rid & CACHE_MASK].attr;
        res->lex = g_strdup(res_l2_cache[rid & CACHE_MASK].lex);
        fs_query_add_row_freeable(q, res->lex);
        g_static_mutex_unlock(&cache_mutex);

	return 0;
    }

    if (!res_l1_cache) {
        setup_l1_cache();
    }
    if ((hit = g_hash_table_lookup(res_l1_cache, &rid))) {
        q->qs->cache_success_l1++;
        /* deep copy */
        res->rid = hit->rid;
        res->attr = hit->attr;
        res->lex = g_strdup(hit->lex);
        fs_query_add_row_freeable(q, res->lex);
        g_static_mutex_unlock(&cache_mutex);

        return 0;
    }

    g_static_mutex_unlock(&cache_mutex);

    GTimer *tmr = NULL;
    if (q->qs->verbosity || q->qs->cache_stats) {
        tmr = g_timer_new();
        q->qs->cache_fail++;
    }

    fs_rid_vector *r = fs_rid_vector_new(1);
    r->data[0] = rid;
#ifdef DEBUG_FILTER
    printf("resolving %016llx\n", rid);
#endif
    g_static_mutex_lock(&cache_mutex);
    if (g_hash_table_lookup(res_l1_cache, &rid) == NULL) {
        fsp_resolve(q->link, FS_RID_SEGMENT(rid, q->segments), r, res);
        fs_rid *trid = malloc(sizeof(fs_rid));
        fs_resource *tres = malloc(sizeof(fs_resource));
        *trid = rid;
        tres->rid = res->rid;
        tres->attr = res->attr;
        tres->lex = g_strdup(res->lex);
        fs_query_add_row_freeable(q, res->lex);
        g_hash_table_insert(res_l1_cache, trid, tres);
    }
    g_static_mutex_unlock(&cache_mutex);
    fs_rid_vector_free(r);

    if (q->qs->verbosity || q->qs->cache_stats) {
        q->qs->resolve_unique_elapse += g_timer_elapsed(tmr, NULL);
        g_timer_destroy(tmr);
    }

    return 0;
}

static fs_row* fs_row_copy(fs_row *r,int cols) {
    fs_row *res = malloc(cols * sizeof(fs_row));
    for (int i = 0; i < cols; i++) {
        res[i].name = g_strdup(r[i].name);
        res[i].rid = r[i].rid;
        res[i].type = r[i].type;
        res[i].lex = g_strdup(r[i].lex);
        res[i].dt = g_strdup(r[i].dt);
        res[i].lang = g_strdup(r[i].lang);
        res[i].stop = r[i].stop;
    }
    return res;
}

static void fs_free_agg_values(GPtrArray *agg,int vars) {
    for(int i=0;i<agg->len;i++) {
        fs_value **p = g_ptr_array_index(agg,i);
        for (int j=0; j<vars; j++) {
            if (p[j]->lex)
                g_free(p[j]->lex);
            free(p[j]);
        }
        free(p);
    }
    g_ptr_array_free(agg,1);
}

static void fs_free_agg_rows(GPtrArray *agg,int vars) {
    for(int i=0;i<agg->len;i++) {
        fs_row *p = g_ptr_array_index(agg,i);
        for (int j=0; j<vars; j++) {
            g_free((gpointer)p[j].name);
            g_free((gpointer)p[j].lex);
            g_free((gpointer)p[j].dt);
            g_free((gpointer)p[j].lang);
        }
        free(p);
    }
    g_ptr_array_free(agg,1);
}

static fs_value literal_to_value_in_aggs(fs_query *q, int row, int block, rasqal_literal *l) {
    rasqal_variable *var = rasqal_literal_as_variable(l);
    int i=0;
    fs_binding *b=q->bt;
    for (i=0; b[i].name; i++) {
        if (!strcmp(b[i].name, (const char *) var->name )) {
            break;
        }
    }
    i--;
    if (i < q->num_vars) {
        fs_value **values = (fs_value **) g_ptr_array_index(q->agg_values,row);
        return *(values[i]);
    }
    return fs_value_error(FS_ERROR,"Order in group by with nonexistent variable");
}

static fs_value literal_to_value(fs_query *q, int row, int block, rasqal_literal *l)
{
    fs_value v;
    fs_rid attr = fs_c.empty;

    switch (l->type) {
    case RASQAL_LITERAL_BLANK:
        return fs_value_error(FS_ERROR_INVALID_TYPE, "unhandled bNode in FILTER expression");

    case RASQAL_LITERAL_URI:
        return fs_value_uri((char *)raptor_uri_as_string(l->value.uri));

    case RASQAL_LITERAL_XSD_STRING:
    case RASQAL_LITERAL_UDT:
    case RASQAL_LITERAL_STRING:
        if (l->language) {
            attr = fs_hash_literal(l->language, 0);
        } else if (l->datatype) {
            attr = fs_hash_uri((char *)raptor_uri_as_string(l->datatype));
        }
        v = fs_value_plain((char *)l->string);
        v.attr = attr;
        v = fn_cast_intl(q, v, attr);
        return v;

    case RASQAL_LITERAL_BOOLEAN:
        return fs_value_boolean(l->value.integer);

    case RASQAL_LITERAL_INTEGER:
    case RASQAL_LITERAL_INTEGER_SUBTYPE:
        return fs_value_integer(l->value.integer);

    case RASQAL_LITERAL_DOUBLE:
        return fs_value_double(l->value.floating);

    case RASQAL_LITERAL_FLOAT:
        return fs_value_float(l->value.floating);

	case RASQAL_LITERAL_DATETIME:
#if RASQAL_VERSION >= 929
	case RASQAL_LITERAL_DATE:
#endif
	    return fs_value_datetime_from_string((char *)l->string);

    case RASQAL_LITERAL_DECIMAL:
        return fs_value_decimal_from_string((char *)l->string);

    case RASQAL_LITERAL_PATTERN:
        return fs_value_plain((char *)l->string);

    case RASQAL_LITERAL_QNAME:
        return fs_value_error(FS_ERROR_INVALID_TYPE,
        "unhandled qname in FILTER expression");

    case RASQAL_LITERAL_VARIABLE:
    {

#ifdef DEBUG_FILTER
        char *name = (char *)l->value.variable->name;
        printf("getting value of ?%s, row %d from B%d\n", name, row, block);
#endif
        fs_binding *b = fs_binding_get(q->bt, l->value.variable);
        /* TODO this code needs to be tested when the parser handles
         * { FILTER() } correctly, but not block can be -1 if we dont
         * care about scope */
#if 0
         if (!b->bound_in_block[block]) {
#ifdef DEBUG_FILTER
              printf("?%s not bound in B%d, appears in B%d\n", name, block, b->appears);
#endif
              q->warnings = g_slist_prepend(q->warnings,
                "variable used in expression block where "
                "it is not bound");
               return fs_value_rid(FS_RID_NULL);
         }
#endif
        if (!b || row >= b->vals->length) {
            return fs_value_rid(FS_RID_NULL);
        }
        fs_resource r;
        resolve(q, b->vals->data[row], &r);
        fs_value v = fs_value_resource(q, &r);

        return v;
    }

    case RASQAL_LITERAL_UNKNOWN:
        return fs_value_error(FS_ERROR_INVALID_TYPE, "bad literal FILTER expression");

    }

    return fs_value_error(FS_ERROR_INVALID_TYPE, "unhandled literal");
}

fs_value fs_expression_eval(fs_query *q, int row, int block, rasqal_expression *e)
{
    if (!e) {
        return fs_value_rid(FS_RID_NULL);
    }
    if (block < 0) {
        fs_error(LOG_ERR, "block was less than zero, changing to 0");
        block = 0;
    }
    switch (e->op) {
#if RASQAL_VERSION >= 925
    case RASQAL_EXPR_ABS:
        return fn_numeric_abs(q, fs_expression_eval(q, row, block, e->arg1));
    case RASQAL_EXPR_ROUND:
        return fn_numeric_round(q, fs_expression_eval(q, row, block, e->arg1));
    case RASQAL_EXPR_CEIL:
        return fn_numeric_ceil(q, fs_expression_eval(q, row, block, e->arg1));
    case RASQAL_EXPR_FLOOR:
        return fn_numeric_floor(q, fs_expression_eval(q, row, block, e->arg1));
    case RASQAL_EXPR_RAND:
        return fn_rand(q);
#endif
#if RASQAL_VERSION >= 926
    case RASQAL_EXPR_TZ:
        /* TZ is rather complex, and not amazingly useful, but contribuitions of code welcome! */
        return fs_value_error(FS_ERROR_INVALID_TYPE, "unsupported TZ function");
    case RASQAL_EXPR_MD5:
        return fn_md5(q, fs_expression_eval(q, row, block, e->arg1));
    case RASQAL_EXPR_SHA1:
        return fn_sha1(q, fs_expression_eval(q, row, block, e->arg1));
    case RASQAL_EXPR_SHA256:
        return fn_sha256(q, fs_expression_eval(q, row, block, e->arg1));
    case RASQAL_EXPR_SHA224:
    case RASQAL_EXPR_SHA384:
    case RASQAL_EXPR_SHA512:
        return fs_value_error(FS_ERROR_INVALID_TYPE, "unsupported hash function");
#endif
#if RASQAL_VERSION >= 928
    case RASQAL_EXPR_STRBEFORE:
        return fn_strbefore(q, fs_expression_eval(q, row, block, e->arg1),
                               fs_expression_eval(q, row, block, e->arg2));
    case RASQAL_EXPR_STRAFTER:
        return fn_strafter(q, fs_expression_eval(q, row, block, e->arg1),
                               fs_expression_eval(q, row, block, e->arg2));
    case RASQAL_EXPR_REPLACE:
        return fs_value_error(FS_ERROR_INVALID_TYPE, "fn:replace not yet implemented");
#endif
#if RASQAL_VERSION >= 929
    case RASQAL_EXPR_UUID:
        return fn_uuid(q);
    case RASQAL_EXPR_STRUUID:
        return fn_struuid(q);
#endif
    case RASQAL_EXPR_AND:
        return fn_logical_and(q, fs_expression_eval(q, row, block, e->arg1),
                                 fs_expression_eval(q, row, block, e->arg2));

    case RASQAL_EXPR_OR:
        return fn_logical_or(q, fs_expression_eval(q, row, block, e->arg1),
                                fs_expression_eval(q, row, block, e->arg2));

    case RASQAL_EXPR_EQ:
    case RASQAL_EXPR_STR_EQ:
        return fn_equal(q, fs_expression_eval(q, row, block, e->arg1),
                           fs_expression_eval(q, row, block, e->arg2));

    case RASQAL_EXPR_NEQ:
    case RASQAL_EXPR_STR_NEQ:
        return fn_not_equal(q, fs_expression_eval(q, row, block, e->arg1),
                               fs_expression_eval(q, row, block, e->arg2));

    case RASQAL_EXPR_LT:
        return fn_less_than(q, fs_expression_eval(q, row, block, e->arg1),
                               fs_expression_eval(q, row, block, e->arg2));

    case RASQAL_EXPR_GT:
        return fn_greater_than(q, fs_expression_eval(q, row, block, e->arg1),
                                  fs_expression_eval(q, row, block, e->arg2));

    case RASQAL_EXPR_LE:
        return fn_less_than_equal(q, fs_expression_eval(q, row, block, e->arg1),
                                     fs_expression_eval(q, row, block, e->arg2));

    case RASQAL_EXPR_GE:
        return fn_greater_than_equal(q, 
                fs_expression_eval(q, row, block, e->arg1),
                fs_expression_eval(q, row, block, e->arg2));
    
    case RASQAL_EXPR_UMINUS:
        return fn_minus(q, fs_expression_eval(q, row, block, e->arg1));

    case RASQAL_EXPR_PLUS:
        return fn_numeric_add(q, fs_expression_eval(q, row, block, e->arg1),
                                 fs_expression_eval(q, row, block, e->arg2));

    case RASQAL_EXPR_MINUS:
        return fn_numeric_subtract(q, fs_expression_eval(q, row, block, e->arg1),
                                      fs_expression_eval(q, row, block, e->arg2));

    case RASQAL_EXPR_STAR:
        return fn_numeric_multiply(q, fs_expression_eval(q, row, block, e->arg1),
                                      fs_expression_eval(q, row, block, e->arg2));

    case RASQAL_EXPR_SLASH:
        return fn_numeric_divide(q, fs_expression_eval(q, row, block, e->arg1),
                                    fs_expression_eval(q, row, block, e->arg2));

    case RASQAL_EXPR_REM:
        return fs_value_error(FS_ERROR_INVALID_TYPE, "unhandled REM operator");

    case RASQAL_EXPR_REGEX:
        return fn_matches(q, fs_expression_eval(q, row, block, e->arg1),
                          fs_expression_eval(q, row, block, e->arg2),
                          fs_expression_eval(q, row, block, e->arg3));

    case RASQAL_EXPR_STR_MATCH:
        return fn_matches(q, fs_expression_eval(q, row, block, e->arg1),
                          literal_to_value(q, row, block, e->literal),
                          fs_value_plain((char *)e->literal->flags));

    case RASQAL_EXPR_STR_NMATCH:
        return fn_not(q, fn_matches(q, fs_expression_eval(q, row, block, e->arg1),
                          literal_to_value(q, row, block, e->literal),
                          fs_value_plain((char *)e->literal->flags)));

    case RASQAL_EXPR_TILDE:
    case RASQAL_EXPR_BANG:
        return fn_not(q, fs_expression_eval(q, row, block, e->arg1));

    case RASQAL_EXPR_FUNCTION:
        if (raptor_sequence_size(e->args) == 1 &&
            !strncmp((char *)raptor_uri_as_string(e->name), XSD_NAMESPACE, strlen(XSD_NAMESPACE))) {
            return fn_cast(q, fs_expression_eval(q, row,
                                block, (rasqal_expression *)raptor_sequence_get_at(e->args, 0)),
                       fs_value_uri((char *)raptor_uri_as_string(e->name)));
        }
        return fs_value_error(FS_ERROR_INVALID_TYPE, "unhandled extension function");

    case RASQAL_EXPR_BOUND:
        return fn_bound(q, fs_expression_eval(q, row, block, e->arg1));

    case RASQAL_EXPR_STR:
        return fn_str(q, fs_expression_eval(q, row, block, e->arg1));

    case RASQAL_EXPR_LANG:
        return fn_lang(q, fs_expression_eval(q, row, block, e->arg1));

    case RASQAL_EXPR_LANGMATCHES:
        return fn_lang_matches(q, fs_expression_eval(q, row, block, e->arg1),
                               fs_expression_eval(q, row, block, e->arg2));

    case RASQAL_EXPR_DATATYPE:
        return fn_datatype(q, fs_expression_eval(q, row, block, e->arg1));

    case RASQAL_EXPR_ISURI:
        return fn_is_iri(q, fs_expression_eval(q, row, block, e->arg1));

    case RASQAL_EXPR_ISBLANK:
        return fn_is_blank(q, fs_expression_eval(q, row, block, e->arg1));

    case RASQAL_EXPR_ISLITERAL:
        return fn_is_literal(q, fs_expression_eval(q, row, block, e->arg1));

    case RASQAL_EXPR_CAST:
        return fn_cast(q, fs_expression_eval(q, row, block, e->arg1),
                       fs_value_uri((char *)raptor_uri_as_string(e->name)));

    case RASQAL_EXPR_ORDER_COND_DESC: {
        fs_value v = fs_expression_eval(q, row, block, e->arg1);
        v.valid |= fs_valid_bit(FS_V_DESC);
        return v;
    }

    case RASQAL_EXPR_ORDER_COND_ASC: {
        fs_value v = fs_expression_eval(q, row, block, e->arg1);
        v.valid &= ~fs_valid_bit(FS_V_DESC);
        return v;
    }

    case RASQAL_EXPR_GROUP_COND_DESC: {
        fs_value v = fs_expression_eval(q, row, block, e->arg1);
        return v;
    }

    case RASQAL_EXPR_GROUP_COND_ASC: {
        fs_value v = fs_expression_eval(q, row, block, e->arg1);
        return v;
    }

    case RASQAL_EXPR_COUNT: {
        if (e->arg1->op == RASQAL_EXPR_VARSTAR && !q->apply_constraints) {
            return fs_value_integer(q->group_length);
        }
        int count = 0;
        fs_rid rid_prev = FS_RID_NULL;
        for (int r=0; r<q->group_length; r++) {
            int rr;
            if (!q->group_by && (e->flags & RASQAL_EXPR_FLAG_DISTINCT))
                rr = q->bt[0].vals->data[r];
            else
                rr = q->group_rows[r];
            if (q->apply_constraints && !fs_bit_array_get(q->apply_constraints,rr)) continue;
            fs_value v = fs_expression_eval(q, rr, block, e->arg1);
            if (v.valid & fs_valid_bit(FS_V_TYPE_ERROR) ||
                ((v.attr == fs_c.empty || v.attr == FS_RID_NULL) &&
                  v.rid == FS_RID_NULL)) {
               /* do nothing */
            } else {
                if (e->flags & RASQAL_EXPR_FLAG_DISTINCT) { 
                    if (v.rid != rid_prev) {
                        count++;
                        rid_prev = v.rid;
                    }
                } else
                    count++;
            }
        }

        return fs_value_integer(count);
    }

    case RASQAL_EXPR_IRI:
    case RASQAL_EXPR_URI:
        return fn_uri(q, fs_expression_eval(q, row, block, e->arg1));

    case RASQAL_EXPR_BNODE:
        return fn_bnode(q, fs_expression_eval(q, row, block, e->arg1));

    case RASQAL_EXPR_STRLANG: {
        fs_value str = fs_expression_eval(q, row, block, e->arg1);
        if (fs_is_error(str)) {
            return str;
        }
        if (str.valid & fs_valid_bit(FS_V_RID) &&
            (FS_IS_BNODE(str.rid) || FS_IS_URI(str.rid))) {
            return fs_value_error(FS_ERROR_INVALID_TYPE, NULL);
        }
        str = fs_value_fill_lexical(q, str);

        fs_value lang = fs_expression_eval(q, row, block, e->arg2);
        if (fs_is_error(lang)) {
            return lang;
        }
        if (lang.valid & fs_valid_bit(FS_V_RID) &&
            (FS_IS_BNODE(lang.rid) || FS_IS_URI(lang.rid))) {
            return fs_value_error(FS_ERROR_INVALID_TYPE, NULL);
        }
        lang = fs_value_fill_lexical(q, lang);

        return fs_value_plain_with_lang(str.lex, lang.lex);
    }

    case RASQAL_EXPR_STRDT: {
        fs_value str = fs_expression_eval(q, row, block, e->arg1);
        if (fs_is_error(str)) {
            return str;
        }
        if (str.valid & fs_valid_bit(FS_V_RID) &&
            (FS_IS_BNODE(str.rid) || FS_IS_URI(str.rid))) {
            return fs_value_error(FS_ERROR_INVALID_TYPE, NULL);
        }
        str = fs_value_fill_lexical(q, str);

        fs_value dt = fs_expression_eval(q, row, block, e->arg2);
        if (fs_is_error(dt)) {
            return dt;
        }
        if (dt.valid & fs_valid_bit(FS_V_RID)) {
            if (!(FS_IS_BNODE(dt.rid) || FS_IS_URI(dt.rid))) {
                return fs_value_error(FS_ERROR_INVALID_TYPE, NULL);
            }
        } else {
            return fs_value_error(FS_ERROR_INVALID_TYPE, NULL);
        }
        dt = fs_value_fill_lexical(q, dt);

        return fs_value_plain_with_dt(str.lex, dt.lex);
    }

    case RASQAL_EXPR_NOT_IN:
    case RASQAL_EXPR_IN: {
        fs_value comp = fs_expression_eval(q, row, block, e->arg1);
        for (int i=0; i < raptor_sequence_size(e->args); i++) {
            fs_value v = fs_expression_eval(q, row, block, raptor_sequence_get_at(e->args, i));
            if (fs_value_equal(comp, v)) {
                return fs_value_boolean(e->op == RASQAL_EXPR_IN ? 1 : 0);
            }
        }

        return fs_value_boolean(e->op == RASQAL_EXPR_IN ? 0 : 1);
    }

    case RASQAL_EXPR_NOW:
    case RASQAL_EXPR_CURRENT_DATETIME:
        return fs_value_datetime(q->start_time);

    case RASQAL_EXPR_FROM_UNIXTIME: {
        fs_value v = fs_expression_eval(q, row, block, e->arg1);
        if (fs_is_numeric(&v)) {
            v = fn_cast_intl(q, v, fs_c.xsd_integer);

            return fs_value_datetime(v.in);
        }

        return fs_value_error(FS_ERROR_INVALID_TYPE, NULL);
    }

    case RASQAL_EXPR_TO_UNIXTIME: {
        fs_value v = fs_expression_eval(q, row, block, e->arg1);
        if (v.attr == fs_c.xsd_datetime) {
            return fs_value_integer(v.in);
        }

        return fs_value_error(FS_ERROR_INVALID_TYPE, NULL);
    }

    case RASQAL_EXPR_STRLEN: {
        fs_value v = fs_expression_eval(q, row, block, e->arg1);
        if (!fs_is_plain_or_string(v)) {
            return fs_value_error(FS_ERROR_INVALID_TYPE, NULL);
        }
        v = fs_value_fill_lexical(q, v);

        return fs_value_integer(strlen(v.lex));
    }

    case RASQAL_EXPR_ISNUMERIC: {
        fs_value v = fs_expression_eval(q, row, block, e->arg1);

        return fs_value_boolean(fs_is_numeric(&v));
    }

    case RASQAL_EXPR_IF: {
        fs_value cond = fn_ebv(fs_expression_eval(q, row, block, e->arg1));
        /* if arg1 is false or error */
        if (fs_is_error(cond)) {
            return cond;
        } else if (cond.in) {
            return fs_expression_eval(q, row, block, e->arg2);
        }

        return fs_expression_eval(q, row, block, e->arg3);
    }

    case RASQAL_EXPR_SUBSTR: {
        return fn_substring(q, fs_expression_eval(q, row, block, e->arg1),
                            fs_expression_eval(q, row, block, e->arg2),
                            fs_expression_eval(q, row, block, e->arg3));
    }

    case RASQAL_EXPR_UCASE:
        return fn_ucase(q, fs_expression_eval(q, row, block, e->arg1));

    case RASQAL_EXPR_LCASE:
        return fn_lcase(q, fs_expression_eval(q, row, block, e->arg1));

    case RASQAL_EXPR_ENCODE_FOR_URI:
        return fn_encode_for_uri(q, fs_expression_eval(q, row, block, e->arg1));

    case RASQAL_EXPR_CONCAT: {
        GString *concat = g_string_new("");
        for (int i=0; i < raptor_sequence_size(e->args); i++) {
            fs_value v = fs_expression_eval(q, row, block, raptor_sequence_get_at(e->args, i));
            if (fs_is_error(v)) {
                g_string_free(concat, TRUE);

                return fs_value_error(FS_ERROR_INVALID_TYPE, NULL);
            }
            if (v.rid == FS_RID_NULL) {
                g_string_free(concat, TRUE);

                return fs_value_error(FS_ERROR_INVALID_TYPE, NULL);
            }

            v = fs_value_fill_lexical(q, v);
            g_string_append(concat, v.lex);
        }

        char *str = g_string_free(concat, FALSE);
        fs_query_add_freeable(q, str);

        return fs_value_plain(str);
    }

    case RASQAL_EXPR_YEAR:
        return fn_year(q, fs_expression_eval(q, row, block, e->arg1));

    case RASQAL_EXPR_MONTH:
        return fn_month(q, fs_expression_eval(q, row, block, e->arg1));

    case RASQAL_EXPR_DAY:
        return fn_day(q, fs_expression_eval(q, row, block, e->arg1));

    case RASQAL_EXPR_HOURS:
        return fn_hours(q, fs_expression_eval(q, row, block, e->arg1));

    case RASQAL_EXPR_MINUTES:
        return fn_minutes(q, fs_expression_eval(q, row, block, e->arg1));

    case RASQAL_EXPR_SECONDS:
        return fn_seconds(q, fs_expression_eval(q, row, block, e->arg1));

    case RASQAL_EXPR_TIMEZONE:
        return fn_timezone(q, fs_expression_eval(q, row, block, e->arg1));

    case RASQAL_EXPR_STRSTARTS:
        return fn_strstarts(q, fs_expression_eval(q, row, block, e->arg1),
                               fs_expression_eval(q, row, block, e->arg2));

    case RASQAL_EXPR_STRENDS:
        return fn_strends(q, fs_expression_eval(q, row, block, e->arg1),
                             fs_expression_eval(q, row, block, e->arg2));

    case RASQAL_EXPR_CONTAINS:
        return fn_contains(q, fs_expression_eval(q, row, block, e->arg1),
                              fs_expression_eval(q, row, block, e->arg2));

    /* aggregates */

    case RASQAL_EXPR_SUM: {
        fs_value v = fs_value_integer(0);
        fs_rid rid_prev = FS_RID_NULL;
        for (int r=0; r<q->group_length; r++) {
            int rr;
            if (!q->group_by && (e->flags & RASQAL_EXPR_FLAG_DISTINCT))
                rr = q->bt[0].vals->data[r];
            else
                rr = q->group_rows[r];
            if (q->apply_constraints && !fs_bit_array_get(q->apply_constraints,rr)) continue;
            fs_value expr = fs_expression_eval(q, rr, block, e->arg1);
            if (e->flags & RASQAL_EXPR_FLAG_DISTINCT) { 
                if (expr.rid != rid_prev) {
                    rid_prev = expr.rid;
                } else
                    continue;
            }
            v = fn_numeric_add(q, v, expr);
        }

        return v;
    }

    case RASQAL_EXPR_AVG: {
        /* if distinct applies we should sort and unique */
        fs_value sum = fs_value_integer(0);
        int count = 0;
        fs_rid rid_prev = FS_RID_NULL;
        for (int r=0; r<q->group_length; r++) {
            int rr;
            if (!q->group_by && (e->flags & RASQAL_EXPR_FLAG_DISTINCT))
                rr = q->bt[0].vals->data[r];
            else
                rr = q->group_rows[r];
            if (q->apply_constraints && !fs_bit_array_get(q->apply_constraints,rr)) continue;
            fs_value expr = fs_expression_eval(q, rr, block, e->arg1);
            if (e->flags & RASQAL_EXPR_FLAG_DISTINCT) { 
                if (expr.rid != rid_prev) {
                    rid_prev = expr.rid;
                } else
                    continue;
            }
            sum = fn_numeric_add(q, sum, expr);
            if (sum.valid & fs_valid_bit(FS_V_TYPE_ERROR)) {
                return sum;
            }
            if (expr.valid & fs_valid_bit(FS_V_TYPE_ERROR) ||
                ((expr.attr == fs_c.empty || expr.attr == FS_RID_NULL) &&
                  expr.rid == FS_RID_NULL)) {
               /* do nothing */
            } else {
                count++;
            }
        }

        return fn_numeric_divide(q, sum, fs_value_integer(count));
    }

    case RASQAL_EXPR_SAMPLE: {
        if (q->group_length > 0) {
            return fs_expression_eval(q, q->group_rows[0], block, e->arg1);
        }

        return fs_value_error(FS_ERROR_INVALID_TYPE, NULL);
    }

    case RASQAL_EXPR_MIN: {
        fs_value m;
        int set = 0;
        int pre=0;
        if (q->group_length > 0) {
            for (int pre=0; !set && pre<q->group_length; pre++) {
                if (q->apply_constraints && !fs_bit_array_get(q->apply_constraints,q->group_rows[pre])) continue;
                m = fs_expression_eval(q, q->group_rows[pre], block, e->arg1);
                set = 1;
            }
        }
        if (!set)
            m = fs_value_error(FS_ERROR_INVALID_TYPE, NULL);
        else {
            for (int r=pre; r<q->group_length; r++) {
                if (q->apply_constraints && !fs_bit_array_get(q->apply_constraints,q->group_rows[r])) continue;
                fs_value expr = fs_expression_eval(q, q->group_rows[r], block, e->arg1);
                int order = fs_order_by_cmp(m, expr);
                if (order > 0) {
                    m = expr;
                }
            }
        }
        return m;
    }

    case RASQAL_EXPR_MAX: {
        fs_value m;
        int set = 0;
        int pre=0;
        if (q->group_length > 0) {
            for (int pre=0; !set && pre<q->group_length; pre++) {
                if (q->apply_constraints && !fs_bit_array_get(q->apply_constraints,q->group_rows[pre])) continue;
                m = fs_expression_eval(q, q->group_rows[pre], block, e->arg1);
                set = 1;
            }
        }
        if (!set)
            m = fs_value_error(FS_ERROR_INVALID_TYPE, NULL);
        else {
            for (int r=pre; r<q->group_length; r++) {
                if (q->apply_constraints && !fs_bit_array_get(q->apply_constraints,q->group_rows[r])) continue;
                fs_value expr = fs_expression_eval(q, q->group_rows[r], block, e->arg1);
                int order = fs_order_by_cmp(m, expr);
                if (order < 0) {
                    m = expr;
                }
            }
        }
        return m;

        return m;
    }

    case RASQAL_EXPR_GROUP_CONCAT: {
        char *sep = " ";
        GString *concat = g_string_new("");
        if (e->literal) {
            sep = (char *)rasqal_literal_as_string(e->literal);
        }
        int count = 0;
        for (int r=0; r<q->group_length; r++) {
            for (int i=0; i < raptor_sequence_size(e->args); i++) {
                fs_value v = fs_expression_eval(q, q->group_rows[r], block, raptor_sequence_get_at(e->args, i));
                if (fs_is_error(v)) {
                    g_string_free(concat, TRUE);

                    return v;
                }
                v = fs_value_fill_lexical(q, v);
                if (count++ > 0) {
                    g_string_append(concat, sep);
                }
                g_string_append(concat, v.lex);
            }
        }

        char *str = g_string_free(concat, FALSE);
        fs_query_add_freeable(q, str);

        return fs_value_plain(str);
    }

    case RASQAL_EXPR_SAMETERM:
        return fn_rdfterm_equal(q, fs_expression_eval(q, row, block, e->arg1),
                                   fs_expression_eval(q, row, block, e->arg2));

    case RASQAL_EXPR_COALESCE: {
        fs_value v;
        for (int i=0; raptor_sequence_get_at(e->args, i); i++) {
            rasqal_expression *ea = (rasqal_expression *)raptor_sequence_get_at(e->args, i);
            v = fs_expression_eval(q, row, block, ea);
            if (!fs_is_error(v) &&
                !(v.valid & fs_valid_bit(FS_V_RID) && v.rid == FS_RID_NULL)) {
                return v;
            }
        }
        return fs_value_error(FS_ERROR_INVALID_TYPE, "no valid arguments to COALESCE");
    }

    case RASQAL_EXPR_VARSTAR: {
        fs_value v = fs_value_integer(1);
        return v;
    }

    case RASQAL_EXPR_UNKNOWN:
        return fs_value_error(FS_ERROR_INVALID_TYPE, "bad value in expression");
    case RASQAL_EXPR_LITERAL:
        break;
    }

    if (e->literal && q->aggregate_order_sorted == 1) {
        return literal_to_value_in_aggs(q, row, block, e->literal);
    } else if (e->literal) {
        if (e->literal &&
            e->literal->type == RASQAL_LITERAL_VARIABLE &&
            e->literal->value.variable->expression)
            return fs_expression_eval(q,row,block,
                    e->literal->value.variable->expression); 
        return literal_to_value(q, row, block, e->literal);
    }

    return fs_value_error(FS_ERROR_INVALID_TYPE, "unhandled operator");
}

static int resolve_precache_all(fsp_link *l, fs_rid_vector *rv[], int segments)
{
    g_static_mutex_lock(&cache_mutex);
    if (!res_l1_cache) {
        setup_l1_cache();
    }
    g_static_mutex_unlock(&cache_mutex);

    fs_resource *res[segments];
    for (int s=0; s<segments; s++) {
        fs_rid_vector_sort(rv[s]);
        fs_rid_vector_uniq(rv[s], 0);
        res[s] = malloc(rv[s]->length * sizeof(fs_resource));
    }
    int ret = fsp_resolve_all(l, rv, res);
    if (ret) {
        fs_error(LOG_CRIT, "resolve_all failed");

        return 1;
    }

    g_static_mutex_lock(&cache_mutex);
    for (int s=0; s<segments; s++) {
        for (int i=0; i<rv[s]->length; i++) {
            if (res[s][i].rid == FS_RID_NULL) break;
            if (g_hash_table_lookup(res_l1_cache, &(res[s][i].rid))) {
                free(res[s][i].lex);
   
                continue;
            }
            fs_rid *trid = malloc(sizeof(fs_rid));
            fs_resource *tres = malloc(sizeof(fs_resource));
            *trid = res[s][i].rid;
            tres->rid = res[s][i].rid;
            tres->attr = res[s][i].attr;
            tres->lex = res[s][i].lex;
            g_hash_table_insert(res_l1_cache, trid, tres);
        }
    }
    g_static_mutex_unlock(&cache_mutex);

    for (int s=0; s<segments; s++) {
        free(res[s]);
    }

    return 0;
}

static int resolve_precache_all_with_stats(fs_query *q) {
    GTimer *tmr=NULL;
    if (q->qs->verbosity || q->qs->cache_stats) tmr = g_timer_new();
    int res = resolve_precache_all(q->link, q->pending, q->segments);
    if (q->qs->verbosity || q->qs->cache_stats) {
        g_static_mutex_lock(&cache_mutex);
        if (q->qs->cache_stats) { /* for web stats the avg */
            gdouble acum = (q->qs->resolve_all_elapse *  q->qs->resolve_all_calls);
            q->qs->resolve_all_elapse = (acum + g_timer_elapsed(tmr,NULL))/
                                        (q->qs->resolve_all_calls+1);
        }
        else
            q->qs->resolve_all_elapse = g_timer_elapsed(tmr,NULL);
        q->qs->resolve_all_calls++;
        g_static_mutex_unlock(&cache_mutex);
        g_timer_destroy(tmr);
    }
    return res;
}

static raptor_term *slot_fill_from_rid(fs_query *q, fs_rid rid)
{
    fs_resource r;
    resolve(q, rid, &r);

    if (FS_IS_BNODE(rid)) {
            if (FS_SKOLEMIZE) {
                char tmp[256];
                sprintf(tmp,"%s%llx", fs_global_skolem_prefix, FS_BNODE_NUM(rid));
                return raptor_new_term_from_uri_string(q->qs->raptor_world, (unsigned char *)tmp);
            }
            else
                return raptor_new_term_from_blank(q->qs->raptor_world, (unsigned char *)r.lex+2);
    } else if (FS_IS_URI(rid)) {
        return raptor_new_term_from_uri_string(q->qs->raptor_world, (unsigned char *)r.lex);
    } else if (FS_IS_LITERAL(rid)) {
        raptor_uri *dt = NULL;
        char *tag = NULL;
        if (r.attr && r.attr != FS_RID_NULL) {
            fs_resource ar;
            resolve(q, r.attr, &ar);
            if (FS_IS_URI(r.attr)) {
                dt = raptor_new_uri(q->qs->raptor_world, (unsigned char *)ar.lex);
            } else {
                tag = ar.lex;
            }
        }
	return raptor_new_term_from_literal(q->qs->raptor_world, (unsigned char *)r.lex, dt, (unsigned char *)tag);
    }

    return raptor_new_term_from_blank(q->qs->raptor_world, (unsigned char *)"unknown");
}

static raptor_term *slot_fill(fs_query *q, rasqal_literal *l, fs_row *row)
{
    switch (l->type) {
    case RASQAL_LITERAL_URI:
	return raptor_new_term_from_uri(q->qs->raptor_world, l->value.uri);

    case RASQAL_LITERAL_BLANK:
    {
        fs_error(LOG_ERR,"freaking blank node");
        char *label = g_strdup_printf("%s_%d", l->string, q->row);
        raptor_term *term = raptor_new_term_from_blank(q->qs->raptor_world,
            (unsigned char *)label);
        g_free(label);

	return term;
    }

    case RASQAL_LITERAL_XSD_STRING:
    case RASQAL_LITERAL_UDT:
    case RASQAL_LITERAL_STRING:
    case RASQAL_LITERAL_BOOLEAN:
	return raptor_new_term_from_literal(q->qs->raptor_world,
            (unsigned char *)l->string, NULL, NULL);

    case RASQAL_LITERAL_INTEGER:
    case RASQAL_LITERAL_INTEGER_SUBTYPE:
    {
        raptor_uri *dt = raptor_new_uri(q->qs->raptor_world,
            (unsigned char *)XSD_INTEGER);
        raptor_term *term = raptor_new_term_from_literal(q->qs->raptor_world,
            l->string, dt, NULL);
        raptor_free_uri(dt);

	return term;
    }

    case RASQAL_LITERAL_DECIMAL:
    {
        raptor_uri *dt = raptor_new_uri(q->qs->raptor_world,
            (unsigned char *)XSD_DECIMAL);
        raptor_term *term = raptor_new_term_from_literal(q->qs->raptor_world,
            l->string, dt, NULL);
        raptor_free_uri(dt);

	return term;
    }

    case RASQAL_LITERAL_DOUBLE:
    case RASQAL_LITERAL_FLOAT:
    {
        raptor_uri *dt = raptor_new_uri(q->qs->raptor_world,
            (unsigned char *)XSD_DOUBLE);
        raptor_term *term = raptor_new_term_from_literal(q->qs->raptor_world,
            l->string, dt, NULL);
        raptor_free_uri(dt);

	return term;
    }

    case RASQAL_LITERAL_DATETIME:
    {
        raptor_uri *dt = raptor_new_uri(q->qs->raptor_world,
            (unsigned char *)XSD_DATETIME);
        raptor_term *term = raptor_new_term_from_literal(q->qs->raptor_world,
            l->string, dt, NULL);
        raptor_free_uri(dt);

	return term;
    }

#if RASQAL_VERSION >= 929
    case RASQAL_LITERAL_DATE:
    {
        raptor_uri *dt = raptor_new_uri(q->qs->raptor_world,
            (unsigned char *)XSD_DATE);
        raptor_term *term = raptor_new_term_from_literal(q->qs->raptor_world,
            l->string, dt, NULL);
        raptor_free_uri(dt);

	return term;
    }
#endif

    case RASQAL_LITERAL_VARIABLE:
    {
	fs_row *b = NULL;
	int col;
	for (col=0; row[col].name; col++) {
	    if (!strcmp((char *)l->value.variable->name, row[col].name)) {
		b = row+col;
                break;
	    }
	}
        if (!b) {
            fs_error(LOG_CRIT, "cannot find column in binding table");

            return raptor_new_term_from_blank(q->qs->raptor_world, (unsigned char *)"");
        }

        if (FS_IS_BNODE(b->rid)) {
            if(strcmp(b->lex, "NULL") == 0) {
                /* b->lex is the string "NULL", so return as is */
                return raptor_new_term_from_blank(q->qs->raptor_world, (unsigned char *)b->lex);
            }
            if (FS_SKOLEMIZE)
                return raptor_new_term_from_uri_string(q->qs->raptor_world, (unsigned char *)b->lex+2);
            else
                return raptor_new_term_from_blank(q->qs->raptor_world, (unsigned char *)b->lex+2);
        } else if (FS_IS_URI(b->rid)) {
            return raptor_new_term_from_uri_string(q->qs->raptor_world, (unsigned char *)b->lex);
        } else if (FS_IS_LITERAL(b->rid)) {
            raptor_uri *dt = NULL;
            const unsigned char *tag = NULL;
            if (b->dt) {
                dt = raptor_new_uri(q->qs->raptor_world, (unsigned char *)b->dt);
            }
            if (b->lang) {
                tag = (unsigned char *)b->lang;
            }
            return raptor_new_term_from_literal(q->qs->raptor_world, (unsigned char *)b->lex, dt, tag);
        } 
    }

    /* this should never happen */
    case RASQAL_LITERAL_PATTERN:
    case RASQAL_LITERAL_QNAME:
    case RASQAL_LITERAL_UNKNOWN:
        fs_error(LOG_CRIT, "fell through result handler");
        break;
    }

    return raptor_new_term_from_blank(q->qs->raptor_world, (unsigned char *)"unknown");
}

static void insert_slot_fill(fs_query *q, fs_rid *rid,
                             rasqal_literal *l, fs_row *row)
{
    fs_resource res = { FS_RID_NULL, NULL, FS_RID_NULL };
    switch (l->type) {
    case RASQAL_LITERAL_URI:
	res.lex = (char *)raptor_uri_as_string(l->value.uri);
        res.rid = fs_hash_uri(res.lex);
        res.attr = FS_RID_NULL;

        break;

    case RASQAL_LITERAL_BLANK:
        res.lex = g_strdup_printf("%s_%d", l->string, q->row);
       /* TODO this should be a bNode, but it's tricky to summon a bNode RID
         * from here */
        res.rid = fs_hash_uri(res.lex);
        res.attr = FS_RID_NULL;
        fs_query_add_freeable(q, res.lex);
	break;

    case RASQAL_LITERAL_XSD_STRING:
    case RASQAL_LITERAL_UDT:
    case RASQAL_LITERAL_STRING:
	res.lex = (char *)l->string;
        res.attr = 0;
        res.rid = fs_hash_literal(res.lex, res.attr);

	break;

    case RASQAL_LITERAL_BOOLEAN:
	res.lex = (char *)l->string;
        res.attr = fs_c.xsd_boolean;
        res.rid = fs_hash_literal(res.lex, res.attr);

	break;

    case RASQAL_LITERAL_INTEGER:
    case RASQAL_LITERAL_INTEGER_SUBTYPE:
	res.lex = (char *)l->string;
        res.attr = fs_c.xsd_integer;
        res.rid = fs_hash_literal(res.lex, res.attr);

	break;

    case RASQAL_LITERAL_DOUBLE:
	res.lex = (char *)l->string;
        res.attr = fs_c.xsd_double;
        res.rid = fs_hash_literal(res.lex, res.attr);

	break;

    case RASQAL_LITERAL_FLOAT:
	res.lex = (char *)l->string;
        res.attr = fs_c.xsd_float;
        res.rid = fs_hash_literal(res.lex, res.attr);

	break;

    case RASQAL_LITERAL_DECIMAL:
	res.lex = (char *)l->string;
        res.attr = fs_c.xsd_decimal;
        res.rid = fs_hash_literal(res.lex, res.attr);

	break;

    case RASQAL_LITERAL_DATETIME:
	res.lex = (char *)l->string;
        res.attr = fs_c.xsd_datetime;
        res.rid = fs_hash_literal(res.lex, res.attr);

	break;

#if RASQAL_VERSION >= 929
    case RASQAL_LITERAL_DATE:
	res.lex = (char *)l->string;
        res.attr = fs_c.xsd_date;
        res.rid = fs_hash_literal(res.lex, res.attr);

	break;
#endif

    case RASQAL_LITERAL_VARIABLE: {
	fs_row *b = NULL;
	for (int col=0; row[col].name; col++) {
	    if (!strcmp((char *)l->value.variable->name, row[col].name)) {
		b = row+col;
                break;
	    }
	}
	if (b == NULL || b->rid == FS_RID_NULL) {
	    *rid = FS_RID_NULL;

	    return;
	}
        *rid = b->rid;

	return;
    }

    /* this should never happen */
    case RASQAL_LITERAL_PATTERN:
    case RASQAL_LITERAL_QNAME:
    case RASQAL_LITERAL_UNKNOWN:
        *rid = FS_RID_NULL;

	return;
    }

    fsp_res_import(q->link, FS_RID_SEGMENT(res.rid, q->segments), 1, &res);
    *rid = res.rid;
}

/* NB row in this case must be the row in the binding structure, not the
 * incremental row number */
static int apply_constraints(fs_query *q, int row)
{
    for (int block=q->block; block >= 0; block--) {
	if (!(q->constraints[block])) continue;
        /* expressions that have been optimised out will be replaces with NULL,
         * so we have to be careful here */
	for (int c=0; c<raptor_sequence_size(q->constraints[block]); c++) {
	    rasqal_expression *e =
		raptor_sequence_get_at(q->constraints[block], c);
	    if (!e) continue;

	    fs_value v = fs_expression_eval(q, row, block, e);
#ifdef DEBUG_FILTER
            printf("FILTERs for B%d\n", block);
	    rasqal_expression_print(e, stdout);
	    printf(" -> ");
	    fs_value_print(v);
	    printf("\n");
#endif
	    if (v.valid & fs_valid_bit(FS_V_TYPE_ERROR) && v.lex) {
                /* only add a warning if it's not already in there */
                if (!q->warnings || !g_slist_find(q->warnings, v.lex)) {
		    q->warnings = g_slist_prepend(q->warnings, v.lex);
                }
	    }
	    fs_value result = fn_ebv(v);
	    if (result.valid & fs_valid_bit(FS_V_TYPE_ERROR) || !result.in) {
                return 0;
	    }
	}
    }

    return 1;
}

static int csv_needs_escape(const char *str, int *escaped_length)
{
    int esc_len = 0;
    int escape = 0;

    if (!str) return 0;

    for (const char *c = str; *c; c++) {
        switch (*c) {
        case '"':
            esc_len += 2;
            escape = 1;
            break;
        case ',':
        case '\r':
        case '\n':
            esc_len += 1;
            escape = 1;
            break;
        default:
            esc_len += 1;
        }
    }
    if (escape) {
        esc_len += 2;
    }
    *escaped_length = esc_len;

    return escape;
}

static char *csv_escape(const char *str, int length)
{
    char *to = malloc(length+1);
    char *outp = to;

    *outp++ = '"';
    for (const char *inp = str; *inp; inp++) {
        switch (*inp) {
        case '"':
            *outp++ = '"';
            *outp++ = '"';
            break;
        default:
            *outp++ = *inp;
            break;
        }
    }
    *outp++ = '"';
    *outp = '\0';

    return to;
}

static int uri_needs_escape(const char *str, int *escaped_length)
{
    int esc_len = 0;
    int escape = 0;

    if (!str) return 0;

    for (const char *c = str; *c; c++) {
        switch (*c) {
        case ' ':
        case '\t':
        case '\r':
        case '\n':
        case '<':
        case '>':
            esc_len += 3;
            escape = 1;
            break;
        default:
            esc_len += 1;
        }
    }
    *escaped_length = esc_len;

    return escape;
}

static char *uri_escape(const char *str, int length)
{
    char *to = malloc(length+1);
    char *outp = to;

    for (const char *inp = str; *inp; inp++) {
        switch (*inp) {
        case ' ':
            *outp++ = '%';
            *outp++ = '2';
            *outp++ = '0';
            break;
        case '\t':
            *outp++ = '%';
            *outp++ = '0';
            *outp++ = '9';
            break;
        case '\n':
            *outp++ = '%';
            *outp++ = '0';
            *outp++ = 'A';
            break;
        case '\r':
            *outp++ = '%';
            *outp++ = '0';
            *outp++ = 'D';
            break;
        case '<':
            *outp++ = '%';
            *outp++ = '3';
            *outp++ = 'C';
            break;
        case '>':
            *outp++ = '%';
            *outp++ = '3';
            *outp++ = 'E';
            break;
        default:
            *outp++ = *inp;
            break;
        }
    }
    *outp = '\0';

    return to;
}

char *fs_uri_escape(const char *str)
{
    int esclen;
    if (uri_needs_escape(str, &esclen)) {
        return uri_escape(str, esclen);
    }

    return g_strdup(str);
}

static int tsv_needs_escape(const char *str, int *escaped_length)
{
    int esc_len = 0;
    int escape = 0;

    if (!str) return 0;

    for (const char *c = str; *c; c++) {
        switch (*c) {
        case '\\':
        case '\t':
        case '\r':
        case '\n':
        case '"':
            esc_len += 2;
            escape = 1;
            break;
        default:
            esc_len += 1;
        }
    }
    *escaped_length = esc_len;

    return escape;
}

static char *tsv_escape(const char *str, int length)
{
    char *to = malloc(length+1);
    char *outp = to;

    for (const char *inp = str; *inp; inp++) {
        switch (*inp) {
        case '\t':
            *outp++ = '\\';
            *outp++ = 't';
            break;
        case '\r':
            *outp++ = '\\';
            *outp++ = 'r';
            break;
        case '\n':
            *outp++ = '\\';
            *outp++ = 'n';
            break;
        case '\\':
        case '"':
            *outp++ = '\\';
            *outp++ = *inp;
            break;
        default:
            *outp++ = *inp;
            break;
        }
    }
    *outp = '\0';

    return to;
}

static int json_needs_escape(const char *str, int *escaped_length)
{
    int esc_len = 0;
    int escape = 0;

    if (!str) return 0;

    for (const char *c = str; *c; c++) {
        switch (*c) {
        case '\\':
        case '\t':
        case '\r':
        case '\n':
        case '"':
            esc_len += 2;
            escape = 1;
            break;
        default:
            esc_len += 1;
        }
    }
    *escaped_length = esc_len;

    return escape;
}

static char *json_escape(const char *str, int length)
{
    char *to = malloc(length+1);
    char *outp = to;

    for (const char *inp = str; *inp; inp++) {
        switch (*inp) {
        case '\t':
            *outp++ = '\\';
            *outp++ = 't';
            break;
        case '\r':
            *outp++ = '\\';
            *outp++ = 'r';
            break;
        case '\n':
            *outp++ = '\\';
            *outp++ = 'n';
            break;
        case '\\':
        case '"':
            *outp++ = '\\';
            *outp++ = *inp;
            break;
        default:
            *outp++ = *inp;
            break;
        }
    }
    *outp = '\0';

    return to;
}

static int is_xml_restricted(int c) {
    /* RestrictedSet from http://www.w3.org/TR/xml11/#charsets */
    if ((c >= 0x01 && c <= 0x08) ||
        (c >= 0x0b && c <= 0x0c) ||
        (c >= 0x0e && c <= 0x1f) ||
        (c >= 0x7f && c <= 0x84) ||
        (c >= 0x86 && c <= 0x9f)) {
        return 1;
    }

    return 0;
}

static int xml_needs_escape(const char *str, int *escaped_length)
{
    int esc_len = 0;
    int escape = 0;

    if (!str) return 0;

    for (const char *c = str; *c; c++) {
	if (*c == '<') {
            esc_len += 4;
            escape = 1;
        } else if (*c == '>') {
            esc_len += 4;
            escape = 1;
        } else if (*c == '&') {
            esc_len += 5;
            escape = 1;
        } else if (is_xml_restricted(*c)) {
            escape = 1;
        } else {
            esc_len++;
	}
    }

    *escaped_length = esc_len;

    return escape;
}

static char *xml_escape(const char *from, int len)
{
    char *to = malloc(len+1);
    char *outp = to;

    for (const char *inp = from; *inp; inp++) {
	if (*inp == '<') {
            strcpy(outp, "&lt;");
            outp += 4;
        } else if (*inp == '>') {
            strcpy(outp, "&gt;");
            outp += 4;
        } else if (*inp == '&') {
            strcpy(outp, "&amp;");
            outp += 5;
        } else if (is_xml_restricted(*inp)) {
            /* skip, these aren't legal in XML */
        } else {
            *outp++ = *inp;
	}
    }

    *outp++ = '\0';

    return to;
}

/* must be called with rasqal_mutex held if multithreaded */

static void describe_uri(fs_query *q, fs_rid rid, raptor_uri *uri)
{
    if (rid == FS_RID_NULL) {
        if (uri) {
            rid = fs_hash_uri((char *)raptor_uri_as_string(uri));
        }
    }
    raptor_statement st;
    raptor_statement_init(&st, q->qs->raptor_world);
    st.graph = NULL;
    fs_rid_vector *es = fs_rid_vector_new(0);
    fs_rid_vector *ss = fs_rid_vector_new_from_args(1, rid);
    fs_rid_vector *gs = es;
    if (q->default_graphs) {
        gs = q->default_graphs;
    }
    fs_rid_vector **result = NULL;
    fsp_bind_limit(q->link, FS_RID_SEGMENT(rid, q->segments),
        FS_BIND_BY_SUBJECT | FS_BIND_PREDICATE | FS_BIND_OBJECT, gs, ss,
        es, es, &result, 0, q->soft_limit);
    fs_rid_vector_free(es);
    fs_rid_vector_free(ss);
    raptor_term *subject;
    if (FS_IS_BNODE(rid)) {
        if (uri) {
            subject = raptor_new_term_from_blank(q->qs->raptor_world,
                raptor_uri_as_string(uri));
        } else {
            char tmp[256];
            if (FS_SKOLEMIZE)
                sprintf(tmp,"%s%llx", fs_global_skolem_prefix, FS_BNODE_NUM(rid));
            else
                sprintf(tmp, "b%016llx", rid);
            subject = raptor_new_term_from_blank(q->qs->raptor_world, (unsigned char *)tmp);
        }
    } else {
        subject = raptor_new_term_from_uri(q->qs->raptor_world, uri);
    }
    for (int row = 0; row < result[0]->length; row++) {
        st.subject = subject;
        st.predicate = slot_fill_from_rid(q, result[0]->data[row]);
        st.object = slot_fill_from_rid(q, result[1]->data[row]);
        raptor_serializer_serialize_statement(q->ser, &st);
        raptor_free_term(st.predicate);
        raptor_free_term(st.object);
    }
    raptor_free_term(subject);
    for (int col=0; col<2; col++) {
        fs_rid_vector_free(result[col]);
    }
    free(result);
}

static void handle_describe(fs_query *q, const char *type, FILE *output)
{
    g_static_mutex_lock(&rasqal_mutex);
    q->ser = raptor_new_serializer(q->qs->raptor_world, type);
    if (!q->ser) {
        fs_error(LOG_ERR, "no such serialiser '%s'", type);
        g_static_mutex_unlock(&rasqal_mutex);

        return;
    }
    for (int i=0; 1; i++) {
        rasqal_prefix *p = rasqal_query_get_prefix(q->rq, i);
        if (!p) break;
        raptor_serializer_set_namespace(q->ser, p->uri, p->prefix);
    }
    raptor_serializer_start_to_file_handle(q->ser, q->base, output);

    fs_p_vector *vars = fs_p_vector_new(0);
    raptor_sequence *desc = rasqal_query_get_describe_sequence(q->rq);
    for (int i=0; 1; i++) {
        rasqal_literal *l = raptor_sequence_get_at(desc, i);
        if (!l) break;
        if (l->type == RASQAL_LITERAL_URI) {
            describe_uri(q, FS_RID_NULL, l->value.uri);
        } else if (l->type == RASQAL_LITERAL_VARIABLE) {
            fs_p_vector_append(vars, l);
        }
    }

    fs_row *row;
    fs_rid_set *described_uris = fs_rid_set_new();
    while ((row = fs_query_fetch_row(q))) {
        for (int i=0; i<vars->length; i++) {
            if (!fs_rid_set_contains(described_uris, row[i].rid)) {
                raptor_term *dterm = slot_fill(q, vars->data[i], row);
                /* can only describe URIs or bNodes */
                if (dterm->type == RAPTOR_TERM_TYPE_URI) {
                    describe_uri(q, row[i].rid, dterm->value.uri);
                } else if (dterm->type == RAPTOR_TERM_TYPE_BLANK) {
                    describe_uri(q, row[i].rid, NULL);
                }
                fs_rid_set_add(described_uris, row[i].rid);
                raptor_free_term(dterm);
            }
        }
    }
    fs_rid_set_free(described_uris);
    raptor_serializer_serialize_end(q->ser);
    raptor_free_serializer(q->ser);
    g_static_mutex_unlock(&rasqal_mutex);
    fs_p_vector_free(vars);
}

static void handle_construct(fs_query *q, const char *type, FILE *output)
{
    const int cols = fs_query_get_columns(q);
    fs_row *row;
    fs_rid quad[4] = { FS_RID_NULL, FS_RID_NULL, FS_RID_NULL,
                       FS_RID_NULL };

    if (q->flags & FS_RESULT_FLAG_CONSTRUCT_AS_INSERT) {
        fsp_start_import_all(q->link);
        quad[0] = fs_hash_uri((char *)raptor_uri_as_string(q->base));
        fs_resource model = { .rid = quad[0],
                              .lex = (char *)raptor_uri_as_string(q->base),
                              .attr = FS_RID_NULL };
        fsp_res_import(q->link, FS_RID_SEGMENT(quad[0], q->segments), 1,
                       &model);
        fs_rid_vector *models = fs_rid_vector_new(1);
        models->data[0] = quad[0];
        fsp_new_model_all(q->link, models);
    } else {
        g_static_mutex_lock(&rasqal_mutex);
        q->ser = raptor_new_serializer(q->qs->raptor_world, type);
        for (int i=0; 1; i++) {
            rasqal_prefix *p = rasqal_query_get_prefix(q->rq, i);
            if (!p) break;
            raptor_serializer_set_namespace(q->ser, p->uri, p->prefix);
        }
        raptor_serializer_start_to_file_handle(q->ser, q->base, output);
        g_static_mutex_unlock(&rasqal_mutex);
    }

    while ((row = fs_query_fetch_row(q))) {
        if (q->flags & FS_RESULT_FLAG_CONSTRUCT_AS_INSERT) {
            for (int i=0; 1; i++) {
                rasqal_triple *trip =
                   rasqal_query_get_construct_triple(q->rq, i);
                if (!trip) break;

                insert_slot_fill(q, quad+1, trip->subject, row);
                insert_slot_fill(q, quad+2, trip->predicate, row);
                insert_slot_fill(q, quad+3, trip->object, row);
                fsp_quad_import(q->link, FS_RID_SEGMENT(quad[1], q->segments), FS_BIND_BY_SUBJECT, 1, &quad);
            }
        } else {
            g_static_mutex_lock(&rasqal_mutex);
            raptor_statement st;
            raptor_statement_init(&st, q->qs->raptor_world);
            st.graph = NULL;

            for (int i=0; 1; i++) {
                rasqal_triple *trip =
                   rasqal_query_get_construct_triple(q->rq, i);
                if (!trip) break;

                st.subject = slot_fill(q, trip->subject, row);
                st.predicate = slot_fill(q, trip->predicate, row);
                st.object = slot_fill(q, trip->object, row);

                int skip = 0;

                if (st.object->type == RAPTOR_TERM_TYPE_BLANK && strcmp((char *)st.object->value.blank.string, "NULL") == 0) {
                    /* bnodes with an id of "NULL" should not be rendered */
                    skip = 1;
                } else if (st.subject->type != RAPTOR_TERM_TYPE_URI &&
                           st.subject->type != RAPTOR_TERM_TYPE_BLANK) {
                    /* subjects muse be URIs or bNodes */
                    skip = 1;
                } else if (st.predicate->type != RAPTOR_TERM_TYPE_URI) {
                    /* predicates must be URIs */
                    skip = 1;
                }

                if (skip) {
                    raptor_free_term(st.subject);
                    raptor_free_term(st.predicate);
                    raptor_free_term(st.object);
                    continue;
                }

                raptor_serializer_serialize_statement(q->ser, &st);
                raptor_free_term(st.subject);
                raptor_free_term(st.predicate);
                raptor_free_term(st.object);
            }
            g_static_mutex_unlock(&rasqal_mutex);
        }
    }

    /* if were CONSTRUCTing a constant expression, and the query is true */
    if (cols == 0 && q->boolean) {
        if (q->flags & FS_RESULT_FLAG_CONSTRUCT_AS_INSERT) {
            for (int i=0; 1; i++) {
                rasqal_triple *trip =
                   rasqal_query_get_construct_triple(q->rq, i);
                if (!trip) break;

                insert_slot_fill(q, quad+1, trip->subject, row);
                insert_slot_fill(q, quad+2, trip->predicate, row);
                insert_slot_fill(q, quad+3, trip->object, row);
                fsp_quad_import(q->link, FS_RID_SEGMENT(quad[1], q->segments), FS_BIND_BY_SUBJECT, 1, &quad);
            }
        } else {
            raptor_statement st;
            raptor_statement_init(&st, q->qs->raptor_world);
            st.graph = NULL;

            for (int i=0; 1; i++) {
                rasqal_triple *trip =
                   rasqal_query_get_construct_triple(q->rq, i);
                if (!trip) break;

                st.subject = slot_fill(q, trip->subject, row);
                st.predicate = slot_fill(q, trip->predicate, row);
                st.object = slot_fill(q, trip->object, row);
                raptor_serializer_serialize_statement(q->ser, &st);
                raptor_free_term(st.subject);
                raptor_free_term(st.predicate);
                raptor_free_term(st.object);
            }
        }
    }

    if (q->flags & FS_RESULT_FLAG_CONSTRUCT_AS_INSERT) {
        for (fs_segment s=0; s<q->segments; s++) {
            fsp_res_import_commit(q->link, s);
            fsp_quad_import_commit(q->link, s, FS_BIND_BY_SUBJECT);
        }
        fsp_stop_import_all(q->link);
    } else {
        g_static_mutex_lock(&rasqal_mutex);
        raptor_serializer_serialize_end(q->ser);
        raptor_free_serializer(q->ser);
        g_static_mutex_unlock(&rasqal_mutex);
    }
}

static void output_sparql(fs_query *q, int flags, FILE *out)
{
    if (!q) return;

    if (flags & FS_RESULT_FLAG_HEADERS) {
	if (q->construct || q->describe) {
	    fprintf(out, "Content-Type: application/rdf+xml; charset=utf-8\r\n\r\n");
	} else {
	    fprintf(out, "Content-Type: application/sparql-results+xml\r\n\r\n");
	}
    }

    fs_row *row;
    int cols = fs_query_get_columns(q);
    if (q->construct) {
        handle_construct(q, "rdfxml", out);
    } else if (q->describe) {
        handle_describe(q, "rdfxml", out);
    } else {
	/* XML output */

	fprintf(out, "<?xml version=\"1.0\"?>\n"
		"<sparql xmlns=\"http://www.w3.org/2005/sparql-results#\">\n");
	row = fs_query_fetch_header_row(q);
	fprintf(out, "  <head>\n");
	for (int c=0; c<cols; c++) {
	    fprintf(out, "    <variable name=\"%s\"/>\n", row[c].name);
	}
	fprintf(out, "  </head>\n");
        if (q->warnings) {
            GSList *it;
            for (it = q->warnings; it; it = it->next) {
                int esc_len;
		if (xml_needs_escape(it->data, &esc_len)) {
		    char *lex = xml_escape(it->data, esc_len);
                    fprintf(out, "<!-- %s -->\n", lex);
                    free(lex);
                } else {
                    fprintf(out, "<!-- %s -->\n", (char *)it->data);
                }
            }
            g_slist_free(q->warnings);
            q->warnings = NULL;
        }
        if (q->ask) {
            while (q->boolean && fs_query_fetch_row(q));
            if (q->boolean) {
                fprintf(out, "  <boolean>true</boolean>\n");
            } else {
                fprintf(out, "  <boolean>false</boolean>\n");
            }
        } else {
            fprintf(out, "  <results>\n");
            while ((!row || !row->stop) && (row = fs_query_fetch_row(q))) {
                fprintf(out, "    <result>\n");
                for (int c=0; c<cols; c++) {
                    int esc_len;
                    char *lex;
                    int need_free = 0;
                    if (xml_needs_escape(row[c].lex, &esc_len)) {
                        lex = xml_escape(row[c].lex, esc_len);
                        need_free = 1;
                    } else {
                        lex = (char *)row[c].lex;
                    }
                    if (row[c].type == FS_TYPE_NONE) continue;
                    fprintf(out, "      <binding name=\"%s\">", row[c].name);
                    switch (row[c].type) {
                        case FS_TYPE_NONE:
                            break;
                        case FS_TYPE_URI:
                            fprintf(out, "<uri>%s</uri>", lex);
                            break;
                        case FS_TYPE_LITERAL:
                            if (row[c].lang) {
                                fprintf(out, "<literal xml:lang=\"%s\">%s</literal>", row[c].lang, lex);
                            } else if (row[c].dt) {
                                fprintf(out, "<literal datatype=\"%s\">%s</literal>", row[c].dt, lex);
                            } else {
                                fprintf(out, "<literal>%s</literal>", lex);
                            }
                            break;
                        case FS_TYPE_BNODE:
                            fprintf(out, "<bnode>%s</bnode>", lex+2);
                    }
                    fprintf(out, "</binding>\n");
                    if (need_free) {
                        free(lex);
                    }
                }
                fprintf(out, "    </result>\n");
            }
            fprintf(out, "  </results>\n");
        }
        if (q->warnings) {
            GSList *it;
            char *last = NULL;
            for (it = q->warnings; it; it = it->next) {
                if (it->data == last) continue;
                last = it->data;
                int esc_len;
                if (xml_needs_escape(it->data, &esc_len)) {
                    char *lex = xml_escape(it->data, esc_len);
                    fprintf(out, "<!-- warning: %s -->\n", lex);
                    free(lex);
                } else {
                    fprintf(out, "<!-- warning: %s -->\n", (char *)it->data);
                }
            }
        }
        fprintf(out, "</sparql>\n");
    }
}

static void output_text(fs_query *q, int flags, FILE *out)
{
    if (!q) return;

    if (flags & FS_RESULT_FLAG_HEADERS) {
	if (q->construct) {
	    fprintf(out, "Content-Type: text/turtle; charset=utf-8\r\n\r\n");
	} else {
	    fprintf(out, "Content-Type: text/tab-separated-values; charset=utf-8\r\n\r\n");
	}
    }

    if (q->ask) {
        while (q->boolean && fs_query_fetch_row(q));
        if (q->boolean) {
            fprintf(out, "true\n");
        } else {
            fprintf(out, "false\n");
        }

        return;
    }

    if (q->describe) {
        handle_describe(q, "turtle", out);

        return;
    }

    fs_row *row=NULL;

    int cols = fs_query_get_columns(q);
    if (!q->construct) {
	row = fs_query_fetch_header_row(q);
	for (int i=0; i<cols; i++) {
	    if (i) fputc('\t', out);
	    fprintf(out, "?%s", row[i].name);
	}
	fprintf(out, "\n");
    }

    if (q->warnings) {
        GSList *it;
        for (it = q->warnings; it; it = it->next) {
            if (it->data) {
                fprintf(out, "# %s\n", (char *)it->data);
            } else {
                fs_error(LOG_ERR, "found NULL warning");
            }
        }
        g_slist_free(q->warnings);
        q->warnings = NULL;
    }

    if (q->construct) {
        handle_construct(q, "ntriples", out);
    } else {
	while ((!row || !row->stop) && (row = fs_query_fetch_row(q))) {
	    for (int c=0; c<cols; c++) {
		int esclen = 0;
		char *escd = NULL;
		const char *lex = row[c].lex;
		if (c) fputc('\t', out);
		switch (row[c].type) {
		    case FS_TYPE_NONE:
			//fprintf(out, "NULL");
			break;
		    case FS_TYPE_URI:
                        if (uri_needs_escape(row[c].lex, &esclen)) {
                            escd = uri_escape(row[c].lex, esclen);
                            lex = escd;
                        }
			fprintf(out, "<%s>", lex);
                        if (escd) free(escd);
			break;
		    case FS_TYPE_LITERAL:
                        if (tsv_needs_escape(row[c].lex, &esclen)) {
                            escd = tsv_escape(row[c].lex, esclen);
                            lex = escd;
                        }
                        if (row[c].lang) {
			    fprintf(out, "\"%s\"@%s", lex, row[c].lang);
                        } else if (row[c].dt) {
                            if (!strcmp(row[c].dt, XSD_INTEGER)) {
                                fprintf(out, "%s", lex);
                            } else if (!strcmp(row[c].dt, XSD_DECIMAL)) {
                                if (strchr(lex, '.')) {
                                    fprintf(out, "%s", lex);
                                } else {
                                    fprintf(out, "%s.0", lex);
                                }
                            } else if (!strcmp(row[c].dt, XSD_DOUBLE)) {
                                if (*lex && (strchr(lex, 'e') ||
                                    !strcmp(lex, "-inf") ||
                                    !strcmp(lex, "inf"))) {
                                    fprintf(out, "%s", lex);
                                } else {
                                    fprintf(out, "%se0", lex);
                                }
                            } else {
                                fprintf(out, "\"%s\"^^<%s>", lex, row[c].dt);
                            }
                        } else {
			    fprintf(out, "\"%s\"", lex);
                        }
                        if (escd) free(escd);
			break;
		    case FS_TYPE_BNODE:
			fprintf(out, "%s", row[c].lex);
		}
	    }
	    fprintf(out, "\n");
	}
    }

    if (q->warnings) {
        GSList *it;
        for (it = q->warnings; it; it = it->next) {
            if (it->data) {
                fprintf(out, "# %s\n", (char *)it->data);
            } else {
                fs_error(LOG_ERR, "found NULL warning");
            }
        }
        g_slist_free(q->warnings);
        q->warnings = NULL;
    }
}

static void output_csv(fs_query *q, int flags, FILE *out)
{
    if (!q) return;

    if (flags & FS_RESULT_FLAG_HEADERS) {
	if (q->construct) {
	    fprintf(out, "Content-Type: text/turtle; charset=utf-8\r\n\r\n");
	} else {
	    fprintf(out, "Content-Type: text/csv; charset=utf-8; header=present\r\n\r\n");
	}
    }

    if (q->ask) {
        while (q->boolean && fs_query_fetch_row(q));
        if (q->boolean) {
            fprintf(out, "ask\r\ntrue\r\n");
        } else {
            fprintf(out, "ask\r\nfalse\r\n");
        }

        return;
    }

    if (q->describe) {
        handle_describe(q, "turtle", out);

        return;
    }

    fs_row *row=NULL;

    int cols = fs_query_get_columns(q);
    if (!q->construct) {
	row = fs_query_fetch_header_row(q);
	for (int i=0; i<cols; i++) {
	    if (i) fputc(',', out);
	    fprintf(out, "%s", row[i].name);
	}
	fprintf(out, "\r\n");
    }

    if (q->warnings) {
        GSList *it;
        for (it = q->warnings; it; it = it->next) {
            if (it->data) {
                fprintf(out, "# %s\r\n", (char *)it->data);
            } else {
                fs_error(LOG_ERR, "found NULL warning");
            }
        }
        g_slist_free(q->warnings);
        q->warnings = NULL;
    }

    if (q->construct) {
        handle_construct(q, "ntriples", out);
    } else {
	while ((!row || !row->stop) && (row = fs_query_fetch_row(q))) {
	    for (int c=0; c<cols; c++) {
		int esclen = 0;
		char *escd = NULL;
		const char *lex = row[c].lex;
		if (c) fputc(',', out);
		switch (row[c].type) {
		    case FS_TYPE_NONE:
			//fprintf(out, "NULL");
			break;
		    case FS_TYPE_URI:
                        if (csv_needs_escape(row[c].lex, &esclen)) {
                            escd = uri_escape(row[c].lex, esclen);
                            lex = escd;
                        }
			fprintf(out, "%s", lex);
                        if (escd) free(escd);
			break;
		    case FS_TYPE_LITERAL:
                        if (csv_needs_escape(row[c].lex, &esclen)) {
                            escd = csv_escape(row[c].lex, esclen);
                            lex = escd;
                        }
                        fprintf(out, "%s", lex);
                        if (escd) free(escd);
			break;
		    case FS_TYPE_BNODE:
			fprintf(out, "%s", row[c].lex);
		}
	    }
	    fprintf(out, "\r\n");
	}
    }

    if (q->warnings) {
        GSList *it;
        for (it = q->warnings; it; it = it->next) {
            if (it->data) {
                fprintf(out, "# %s\r\n", (char *)it->data);
            } else {
                fs_error(LOG_ERR, "found NULL warning");
            }
        }
        g_slist_free(q->warnings);
        q->warnings = NULL;
    }
}

static void output_json(fs_query *q, int flags, FILE *out)
{
    if (!q) return;

    if (flags & FS_RESULT_FLAG_HEADERS) {
	if (q->construct) {
	    fprintf(out, "Content-Type: text/turtle; charset=utf-8\r\n\r\n");
	} else {
	    fprintf(out, "Content-Type: application/sparql-results+json\r\n\r\n");
	}
    }

    if (q->construct) {
        if (q->warnings) {
            GSList *it;
            for (it = q->warnings; it; it = it->next) {
                fprintf(out, "# %s\n", (char *)it->data);
            }
            g_slist_free(q->warnings);
            q->warnings = NULL;
        }
        handle_construct(q, "ntriples", out);
        if (q->warnings) {
            GSList *it;
            for (it = q->warnings; it; it = it->next) {
                fprintf(out, "# %s\n", (char *)it->data);
            }
            g_slist_free(q->warnings);
            q->warnings = NULL;
        }

        return;
    } else if (q->describe) {
        if (q->json_function) {
            fprintf(out, "%s(", q->json_function);
        }
        handle_describe(q, "json", out);
        if (q->json_function) {
            fprintf(out, ");");
        }

        return;
    }

    const int cols = fs_query_get_columns(q);

    fs_row *row, *header;
    row = header = fs_query_fetch_header_row(q);
    if (q->json_function) {
        fprintf(out, "%s(", q->json_function);
    }
    fprintf(out, "{\"head\":{\"vars\":[");
    for (int i=0; i<cols; i++) {
        if (i) fputs(",", out);
        fprintf(out, "\"%s\"", header[i].name);
    }
    fprintf(out, "]},\n");

    if (q->ask) {
        while (q->boolean && fs_query_fetch_row(q));
        if (q->boolean) {
            fprintf(out, "\"boolean\": true");
        } else {
            fprintf(out, "\"boolean\": false");
        }
    } else {
        fprintf(out, " \"results\": {\n");
        fprintf(out, "  \"bindings\":[");
        int rownum = 0;
        while ((!row || !row->stop) && (row = fs_query_fetch_row(q))) {
            if (rownum++ > 0) {
                fprintf(out, ",\n");
            } else {
                fprintf(out, "\n");
            }
            fprintf(out, "   {");
            for (int c=0; c<cols; c++) {
                if (c) fputs(",\n    ", out);
                fprintf(out, "\"%s\":{", header[c].name);
                int esclen = 0;
                char *escd = NULL;
                const char *lex = row[c].lex;
                switch (row[c].type) {
                    case FS_TYPE_NONE:
                        break;
                    case FS_TYPE_URI:
                        if (json_needs_escape(row[c].lex, &esclen)) {
                            escd = json_escape(row[c].lex, esclen);
                            lex = escd;
                        }
                        fprintf(out, "\"type\":\"uri\",\"value\":\"%s\"", lex);
                        if (escd) free(escd);
                        break;
                    case FS_TYPE_LITERAL:
                        if (json_needs_escape(row[c].lex, &esclen)) {
                            escd = json_escape(row[c].lex, esclen);
                            lex = escd;
                        }
                        if (row[c].lang) {
                            fprintf(out, "\"type\":\"literal\",\"value\":\"%s\",\"xml:lang\":\"%s\"", lex, row[c].lang);
                        } else if (row[c].dt) {
                            fprintf(out, "\"type\":\"literal\",\"value\":\"%s\",\"datatype\":\"%s\"", lex, row[c].dt);
                        } else {
                            fprintf(out, "\"type\":\"literal\",\"value\":\"%s\"", lex);
                        }
                        if (escd) free(escd);
                        break;
                    case FS_TYPE_BNODE:
                        fprintf(out, "\"type\":\"bnode\",\"value\":\"%s\"", row[c].lex + 2);
                }
                fputs("}", out);
            }
            fputs("}", out);
        }
        if (rownum) {
            fputs("\n  ", out);
        }
        fprintf(out, "]\n }");
    }

    if (q->warnings) {
        fprintf(out, ",\n \"warnings\": [");
        GSList *it;
        for (it = q->warnings; it; it = it->next) {
            char *text = it->data;
            char *escd = NULL;
            int esclen = 0;
            if (json_needs_escape(text, &esclen)) {
                escd = json_escape(text, esclen);
                text = escd;
            }
            fprintf(out, "\"%s\"", text);
            if (it->next)
                fprintf(out, ",\n");

            if (escd) free(escd);
        }
        g_slist_free(q->warnings);
        q->warnings = NULL;
        fprintf(out, "]\n");
    }

    if (q->json_function) {
        fprintf(out, "});\n");
    } else {
        fprintf(out, "}\n");
    }
}

static void output_testcase(fs_query *q, int flags, FILE *out)
{
    if (!q) return;

    if (q->errors) {
        if (q->warnings) {
            GSList *p = q->warnings;
            while (p) {
                fprintf(stderr, "# %s\n", (char *)p->data);
                p = p->next;
            }
        }

        return;
    }

    if (q->construct) {
	output_text(q, flags, out);

	return;
    } else if (q->describe) {
        handle_describe(q, "turtle", out);

        return;
    }

    if (flags & FS_RESULT_FLAG_HEADERS) {
	fprintf(out, "Content-Type: text/turtle; charset=utf-8\r\n\r\n");
    }
    fprintf(out, "@prefix rs: <http://www.w3.org/2001/sw/DataAccess/tests/result-set#> .\n");
    fprintf(out, "@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .\n");
    fprintf(out, "@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .\n");
    if (q->warnings) {
	GSList *p = q->warnings;
	while (p) {
	    fprintf(out, "# %s\n", (char *)p->data);
	    p = p->next;
	}
    }
    fs_row *row;
    int cols = fs_query_get_columns(q);
    fprintf(out, "\n[] rdf:type rs:ResultSet ;\n");
    if (q->num_vars > 0) {
	fprintf(out, "   rs:resultVariable ");
	row = fs_query_fetch_header_row(q);
	for (int c=0; c<cols; c++) {
	    if (c > 0) fprintf(out, ", ");
	    fprintf(out, "\"%s\"", row[c].name);
	}
    } else {
        /* apply the filters until we find one that matches or run out of
         * rows */
        while (q->boolean && fs_query_fetch_row(q));
        if (q->boolean) {
            fprintf(out, "   rs:boolean \"true\"^^xsd:boolean .\n");
        } else {
            fprintf(out, "   rs:boolean \"false\"^^xsd:boolean .\n");
        }

        return;
    }

    while ((!row || !row->stop) && (row = fs_query_fetch_row(q))) {
	fprintf(out, " ;\n   rs:solution [\n");
        if (q->ordering) {
            static int index = 0;
            fprintf(out, "      rs:index %d ;\n", ++index);
        }

	int count = 0;
	for (int c=0; c<cols; c++) {
	    if (row[c].type == FS_TYPE_NONE) continue;

	    if (count++ > 0) fprintf(out, " ;\n");

	    fprintf(out, "      rs:binding [ rs:variable \"%s\" ;\n", row[c].name);
	    switch (row[c].type) {
		case FS_TYPE_NONE:
		    break;
		case FS_TYPE_URI:
		    fprintf(out, "                   rs:value <%s> ]", row[c].lex);
		    break;
		case FS_TYPE_LITERAL:
		    if (row[c].lang) {
			fprintf(out, "                   rs:value \"%s\"@%s ]", row[c].lex, row[c].lang);
		    } else if (row[c].dt) {
			fprintf(out, "                   rs:value \"%s\"^^<%s> ]", row[c].lex, row[c].dt);
		    } else {
			fprintf(out, "                   rs:value \"%s\" ]", row[c].lex);
		    }
		    break;
		case FS_TYPE_BNODE:
		    fprintf(out, "                   rs:value %s ]", row[c].lex);
	    }
	}
	fprintf(out, "\n   ]");
    }

    fprintf(out, " .\n");
}

int fs_query_get_columns(fs_query *q)
{
    if (!q) return 0;

    return q->num_vars;
}

fs_row *fs_query_fetch_header_row(fs_query *q)
{
    if (!q->resrow) {
	q->resrow = calloc(q->num_vars + 1, sizeof(fs_row));
	for (int col=0; col < q->num_vars; col++) {
	    q->resrow[col].name = q->bb[0][col+1].name;
	}
    }

    return q->resrow;
}

/* call with mutex held only, pushed L1 cache entry into L2 */
static gboolean cache_dump(gpointer key, gpointer value, gpointer user_data)
{
    fs_resource *res = value;

    free(key);
    const int cpos = res->rid & CACHE_MASK;
    if (res_l2_cache[cpos].lex) {
        free(res_l2_cache[cpos].lex);
    }
    res_l2_cache[cpos] = *res;
    free(res);

    return 1;
}

static void prefetch_lexical_data(fs_query *q, long int next_row,const int rows) {

    /* ms8: aggregates prefetch everything in one go */
    if (q->aggregate > 2)
        return;
    if (q->aggregate) q->aggregate = 3; 

    for (int i=0; i<q->segments; i++) {
        fs_rid_vector_clear(q->pending[i]);
    }

    /* dump L1 cache into L2 */
    g_static_mutex_lock(&cache_mutex);
    if (res_l1_cache) g_hash_table_foreach_steal(res_l1_cache, cache_dump, NULL);

    int lookup_buffer_size = RESOURCE_LOOKUP_BUFFER;
    if (q->limit > 0 && q->limit < RESOURCE_LOOKUP_BUFFER) {
        lookup_buffer_size = q->limit * 2;
    }

    unsigned int pre_cache_len = 0;
    if (q->aggregate) {
        /* in case this is an aggregate we need to cache all of it
        because next_row has been moved to the last solution
        TODO: all RIDs are cached in one go */
       lookup_buffer_size = next_row;
    }
    unsigned int cache_l2_hit = 0;
    for (int row=q->row; row < q->row + lookup_buffer_size && row < rows; row++) {
        for (int col=1; col <= q->num_vars_total; col++) {
            if (!q->bt[col].need_val && !q->bt[col].expression) continue;
            fs_rid rid;
            if (row < q->bt[col].vals->length) {
                if (q->ordering) {
                    rid = q->bt[col].vals->data[q->ordering[row]];
                } else {
                    rid = q->bt[col].vals->data[row];
                }
            } else {
                rid = FS_RID_NULL;
            }
            if (FS_IS_BNODE(rid)) continue;
            if (res_l2_cache[rid & CACHE_MASK].rid == rid) {
                cache_l2_hit++; 
                continue;
            }
            pre_cache_len++;
            fs_rid_vector_append(q->pending[FS_RID_SEGMENT(rid, q->segments)], rid);
        }
    }
    if (q->qs->cache_stats) {
        double avg_saved = (cache_l2_hit+0.00001) / (cache_l2_hit+pre_cache_len+0.00001);
        double total_avg_saved = q->qs->resolve_all_calls * q->qs->avg_cache_saves_l2;
        q->qs->avg_cache_saves_l2 = (avg_saved + total_avg_saved) /
                                    (q->qs->resolve_all_calls + 1.0001);
    }
    g_static_mutex_unlock(&cache_mutex);
    if (pre_cache_len)
        resolve_precache_all_with_stats(q);
    q->qs->pre_cache_total += pre_cache_len;
    q->lastrow = q->row + lookup_buffer_size;
}



fs_row *fs_query_fetch_row(fs_query *q)
{
    if (!q) return NULL;

    /* free up stuff used by previous row */
    fs_query_free_row_freeable(q);

nextrow: ;
    long int next_row = q->row + 1;
    fs_rid_vector *grows = NULL;

    /* handle aggregates */
    if (q->aggregate && (q->aggregate < 2 || q->group_by)) {
        if (q->length == 0) {
            fs_rid_vector *groups = fs_binding_get_vals(q->bt, "_group", NULL);
            if (groups) {
                /* GROUP BY + no rows , we stop */
                return NULL;
            }
            /* if not GROUP BY + no rows , we evaluate */
            q->resrow->stop = 1;
            for (int i=0; i<q->num_vars; i++) {
               fs_value val = fs_expression_eval(q, 0, 0, q->bt[i+1].expression);
               fs_value_to_row(q, val, q->resrow+i);
            }

            return q->resrow;
        } else if (q->row >= q->length) {
           returng: ;
           if (q->aggregate_order) {
                while (q->offset_aggregate > 0) {
                    q->offset_aggregate--;
                    q->agg_index++;
                }
                if (q->limit >= 0 && q->rows_output >= (q->offset + q->limit)) {
                    if (grows) fs_rid_vector_free(grows);
                    return NULL;
                }
                q->rows_output++;

                if (q->agg_index >= q->agg_rows->len) {
                    fs_free_agg_rows(q->agg_rows,q->num_vars);
                    fs_free_agg_values(q->agg_values,q->num_vars);
                    return NULL;
                }
                if (!q->aggregate_order_sorted) {
                    q->aggregate_order_sorted = 1;
                    fs_values_order(q);
                    q->aggregate_order_sorted = 2;
                 }
                 int order_agg = q->ordering[q->agg_index++];
                 fs_row *xx = (fs_row *) g_ptr_array_index(q->agg_rows,order_agg);
                 return xx;
             }
             return NULL;
        }
        fs_rid_vector *groups = fs_binding_get_vals(q->bt, "_group", NULL);
        fs_rid_vector *ord = q->bt[0].vals;
        if (q->aggregate && q->length > 0 && fs_rid_vector_length(ord) == 0) {
            /* fallback position: ord should contain values, but in some cases it does not */
            fs_binding *b = q->bt;
            int some_sort = 0;
            for (int i=0; b[i].name; i++)
                some_sort |=  b[i].sort;
            if (!some_sort) {
                for (int i=0; b[i].name; i++) {
                    if (b[i].proj || b[i].selected) {
                        b[i].sort = 1;
                    } else {
                        b[i].sort = 0;
                    }
                }
            }
            fs_binding_sort(q->bt);
            ord = q->bt[0].vals;
        }
        if (groups) {
            nextgroup: ;
            q->group_by = 1;

            next_row--;
            fs_rid group;

            int constrain_group = 0;
            do {
                group = groups->data[ord->data[next_row]];
                constrain_group = apply_constraints(q,ord->data[next_row]);
                if (constrain_group) {
                    grows = fs_rid_vector_new(0);
                    fs_rid_vector_append(grows, ord->data[next_row]);
                }
                next_row++;
            } while (next_row < q->length && !constrain_group);
            if (constrain_group) {
                while (next_row < q->length && groups->data[ord->data[next_row]] == group) {
                    if (apply_constraints(q,ord->data[next_row]))
                        fs_rid_vector_append(grows, ord->data[next_row]);
                    next_row++;
                }
                if (q->offset_aggregate > 0 && !q->order) { 
                    q->offset_aggregate--;
                    next_row++;
                    goto nextgroup;
                }
            } else {
                goto returng;
            }
        } else {
            long len = fs_binding_length(q->bt);
            grows = fs_rid_vector_new(len);
            for (long i=0; i<len; i++) {
                grows->data[i] = i;
            }
            next_row = len;
        }
        q->group_length = grows->length;
        q->group_rows = (uint64_t *)grows->data;
    }

    const int rows = q->length;
    if (!q->aggregate_order && q->limit >= 0 && q->rows_output >= (q->offset + q->limit)) {
        if (grows) fs_rid_vector_free(grows);
        return NULL;
    }
    if (q->row >= rows) {
	if (fsp_hit_limits(q->link) > 0) {
	    fs_error(LOG_ERR, "hit soft limit %d times", fsp_hit_limits(q->link));
	    char *msg = g_strdup_printf("hit complexity limit %d times, increasing soft limit may give more results", fsp_hit_limits(q->link));
	    q->warnings = g_slist_prepend(q->warnings, msg);
	    fs_query_add_freeable(q, msg);
	}
        if (grows) fs_rid_vector_free(grows);
        return NULL;
    }

    if (!q->resrow) {
        fs_query_fetch_header_row(q);
    }

    if (q->row == q->lastrow && (q->aggregate < 3)) {
        prefetch_lexical_data(q, next_row, rows);
    }

    int row = q->row;
    /* consquence of this if is that you can't have grouping and ordering */
    if (q->aggregate) {
        /* set row number to first row in group */
        row = q->group_rows[0];
        if (q->ordering) {
            if (!q->agg_rows) {
                q->agg_rows =  g_ptr_array_new();
                q->agg_values = g_ptr_array_new();
            }
            q->aggregate_order = 1;
            q->rows_output = 0;
        }
    } else if (q->ordering) {
        row = q->ordering[q->row];
    }

    int row_agg = 0;
    if (q->row < q->length && !q->group_by) {
        consnext: ;
        if (q->aggregate && !q->group_by) row = row_agg;
        if (!apply_constraints(q, row)) {
            q->boolean = 0;
            /* if we dont need any bindings we may as well stop */
            if (q->num_vars == 0) {
                if (grows) fs_rid_vector_free(grows);
                return NULL;
            }
            q->row = next_row;
            if (!q->aggregate) {
                goto nextrow;
            } else {
                if(!q->apply_constraints) 
                    q->apply_constraints = fs_new_bit_array(q->group_length);
                fs_bit_array_set(q->apply_constraints,row_agg,0);
            }
        } else if (q->aggregate) {
            q->row = next_row;
        }    
    }

    int repeat_row = 1;
    fs_value **values = NULL;
    for (int i=0; i<q->num_vars; i++) {
        if (q->agg_values && i == 0)
            values = malloc(q->num_vars * sizeof(fs_value *));
        fs_rid last_rid = q->resrow[i].rid;
        q->resrow[i].rid = q->bt[i+1].bound && row < q->bt[i+1].vals->length ?
                           q->bt[i+1].vals->data[row] : FS_RID_NULL;
        if (last_rid != q->resrow[i].rid) repeat_row = 0;
        if (q->bt[i+1].expression) {
            fs_value val;
            if (!q->aggregate || q->group_by) {
                val = fs_expression_eval(q, row, 0, q->bt[i+1].expression);
                if (fs_is_error(val)) {
                    if (val.lex) {
                        if (!q->warnings || !g_slist_find(q->warnings, val.lex)) {
                            q->warnings = g_slist_prepend(q->warnings, val.lex);
                        }
                    }
                    q->row = next_row;
                    goto nextrow;
                }
            }
            
            if (!q->group_by) {
                if (q->aggregate && (row_agg+1) < q->length) {
                    row_agg++;
                    goto consnext;
                } else { 
                    val = fs_expression_eval(q, row, 0, q->bt[i+1].expression);
                }
            }
            fs_value_to_row(q, val, q->resrow+i);
            if (q->agg_values) {
                fs_value *cpy = malloc(sizeof(fs_value));
                memcpy(cpy,&val,sizeof(fs_value));
                if (val.lex)
                    cpy->lex = g_strdup(val.lex);
                values[i] = cpy;
            }
            if (q->group_by && q->ordering && q->num_vars == i+1) {
                g_ptr_array_add(q->agg_values,values);
                q->row = next_row;
            }
        } else {
            fs_resource r;
            resolve(q, q->resrow[i].rid, &r);
            q->resrow[i].lex = r.lex;
            q->resrow[i].dt = NULL;
            q->resrow[i].lang = NULL;
            if (q->resrow[i].rid == FS_RID_NULL) {
                q->resrow[i].type = FS_TYPE_NONE;
            } else if (FS_IS_BNODE(q->resrow[i].rid)) {
                if (FS_SKOLEMIZE) {
                    q->resrow[i].type = FS_TYPE_URI;
                    q->resrow[i].lex = g_strdup_printf("%s%llx", fs_global_skolem_prefix, FS_BNODE_NUM(r.rid));
                    fs_query_add_freeable(q, (char *)q->resrow[i].lex);
                } else {
                    q->resrow[i].type = FS_TYPE_BNODE;
                }
            } else if (FS_IS_URI(q->resrow[i].rid)) {
                q->resrow[i].type = FS_TYPE_URI;
            } else  {
                q->resrow[i].type = FS_TYPE_LITERAL;
                if (r.attr != FS_RID_NULL && r.attr != fs_c.empty) {
                    fs_rid attr = r.attr;
                    resolve(q, attr, &r);
                    if (FS_IS_URI(attr)) {
                        q->resrow[i].dt = r.lex;
                    } else {
                        q->resrow[i].lang = r.lex;
                    }
                }
            }
            if (q->agg_values) {
                values[i] =  malloc(sizeof(fs_value));
                values[i]->lex = g_strdup(r.lex);
                values[i]->rid = r.rid;
                values[i]->attr = r.attr;
            }
            if (q->group_by && q->ordering && q->num_vars == i+1)
                g_ptr_array_add(q->agg_values,values);
        }
    }

    /* if it's DISTINCT and there are FILTERS then we might have more
     * distincting to do */
    /* TODO could add REDUCED handling here too */
    if (q->flags & FS_BIND_DISTINCT && repeat_row && !q->aggregate) {
        q->row = next_row;
        goto nextrow;
    }

    q->row = next_row;
    if (!q->aggregate_order) {
        if (q->rows_output < q->offset) {
            q->rows_output++;
            q->row = next_row;
            goto nextrow;
        }
        q->rows_output++;
    }
    if (grows) fs_rid_vector_free(grows);

    if (!q->group_by && q->aggregate) {
        q->resrow->stop=1;
        if (q->apply_constraints)
            fs_bit_array_destroy(q->apply_constraints);
    }

    if (q->aggregate_order) {
        fs_row *copy = fs_row_copy(q->resrow, q->num_vars);
        g_ptr_array_add(q->agg_rows,copy);
        goto nextrow; 
    }
    return q->resrow;
}

void fs_query_results_output(fs_query *q, const char *fmt, int flags, FILE *out)
{
    if (!fmt) fmt = "sparql";

    if (!strcmp(fmt, "sparql")) {
        output_sparql(q, flags, out);
    } else if (!strcmp(fmt, "text") || !strcmp(fmt, "ascii") || !strcmp(fmt, "tsv")) {
        output_text(q, flags, out);
    } else if (!strcmp(fmt, "csv")) {
        output_csv(q, flags, out);
    } else if (!strcmp(fmt, "json")) {
        output_json(q, flags, out);
    } else if (!strcmp(fmt, "testcase")) {
        output_testcase(q, flags, out);
    } else {
        fprintf(out, "unknown format: %s\n", fmt);
    }

    fs_query_free_row_freeable(q);
}

void fs_value_to_row(fs_query *q, fs_value v, fs_row *r)
{
    if (v.valid & fs_valid_bit(FS_V_TYPE_ERROR)) {
        r->rid = 1;
        r->dt = NULL;
        r->lang = NULL;
        r->lex = g_strdup_printf("error: %s", v.lex);
        fs_query_add_freeable(q, (char *)r->lex);

        return;
    }

    if (v.attr == fs_c.xsd_double) {
        r->rid = 1;
        r->dt = XSD_DOUBLE;
        r->lang = NULL;
        r->type = FS_TYPE_LITERAL;
        if (v.lex) {
            r->lex = g_strdup(v.lex);
        } else {
            r->lex = g_strdup_printf("%g", v.fp);
        }
        fs_query_add_freeable(q, (char *)r->lex);
    } else if (v.attr == fs_c.xsd_float) {
        r->rid = 1;
        r->dt = XSD_FLOAT;
        r->lang = NULL;
        r->type = FS_TYPE_LITERAL;
        if (v.lex) {
            r->lex = g_strdup(v.lex);
        } else {
            r->lex = g_strdup_printf("%g", v.fp);
        }
        fs_query_add_freeable(q, (char *)r->lex);
    } else if (v.attr == fs_c.xsd_decimal) {
        r->rid = 1;
        r->dt = XSD_DECIMAL;
        r->lang = NULL;
        r->type = FS_TYPE_LITERAL;
        if (v.lex) {
            r->lex = g_strdup(v.lex);
        } else {
            r->lex = fs_decimal_to_lex(&v.de);
        }
        fs_query_add_freeable(q, (char *)r->lex);
    } else if (v.attr == fs_c.xsd_integer) {
        r->rid = 1;
        r->dt = XSD_INTEGER;
        r->lang = NULL;
        r->type = FS_TYPE_LITERAL;
        if (v.lex) {
            r->lex = g_strdup(v.lex);
        } else {
            r->lex = g_strdup_printf("%lld", (long long)v.in);
        }
        fs_query_add_freeable(q, (char *)r->lex);
    } else if (v.attr == fs_c.xsd_boolean) {
        r->rid = 1;
        r->dt = XSD_BOOLEAN;
        r->lang = NULL;
        r->type = FS_TYPE_LITERAL;
        if (v.lex) {
            r->lex = g_strdup(v.lex);
        } else {
            r->lex = g_strdup_printf("%lld", (long long)v.in);
        }
        fs_query_add_freeable(q, (char *)r->lex);
    } else if (v.attr == fs_c.xsd_string) {
        r->rid = 1;
        r->dt = XSD_STRING;
        r->lang = NULL;
        r->type = FS_TYPE_LITERAL;
        r->lex = g_strdup(v.lex);
        fs_query_add_freeable(q, (char *)r->lex);
    } else if (v.attr == fs_c.xsd_datetime) {
        r->rid = 1;
        r->dt = XSD_DATETIME;
        r->lang = NULL;
        r->type = FS_TYPE_LITERAL;
        r->lex = g_strdup(v.lex);
        fs_query_add_freeable(q, (char *)r->lex);
    } else if (v.attr == fs_c.empty || v.attr == FS_RID_NULL) {
        if (v.rid == FS_RID_NULL) {
        } else if (FS_IS_BNODE(v.rid)) {
            r->rid = v.rid;
            r->dt = NULL;
            r->lang = NULL;
            if (FS_SKOLEMIZE) {
                r->type = FS_TYPE_URI;
                r->lex = g_strdup_printf("%s%llx", fs_global_skolem_prefix, FS_BNODE_NUM(v.rid));
            } else {
                r->type = FS_TYPE_BNODE;
                r->lex = g_strdup_printf("_:b%llx", FS_BNODE_NUM(v.rid));
            }
            fs_query_add_freeable(q, (char *)r->lex);
        } else if (FS_IS_URI(v.rid)) {
            r->rid = 1;
            r->dt = NULL;
            r->lang = NULL;
            r->type = FS_TYPE_URI;
            r->lex = g_strdup(v.lex);
            fs_query_add_freeable(q, (char *)r->lex);
        } else {
            r->rid = 1;
            r->dt = NULL;
            r->lang = NULL;
            r->type = FS_TYPE_LITERAL;
            r->lex = g_strdup(v.lex);
            fs_query_add_freeable(q, (char *)r->lex);
        }
    } else {
        fs_resource res;
        resolve(q, v.attr, &res);
        r->rid = 1;
        if (FS_IS_URI(v.attr)) {
            r->dt = res.lex;
            r->lang = NULL;
        } else {
            r->dt = NULL;
            r->lang = res.lex;
        }
        r->type = FS_TYPE_LITERAL;
        r->lex = g_strdup(v.lex);
        fs_query_add_freeable(q, (char *)r->lex);
    }
}

struct simple_sort {
    int row;
    const char *str;
};

static int simple_sort_cmp(const void *va, const void *vb)
{
    const struct simple_sort *a = va, *b = vb;

    return strcmp(a->str, b->str);
}

static void rl_free(gpointer key, gpointer value, gpointer user_data)
{
    if (value != NULL_PROXY && value != BNODE_PROXY) {
        free(value);
    }
}

/* sort column by ORDER BY rules, only works on NULL, bNodes, URIs, simple and
 * xsd:strings */
int fs_sort_column(fs_query *q, fs_binding *b, int col, int **sorted)
{
    *sorted = NULL;

    fs_rid_vector *rv[q->segments];
    for (int s=0; s<q->segments; s++) {
        rv[s] = fs_rid_vector_new(0);
    }

    const int length = b[col].vals->length;
    if (length == 0) {
        return 0;
    }

    /* resolve all the resources */
    for (int row=0; row < length; row++) {
        fs_rid rid = b[col].vals->data[row];
        if (FS_IS_BNODE(rid)) continue;
        fs_rid_vector_append(rv[FS_RID_SEGMENT(rid, q->segments)], rid);
    }
    fs_resource *res[q->segments];
    for (int s=0; s<q->segments; s++) {
        fs_rid_vector_sort(rv[s]);
        fs_rid_vector_uniq(rv[s], 0);
        res[s] = malloc(rv[s]->length * sizeof(fs_resource));
    }
    int ret = fsp_resolve_all(q->link, rv, res);
    if (ret) {
        fs_error(LOG_CRIT, "resolve_all failed");

        return 1;
    }

    /* store strings that will strcmp into the correct order */
    GHashTable *rl = g_hash_table_new_full(fs_rid_hash, fs_rid_equal, g_free, NULL);
    for (int s=0; s<q->segments; s++) {
        for (int i=0; i<rv[s]->length; i++) {
            fs_rid *rid = g_malloc(sizeof(fs_rid));
            *rid = res[s][i].rid;
            if (res[s][i].attr == fs_c.xsd_integer ||
                res[s][i].attr == fs_c.xsd_float ||
                res[s][i].attr == fs_c.xsd_double ||
                res[s][i].attr == fs_c.xsd_decimal ||
                res[s][i].attr == fs_c.xsd_datetime) {
                /* unsupported type */
                for (int s=0; s<q->segments; s++) {
                    for (int i=0; i<rv[s]->length; i++) {
                        free(res[s][i].lex);
                    }
                    free(res[s]);
                    fs_rid_vector_free(rv[s]);
                }
                g_free(rid);
                g_hash_table_foreach(rl, rl_free, NULL);
                g_hash_table_destroy(rl);

                return 1;
            }
            char *lex = res[s][i].lex;
            /* if it's a tmp resource, this resolve will fail */
            /* potential optimisation: wrap tsp_resolve_all instead to save
             * shunting data about */
            fs_resource *tr = g_hash_table_lookup(q->tmp_resources, rid);
            if (tr) lex = tr->lex;
            int len = strlen(lex);
            char *sort = malloc(len+2);
            memcpy(sort+1, lex, len);
            sort[len+1] = '\0';
            if (FS_IS_URI(res[s][i].rid)) {
                sort[0] = 'U';
            } else {
                if (res[s][i].attr == fs_c.xsd_string) {
                    sort[0] = 's';
                } else {
                    sort[0] = 'l';
                }
            }
            g_hash_table_insert(rl, rid, sort);
        }
    }
    for (int s=0; s<q->segments; s++) {
        for (int i=0; i<rv[s]->length; i++) {
            free(res[s][i].lex);
        }
        free(res[s]);
        fs_rid_vector_free(rv[s]);
    }

    struct simple_sort *sortable = malloc(sizeof(struct simple_sort) * length);
    for (int row=0; row < length; row++) {
        sortable[row].row = row;
        const fs_rid rid = b[col].vals->data[row];
        if (rid == FS_RID_NULL) {
            sortable[row].str = NULL_PROXY;
            continue;
        } else if (FS_IS_BNODE(rid)) {
            sortable[row].str = BNODE_PROXY;
            continue;
        }
        char *sort = g_hash_table_lookup(rl, &rid);
        if (!sort) {
            /* this shouldn't happen, but just incase */
            fs_error(LOG_ERR, "cannot get sortable string for %016llx", rid);

            return 1;
        }
        sortable[row].str = sort;
    }

    qsort(sortable, length, sizeof(struct simple_sort), simple_sort_cmp);

    g_hash_table_foreach(rl, rl_free, NULL);
    g_hash_table_destroy(rl);

    int *order = malloc(length * sizeof(int));
    for (int i=0; i<length; i++) {
        order[i] = sortable[i].row;
    }
    *sorted = order;

    free(sortable);

    return 0;
}

/* vi:set expandtab sts=4 sw=4: */