File: maporaclespatial.c

package info (click to toggle)
mapserver 7.2.2-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 16,620 kB
  • sloc: ansic: 176,974; cpp: 58,161; python: 2,969; xml: 1,676; cs: 997; yacc: 856; lex: 766; java: 588; perl: 428; makefile: 374; sh: 184; tcl: 158; ruby: 55
file content (4022 lines) | stat: -rw-r--r-- 153,270 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
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
/******************************************************************************
 * Project: MapServer
 * Purpose: Native access to Oracle Spatial (SDO) data.
 * Author:  Fernando Simon (fsimon@univali.br)
 *          Rodrigo Becke Cabral
 *          Adriana Gomes Alves
 *
 * Notes: Developed under several funding agreements:
 *
 *   1) n.45/00 between CTTMAR/UNIVALI (www.cttmar.univali.br)
 *      and CEPSUL/IBAMA (www.ibama.gov.br)
 *
 *   2) CNPq (www.cnpq.br) under process 401263.03-7
 *
 *   3) FUNCITEC (www.funcitec.rct-sc.br) under process FCTP1523-031
 *
 ******************************************************************************
 * Copyright (c) 1996-2008 Regents of the University of Minnesota.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies of this Software or works derived from this Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *****************************************************************************/

#include "mapserver.h"
#include "maptime.h" 
#include "mapows.h"
#include <assert.h>



#if defined(USE_ORACLESPATIAL) || defined(USE_ORACLE_PLUGIN)

#include <oci.h>
#include <ctype.h>

#define ARRAY_SIZE                 1024
#define QUERY_SIZE                 1
#define TEXT_SIZE                  4000 /* ticket #2260 */
#define TYPE_OWNER                 "MDSYS"
#define SDO_GEOMETRY               TYPE_OWNER".SDO_GEOMETRY"
#define SDO_ORDINATE_ARRAY         TYPE_OWNER".SDO_ORDINATE_ARRAY"
#define SDO_GEOMETRY_LEN           strlen( SDO_GEOMETRY )
#define FUNCTION_FILTER            1
#define FUNCTION_RELATE            2
#define FUNCTION_GEOMRELATE        3
#define FUNCTION_NONE              4
#define VERSION_8i                 1
#define VERSION_9i                 2
#define VERSION_10g                3
#define TOLERANCE                  0.001
#define NULLERRCODE                1405
#define TABLE_NAME_SIZE            2000

typedef
struct {
  OCINumber x;
  OCINumber y;
  OCINumber z;
} SDOPointObj;

typedef
struct {
  OCINumber gtype;
  OCINumber srid;
  SDOPointObj point;
  OCIArray *elem_info;
  OCIArray *ordinates;
} SDOGeometryObj;

typedef
struct {
  OCIInd _atomic;
  OCIInd x;
  OCIInd y;
  OCIInd z;
} SDOPointInd;

typedef
struct {
  OCIInd _atomic;
  OCIInd gtype;
  OCIInd srid;
  SDOPointInd point;
  OCIInd elem_info;
  OCIInd ordinates;
} SDOGeometryInd;

typedef
text item_text[TEXT_SIZE];

typedef
item_text item_text_array[ARRAY_SIZE];

typedef
item_text item_text_array_query[QUERY_SIZE];

typedef
ub2 query_dtype[ARRAY_SIZE];

typedef
struct {
  /*Oracle handlers (global to connection)*/
  OCIEnv *envhp;
  OCIError *errhp;
  OCISvcCtx *svchp;
  int last_oci_status;
  text last_oci_error[2048];
  /* This references counter is to avoid the cache freed if there are other layers that could use it */
  int ref_count;
} msOracleSpatialHandler;

typedef
struct {
  /* Oracle data handlers (global to connection) */
  OCIDescribe *dschp;
  OCIType *tdo;
} msOracleSpatialDataHandler;

typedef
struct {
  OCIStmt *stmthp;

  /* fetch data buffer */
  ub4 rows_count; /* total number of rows (so far) within cursor */
  ub4 row_num; /* current row index within cursor results */
  ub4 rows_fetched; /* total number of rows fetched into our buffer */
  ub4 row; /* current row index within our buffer */

  item_text_array *items; /* items buffer */
  item_text_array_query *items_query; /* items buffer */
  SDOGeometryObj *obj[ARRAY_SIZE]; /* spatial object buffer */
  SDOGeometryInd *ind[ARRAY_SIZE]; /* object indicator (null) buffer */

  int uniqueidindex; /*allows to keep whic attribute id index is used as unique id*/


} msOracleSpatialStatement;

typedef
struct {
  /* oracle handlers */
  msOracleSpatialHandler *orahandlers;

  /* oracle data handlers */
  msOracleSpatialDataHandler *oradatahandlers;
  msOracleSpatialStatement *orastmt;

  /* Following items are setup by WhichShapes
   * used by NextShape, ResultGetShape
   * disposed by CloseLayer (if set)
   */
  msOracleSpatialStatement *orastmt2;
  /* Driver handling of pagination, enabled by default */
  int paging;

} msOracleSpatialLayerInfo;

static OCIType  *ordinates_tdo = NULL;
static OCIArray *ordinates;





/* local prototypes */
static int TRY( msOracleSpatialHandler *hand, sword status );
static int ERROR( char *routine, msOracleSpatialHandler *hand, msOracleSpatialDataHandler *dthand );
static void msSplitLogin( char *connection, mapObj *map, char **username, char **password, char **dblink );
static int msSplitData( char *data, char **geometry_column_name, char **table_name, char **unique, char **srid, char **indexfield, int *function, int * version);
static void msOCICloseConnection( void *layerinfo );
static msOracleSpatialHandler *msOCISetHandlers( char *username, char *password, char *dblink );
static int msOCISetDataHandlers( msOracleSpatialHandler *hand, msOracleSpatialDataHandler *dthand );
static void msOCICloseDataHandlers ( msOracleSpatialDataHandler *dthand );
static void msOCICloseHandlers( msOracleSpatialHandler *hand );
static void msOCIClearLayerInfo( msOracleSpatialLayerInfo *layerinfo );
static int msOCIOpenStatement( msOracleSpatialHandler *hand, msOracleSpatialStatement *sthand );
static void msOCIFinishStatement( msOracleSpatialStatement *sthand );
static int msOCIGet2DOrdinates( msOracleSpatialHandler *hand, SDOGeometryObj *obj, int s, int e, pointObj *pt );
static int msOCIGet3DOrdinates( msOracleSpatialHandler *hand, SDOGeometryObj *obj, int s, int e, pointObj *pt );
static int msOCIGet4DOrdinates( msOracleSpatialHandler *hand, SDOGeometryObj *obj, int s, int e, pointObj *pt );
static int msOCIConvertCircle( pointObj *pt );
static void osFilteritem(layerObj *layer, int function, char *query_str, size_t size, int mode);
static void osAggrGetExtent(layerObj *layer, char *query_str, size_t size, char *geom_column_name, char *table_name);
static void osConvexHullGetExtent(layerObj *layer, char *query_str, size_t size, char *geom_column_name, char *table_name);
static void osGeodeticData(int function, int version, char *query_str, size_t size, char *geom_column_name, char *index_column_name, char *srid, rectObj rect);
static void osNoGeodeticData(int function, int version, char *query_str, size_t size, char *geom_column_name, char *index_column_name, char *srid, rectObj rect);
static double osCalculateArcRadius(pointObj *pnt);
static void osCalculateArc(pointObj *pnt, int data3d, int data4d, double area, double radius, double npoints, int side, lineObj arcline, shapeObj *shape);
static void osGenerateArc(shapeObj *shape, lineObj arcline, lineObj points, int i, int n, int data3d, int data4d);
static void osShapeBounds ( shapeObj *shp );
static void osCloneShape(shapeObj *shape, shapeObj *newshape, int data3d, int data4d);
static void osPointCluster(msOracleSpatialHandler *hand, shapeObj *shape, SDOGeometryObj *obj, int start, int end, lineObj points, int interpretation, int data3d, int data4d);
static void osPoint(msOracleSpatialHandler *hand, shapeObj *shape, SDOGeometryObj *obj, int start, int end, lineObj points, pointObj *pnt, int data3d, int data4d);
static void osClosedPolygon(msOracleSpatialHandler *hand, shapeObj *shape, SDOGeometryObj *obj, int start, int end, lineObj points, int elem_type, int data3d, int data4d);
static void osRectangle(msOracleSpatialHandler *hand, shapeObj *shape, SDOGeometryObj *obj, int start, int end, lineObj points, pointObj *pnt, int data3d, int data4d);
static void osCircle(msOracleSpatialHandler *hand, shapeObj *shape, SDOGeometryObj *obj, int start, int end, lineObj points, pointObj *pnt, int data3d, int data4d);
static void osArcPolygon(msOracleSpatialHandler *hand, shapeObj *shape, SDOGeometryObj *obj, int start, int end, lineObj arcpoints,int elem_type,int data3d, int data4d);
static int osGetOrdinates(msOracleSpatialDataHandler *dthand, msOracleSpatialHandler *hand, shapeObj *shape, SDOGeometryObj *obj, SDOGeometryInd *ind);
static int osCheck2DGtype(int pIntGtype);
static int osCheck3DGtype(int pIntGtype);
static int osCheck4DGtype(int pIntGtype);



/******************************************************************************
 *                          Local Helper Functions                            *
 ******************************************************************************/


/* if an error ocurred call msSetError, sets last_oci_status to MS_FAILURE and return 0;
 * otherwise returns 1 */
static int TRY( msOracleSpatialHandler *hand, sword status )
{
  sb4 errcode = 0;

  if (hand->last_oci_status == MS_FAILURE)
    return 0; /* error from previous call */

  switch (status) {
    case OCI_SUCCESS_WITH_INFO:
    case OCI_ERROR:
      OCIErrorGet((dvoid *)hand->errhp, (ub4)1, (text *)NULL, &errcode, hand->last_oci_error, (ub4)sizeof(hand->last_oci_error), OCI_HTYPE_ERROR );
      if (errcode == NULLERRCODE) {
        hand->last_oci_error[0] = (text)'\0';
        return 1;
      }
      hand->last_oci_error[sizeof(hand->last_oci_error)-1] = 0; /* terminate string!? */
      break;
    case OCI_NEED_DATA:
      strlcpy( (char *)hand->last_oci_error, "OCI_NEED_DATA", sizeof(hand->last_oci_error));
      break;
    case OCI_INVALID_HANDLE:
      strlcpy( (char *)hand->last_oci_error, "OCI_INVALID_HANDLE", sizeof(hand->last_oci_error));
      break;
    case OCI_STILL_EXECUTING:
      ((char*)hand->last_oci_error)[sizeof(hand->last_oci_error)-1] = 0;
      break;
    case OCI_CONTINUE:
      strlcpy( (char *)hand->last_oci_error, "OCI_CONTINUE", sizeof(hand->last_oci_error));
      break;
    default:
      return 1; /* no error */
  }

  /* if I got here, there was an error */
  hand->last_oci_status = MS_FAILURE;

  return 0; /* error! */
}

OCIType *get_tdo(char *typename, msOracleSpatialHandler *hand, msOracleSpatialDataHandler *dthand )
{
  OCIParam *paramp = NULL;
  OCIRef *type_ref = NULL;
  OCIType *tdoe = NULL;
  int success = 0;


  success = TRY( hand, OCIDescribeAny(hand->svchp, hand->errhp, (text *)typename,  (ub4)strlen((char *)typename), OCI_OTYPE_NAME, (ub1)1, (ub1)OCI_PTYPE_TYPE, dthand->dschp))
            &&TRY( hand, OCIAttrGet((dvoid *)dthand->dschp, (ub4)OCI_HTYPE_DESCRIBE, (dvoid *)&paramp, (ub4 *)0, (ub4)OCI_ATTR_PARAM, hand->errhp))
            &&TRY( hand, OCIAttrGet((dvoid *)paramp, (ub4)OCI_DTYPE_PARAM, (dvoid *)&type_ref, (ub4 *)0, (ub4)OCI_ATTR_REF_TDO, hand->errhp))
            &&TRY( hand, OCIObjectPin(hand->envhp, hand->errhp, type_ref, (OCIComplexObject *)0, OCI_PIN_ANY, OCI_DURATION_SESSION, OCI_LOCK_NONE, (dvoid **)&tdoe));
  if (success)
    return tdoe;

  /* if failure, return NULL*/
  return NULL;
}


/* check last_oci_status for MS_FAILURE (set by TRY()) if an error ocurred return 1;
 * otherwise, returns 0 */
static int ERROR( char *routine, msOracleSpatialHandler *hand, msOracleSpatialDataHandler *dthand )
{
  if (hand->last_oci_status == MS_FAILURE) {
    /* there was an error */
    msSetError( MS_ORACLESPATIALERR, "OracleSpatial server returned an error, check logs for more details", routine );
    msDebug("OracleSpatial server returned an error in funtion (%s): %s.\n", routine, (char*)hand->last_oci_error );

    /* reset error flag */
    hand->last_oci_status = MS_SUCCESS;
    
    return 1; /* error processed */
  } else
    return 0; /* no error */
}

/* break layer->connection (username/password@dblink) into username, password and dblink */
static void msSplitLogin( char *connection, mapObj *map, char **username, char **password, char **dblink )
{
  char *src, *tgt, *conn_decrypted;
  size_t buffer_size = 0;

  /* bad 'connection' */
  if (connection == NULL) return;

  buffer_size = strlen(connection)+1;
  *username = (char*)malloc(buffer_size);
  *password = (char*)malloc(buffer_size);
  *dblink = (char*)malloc(buffer_size);

  /* clearup */
  **username = **password = **dblink = 0;

  /* Decrypt any encrypted token */
  conn_decrypted = msDecryptStringTokens(map, connection);
  if (conn_decrypted == NULL) return;

  /* ok, split connection */
  for( tgt=*username, src=conn_decrypted; *src; src++, tgt++ )
    if (*src=='/' || *src=='@')
      break;
    else
      *tgt = *src;
  *tgt = 0;
  if (*src == '/') {
    for( tgt=*password, ++src; *src; src++, tgt++ )
      if (*src == '@')
        break;
      else
        *tgt = *src;
    *tgt = 0;
  }
  if (*src == '@') {
    strlcpy( *dblink, ++src, buffer_size);
  }

  msFree(conn_decrypted);
}

/* break layer->data into geometry_column_name, table_name and srid */
static int msSplitData( char *data, char **geometry_column_name, char **table_name, char **unique, char **srid, char **indexfield, int *function, int *version )
{
  char *tok_from = "from";
  char *tok_using = "using";
  char *tok_unique = "unique";
  char *tok_srid = "srid";
  char *tok_indexfield="indexfield";
  char *tok_version = "version";
  char data_version[4] = "";
  char tok_function[11] = "";
  int parenthesis, i;
  char *src = data, *tgt;
  int table_name_size = TABLE_NAME_SIZE;
  size_t buffer_size = 0;

  /* bad 'data' */
  if (data == NULL)
    return 0;

  buffer_size = strlen(data)+1;
  *geometry_column_name = (char*)malloc(buffer_size);
  *unique = (char*)malloc(buffer_size);
  *srid = (char*)malloc(buffer_size);
  *indexfield=(char*)malloc(buffer_size);


  /* clearup */
  **geometry_column_name = **table_name = 0;

  /* parsing 'geometry_column_name' */
  for( ; *src && isspace( *src ); src++ ); /* skip blanks */
  for( tgt=*geometry_column_name; *src; src++, tgt++ )
    if (isspace( *src ))
      break;
    else
      *tgt = *src;
  *tgt = 0;

  /* parsing 'from' */
  for( ; *src && isspace( *src ); src++ ) ; /* skip blanks */
  for( ; *src && *tok_from && tolower(*src)==*tok_from; src++, tok_from++ );
  if (*tok_from != '\0')
    return 0;

  /* parsing 'table_name' or '(SELECT stmt)' */
  i = 0;
  for( ; *src && isspace( *src ); src++ ); /* skip blanks */
  for( tgt=*table_name, parenthesis=0; *src; src++, tgt++, ++i ) {
    if (*src == '(')
      parenthesis++;
    else if (*src == ')')
      parenthesis--;
    else if (parenthesis==0 && isspace( *src ))
      break; /* stop on spaces */
    /* double the size of the table_name array if necessary */
    if (i == table_name_size) {
      size_t tgt_offset = tgt - *table_name;
      table_name_size *= 2;
      *table_name = (char *) realloc(*table_name,sizeof(char *) * table_name_size);
      tgt = *table_name + tgt_offset;
    }
    *tgt = *src;
  }
  *tgt = 0;

  strlcpy( *unique, "", buffer_size);
  strlcpy( *srid, "NULL", buffer_size);
  strlcpy( *indexfield, "", buffer_size);
   
  *function = -1;
  *version = -1;

  /* parsing 'unique' */
  for( ; *src && isspace( *src ); src++ ) ; /* skip blanks */
  if (*src != '\0') {
    /* parse 'using' */
    for( ; *src && *tok_using && tolower(*src)==*tok_using; src++, tok_using++ );
    if (*tok_using != '\0')
      return 0;

    /* parsing 'unique' */
    for( ; *src && isspace( *src ); src++ ); /* skip blanks */
    for( ; *src && *tok_unique && tolower(*src)==*tok_unique; src++, tok_unique++ );

    if (*tok_unique == '\0') {
      for( ; *src && isspace( *src ); src++ ); /* skip blanks */
      if (*src == '\0')
        return 0;
      for( tgt=*unique; *src; src++, tgt++ )
        if (isspace( *src ))
          break;
        else
          *tgt = *src;
      *tgt = 0;

      if (*tok_unique != '\0')
        return 0;
    }

    /* parsing 'srid' */
    for( ; *src && isspace( *src ); src++ ); /* skip blanks */
    for( ; *src && *tok_srid && tolower(*src)==*tok_srid; src++, tok_srid++ );
    if (*tok_srid == '\0') {
      for( ; *src && isspace( *src ); src++ ); /* skip blanks */
      if (*src == '\0')
        return 0;
      for( tgt=*srid; *src; src++, tgt++ )
        if (isspace( *src ))
          break;
        else
          *tgt = *src;
      *tgt = 0;

      if (*tok_srid != '\0')
        return 0;
    }

    /* parsing 'indexfield' */
    for( ; *src && isspace( *src ); src++ ); /* skip blanks */
    for( ; *src && *tok_indexfield && tolower(*src)==*tok_indexfield; src++, tok_indexfield++ );

    if (*tok_indexfield == '\0') {
      for( ; *src && isspace( *src ); src++ ); /* skip blanks */
      if (*src == '\0')
        return 0;
      for( tgt=*indexfield; *src; src++, tgt++ )
        if (isspace( *src ))
          break;
        else
          *tgt = *src;
      *tgt = 0;

      if (*tok_indexfield != '\0')
        return 0;
    }

    /*parsing function/version */
    for( ; *src && isspace( *src ); src++ );
    if (*src != '\0') {
      for( tgt=tok_function; *src; src++, tgt++ )
        if (isspace( *src ))
          break;
        else
          *tgt = *src;
      *tgt = 0;
    }

    /*Upcase conversion for the FUNCTION/VERSION token*/
    for (i=0; tok_function[i] != '\0'; i++)
      tok_function[i] = toupper(tok_function[i]);

    if (strcmp(tok_function, "VERSION")) {
      if (!strcmp(tok_function, "FILTER") || !strcmp(tok_function, ""))
        *function = FUNCTION_FILTER;
      else if(!strcmp(tok_function, "RELATE"))
        *function = FUNCTION_RELATE;
      else if (!strcmp(tok_function,"GEOMRELATE"))
        *function = FUNCTION_GEOMRELATE;
      else if (!strcmp(tok_function,"NONE"))
        *function = FUNCTION_NONE;
      else {
        *function = -1;
        return 0;
      }

      /*parsing VERSION token when user defined one function*/
      for( ; *src && isspace( *src ); src++ );
      for( ; *src && *tok_version && tolower(*src)==*tok_version; src++, tok_version++ );
    } else {
      for(tgt = "VERSION"; *tgt && *tok_version && toupper(*tgt)==toupper(*tok_version); tgt++, tok_version++ );
      *function = FUNCTION_FILTER;
    }

    /*parsing version*/
    if (*tok_version == '\0') {
      for( ; *src && isspace( *src ); src++ ); /* skip blanks */
      for( tgt=data_version; *src; src++, tgt++ )
        if (isspace( *src ))
          break;
        else
          *tgt = *src;
      *tgt = 0;

      for (i=0; data_version[i] != '\0'; i++)
        data_version[i] = tolower(data_version[i]);

      if (!strcmp(data_version, "8i"))
        *version = VERSION_8i;
      else if(!strcmp(data_version, "9i"))
        *version = VERSION_9i;
      else if (!strcmp(data_version, "10g"))
        *version = VERSION_10g;
      else
        return 0;

    }

  }
  /* finish parsing */
  for( ; *src && isspace( *src ); src++ ); /* skip blanks */

  return (*src == '\0');
}


/******************************************************************************
 *                          OCI Helper Functions                              *
 ******************************************************************************/

/* create statement handle from database connection */
static int msOCIOpenStatement( msOracleSpatialHandler *hand, msOracleSpatialStatement *sthand)
{
  int success = 0;
  char * cmd  = "";
  
  /* allocate stmthp */
  success = TRY( hand, OCIHandleAlloc( (dvoid *)hand->envhp, (dvoid **)&sthand->stmthp, (ub4)OCI_HTYPE_STMT, (size_t)0, (dvoid **)0 ) );

  sthand->rows_count = 0;
  sthand->row_num = 0;
  sthand->rows_fetched = 0;
  sthand->row = 0;
  sthand->items = NULL;
  sthand->items_query = NULL;

  /* setting environment values to enable time parsing */

  cmd = "alter session set NLS_DATE_FORMAT='yyyy-mm-dd hh24:mi:ss'";
  success = TRY(hand, OCIStmtPrepare( sthand->stmthp, hand->errhp, (const OraText*)cmd, (ub4) strlen(cmd), (ub4) OCI_NTV_SYNTAX, (ub4) OCI_DEFAULT));
  success = TRY(hand, OCIStmtExecute( hand->svchp, sthand->stmthp, hand->errhp, (ub4)ARRAY_SIZE, (ub4)0, (OCISnapshot *)NULL, (OCISnapshot *)NULL, (ub4)OCI_DEFAULT ) );
  
  cmd = "alter session set NLS_TIMESTAMP_TZ_FORMAT='yyyy-mm-dd hh24:mi:ss'";       
  success = TRY(hand, OCIStmtPrepare( sthand->stmthp, hand->errhp, (const OraText*)cmd, (ub4) strlen(cmd), (ub4) OCI_NTV_SYNTAX, (ub4) OCI_DEFAULT));
  success = TRY(hand, OCIStmtExecute( hand->svchp, sthand->stmthp, hand->errhp, (ub4)ARRAY_SIZE, (ub4)0, (OCISnapshot *)NULL, (OCISnapshot *)NULL, (ub4)OCI_DEFAULT ) );
  
  cmd = "alter session set NLS_TIMESTAMP_FORMAT = 'yyyy-mm-dd hh24:mi:ss'";
  success = TRY(hand, OCIStmtPrepare( sthand->stmthp, hand->errhp, (const OraText*)cmd, (ub4) strlen(cmd), (ub4) OCI_NTV_SYNTAX, (ub4) OCI_DEFAULT));
  success = TRY(hand, OCIStmtExecute( hand->svchp, sthand->stmthp, hand->errhp, (ub4)ARRAY_SIZE, (ub4)0, (OCISnapshot *)NULL, (OCISnapshot *)NULL, (ub4)OCI_DEFAULT ) );
  
  cmd = "alter session set time_zone = 'GMT'";
  success = TRY(hand, OCIStmtPrepare( sthand->stmthp, hand->errhp, (const OraText*)cmd, (ub4) strlen(cmd), (ub4) OCI_NTV_SYNTAX, (ub4) OCI_DEFAULT));
  success = TRY(hand, OCIStmtExecute( hand->svchp, sthand->stmthp, hand->errhp, (ub4)ARRAY_SIZE, (ub4)0, (OCISnapshot *)NULL, (OCISnapshot *)NULL, (ub4)OCI_DEFAULT ) );
  

  /* fprintf(stderr, "Creating statement handle at %p\n", sthand->stmthp); */

  return success;
}

/* create statement handle from database connection */
static void msOCIFinishStatement( msOracleSpatialStatement *sthand )
{
  if(sthand != NULL) {
    /* fprintf(stderr, "Freeing statement handle at %p\n", sthand->stmthp); */

    if (sthand->stmthp != NULL)
      OCIHandleFree( (dvoid *)sthand->stmthp, (ub4)OCI_HTYPE_STMT );
    if (sthand->items != NULL)
      free( sthand->items );
    if (sthand->items_query != NULL)
      free( sthand->items_query );
    memset(sthand, 0, sizeof( msOracleSpatialStatement ) );
    free(sthand);
  }
}

static int msOCISetDataHandlers(msOracleSpatialHandler *hand, msOracleSpatialDataHandler *dthand)
{
  int success = 0;
  OCIParam *paramp = NULL;
  OCIRef *type_ref = NULL;

  success = TRY( hand,
                 /* allocate dschp */
                 OCIHandleAlloc( hand->envhp, (dvoid **)&dthand->dschp, (ub4)OCI_HTYPE_DESCRIBE, (size_t)0, (dvoid **)0 ) )
            && TRY( hand,
                    /* describe SDO_GEOMETRY in svchp (dschp) */
                    OCIDescribeAny( hand->svchp, hand->errhp, (text *)SDO_GEOMETRY, (ub4)SDO_GEOMETRY_LEN, OCI_OTYPE_NAME, (ub1)1, (ub1)OCI_PTYPE_TYPE, dthand->dschp ) )
            && TRY( hand,
                    /* get param for SDO_GEOMETRY */
                    OCIAttrGet( (dvoid *)dthand->dschp, (ub4)OCI_HTYPE_DESCRIBE, (dvoid *)&paramp, (ub4 *)0,  (ub4)OCI_ATTR_PARAM, hand->errhp ) )
            && TRY( hand,
                    /* get type_ref for SDO_GEOMETRY */
                    OCIAttrGet( (dvoid *)paramp, (ub4)OCI_DTYPE_PARAM, (dvoid *)&type_ref, (ub4 *)0, (ub4)OCI_ATTR_REF_TDO, hand->errhp ) )
            && TRY( hand,
                    /* get TDO for SDO_GEOMETRY */
                    OCIObjectPin( hand->envhp, hand->errhp, type_ref, (OCIComplexObject *)0, OCI_PIN_ANY, OCI_DURATION_SESSION, OCI_LOCK_NONE, (dvoid **)&dthand->tdo ) );

  return success;
}

/* connect to database */
static msOracleSpatialHandler *msOCISetHandlers( char *username, char *password, char *dblink )
{
  int success;

  msOracleSpatialHandler *hand = NULL;

  hand = (msOracleSpatialHandler *) malloc( sizeof(msOracleSpatialHandler));
  if (hand == NULL) {
    msSetError(MS_MEMERR, NULL, "msOCISetHandlers()");
    return NULL;
  }
  memset( hand, 0, sizeof(msOracleSpatialHandler) );

  hand->ref_count = 1;
  hand->last_oci_status = MS_SUCCESS;
  hand->last_oci_error[0] = (text)'\0';

  success = TRY( hand,
                 /* allocate envhp */
#ifdef USE_THREAD
                 OCIEnvCreate( &hand->envhp, OCI_OBJECT|OCI_THREADED, (dvoid *)0, 0, 0, 0, (size_t) 0, (dvoid **)0 ) )
#else
                 OCIEnvCreate( &hand->envhp, OCI_OBJECT, (dvoid *)0, 0, 0, 0, (size_t) 0, (dvoid **)0 ) )
#endif
            && TRY( hand,
                    /* allocate errhp */
                    OCIHandleAlloc( (dvoid *)hand->envhp, (dvoid **)&hand->errhp, (ub4)OCI_HTYPE_ERROR, (size_t)0, (dvoid **)0 ) )
            && TRY( hand,
                    /* logon */
                    OCILogon( hand->envhp, hand->errhp, &hand->svchp, (text *)username, strlen(username), (text *)password, strlen(password), (text *)dblink, strlen(dblink) ) );

  if ( !success ) {
    msDebug(   "Cannot create OCI Handlers. "
                "Connection failure."
                "Error: %s."
                "msOracleSpatialLayerOpen()\n", hand->last_oci_error);
    msSetError( MS_ORACLESPATIALERR,
                "Cannot create OCI Handlers. "
                "Connection failure. Check your logs and the connection string. ",
                "msOracleSpatialLayerOpen()");

    msOCICloseHandlers(hand);
    return NULL;
  }

  return hand;

}

/* disconnect from database */
static void msOCICloseHandlers( msOracleSpatialHandler *hand )
{
  if (hand->svchp != NULL)
    OCILogoff( hand->svchp, hand->errhp );
  if (hand->errhp != NULL)
    OCIHandleFree( (dvoid *)hand->errhp, (ub4)OCI_HTYPE_ERROR );
  if (hand->envhp != NULL)
    OCIHandleFree( (dvoid *)hand->envhp, (ub4)OCI_HTYPE_ENV );
  if (hand != NULL)
    memset( hand, 0, sizeof (msOracleSpatialHandler));
  free(hand);
}

static void msOCICloseDataHandlers( msOracleSpatialDataHandler *dthand )
{
  if (dthand->dschp != NULL)
    OCIHandleFree( (dvoid *)dthand->dschp, (ub4)OCI_HTYPE_DESCRIBE );
  if (dthand != NULL)
    memset( dthand, 0, sizeof (msOracleSpatialDataHandler));
  free(dthand);
}

static void msOCIClearLayerInfo( msOracleSpatialLayerInfo *layerinfo )
{
  if (layerinfo != NULL) {
    memset( layerinfo, 0, sizeof( msOracleSpatialLayerInfo ) );
    free(layerinfo);
  }
}

/*function that creates the correct sql for geoditical srid for version 9i*/
static void osGeodeticData(int function, int version, char *query_str, size_t size, char *geom_column_name, char *index_column_name, char *srid, rectObj rect)
{
  char *filter_field=index_column_name[0]=='\0' ? geom_column_name : index_column_name;
  switch (function) {
    case FUNCTION_FILTER: {
      snprintf( query_str + strlen(query_str), size-strlen(query_str),
                "SDO_FILTER( %s, SDO_CS.VIEWPORT_TRANSFORM(MDSYS.SDO_GEOMETRY("
                "2003, 0, NULL,"
                "MDSYS.SDO_ELEM_INFO_ARRAY(1,1003,3),"
                ":ordinates ), :srid),"
                "'querytype=window') = 'TRUE'",
                filter_field);
      break;
    }
    case FUNCTION_RELATE: {
      snprintf( query_str + strlen(query_str), size-strlen(query_str),
                "SDO_RELATE( %s, SDO_CS.VIEWPORT_TRANSFORM(MDSYS.SDO_GEOMETRY("
                "2003, 0, NULL,"
                "MDSYS.SDO_ELEM_INFO_ARRAY(1,1003,3),"
                ":ordinates ), :srid),"
                "'mask=anyinteract querytype=window') = 'TRUE'",
                filter_field);
      break;
    }
    case FUNCTION_GEOMRELATE: {
      snprintf( query_str + strlen(query_str), size-strlen(query_str),
                "SDO_GEOM.RELATE( %s, 'anyinteract', SDO_CS.VIEWPORT_TRANSFORM(MDSYS.SDO_GEOMETRY("
                "2003, 0, NULL,"
                "MDSYS.SDO_ELEM_INFO_ARRAY(1,1003,3),"
                ":ordinates), :srid),"
                "%f) = 'TRUE' AND %s IS NOT NULL",
                index_column_name,  TOLERANCE, geom_column_name );
      break;
    }
    case FUNCTION_NONE: {
      break;
    }
    default: {
      snprintf( query_str + strlen(query_str),  size-strlen(query_str),
                "SDO_FILTER( %s, SDO_CS.VIEWPORT_TRANSFORM(MDSYS.SDO_GEOMETRY("
                "2003, 0, NULL,"
                "MDSYS.SDO_ELEM_INFO_ARRAY(1,1003,3),"
                ":ordinates), :srid),"
                "'querytype=window') = 'TRUE'",
                filter_field );
    }
  }
}

/*function that generate the correct sql for no geoditic srid's*/
static void osNoGeodeticData(int function, int version, char *query_str, size_t size, char *geom_column_name, char *index_column_name, char *srid, rectObj rect)
{
   char *filter_field= index_column_name[0]=='\0' ? geom_column_name : index_column_name;
   switch (function) {
    case FUNCTION_FILTER: {
      snprintf( query_str + strlen(query_str), size-strlen(query_str),
                "SDO_FILTER( %s, MDSYS.SDO_GEOMETRY("
                "2003, :srid, NULL,"
                "MDSYS.SDO_ELEM_INFO_ARRAY(1,1003,3),"
                /*   "MDSYS.SDO_ORDINATE_ARRAY(%.9g,%.9g,%.9g,%.9g)" */
                ":ordinates"
                " ),'querytype=window') = 'TRUE'",
                filter_field);
      break;
    }
    case FUNCTION_RELATE: {
      if (version == VERSION_10g) {
        snprintf( query_str + strlen(query_str), size-strlen(query_str),
                  "SDO_ANYINTERACT( %s, MDSYS.SDO_GEOMETRY("
                  "2003, :srid, NULL,"
                  "MDSYS.SDO_ELEM_INFO_ARRAY(1,1003,3),"
                  ":ordinates)) = 'TRUE'",
                  filter_field);
      } else {
        snprintf( query_str + strlen(query_str), size-strlen(query_str),
                  "SDO_RELATE( %s, MDSYS.SDO_GEOMETRY("
                  "2003, :srid, NULL,"
                  "MDSYS.SDO_ELEM_INFO_ARRAY(1,1003,3),"
                  ":ordinates),"
                  "'mask=anyinteract querytype=window') = 'TRUE'",
                  geom_column_name);
      }
      break;
    }
    case FUNCTION_GEOMRELATE: {
      snprintf( query_str + strlen(query_str), size-strlen(query_str),
                "SDO_GEOM.RELATE( %s, 'anyinteract', MDSYS.SDO_GEOMETRY("
                "2003, :srid, NULL,"
                "MDSYS.SDO_ELEM_INFO_ARRAY(1,1003,3),"
                ":ordinates),"
                "%f) = 'TRUE' AND %s IS NOT NULL",
                index_column_name, TOLERANCE, geom_column_name );
      break;
    }
    case FUNCTION_NONE: {
      break;
    }
    default: {
      snprintf( query_str + strlen(query_str), size-strlen(query_str),
                "SDO_FILTER( %s, MDSYS.SDO_GEOMETRY("
                "2003, :srid, NULL,"
                "MDSYS.SDO_ELEM_INFO_ARRAY(1,1003,3),"
                ":ordinates),"
                "'querytype=window') = 'TRUE'",
                filter_field);
    }
  }
}

/* get ordinates from SDO buffer */
static int msOCIGet2DOrdinates( msOracleSpatialHandler *hand, SDOGeometryObj *obj, int s, int e, pointObj *pt )
{
  double x, y;
  int i, n, success = 1;
  boolean exists;
  OCINumber *oci_number;

  for( i=s, n=0; i < e && success; i+=2, n++ ) {
    success = TRY( hand,
                   OCICollGetElem( hand->envhp, hand->errhp, (OCIColl *)obj->ordinates, (sb4)i, (boolean *)&exists, (dvoid *)&oci_number, (dvoid **)0 ) )
              && TRY( hand,
                      OCINumberToReal( hand->errhp, oci_number, (uword)sizeof(double), (dvoid *)&x ) )
              && TRY( hand,
                      OCICollGetElem( hand->envhp, hand->errhp, (OCIColl *)obj->ordinates, (sb4)i+1, (boolean *)&exists, (dvoid *)&oci_number, (dvoid **)0 ) )
              && TRY( hand,
                      OCINumberToReal( hand->errhp, oci_number, (uword)sizeof(double), (dvoid *)&y ) );

    if (success) {
      pt[n].x = x;
      pt[n].y = y;
    }
  }

  return success ? n : 0;
}

static int msOCIGet3DOrdinates( msOracleSpatialHandler *hand, SDOGeometryObj *obj, int s, int e, pointObj *pt )
{
  double x, y;
  int i, n, success = 1;
  boolean exists;
#ifdef USE_POINT_Z_M
  double z;
  boolean numnull;
#endif /* USE_POINT_Z_M */
  OCINumber *oci_number;

  for( i=s, n=0; i < e && success; i+=3, n++ ) {
    success = TRY( hand,
                   OCICollGetElem( hand->envhp, hand->errhp, (OCIColl *)obj->ordinates, (sb4)i, (boolean *)&exists, (dvoid *)&oci_number, (dvoid **)0 ) )
              && TRY( hand,
                      OCINumberToReal( hand->errhp, oci_number, (uword)sizeof(double), (dvoid *)&x ) )
              && TRY( hand,
                      OCICollGetElem( hand->envhp, hand->errhp, (OCIColl *)obj->ordinates, (sb4)i+1, (boolean *)&exists, (dvoid *)&oci_number, (dvoid **)0 ) )
              && TRY( hand,
                      OCINumberToReal( hand->errhp, oci_number, (uword)sizeof(double), (dvoid *)&y ) )
#ifdef USE_POINT_Z_M
              && TRY( hand,
                      OCICollGetElem( hand->envhp, hand->errhp, (OCIColl *)obj->ordinates, (sb4)i+2, (boolean *)&exists, (dvoid *)&oci_number, (dvoid **)0 ) )
#endif /* USE_POINT_Z_M */
              ;
#ifdef USE_POINT_Z_M
    if (success) {
      success = TRY(hand, OCINumberIsZero( hand->errhp, oci_number, (boolean *)&numnull));
      if (success) {
        success = TRY( hand, OCINumberToReal( hand->errhp, oci_number, (uword)sizeof(double), (dvoid *)&z ) );
      } else {
        hand->last_oci_status = MS_SUCCESS;
        strlcpy( (char *)hand->last_oci_error, "Retrieve z value, but NULL value for z. Setting z to 0.", sizeof(hand->last_oci_error));
        z = 0;
        success = 1;
      }
    }
#endif /* USE_POINT_Z_M */
    if (success) {
      pt[n].x = x;
      pt[n].y = y;
#ifdef USE_POINT_Z_M
      pt[n].z = z;
#endif /* USE_POINT_Z_M */
    }
  }

  return success ? n : 0;
}

static int msOCIGet4DOrdinates( msOracleSpatialHandler *hand, SDOGeometryObj *obj, int s, int e, pointObj *pt )
{
  double x, y;
  int i, n, success = 1;
  boolean exists;
#ifdef USE_POINT_Z_M
  double z;
  boolean numnull;
#endif /* USE_POINT_Z_M */
  OCINumber *oci_number;

  for( i=s, n=0; i < e && success; i+=4, n++ ) {
    success = TRY( hand,
                   OCICollGetElem( hand->envhp, hand->errhp, (OCIColl *)obj->ordinates, (sb4)i, (boolean *)&exists, (dvoid *)&oci_number, (dvoid **)0 ) )
              && TRY( hand,
                      OCINumberToReal( hand->errhp, oci_number, (uword)sizeof(double), (dvoid *)&x ) )
              && TRY( hand,
                      OCICollGetElem( hand->envhp, hand->errhp, (OCIColl *)obj->ordinates, (sb4)i+1, (boolean *)&exists, (dvoid *)&oci_number, (dvoid **)0 ) )
              && TRY( hand,
                      OCINumberToReal( hand->errhp, oci_number, (uword)sizeof(double), (dvoid *)&y ) )
#ifdef USE_POINT_Z_M
              && TRY( hand,
                      OCICollGetElem( hand->envhp, hand->errhp, (OCIColl *)obj->ordinates, (sb4)i+2, (boolean *)&exists, (dvoid *)&oci_number, (dvoid **)0 ) )

#endif /* USE_POINT_Z_M */
              ;
#ifdef USE_POINT_Z_M
    if (success) {
      success = TRY(hand, OCINumberIsZero( hand->errhp, oci_number, (boolean *)&numnull));
      if (success) {
        success = TRY( hand, OCINumberToReal( hand->errhp, oci_number, (uword)sizeof(double), (dvoid *)&z ) );
      } else {
        hand->last_oci_status = MS_SUCCESS;
        strlcpy( (char *)hand->last_oci_error, "Retrieve z value, but NULL value for z. Setting z to 0.", sizeof(hand->last_oci_error));
        z = 0;
        success = 1;
      }
    }
#endif /* USE_POINT_Z_M */
    if (success) {
      pt[n].x = x;
      pt[n].y = y;
#ifdef USE_POINT_Z_M
      pt[n].z = z;

#endif /* USE_POINT_Z_M */
    }
  }
  return success ? n : 0;
}

/* convert three-point circle to two-point rectangular bounds */
static int msOCIConvertCircle( pointObj *pt )
{
  pointObj ptaux;
  double dXa, dXb;
  double ma, mb;
  double cx, cy, r;
  int success;

  dXa = pt[1].x - pt[0].x;
  success = (fabs( dXa ) > 1e-8);
  if (!success) {
    /* switch points 1 & 2 */
    ptaux = pt[1];
    pt[1] = pt[2];
    pt[2] = ptaux;
    dXa = pt[1].x - pt[0].x;
    success = (fabs( dXa ) > 1e-8);
  }
  if (success) {
    dXb = pt[2].x - pt[1].x;
    success = (fabs( dXb ) > 1e-8);
    if (!success) {
      /* insert point 2 before point 0 */
      ptaux = pt[2];
      pt[2] = pt[1];
      pt[1] = pt[0];
      pt[0] = ptaux;
      dXb = dXa; /* segment A has become B */
      dXa = pt[1].x - pt[0].x; /* recalculate new segment A */
      success = (fabs( dXa ) > 1e-8);
    }
  }
  if (success) {
    ma = (pt[1].y - pt[0].y)/dXa;
    mb = (pt[2].y - pt[1].y)/dXb;
    success = (fabs( mb - ma ) > 1e-8);
  }
  if (!success)
    return 0;

  /* calculate center and radius */
  cx = (ma*mb*(pt[0].y - pt[2].y) + mb*(pt[0].x + pt[1].x) - ma*(pt[1].x + pt[2].x))/(2*(mb - ma));
  cy = (fabs( ma ) > 1e-8)
       ? ((pt[0].y + pt[1].y)/2 - (cx - (pt[0].x + pt[1].x)/2)/ma)
       : ((pt[1].y + pt[2].y)/2 - (cx - (pt[1].x + pt[2].x)/2)/mb);

  r  = sqrt( pow( pt[0].x - cx, 2 ) + pow( pt[0].y - cy, 2 ) );

  /* update pt buffer with rectangular bounds */
  pt[0].x = cx - r;
  pt[0].y = cy - r;
  pt[1].x = cx + r;
  pt[1].y = cy + r;

  return 1;
}

/*function that creates the correct sql for filter and filteritem*/
static void osFilteritem(layerObj *layer, int function, char *query_str, size_t size, int mode)
{
  char *native_filter; 
  if (layer->filter.native_string != NULL) {
    if (mode == 1)
      strlcat( query_str, " WHERE ", size);
    else
      strlcat( query_str, " AND ", size);

   /* if (layer->filteritem != NULL) {
      snprintf (query_str + strlen(query_str), size-strlen(query_str), " %s = ", layer->filteritem); */
      /* snprintf (query_str + strlen(query_str), " %s = ", layer->filteritem); */
  /*  } */

    snprintf (query_str + strlen(query_str), size-strlen(query_str), " %s ", layer->filter.native_string);
    /* snprintf(buffer, n, "gfdg %s %s %s", layer->filter.native_string, (layer->filteritem != NULL ? layer->filteritem : ""), ); */

    if (function != FUNCTION_NONE)
      snprintf (query_str + strlen(query_str), size-strlen(query_str), " AND ");
  } else {
    if (function != FUNCTION_NONE)
      strlcat( query_str, " WHERE ", size);
  }

  /* Handle a native filter set as a PROCESSING option (#5001). */
  if ( msLayerGetProcessingKey(layer, "NATIVE_FILTER") != NULL ) {
     if ((function == FUNCTION_NONE)&&(layer->filter.native_string == NULL)) {
     strlcat( query_str, " WHERE ", size);
     }
     if ((function == FUNCTION_NONE)&&(layer->filter.native_string != NULL)) {
     strlcat( query_str, " AND ", size);
     }
    native_filter = msLayerGetProcessingKey(layer, "NATIVE_FILTER");
    snprintf(query_str + strlen(query_str) , size-strlen(query_str), " %s ", native_filter);
    if (function != FUNCTION_NONE) {
     strlcat( query_str, " AND ", size);
     }
   
  }


}

static void osAggrGetExtent(layerObj *layer, char *query_str, size_t size, char *geom_column_name, char *table_name)
{
  char query_str2[6000];
  int i = 0;

  snprintf( query_str2, sizeof(query_str2), "(SELECT");
  for( i = 0; i < layer->numitems; ++i )
    snprintf( query_str2 + strlen(query_str2), sizeof(query_str2)-strlen(query_str2), " %s,", layer->items[i] );

  snprintf( query_str2 + strlen(query_str2), sizeof(query_str2)-strlen(query_str2), " %s FROM %s", geom_column_name, table_name);

  osFilteritem(layer, FUNCTION_NONE, query_str2, sizeof(query_str2), 1);

  snprintf( query_str, size, "SELECT SDO_AGGR_MBR(%s) AS GEOM from %s)", geom_column_name, query_str2);

  if (layer->debug)
    msDebug("osAggrGetExtent was called: %s.\n", query_str);
}

static void osConvexHullGetExtent(layerObj *layer, char *query_str, size_t size, char *geom_column_name, char *table_name)
{
  char query_str2[6000];
  int i = 0;

  snprintf( query_str2, sizeof(query_str2), "(SELECT");
  for( i = 0; i < layer->numitems; ++i )
    snprintf( query_str2 + strlen(query_str2), sizeof(query_str2)-strlen(query_str2), " %s,", layer->items[i] );

  snprintf( query_str2 + strlen(query_str2), sizeof(query_str2)-strlen(query_str2), " %s FROM %s", geom_column_name, table_name);

  osFilteritem(layer, FUNCTION_NONE, query_str2, sizeof(query_str2), 1);


  snprintf( query_str, size, "SELECT SDO_GEOM.SDO_CONVEXHULL(%s, %f) AS GEOM from %s)", geom_column_name, TOLERANCE, query_str2);
}

static double osCalculateArcRadius(pointObj *pnt)
{
  double rc;
  double r1, r2, r3;

  r1 = sqrt( pow(pnt[0].x-pnt[1].x,2) + pow(pnt[0].y-pnt[1].y,2) );
  r2 = sqrt( pow(pnt[1].x-pnt[2].x,2) + pow(pnt[1].y-pnt[2].y,2) );
  r3 = sqrt( pow(pnt[2].x-pnt[0].x,2) + pow(pnt[2].y-pnt[0].y,2) );
  rc = ( r1+r2+r3 )/2;

  return ( ( r1*r2*r3 )/( 4*sqrt( rc * (rc-r1) * (rc-r2) * (rc-r3) ) ) );
}

static void osCalculateArc(pointObj *pnt, int data3d, int data4d, double area, double radius, double npoints, int side, lineObj arcline, shapeObj *shape)
{
  double length, ctrl, angle;
  double divbas, plusbas, cosbas, sinbas = 0;
#ifdef USE_POINT_Z_M
  double zrange = 0;
#endif /* USE_POINT_Z_M */
  int i = 0;

  if ( npoints > 0 ) {
    length = sqrt(((pnt[1].x-pnt[0].x)*(pnt[1].x-pnt[0].x))+((pnt[1].y-pnt[0].y)*(pnt[1].y-pnt[0].y)));
    ctrl = length/(2*radius);

#ifdef USE_POINT_Z_M
    if (data3d||data4d) {
      zrange = labs(pnt[0].z-pnt[1].z)/npoints;
      if ((pnt[0].z > pnt[1].z) && side == 1)
        zrange *= -1;
      else if ((pnt[0].z < pnt[1].z) && side == 1)
        zrange = zrange;
      else if ((pnt[0].z > pnt[1].z) && side != 1)
        zrange *= -1;
      else if ((pnt[0].z < pnt[1].z) && side != 1)
        zrange = zrange;
    }
#endif /* USE_POINT_Z_M */

    if( ctrl <= 1 ) {
      divbas = 2 * asin(ctrl);
      plusbas = divbas/(npoints);
      cosbas = (pnt[0].x-pnt[3].x)/radius;
      sinbas = (pnt[0].y-pnt[3].y)/radius;
      angle = plusbas;

      arcline.point = (pointObj *)malloc(sizeof(pointObj)*(npoints+1));
      arcline.point[0].x = pnt[0].x;
      arcline.point[0].y = pnt[0].y;
#ifdef USE_POINT_Z_M
      if (data3d||data4d)
        arcline.point[0].z = pnt[0].z;
#endif /* USE_POINT_Z_M */

      for (i = 1; i <= npoints; i++) {
        if( side == 1) {
          arcline.point[i].x = pnt[3].x + radius * ((cosbas*cos(angle))-(sinbas*sin(angle)));
          arcline.point[i].y = pnt[3].y + radius * ((sinbas*cos(angle))+(cosbas*sin(angle)));
#ifdef USE_POINT_Z_M
          if (data3d||data4d)
            arcline.point[i].z = pnt[0].z + (zrange*i);
#endif /* USE_POINT_Z_M */
        } else {
          if ( side == -1) {
            arcline.point[i].x = pnt[3].x + radius * ((cosbas*cos(angle))+(sinbas*sin(angle)));
            arcline.point[i].y = pnt[3].y + radius * ((sinbas*cos(angle))-(cosbas*sin(angle)));
#ifdef USE_POINT_Z_M
            if (data3d||data4d)
              arcline.point[i].z = pnt[0].z + (zrange*i);
#endif /* USE_POINT_Z_M */
          } else {
            arcline.point[i].x = pnt[0].x;
            arcline.point[i].y = pnt[0].y;
#ifdef USE_POINT_Z_M
            if (data3d||data4d)
              arcline.point[i].z = pnt[0].z;
#endif /* USE_POINT_Z_M */
          }
        }
        angle += plusbas;
      }

      arcline.numpoints = npoints+1;
      msAddLine( shape, &arcline );
      free (arcline.point);
    }
  } else {
    arcline.point = (pointObj *)malloc(sizeof(pointObj)*(2));
    arcline.point[0].x = pnt[0].x;
    arcline.point[0].y = pnt[0].y;
    arcline.point[1].x = pnt[1].x;
    arcline.point[1].y = pnt[1].y;

#ifdef USE_POINT_Z_M
    if(data3d||data4d) {
      arcline.point[0].z = pnt[0].z;
      arcline.point[1].z = pnt[1].z;
    }
#endif /* USE_POINT_Z_M */

    arcline.numpoints = 2;

    msAddLine( shape, &arcline );
    free (arcline.point);
  }
}

/* Part of this function was based on Terralib function TeGenerateArc
 * found in TeGeometryAlgorith.cpp (www.terralib.org).
 * Part of this function was based on Dr. Ialo (Univali/Cttmar) functions. */
static void osGenerateArc(shapeObj *shape, lineObj arcline, lineObj points, int i, int n, int data3d, int data4d)
{
  double mult, plus1, plus2, plus3, bpoint;
  double cx, cy;
  double radius, side, area, npoints;
  double dist1 = 0;
  double dist2 = 0;
  pointObj point5[4];

  mult = ( points.point[i+1].x - points.point[i].x )
         * ( points.point[i+2].y - points.point[i].y )
         - ( points.point[i+1].y - points.point[i].y )
         * ( points.point[i+2].x - points.point[i].x );

  if (mult) {
    /*point5 = (pointObj *)malloc(sizeof(pointObj)*(4));*/

    plus1 = points.point[i].x * points.point[i].x + points.point[i].y * points.point[i].y;
    plus2 = points.point[i+1].x * points.point[i+1].x + points.point[i+1].y * points.point[i+1].y;
    plus3 = points.point[i+2].x * points.point[i+2].x + points.point[i+2].y * points.point[i+2].y;

    bpoint = plus1 * ( points.point[i+1].y - points.point[i+2].y )
             + plus2 * ( points.point[i+2].y - points.point[i].y )
             + plus3 * ( points.point[i].y - points.point[i+1].y );

    cx = bpoint / (2.0 * mult);

    bpoint = plus1 * ( points.point[i+2].x - points.point[i+1].x )
             + plus2 * ( points.point[i].x - points.point[i+2].x )
             + plus3 * ( points.point[i+1].x - points.point[i].x );

    cy = bpoint / (2.0 * mult);

    dist1 = (points.point[i+1].x - points.point[i].x) * (cy - points.point[i].y);
    dist2 = (points.point[i+1].y - points.point[i].y) * (cx - points.point[i].x);
    side = 0;

    if((dist1-dist2) > 0)
      side = 1;
    else {
      if((dist1-dist2) < 0)
        side = -1;
    }

    point5[0] = points.point[i];
    point5[1] = points.point[i+1];
    point5[2] = points.point[i+2];
    point5[3].x = cx;
    point5[3].y = cy;

    radius = osCalculateArcRadius(point5);

    area = ((points.point[i].x + points.point[i+1].x) * (points.point[i+1].y - points.point[i].y))
           + ((points.point[i+1].x + points.point[i+2].x) * (points.point[i+2].y - points.point[i+1].y));

    npoints = labs(area/radius);

    point5[0] = points.point[i];
    point5[1] = points.point[i+1];
    osCalculateArc(point5, data3d, data4d, area, radius, (npoints>1000)?1000:npoints, side, arcline, shape);

    point5[0] = points.point[i+1];
    point5[1] = points.point[i+2];
    osCalculateArc(point5, data3d, data4d,  area, radius, (npoints>1000)?1000:npoints, side, arcline, shape);

  } else {
    arcline.point = (pointObj *)malloc(sizeof(pointObj)*(2));
    arcline.point[0].x = points.point[i].x;
    arcline.point[0].y = points.point[i].y;
    arcline.point[1].x = points.point[i+2].x;
    arcline.point[1].y = points.point[i+2].y;

#ifdef USE_POINT_Z_M
    if (data3d||data4d) {
      arcline.point[0].z = points.point[i].z;
      arcline.point[1].z = points.point[i+2].z;
    }
#endif /* USE_POINT_Z_M */

    arcline.numpoints = 2;

    msAddLine( shape, &arcline );
    free (arcline.point);
  }
}

static void osShapeBounds ( shapeObj *shp )
{
  int i, f;

  if ( (shp->numlines > 0) && (shp->line[0].numpoints > 0) ) {
    shp->bounds.minx = shp->line[0].point[0].x;
    shp->bounds.maxx = shp->line[0].point[0].x;
    shp->bounds.miny = shp->line[0].point[0].y;
    shp->bounds.maxy = shp->line[0].point[0].y;
  }

  for ( i = 0 ; i < shp->numlines; i++) {
    for( f = 0; f < shp->line[i].numpoints; f++) {
      if (shp->line[i].point[f].x < shp->bounds.minx)
        shp->bounds.minx = shp->line[i].point[f].x;
      if (shp->line[i].point[f].x > shp->bounds.maxx)
        shp->bounds.maxx = shp->line[i].point[f].x;
      if (shp->line[i].point[f].y < shp->bounds.miny)
        shp->bounds.miny = shp->line[i].point[f].y;
      if (shp->line[i].point[f].y > shp->bounds.maxy)
        shp->bounds.maxy = shp->line[i].point[f].y;
    }
  }
}

static void osCloneShape(shapeObj *shape, shapeObj *newshape, int data3d, int data4d)
{
  int max_points = 0;
  int i,f,g;
  lineObj shapeline = {0, NULL};

  for (i = 0; i < shape->numlines; i++)
    max_points += shape->line[i].numpoints;

  if (max_points > 0)
    shapeline.point = (pointObj *)malloc( sizeof(pointObj)*max_points );

  g = 0;
  for ( i = 0 ; i < shape->numlines; i++) {
    for( f = 0; f < shape->line[i].numpoints && g <= max_points; f++, g++) {
      shapeline.point[g].x = shape->line[i].point[f].x;
      shapeline.point[g].y = shape->line[i].point[f].y;
#ifdef USE_POINT_Z_M
      if (data3d||data4d)
        shapeline.point[g].z = shape->line[i].point[f].z;
#endif /* USE_POINT_Z_M */
    }
  }

  if (g) {
    shapeline.numpoints = g;
    newshape->type = shape->type; /* jimk: 2009/09/23 Fixes compound linestrings being converted to polygons */
    msAddLine( newshape, &shapeline );
  }
}

static void osPointCluster(msOracleSpatialHandler *hand, shapeObj *shape, SDOGeometryObj *obj, int start, int end, lineObj points, int interpretation, int data3d, int data4d)
{
  int n;

  n = (end - start)/2;
  /* n = interpretation; */

  /* if (n == interpretation) { */
  points.point = (pointObj *)malloc( sizeof(pointObj)*n );

  if (data3d)
    n = msOCIGet3DOrdinates( hand, obj, start, end, points.point );
  else if (data4d)
    n = msOCIGet4DOrdinates( hand, obj, start, end, points.point );
  else
    n = msOCIGet2DOrdinates( hand, obj, start, end, points.point );

  if (n == interpretation && n>0) {
    shape->type = MS_SHAPE_POINT;
    points.numpoints = n;
    msAddLine( shape, &points );
  }
  free( points.point );
  /* } */
}

static void osPoint(msOracleSpatialHandler *hand, shapeObj *shape, SDOGeometryObj *obj, int start, int end, lineObj points, pointObj *pnt, int data3d, int data4d)
{
  int n;

  if (data3d)
    n = msOCIGet3DOrdinates( hand, obj, start, end, pnt );
  else if (data4d)
    n = msOCIGet4DOrdinates( hand, obj, start, end,  pnt );
  else
    n = msOCIGet2DOrdinates( hand, obj, start, end, pnt ); /* n must be < 5 */

  if (n == 1) {
    shape->type = MS_SHAPE_POINT;
    points.numpoints = 1;
    points.point = pnt;
    msAddLine( shape, &points );
  }
}

static void osClosedPolygon(msOracleSpatialHandler *hand, shapeObj *shape, SDOGeometryObj *obj, int start, int end, lineObj points, int elem_type, int data3d, int data4d)
{
  int n;

  n = (end - start)/2;
  points.point = (pointObj *)malloc( sizeof(pointObj)*n );

  if (data3d)
    n = msOCIGet3DOrdinates( hand, obj, start, end, points.point );
  else if (data4d)
    n = msOCIGet4DOrdinates( hand, obj, start, end, points.point );
  else
    n = msOCIGet2DOrdinates( hand, obj, start, end, points.point );

  if (n > 0) {
    shape->type = (elem_type==21) ? MS_SHAPE_LINE : MS_SHAPE_POLYGON;
    points.numpoints = n;
    msAddLine( shape, &points );
  }
  free( points.point );
}

static void osRectangle(msOracleSpatialHandler *hand, shapeObj *shape, SDOGeometryObj *obj, int start, int end, lineObj points, pointObj *pnt, int data3d, int data4d)
{
  int n;

  if (data3d)
    n = msOCIGet3DOrdinates( hand, obj, start, end, pnt ); /* n must be < 5 */
  else if (data4d)
    n = msOCIGet4DOrdinates( hand, obj, start, end, pnt ); /* n must be < 5 */
  else
    n = msOCIGet2DOrdinates( hand, obj, start, end, pnt ); /* n must be < 5 */

  if (n == 2) {
    shape->type = MS_SHAPE_POLYGON;
    points.numpoints = 5;
    points.point = pnt;

    /* point5 [0] & [1] contains the lower-left and upper-right points of the rectangle */
    pnt[2] = pnt[1];
    pnt[1].x = pnt[0].x;
    pnt[3].x = pnt[2].x;
    pnt[3].y = pnt[0].y;
    pnt[4] = pnt[0];
#ifdef USE_POINT_Z_M
    if (data3d||data4d) {
      pnt[1].z = pnt[0].z;
      pnt[3].z = pnt[2].z;
    }
#endif /* USE_POINT_Z_M */

    msAddLine( shape, &points );
  }
}

static void osCircle(msOracleSpatialHandler *hand, shapeObj *shape, SDOGeometryObj *obj, int start, int end, lineObj points, pointObj *pnt, int data3d, int data4d)
{
  int n;

  if (data3d)
    n = msOCIGet3DOrdinates( hand, obj, start, end, pnt ); /* n must be < 5 */
  else if (data4d)
    n = msOCIGet4DOrdinates( hand, obj, start, end, pnt ); /* n must be < 5 */
  else
    n = msOCIGet2DOrdinates( hand, obj, start, end, pnt ); /* n must be < 5 */

  if (n == 3) {
    if (msOCIConvertCircle( pnt )) {
      shape->type = MS_SHAPE_POINT;
      points.numpoints = 2;
      points.point = pnt;
      msAddLine( shape, &points );
    } else {
      strlcpy( (char *)hand->last_oci_error, "Points in circle object are colinear", sizeof(hand->last_oci_error));
      hand->last_oci_status = MS_FAILURE;
    }
  }
}

static void osArcPolygon(msOracleSpatialHandler *hand, shapeObj *shape, SDOGeometryObj *obj, int start, int end, lineObj arcpoints, int elem_type, int data3d, int data4d)
{
  int n, i;
  lineObj points = {0, NULL};

  n = (end - start)/2;
  points.point = (pointObj *)malloc( sizeof(pointObj)*n );

  if (data3d)
    n = msOCIGet3DOrdinates( hand, obj, start, end, points.point );
  else if (data4d)
    n = msOCIGet4DOrdinates( hand, obj, start, end, points.point );
  else
    n = msOCIGet2DOrdinates( hand, obj, start, end, points.point );

  if (n > 2) {
    shape->type = (elem_type==32) ? MS_SHAPE_POLYGON : MS_SHAPE_LINE;
    points.numpoints = n;

    for (i = 0; i < n-2; i = i+2)
      osGenerateArc(shape, arcpoints, points, i, n, data3d, data4d);
  }
  free (points.point);
}

static int osCheck2DGtype(int pIntGtype)
{
  if (pIntGtype > 2000 && pIntGtype < 2008) {
    if (pIntGtype != 2004)
      return MS_TRUE;
  }

  return MS_FALSE;
}

static int osCheck3DGtype(int pIntGtype)
{
  if (pIntGtype > 3000 && pIntGtype < 3308) {
    if (pIntGtype > 3007)
      pIntGtype-= 300;

    if (pIntGtype <= 3007 && pIntGtype != 3004)
      return MS_TRUE;
  }
  /*
  * Future version, untested
  * return (pIntGtype & 2208 && (pIntGtype & 3000 || pIntGtype & 3296) && pIntGtype & 3);
  */
  return MS_FALSE;
}

static int osCheck4DGtype(int pIntGtype)
{

  if (pIntGtype > 4000 && pIntGtype < 4408) {
    if (pIntGtype > 4007)
      pIntGtype-= 400;

    if (pIntGtype <= 4007 && pIntGtype != 4004)
      return MS_TRUE;


  }

  return MS_FALSE;
}



static int osGetOrdinates(msOracleSpatialDataHandler *dthand, msOracleSpatialHandler *hand, shapeObj *shape, SDOGeometryObj *obj, SDOGeometryInd *ind)
{
  int gtype, elem_type, compound_type;
  float compound_lenght, compound_count;
  ub4 etype;
  ub4 interpretation;
  int nelems, nords, data3d, data4d;
  int elem, ord_start, ord_end;
  boolean exists;
  OCINumber *oci_number;
  double x, y;
#ifdef USE_POINT_Z_M
  double z;
#endif /* USE_POINT_Z_M */
  int success;
  lineObj points = {0, NULL};
  pointObj point5[5]; /* for quick access */
  shapeObj newshape; /* for compound polygons */

  /*stat the variables for compound polygons*/
  compound_lenght = 0;
  compound_type = 0;
  compound_count = -1;
  data3d = 0;
  data4d = 0;

  if (ind->_atomic != OCI_IND_NULL) { /* not a null object */
    nelems = nords = 0;
    success = TRY( hand, OCICollSize( hand->envhp, hand->errhp, (OCIColl *)obj->elem_info, &nelems ) )
              && TRY( hand, OCICollSize( hand->envhp, hand->errhp, (OCIColl *)obj->ordinates, &nords ) )
              && TRY( hand, OCINumberToInt( hand->errhp, &(obj->gtype), (uword)sizeof(int), OCI_NUMBER_SIGNED, (dvoid *)&gtype ) );
    /*&& (nords%2==0 && nelems%3==0);*/ /* check %2==0 for 2D geometries; and %3==0 for element info triplets */

    if (success && osCheck2DGtype(gtype)) {
      success = (nords%2==0 && nelems%3==0)?1:0; /* check %2==0 for 2D geometries; and %3==0 for element info triplets */
    } else if (success && osCheck3DGtype(gtype)) {
      success = (nords%3==0 && nelems%3==0)?1:0; /* check %2==0 for 2D geometries; and %3==0 for element info triplets */
      data3d = 1;

    } else if (success && osCheck4DGtype(gtype)) {
      success = (nords%4==0 && nelems%3==0)?1:0; /* check %2==0 for 2D geometries; and %3==0 for element info triplets */
      data4d = 1;
    }


    if (success) {
      /* reading SDO_POINT from SDO_GEOMETRY for a 2D/3D point geometry */
      if ((gtype==2001 || gtype==3001 || gtype==4001 ) && ind->point._atomic == OCI_IND_NOTNULL && ind->point.x == OCI_IND_NOTNULL && ind->point.y == OCI_IND_NOTNULL) {


        success = TRY( hand, OCINumberToReal( hand->errhp, &(obj->point.x), (uword)sizeof(double), (dvoid *)&x ) )
                  && TRY( hand, OCINumberToReal( hand->errhp, &(obj->point.y), (uword)sizeof(double), (dvoid *)&y ) );

        if (ERROR( "osGetOrdinates()", hand, dthand ))
          return MS_FAILURE;

        shape->type = MS_SHAPE_POINT;

        points.numpoints = 1;
        points.point = point5;
        point5[0].x = x;
        point5[0].y = y;
#ifdef USE_POINT_Z_M
        if (data3d || data4d) {
          if (ind->point.z == OCI_IND_NOTNULL) {
            success = TRY( hand, OCINumberToReal( hand->errhp, &(obj->point.z), (uword)sizeof(double), (dvoid *)&z ));
            if (ERROR( "osGetOrdinates()", hand, dthand ))
              return MS_FAILURE;
            else
              point5[0].z = z;
          } else
            point5[0].z = z;
        }
#endif /* USE_POINT_Z_M */
        msAddLine( shape, &points );
        return MS_SUCCESS;
      }
      /* if SDO_POINT not fetched, proceed reading elements (element info/ordinates) */
      success = TRY( hand, OCICollGetElem( hand->envhp, hand->errhp, (OCIColl *)obj->elem_info,(sb4)0, (boolean *)&exists, (dvoid *)&oci_number, (dvoid **)0 ) )
                && TRY( hand, OCINumberToInt( hand->errhp, oci_number, (uword)sizeof(ub4), OCI_NUMBER_SIGNED, (dvoid *)&ord_end ) );

      elem = 0;
      ord_end--; /* shifts offset from 1..n to 0..n-1 */

      do {
        ord_start = ord_end;
        if (elem+3 >= nelems) { /* processing last element */
          ord_end = nords;
          success = 1;
        } else { /* get start ordinate position for next element which is ord_end for this element */
          success = TRY( hand, OCICollGetElem( hand->envhp, hand->errhp, (OCIColl *)obj->elem_info, (sb4)elem+3, (boolean *)&exists, (dvoid *)&oci_number, (dvoid **)0 ) )
                    && TRY( hand, OCINumberToInt( hand->errhp, oci_number, (uword)sizeof(ub4), OCI_NUMBER_SIGNED, (dvoid *)&ord_end ) );

          ord_end--; /* shifts offset from 1..n to 0..n-1 */
        }
        success = (success
                   && TRY( hand, OCICollGetElem( hand->envhp, hand->errhp, (OCIColl *)obj->elem_info, (sb4)elem+1, (boolean *)&exists, (dvoid *)&oci_number, (dvoid **)0) )
                   && TRY( hand, OCINumberToInt( hand->errhp, oci_number, (uword)sizeof(ub4), OCI_NUMBER_UNSIGNED, (dvoid *)&etype ) )
                   && TRY( hand, OCICollGetElem( hand->envhp, hand->errhp, (OCIColl *)obj->elem_info, (sb4)elem+2, (boolean *)&exists, (dvoid *)&oci_number, (dvoid **)0 ) )
                   && TRY( hand, OCINumberToInt( hand->errhp, oci_number, (uword)sizeof(ub4), OCI_NUMBER_UNSIGNED, (dvoid *)&interpretation ) ));

        if (ERROR( "osGetOrdinates()", hand, dthand ))
          return MS_FAILURE;

        if ( etype == 1005 || etype == 2005  || etype == 4 ) {
          compound_type = 1;
          compound_lenght = interpretation;
          compound_count = 0;
          msInitShape(&newshape);
        }

        elem_type = (etype == 1 && interpretation > 1) ? 10 : ((etype%10)*10 + interpretation);


        /* msDebug("osGetOrdinates shape->index = %ld\telem_type =  %d\n",shape->index, elem_type); */

        switch (elem_type) {
          case 10: /* point cluster with 'interpretation'-points */
            osPointCluster (hand, shape, obj, ord_start, ord_end, points, interpretation, data3d, data4d);
            break;
          case 11: /* point type */
            osPoint(hand, shape, obj, ord_start, ord_end, points, point5, data3d, data4d);
            break;
          case 21: /* line string whose vertices are connected by straight line segments */
            if (compound_type)
              osClosedPolygon(hand, &newshape, obj, ord_start, (compound_count<compound_lenght)?ord_end+2:ord_end, points, elem_type, data3d, data4d);
            else
              osClosedPolygon(hand, shape, obj, ord_start, ord_end, points, elem_type, data3d, data4d);
            break;
          case 22: /* compound type */
            if (compound_type)
              osArcPolygon(hand, &newshape, obj, ord_start, (compound_count<compound_lenght)?ord_end+2:ord_end , points, elem_type, data3d, data4d);
            else
              osArcPolygon(hand, shape, obj, ord_start, ord_end, points, elem_type, data3d, data4d);
            break;
          case 31: /* simple polygon with n points, last point equals the first one */
            osClosedPolygon(hand, shape, obj, ord_start, ord_end, points, elem_type, data3d, data4d);
            break;
          case 32: /* Polygon with arcs */
            osArcPolygon(hand, shape, obj, ord_start, ord_end, points, elem_type, data3d, data4d);
            break;
          case 33: /* rectangle defined by 2 points */
            osRectangle(hand, shape, obj, ord_start, ord_end, points, point5, data3d, data4d);
            break;
          case 34: /* circle defined by 3 points */
            osCircle(hand, shape, obj, ord_start, ord_end, points, point5, data3d, data4d);
            break;
        }

        if (compound_count >= compound_lenght) {
          osCloneShape(&newshape, shape, data3d, data4d);
          msFreeShape(&newshape);
        }

        if (ERROR( "osGetOrdinates()", hand, dthand ))
          return MS_FAILURE;

        /* prepare for next cycle */
        ord_start = ord_end;
        elem += 3;

        if (compound_type)
          compound_count++;

      } while (elem < nelems); /* end of element loop */
    } /* end of gtype big-if */
  } /* end of not-null-object if */

  if (compound_type){
    if (gtype == 2003 || gtype == 2007)
      shape->type = MS_SHAPE_POLYGON;
    msFreeShape(&newshape);
  }

  return MS_SUCCESS;
}

static void msOCICloseConnection( void *hand )
{
  msOCICloseHandlers( (msOracleSpatialHandler *)hand );
}

/* opens a layer by connecting to db with username/password@database stored in layer->connection */
int msOracleSpatialLayerOpen( layerObj *layer )
{
  char *username = NULL, *password = NULL, *dblink =  NULL;

  msOracleSpatialLayerInfo *layerinfo = NULL;
  msOracleSpatialDataHandler *dthand = NULL;
  msOracleSpatialStatement *sthand = NULL, *sthand2 = NULL;
  msOracleSpatialHandler *hand = NULL;

  if (layer->debug >=2)
    msDebug("msOracleSpatialLayerOpen called with: %s (Layer pointer %p)\n",layer->data, layer);

  if (layer->layerinfo != NULL) /* Skip if layer is already open */
    return MS_SUCCESS;

  if (layer->data == NULL) {
    msDebug(    "Error parsing OracleSpatial DATA variable. Must be:"
                "'geometry_column FROM table_name [USING UNIQUE <column> SRID srid# FUNCTION]' or "
                "'geometry_column FROM (SELECT stmt) [USING UNIQUE <column> SRID srid# FUNCTION]'."
                "If want to set the FUNCTION statement you can use: FILTER, RELATE, GEOMRELATE or NONE.\n");
    msSetError( MS_ORACLESPATIALERR,
                "Error parsing OracleSpatial DATA variable. More info in server logs", "msOracleSpatialLayerOpen()");

    return MS_FAILURE;
  }

  layerinfo = (msOracleSpatialLayerInfo *)malloc(sizeof(msOracleSpatialLayerInfo));
  dthand = (msOracleSpatialDataHandler *)malloc(sizeof(msOracleSpatialDataHandler));
  sthand = (msOracleSpatialStatement *)malloc(sizeof(msOracleSpatialStatement));
  sthand2 = (msOracleSpatialStatement *)malloc(sizeof(msOracleSpatialStatement));

  if ((dthand == NULL) || (layerinfo == NULL)) {
    msSetError(MS_MEMERR, NULL, "msOracleSpatialLayerOpen()");
    return MS_FAILURE;
  }

  memset( dthand, 0, sizeof(msOracleSpatialDataHandler) );
  memset( sthand, 0, sizeof(msOracleSpatialStatement) );
  memset( sthand2, 0, sizeof(msOracleSpatialStatement) );
  memset( layerinfo, 0, sizeof(msOracleSpatialLayerInfo) );
  layerinfo->paging = MS_TRUE;

  msSplitLogin( layer->connection, layer->map, &username, &password, &dblink );

  hand = (msOracleSpatialHandler *) msConnPoolRequest( layer );

  if( hand == NULL ) {

    hand = msOCISetHandlers( username, password, dblink );

    if (hand == NULL) {
      msOCICloseDataHandlers( dthand );
      msOCIFinishStatement( sthand );
      msOCIFinishStatement( sthand2 );
      msOCIClearLayerInfo( layerinfo );

      if (username) free(username);
      if (password) free(password);
      if (dblink) free(dblink);

      return MS_FAILURE;
    }

    if ( layer->debug >=2)
      msDebug("msOracleSpatialLayerOpen. Shared connection not available. Creating one.\n");

    msConnPoolRegister( layer, hand, msOCICloseConnection );
  } else {
    hand->ref_count++;
    hand->last_oci_status = MS_SUCCESS;
    hand->last_oci_error[0] = (text)'\0';
  }

  if (!(msOCISetDataHandlers(hand, dthand) & msOCIOpenStatement(hand, sthand) & msOCIOpenStatement(hand, sthand2))) {
    msSetError( MS_ORACLESPATIALERR,
                "Cannot create OCI LayerInfo. "
                "Connection failure.",
                "msOracleSpatialLayerOpen()");

    if (layer->debug>=2)
      msDebug("msOracleSpatialLayerOpen. Cannot create OCI LayerInfo. Connection failure.\n");

    msOCICloseDataHandlers ( dthand );
    msOCICloseHandlers( hand );
    msOCIClearLayerInfo( layerinfo );
  }
  layerinfo->orahandlers = hand;
  layerinfo->oradatahandlers = dthand;
  layerinfo->orastmt = sthand;
  layerinfo->orastmt2 = sthand2;
  layer->layerinfo = layerinfo;

  if (username) free(username);
  if (password) free(password);
  if (dblink) free(dblink);

  return layer->layerinfo != NULL ? MS_SUCCESS : MS_FAILURE;
}

/* return MS_TRUE if layer is open, MS_FALSE otherwise.*/
int msOracleSpatialLayerIsOpen(layerObj *layer)
{
  if (layer->layerinfo != NULL)
    return MS_TRUE;

  return MS_FALSE;
}

/* closes the layer, disconnecting from db if connected. layer->layerinfo is freed */
int msOracleSpatialLayerClose( layerObj *layer )
{
  msOracleSpatialLayerInfo *layerinfo = (msOracleSpatialLayerInfo *)layer->layerinfo;
  /*int lIntSuccessFree = 0;*/

  if (layer->debug>=2)
    msDebug("msOracleSpatialLayerClose was called. Layer: %p, Layer name: %s\n", layer, layer->name);

  if (layerinfo != NULL) {

    /*
     * Some errors with the OCIObjectFree with query function
     * If uncomment draw mode will work but no query modes
     * Need to investigate the error cause
     */
    /*lIntSuccessFree = TRY (layerinfo->orahandlers, OCIObjectFree(layerinfo->orahandlers->envhp, layerinfo->orahandlers->errhp, (dvoid *)layerinfo->obj, (ub2)OCI_OBJECTFREE_FORCE));
     *if (!lIntSuccessFree)
     *  msDebug("Error: %s\n", layerinfo->orahandlers->last_oci_error);
     */
    /* Release Statement Handles */
    if (layerinfo->orastmt != NULL) {
      msOCIFinishStatement(layerinfo->orastmt);
      layerinfo->orastmt = NULL;
    }
    if (layerinfo->orastmt2 != NULL) {
      msOCIFinishStatement(layerinfo->orastmt2);
      layerinfo->orastmt2 = NULL;
    }

    /* Release Datahandlers */
    if (layer->debug>=4)
      msDebug("msOracleSpatialLayerClose. Cleaning layerinfo handlers.\n");
    msOCICloseDataHandlers( layerinfo->oradatahandlers );
    layerinfo->oradatahandlers = NULL;

    /* Free the OCI cache only if there is no more layer that could use it */
    layerinfo->orahandlers->ref_count--;
    if (layerinfo->orahandlers->ref_count == 0)
      OCICacheFree (layerinfo->orahandlers->envhp, layerinfo->orahandlers->errhp, layerinfo->orahandlers->svchp);

    /* Release Mapserver Pool */
    if (layer->debug>=4)
      msDebug("msOracleSpatialLayerClose. Release the Oracle Pool.\n");
    msConnPoolRelease( layer, layerinfo->orahandlers );

    /* Release Layerinfo */
    layerinfo->orahandlers = NULL;

    msOCIClearLayerInfo( layerinfo );
    layer->layerinfo = NULL;
  }

  return MS_SUCCESS;
}

/* create SQL statement for retrieving shapes */
/* Sets up cursor for use in *NextShape and *GetShape */
int msOracleSpatialLayerWhichShapes( layerObj *layer, rectObj rect, int isQuery)
{
  int success, i;
  int function = 0;
  int version = 0;
  char query_str[6000];
  char query_str2[256];
  char *tmp_str=NULL, *tmp1_str=NULL;
  char *table_name;
  char *geom_column_name = NULL, *unique = NULL, *srid = NULL, *indexfield=NULL;
  OCIDefine *adtp = NULL;
  OCIDefine **items = NULL;
  OCINumber oci_number;
  OCIBind *bnd1p = NULL,  *bnd2p = NULL;
  
  int existunique = MS_FALSE;
  int rownumisuniquekey = MS_FALSE;
  int numitemsinselect = 0;

  /* get layerinfo */
  msOracleSpatialLayerInfo *layerinfo = (msOracleSpatialLayerInfo *)layer->layerinfo;
  msOracleSpatialDataHandler *dthand = NULL;
  msOracleSpatialHandler *hand = NULL;
  msOracleSpatialStatement *sthand = NULL;

  if (layer->debug>=3)
    msDebug("msOracleSpatialLayerWhichShapes was called.\n");

  if (layerinfo == NULL) {
    msSetError( MS_ORACLESPATIALERR,
                "msOracleSpatialLayerWhichShapes called on unopened layer",
                "msOracleSpatialLayerWhichShapes()" );

    return MS_FAILURE;
  } else {
    dthand = (msOracleSpatialDataHandler *)layerinfo->oradatahandlers;
    hand = (msOracleSpatialHandler *)layerinfo->orahandlers;
    sthand = (msOracleSpatialStatement *)layerinfo->orastmt2;
  }

  /*init uniqueindex field*/
  sthand->uniqueidindex=0;

  table_name = (char *) malloc(sizeof(char) * TABLE_NAME_SIZE);
  /* parse geom_column_name and table_name */
  if (!msSplitData( layer->data, &geom_column_name, &table_name, &unique, &srid, &indexfield, &function, &version)) {
    msDebug( "Error parsing OracleSpatial DATA variable. Must be:"
                "'geometry_column FROM table_name [USING UNIQUE <column> SRID srid# FUNCTION]' or "
                "'geometry_column FROM (SELECT stmt) [USING UNIQUE <column> SRID srid# FUNCTION]'."
                "If want to set the FUNCTION statement you can use: FILTER, RELATE, GEOMRELATE or NONE."
                "Your data statement: (%s)"
                "in msOracleSpatialLayerWhichShapes()\n", layer->data );
    msSetError( MS_ORACLESPATIALERR,
                "Error parsing OracleSpatial DATA variable. More info in server logs",
                "msOracleSpatialLayerWhichShapes()" );

    if (geom_column_name) free(geom_column_name);
    if (srid) free(srid);
    if (unique) free(unique);
    if (indexfield) free(indexfield);
    free(table_name);
    return MS_FAILURE;
  }

  /*rownum will be the first in the select if no UNIQUE key is defined or
    will be added at the end of the select*/
  rownumisuniquekey = MS_TRUE;
  /*Define the unique*/
  if (unique[0] == '\0')
    strcpy( unique, "rownum" );
  else
    rownumisuniquekey = MS_FALSE;

  /* Check if the unique field is already in the items list */
  existunique = MS_FALSE;
  if (unique) {
    for( i=0; i < layer->numitems; ++i ) {
      if (strcasecmp(unique, layer->items[i])==0) {
        sthand->uniqueidindex = i;
        existunique = MS_TRUE;
        break;
      }
    }
  }

  /* If no SRID is provided, set it to -1 (NULL) for binding */
  if (strcmp(srid,"NULL") == 0)
    strcpy(srid,"-1");

  snprintf( query_str, sizeof(query_str), "SELECT ");
  numitemsinselect = layer->numitems;
  /* allocate enough space for items */
  if (layer->numitems >= 0) {
    /*we will always add a rownumber in the selection*/
    numitemsinselect++;

    /*if unique key in the data is specfied and is not part of the current item lists,
      we should add it to the select*/
    if(existunique == MS_FALSE && rownumisuniquekey == MS_FALSE)
      numitemsinselect++;

    /*the usinque index is there was no uniqueid given or the uniqueid given was not part of the items lists*/
    if (existunique == MS_FALSE)
      sthand->uniqueidindex = layer->numitems;

    sthand->items = (item_text_array *)malloc( sizeof(item_text_array) * (numitemsinselect) );
    if (sthand->items == NULL) {
      msSetError( MS_ORACLESPATIALERR,"Cannot allocate layerinfo->items buffer","msOracleSpatialLayerWhichShapes()" );
      if (geom_column_name) free(geom_column_name);
      if (srid) free(srid);
      if (unique) free(unique);
      if(indexfield) free(indexfield);
      free(table_name);
      return MS_FAILURE;
    }

    items = (OCIDefine **)malloc(sizeof(OCIDefine *)*(numitemsinselect));
    if (items == NULL) {
      msSetError( MS_ORACLESPATIALERR,"Cannot allocate items buffer","msOracleSpatialLayerWhichShapes()" );
      if (geom_column_name) free(geom_column_name);
      if (srid) free(srid);
      if (unique) free(unique);
      if(indexfield) free(indexfield);
      free(table_name);
      return MS_FAILURE;
    }
    memset(items ,0,sizeof(OCIDefine *)*(numitemsinselect));
  }

  /* define SQL query */
  for( i=0; i < layer->numitems; ++i ) {
      
      snprintf( query_str + strlen(query_str), sizeof(query_str)-strlen(query_str), "\"%s\", ", layer->items[i] );
  }

  /*we add the uniqueid if it was not part of the current item list*/
  if(existunique == MS_FALSE && rownumisuniquekey == MS_FALSE)
    snprintf( query_str + strlen(query_str), sizeof(query_str)-strlen(query_str), "%s,", unique);

  /*we always want to add rownum is the selection to allow paging to work*/
  snprintf( query_str + strlen(query_str), sizeof(query_str)-strlen(query_str), "%s, ", "rownum");


  snprintf( query_str + strlen(query_str), sizeof(query_str)-strlen(query_str), "%s FROM %s", geom_column_name, table_name );

  osFilteritem(layer, function, query_str, sizeof(query_str), 1);

  if (layerinfo->paging && layer->maxfeatures > 0 && layer->startindex < 0) {
    if (function == FUNCTION_NONE && layer->filter.native_string == NULL)
      snprintf( query_str + strlen(query_str), sizeof(query_str)-strlen(query_str), "%s"," WHERE ");
    else if (function == FUNCTION_NONE && layer->filter.native_string != NULL)
      snprintf( query_str + strlen(query_str), sizeof(query_str)-strlen(query_str), "%s"," AND ");
    snprintf( query_str + strlen(query_str), sizeof(query_str)-strlen(query_str), " ROWNUM<=%d ", layer->maxfeatures);
    if (function != FUNCTION_NONE)
      snprintf (query_str + strlen(query_str), sizeof(query_str)-strlen(query_str), " AND ");
  }

  if ((((atol(srid) >= 8192) && (atol(srid) <= 8330)) || (atol(srid) == 2) || (atol(srid) == 5242888) || (atol(srid) == 2000001)) && (version == VERSION_9i))
    osGeodeticData(function, version, query_str, sizeof(query_str), geom_column_name, indexfield, srid, rect);
  else
    osNoGeodeticData(function, version, query_str, sizeof(query_str), geom_column_name, indexfield, srid, rect);

  if( layer->sortBy.nProperties > 0 ) {
      msDebug("Layer sorting is requested\n");
      tmp1_str = msLayerBuildSQLOrderBy(layer);
      snprintf( query_str + strlen(query_str), sizeof(query_str)-strlen(query_str), " ORDER BY %s  ", tmp1_str );
      msFree(tmp1_str);
    }

  /*assuming startindex starts at 1*/
  if (layerinfo->paging && layer->startindex > 0) {
    tmp1_str = msStrdup("SELECT * from (SELECT atmp.*, ROWNUM rnum from (");
    tmp_str = msStringConcatenate(tmp_str,  tmp1_str);
    msFree(tmp1_str);
    tmp_str = msStringConcatenate(tmp_str, query_str);
    /*oder by rowid does not seem to work with function using the spatial filter, at least
      on layers loaded using ogr in a 11g database*/
    if (function == FUNCTION_NONE  || function == FUNCTION_RELATE || function == FUNCTION_GEOMRELATE)
      tmp1_str = msStrdup( "order by rowid");
    /* Populate strOrderBy, if necessary */
    else
      tmp1_str = msStrdup("");

    if (layer->maxfeatures > 0)
      snprintf(query_str2, sizeof(query_str2),  " %s) atmp where ROWNUM<=%d) where rnum >=%d",   tmp1_str,
               layer->maxfeatures+layer->startindex-1,  layer->startindex);
    else
      snprintf( query_str2, sizeof(query_str2),  " %s) atmp) where rnum >=%d",  tmp1_str, layer->startindex);
    msFree(tmp1_str);

    tmp_str = msStringConcatenate(tmp_str,  query_str2);
    snprintf(query_str, sizeof(query_str), "%s", tmp_str);
    msFree(tmp_str);
  }


  if (layer->debug)
    msDebug("msOracleSpatialLayerWhichShapes. Using this Sql to retrieve the data: %s\n", query_str);

  if (layer->debug)
    msDebug("msOracleSpatialLayerWhichShapes. Bind values: srid:%s   minx:%f   miny:%f  maxx:%f   maxy:%f \n", srid, rect.minx, rect.miny, rect.maxx, rect.maxy);

  /* prepare */
  success = TRY( hand, OCIStmtPrepare( sthand->stmthp, hand->errhp, (text *)query_str, (ub4)strlen(query_str), (ub4)OCI_NTV_SYNTAX, (ub4)OCI_DEFAULT) );

  if (layer->debug>=4)
    msDebug("msOracleSpatialLayerWhichShapes getting ordinate definition.\n");

  /* get the object definition of the ordinate array */
  ordinates_tdo = get_tdo(SDO_ORDINATE_ARRAY, hand, dthand );

  if (layer->debug>=4)
    msDebug("msOracleSpatialLayerWhichShapes converting to OCIColl.\n");

  /* initialized the collection array */
  success = TRY( hand, OCIObjectNew(hand->envhp, hand->errhp, hand->svchp, OCI_TYPECODE_VARRAY, ordinates_tdo, (dvoid *)NULL, OCI_DURATION_SESSION, FALSE, (dvoid **)&ordinates) );

  /* convert it to a OCI number and then append minx...maxy to the collection */
  success = TRY ( hand, OCINumberFromReal(hand->errhp, (dvoid *)&(rect.minx), (uword)sizeof(double),(dvoid *)&oci_number))
            &&TRY ( hand, OCICollAppend(hand->envhp, hand->errhp,(dvoid *) &oci_number,(dvoid *)0, (OCIColl *)ordinates))
            &&TRY ( hand, OCINumberFromReal(hand->errhp, (dvoid *)&(rect.miny), (uword)sizeof(double),(dvoid *)&oci_number))
            &&TRY ( hand, OCICollAppend(hand->envhp, hand->errhp,(dvoid *) &oci_number,(dvoid *)0, (OCIColl *)ordinates))
            &&TRY ( hand, OCINumberFromReal(hand->errhp, (dvoid *)&(rect.maxx), (uword)sizeof(double),(dvoid *)&oci_number))
            &&TRY ( hand, OCICollAppend(hand->envhp, hand->errhp,(dvoid *) &oci_number,(dvoid *)0, (OCIColl *)ordinates))
            &&TRY ( hand, OCINumberFromReal(hand->errhp, (dvoid *)&(rect.maxy), (uword)sizeof(double),(dvoid *)&oci_number))
            &&TRY ( hand, OCICollAppend(hand->envhp, hand->errhp,(dvoid *) &oci_number,(dvoid *)0, (OCIColl *)ordinates));


  if (layer->debug>=3)
    msDebug("msOracleSpatialLayerWhichShapes bind by name and object.\n");

  /* do the actual binding */

  if (success && function != FUNCTION_NONE) {
    const char* bind_key;
    char* bind_value;
    char* bind_tag;
    success = TRY( hand,
                   /* bind in srid */
                   OCIBindByName( sthand->stmthp, &bnd2p,  hand->errhp, (text *) ":srid", strlen(":srid"),(ub1 *) srid,  strlen(srid)+1, SQLT_STR,
                                  (dvoid *) 0, (ub2 *) 0, (ub2) 0, (ub4) 0, (ub4 *) 0, OCI_DEFAULT) )
              && TRY(hand,
                     /* bind in rect by name */
                     OCIBindByName( sthand->stmthp, &bnd1p,  hand->errhp,  (text *)":ordinates", -1, (dvoid *)0, (sb4)0, SQLT_NTY, (dvoid *)0, (ub2 *)0,(ub2 *)0, (ub4)0, (ub4 *)0, (ub4)OCI_DEFAULT))
              && TRY(hand,
                     /* bind in rect object */
                     OCIBindObject(bnd1p, hand->errhp, ordinates_tdo, (dvoid **)&ordinates, (ub4 *)0, (dvoid **)0, (ub4 *)0));

    /* bind the variables from the bindvals hash */
    bind_key = (char*)msFirstKeyFromHashTable(&layer->bindvals);
    while(bind_key != NULL) {
      bind_value = msLookupHashTable(&layer->bindvals, bind_key);
      bind_tag = (char*)malloc(sizeof(char) * strlen(bind_key) + 2);
      sprintf(bind_tag, ":%s", bind_key);

      success = success && TRY(hand, OCIBindByName( sthand->stmthp, &bnd2p,  hand->errhp, (text *)bind_tag, strlen(bind_tag),(ub1 *) bind_value,  strlen(bind_value)+1, SQLT_STR,
                               (dvoid *) 0, (ub2 *) 0, (ub2) 0, (ub4) 0, (ub4 *) 0, OCI_DEFAULT));
      bind_key = msNextKeyFromHashTable(&layer->bindvals, bind_key);
    }
  }


  if (layer->debug>=3)
    msDebug("msOracleSpatialLayerWhichShapes name and object now bound.\n");


  if (success && layer->numitems >= 0) {
    for( i=0; i < numitemsinselect && success; ++i ){
      if (i< numitemsinselect -1) {
        //msDebug("Defining by POS, for %s\n", layer->items[i]);
        //msDebug("datatype retrieved is %i\n", layer->iteminfo);
      }
      success = TRY( hand, OCIDefineByPos( sthand->stmthp, &items[i], hand->errhp, (ub4)i+1, (dvoid *)sthand->items[i], (sb4)TEXT_SIZE, SQLT_STR, (dvoid *)0, (ub2 *)0, (ub2 *)0, (ub4)OCI_DEFAULT ) );
    }
  }


  if (success) {
    int cursor_type = OCI_DEFAULT;
    if(isQuery) cursor_type =OCI_STMT_SCROLLABLE_READONLY;

    success = TRY( hand,
                   /* define spatial position adtp ADT object */
                   OCIDefineByPos( sthand->stmthp, &adtp, hand->errhp, (ub4)numitemsinselect+1, (dvoid *)0, (sb4)0, SQLT_NTY, (dvoid *)0, (ub2 *)0, (ub2 *)0, (ub4)OCI_DEFAULT) )
              && TRY( hand,
                      /* define object tdo from adtp */
                      OCIDefineObject( adtp, hand->errhp, dthand->tdo, (dvoid **)sthand->obj, (ub4 *)0, (dvoid **)sthand->ind, (ub4 *)0 ) )
              && TRY(hand,
                     /* execute */
                     OCIStmtExecute( hand->svchp, sthand->stmthp, hand->errhp, (ub4)ARRAY_SIZE, (ub4)0, (OCISnapshot *)NULL, (OCISnapshot *)NULL, (ub4)cursor_type ) )
              &&  TRY( hand,
                       /* get rows fetched */
                       OCIAttrGet( (dvoid *)sthand->stmthp, (ub4)OCI_HTYPE_STMT, (dvoid *)&sthand->rows_fetched, (ub4 *)0, (ub4)OCI_ATTR_ROWS_FETCHED, hand->errhp ) )
              && TRY( hand,
                      /* get rows count */
                      OCIAttrGet( (dvoid *)sthand->stmthp, (ub4)OCI_HTYPE_STMT, (dvoid *)&sthand->rows_count, (ub4 *)0, (ub4)OCI_ATTR_ROW_COUNT, hand->errhp ) );
  }

  if (!success) {
    msDebug( "Error: %s . "
                "Query statement: %s . "
                "Check your data statement."
                "msOracleSpatialLayerWhichShapes()\n", hand->last_oci_error, query_str );
    msSetError( MS_ORACLESPATIALERR,
                "Check your data statement and server logs",
                "msOracleSpatialLayerWhichShapes()");

    /* clean items */
    free(items);
    if (geom_column_name) free(geom_column_name);
    if (srid) free(srid);
    if (unique) free(unique);
    if (indexfield) free(indexfield);
    free(table_name);

    return MS_FAILURE;
  }

  /* should begin processing first row */
  sthand->row_num = sthand->row = 0;

  /* clean items */
  free(items);
  if (geom_column_name) free(geom_column_name);
  if (srid) free(srid);
  if (unique) free(unique);
  if (indexfield) free(indexfield);
  free(table_name);

  return MS_SUCCESS;
}

/* fetch next shape from previous SELECT stmt (see *WhichShape()) */
int msOracleSpatialLayerNextShape( layerObj *layer, shapeObj *shape )
{
  SDOGeometryObj *obj;
  SDOGeometryInd *ind;
  int success, /*lIntSuccessFree,*/ i;

  /* get layerinfo */
  msOracleSpatialLayerInfo *layerinfo = (msOracleSpatialLayerInfo *)layer->layerinfo;
  msOracleSpatialDataHandler *dthand = NULL;
  msOracleSpatialHandler *hand = NULL;
  msOracleSpatialStatement *sthand = NULL;


  if (layerinfo == NULL) {
    msSetError( MS_ORACLESPATIALERR, "msOracleSpatialLayerWhichShapes called on unopened layer", "msOracleSpatialLayerNextShape()" );
    return MS_FAILURE;
  } else {
    dthand = (msOracleSpatialDataHandler *)layerinfo->oradatahandlers;
    hand = (msOracleSpatialHandler *)layerinfo->orahandlers;
    sthand = (msOracleSpatialStatement *)layerinfo->orastmt2;
  }

  /* no rows fetched */
  if (sthand->rows_fetched == 0)
    return MS_DONE;

  if(layer->debug >=5 )
    msDebug("msOracleSpatialLayerNextShape on layer %p, row_num: %d\n", layer, sthand->row_num);

  do {
    /* is buffer empty? */
    if (sthand->row >= sthand->rows_fetched) {
      /* fetch more */
      success = TRY( hand, OCIStmtFetch2( sthand->stmthp, hand->errhp, (ub4)ARRAY_SIZE, (ub2)OCI_FETCH_NEXT, (sb4)0, (ub4)OCI_DEFAULT ) )
                && TRY( hand, OCIAttrGet( (dvoid *)sthand->stmthp, (ub4)OCI_HTYPE_STMT, (dvoid *)&sthand->rows_fetched, (ub4 *)0, (ub4)OCI_ATTR_ROWS_FETCHED, hand->errhp ) )
                && TRY( hand, OCIAttrGet( (dvoid *)sthand->stmthp, (ub4)OCI_HTYPE_STMT, (dvoid *)&sthand->rows_count, (ub4 *)0, (ub4)OCI_ATTR_ROW_COUNT, hand->errhp ) );

  
      if (!success || sthand->rows_fetched == 0 || sthand->row_num >= sthand->rows_count) {
        hand->last_oci_status=MS_SUCCESS;
        return MS_DONE;
      }
      if(layer->debug >= 4 )
        msDebug("msOracleSpatialLayerNextShape on layer %p, Fetched %d more rows (%d total)\n", layer, sthand->rows_fetched, sthand->rows_count);

      sthand->row = 0; /* reset buffer row index */
    }

    /* set obj & ind for current row */
    obj = sthand->obj[ sthand->row ];
    ind = sthand->ind[ sthand->row ];

    /* get the items for the shape */
    shape->index = atol( (char *)(sthand->items[sthand->uniqueidindex][ sthand->row ])); /* Primary Key */
    shape->resultindex = sthand->row_num;
    shape->numvalues = layer->numitems;

    shape->values = (char **)malloc( sizeof(char*) * shape->numvalues );
    if (shape->values == NULL) {
      msSetError( MS_ORACLESPATIALERR, "No memory avaliable to allocate the values", "msOracleSpatialLayerNextShape()" );
      return MS_FAILURE;
    }

    for( i=0; i < shape->numvalues; ++i ) {
      shape->values[i] = (char *)malloc(strlen((char *)sthand->items[i][ sthand->row ])+1);
      if (shape->values[i] == NULL) {
        msSetError( MS_ORACLESPATIALERR, "No memory avaliable to allocate the items", "msOracleSpatialLayerNextShape()" );
        return MS_FAILURE;
      } else {
        strcpy(shape->values[i], (char *)sthand->items[i][ sthand->row ]);
        shape->values[i][strlen((char *)sthand->items[i][ sthand->row ])] = '\0';
      }
    }

    /* fetch a layer->type object */
    success = osGetOrdinates(dthand, hand, shape, obj, ind);

    /* increment for next row */
    sthand->row_num++;
    sthand->row++;

    if (success != MS_SUCCESS) {
      return MS_FAILURE;
    }

    osShapeBounds(shape);
  } while(shape->type == MS_SHAPE_NULL);

  return MS_SUCCESS;
}

int msOracleSpatialLayerGetShape( layerObj *layer, shapeObj *shape, resultObj *record)
{
  int success, i;
  SDOGeometryObj *obj;
  SDOGeometryInd *ind;
  msOracleSpatialDataHandler *dthand = NULL;
  msOracleSpatialHandler *hand = NULL;
  msOracleSpatialLayerInfo *layerinfo;
  msOracleSpatialStatement *sthand = NULL;

  long shapeindex = record->shapeindex;
  int resultindex = record->resultindex;

  if(layer == NULL) {
    msSetError( MS_ORACLESPATIALERR, "msOracleSpatialLayerGetShape called on unopened layer","msOracleSpatialLayerGetShape()" );
    return MS_FAILURE;
  }

  layerinfo = (msOracleSpatialLayerInfo *)layer->layerinfo;

  if (layerinfo == NULL) {
    msSetError( MS_ORACLESPATIALERR, "msOracleSpatialLayerGetShape called on unopened layer (layerinfo)","msOracleSpatialLayerGetShape()" );
    return MS_FAILURE;
  }

  /* If resultindex is set, fetch the shape from the resultcache, otherwise fetch it from the DB  */
  if (resultindex >= 0) {
    long buffer_first_row_num, buffer_last_row_num;

    /* get layerinfo */
    dthand = (msOracleSpatialDataHandler *)layerinfo->oradatahandlers;
    hand = (msOracleSpatialHandler *)layerinfo->orahandlers;
    sthand = (msOracleSpatialStatement *)layerinfo->orastmt2;

    if (layer->resultcache == NULL) {
      msSetError( MS_ORACLESPATIALERR, "msOracleSpatialLayerGetShape called before msOracleSpatialLayerWhichShapes()","msOracleSpatialLayerGetShape()" );
      return MS_FAILURE;
    }

    if (resultindex >= sthand->rows_count) {
      if (layer->debug >= 5)
               msDebug("msOracleSpatialLayerGetShape problem with cursor. Trying to fetch record = %d of %d, falling back to GetShape\n", resultindex, sthand->rows_count);

      msSetError( MS_ORACLESPATIALERR, "msOracleSpatialLayerGetShape record out of range","msOracleSpatialLayerGetShape()" );
      return MS_FAILURE;
    }

    if (layer->debug >= 5)
      msDebug("msOracleSpatialLayerGetShape was called. Using the record = %d of %d. (shape: %ld should equal pkey: %ld)\n",
              resultindex, layer->resultcache->numresults, layer->resultcache->results[resultindex].shapeindex, shapeindex);

    /* NOTE: with the way the resultcache works, we should see items in increasing order, but some may have been filtered out. */
    /* Best case: item in buffer */
    /* Next best case: item is in next fetch block */
    /* Worst case: item is random access */
    buffer_first_row_num = sthand->row_num - sthand->row; /* cursor id of first item in buffer */
    buffer_last_row_num  = buffer_first_row_num + sthand->rows_fetched - 1; /* cursor id of last item in buffer */
    if(resultindex >= buffer_first_row_num && resultindex <= buffer_last_row_num) { /* Item is in buffer. Calculate position in buffer */
      sthand->row += resultindex - sthand->row_num; /* move sthand row an row_num by offset from last call */
      sthand->row_num += resultindex - sthand->row_num;
    } else { /* Item is not in buffer. Fetch item from Oracle */
      if (layer->debug >= 4)
        msDebug("msOracleSpatialLayerGetShape: Fetching result from DB start: %ld end:%ld record: %d\n", buffer_first_row_num, buffer_last_row_num, resultindex);

      success = TRY( hand, OCIStmtFetch2( sthand->stmthp, hand->errhp, (ub4)ARRAY_SIZE, (ub2)OCI_FETCH_ABSOLUTE, (sb4)resultindex+1, (ub4)OCI_DEFAULT ) )
                && TRY( hand, OCIAttrGet( (dvoid *)sthand->stmthp, (ub4)OCI_HTYPE_STMT, (dvoid *)&sthand->rows_fetched, (ub4 *)0, (ub4)OCI_ATTR_ROWS_FETCHED, hand->errhp ) );
      
      sthand->row_num = resultindex;
      sthand->row = 0; /* reset row index */

      if(ERROR("msOracleSpatialLayerGetShape", hand, dthand))
          return MS_FAILURE;

      if (!success || sthand->rows_fetched == 0) {
        msSetError( MS_ORACLESPATIALERR, "msOracleSpatialLayerGetShape could not fetch specified record.", "msOracleSpatialLayerGetShape()" );
        return MS_FAILURE;
      }
    }

    /* set obj & ind for current row */
    obj = sthand->obj[ sthand->row ];
    ind = sthand->ind[ sthand->row ];

    /* get the items for the shape */
    shape->index = shapeindex; /* By definition this is what we asked for */
    shape->numvalues = layer->numitems;

    shape->values = (char **)malloc( sizeof(char*) * shape->numvalues );
    if (shape->values == NULL) {
      msSetError( MS_ORACLESPATIALERR, "No memory avaliable to allocate the values", "msOracleSpatialLayerNextShape()" );
      return MS_FAILURE;
    }

    for( i=0; i < shape->numvalues; ++i ) {
      shape->values[i] = (char *)malloc(strlen((char *)sthand->items[i][ sthand->row ])+1);
      if (shape->values[i] == NULL) {
        msSetError( MS_ORACLESPATIALERR, "No memory avaliable to allocate the items", "msOracleSpatialLayerNextShape()" );
        return MS_FAILURE;
      } else {
        strcpy(shape->values[i], (char *)sthand->items[i][ sthand->row ]);
        shape->values[i][strlen((char *)sthand->items[i][ sthand->row ])] = '\0';
      }
    }

    /* fetch a layer->type object */
    success = osGetOrdinates(dthand, hand, shape, obj, ind);

    if (success != MS_SUCCESS) {
      msSetError( MS_ORACLESPATIALERR, "Call to osGetOrdinates failed.", "msOracleSpatialLayerGetShape()" );
      return MS_FAILURE;
    }

    osShapeBounds(shape);
    if(shape->type == MS_SHAPE_NULL)  {
      msSetError( MS_ORACLESPATIALERR, "Shape type is null... this probably means a record number was requested that could not have beeen in a result set (as returned by NextShape).", "msOracleSpatialLayerGetShape()" );
      return MS_FAILURE;
    }

    return (MS_SUCCESS);
  } else { /* no resultindex, fetch the shape from the DB */
    char *table_name;
    char query_str[6000], *geom_column_name = NULL, *unique = NULL, *srid = NULL, *indexfield = NULL;
    int function = 0;
    int version = 0;
    sb2 *nullind = NULL;
    /*OCIDefine *adtp = NULL, *items[QUERY_SIZE] = { NULL };*/
    OCIDefine *adtp = NULL;
    OCIDefine  **items = NULL;

    if (layer->debug>=4)
      msDebug("msOracleSpatialLayerGetShape was called. Using the record = %ld.\n", shapeindex);

    dthand = (msOracleSpatialDataHandler *)layerinfo->oradatahandlers;
    hand = (msOracleSpatialHandler *)layerinfo->orahandlers;
    sthand = (msOracleSpatialStatement *) layerinfo->orastmt;

    /* allocate enough space for items */
    if (layer->numitems > 0) {
      if (sthand->items_query == NULL)
        sthand->items_query = (item_text_array_query *)malloc( sizeof(item_text_array_query) * (layer->numitems) );

      if (sthand->items_query == NULL) {
        msSetError( MS_ORACLESPATIALERR, "Cannot allocate layerinfo->items_query buffer", "msOracleSpatialLayerGetShape()" );
        return MS_FAILURE;
      }

      nullind = (sb2 *)malloc( sizeof(sb2) * (layer->numitems) );
      if (nullind == NULL) {
        msSetError( MS_ORACLESPATIALERR, "Cannot allocate nullind buffer", "msOracleSpatialLayerGetShape()" );
        return MS_FAILURE;
      }
      memset(nullind ,0, sizeof(sb2) * (layer->numitems) );

      items = (OCIDefine **)malloc(sizeof(OCIDefine *)*layer->numitems);
      if (items == NULL) {
        msSetError( MS_ORACLESPATIALERR,"Cannot allocate items buffer","msOracleSpatialLayerWhichShapes()" );

        /* clean nullind  */
        free(nullind);

        return MS_FAILURE;
      }
      memset(items ,0,sizeof(OCIDefine *)*layer->numitems);
    }

    table_name = (char *) malloc(sizeof(char) * TABLE_NAME_SIZE);
    if (!msSplitData( layer->data, &geom_column_name, &table_name, &unique, &srid, &indexfield, &function, &version )) {
      msDebug( "Error parsing OracleSpatial DATA variable. Must be: "
                  "'geometry_column FROM table_name [USING UNIQUE <column> SRID srid# FUNCTION]' or "
                  "'geometry_column FROM (SELECT stmt) [USING UNIQUE <column> SRID srid# FUNCTION]'. "
                  "If want to set the FUNCTION statement you can use: FILTER, RELATE, GEOMRELATE or NONE. "
                  "Your data statement: (%s) msOracleSpatialLayerGetShape()\n", layer->data );
      msSetError( MS_ORACLESPATIALERR,
                  "Error parsing OracleSpatial DATA variable. Check server logs. ",
                  "msOracleSpatialLayerGetShape()");

      /* clean nullind  */
      free(nullind);

      /* clean items */
      free(items);

      if (geom_column_name) free(geom_column_name);
      if (srid) free(srid);
      if (unique) free(unique);
      if (indexfield) free(indexfield);
      free(table_name);

      return MS_FAILURE;
    }

    /*Define the first query to retrive itens*/
    if (unique[0] == '\0') {
      msSetError( MS_ORACLESPATIALERR,
                  "Error parsing OracleSpatial DATA variable for query. To execute "
                  "query functions you need to define one "
                  "unique column [USING UNIQUE <#column>]",
                  "msOracleSpatialLayerGetShape()" );

      /* clean nullind  */
      free(nullind);

      /* clean items */
      free(items);

      if (geom_column_name) free(geom_column_name);
      if (srid) free(srid);
      if (unique) free(unique);
      if (indexfield) free(indexfield);
      free(table_name);

      return MS_FAILURE;
    } else
      snprintf( query_str, sizeof(query_str), "SELECT");

    /*Define the query*/
    for( i = 0; i < layer->numitems; ++i ) 
      snprintf( query_str + strlen(query_str), sizeof(query_str)-strlen(query_str), " %s,", layer->items[i] );

    snprintf( query_str + strlen(query_str), sizeof(query_str)-strlen(query_str), " %s FROM %s WHERE %s = %ld", geom_column_name, table_name, unique, shapeindex);

    /*if (layer->filter.native_string != NULL)
      sprintf( query_str + strlen(query_str), " AND %s", (layer->filter.string));*/
    osFilteritem(layer, FUNCTION_NONE, query_str, sizeof(query_str), 2);


    if (layer->debug)
      msDebug("msOracleSpatialLayerGetShape. Sql: %s\n", query_str);

    /*Prepare the handlers to the query*/
    success = TRY( hand,OCIStmtPrepare( sthand->stmthp, hand->errhp, (text *)query_str, (ub4)strlen(query_str), (ub4)OCI_NTV_SYNTAX, (ub4)OCI_DEFAULT) );

    if (success && layer->numitems > 0) {
      for( i = 0; i < layer->numitems && success; i++ )
        success = TRY( hand, OCIDefineByPos( sthand->stmthp, &items[i], hand->errhp, (ub4)i+1, (dvoid *)sthand->items_query[i], (sb4)TEXT_SIZE, SQLT_STR, (sb2 *)&nullind[i], (ub2 *)0, (ub2 *)0, (ub4)OCI_DEFAULT ) );
    }

    if(!success) {
      msSetError( MS_ORACLESPATIALERR,
                  "Error: %s . "
                  "Query statement: %s . "
                  "Check your data statement.",
                  "msOracleSpatialLayerGetShape()\n", hand->last_oci_error, query_str );

      /* clean nullind  */
      free(nullind);

      /* clean items */
      free(items);

      if (geom_column_name) free(geom_column_name);
      if (srid) free(srid);
      if (unique) free(unique);
      if (indexfield) free(indexfield);
      free(table_name);

      return MS_FAILURE;
    }

    if (success) {
      success = TRY( hand, OCIDefineByPos( sthand->stmthp, &adtp, hand->errhp, (ub4)layer->numitems+1, (dvoid *)0, (sb4)0, SQLT_NTY, (dvoid *)0, (ub2 *)0, (ub2 *)0, (ub4)OCI_DEFAULT) )
                && TRY( hand, OCIDefineObject( adtp, hand->errhp, dthand->tdo, (dvoid **)sthand->obj, (ub4 *)0, (dvoid **)sthand->ind, (ub4 *)0 ) )
                && TRY (hand, OCIStmtExecute( hand->svchp, sthand->stmthp, hand->errhp, (ub4)QUERY_SIZE, (ub4)0, (OCISnapshot *)NULL, (OCISnapshot *)NULL, (ub4)OCI_DEFAULT ))
                && TRY (hand, OCIAttrGet( (dvoid *)sthand->stmthp, (ub4)OCI_HTYPE_STMT, (dvoid *)&sthand->rows_fetched, (ub4 *)0, (ub4)OCI_ATTR_ROW_COUNT, hand->errhp ));

    }

    if(!success) {
      msDebug( "Error: %s . "
                  "Query statement: %s ."
                  "Check your data statement."
                  "in msOracleSpatialLayerGetShape()\n", hand->last_oci_error, query_str );
      msSetError( MS_ORACLESPATIALERR,
                  "Error in Query statement. Check your server logs","msOracleSpatialLayerGetShape()");

      /* clean nullind  */
      free(nullind);

      /* clean items */
      free(items);

      if (geom_column_name) free(geom_column_name);
      if (srid) free(srid);
      if (unique) free(unique);
      if (indexfield) free(indexfield);
      free(table_name);

      return MS_FAILURE;
    }

    shape->type = MS_SHAPE_NULL;

    /* no rows fetched */
    if (sthand->rows_fetched == 0) {
      /* clean nullind  */
      free(nullind);

      /* clean items */
      free(items);

      if (geom_column_name) free(geom_column_name);
      if (srid) free(srid);
      if (unique) free(unique);
      if (indexfield) free(indexfield);
      free(table_name);

      return (MS_DONE);
    }

    obj = sthand->obj[ sthand->row ];
    ind = sthand->ind[ sthand->row ];

    /* get the items for the shape */
    shape->numvalues = layer->numitems;
    shape->values = (char **) malloc(sizeof(char *) * layer->numitems);
    if (shape->values == NULL) {
      msSetError( MS_ORACLESPATIALERR, "No memory avaliable to allocate the values.", "msOracleSpatialLayerGetShape()" );

      /* clean nullind  */
      free(nullind);

      /* clean items */
      free(items);

      if (geom_column_name) free(geom_column_name);
      if (srid) free(srid);
      if (unique) free(unique);
      if (indexfield) free(indexfield);
      free(table_name);

      return MS_FAILURE;
    }

    shape->index = shapeindex;

    for( i = 0; i < layer->numitems; ++i ) {
      shape->values[i] = (char *)malloc(strlen((char *)sthand->items_query[sthand->row][i])+1);

      if (shape->values[i] == NULL) {
        msSetError( MS_ORACLESPATIALERR, "No memory avaliable to allocate the items buffer.", "msOracleSpatialLayerGetShape()" );

        /* clean nullind  */
        free(nullind);

        /* clean items */
        free(items);

        if (geom_column_name) free(geom_column_name);
        if (srid) free(srid);
        if (unique) free(unique);
        if (indexfield) free(indexfield);
        free(table_name);

        return MS_FAILURE;
      } else {
        if (nullind[i] != OCI_IND_NULL) {
          strcpy(shape->values[i], (char *)sthand->items_query[sthand->row][i]);
          shape->values[i][strlen((char *)sthand->items_query[sthand->row][i])] = '\0';
        } else {
          shape->values[i][0] = '\0';
        }
      }
    }

    /* increment for next row */
    sthand->row_num++;
    sthand->row++;

    /* fetch a layer->type object */
    success = osGetOrdinates(dthand, hand, shape, obj, ind);
    if (success != MS_SUCCESS) {
      msSetError( MS_ORACLESPATIALERR, "Cannot execute query", "msOracleSpatialLayerGetShape()" );

      /* clean nullind  */
      free(nullind);

      /* clean items */
      free(items);

      if (geom_column_name) free(geom_column_name);
      if (srid) free(srid);
      if (unique) free(unique);
      if (indexfield) free(indexfield);
      free(table_name);

      return MS_FAILURE;
    }
    osShapeBounds(shape);
    sthand->row = sthand->row_num = 0;

    /* clean nullind  */
    free(nullind);

    /* clean items */
    free(items);

    if (geom_column_name) free(geom_column_name);
    if (srid) free(srid);
    if (unique) free(unique);
    if (indexfield) free(indexfield);
    free(table_name);

    return (MS_SUCCESS);
  }
}

int msOracleSpatialLayerInitItemInfo( layerObj *layer )
{
  int i;
  int *itemindexes ;

  if (layer->debug>=3)
    msDebug("msOracleSpatialLayerInitItemInfo was called.\n");

  if (layer->numitems == 0)
    return MS_SUCCESS;

  if (layer->iteminfo)
    free( layer->iteminfo );

  if ((layer->iteminfo = (long *)malloc(sizeof(int)*layer->numitems))== NULL) {
    msSetError(MS_MEMERR, NULL, "msOracleSpatialLayerInitItemInfo()");
    return MS_FAILURE;
  }

  itemindexes = (int*)layer->iteminfo;
  
    

  for(i=0; i < layer->numitems; i++){
    itemindexes[i] = i;  /*last one is always the geometry one - the rest are non-geom*/
  }

  return MS_SUCCESS;
}

/* AutoProjection Support for RFC 37 #3333
 * TODO: Needs testing
 */
int msOracleSpatialLayerGetAutoProjection( layerObj *layer, projectionObj *projection )
{
  char *table_name;
  char *query_str, *geom_column_name = NULL, *unique = NULL, *srid = NULL, *indexfield=NULL;
  int success;
  int function = 0;
  int version = 0;
  char wktext[4000];

  OCIDefine *def1p = NULL;
  OCIBind *bnd1p = NULL,  *bnd2p = NULL;

  msOracleSpatialLayerInfo *layerinfo = (msOracleSpatialLayerInfo *)layer->layerinfo;
  msOracleSpatialDataHandler *dthand = NULL;
  msOracleSpatialHandler *hand = NULL;
  msOracleSpatialStatement *sthand = NULL;

  if (layer->debug>=3)
    msDebug("msOracleSpatialLayerGetAutoProjection was called.\n");

  if (layerinfo == NULL) {
    msSetError( MS_ORACLESPATIALERR, "msOracleSpatialLayerGetAutoProjection called on unopened layer","msOracleSpatialLayerGetAutoProjection()");
    return MS_FAILURE;
  } else {
    dthand = (msOracleSpatialDataHandler *)layerinfo->oradatahandlers;
    hand = (msOracleSpatialHandler *)layerinfo->orahandlers;
    sthand = (msOracleSpatialStatement *) layerinfo->orastmt;
  }

  table_name = (char *) malloc(sizeof(char) * TABLE_NAME_SIZE);
  if (!msSplitData( layer->data, &geom_column_name, &table_name, &unique, &srid, &indexfield, &function, &version )) {
    msDebug(  "Error parsing OracleSpatial DATA variable. Must be: "
                "'geometry_column FROM table_name [USING UNIQUE <column> SRID srid# FUNCTION]' or "
                "'geometry_column FROM (SELECT stmt) [USING UNIQUE <column> SRID srid# FUNCTION]'. "
                "If want to set the FUNCTION statement you can use: FILTER, RELATE, GEOMRELATE or NONE. "
                "Your data statement: (%s) "
                "in msOracleSpatialLayerGetAutoProjection()\n", layer->data );

    msSetError( MS_ORACLESPATIALERR,
                "Error parsing OracleSpatial DATA variable",
                "msOracleSpatialLayerGetAutoProjection()");

    if (geom_column_name) free(geom_column_name);
    if (srid) free(srid);
    if (unique) free(unique);
    if (indexfield) free(indexfield);
    free(table_name);

    return MS_FAILURE;
  }

  query_str = "SELECT wktext FROM mdsys.all_sdo_geom_metadata m, mdsys.cs_srs c WHERE c.srid = m.srid and m.owner||'.'||m.table_name = :table_name and m.column_name = :geo_col_name "
              "UNION SELECT wktext from mdsys.user_sdo_geom_metadata m, mdsys.cs_srs c WHERE c.srid = m.srid and m.table_name = :table_name and m.column_name = :geo_col_name";

  if (layer->debug>=2)
    msDebug("msOracleSpatialLayerGetAutoProjection. Using this Sql to retrieve the projection: %s.\n", query_str);

  /*Prepare the handlers to the query*/
  success = TRY( hand, OCIStmtPrepare( sthand->stmthp, hand->errhp, (text *)query_str, (ub4)strlen(query_str), (ub4)OCI_NTV_SYNTAX, (ub4)OCI_DEFAULT ) )
            && TRY( hand, OCIBindByName( sthand->stmthp, &bnd2p, hand->errhp, (text *) ":table_name", strlen(":table_name"), (ub1*) table_name, strlen(table_name)+1, SQLT_STR, (dvoid *) 0, (ub2 *) 0, (ub2) 0, (ub4) 0, (ub4 *) 0, OCI_DEFAULT ) )
            && TRY( hand, OCIBindByName( sthand->stmthp, &bnd1p, hand->errhp, (text *) ":geo_col_name", strlen(":geo_col_name"), (ub1*) geom_column_name, strlen(geom_column_name)+1, SQLT_STR, (dvoid *) 0, (ub2 *) 0, (ub2) 0, (ub4) 0, (ub4 *) 0, OCI_DEFAULT ) )
            && TRY( hand, OCIDefineByPos( sthand->stmthp, &def1p, hand->errhp, (ub4)1, (dvoid *)wktext, (sb4)4000, SQLT_STR, (dvoid *)0, (ub2 *)0, (ub2 *)0, (ub4)OCI_DEFAULT ) )
            && TRY( hand, OCIStmtExecute( hand->svchp, sthand->stmthp, hand->errhp, (ub4)0, (ub4)0, (OCISnapshot *)NULL, (OCISnapshot *)NULL, (ub4)OCI_DEFAULT ) )
            && TRY( hand, OCIAttrGet( (dvoid *)sthand->stmthp, (ub4)OCI_HTYPE_STMT, (dvoid *)&sthand->rows_fetched, (ub4 *)0, (ub4)OCI_ATTR_ROWS_FETCHED, hand->errhp ) );

  if(!success) {
    msDebug( "Error: %s . "
                "Query statement: %s . "
                "Check your data statement."
                "in msOracleSpatialLayerGetAutoProjection()\n", hand->last_oci_error, query_str );
    msSetError( MS_ORACLESPATIALERR,
                "Error "
                "Check your data statement and server logs",
                "msOracleSpatialLayerGetAutoProjection()" );

    if (geom_column_name) free(geom_column_name);
    if (srid) free(srid);
    if (unique) free(unique);
    if (indexfield) free(indexfield);
    free(table_name);
    return MS_FAILURE;
  }
  do {
    success = TRY( hand, OCIStmtFetch( sthand->stmthp, hand->errhp, (ub4)1, (ub2)OCI_FETCH_NEXT, (ub4)OCI_DEFAULT ) )
              && TRY( hand, OCIAttrGet( (dvoid *)sthand->stmthp, (ub4)OCI_HTYPE_STMT, (dvoid *)&sthand->rows_fetched, (ub4 *)0, (ub4)OCI_ATTR_ROWS_FETCHED, hand->errhp ) );
    if (success && sthand->rows_fetched > 0) {

      if( layer->debug )
        msDebug("Found WKT projection for table %s: %s\n", table_name, wktext);

      if(wktext != NULL && projection != NULL)
        if(msOGCWKT2ProjectionObj(wktext, projection, layer->debug) == MS_FAILURE)
          return(MS_FAILURE);
    }
  } while (sthand->rows_fetched > 0);

  if (geom_column_name) free(geom_column_name);
  if (srid) free(srid);
  if (unique) free(unique);
  if (indexfield) free(indexfield);
  free(table_name);
  return MS_SUCCESS;
}

/**********************************************************************
 *             msOracleSpatialGetFieldDefn()
 *
 * Pass the field definitions through to the layer metadata in the
 * "gml_[item]_{type,width,precision}" set of metadata items for
 * defining fields.
 **********************************************************************/
static void
msOracleSpatialGetFieldDefn( layerObj *layer,
                             msOracleSpatialHandler *hand,
                             const char *item,
                             OCIParam *pard )

{
  const char *gml_type = "Character";
  char md_item_name[256];
  char gml_width[32], gml_precision[32];
  int success;
  ub2 rzttype, nOCILen;

  gml_width[0] = '\0';
  gml_precision[0] = '\0';

  /* -------------------------------------------------------------------- */
  /*      Get basic parameter details.                                    */
  /* -------------------------------------------------------------------- */
  success =
    TRY( hand, OCIAttrGet ((dvoid *) pard,(ub4) OCI_DTYPE_PARAM,
                           (dvoid*)&rzttype,(ub4 *)0,
                           (ub4) OCI_ATTR_DATA_TYPE, hand->errhp ))
    && TRY( hand, OCIAttrGet ((dvoid *) pard,(ub4) OCI_DTYPE_PARAM,
                              (dvoid*)&nOCILen ,(ub4 *)0,
                              (ub4) OCI_ATTR_DATA_SIZE, hand->errhp ));

  if( !success )
    return;

  switch( rzttype ) {
    case SQLT_CHR:
    case SQLT_AFC:
      gml_type = "Character";
      if( nOCILen <= 4000 )
        sprintf( gml_width, "%d", nOCILen );
      break;

    case SQLT_NUM: {
      /* NOTE: OCI docs say this should be ub1 type, but we have
         determined that oracle is actually returning a short so we
         use that type and try to compensate for possible problems by
         initializing, and dividing by 256 if it is large. */
      unsigned short byPrecision = 0;
      sb1 nScale = 0;

      if( !TRY( hand, OCIAttrGet ((dvoid *) pard,(ub4) OCI_DTYPE_PARAM,
                                  (dvoid*)&byPrecision ,(ub4 *)0,
                                  (ub4) OCI_ATTR_PRECISION,
                                  hand->errhp ))
          || !TRY( hand, OCIAttrGet ((dvoid *) pard,(ub4) OCI_DTYPE_PARAM,
                                     (dvoid*)&nScale,(ub4 *)0,
                                     (ub4) OCI_ATTR_SCALE,
                                     hand->errhp )) )
        return;
      if( byPrecision > 255 )
        byPrecision = byPrecision / 256;

      if( nScale > 0 ) {
        gml_type = "Real";
        sprintf( gml_width, "%d", byPrecision );
        sprintf( gml_precision, "%d", nScale );
      } else if( nScale < 0 )
        gml_type = "Real";
      else {
        gml_type = "Integer";
        if( byPrecision < 38 )
          sprintf( gml_width, "%d", byPrecision );
      }
    }
    break;

    case SQLT_DAT:
    case SQLT_DATE:
    case SQLT_TIMESTAMP:
    case SQLT_TIMESTAMP_TZ:
    case SQLT_TIMESTAMP_LTZ:
    case SQLT_TIME:
    case SQLT_TIME_TZ:
      gml_type = "Date";
      break;

    default:
      gml_type = "Character";
  }

  snprintf( md_item_name, sizeof(md_item_name), "gml_%s_type", item );
  if( msOWSLookupMetadata(&(layer->metadata), "G", "type") == 0 )
    msInsertHashTable(&(layer->metadata), md_item_name, gml_type );

  snprintf( md_item_name, sizeof(md_item_name), "gml_%s_width", item );
  if( strlen(gml_width) > 0
      && msOWSLookupMetadata(&(layer->metadata), "G", "width") == 0 )
    msInsertHashTable(&(layer->metadata), md_item_name, gml_width );

  snprintf( md_item_name, sizeof(md_item_name), "gml_%s_precision",item );
  if( strlen(gml_precision) > 0
      && msOWSLookupMetadata(&(layer->metadata), "G", "precision")==0 )
    msInsertHashTable(&(layer->metadata), md_item_name, gml_precision );
}

int msOracleSpatialLayerGetItems( layerObj *layer )
{
  char *rzt = "";
  ub2 rzttype = 0;
  char *flk = "";
  int function = 0;
  int version = 0;
  int existgeom;
  int count_item, flk_len, success, i;
  char *table_name;
  char query_str[6000], *geom_column_name = NULL, *unique = NULL, *srid = NULL, *indexfield=NULL;
  OCIParam *pard = (OCIParam *) 0;

  msOracleSpatialLayerInfo *layerinfo = (msOracleSpatialLayerInfo *) layer->layerinfo;
  msOracleSpatialDataHandler *dthand = NULL;
  msOracleSpatialHandler *hand = NULL;
  msOracleSpatialStatement *sthand = NULL;
  int get_field_details = 0;
  const char *value;

  if (layer->debug>=3)
    msDebug("msOracleSpatialLayerGetItems was called.\n");

  if (layerinfo == NULL) {
    msSetError( MS_ORACLESPATIALERR, "msOracleSpatialLayerGetItems called on unopened layer", "msOracleSpatialLayerGetItems()" );
    return MS_FAILURE;
  } else {
    dthand = (msOracleSpatialDataHandler *)layerinfo->oradatahandlers;
    hand = (msOracleSpatialHandler *)layerinfo->orahandlers;
    sthand = (msOracleSpatialStatement *) layerinfo->orastmt;
  }

  /* Will we want to capture the field details? */
  if((value = msOWSLookupMetadata(&(layer->metadata), "G", "types")) != NULL
      && strcasecmp(value,"auto") == 0 )
    get_field_details = 1;

  table_name = (char *) malloc(sizeof(char) * TABLE_NAME_SIZE);
  if (!msSplitData(layer->data, &geom_column_name, &table_name, &unique, &srid, &indexfield, &function, &version)) {
    msDebug(   "Error parsing OracleSpatial DATA variable. Must be: "
                "'geometry_column FROM table_name [USING UNIQUE <column> SRID srid# FUNCTION]' or "
                "'geometry_column FROM (SELECT stmt) [USING UNIQUE <column> SRID srid# FUNCTION]'. "
                "If want to set the FUNCTION statement you can use: FILTER, RELATE, GEOMRELATE or NONE. "
                "Your data statement: (%s)"
                "in msOracleSpatialLayerGetItems()\n", layer->data );
    msSetError( MS_ORACLESPATIALERR,
                "Error parsing OracleSpatial DATA variable. Check server logs. ",
                "msOracleSpatialLayerGetItems()");

    if (geom_column_name) free(geom_column_name);
    if (srid) free(srid);
    if (unique) free(unique);
    if (indexfield) free(indexfield);
    free(table_name);
    return MS_FAILURE;
  }

  snprintf( query_str, sizeof(query_str), "SELECT * FROM %s", table_name );

  success =  TRY( hand, OCIStmtPrepare( sthand->stmthp, hand->errhp, (text *)query_str, (ub4)strlen(query_str), (ub4)OCI_NTV_SYNTAX, (ub4)OCI_DESCRIBE_ONLY) )
             && TRY( hand, OCIStmtExecute( hand->svchp, sthand->stmthp, hand->errhp, (ub4)QUERY_SIZE, (ub4)0, (OCISnapshot *)NULL, (OCISnapshot *)NULL, (ub4)OCI_DESCRIBE_ONLY ) )
             && TRY( hand, OCIAttrGet( (dvoid *)sthand->stmthp, (ub4)OCI_HTYPE_STMT, (dvoid *)&layer->numitems, (ub4 *)0, OCI_ATTR_PARAM_COUNT, hand->errhp) );


  if (!success) {
    msSetError( MS_QUERYERR, "Cannot retrieve column list", "msOracleSpatialLayerGetItems()" );
    if (geom_column_name) free(geom_column_name);
    if (srid) free(srid);
    if (unique) free(unique);
    if (indexfield) free(indexfield);
    free(table_name);
    return MS_FAILURE;
  }

  sthand->row_num = sthand->row = 0;
  layer->numitems = layer->numitems-1;

  layer->items = malloc (sizeof(char *) * (layer->numitems));
  if (layer->items == NULL) {
    msSetError( MS_ORACLESPATIALERR,"Cannot allocate items", "msOracleSpatialLayerGetItems()" );
    if (geom_column_name) free(geom_column_name);
    if (srid) free(srid);
    if (unique) free(unique);
    if (indexfield) free(indexfield);
    free(table_name);
    return MS_FAILURE;
  }

  if (layer->numitems > 0) {
    if (sthand->items_query == NULL)
      sthand->items_query = (item_text_array_query *)malloc( sizeof(item_text_array_query) * (layer->numitems) );

    if (sthand->items_query == NULL) {
      msSetError( MS_ORACLESPATIALERR,"Cannot allocate items buffer", "msOracleSpatialLayerGetItems()" );
      if (geom_column_name) free(geom_column_name);
      if (srid) free(srid);
      if (unique) free(unique);
      if (indexfield) free(indexfield);
      free(table_name);
      return MS_FAILURE;
    }
  }

  count_item = 0;
  existgeom = 0;

  /*Upcase conversion for the geom_column_name*/
  for (i=0; geom_column_name[i] != '\0'; i++)
    geom_column_name[i] = toupper(geom_column_name[i]);

  /*Retrive columns name from the user table*/
  for (i = 0; i <= layer->numitems; i++) {

    success = TRY( hand, OCIParamGet ((dvoid*) sthand->stmthp, (ub4)OCI_HTYPE_STMT,hand->errhp,(dvoid*)&pard, (ub4)i+1))
              && TRY( hand, OCIAttrGet ((dvoid *) pard,(ub4) OCI_DTYPE_PARAM,(dvoid*)&rzttype,(ub4 *)0, (ub4) OCI_ATTR_DATA_TYPE, hand->errhp ))
              && TRY( hand, OCIParamGet ((dvoid*) sthand->stmthp, (ub4)OCI_HTYPE_STMT,hand->errhp,(dvoid*)&pard, (ub4)i+1))
              && TRY( hand, OCIAttrGet ((dvoid *) pard,(ub4) OCI_DTYPE_PARAM,(dvoid*)&rzt,(ub4 *)&flk_len, (ub4) OCI_ATTR_NAME, hand->errhp ));

     /*  if (layer->debug)
            msDebug("msOracleSpatialLayerGetItems checking type. Column = %s Type = %d\n", rzt, rzttype);  */
    flk = (char *)malloc(sizeof(char*) * flk_len+1);
    if (flk == NULL) {
      msSetError( MS_ORACLESPATIALERR, "No memory avaliable to allocate the items", "msOracleSpatialLayerGetItems()" );
      if (geom_column_name) free(geom_column_name);
      if (srid) free(srid);
      if (unique) free(unique);
      free(table_name);
      return MS_FAILURE;
    } else {
      //layer->iteminfo->dtype[i]= 1;
      strlcpy(flk, rzt, flk_len+1);
    }

    /*Comapre the column name (flk) with geom_column_name and ignore with true*/
    if (strcmp(flk, geom_column_name) != 0) {
      if (rzttype!=OCI_TYPECODE_BLOB) {
        layer->items[count_item] = (char *)malloc(sizeof(char) * flk_len+1);
        if (layer->items[count_item] == NULL) {
          msSetError( MS_ORACLESPATIALERR, "No memory avaliable to allocate the items buffer", "msOracleSpatialLayerGetItems()" );
          if (geom_column_name) free(geom_column_name);
          if (srid) free(srid);
          if (unique) free(unique);
          free(table_name);
          return MS_FAILURE;
        }

        strcpy(layer->items[count_item], flk);
        count_item++;

       if( get_field_details )
          msOracleSpatialGetFieldDefn( layer, hand,
                                       layer->items[count_item-1],
                                       pard ); 
      }
    } else 
      existgeom = 1;

    strcpy( rzt, "" );
    free(flk); /* Better?!*/
    flk_len = 0;
  }

  layer->numitems = count_item;

  if (!(existgeom)) {
    msSetError (MS_ORACLESPATIALERR, "No geometry column, check stmt", "msOracleSpatialLayerGetItems()" );
    if (geom_column_name) free(geom_column_name);
    if (srid) free(srid);
    if (unique) free(unique);
    if (indexfield) free(indexfield);
    free(table_name);
    return MS_FAILURE;
  }

  if (geom_column_name) free(geom_column_name);
  if (srid) free(srid);
  if (unique) free(unique);
  if (indexfield) free(indexfield);
  free(table_name);
  return msOracleSpatialLayerInitItemInfo( layer );
}

int msOracleSpatialLayerGetExtent(layerObj *layer, rectObj *extent)
{
  char *table_name;
  char query_str[6000], *geom_column_name = NULL, *unique = NULL, *srid = NULL, *indexfield=NULL;
  int success, i;
  int function = 0;
  int version = 0;
  SDOGeometryObj *obj = NULL;
  SDOGeometryInd *ind = NULL;
  shapeObj shape;
  rectObj bounds;
  /*OCIDefine *adtp = NULL, *items[QUERY_SIZE] = { NULL };*/
  OCIDefine *adtp = NULL;
  OCIDefine **items = NULL;

  msOracleSpatialLayerInfo *layerinfo = (msOracleSpatialLayerInfo *)layer->layerinfo;
  msOracleSpatialDataHandler *dthand = NULL;
  msOracleSpatialHandler *hand = NULL;
  msOracleSpatialStatement *sthand = NULL;

  if (layer->debug>=3)
    msDebug("msOracleSpatialLayerGetExtent was called.\n");

  if (layerinfo == NULL) {
    msSetError( MS_ORACLESPATIALERR, "msOracleSpatialLayerGetExtent called on unopened layer","msOracleSpatialLayerGetExtent()");
    return MS_FAILURE;
  } else {
    dthand = (msOracleSpatialDataHandler *)layerinfo->oradatahandlers;
    hand = (msOracleSpatialHandler *)layerinfo->orahandlers;
    sthand = (msOracleSpatialStatement *) layerinfo->orastmt;
  }

  /* allocate enough space for items */
  if (layer->numitems > 0) {
    sthand->items_query = (item_text_array_query *)malloc( sizeof(item_text_array_query) * (layer->numitems) );
    if (sthand->items_query == NULL) {
      msSetError( MS_ORACLESPATIALERR, "Cannot allocate layerinfo->items buffer", "msOracleSpatialLayerGetExtent()" );
      return MS_FAILURE;
    }
    items = (OCIDefine **)malloc(sizeof(OCIDefine *)*layer->numitems);
    if (items == NULL) {
      msSetError( MS_ORACLESPATIALERR,"Cannot allocate items buffer","msOracleSpatialLayerWhichShapes()" );
      return MS_FAILURE;
    }
    memset(items ,0,sizeof(OCIDefine *)*layer->numitems);
  }

  table_name = (char *) malloc(sizeof(char) * TABLE_NAME_SIZE);
  if (!msSplitData( layer->data, &geom_column_name, &table_name, &unique, &srid, &indexfield, &function, &version )) {
    msDebug(   "Error parsing OracleSpatial DATA variable. Must be: "
                "'geometry_column FROM table_name [USING UNIQUE <column> SRID srid# FUNCTION]' or "
                "'geometry_column FROM (SELECT stmt) [USING UNIQUE <column> SRID srid# FUNCTION]'. "
                "If want to set the FUNCTION statement you can use: FILTER, RELATE, GEOMRELATE or NONE. "
                "Your data statement: (%s) "
                "in msOracleSpatialLayerGetExtent()\n", layer->data );
    msSetError( MS_ORACLESPATIALERR,
                "Error parsing OracleSpatial DATA variable. Check server logs. ",
                "msOracleSpatialLayerGetExtent()");
    /* clean items */
    free(items);

    if (geom_column_name) free(geom_column_name);
    if (srid) free(srid);
    if (unique) free(unique);
    if (indexfield) free(indexfield);
    free(table_name);

    return MS_FAILURE;
  }

  //if (version == VERSION_10g)
    osAggrGetExtent(layer, query_str, sizeof(query_str), geom_column_name, table_name);
  /*else {
    if (((atol(srid) < 8192) || (atol(srid) > 8330)) && (atol(srid) != 2) && (atol(srid) != 5242888) && (atol(srid) != 2000001)) {
      if (version == VERSION_9i)
        osAggrGetExtent(layer, query_str, sizeof(query_str), geom_column_name, table_name);
      else
        osConvexHullGetExtent(layer, query_str, sizeof(query_str), geom_column_name, table_name);
    } else
      osConvexHullGetExtent(layer, query_str, sizeof(query_str), geom_column_name, table_name);
  } */

  if (layer->debug>=3)
    msDebug("msOracleSpatialLayerGetExtent. Using this Sql to retrieve the extent: %s.\n", query_str);

  /*Prepare the handlers to the query*/
  success = TRY( hand,OCIStmtPrepare( sthand->stmthp, hand->errhp, (text *)query_str, (ub4)strlen(query_str), (ub4)OCI_NTV_SYNTAX, (ub4)OCI_DEFAULT) );

  if (success && layer->numitems > 0) {
    for( i = 0; i < layer->numitems && success; ++i )
      success = TRY( hand, OCIDefineByPos( sthand->stmthp, &items[i], hand->errhp, (ub4)i+1, (dvoid *)sthand->items_query[i], (sb4)TEXT_SIZE, SQLT_STR, (dvoid *)0, (ub2 *)0, (ub2 *)0, (ub4)OCI_DEFAULT ) );
  }

  if(!success) {
    msDebug(   "Error: %s . "
                "Query statement: %s . "
                "Check your data statement."
                "in msOracleSpatialLayerGetExtent()\n", hand->last_oci_error, query_str );

    msSetError( MS_ORACLESPATIALERR,
                "Check your data statement and server logs",
                "msOracleSpatialLayerGetExtent()" );

    /* clean items */
    free(items);

    if (geom_column_name) free(geom_column_name);
    if (srid) free(srid);
    if (unique) free(unique);
    if (indexfield) free(indexfield);
    free(table_name);

    return MS_FAILURE;
  }

  if (success) {
    success = TRY( hand, OCIDefineByPos( sthand->stmthp, &adtp, hand->errhp, (ub4)layer->numitems+1, (dvoid *)0, (sb4)0, SQLT_NTY, (dvoid *)0, (ub2 *)0, (ub2 *)0, (ub4)OCI_DEFAULT) )
              && TRY( hand, OCIDefineObject( adtp, hand->errhp, dthand->tdo, (dvoid **)sthand->obj, (ub4 *)0, (dvoid **)sthand->ind, (ub4 *)0 ) )
              && TRY (hand, OCIStmtExecute( hand->svchp, sthand->stmthp, hand->errhp, (ub4)QUERY_SIZE, (ub4)0, (OCISnapshot *)NULL, (OCISnapshot *)NULL, (ub4)OCI_DEFAULT ))
              && TRY (hand, OCIAttrGet( (dvoid *)sthand->stmthp, (ub4)OCI_HTYPE_STMT, (dvoid *)&sthand->rows_fetched, (ub4 *)0, (ub4)OCI_ATTR_ROW_COUNT, hand->errhp ));

  }

  if(!success) {
    msDebug(    "Error: %s . "
                "Query statement: %s ."
                "Check your data statement."
                "in msOracleSpatialLayerGetExtent()\n", hand->last_oci_error, query_str );
    msSetError( MS_ORACLESPATIALERR,
                "Check your data statement and server logs",
                "msOracleSpatialLayerGetExtent()" );

    /* clean items */
    free(items);

    if (geom_column_name) free(geom_column_name);
    if (srid) free(srid);
    if (unique) free(unique);
    if (indexfield) free(indexfield);
    free(table_name);

    return MS_FAILURE;
  }

  /* should begin processing first row */
  sthand->row_num = sthand->row = 0;
  msInitShape( &shape );
  do {
    /* is buffer empty? */
    if (sthand->row_num >= sthand->rows_fetched) {
      /* fetch more */
      success = TRY( hand, OCIStmtFetch( sthand->stmthp, hand->errhp, (ub4)ARRAY_SIZE, (ub2)OCI_FETCH_NEXT, (ub4)OCI_DEFAULT ) )
                && TRY( hand, OCIAttrGet( (dvoid *)sthand->stmthp, (ub4)OCI_HTYPE_STMT, (dvoid *)&sthand->rows_fetched, (ub4 *)0, (ub4)OCI_ATTR_ROW_COUNT, hand->errhp ) );

      if (!success || sthand->rows_fetched == 0 || sthand->row_num >= sthand->rows_fetched) {
        hand->last_oci_status=MS_SUCCESS;
        break;
      }

      sthand->row = 0; /* reset row index */
    }

    /* no rows fetched */
    if (sthand->rows_fetched == 0)
      break;

    obj = sthand->obj[ sthand->row ];
    ind = sthand->ind[ sthand->row ];

    /* get the items for the shape */
    shape.numvalues = layer->numitems;
    shape.values = (char **) malloc(sizeof(char *) * layer->numitems);
    if (shape.values == NULL) {
      msSetError( MS_ORACLESPATIALERR, "No memory avaliable to allocate the values.", "msOracleSpatialLayerGetExtent()" );
      if (geom_column_name) free(geom_column_name);
      if (srid) free(srid);
      if (unique) free(unique);
      if (indexfield) free(indexfield);
      free(table_name);
      return MS_FAILURE;
    }

    shape.index = sthand->row_num;

    for( i = 0; i < layer->numitems; ++i ) {
      shape.values[i] = (char *)malloc(strlen((char *)sthand->items_query[sthand->row][i])+1);

      if (shape.values[i] == NULL) {
        msSetError( MS_ORACLESPATIALERR, "No memory avaliable to allocate the items buffer.", "msOracleSpatialLayerGetExtent()" );

        /* clean items */
        free(items);

        if (geom_column_name) free(geom_column_name);
        if (srid) free(srid);
        if (unique) free(unique);
        if (indexfield) free(indexfield);
        free(table_name);

        return MS_FAILURE;
      } else {
        strcpy(shape.values[i], (char *)sthand->items_query[sthand->row][i]);
        shape.values[i][strlen((char *)sthand->items_query[sthand->row][i])] = '\0';
      }
    }

    /* increment for next row */
    sthand->row_num++;
    sthand->row++;

    /* fetch a layer->type object */
    success = osGetOrdinates(dthand, hand, &shape, obj, ind);
    if (success != MS_SUCCESS) {
      msSetError( MS_ORACLESPATIALERR, "Cannot execute query", "msOracleSpatialLayerGetExtent()" );

      /* clean items */
      free(items);

      if (geom_column_name) free(geom_column_name);
      if (srid) free(srid);
      if (unique) free(unique);
      if (indexfield) free(indexfield);
      free(table_name);

      return MS_FAILURE;
    }

  } while(sthand->row <= sthand->rows_fetched);

  sthand->row = sthand->row_num = 0;

  osShapeBounds(&shape);
  bounds = shape.bounds;

  extent->minx = bounds.minx;
  extent->miny = bounds.miny;
  extent->maxx = bounds.maxx;
  extent->maxy = bounds.maxy;

  msFreeShape(&shape);

  /* clean items */
  free(items);

  if (geom_column_name) free(geom_column_name);
  if (srid) free(srid);
  if (unique) free(unique);
  if (indexfield) free(indexfield);
  free(table_name);

  return(MS_SUCCESS);
}

void msOracleSpatialLayerFreeItemInfo( layerObj *layer )
{
  if (layer->debug>=3)
    msDebug("msOracleSpatialLayerFreeItemInfo was called.\n");

  if (layer->iteminfo)
    free(layer->iteminfo);

  layer->iteminfo = NULL;
  /* nothing to do */
}

int msOracleSpatialLayerGetAutoStyle( mapObj *map, layerObj *layer, classObj *c, shapeObj *shape )
{
  msSetError( MS_ORACLESPATIALERR, "Function not implemented yet", "msLayerGetAutoStyle()" );
  return MS_FAILURE;
}

/************************************************************************/
/*                       msOracleSpatialEscapePropertyName              */
/*                                                                      */
/*      Return the property name in a properly escaped and quoted form. */
/************************************************************************/
char *msOracleSpatialEscapePropertyName(layerObj *layer, const char* pszString)
{
  char* pszEscapedStr=NULL;
  int i, j = 0;

  if (layer && pszString && strlen(pszString) > 0) {
    int nLength = strlen(pszString);

    pszEscapedStr = (char*) msSmallMalloc( 1 + 2 * nLength + 1 + 1);
    //pszEscapedStr[j++] = '';

    for (i=0; i<nLength; i++) {
      char c = pszString[i];
      if (c == '"') {
        pszEscapedStr[j++] = '"';
        pszEscapedStr[j++] ='"';
      } else if (c == '\\') {
        pszEscapedStr[j++] = '\\';
        pszEscapedStr[j++] = '\\';
      } else
        pszEscapedStr[j++] = c;
    }
    //pszEscapedStr[j++] = '';
    pszEscapedStr[j++] = 0;

  }
  return pszEscapedStr;
}

int msOracleSpatialGetPaging(layerObj *layer)
{
  msOracleSpatialLayerInfo *layerinfo = NULL;

  //if (layer->debug)
  //  msDebug("msOracleSpatialLayerGetPaging was called.\n");

  if(!msOracleSpatialLayerIsOpen(layer))
    return MS_TRUE;

  assert( layer->layerinfo != NULL);
  layerinfo = (msOracleSpatialLayerInfo *)layer->layerinfo;

  return layerinfo->paging;
}

void msOracleSpatialEnablePaging(layerObj *layer, int value)
{
  msOracleSpatialLayerInfo *layerinfo = NULL;

  if (layer->debug>=3)
    msDebug("msOracleSpatialLayerEnablePaging was called.\n");

  if(!msOracleSpatialLayerIsOpen(layer))
    msOracleSpatialLayerOpen(layer);

  assert( layer->layerinfo != NULL);
  layerinfo = (msOracleSpatialLayerInfo *)layer->layerinfo;

  layerinfo->paging = value;

  return;
}

int msOracleSpatialLayerTranslateFilter(layerObj *layer, expressionObj *filter, char *filteritem)
{
  char *native_string = NULL;

  int nodeCount = 0;

  int function = 0, version = 0, dwithin = 0, regexp_like = 0, case_ins = 0, ieq = 0;
  char *table_name;
  char *geom_column_name = NULL, *unique = NULL, *srid = NULL, *indexfield=NULL;
  char *snippet = NULL;
  char *strtmpl = NULL; 
  double dfDistance = -1;

  table_name = (char *) malloc(sizeof(char) * TABLE_NAME_SIZE);
  if (!msSplitData( layer->data, &geom_column_name, &table_name, &unique, &srid, &indexfield, &function, &version )) {
    msDebug(   "Error parsing OracleSpatial DATA variable. Must be: "
                "'geometry_column FROM table_name [USING UNIQUE <column> SRID srid# FUNCTION]' or "
                "'geometry_column FROM (SELECT stmt) [USING UNIQUE <column> SRID srid# FUNCTION]'. "
                "If want to set the FUNCTION statement you can use: FILTER, RELATE, GEOMRELATE or NONE. "
                "Your data statement: (%s)"
                "in msOracleSpatialLayerGetExtent()\n", layer->data );
    msSetError( MS_ORACLESPATIALERR,
                "Error parsing OracleSpatial DATA variable. Check server logs. ",
                "msOracleSpatialLayerGetExtent()");
    /* clean items */
    
    if (geom_column_name) free(geom_column_name);
    if (srid) free(srid);
    if (unique) free(unique);
    if (indexfield) free(indexfield);
    free(table_name);

    return MS_FAILURE;
  }

  //msDebug("filter.string was set: %s\n",filter->string);
  if(!filter->string) return MS_SUCCESS;

  /* for backwards compatibility we continue to allow SQL snippets as a string */
  
 if(filter->type == MS_STRING && filter->string && filteritem) { /* item/value pair */
    if(filter->flags & MS_EXP_INSENSITIVE) {
      native_string = msStringConcatenate(native_string, "upper(");
      native_string = msStringConcatenate(native_string, filteritem);
      native_string = msStringConcatenate(native_string, ") = upper(");
    } else {
      native_string = msStringConcatenate(native_string, filteritem);
      native_string = msStringConcatenate(native_string, " = ");
    }

    strtmpl = "'%s'";  /* don't have a type for the righthand literal so assume it's a string and we quote */
    snippet = (char *) msSmallMalloc(strlen(strtmpl) + strlen(filter->string));
    sprintf(snippet, strtmpl, filter->string);  // TODO: escape filter->string (msPostGISEscapeSQLParam)
    native_string = msStringConcatenate(native_string, snippet);
    free(snippet);

    if(filter->flags & MS_EXP_INSENSITIVE) native_string = msStringConcatenate(native_string, ")");

    if (layer->debug>=2) msDebug("msOracleSpatialLayerTranslateFilter: **item/value combo: %s\n", native_string);
  } else if(filter->type == MS_REGEX && filter->string && filteritem) { /* item/regex pair */
    native_string = msStringConcatenate(native_string, "REGEXP_LIKE (");
    native_string = msStrdup(filteritem);
    native_string = msStringConcatenate(native_string, ", ");
    strtmpl = "'%s'";
    snippet = (char *) msSmallMalloc(strlen(strtmpl) + strlen(filter->string));
    sprintf(snippet, strtmpl, filter->string); // TODO: escape filter->string (msPostGISEscapeSQLParam)
    native_string = msStringConcatenate(native_string, snippet);

    if(filter->flags & MS_EXP_INSENSITIVE) {
      native_string = msStringConcatenate(native_string, ",i ");
    } 
    native_string = msStringConcatenate(native_string, " )");
    free(snippet);
  } else if(filter->type == MS_EXPRESSION) { 

    tokenListNodeObjPtr node = NULL;
    //tokenListNodeObjPtr nextNode = NULL;

    if (layer->debug>2)
      msDebug("msOracleSpatialLayerTranslateFilter. String: %s \n", filter->string);
    if (layer->debug>2 && !filter->tokens)
      msDebug("msOracleSpatialLayerTranslateFilter. No tokens to process\n");

    if(!filter->tokens) return MS_SUCCESS; /* nothing to work from */
    
    if (layer->debug>2)
      msDebug("msOracleSpatialLayerTranslateFilter. There are tokens to process \n"); 
    
    /* try to convert tokens */
    node = filter->tokens;
    while (node != NULL) {
      //msDebug("token count :%i, token is %i\n", nodeCount, node->token);
      switch(node->token) {
        case '(':
          // if (buffer == MS_FALSE) 
           native_string = msStringConcatenate(native_string, "( ");
           break;
        case ')':
           if (regexp_like == MS_TRUE) {
            if (case_ins == MS_TRUE) {
              native_string = msStringConcatenate(native_string, ",'i' ");
              case_ins = MS_FALSE;
            } 
           regexp_like = MS_FALSE; 
           native_string = msStringConcatenate(native_string, " )"); 
           msDebug("closing RE comparison\n");
           } 
           native_string = msStringConcatenate(native_string, " )");  
           break;   
        case MS_TOKEN_LITERAL_NUMBER:
          strtmpl = "%lf";
          snippet = (char *) msSmallMalloc(strlen(strtmpl) + 16);
          sprintf(snippet, strtmpl, node->tokenval.dblval);  // TODO: escape strval
          if (dwithin == MS_TRUE) {
            dfDistance = node->tokenval.dblval;
            if (layer->units == MS_DD){
              dfDistance *= msInchesPerUnit(MS_DD,0)/msInchesPerUnit(MS_METERS,0);
              //msDebug("Converted Distance value is %lf\n", dfDistance);
            }
            sprintf(snippet, strtmpl, dfDistance); 
            native_string = msStringConcatenate(native_string, "'distance=");
            native_string = msStringConcatenate(native_string, snippet);
            native_string = msStringConcatenate(native_string, "'");
          } else {
            native_string = msStringConcatenate(native_string, snippet);
          }  
          free(snippet);
            
          break;
        case MS_TOKEN_LITERAL_STRING:    
          strtmpl = "%s";
          snippet = (char *) msSmallMalloc(strlen(strtmpl) + strlen(node->tokenval.strval));
          sprintf(snippet, strtmpl, node->tokenval.strval);  // TODO: escape strval
          snippet = msReplaceSubstring(snippet,"'","''");
          native_string = msStringConcatenate(native_string, "'");
          if (ieq == MS_TRUE) {
            native_string = msStringConcatenate(native_string, "^");   
          }
          native_string = msStringConcatenate(native_string, snippet);
          if (ieq == MS_TRUE) {
            native_string = msStringConcatenate(native_string, "$");
            ieq = MS_FALSE;   
          }
          native_string = msStringConcatenate(native_string, "'");
          msFree(snippet);
           break;
        case MS_TOKEN_LITERAL_BOOLEAN:
          if(node->tokenval.dblval == MS_TRUE)
            native_string = msStringConcatenate(native_string, "'TRUE'");
          else
             native_string = msStringConcatenate(native_string, "'FALSE'");
           break;
        case MS_TOKEN_LITERAL_TIME:
        {
          int resolution = msTimeGetResolution(node->tokensrc);
          snippet = (char *) msSmallMalloc(128);
          switch(resolution) {
            case TIME_RESOLUTION_YEAR:
              strtmpl = "to_date('%d-01','YYYY-MM')";
              sprintf(snippet, strtmpl, (node->tokenval.tmval.tm_year+1900));
              break;
            case TIME_RESOLUTION_MONTH:
              strtmpl = "to_date('%d-%02d','YYYY-MM')";
              sprintf(snippet, strtmpl, (node->tokenval.tmval.tm_year+1900), (node->tokenval.tmval.tm_mon+1));
              break;
            case TIME_RESOLUTION_DAY:
              strtmpl = "to_date('%d-%02d-%02d','YYYY-MM-DD') ";
              sprintf(snippet, strtmpl, (node->tokenval.tmval.tm_year+1900), (node->tokenval.tmval.tm_mon+1), node->tokenval.tmval.tm_mday);
              break;
            case TIME_RESOLUTION_HOUR:
              strtmpl = "to_timestamp('%d-%02d-%02d %02d','YYYY-MM-DD hh24')";
              sprintf(snippet, strtmpl, (node->tokenval.tmval.tm_year+1900), (node->tokenval.tmval.tm_mon+1), node->tokenval.tmval.tm_mday, node->tokenval.tmval.tm_hour);
              break;
            case TIME_RESOLUTION_MINUTE:
              strtmpl = "to_timestamp('%d-%02d-%02d %02d:%02d','YYYY-MM-DD hh24:mi')";
              sprintf(snippet, strtmpl, (node->tokenval.tmval.tm_year+1900), (node->tokenval.tmval.tm_mon+1), node->tokenval.tmval.tm_mday, node->tokenval.tmval.tm_hour, node->tokenval.tmval.tm_min);
              break;
            case TIME_RESOLUTION_SECOND:
              strtmpl = "to_timestamp('%d-%02d-%02d %02d:%02d:%02d','YYYY-MM-DD hh24:mi:ss')";
              sprintf(snippet, strtmpl, (node->tokenval.tmval.tm_year+1900), (node->tokenval.tmval.tm_mon+1), node->tokenval.tmval.tm_mday, node->tokenval.tmval.tm_hour, node->tokenval.tmval.tm_min, node->tokenval.tmval.tm_sec);
              break;
          }
          native_string = msStringConcatenate(native_string, snippet);
          msFree(snippet);
          break;
        }  
        case MS_TOKEN_LITERAL_SHAPE:
          native_string = msStringConcatenate(native_string, " SDO_GEOMETRY('");
          native_string = msStringConcatenate(native_string, msShapeToWKT(node->tokenval.shpval));
          native_string = msStringConcatenate(native_string, "'");
          if(srid && strcmp(srid, "") != 0) {
            native_string = msStringConcatenate(native_string, ", ");
            native_string = msStringConcatenate(native_string, srid);
          }
          native_string = msStringConcatenate(native_string, ") ");
          //msDebug("------> srid node value: %s", node->tokenval.shpval);
          break;
        case MS_TOKEN_BINDING_DOUBLE:
          native_string = msStringConcatenate(native_string, node->tokenval.bindval.item);
          break;
        case MS_TOKEN_BINDING_INTEGER:
          native_string = msStringConcatenate(native_string, node->tokenval.bindval.item);
          break;
        case MS_TOKEN_BINDING_STRING:
         if (node->next->token == MS_TOKEN_COMPARISON_RE || node->next->token == MS_TOKEN_COMPARISON_IRE 
          || node->next->token == MS_TOKEN_COMPARISON_IEQ ) {
              native_string = msStringConcatenate(native_string, "REGEXP_LIKE( ");
          } 
          strtmpl = "%s";
          snippet = (char *) msSmallMalloc(strlen(strtmpl) + strlen(node->tokenval.strval));
          sprintf(snippet, strtmpl, node->tokenval.strval);  // TODO: escape strval (msPostGISEscapeSQLParam)
          native_string = msStringConcatenate(native_string, snippet);
          free(snippet);
          break;
        case MS_TOKEN_BINDING_TIME:
          native_string = msStringConcatenate(native_string, node->tokenval.bindval.item);
          break;
        case MS_TOKEN_BINDING_SHAPE: 
          native_string = msStringConcatenate(native_string, geom_column_name);
          break;
        case MS_TOKEN_BINDING_MAP_CELLSIZE:
          strtmpl = "%lf";
          snippet = (char *) msSmallMalloc(strlen(strtmpl) + 16);
          sprintf(snippet, strtmpl, layer->map->cellsize);
          native_string = msStringConcatenate(native_string, snippet);
          free(snippet);
          break;
        case MS_TOKEN_LOGICAL_AND:
          native_string = msStringConcatenate(native_string, " AND ");
          break;
        case MS_TOKEN_LOGICAL_OR:
          native_string = msStringConcatenate(native_string, " OR ");
          break;
        case MS_TOKEN_LOGICAL_NOT:
          native_string = msStringConcatenate(native_string, " NOT ");
          break;
        case MS_TOKEN_COMPARISON_EQ:
          native_string = msStringConcatenate(native_string, " = ");
          break;
        case MS_TOKEN_COMPARISON_NE: 
          native_string = msStringConcatenate(native_string, " != ");
          break;
        case MS_TOKEN_COMPARISON_GT: 
          native_string = msStringConcatenate(native_string, " > ");
          break;
        case MS_TOKEN_COMPARISON_GE:
          native_string = msStringConcatenate(native_string, " >= ");
          break;
        case MS_TOKEN_COMPARISON_LT:
          native_string = msStringConcatenate(native_string, " < ");
          break;
        case MS_TOKEN_COMPARISON_LE:
          native_string = msStringConcatenate(native_string, " <= ");
          break;
        case MS_TOKEN_COMPARISON_IEQ:
          // this is for  case insensitve equals check
          msDebug("got a IEQ comparison\n");
          regexp_like = MS_TRUE;
          case_ins = MS_TRUE;
          ieq = MS_TRUE;
          native_string = msStringConcatenate(native_string, ", ");
          break;
        case MS_TOKEN_COMPARISON_RE:
          // the regex formats that MS uses as Oracle users are different so just return and eval the regex's in MS
          //return MS_SUCCESS;
          msDebug("got a RE comparison\n");
          regexp_like = MS_TRUE;
          native_string = msStringConcatenate(native_string, ", ");
          break;
        case MS_TOKEN_COMPARISON_IRE:
          // the regex formats that MS uses as Oracle users are different so just return and eval the regex's in MS
          regexp_like = MS_TRUE;
          case_ins = MS_TRUE;
          native_string = msStringConcatenate(native_string, ", ");
          break;
        case MS_TOKEN_COMPARISON_IN:
          native_string = msStringConcatenate(native_string, " IN ");
          break;
        case MS_TOKEN_COMPARISON_LIKE:
          native_string = msStringConcatenate(native_string, " LIKE ");
          break;
        case MS_TOKEN_COMPARISON_INTERSECTS:
          native_string = msStringConcatenate(native_string, " ST_INTERSECTS ");
          break;
        case MS_TOKEN_COMPARISON_DISJOINT:
          native_string = msStringConcatenate(native_string, " NOT ST_INTERSECTS ");
          break;
        case MS_TOKEN_COMPARISON_TOUCHES:
          native_string = msStringConcatenate(native_string, " ST_TOUCH ");
          break;
        case MS_TOKEN_COMPARISON_OVERLAPS:
          native_string = msStringConcatenate(native_string, " ST_OVERLAPS ");
          break;
        case MS_TOKEN_COMPARISON_CROSSES:
          native_string = msStringConcatenate(native_string, " SDO_OVERLAPBDYDISJOINT ");
          break;
        case MS_TOKEN_COMPARISON_WITHIN:
          native_string = msStringConcatenate(native_string, " ST_INSIDE ");
          break;
        case MS_TOKEN_COMPARISON_CONTAINS:
          native_string = msStringConcatenate(native_string, " SDO_CONTAINS ");
          break;
        case MS_TOKEN_COMPARISON_EQUALS:
          native_string = msStringConcatenate(native_string, " SDO_EQUAL ");
          break;  
        case MS_TOKEN_COMPARISON_BEYOND:
          //support for the wfs case
          dwithin = MS_TRUE;
          native_string = msStringConcatenate(native_string, "NOT SDO_WITHIN_DISTANCE ");
          break;
        case MS_TOKEN_COMPARISON_DWITHIN:
          dwithin = MS_TRUE;
          native_string = msStringConcatenate(native_string, "SDO_WITHIN_DISTANCE ");
          break;
        case MS_TOKEN_FUNCTION_LENGTH:
          break;
        case MS_TOKEN_FUNCTION_TOSTRING:
          break;
        case MS_TOKEN_FUNCTION_COMMIFY:
          break;
        case MS_TOKEN_FUNCTION_AREA:
          native_string = msStringConcatenate(native_string, "SDO_GEOM.SDO_AREA "); 
          break;
        case MS_TOKEN_FUNCTION_ROUND:
          native_string = msStringConcatenate(native_string, "ROUND ");  
          break;
        case MS_TOKEN_FUNCTION_FROMTEXT:
          native_string = msStringConcatenate(native_string, "SDO_GEOMETRY "); 
          break;
        case MS_TOKEN_FUNCTION_BUFFER:
           // native_string = msStringConcatenate(native_string, " SDO_BUFFER "); 
           //buffer = MS_TRUE; 
          break;
        case MS_TOKEN_FUNCTION_DIFFERENCE:
          native_string = msStringConcatenate(native_string, "ST_DIFFERENCE ");
          break;
        case MS_TOKEN_FUNCTION_SIMPLIFY:
          native_string = msStringConcatenate(native_string, "SDO_UTIL.SIMPLIFY "); 
          break;
        case MS_TOKEN_FUNCTION_SIMPLIFYPT:
          break;
        case MS_TOKEN_FUNCTION_GENERALIZE:
          native_string = msStringConcatenate(native_string, "SDO_UTIL.SIMPLIFY "); 
          break;
        case ',':
          native_string = msStringConcatenate(native_string, ",");
          break;
        case '~':
          break;
        default:
          fprintf(stderr, "Translation to native SQL failed.\n");
          msFree(native_string);
          if (layer->debug) {
            msDebug("Token not caught, exiting: Token is %i\n", node->token);
          }

          return MS_SUCCESS; /* not an error */
        }
      nodeCount++;  
      node = node->next;
      
      //fprintf(stderr, "native filter: %s\n", native_string);
    }

    filter->native_string = msStrdup(native_string);
    if (layer->debug>=4)
      msDebug("total filter tokens are %i\n,", nodeCount);
    msFree(native_string);
  }
  return MS_SUCCESS;
}


#else
/* OracleSpatial "not-supported" procedures */

int msOracleSpatialLayerOpen(layerObj *layer)
{
  msSetError( MS_ORACLESPATIALERR, "OracleSpatial is not supported", "msOracleSpatialLayerOpen()" );
  return MS_FAILURE;
}

int msOracleSpatialLayerIsOpen(layerObj *layer)
{
  msSetError( MS_ORACLESPATIALERR, "OracleSpatial is not supported", "msOracleSpatialLayerIsOpen()" );
  return MS_FALSE;
}

int msOracleSpatialLayerClose(layerObj *layer)
{
  msSetError( MS_ORACLESPATIALERR, "OracleSpatial is not supported", "msOracleSpatialLayerClose()" );
  return MS_FAILURE;
}

int msOracleSpatialLayerWhichShapes(layerObj *layer, rectObj rect, int isQuery)
{
  msSetError( MS_ORACLESPATIALERR, "OracleSpatial is not supported", "msOracleSpatialLayerWhichShapes()" );
  return MS_FAILURE;
}

int msOracleSpatialLayerNextShape(layerObj *layer, shapeObj *shape)
{
  msSetError( MS_ORACLESPATIALERR, "OracleSpatial is not supported", "msOracleSpatialLayerNextShape()" );
  return MS_FAILURE;
}

int msOracleSpatialLayerGetItems(layerObj *layer)
{
  msSetError( MS_ORACLESPATIALERR, "OracleSpatial is not supported", "msOracleSpatialLayerGetItems()" );
  return MS_FAILURE;
}

int msOracleSpatialLayerGetShape( layerObj *layer, shapeObj *shape, resultObj *record )
{
  msSetError( MS_ORACLESPATIALERR, "OracleSpatial is not supported", "msOracleSpatialLayerGetShape()" );
  return MS_FAILURE;
}

int msOracleSpatialLayerGetExtent(layerObj *layer, rectObj *extent)
{
  msSetError( MS_ORACLESPATIALERR, "OracleSpatial is not supported", "msOracleSpatialLayerGetExtent()" );
  return MS_FAILURE;
}

int msOracleSpatialLayerInitItemInfo(layerObj *layer)
{
  msSetError( MS_ORACLESPATIALERR, "OracleSpatial is not supported", "msOracleSpatialLayerInitItemInfo()" );
  return MS_FAILURE;
}

void msOracleSpatialLayerFreeItemInfo(layerObj *layer)
{
  msSetError( MS_ORACLESPATIALERR, "OracleSpatial is not supported", "msOracleSpatialLayerFreeItemInfo()" );
}

int msOracleSpatialLayerGetAutoStyle( mapObj *map, layerObj *layer, classObj *c, shapeObj *shape )
{
  msSetError( MS_ORACLESPATIALERR, "OracleSpatial is not supported", "msLayerGetAutoStyle()" );
  return MS_FAILURE;
}

void msOracleSpatialEnablePaging(layerObj *layer, int value)
{
  msSetError( MS_ORACLESPATIALERR, "OracleSpatial is not supported", "msLayerEnablePaging()" );
  return;
}

int msOracleSpatialGetPaging(layerObj *layer)
{
  msSetError( MS_ORACLESPATIALERR, "OracleSpatial is not supported", "msLayerGetPaging()" );
  return MS_FAILURE;
}

int msOracleSpatialLayerTranslateFilter(layerObj *layer, expressionObj *filter, char *filteritem)
{
  msSetError( MS_ORACLESPATIALERR, "OracleSpatial is not supported", "msLayerTranslateFilter()" );
  return MS_FAILURE;
}

char *msOracleSpatialEscapePropertyName(layerObj *layer, const char* pszString)
{
  msSetError( MS_ORACLESPATIALERR, "OracleSpatial is not supported", "msLayerEscapePropertyName()" );
  return msStrdup(pszString);
}
#endif

#if defined USE_ORACLE_PLUGIN
MS_DLL_EXPORT  int
PluginInitializeVirtualTable(layerVTableObj* vtable, layerObj *layer)
{
  assert(layer != NULL);
  assert(vtable != NULL);

  vtable->LayerTranslateFilter = msOracleSpatialLayerTranslateFilter;


  vtable->LayerInitItemInfo = msOracleSpatialLayerInitItemInfo;
  vtable->LayerFreeItemInfo = msOracleSpatialLayerFreeItemInfo;
  vtable->LayerOpen = msOracleSpatialLayerOpen;
  vtable->LayerIsOpen = msOracleSpatialLayerIsOpen;
  vtable->LayerWhichShapes = msOracleSpatialLayerWhichShapes;
  vtable->LayerNextShape = msOracleSpatialLayerNextShape;
  vtable->LayerGetShape = msOracleSpatialLayerGetShape;
  vtable->LayerClose = msOracleSpatialLayerClose;
  vtable->LayerGetItems = msOracleSpatialLayerGetItems;
  vtable->LayerGetExtent = msOracleSpatialLayerGetExtent;
  /* layer->vtable->LayerGetAutoStyle, use default */
  /* layer->vtable->LayerApplyFilterToLayer, use default */
  vtable->LayerCloseConnection = msOracleSpatialLayerClose;
  vtable->LayerApplyFilterToLayer = msLayerApplyCondSQLFilterToLayer;
  vtable->LayerSetTimeFilter = msLayerMakeBackticsTimeFilter;
  //vtable->LayerSetTimeFilter = msOracleSpatialLayerSetTimeFilter;
  //vtable->LayerEscapePropertyName = msOracleSpatialEscapePropertyName;
  /* layer->vtable->LayerGetNumFeatures, use default */
  /* layer->vtable->LayerGetAutoProjection = msOracleSpatialLayerGetAutoProjection; Disabled until tested */
  vtable->LayerEnablePaging = msOracleSpatialEnablePaging;
  vtable->LayerGetPaging = msOracleSpatialGetPaging;

  return MS_SUCCESS;
}

#else /*if ORACLE_PLUGIN is defined, then this file is not used by libmapserver
        and therefre there is no need to include this function */
int msOracleSpatialLayerInitializeVirtualTable(layerObj *layer)
{
  assert(layer != NULL);
  assert(layer->vtable != NULL);

  layer->vtable->LayerTranslateFilter = msOracleSpatialLayerTranslateFilter;


  layer->vtable->LayerInitItemInfo = msOracleSpatialLayerInitItemInfo;
  layer->vtable->LayerFreeItemInfo = msOracleSpatialLayerFreeItemInfo;
  layer->vtable->LayerOpen = msOracleSpatialLayerOpen;
  layer->vtable->LayerIsOpen = msOracleSpatialLayerIsOpen;
  layer->vtable->LayerWhichShapes = msOracleSpatialLayerWhichShapes;
  layer->vtable->LayerNextShape = msOracleSpatialLayerNextShape;
  layer->vtable->LayerGetShape = msOracleSpatialLayerGetShape;
  /* layer->vtable->LayerGetShapeCount, use default */
  layer->vtable->LayerClose = msOracleSpatialLayerClose;
  layer->vtable->LayerGetItems = msOracleSpatialLayerGetItems;
  layer->vtable->LayerGetExtent = msOracleSpatialLayerGetExtent;
  /* layer->vtable->LayerGetAutoStyle, use default */
  layer->vtable->LayerCloseConnection = msOracleSpatialLayerClose;
  layer->vtable->LayerApplyFilterToLayer = msLayerApplyCondSQLFilterToLayer;
  layer->vtable->LayerSetTimeFilter = msLayerMakeBackticsTimeFilter;
  //layer->vtable->LayerSetTimeFilter = msOracleSpatialLayerSetTimeFilter;
  //layer->vtable->LayerEscapePropertyName = msOracleSpatialEscapePropertyName;
  /* layer->vtable->LayerCreateItems, use default */
  /* layer->vtable->LayerGetNumFeatures, use default */
  /* layer->vtable->LayerGetAutoProjection = msOracleSpatialLayerGetAutoProjection; Disabled until tested */
  layer->vtable->LayerEnablePaging = msOracleSpatialEnablePaging;
  layer->vtable->LayerGetPaging = msOracleSpatialGetPaging;

  return MS_SUCCESS;
}
#endif