Skip to content
This repository
tree: cce80f3892
Fetching contributors…

Cannot retrieve contributors at this time

file 3333 lines (2879 sloc) 118.582 kb
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
/**********************************************************************
* $Id$
*
* Project: MapServer
* Purpose: OGR Link
* Author: Daniel Morissette, DM Solutions Group (morissette@dmsolutions.ca)
* Frank Warmerdam (warmerdam@pobox.com)
*
**********************************************************************
* Copyright (c) 2000-2005, Daniel Morissette, DM Solutions Group Inc
*
* 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 <assert.h>
#include "mapserver.h"
#include "mapproject.h"
#include "mapthread.h"

#if defined(USE_OGR) || defined(USE_GDAL)
# include "gdal_version.h"
# include "cpl_conv.h"
# include "cpl_string.h"
# include "ogr_srs_api.h"
#endif



#define ACQUIRE_OGR_LOCK msAcquireLock( TLOCK_OGR )
#define RELEASE_OGR_LOCK msReleaseLock( TLOCK_OGR )

#ifdef USE_OGR

#include "ogr_api.h"

typedef struct ms_ogr_file_info_t
{
  char *pszFname;
  int nLayerIndex;
  OGRDataSourceH hDS;
  OGRLayerH hLayer;
  OGRFeatureH hLastFeature;

  int nTileId; /* applies on the tiles themselves. */

  struct ms_ogr_file_info_t *poCurTile; /* exists on tile index, -> tiles */
  rectObj rect; /* set by WhichShapes */

  int last_record_index_read;

} msOGRFileInfo;

static int msOGRLayerIsOpen(layerObj *layer);
static int msOGRLayerInitItemInfo(layerObj *layer);
static int msOGRLayerGetAutoStyle(mapObj *map, layerObj *layer, classObj *c,
                                  shapeObj* shape);
static void msOGRCloseConnection( void *conn_handle );

/* ==================================================================
* Geometry conversion functions
* ================================================================== */

/**********************************************************************
* ogrPointsAddPoint()
*
* NOTE: This function assumes the line->point array already has been
* allocated large enough for the point to be added, but that numpoints
* does not include this new point.
**********************************************************************/
static void ogrPointsAddPoint(lineObj *line, double dX, double dY,
                              int lineindex, rectObj *bounds)
{
    /* Keep track of shape bounds */
    if (line->numpoints == 0 && lineindex == 0)
    {
        bounds->minx = bounds->maxx = dX;
        bounds->miny = bounds->maxy = dY;
    }
    else
    {
        if (dX < bounds->minx) bounds->minx = dX;
        if (dX > bounds->maxx) bounds->maxx = dX;
        if (dY < bounds->miny) bounds->miny = dY;
        if (dY > bounds->maxy) bounds->maxy = dY;
    }

    line->point[line->numpoints].x = dX;
    line->point[line->numpoints].y = dY;
#ifdef USE_POINT_Z_M
    line->point[line->numpoints].z = 0.0;
    line->point[line->numpoints].m = 0.0;
#endif
    line->numpoints++;
}

/**********************************************************************
* ogrGeomPoints()
**********************************************************************/
static int ogrGeomPoints(OGRGeometryH hGeom, shapeObj *outshp)
{
  int i;
  int numpoints;

  if (hGeom == NULL)
      return 0;

  OGRwkbGeometryType eGType = wkbFlatten( OGR_G_GetGeometryType( hGeom ) );

/* -------------------------------------------------------------------- */
/* Container types result in recursive invocation on each */
/* subobject to add a set of points to the current list. */
/* -------------------------------------------------------------------- */
  switch( eGType )
  {
      case wkbGeometryCollection:
      case wkbMultiLineString:
      case wkbMultiPolygon:
      case wkbPolygon:
      {
          /* Treat it as GeometryCollection */
          for (int iGeom=0; iGeom < OGR_G_GetGeometryCount( hGeom ); iGeom++ )
          {
              if( ogrGeomPoints( OGR_G_GetGeometryRef( hGeom, iGeom ),
                                 outshp ) == -1 )
                  return -1;
          }

          return 0;
      }
      break;

      case wkbPoint:
      case wkbMultiPoint:
      case wkbLineString:
      case wkbLinearRing:
          /* We will handle these directly */
          break;

      default:
          /* There shouldn't be any more cases should there? */
          msSetError(MS_OGRERR,
                     "OGRGeometry type `%s' not supported yet.",
                     "ogrGeomPoints()",
                     OGR_G_GetGeometryName( hGeom ) );
          return(-1);
  }


/* ------------------------------------------------------------------
* Count total number of points
* ------------------------------------------------------------------ */
  if ( eGType == wkbPoint )
  {
      numpoints = 1;
  }
  else if ( eGType == wkbLineString
            || eGType == wkbLinearRing )
  {
      numpoints = OGR_G_GetPointCount( hGeom );
  }
  else if ( eGType == wkbMultiPoint )
  {
      numpoints = OGR_G_GetGeometryCount( hGeom );
  }
  else
  {
      msSetError(MS_OGRERR,
                 "OGRGeometry type `%s' not supported yet.",
                 "ogrGeomPoints()",
                 OGR_G_GetGeometryName( hGeom ) );
      return(-1);
  }

/* ------------------------------------------------------------------
* Do we need to allocate a line object to contain all our points?
* ------------------------------------------------------------------ */
  if( outshp->numlines == 0 )
  {
      lineObj newline;
      
      newline.numpoints = 0;
      newline.point = NULL;
      msAddLine(outshp, &newline);
  }
  
/* ------------------------------------------------------------------
* Extend the point array for the new of points to add from the
* current geometry.
* ------------------------------------------------------------------ */
  lineObj *line = outshp->line + outshp->numlines-1;

  if( line->point == NULL )
      line->point = (pointObj *) malloc(sizeof(pointObj) * numpoints);
  else
      line->point = (pointObj *)
          realloc(line->point,sizeof(pointObj) * (numpoints+line->numpoints));
  
  if(!line->point)
  {
      msSetError(MS_MEMERR, "Unable to allocate temporary point cache.",
                 "ogrGeomPoints()");
      return(-1);
  }
   
/* ------------------------------------------------------------------
* alloc buffer and filter/transform points
* ------------------------------------------------------------------ */
  if( eGType == wkbPoint )
  {
      ogrPointsAddPoint(line, OGR_G_GetX(hGeom, 0), OGR_G_GetY(hGeom, 0),
                        outshp->numlines-1, &(outshp->bounds));
  }
  else if( eGType == wkbLineString
           || eGType == wkbLinearRing )
  {
      for(i=0; i<numpoints; i++)
          ogrPointsAddPoint(line, OGR_G_GetX(hGeom, i), OGR_G_GetY(hGeom, i),
                            outshp->numlines-1, &(outshp->bounds));
  }
  else if( eGType == wkbMultiPoint )
  {
      for(i=0; i<numpoints; i++)
      {
          OGRGeometryH hPoint = OGR_G_GetGeometryRef( hGeom, i );
          ogrPointsAddPoint(line, OGR_G_GetX(hPoint, 0), OGR_G_GetY(hPoint, 0),
                            outshp->numlines-1, &(outshp->bounds));
      }
  }

  outshp->type = MS_SHAPE_POINT;

  return(0);
}


/**********************************************************************
* ogrGeomLine()
*
* Recursively convert any OGRGeometry into a shapeObj. Each part becomes
* a line in the overall shapeObj.
**********************************************************************/
static int ogrGeomLine(OGRGeometryH hGeom, shapeObj *outshp,
                       int bCloseRings)
{
  if (hGeom == NULL)
      return 0;

/* ------------------------------------------------------------------
* Use recursive calls for complex geometries
* ------------------------------------------------------------------ */
  OGRwkbGeometryType eGType = wkbFlatten( OGR_G_GetGeometryType( hGeom ) );

  
  if ( eGType == wkbPolygon
       || eGType == wkbGeometryCollection
       || eGType == wkbMultiLineString
       || eGType == wkbMultiPolygon )
  {
      if (eGType == wkbPolygon && outshp->type == MS_SHAPE_NULL)
          outshp->type = MS_SHAPE_POLYGON;

      /* Treat it as GeometryCollection */
      for (int iGeom=0; iGeom < OGR_G_GetGeometryCount( hGeom ); iGeom++ )
      {
          if( ogrGeomLine( OGR_G_GetGeometryRef( hGeom, iGeom ),
                           outshp, bCloseRings ) == -1 )
              return -1;
      }
  }
/* ------------------------------------------------------------------
* OGRPoint and OGRMultiPoint
* ------------------------------------------------------------------ */
  else if ( eGType == wkbPoint || eGType == wkbMultiPoint )
  {
      /* Hummmm a point when we're drawing lines/polygons... just drop it! */
  }
/* ------------------------------------------------------------------
* OGRLinearRing/OGRLineString ... both are of type wkbLineString
* ------------------------------------------------------------------ */
  else if ( eGType == wkbLineString )
  {
      int j, numpoints;
      lineObj line={0,NULL};
      double dX, dY;

      if ((numpoints = OGR_G_GetPointCount( hGeom )) < 2)
          return 0;

      if (outshp->type == MS_SHAPE_NULL)
          outshp->type = MS_SHAPE_LINE;

      line.numpoints = 0;
      line.point = (pointObj *)malloc(sizeof(pointObj)*(numpoints+1));
      if(!line.point)
      {
          msSetError(MS_MEMERR, "Unable to allocate temporary point cache.",
                     "ogrGeomLine");
          return(-1);
      }

#if GDAL_VERSION_NUM >= 1900
      OGR_G_GetPoints(hGeom,
                      &(line.point[0].x), sizeof(pointObj),
                      &(line.point[0].y), sizeof(pointObj),
                      NULL, 0);
#endif

      for(j=0; j<numpoints; j++)
      {
#if GDAL_VERSION_NUM < 1900
          dX = line.point[j].x = OGR_G_GetX( hGeom, j);
          dY = line.point[j].y = OGR_G_GetY( hGeom, j);
#else
          dX = line.point[j].x;
          dY = line.point[j].y;
#endif

          /* Keep track of shape bounds */
          if (j == 0 && outshp->numlines == 0)
          {
              outshp->bounds.minx = outshp->bounds.maxx = dX;
              outshp->bounds.miny = outshp->bounds.maxy = dY;
          }
          else
          {
              if (dX < outshp->bounds.minx) outshp->bounds.minx = dX;
              if (dX > outshp->bounds.maxx) outshp->bounds.maxx = dX;
              if (dY < outshp->bounds.miny) outshp->bounds.miny = dY;
              if (dY > outshp->bounds.maxy) outshp->bounds.maxy = dY;
          }

      }
      line.numpoints = numpoints;

      if (bCloseRings &&
          ( line.point[line.numpoints-1].x != line.point[0].x ||
            line.point[line.numpoints-1].y != line.point[0].y ) )
      {
          line.point[line.numpoints].x = line.point[0].x;
          line.point[line.numpoints].y = line.point[0].y;
          line.numpoints++;
      }

      msAddLineDirectly(outshp, &line);
  }
  else
  {
      msSetError(MS_OGRERR,
                 "OGRGeometry type `%s' not supported.",
                 "ogrGeomLine()",
                 OGR_G_GetGeometryName( hGeom ) );
      return(-1);
  }

  return(0);
}


/**********************************************************************
* ogrConvertGeometry()
*
* Convert OGR geometry into a shape object doing the best possible
* job to match OGR Geometry type and layer type.
*
* If layer type is incompatible with geometry, then shape is returned with
* shape->type = MS_SHAPE_NULL
**********************************************************************/
static int ogrConvertGeometry(OGRGeometryH hGeom, shapeObj *outshp,
                              enum MS_LAYER_TYPE layertype)
{
/* ------------------------------------------------------------------
* Process geometry according to layer type
* ------------------------------------------------------------------ */
  int nStatus = MS_SUCCESS;

  if (hGeom == NULL)
  {
      // Empty geometry... this is not an error... we'll just skip it
      return MS_SUCCESS;
  }

  switch(layertype)
  {
/* ------------------------------------------------------------------
* POINT layer - Any geometry can be converted to point/multipoint
* ------------------------------------------------------------------ */
    case MS_LAYER_POINT:
      if(ogrGeomPoints(hGeom, outshp) == -1)
      {
          nStatus = MS_FAILURE; // Error message already produced.
      }
      break;
/* ------------------------------------------------------------------
* LINE layer
* ------------------------------------------------------------------ */
    case MS_LAYER_LINE:
      if(ogrGeomLine(hGeom, outshp, MS_FALSE) == -1)
      {
          nStatus = MS_FAILURE; // Error message already produced.
      }
      if (outshp->type != MS_SHAPE_LINE && outshp->type != MS_SHAPE_POLYGON)
          outshp->type = MS_SHAPE_NULL; // Incompatible type for this layer
      break;
/* ------------------------------------------------------------------
* POLYGON layer
* ------------------------------------------------------------------ */
    case MS_LAYER_POLYGON:
      if(ogrGeomLine(hGeom, outshp, MS_TRUE) == -1)
      {
          nStatus = MS_FAILURE; // Error message already produced.
      }
      if (outshp->type != MS_SHAPE_POLYGON)
          outshp->type = MS_SHAPE_NULL; // Incompatible type for this layer
      break;
/* ------------------------------------------------------------------
* MS_ANNOTATION layer - return real feature type
* ------------------------------------------------------------------ */
    case MS_LAYER_ANNOTATION:
    case MS_LAYER_CHART:
    case MS_LAYER_QUERY:
      switch( OGR_G_GetGeometryType( hGeom ) )
      {
        case wkbPoint:
        case wkbPoint25D:
        case wkbMultiPoint:
        case wkbMultiPoint25D:
          if(ogrGeomPoints(hGeom, outshp) == -1)
          {
              nStatus = MS_FAILURE; // Error message already produced.
          }
          break;
        default:
          // Handle any non-point types as lines/polygons ... ogrGeomLine()
          // will decide the shape type
          if(ogrGeomLine(hGeom, outshp, MS_FALSE) == -1)
          {
              nStatus = MS_FAILURE; // Error message already produced.
          }
      }
      break;

    default:
      msSetError(MS_MISCERR, "Unknown or unsupported layer type.",
                 "msOGRLayerNextShape()");
      nStatus = MS_FAILURE;
  } /* switch layertype */

  return nStatus;
}

/**********************************************************************
* msOGRGeometryToShape()
*
* Utility function to convert from OGR geometry to a mapserver shape
* object.
**********************************************************************/
int msOGRGeometryToShape(OGRGeometryH hGeometry, shapeObj *psShape,
                         OGRwkbGeometryType nType)
{
    if (hGeometry && psShape && nType > 0)
    {
        if (nType == wkbPoint || nType == wkbMultiPoint )
            return ogrConvertGeometry(hGeometry, psShape, MS_LAYER_POINT);
        else if (nType == wkbLineString || nType == wkbMultiLineString)
            return ogrConvertGeometry(hGeometry, psShape, MS_LAYER_LINE);
        else if (nType == wkbPolygon || nType == wkbMultiPolygon)
            return ogrConvertGeometry(hGeometry, psShape, MS_LAYER_POLYGON);
        else
            return MS_FAILURE;
    }
    else
        return MS_FAILURE;
}


/* ==================================================================
* Attributes handling functions
* ================================================================== */

// Special field index codes for handling text string and angle coming from
// OGR style strings.
#define MSOGR_LABELNUMITEMS 21
#define MSOGR_LABELFONTNAMENAME "OGR:LabelFont"
#define MSOGR_LABELFONTNAMEINDEX -100
#define MSOGR_LABELSIZENAME "OGR:LabelSize"
#define MSOGR_LABELSIZEINDEX -101
#define MSOGR_LABELTEXTNAME "OGR:LabelText"
#define MSOGR_LABELTEXTINDEX -102
#define MSOGR_LABELANGLENAME "OGR:LabelAngle"
#define MSOGR_LABELANGLEINDEX -103
#define MSOGR_LABELFCOLORNAME "OGR:LabelFColor"
#define MSOGR_LABELFCOLORINDEX -104
#define MSOGR_LABELBCOLORNAME "OGR:LabelBColor"
#define MSOGR_LABELBCOLORINDEX -105
#define MSOGR_LABELPLACEMENTNAME "OGR:LabelPlacement"
#define MSOGR_LABELPLACEMENTINDEX -106
#define MSOGR_LABELANCHORNAME "OGR:LabelAnchor"
#define MSOGR_LABELANCHORINDEX -107
#define MSOGR_LABELDXNAME "OGR:LabelDx"
#define MSOGR_LABELDXINDEX -108
#define MSOGR_LABELDYNAME "OGR:LabelDy"
#define MSOGR_LABELDYINDEX -109
#define MSOGR_LABELPERPNAME "OGR:LabelPerp"
#define MSOGR_LABELPERPINDEX -110
#define MSOGR_LABELBOLDNAME "OGR:LabelBold"
#define MSOGR_LABELBOLDINDEX -111
#define MSOGR_LABELITALICNAME "OGR:LabelItalic"
#define MSOGR_LABELITALICINDEX -112
#define MSOGR_LABELUNDERLINENAME "OGR:LabelUnderline"
#define MSOGR_LABELUNDERLINEINDEX -113
#define MSOGR_LABELPRIORITYNAME "OGR:LabelPriority"
#define MSOGR_LABELPRIORITYINDEX -114
#define MSOGR_LABELSTRIKEOUTNAME "OGR:LabelStrikeout"
#define MSOGR_LABELSTRIKEOUTINDEX -115
#define MSOGR_LABELSTRETCHNAME "OGR:LabelStretch"
#define MSOGR_LABELSTRETCHINDEX -116
#define MSOGR_LABELADJHORNAME "OGR:LabelAdjHor"
#define MSOGR_LABELADJHORINDEX -117
#define MSOGR_LABELADJVERTNAME "OGR:LabelAdjVert"
#define MSOGR_LABELADJVERTINDEX -118
#define MSOGR_LABELHCOLORNAME "OGR:LabelHColor"
#define MSOGR_LABELHCOLORINDEX -119
#define MSOGR_LABELOCOLORNAME "OGR:LabelOColor"
#define MSOGR_LABELOCOLORINDEX -120


/**********************************************************************
* msOGRGetValues()
*
* Load selected item (i.e. field) values into a char array
*
* Some special attribute names are used to return some OGRFeature params
* like for instance stuff encoded in the OGRStyleString.
* For now the following pseudo-attribute names are supported:
* "OGR:TextString" OGRFeatureStyle's text string if present
* "OGR:TextAngle" OGRFeatureStyle's text angle, or 0 if not set
**********************************************************************/
static char **msOGRGetValues(layerObj *layer, OGRFeatureH hFeature)
{
  char **values;
  const char *pszValue = NULL;
  int i;

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

  if(!layer->iteminfo) // Should not happen... but just in case!
      if (msOGRLayerInitItemInfo(layer) != MS_SUCCESS)
          return NULL;

  if((values = (char **)malloc(sizeof(char *)*layer->numitems)) == NULL)
  {
    msSetError(MS_MEMERR, NULL, "msOGRGetValues()");
    return(NULL);
  }

  OGRStyleMgrH hStyleMgr = NULL;
  OGRStyleToolH hLabelStyle = NULL;

  int *itemindexes = (int*)layer->iteminfo;

  for(i=0;i<layer->numitems;i++)
  {
    if (itemindexes[i] >= 0)
    {
        // Extract regular attributes
        values[i] = msStrdup(OGR_F_GetFieldAsString( hFeature, itemindexes[i]));
    }
    else
    {
        // Handle special OGR attributes coming from StyleString
        if (!hStyleMgr)
        {
            hStyleMgr = OGR_SM_Create(NULL);
            OGR_SM_InitFromFeature(hStyleMgr, hFeature);
            OGRStyleToolH hStylePart = OGR_SM_GetPart(hStyleMgr, 0, NULL);
            if (hStylePart && OGR_ST_GetType(hStylePart) == OGRSTCLabel)
                hLabelStyle = hStylePart;
            else if (hStylePart)
            {
                OGR_ST_Destroy(hStylePart);
                hStylePart = NULL;
            }

          /* Setting up the size units according to msOGRLayerGetAutoStyle*/
          if (hStylePart && layer->map)
            OGR_ST_SetUnit(hStylePart, OGRSTUPixel, layer->map->cellsize*72.0*39.37);
        }
        int bDefault;
        if (itemindexes[i] == MSOGR_LABELTEXTINDEX)
        {
            if (hLabelStyle == NULL
                || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
                                                          OGRSTLabelTextString,
                                                          &bDefault)) == NULL))
                values[i] = msStrdup("");
            else
                values[i] = msStrdup(pszValue);

            if (layer->debug >= MS_DEBUGLEVEL_VVV)
                msDebug(MSOGR_LABELTEXTNAME " = \"%s\"\n", values[i]);
        }
        else if (itemindexes[i] == MSOGR_LABELANGLEINDEX)
        {
            if (hLabelStyle == NULL
                || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
                                                          OGRSTLabelAngle,
                                                          &bDefault)) == NULL))
                values[i] = msStrdup("0");
            else
                values[i] = msStrdup(pszValue);

            if (layer->debug >= MS_DEBUGLEVEL_VVV)
                msDebug(MSOGR_LABELANGLENAME " = \"%s\"\n", values[i]);
        }
        else if (itemindexes[i] == MSOGR_LABELSIZEINDEX)
        {
            if (hLabelStyle == NULL
                || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
                                                          OGRSTLabelSize,
                                                          &bDefault)) == NULL))
                values[i] = msStrdup("0");
            else
                values[i] = msStrdup(pszValue);

            if (layer->debug >= MS_DEBUGLEVEL_VVV)
                msDebug(MSOGR_LABELSIZENAME " = \"%s\"\n", values[i]);
        }
        else if (itemindexes[i] == MSOGR_LABELFCOLORINDEX)
        {
            if (hLabelStyle == NULL
                || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
                                                          OGRSTLabelFColor,
                                                          &bDefault)) == NULL))
                values[i] = msStrdup("#000000");
            else
                values[i] = msStrdup(pszValue);

            if (layer->debug >= MS_DEBUGLEVEL_VVV)
                msDebug(MSOGR_LABELFCOLORNAME " = \"%s\"\n", values[i]);
        }
        else if (itemindexes[i] == MSOGR_LABELFONTNAMEINDEX )
        {
            if (hLabelStyle == NULL
                || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
                                                          OGRSTLabelFontName,
                                                          &bDefault)) == NULL))
                values[i] = msStrdup("Arial");
            else
                values[i] = msStrdup(pszValue);

            if (layer->debug >= MS_DEBUGLEVEL_VVV)
                msDebug(MSOGR_LABELFONTNAMENAME " = \"%s\"\n", values[i]);
        }
        else if (itemindexes[i] == MSOGR_LABELBCOLORINDEX)
        {
            if (hLabelStyle == NULL
                || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
                                                          OGRSTLabelBColor,
                                                          &bDefault)) == NULL))
                values[i] = msStrdup("#000000");
            else
                values[i] = msStrdup(pszValue);

            if (layer->debug >= MS_DEBUGLEVEL_VVV)
                msDebug(MSOGR_LABELBCOLORNAME " = \"%s\"\n", values[i]);
        }
        else if (itemindexes[i] == MSOGR_LABELPLACEMENTINDEX)
        {
            if (hLabelStyle == NULL
                || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
                                                          OGRSTLabelPlacement,
                                                          &bDefault)) == NULL))
                values[i] = msStrdup("");
            else
                values[i] = msStrdup(pszValue);

            if (layer->debug >= MS_DEBUGLEVEL_VVV)
                msDebug(MSOGR_LABELPLACEMENTNAME " = \"%s\"\n", values[i]);
        }
        else if (itemindexes[i] == MSOGR_LABELANCHORINDEX)
        {
            if (hLabelStyle == NULL
                || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
                                                          OGRSTLabelAnchor,
                                                          &bDefault)) == NULL))
                values[i] = msStrdup("0");
            else
                values[i] = msStrdup(pszValue);

            if (layer->debug >= MS_DEBUGLEVEL_VVV)
                msDebug(MSOGR_LABELANCHORNAME " = \"%s\"\n", values[i]);
        }
        else if (itemindexes[i] == MSOGR_LABELDXINDEX)
        {
            if (hLabelStyle == NULL
                || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
                                                          OGRSTLabelDx,
                                                          &bDefault)) == NULL))
                values[i] = msStrdup("0");
            else
                values[i] = msStrdup(pszValue);

            if (layer->debug >= MS_DEBUGLEVEL_VVV)
                msDebug(MSOGR_LABELDXNAME " = \"%s\"\n", values[i]);
        }
        else if (itemindexes[i] == MSOGR_LABELDYINDEX)
        {
            if (hLabelStyle == NULL
                || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
                                                          OGRSTLabelDy,
                                                          &bDefault)) == NULL))
                values[i] = msStrdup("0");
            else
                values[i] = msStrdup(pszValue);

            if (layer->debug >= MS_DEBUGLEVEL_VVV)
                msDebug(MSOGR_LABELDYNAME " = \"%s\"\n", values[i]);
        }
        else if (itemindexes[i] == MSOGR_LABELPERPINDEX)
        {
            if (hLabelStyle == NULL
                || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
                                                          OGRSTLabelPerp,
                                                          &bDefault)) == NULL))
                values[i] = msStrdup("0");
            else
                values[i] = msStrdup(pszValue);

            if (layer->debug >= MS_DEBUGLEVEL_VVV)
                msDebug(MSOGR_LABELPERPNAME " = \"%s\"\n", values[i]);
        }
        else if (itemindexes[i] == MSOGR_LABELBOLDINDEX)
        {
            if (hLabelStyle == NULL
                || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
                                                          OGRSTLabelBold,
                                                          &bDefault)) == NULL))
                values[i] = msStrdup("0");
            else
                values[i] = msStrdup(pszValue);

            if (layer->debug >= MS_DEBUGLEVEL_VVV)
                msDebug(MSOGR_LABELBOLDNAME " = \"%s\"\n", values[i]);
        }
        else if (itemindexes[i] == MSOGR_LABELITALICINDEX)
        {
            if (hLabelStyle == NULL
                || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
                                                          OGRSTLabelItalic,
                                                          &bDefault)) == NULL))
                values[i] = msStrdup("0");
            else
                values[i] = msStrdup(pszValue);

            if (layer->debug >= MS_DEBUGLEVEL_VVV)
                msDebug(MSOGR_LABELITALICNAME " = \"%s\"\n", values[i]);
        }
        else if (itemindexes[i] == MSOGR_LABELUNDERLINEINDEX)
        {
            if (hLabelStyle == NULL
                || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
                                                          OGRSTLabelUnderline,
                                                          &bDefault)) == NULL))
                values[i] = msStrdup("0");
            else
                values[i] = msStrdup(pszValue);

            if (layer->debug >= MS_DEBUGLEVEL_VVV)
                msDebug(MSOGR_LABELUNDERLINENAME " = \"%s\"\n", values[i]);
        }
        else if (itemindexes[i] == MSOGR_LABELPRIORITYINDEX)
        {
            if (hLabelStyle == NULL
                || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
                                                          OGRSTLabelPriority,
                                                          &bDefault)) == NULL))
                values[i] = msStrdup("0");
            else
                values[i] = msStrdup(pszValue);

            if (layer->debug >= MS_DEBUGLEVEL_VVV)
                msDebug(MSOGR_LABELPRIORITYNAME " = \"%s\"\n", values[i]);
        }
        else if (itemindexes[i] == MSOGR_LABELSTRIKEOUTINDEX)
        {
            if (hLabelStyle == NULL
                || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
                                                          OGRSTLabelStrikeout,
                                                          &bDefault)) == NULL))
                values[i] = msStrdup("0");
            else
                values[i] = msStrdup(pszValue);

            if (layer->debug >= MS_DEBUGLEVEL_VVV)
                msDebug(MSOGR_LABELSTRIKEOUTNAME " = \"%s\"\n", values[i]);
        }
        else if (itemindexes[i] == MSOGR_LABELSTRETCHINDEX)
        {
            if (hLabelStyle == NULL
                || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
                                                          OGRSTLabelStretch,
                                                          &bDefault)) == NULL))
                values[i] = msStrdup("0");
            else
                values[i] = msStrdup(pszValue);

            if (layer->debug >= MS_DEBUGLEVEL_VVV)
                msDebug(MSOGR_LABELSTRETCHNAME " = \"%s\"\n", values[i]);
        }
        else if (itemindexes[i] == MSOGR_LABELADJHORINDEX)
        {
            if (hLabelStyle == NULL
                || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
                                                          OGRSTLabelAdjHor,
                                                          &bDefault)) == NULL))
                values[i] = msStrdup("");
            else
                values[i] = msStrdup(pszValue);

            if (layer->debug >= MS_DEBUGLEVEL_VVV)
                msDebug(MSOGR_LABELADJHORNAME " = \"%s\"\n", values[i]);
        }
        else if (itemindexes[i] == MSOGR_LABELADJVERTINDEX)
        {
            if (hLabelStyle == NULL
                || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
                                                          OGRSTLabelAdjVert,
                                                          &bDefault)) == NULL))
                values[i] = msStrdup("");
            else
                values[i] = msStrdup(pszValue);

            if (layer->debug >= MS_DEBUGLEVEL_VVV)
                msDebug(MSOGR_LABELADJVERTNAME " = \"%s\"\n", values[i]);
        }
        else if (itemindexes[i] == MSOGR_LABELHCOLORINDEX)
        {
            if (hLabelStyle == NULL
                || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
                                                          OGRSTLabelHColor,
                                                          &bDefault)) == NULL))
                values[i] = msStrdup("");
            else
                values[i] = msStrdup(pszValue);

            if (layer->debug >= MS_DEBUGLEVEL_VVV)
                msDebug(MSOGR_LABELHCOLORNAME " = \"%s\"\n", values[i]);
        }
#if GDAL_VERSION_NUM >= 1600
        else if (itemindexes[i] == MSOGR_LABELOCOLORINDEX)
        {
            if (hLabelStyle == NULL
                || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
                                                          OGRSTLabelOColor,
                                                          &bDefault)) == NULL))
                values[i] = msStrdup("");
            else
                values[i] = msStrdup(pszValue);

            if (layer->debug >= MS_DEBUGLEVEL_VVV)
                msDebug(MSOGR_LABELOCOLORNAME " = \"%s\"\n", values[i]);
        }
#endif /* GDAL_VERSION_NUM >= 1600 */
        else
        {
            msSetError(MS_OGRERR,"Invalid field index!?!","msOGRGetValues()");
            return(NULL);
        }
    }
  }

  OGR_SM_Destroy(hStyleMgr);
  OGR_ST_Destroy(hLabelStyle);

  return(values);
}

#endif /* USE_OGR */

#if defined(USE_OGR) || defined(USE_GDAL)

/**********************************************************************
* msOGRSpatialRef2ProjectionObj()
*
* Init a MapServer projectionObj using an OGRSpatialRef
* Works only with PROJECTION AUTO
*
* Returns MS_SUCCESS/MS_FAILURE
**********************************************************************/
static int msOGRSpatialRef2ProjectionObj(OGRSpatialReferenceH hSRS,
                                         projectionObj *proj, int debug_flag )
{
#ifdef USE_PROJ
  // First flush the "auto" name from the projargs[]...
  msFreeProjection( proj );

  if (hSRS == NULL || OSRIsLocal( hSRS ) )
  {
      // Dataset had no set projection or is NonEarth (LOCAL_CS)...
      // Nothing else to do. Leave proj empty and no reprojection will happen!
      return MS_SUCCESS;
  }

  // Export OGR SRS to a PROJ4 string
  char *pszProj = NULL;

  if (OSRExportToProj4( hSRS, &pszProj ) != OGRERR_NONE ||
      pszProj == NULL || strlen(pszProj) == 0)
  {
      msSetError(MS_OGRERR, "Conversion from OGR SRS to PROJ4 failed.",
                 "msOGRSpatialRef2ProjectionObj()");
      CPLFree(pszProj);
      return(MS_FAILURE);
  }

  if( debug_flag )
      msDebug( "AUTO = %s\n", pszProj );

  if( msLoadProjectionString( proj, pszProj ) != 0 )
      return MS_FAILURE;

  CPLFree(pszProj);
#endif

  return MS_SUCCESS;
}
#endif // defined(USE_OGR) || defined(USE_GDAL)

/**********************************************************************
* msOGCWKT2ProjectionObj()
*
* Init a MapServer projectionObj using an OGC WKT definition.
* Works only with PROJECTION AUTO
*
* Returns MS_SUCCESS/MS_FAILURE
**********************************************************************/

int msOGCWKT2ProjectionObj( const char *pszWKT,
                            projectionObj *proj,
                            int debug_flag )

{
#if defined(USE_OGR) || defined(USE_GDAL)

    OGRSpatialReferenceH hSRS;
    char *pszAltWKT = (char *) pszWKT;
    OGRErr eErr;
    int ms_result;

    hSRS = OSRNewSpatialReference( NULL );

    if( !EQUALN(pszWKT,"GEOGCS",6)
        && !EQUALN(pszWKT,"PROJCS",6)
        && !EQUALN(pszWKT,"LOCAL_CS",8) )
        eErr = OSRSetFromUserInput( hSRS, pszWKT );
    else
        eErr = OSRImportFromWkt( hSRS, &pszAltWKT );

    if( eErr != OGRERR_NONE )
    {
        OSRDestroySpatialReference( hSRS );
        msSetError(MS_OGRERR,
                   "Ingestion of WKT string '%s' failed.",
                   "msOGCWKT2ProjectionObj()",
                   pszWKT );
        return MS_FAILURE;
    }

    ms_result = msOGRSpatialRef2ProjectionObj( hSRS, proj, debug_flag );

    OSRDestroySpatialReference( hSRS );
    return ms_result;
#else
    msSetError(MS_OGRERR,
               "Not implemented since neither OGR nor GDAL is enabled.",
               "msOGCWKT2ProjectionObj()");
    return MS_FAILURE;
#endif
}

/**********************************************************************
* msOGRFileOpen()
*
* Open an OGR connection, and initialize a msOGRFileInfo.
**********************************************************************/

static int bOGRDriversRegistered = MS_FALSE;

void msOGRInitialize(void)

{
#ifdef USE_OGR
/* ------------------------------------------------------------------
* Register OGR Drivers, only once per execution
* ------------------------------------------------------------------ */
    if (!bOGRDriversRegistered)
    {
        ACQUIRE_OGR_LOCK;

        OGRRegisterAll();
        CPLPushErrorHandler( CPLQuietErrorHandler );

/* ------------------------------------------------------------------
* Pass config option GML_FIELDTYPES=ALWAYS_STRING to OGR so that all
* GML attributes are returned as strings to MapServer. This is most efficient
* and prevents problems with autodetection of some attribute types.
* ------------------------------------------------------------------ */
        CPLSetConfigOption("GML_FIELDTYPES","ALWAYS_STRING");

        bOGRDriversRegistered = MS_TRUE;
      
        RELEASE_OGR_LOCK;
    }
#endif /* USE_OGR */
}

/* ==================================================================
* The following functions closely relate to the API called from
* maplayer.c, but are intended to be used for the tileindex or direct
* layer access.
* ================================================================== */

#ifdef USE_OGR

/**********************************************************************
* msOGRFileOpen()
*
* Open an OGR connection, and initialize a msOGRFileInfo.
**********************************************************************/

static msOGRFileInfo *
msOGRFileOpen(layerObj *layer, const char *connection )

{
  char *conn_decrypted = NULL;

  msOGRInitialize();

/* ------------------------------------------------------------------
* Make sure any encrypted token in the connection string are decrypted
* ------------------------------------------------------------------ */
  if (connection)
  {
      conn_decrypted = msDecryptStringTokens(layer->map, connection);
      if (conn_decrypted == NULL)
          return NULL; /* An error should already have been reported */
  }

/* ------------------------------------------------------------------
* Parse connection string into dataset name, and layer name.
* ------------------------------------------------------------------ */
  char *pszDSName = NULL, *pszLayerDef = NULL;

  if( conn_decrypted == NULL )
  {
      /* we don't have anything */
  }
  else if( layer->data != NULL )
  {
      pszDSName = CPLStrdup(conn_decrypted);
      pszLayerDef = CPLStrdup(layer->data);
  }
  else
  {
      char **papszTokens = NULL;

      papszTokens = CSLTokenizeStringComplex( conn_decrypted, ",", TRUE, FALSE );

      if( CSLCount(papszTokens) > 0 )
          pszDSName = CPLStrdup( papszTokens[0] );
      if( CSLCount(papszTokens) > 1 )
          pszLayerDef = CPLStrdup( papszTokens[1] );

      CSLDestroy(papszTokens);
  }

  /* Get rid of decrypted connection string. We'll use the original (not
* decrypted) string for debug and error messages in the rest of the code.
*/
  msFree(conn_decrypted);
  conn_decrypted = NULL;

  if( pszDSName == NULL )
  {
      msSetError(MS_OGRERR,
                 "Error parsing OGR connection information in layer `%s'",
                 "msOGRFileOpen()",
                 layer->name?layer->name:"(null)" );
      return NULL;
  }

  if( pszLayerDef == NULL )
      pszLayerDef = CPLStrdup("0");

/* -------------------------------------------------------------------- */
/* Can we get an existing connection for this layer? */
/* -------------------------------------------------------------------- */
  OGRDataSourceH hDS;

  hDS = (OGRDataSourceH) msConnPoolRequest( layer );

/* -------------------------------------------------------------------- */
/* If not, open now, and register this connection with the */
/* pool. */
/* -------------------------------------------------------------------- */
  if( hDS == NULL )
  {
      char szPath[MS_MAXPATHLEN] = "";
      const char *pszDSSelectedName = pszDSName;
      
      if( layer->debug )
          msDebug("msOGRFileOpen(%s)...\n", connection);
      
      CPLErrorReset();
      if (msTryBuildPath3(szPath, layer->map->mappath,
                          layer->map->shapepath, pszDSName) != NULL ||
          msTryBuildPath(szPath, layer->map->mappath, pszDSName) != NULL)
      {
          /* Use relative path */
          pszDSSelectedName = szPath;
      }
      
      if( layer->debug )
          msDebug("OGROPen(%s)\n", pszDSSelectedName);

      ACQUIRE_OGR_LOCK;
      hDS = OGROpen( pszDSSelectedName, MS_FALSE, NULL );
      RELEASE_OGR_LOCK;
      
      if( hDS == NULL )
      {
          if( strlen(CPLGetLastErrorMsg()) == 0 )
              msSetError(MS_OGRERR,
                         "Open failed for OGR connection in layer `%s'. "
                         "File not found or unsupported format.",
                         "msOGRFileOpen()",
                         layer->name?layer->name:"(null)" );
          else
              msSetError(MS_OGRERR,
                         "Open failed for OGR connection in layer `%s'.\n%s\n",
                         "msOGRFileOpen()",
                         layer->name?layer->name:"(null)",
                         CPLGetLastErrorMsg() );
          CPLFree( pszDSName );
          CPLFree( pszLayerDef );
          return NULL;
      }

      msConnPoolRegister( layer, hDS, msOGRCloseConnection );
  }
      
  CPLFree( pszDSName );
  pszDSName = NULL;

/* ------------------------------------------------------------------
* Find the layer selected.
* ------------------------------------------------------------------ */
  
  int nLayerIndex = 0;
  OGRLayerH hLayer = NULL;

  int iLayer;

  if( EQUALN(pszLayerDef,"SELECT ",7) )
  {
      ACQUIRE_OGR_LOCK;
      hLayer = OGR_DS_ExecuteSQL( hDS, pszLayerDef, NULL, NULL );
      if( hLayer == NULL )
      {
          msSetError(MS_OGRERR,
                     "ExecuteSQL(%s) failed.\n%s",
                     "msOGRFileOpen()",
                     pszLayerDef, CPLGetLastErrorMsg() );
          RELEASE_OGR_LOCK;
          msConnPoolRelease( layer, hDS );
          CPLFree( pszLayerDef );
          return NULL;
      }
      RELEASE_OGR_LOCK;
      nLayerIndex = -1;
  }

  for( iLayer = 0; hLayer == NULL && iLayer < OGR_DS_GetLayerCount(hDS); iLayer++ )
  {
      hLayer = OGR_DS_GetLayer( hDS, iLayer );
      if( hLayer != NULL
#if GDAL_VERSION_NUM >= 1800
          && EQUAL(OGR_L_GetName(hLayer),pszLayerDef) )
#else
          && EQUAL(OGR_FD_GetName( OGR_L_GetLayerDefn(hLayer) ),pszLayerDef) )
#endif
      {
          nLayerIndex = iLayer;
          break;
      }
      else
          hLayer = NULL;
  }
  
  if( hLayer == NULL && (atoi(pszLayerDef) > 0 || EQUAL(pszLayerDef,"0")) )
  {
      nLayerIndex = atoi(pszLayerDef);
      if( nLayerIndex < OGR_DS_GetLayerCount(hDS) )
          hLayer = OGR_DS_GetLayer( hDS, nLayerIndex );
  }

  if (hLayer == NULL)
  {
      msSetError(MS_OGRERR, "GetLayer(%s) failed for OGR connection `%s'.",
                 "msOGRFileOpen()",
                 pszLayerDef, connection );
      CPLFree( pszLayerDef );
      msConnPoolRelease( layer, hDS );
      return NULL;
  }

  CPLFree( pszLayerDef );

/* ------------------------------------------------------------------
* OK... open succeded... alloc and fill msOGRFileInfo inside layer obj
* ------------------------------------------------------------------ */
  msOGRFileInfo *psInfo =(msOGRFileInfo*)CPLCalloc(1,sizeof(msOGRFileInfo));

  psInfo->pszFname = CPLStrdup(OGR_DS_GetName( hDS ));
  psInfo->nLayerIndex = nLayerIndex;
  psInfo->hDS = hDS;
  psInfo->hLayer = hLayer;

  psInfo->nTileId = 0;
  psInfo->poCurTile = NULL;
  psInfo->rect.minx = psInfo->rect.maxx = 0;
  psInfo->rect.miny = psInfo->rect.maxy = 0;
  psInfo->last_record_index_read = -1;

  return psInfo;
}

/************************************************************************/
/* msOGRCloseConnection() */
/* */
/* Callback for thread pool to actually release an OGR */
/* connection. */
/************************************************************************/

static void msOGRCloseConnection( void *conn_handle )

{
    OGRDataSourceH hDS = (OGRDataSourceH) conn_handle;

    ACQUIRE_OGR_LOCK;
    OGR_DS_Destroy( hDS );
    RELEASE_OGR_LOCK;
}

/**********************************************************************
* msOGRFileClose()
**********************************************************************/
static int msOGRFileClose(layerObj *layer, msOGRFileInfo *psInfo )
{
  if (!psInfo)
      return MS_SUCCESS;

  if( layer->debug )
      msDebug("msOGRFileClose(%s,%d).\n",
              psInfo->pszFname, psInfo->nLayerIndex);

  CPLFree(psInfo->pszFname);

  ACQUIRE_OGR_LOCK;
  if (psInfo->hLastFeature)
      OGR_F_Destroy( psInfo->hLastFeature );

  /* If nLayerIndex == -1 then the layer is an SQL result ... free it */
  if( psInfo->nLayerIndex == -1 )
      OGR_DS_ReleaseResultSet( psInfo->hDS, psInfo->hLayer );

  // Release (potentially close) the datasource connection.
  // Make sure we aren't holding the lock when the callback may need it.
  RELEASE_OGR_LOCK;
  msConnPoolRelease( layer, psInfo->hDS );
  ACQUIRE_OGR_LOCK;

  // Free current tile if there is one.
  if( psInfo->poCurTile != NULL )
      msOGRFileClose( layer, psInfo->poCurTile );

  CPLFree(psInfo);

  RELEASE_OGR_LOCK;

  return MS_SUCCESS;
}

/**********************************************************************
* msOGRFileWhichShapes()
*
* Init OGR layer structs ready for calls to msOGRFileNextShape().
*
* Returns MS_SUCCESS/MS_FAILURE, or MS_DONE if no shape matching the
* layer's FILTER overlaps the selected region.
**********************************************************************/
static int msOGRFileWhichShapes(layerObj *layer, rectObj rect,
                                msOGRFileInfo *psInfo )
{
  if (psInfo == NULL || psInfo->hLayer == NULL)
  {
    msSetError(MS_MISCERR, "Assertion failed: OGR layer not opened!!!",
               "msOGRFileWhichShapes()");
    return(MS_FAILURE);
  }

/* ------------------------------------------------------------------
* Set Spatial filter... this may result in no features being returned
* if layer does not overlap current view.
*
* __TODO__ We should return MS_DONE if no shape overlaps the selected
* region and matches the layer's FILTER expression, but there is currently
* no _efficient_ way to do that with OGR.
* ------------------------------------------------------------------ */
  ACQUIRE_OGR_LOCK;

  OGRGeometryH hSpatialFilterPolygon = OGR_G_CreateGeometry( wkbPolygon );
  OGRGeometryH hRing = OGR_G_CreateGeometry( wkbLinearRing );

  OGR_G_AddPoint_2D( hRing, rect.minx, rect.miny);
  OGR_G_AddPoint_2D( hRing, rect.maxx, rect.miny);
  OGR_G_AddPoint_2D( hRing, rect.maxx, rect.maxy);
  OGR_G_AddPoint_2D( hRing, rect.minx, rect.maxy);
  OGR_G_AddPoint_2D( hRing, rect.minx, rect.miny);

  OGR_G_AddGeometryDirectly( hSpatialFilterPolygon, hRing );

  OGR_L_SetSpatialFilter( psInfo->hLayer, hSpatialFilterPolygon );

  OGR_G_DestroyGeometry( hSpatialFilterPolygon );

  psInfo->rect = rect;

  if (layer->debug >= MS_DEBUGLEVEL_VVV)
      msDebug("msOGRFileWhichShapes: Setting spatial filter to %f %f %f %f\n",
              rect.minx, rect.miny, rect.maxx, rect.maxy );

/* ------------------------------------------------------------------
* Apply an attribute filter if we have one prefixed with a WHERE
* keyword in the filter string. Otherwise, ensure the attribute
* filter is clear.
* ------------------------------------------------------------------ */
  if( layer->filter.string && EQUALN(layer->filter.string,"WHERE ",6) )
  {
      CPLErrorReset();
      if( OGR_L_SetAttributeFilter( psInfo->hLayer, layer->filter.string+6 )
          != OGRERR_NONE )
      {
          msSetError(MS_OGRERR,
                     "SetAttributeFilter(%s) failed on layer %s.\n%s",
                     "msOGRFileWhichShapes()",
                     layer->filter.string+6, layer->name?layer->name:"(null)",
                     CPLGetLastErrorMsg() );
          RELEASE_OGR_LOCK;
          return MS_FAILURE;
      }
  }
  else
      OGR_L_SetAttributeFilter( psInfo->hLayer, NULL );

/* ------------------------------------------------------------------
* Reset current feature pointer
* ------------------------------------------------------------------ */
  OGR_L_ResetReading( psInfo->hLayer );
  psInfo->last_record_index_read = -1;

  RELEASE_OGR_LOCK;

  return MS_SUCCESS;
}

/**********************************************************************
* msOGRPassThroughFieldDefinitions()
*
* 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
msOGRPassThroughFieldDefinitions( layerObj *layer, msOGRFileInfo *psInfo )

{
    OGRFeatureDefnH hDefn = OGR_L_GetLayerDefn( psInfo->hLayer );
    int numitems, i;
  
    numitems = OGR_FD_GetFieldCount( hDefn );

    for(i=0;i<numitems;i++)
    {
        OGRFieldDefnH hField = OGR_FD_GetFieldDefn( hDefn, i );
        char md_item_name[256];
        char gml_width[32], gml_precision[32];
        const char *gml_type = NULL;
        const char *item = OGR_Fld_GetNameRef( hField );

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

        switch( OGR_Fld_GetType( hField ) )
        {
          case OFTInteger:
            gml_type = "Integer";
            if( OGR_Fld_GetWidth( hField) > 0 )
                sprintf( gml_width, "%d", OGR_Fld_GetWidth( hField) );
            break;

          case OFTReal:
            gml_type = "Real";
            if( OGR_Fld_GetWidth( hField) > 0 )
                sprintf( gml_width, "%d", OGR_Fld_GetWidth( hField) );
            if( OGR_Fld_GetPrecision( hField ) > 0 )
                sprintf( gml_precision, "%d", OGR_Fld_GetPrecision( hField) );
            break;

          case OFTString:
            gml_type = "Character";
            if( OGR_Fld_GetWidth( hField) > 0 )
                sprintf( gml_width, "%d", OGR_Fld_GetWidth( hField) );
            break;

          case OFTDate:
          case OFTTime:
          case OFTDateTime:
            gml_type = "Date";
            break;

          default:
            gml_type = "Character";
            break;
        }

        snprintf( md_item_name, sizeof(md_item_name), "gml_%s_type", item );
        if( msOWSLookupMetadata(&(layer->metadata), "G", "type") == NULL )
            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") == NULL )
            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")==NULL )
            msInsertHashTable(&(layer->metadata), md_item_name, gml_precision );
    }

    /* Should we try to address style items, or other special items? */
}

/**********************************************************************
* msOGRFileGetItems()
*
* Returns a list of field names in a NULL terminated list of strings.
**********************************************************************/
static char **msOGRFileGetItems(layerObj *layer, msOGRFileInfo *psInfo )
{
  OGRFeatureDefnH hDefn;
  int i, numitems,totalnumitems;
  int numStyleItems = MSOGR_LABELNUMITEMS;
  char **items;
  const char *getShapeStyleItems, *value;

  if((hDefn = OGR_L_GetLayerDefn( psInfo->hLayer )) == NULL)
  {
    msSetError(MS_OGRERR,
               "OGR Connection for layer `%s' contains no field definition.",
               "msOGRFileGetItems()",
               layer->name?layer->name:"(null)" );
    return NULL;
  }

  totalnumitems = numitems = OGR_FD_GetFieldCount( hDefn );

  getShapeStyleItems = msLayerGetProcessingKey( layer, "GETSHAPE_STYLE_ITEMS" );
  if (getShapeStyleItems && EQUAL(getShapeStyleItems, "all"))
      totalnumitems += numStyleItems;

  if((items = (char**)malloc(sizeof(char *)*(totalnumitems+1))) == NULL)
  {
    msSetError(MS_MEMERR, NULL, "msOGRFileGetItems()");
    return NULL;
  }

  for(i=0;i<numitems;i++)
  {
      OGRFieldDefnH hField = OGR_FD_GetFieldDefn( hDefn, i );
      items[i] = msStrdup( OGR_Fld_GetNameRef( hField ));
  }

  if (getShapeStyleItems && EQUAL(getShapeStyleItems, "all"))
  {
      assert(numStyleItems == 21);
      items[i++] = msStrdup( MSOGR_LABELFONTNAMENAME );
      items[i++] = msStrdup( MSOGR_LABELSIZENAME );
      items[i++] = msStrdup( MSOGR_LABELTEXTNAME );
      items[i++] = msStrdup( MSOGR_LABELANGLENAME );
      items[i++] = msStrdup( MSOGR_LABELFCOLORNAME );
      items[i++] = msStrdup( MSOGR_LABELBCOLORNAME );
      items[i++] = msStrdup( MSOGR_LABELPLACEMENTNAME );
      items[i++] = msStrdup( MSOGR_LABELANCHORNAME );
      items[i++] = msStrdup( MSOGR_LABELDXNAME );
      items[i++] = msStrdup( MSOGR_LABELDYNAME );
      items[i++] = msStrdup( MSOGR_LABELPERPNAME );
      items[i++] = msStrdup( MSOGR_LABELBOLDNAME );
      items[i++] = msStrdup( MSOGR_LABELITALICNAME );
      items[i++] = msStrdup( MSOGR_LABELUNDERLINENAME );
      items[i++] = msStrdup( MSOGR_LABELPRIORITYNAME );
      items[i++] = msStrdup( MSOGR_LABELSTRIKEOUTNAME );
      items[i++] = msStrdup( MSOGR_LABELSTRETCHNAME );
      items[i++] = msStrdup( MSOGR_LABELADJHORNAME );
      items[i++] = msStrdup( MSOGR_LABELADJVERTNAME );
      items[i++] = msStrdup( MSOGR_LABELHCOLORNAME );
      items[i++] = msStrdup( MSOGR_LABELOCOLORNAME );
  }
  items[i++] = NULL;

/* -------------------------------------------------------------------- */
/* consider populating the field definitions in metadata. */
/* -------------------------------------------------------------------- */
  if((value = msOWSLookupMetadata(&(layer->metadata), "G", "types")) != NULL
     && strcasecmp(value,"auto") == 0 )
      msOGRPassThroughFieldDefinitions( layer, psInfo );

  return items;
}

/**********************************************************************
* msOGRFileNextShape()
*
* Returns shape sequentially from OGR data source.
* msOGRLayerWhichShape() must have been called first.
*
* Returns MS_SUCCESS/MS_FAILURE
**********************************************************************/
static int
msOGRFileNextShape(layerObj *layer, shapeObj *shape,
                   msOGRFileInfo *psInfo )
{
  OGRFeatureH hFeature = NULL;

  if (psInfo == NULL || psInfo->hLayer == NULL)
  {
    msSetError(MS_MISCERR, "Assertion failed: OGR layer not opened!!!",
               "msOGRFileNextShape()");
    return(MS_FAILURE);
  }

/* ------------------------------------------------------------------
* Read until we find a feature that matches attribute filter and
* whose geometry is compatible with current layer type.
* ------------------------------------------------------------------ */
  msFreeShape(shape);
  shape->type = MS_SHAPE_NULL;

  ACQUIRE_OGR_LOCK;
  while (shape->type == MS_SHAPE_NULL)
  {
      if( hFeature )
          OGR_F_Destroy( hFeature );

      if( (hFeature = OGR_L_GetNextFeature( psInfo->hLayer )) == NULL )
      {
          psInfo->last_record_index_read = -1;
          if( CPLGetLastErrorType() == CE_Failure )
          {
              msSetError(MS_OGRERR, "%s", "msOGRFileNextShape()",
                         CPLGetLastErrorMsg() );
              RELEASE_OGR_LOCK;
              return MS_FAILURE;
          }
          else
          {
              RELEASE_OGR_LOCK;
              if (layer->debug >= MS_DEBUGLEVEL_VV)
                  msDebug("msOGRFileNextShape: Returning MS_DONE (no more shapes)\n" );
              return MS_DONE; // No more features to read
          }
      }

      psInfo->last_record_index_read++;

      if(layer->numitems > 0)
      {
          shape->values = msOGRGetValues(layer, hFeature);
          shape->numvalues = layer->numitems;
          if(!shape->values)
          {
              OGR_F_Destroy( hFeature );
              RELEASE_OGR_LOCK;
              return(MS_FAILURE);
          }
      }

      // Check the expression unless it is a WHERE clause already
      // handled by OGR.
      if( (layer->filter.string && EQUALN(layer->filter.string,"WHERE ",6))
          || msEvalExpression(layer, shape, &(layer->filter), layer->filteritemindex) == MS_TRUE )
      {
          // Feature matched filter expression... process geometry
          // shape->type will be set if geom is compatible with layer type
          if (ogrConvertGeometry(OGR_F_GetGeometryRef( hFeature ), shape,
                                 layer->type) == MS_SUCCESS)
          {
              if (shape->type != MS_SHAPE_NULL)
                  break; // Shape is ready to be returned!

              if (layer->debug >= MS_DEBUGLEVEL_VVV)
                  msDebug("msOGRFileNextShape: Rejecting feature (shapeid = %d, tileid=%d) of incompatible type for this layer (feature wkbType %d, layer type %d)\n",
                          OGR_F_GetFID( hFeature ), psInfo->nTileId,
                          OGR_F_GetGeometryRef( hFeature )==NULL ? wkbFlatten(wkbUnknown):wkbFlatten( OGR_G_GetGeometryType( OGR_F_GetGeometryRef( hFeature ) ) ),
                          layer->type);

          }
          else
          {
              msFreeShape(shape);
              OGR_F_Destroy( hFeature );
              RELEASE_OGR_LOCK;
              return MS_FAILURE; // Error message already produced.
          }
      }

      // Feature rejected... free shape to clear attributes values.
      msFreeShape(shape);
      shape->type = MS_SHAPE_NULL;
  }

  shape->index = OGR_F_GetFID( hFeature );;
  shape->resultindex = psInfo->last_record_index_read;
  shape->tileindex = psInfo->nTileId;

  if (layer->debug >= MS_DEBUGLEVEL_VVV)
      msDebug("msOGRFileNextShape: Returning shape=%d, tile=%d\n",
              shape->index, shape->tileindex );

  // Keep ref. to last feature read in case we need style info.
  if (psInfo->hLastFeature)
      OGR_F_Destroy( psInfo->hLastFeature );
  psInfo->hLastFeature = hFeature;

  RELEASE_OGR_LOCK;

  return MS_SUCCESS;
}

/**********************************************************************
* msOGRFileGetShape()
*
* Returns shape from OGR data source by id.
*
* Returns MS_SUCCESS/MS_FAILURE
**********************************************************************/
static int
msOGRFileGetShape(layerObj *layer, shapeObj *shape, long record,
                  msOGRFileInfo *psInfo, int record_is_fid )
{
  OGRFeatureH hFeature;

  if (psInfo == NULL || psInfo->hLayer == NULL)
  {
    msSetError(MS_MISCERR, "Assertion failed: OGR layer not opened!!!",
               "msOGRFileNextShape()");
    return(MS_FAILURE);
  }

/* -------------------------------------------------------------------- */
/* Clear previously loaded shape. */
/* -------------------------------------------------------------------- */
  msFreeShape(shape);
  shape->type = MS_SHAPE_NULL;

/* -------------------------------------------------------------------- */
/* Support reading feature by fid. */
/* -------------------------------------------------------------------- */
  if( record_is_fid )
  {
      ACQUIRE_OGR_LOCK;
      if( (hFeature = OGR_L_GetFeature( psInfo->hLayer, record )) == NULL )
      {
          RELEASE_OGR_LOCK;
          return MS_FAILURE;
      }
  }

/* -------------------------------------------------------------------- */
/* Support reading shape by offset within the current */
/* resultset. */
/* -------------------------------------------------------------------- */
  else if( !record_is_fid )
  {
      ACQUIRE_OGR_LOCK;
      if( record <= psInfo->last_record_index_read
          || psInfo->last_record_index_read == -1 )
      {
          OGR_L_ResetReading( psInfo->hLayer );
          psInfo->last_record_index_read = -1;
      }

      hFeature = NULL;
      while( psInfo->last_record_index_read < record )
      {
          if( hFeature != NULL )
          {
              OGR_F_Destroy( hFeature );
              hFeature = NULL;
          }
          if( (hFeature = OGR_L_GetNextFeature( psInfo->hLayer )) == NULL )
          {
              RELEASE_OGR_LOCK;
              return MS_FAILURE;
          }
          psInfo->last_record_index_read++;
      }
  }

/* ------------------------------------------------------------------
* Handle shape geometry...
* ------------------------------------------------------------------ */
  // shape->type will be set if geom is compatible with layer type
  if (ogrConvertGeometry(OGR_F_GetGeometryRef( hFeature ), shape,
                         layer->type) != MS_SUCCESS)
  {
      RELEASE_OGR_LOCK;
      return MS_FAILURE; // Error message already produced.
  }
  
  if (shape->type == MS_SHAPE_NULL)
  {
      msSetError(MS_OGRERR,
                 "Requested feature is incompatible with layer type",
                 "msOGRLayerGetShape()");
      RELEASE_OGR_LOCK;
      return MS_FAILURE;
  }

/* ------------------------------------------------------------------
* Process shape attributes
* ------------------------------------------------------------------ */
  if(layer->numitems > 0)
  {
      shape->values = msOGRGetValues(layer, hFeature);
      shape->numvalues = layer->numitems;
      if(!shape->values)
      {
          RELEASE_OGR_LOCK;
          return(MS_FAILURE);
      }

  }

  if (record_is_fid)
  {
      shape->index = record;
      shape->resultindex = -1;
  }
  else
  {
      shape->index = OGR_F_GetFID( hFeature );
      shape->resultindex = record;
  }

  shape->tileindex = psInfo->nTileId;

  // Keep ref. to last feature read in case we need style info.
  if (psInfo->hLastFeature)
      OGR_F_Destroy( psInfo->hLastFeature );
  psInfo->hLastFeature = hFeature;

  RELEASE_OGR_LOCK;

  return MS_SUCCESS;
}

/************************************************************************/
/* msOGRFileReadTile() */
/* */
/* Advance to the next tile (or if targetTile is not -1 advance */
/* to that tile), causing the tile to become the poCurTile in */
/* the tileindexes psInfo structure. Returns MS_DONE if there */
/* are no more available tiles. */
/* */
/* Newly loaded tiles are automatically "WhichShaped" based on */
/* the current rectangle. */
/************************************************************************/

int msOGRFileReadTile( layerObj *layer, msOGRFileInfo *psInfo,
                       int targetTile = -1 )

{
    int nFeatureId;

/* -------------------------------------------------------------------- */
/* Close old tile if one is open. */
/* -------------------------------------------------------------------- */
    if( psInfo->poCurTile != NULL )
    {
        msOGRFileClose( layer, psInfo->poCurTile );
        psInfo->poCurTile = NULL;
    }

/* -------------------------------------------------------------------- */
/* If -2 is passed, then seek reset reading of the tileindex. */
/* We want to start from the beginning even if this file is */
/* shared between layers or renders. */
/* -------------------------------------------------------------------- */
    ACQUIRE_OGR_LOCK;
    if( targetTile == -2 )
    {
        OGR_L_ResetReading( psInfo->hLayer );
    }
        
/* -------------------------------------------------------------------- */
/* Get the name (connection string really) of the next tile. */
/* -------------------------------------------------------------------- */
    OGRFeatureH hFeature;
    char *connection = NULL;
    msOGRFileInfo *psTileInfo = NULL;
    int status;

#ifndef IGNORE_MISSING_DATA
  NextFile:
#endif

    if( targetTile < 0 )
        hFeature = OGR_L_GetNextFeature( psInfo->hLayer );
    
    else
        hFeature = OGR_L_GetFeature( psInfo->hLayer, targetTile );

    if( hFeature == NULL )
    {
        RELEASE_OGR_LOCK;
        if( targetTile == -1 )
            return MS_DONE;
        else
            return MS_FAILURE;
        
    }

    connection = msStrdup( OGR_F_GetFieldAsString( hFeature,
                                                 layer->tileitemindex ));
    
    nFeatureId = OGR_F_GetFID( hFeature );

    OGR_F_Destroy( hFeature );
                        
    RELEASE_OGR_LOCK;

/* -------------------------------------------------------------------- */
/* Open the new tile file. */
/* -------------------------------------------------------------------- */
    psTileInfo = msOGRFileOpen( layer, connection );

    free( connection );

#ifndef IGNORE_MISSING_DATA
    if( psTileInfo == NULL && targetTile == -1 )
        goto NextFile;
#endif

    if( psTileInfo == NULL )
        return MS_FAILURE;

    psTileInfo->nTileId = nFeatureId;

/* -------------------------------------------------------------------- */
/* Initialize the spatial query on this file. */
/* -------------------------------------------------------------------- */
    if( psInfo->rect.minx != 0 || psInfo->rect.maxx != 0 )
    {
        status = msOGRFileWhichShapes( layer, psInfo->rect, psTileInfo );
        if( status != MS_SUCCESS )
            return status;
    }
    
    psInfo->poCurTile = psTileInfo;
    
/* -------------------------------------------------------------------- */
/* Update the iteminfo in case this layer has a different field */
/* list. */
/* -------------------------------------------------------------------- */
    msOGRLayerInitItemInfo( layer );

    return MS_SUCCESS;
}

#endif /* def USE_OGR */

/* ==================================================================
* Here comes the REAL stuff... the functions below are called by maplayer.c
* ================================================================== */

/**********************************************************************
* msOGRLayerOpen()
*
* Open OGR data source for the specified map layer.
*
* If pszOverrideConnection != NULL then this value is used as the connection
* string instead of lp->connection. This is used for instance to open
* a WFS layer, in this case lp->connection is the WFS url, but we want
* OGR to open the local file on disk that was previously downloaded.
*
* An OGR connection string is: <dataset_filename>[,<layer_index>]
* <dataset_filename> is file format specific
* <layer_index> (optional) is the OGR layer index
* default is 0, the first layer.
*
* One can use the "ogrinfo" program to find out the layer indices in a dataset
*
* Returns MS_SUCCESS/MS_FAILURE
**********************************************************************/
int msOGRLayerOpen(layerObj *layer, const char *pszOverrideConnection)
{
#ifdef USE_OGR

  msOGRFileInfo *psInfo;

  if (layer->layerinfo != NULL)
  {
      return MS_SUCCESS; // Nothing to do... layer is already opened
  }

/* -------------------------------------------------------------------- */
/* If this is not a tiled layer, just directly open the target. */
/* -------------------------------------------------------------------- */
  if( layer->tileindex == NULL )
  {
      psInfo = msOGRFileOpen( layer,
                              (pszOverrideConnection ? pszOverrideConnection:
                                                       layer->connection) );
      layer->layerinfo = psInfo;
      layer->tileitemindex = -1;
      
      if( layer->layerinfo == NULL )
          return MS_FAILURE;
  }

/* -------------------------------------------------------------------- */
/* Otherwise we open the tile index, identify the tile item */
/* index and try to select the first file matching our query */
/* region. */
/* -------------------------------------------------------------------- */
  else
  {
      // Open tile index

      psInfo = msOGRFileOpen( layer, layer->tileindex );
      layer->layerinfo = psInfo;
      
      if( layer->layerinfo == NULL )
          return MS_FAILURE;

      // Identify TILEITEM

      OGRFeatureDefnH hDefn = OGR_L_GetLayerDefn( psInfo->hLayer );
      for( layer->tileitemindex = 0;
           layer->tileitemindex < OGR_FD_GetFieldCount( hDefn )
           && !EQUAL( OGR_Fld_GetNameRef( OGR_FD_GetFieldDefn( hDefn, layer->tileitemindex) ),
                      layer->tileitem);
           layer->tileitemindex++ ) {}

      if( layer->tileitemindex == OGR_FD_GetFieldCount( hDefn ) )
      {
          msSetError(MS_OGRERR,
                     "Can't identify TILEITEM %s field in TILEINDEX `%s'.",
                     "msOGRLayerOpen()",
                     layer->tileitem, layer->tileindex );
          msOGRFileClose( layer, psInfo );
          layer->layerinfo = NULL;
          return MS_FAILURE;
      }
  }

/* ------------------------------------------------------------------
* If projection was "auto" then set proj to the dataset's projection.
* For a tile index, it is assume the tile index has the projection.
* ------------------------------------------------------------------ */
#ifdef USE_PROJ
  if (layer->projection.numargs > 0 &&
      EQUAL(layer->projection.args[0], "auto"))
  {
      ACQUIRE_OGR_LOCK;
      OGRSpatialReferenceH hSRS = OGR_L_GetSpatialRef( psInfo->hLayer );

      if (msOGRSpatialRef2ProjectionObj(hSRS,
                                        &(layer->projection),
                                        layer->debug ) != MS_SUCCESS)
      {
          errorObj *ms_error = msGetErrorObj();

          RELEASE_OGR_LOCK;
          msSetError(MS_OGRERR,
                     "%s "
                     "PROJECTION AUTO cannot be used for this "
                     "OGR connection (in layer `%s').",
                     "msOGRLayerOpen()",
                     ms_error->message,
                     layer->name?layer->name:"(null)" );
          msOGRFileClose( layer, psInfo );
          layer->layerinfo = NULL;
          return(MS_FAILURE);
      }
      RELEASE_OGR_LOCK;
  }
#endif

  return MS_SUCCESS;

#else
/* ------------------------------------------------------------------
* OGR Support not included...
* ------------------------------------------------------------------ */

  msSetError(MS_MISCERR, "OGR support is not available.", "msOGRLayerOpen()");
  return(MS_FAILURE);

#endif /* USE_OGR */
}

/**********************************************************************
* msOGRLayerOpenVT()
*
* Overloaded version of msOGRLayerOpen for virtual table architecture
**********************************************************************/
static int msOGRLayerOpenVT(layerObj *layer)
{
    return msOGRLayerOpen(layer, NULL);
}

/**********************************************************************
* msOGRLayerClose()
**********************************************************************/
int msOGRLayerClose(layerObj *layer)
{
#ifdef USE_OGR
  msOGRFileInfo *psInfo =(msOGRFileInfo*)layer->layerinfo;

  if (psInfo)
  {
      if( layer->debug )
          msDebug("msOGRLayerClose(%s).\n", layer->connection);

      msOGRFileClose( layer, psInfo );
      layer->layerinfo = NULL;
  }

  return MS_SUCCESS;

#else
/* ------------------------------------------------------------------
* OGR Support not included...
* ------------------------------------------------------------------ */

  msSetError(MS_MISCERR, "OGR support is not available.", "msOGRLayerClose()");
  return(MS_FAILURE);

#endif /* USE_OGR */
}

/**********************************************************************
* msOGRLayerIsOpen()
**********************************************************************/
static int msOGRLayerIsOpen(layerObj *layer)
{
#ifdef USE_OGR
  if (layer->layerinfo)
      return MS_TRUE;

  return MS_FALSE;

#else
/* ------------------------------------------------------------------
* OGR Support not included...
* ------------------------------------------------------------------ */

  msSetError(MS_MISCERR, "OGR support is not available.", "msOGRLayerIsOpen()");
  return(MS_FALSE);

#endif /* USE_OGR */
}

/**********************************************************************
* msOGRLayerWhichShapes()
*
* Init OGR layer structs ready for calls to msOGRLayerNextShape().
*
* Returns MS_SUCCESS/MS_FAILURE, or MS_DONE if no shape matching the
* layer's FILTER overlaps the selected region.
**********************************************************************/
int msOGRLayerWhichShapes(layerObj *layer, rectObj rect, int isQuery)
{
#ifdef USE_OGR
  msOGRFileInfo *psInfo =(msOGRFileInfo*)layer->layerinfo;
  int status;

  if (psInfo == NULL || psInfo->hLayer == NULL)
  {
    msSetError(MS_MISCERR, "Assertion failed: OGR layer not opened!!!",
               "msOGRLayerWhichShapes()");
    return(MS_FAILURE);
  }

  status = msOGRFileWhichShapes( layer, rect, psInfo );

  if( status != MS_SUCCESS || layer->tileindex == NULL )
      return status;

  // If we are using a tile index, we need to advance to the first
  // tile matching the spatial query, and load it.

  return msOGRFileReadTile( layer, psInfo );

#else
/* ------------------------------------------------------------------
* OGR Support not included...
* ------------------------------------------------------------------ */

  msSetError(MS_MISCERR, "OGR support is not available.",
             "msOGRLayerWhichShapes()");
  return(MS_FAILURE);

#endif /* USE_OGR */
}

/**********************************************************************
* msOGRLayerGetItems()
*
* Load item (i.e. field) names in a char array. If we are working
* with a tiled layer, ensure a tile is loaded and use it for the items.
* It is implicitly assumed that the schemas will match on all tiles.
**********************************************************************/
int msOGRLayerGetItems(layerObj *layer)
{
#ifdef USE_OGR
  msOGRFileInfo *psInfo =(msOGRFileInfo*)layer->layerinfo;
  
  if (psInfo == NULL || psInfo->hLayer == NULL)
  {
    msSetError(MS_MISCERR, "Assertion failed: OGR layer not opened!!!",
               "msOGRLayerGetItems()");
    return(MS_FAILURE);
  }

  if( layer->tileindex != NULL )
  {
      if( psInfo->poCurTile == NULL
          && msOGRFileReadTile( layer, psInfo ) != MS_SUCCESS )
          return MS_FAILURE;
      
      psInfo = psInfo->poCurTile;
  }

  layer->numitems = 0;
  layer->items = msOGRFileGetItems(layer, psInfo);
  if( layer->items == NULL )
      return MS_FAILURE;

  while( layer->items[layer->numitems] != NULL )
      layer->numitems++;

  return msOGRLayerInitItemInfo(layer);

#else
/* ------------------------------------------------------------------
* OGR Support not included...
* ------------------------------------------------------------------ */

  msSetError(MS_MISCERR, "OGR support is not available.",
             "msOGRLayerGetItems()");
  return(MS_FAILURE);

#endif /* USE_OGR */
}

/**********************************************************************
* msOGRLayerInitItemInfo()
*
* Init the itemindexes array after items[] has been reset in a layer.
**********************************************************************/
static int msOGRLayerInitItemInfo(layerObj *layer)
{
#ifdef USE_OGR
  msOGRFileInfo *psInfo =(msOGRFileInfo*)layer->layerinfo;
  int i;
  OGRFeatureDefnH hDefn;

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

  if( layer->tileindex != NULL )
  {
      if( psInfo->poCurTile == NULL
          && msOGRFileReadTile( layer, psInfo, -2 ) != MS_SUCCESS )
          return MS_FAILURE;
      
      psInfo = psInfo->poCurTile;
  }

  if (psInfo == NULL || psInfo->hLayer == NULL)
  {
      msSetError(MS_MISCERR, "Assertion failed: OGR layer not opened!!!",
                 "msOGRLayerInitItemInfo()");
      return(MS_FAILURE);
  }

  if((hDefn = OGR_L_GetLayerDefn( psInfo->hLayer )) == NULL)
  {
    msSetError(MS_OGRERR, "Layer contains no fields.",
               "msOGRLayerInitItemInfo()");
    return(MS_FAILURE);
  }

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

  int *itemindexes = (int*)layer->iteminfo;
  for(i=0;i<layer->numitems;i++)
  {
      // Special case for handling text string and angle coming from
      // OGR style strings. We use special attribute snames.
      if (EQUAL(layer->items[i], MSOGR_LABELFONTNAMENAME))
          itemindexes[i] = MSOGR_LABELFONTNAMEINDEX;
      else if (EQUAL(layer->items[i], MSOGR_LABELSIZENAME))
          itemindexes[i] = MSOGR_LABELSIZEINDEX;
      else if (EQUAL(layer->items[i], MSOGR_LABELTEXTNAME))
          itemindexes[i] = MSOGR_LABELTEXTINDEX;
      else if (EQUAL(layer->items[i], MSOGR_LABELANGLENAME))
          itemindexes[i] = MSOGR_LABELANGLEINDEX;
      else if (EQUAL(layer->items[i], MSOGR_LABELFCOLORNAME))
          itemindexes[i] = MSOGR_LABELFCOLORINDEX;
      else if (EQUAL(layer->items[i], MSOGR_LABELBCOLORNAME))
          itemindexes[i] = MSOGR_LABELBCOLORINDEX;
      else if (EQUAL(layer->items[i], MSOGR_LABELPLACEMENTNAME))
          itemindexes[i] = MSOGR_LABELPLACEMENTINDEX;
      else if (EQUAL(layer->items[i], MSOGR_LABELANCHORNAME))
          itemindexes[i] = MSOGR_LABELANCHORINDEX;
      else if (EQUAL(layer->items[i], MSOGR_LABELDXNAME))
          itemindexes[i] = MSOGR_LABELDXINDEX;
      else if (EQUAL(layer->items[i], MSOGR_LABELDYNAME))
          itemindexes[i] = MSOGR_LABELDYINDEX;
      else if (EQUAL(layer->items[i], MSOGR_LABELPERPNAME))
          itemindexes[i] = MSOGR_LABELPERPINDEX;
      else if (EQUAL(layer->items[i], MSOGR_LABELBOLDNAME))
          itemindexes[i] = MSOGR_LABELBOLDINDEX;
      else if (EQUAL(layer->items[i], MSOGR_LABELITALICNAME))
          itemindexes[i] = MSOGR_LABELITALICINDEX;
      else if (EQUAL(layer->items[i], MSOGR_LABELUNDERLINENAME))
          itemindexes[i] = MSOGR_LABELUNDERLINEINDEX;
      else if (EQUAL(layer->items[i], MSOGR_LABELPRIORITYNAME))
          itemindexes[i] = MSOGR_LABELPRIORITYINDEX;
      else if (EQUAL(layer->items[i], MSOGR_LABELSTRIKEOUTNAME))
          itemindexes[i] = MSOGR_LABELSTRIKEOUTINDEX;
      else if (EQUAL(layer->items[i], MSOGR_LABELSTRETCHNAME))
          itemindexes[i] = MSOGR_LABELSTRETCHINDEX;
      else if (EQUAL(layer->items[i], MSOGR_LABELADJHORNAME))
          itemindexes[i] = MSOGR_LABELADJHORINDEX;
      else if (EQUAL(layer->items[i], MSOGR_LABELADJVERTNAME))
          itemindexes[i] = MSOGR_LABELADJVERTINDEX;
      else if (EQUAL(layer->items[i], MSOGR_LABELHCOLORNAME))
          itemindexes[i] = MSOGR_LABELHCOLORINDEX;
#if GDAL_VERSION_NUM >= 1600
      else if (EQUAL(layer->items[i], MSOGR_LABELOCOLORNAME))
          itemindexes[i] = MSOGR_LABELOCOLORINDEX;
#endif /* GDAL_VERSION_NUM >= 1600 */
      else
          itemindexes[i] = OGR_FD_GetFieldIndex( hDefn, layer->items[i] );
      if(itemindexes[i] == -1)
      {
          msSetError(MS_OGRERR,
                     (char*)CPLSPrintf("Invalid Field name: %s",
                                       layer->items[i]),
                     "msOGRLayerInitItemInfo()");
          return(MS_FAILURE);
      }
  }

  return(MS_SUCCESS);
#else
/* ------------------------------------------------------------------
* OGR Support not included...
* ------------------------------------------------------------------ */

  msSetError(MS_MISCERR, "OGR support is not available.",
             "msOGRLayerInitItemInfo()");
  return(MS_FAILURE);

#endif /* USE_OGR */
}

/**********************************************************************
* msOGRLayerFreeItemInfo()
*
* Free the itemindexes array in a layer.
**********************************************************************/
void msOGRLayerFreeItemInfo(layerObj *layer)
{
#ifdef USE_OGR

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

#else
/* ------------------------------------------------------------------
* OGR Support not included...
* ------------------------------------------------------------------ */

  msSetError(MS_MISCERR, "OGR support is not available.",
             "msOGRLayerFreeItemInfo()");

#endif /* USE_OGR */
}


/**********************************************************************
* msOGRLayerNextShape()
*
* Returns shape sequentially from OGR data source.
* msOGRLayerWhichShape() must have been called first.
*
* Returns MS_SUCCESS/MS_FAILURE
**********************************************************************/
int msOGRLayerNextShape(layerObj *layer, shapeObj *shape)
{
#ifdef USE_OGR
  msOGRFileInfo *psInfo =(msOGRFileInfo*)layer->layerinfo;
  int status;

  if (psInfo == NULL || psInfo->hLayer == NULL)
  {
    msSetError(MS_MISCERR, "Assertion failed: OGR layer not opened!!!",
               "msOGRLayerNextShape()");
    return(MS_FAILURE);
  }

  if( layer->tileindex == NULL )
      return msOGRFileNextShape( layer, shape, psInfo );

  // Do we need to load the first tile?
  if( psInfo->poCurTile == NULL )
  {
      status = msOGRFileReadTile( layer, psInfo );
      if( status != MS_SUCCESS )
          return status;
  }

  do
  {
      // Try getting a shape from this tile.
      status = msOGRFileNextShape( layer, shape, psInfo->poCurTile );
      if( status != MS_DONE )
          return status;
  
      // try next tile.
      status = msOGRFileReadTile( layer, psInfo );
      if( status != MS_SUCCESS )
          return status;
  } while( status == MS_SUCCESS );

  return status;
#else
/* ------------------------------------------------------------------
* OGR Support not included...
* ------------------------------------------------------------------ */

  msSetError(MS_MISCERR, "OGR support is not available.",
             "msOGRLayerNextShape()");
  return(MS_FAILURE);

#endif /* USE_OGR */
}

/**********************************************************************
* msOGRLayerGetShape()
*
* Returns shape from OGR data source by fid.
*
* Returns MS_SUCCESS/MS_FAILURE
**********************************************************************/
int msOGRLayerGetShape(layerObj *layer, shapeObj *shape, resultObj *record)
{
#ifdef USE_OGR
  msOGRFileInfo *psInfo =(msOGRFileInfo*)layer->layerinfo;

  long shapeindex = record->shapeindex;
  int tileindex = record->tileindex;
  int resultindex = record->resultindex;
  int record_is_fid = TRUE;

  /* set the resultindex as shapeindex if available */
  if (resultindex >= 0)
  {
    record_is_fid = FALSE;
    shapeindex = resultindex;
  }

  if (psInfo == NULL || psInfo->hLayer == NULL)
  {
    msSetError(MS_MISCERR, "Assertion failed: OGR layer not opened!!!", "msOGRLayerGetShape()");
    return(MS_FAILURE);
  }

  if( layer->tileindex == NULL )
      return msOGRFileGetShape(layer, shape, shapeindex, psInfo, record_is_fid );
  else
  {
      if( psInfo->poCurTile == NULL
          || psInfo->poCurTile->nTileId != tileindex )
      {
          if( msOGRFileReadTile( layer, psInfo, tileindex ) != MS_SUCCESS )
              return MS_FAILURE;
      }

      return msOGRFileGetShape(layer, shape, shapeindex, psInfo->poCurTile, record_is_fid );
  }
#else
/* ------------------------------------------------------------------
* OGR Support not included...
* ------------------------------------------------------------------ */

  msSetError(MS_MISCERR, "OGR support is not available.",
             "msOGRLayerGetShape()");
  return(MS_FAILURE);

#endif /* USE_OGR */
}

/**********************************************************************
* msOGRLayerGetExtent()
*
* Returns the layer extents.
*
* Returns MS_SUCCESS/MS_FAILURE
**********************************************************************/
int msOGRLayerGetExtent(layerObj *layer, rectObj *extent)
{
#ifdef USE_OGR
  msOGRFileInfo *psInfo =(msOGRFileInfo*)layer->layerinfo;
  OGREnvelope oExtent;

  if (psInfo == NULL || psInfo->hLayer == NULL)
  {
    msSetError(MS_MISCERR, "Assertion failed: OGR layer not opened!!!",
               "msOGRLayerGetExtent()");
    return(MS_FAILURE);
  }

/* ------------------------------------------------------------------
* Call OGR's GetExtent()... note that for some formats this will
* result in a scan of the whole layer and can be an expensive call.
*
* For tile indexes layers we assume it is sufficient to get the
* extents of the tile index.
* ------------------------------------------------------------------ */
  ACQUIRE_OGR_LOCK;
  if (OGR_L_GetExtent( psInfo->hLayer, &oExtent, TRUE) != OGRERR_NONE)
  {
      RELEASE_OGR_LOCK;
    msSetError(MS_MISCERR, "Unable to get extents for this layer.",
               "msOGRLayerGetExtent()");
    return(MS_FAILURE);
  }
  RELEASE_OGR_LOCK;

  extent->minx = oExtent.MinX;
  extent->miny = oExtent.MinY;
  extent->maxx = oExtent.MaxX;
  extent->maxy = oExtent.MaxY;

  return MS_SUCCESS;
#else
/* ------------------------------------------------------------------
* OGR Support not included...
* ------------------------------------------------------------------ */

  msSetError(MS_MISCERR, "OGR support is not available.",
             "msOGRLayerGetExtent()");
  return(MS_FAILURE);

#endif /* USE_OGR */
}


/**********************************************************************
* msOGRGetSymbolId()
*
* Returns a MapServer symbol number matching one of the symbols from
* the OGR symbol id string. If not found then try to locate the
* default symbol name, and if not found return 0.
**********************************************************************/
#ifdef USE_OGR
static int msOGRGetSymbolId(symbolSetObj *symbolset, const char *pszSymbolId,
                            const char *pszDefaultSymbol, int try_addimage_if_notfound)
{
    // Symbol name mapping:
    // First look for the native symbol name, then the ogr-...
    // generic name, and in last resort try pszDefaultSymbol if
    // provided by user.
    char **params;
    int numparams;
    int nSymbol = -1;

    if (pszSymbolId && pszSymbolId[0] != '\0')
    {
#if GDAL_VERSION_NUM >= 1800 /* Use comma as the separator */
        params = msStringSplit(pszSymbolId, ',', &numparams);
#else
        params = msStringSplit(pszSymbolId, '.', &numparams);
#endif
        if (params != NULL)
        {
            for(int j=0; j<numparams && nSymbol == -1; j++)
            {
                nSymbol = msGetSymbolIndex(symbolset, params[j],
                                           try_addimage_if_notfound);
            }
            msFreeCharArray(params, numparams);
        }
    }
    if (nSymbol == -1 && pszDefaultSymbol)
    {
        nSymbol = msGetSymbolIndex(symbolset,(char*)pszDefaultSymbol,
                                   try_addimage_if_notfound);
    }
    if (nSymbol == -1)
        nSymbol = 0;

    return nSymbol;
}
#endif

/**********************************************************************
* msOGRUpdateStyle()
*
* Update the mapserver style according to the ogr style.
* The function is called by msOGRGetAutoStyle and
* msOGRUpdateStyleFromString
**********************************************************************/

#ifdef USE_OGR
static int msOGRUpdateStyle(OGRStyleMgrH hStyleMgr, mapObj *map, layerObj *layer, classObj *c)
{
    GBool bIsNull, bIsBrush=MS_FALSE, bIsPen=MS_FALSE;
    int r=0,g=0,b=0,t=0;
    double dfTmp;
    int try_addimage_if_notfound = MS_FALSE;
    int numParts = OGR_SM_GetPartCount(hStyleMgr, NULL);

/* ------------------------------------------------------------------
* Handle each part
* ------------------------------------------------------------------ */

    for(int i=0; i<numParts; i++)
    {
      OGRSTClassId eStylePartType;
      OGRStyleToolH hStylePart = OGR_SM_GetPart(hStyleMgr, i, NULL);
      if (!hStylePart)
          continue;
      eStylePartType = OGR_ST_GetType(hStylePart);

      // We want all size values returned in pixels.
      //
      // The scale factor that OGR expect is the ground/paper scale
      // e.g. if 1 ground unit = 0.01 paper unit then scale=1/0.01=100
      // cellsize if number of ground units/pixel, and OGR assumes that
      // there is 72*39.37 pixels/ground units (since meter is assumed
      // for ground... but what ground units we have does not matter
      // as long as use the same assumptions everywhere)
      // That gives scale = cellsize*72*39.37

      OGR_ST_SetUnit(hStylePart, OGRSTUPixel, map->cellsize*72.0*39.37);

      if (eStylePartType == OGRSTCLabel && c->numlabels >= 1)
      {
          OGRStyleToolH hLabelStyle = hStylePart;

          // Enclose the text string inside quotes to make sure it is seen
          // as a string by the parser inside loadExpression(). (bug185)
          /* See bug 3481 about the isalnum hack */
          const char *labelTextString = OGR_ST_GetParamStr(hLabelStyle,
                                                           OGRSTLabelTextString,
                                                           &bIsNull);
          char *escapedTextString = msStringEscape((char*)labelTextString);
          msLoadExpressionString(&(c->text),
                                 (char*)CPLSPrintf("\"%s\"", escapedTextString));
          free(escapedTextString);

          c->labels[0]->angle = OGR_ST_GetParamDbl(hLabelStyle,
                                              OGRSTLabelAngle, &bIsNull);

          c->labels[0]->size = OGR_ST_GetParamDbl(hLabelStyle,
                                             OGRSTLabelSize, &bIsNull);
          if( c->labels[0]->size < 1 ) /* no point dropping to zero size */
              c->labels[0]->size = 1;

          // OGR default is anchor point = LL, so label is at UR of anchor
          c->labels[0]->position = MS_UR;

          int nPosition = OGR_ST_GetParamNum(hLabelStyle,
                                             OGRSTLabelAnchor,
                                             &bIsNull);
          if( !bIsNull )
          {
              switch( nPosition ) {
                case 1: c->labels[0]->position = MS_UR; break;
                case 2: c->labels[0]->position = MS_UC; break;
                case 3: c->labels[0]->position = MS_UL; break;
                case 4: c->labels[0]->position = MS_CR; break;
                case 5: c->labels[0]->position = MS_CC; break;
                case 6: c->labels[0]->position = MS_CL; break;
                case 7: c->labels[0]->position = MS_LR; break;
                case 8: c->labels[0]->position = MS_LC; break;
                case 9: c->labels[0]->position = MS_LL; break;
                case 10: c->labels[0]->position = MS_UR; break; /*approximate*/
                case 11: c->labels[0]->position = MS_UC; break;
                case 12: c->labels[0]->position = MS_UL; break;
                default: break;
              }
          }

          const char *pszColor = OGR_ST_GetParamStr(hLabelStyle,
                                                    OGRSTLabelFColor,
                                                    &bIsNull);
          if (!bIsNull && OGR_ST_GetRGBFromString(hLabelStyle, pszColor,
                                                  &r, &g, &b, &t))
          {
              MS_INIT_COLOR(c->labels[0]->color, r, g, b, t);
          }

          pszColor = OGR_ST_GetParamStr(hLabelStyle,
                                        OGRSTLabelHColor,
                                        &bIsNull);
          if (!bIsNull && OGR_ST_GetRGBFromString(hLabelStyle, pszColor,
                                                  &r, &g, &b, &t))
          {
              MS_INIT_COLOR(c->labels[0]->shadowcolor, r, g, b, t);
          }

#if GDAL_VERSION_NUM >= 1600
          pszColor = OGR_ST_GetParamStr(hLabelStyle,
                                        OGRSTLabelOColor,
                                        &bIsNull);
          if (!bIsNull && OGR_ST_GetRGBFromString(hLabelStyle, pszColor,
                                                  &r, &g, &b, &t))
          {
              MS_INIT_COLOR(c->labels[0]->outlinecolor, r, g, b, t);
          }
#endif /* GDAL_VERSION_NUM >= 1600 */

          const char *pszBold = OGR_ST_GetParamNum(hLabelStyle,
                                                       OGRSTLabelBold,
                                                       &bIsNull) ? "-bold" : "";
          const char *pszItalic = OGR_ST_GetParamNum(hLabelStyle,
                                                       OGRSTLabelItalic,
                                                       &bIsNull) ? "-italic" : "";
          const char *pszFontName = OGR_ST_GetParamStr(hLabelStyle,
                                                       OGRSTLabelFontName,
                                                       &bIsNull);
          const char *pszName = CPLSPrintf("%s%s%s", pszFontName, pszBold, pszItalic);
          bool bFont = true;

          if (pszFontName != NULL && !bIsNull && pszFontName[0] != '\0')
          {
              if (msLookupHashTable(&(map->fontset.fonts), (char*)pszName) != NULL)
              {
                  c->labels[0]->type = MS_TRUETYPE;
                  c->labels[0]->font = msStrdup(pszName);
                  if (layer->debug >= MS_DEBUGLEVEL_VVV)
                      msDebug("** Using '%s' TTF font **\n", pszName);
              }
              else if ( (strcmp(pszFontName,pszName) != 0) &&
                        msLookupHashTable(&(map->fontset.fonts), (char*)pszFontName) != NULL)
              {
                  c->labels[0]->type = MS_TRUETYPE;
                  c->labels[0]->font = msStrdup(pszFontName);
                  if (layer->debug >= MS_DEBUGLEVEL_VVV)
                      msDebug("** Using '%s' TTF font **\n", pszFontName);
              }
              else if (msLookupHashTable(&(map->fontset.fonts),"default") != NULL)
              {
                  c->labels[0]->type = MS_TRUETYPE;
                  c->labels[0]->font = msStrdup("default");
                  if (layer->debug >= MS_DEBUGLEVEL_VVV)
                      msDebug("** Using 'default' TTF font **\n");
              }
              else
                  bFont = false;
          }

          if (!bFont)
          {
              c->labels[0]->type = MS_BITMAP;
              c->labels[0]->size = MS_MEDIUM;
              if (layer->debug >= MS_DEBUGLEVEL_VVV)
                  msDebug("** Using 'medium' BITMAP font **\n");
          }
      }
      else if (eStylePartType == OGRSTCPen)
      {
          OGRStyleToolH hPenStyle = hStylePart;
          bIsPen = TRUE;

          const char *pszPenName = OGR_ST_GetParamStr(hPenStyle,
                                                      OGRSTPenId,
                                                      &bIsNull);
          if (bIsNull) pszPenName = NULL;
          colorObj oPenColor;
          int nPenSymbol = 0;
          int nPenSize = 1;
          t =-1;

          // Make sure pen is always initialized
          MS_INIT_COLOR(oPenColor, -1, -1, -1,255);

          // Check for Pen Pattern "ogr-pen-1": the invisible pen
          // If that's what we have then set pen color to -1
          if (pszPenName && strstr(pszPenName, "ogr-pen-1") != NULL)
          {
              MS_INIT_COLOR(oPenColor, -1, -1, -1,255);
          }
          else
          {
              const char *pszColor = OGR_ST_GetParamStr(hPenStyle,
                                                        OGRSTPenColor,
                                                        &bIsNull);
              if (!bIsNull && OGR_ST_GetRGBFromString(hPenStyle, pszColor,
                                                      &r, &g, &b, &t))
              {
                  MS_INIT_COLOR(oPenColor, r, g, b, t);
                  if (layer->debug >= MS_DEBUGLEVEL_VVV)
                      msDebug("** PEN COLOR = %d %d %d **\n", r,g,b);
              }

              nPenSize = OGR_ST_GetParamNum(hPenStyle,
                                            OGRSTPenWidth, &bIsNull);
              if (bIsNull)
                  nPenSize = 1;
              if (pszPenName!=NULL)
              {
                  // Try to match pen name in symbol file
                  nPenSymbol = msOGRGetSymbolId(&(map->symbolset),
                                                pszPenName, NULL, MS_FALSE);
              }
          }
          if (layer->debug >= MS_DEBUGLEVEL_VVV)
              msDebug("** PEN COLOR = %d %d %d **\n", oPenColor.red,oPenColor.green,oPenColor.blue);
          if (bIsBrush || layer->type == MS_LAYER_POLYGON)
          {
              // This is a multipart symbology, so pen defn goes in the
              // overlaysymbol params
              if (msMaybeAllocateClassStyle(c, 1))
              {
                  OGR_ST_Destroy(hStylePart);
                  return(MS_FAILURE);
              }

              c->styles[1]->outlinecolor = oPenColor;
              c->styles[1]->size = nPenSize;
              c->styles[1]->symbol = nPenSymbol;
              c->styles[1]->width = nPenSize;
          }
          else
          {
              // Single part symbology
              if (msMaybeAllocateClassStyle(c, 0))
              {
                  OGR_ST_Destroy(hStylePart);
                  return(MS_FAILURE);
              }

              if(layer->type == MS_LAYER_POLYGON)
                  c->styles[0]->outlinecolor = c->styles[0]->color =
                      oPenColor;
              else
                  c->styles[0]->color = oPenColor;
              c->styles[0]->symbol = nPenSymbol;
              c->styles[0]->size = nPenSize;
              c->styles[0]->width = nPenSize;
          }

      }
      else if (eStylePartType == OGRSTCBrush)
      {
          OGRStyleToolH hBrushStyle = hStylePart;

          const char *pszBrushName = OGR_ST_GetParamStr(hBrushStyle,
                                                        OGRSTBrushId,
                                                        &bIsNull);
          if (bIsNull) pszBrushName = NULL;

          /* We need 1 style */
          if (msMaybeAllocateClassStyle(c, 0))
          {
              OGR_ST_Destroy(hStylePart);
              return(MS_FAILURE);
          }

          // Check for Brush Pattern "ogr-brush-1": the invisible fill
          // If that's what we have then set fill color to -1
          if (pszBrushName && strstr(pszBrushName, "ogr-brush-1") != NULL)
          {
              MS_INIT_COLOR(c->styles[0]->color, -1, -1, -1, 255);
          }
          else
          {
              bIsBrush = TRUE;
              const char *pszColor = OGR_ST_GetParamStr(hBrushStyle,
                                                        OGRSTBrushFColor,
                                                        &bIsNull);
              if (!bIsNull && OGR_ST_GetRGBFromString(hBrushStyle,
                                                      pszColor,
                                                      &r, &g, &b, &t))
              {
                  MS_INIT_COLOR(c->styles[0]->color, r, g, b, t);

                  if (layer->debug >= MS_DEBUGLEVEL_VVV)
                      msDebug("** BRUSH COLOR = %d %d %d **\n", r,g,b);
              }

              pszColor = OGR_ST_GetParamStr(hBrushStyle,
                                            OGRSTBrushBColor, &bIsNull);
              if (!bIsNull && OGR_ST_GetRGBFromString(hBrushStyle,
                                                      pszColor,
                                                      &r, &g, &b, &t))
              {
                  MS_INIT_COLOR(c->styles[0]->backgroundcolor, r, g, b, t);
              }

              // Symbol name mapping:
              // First look for the native symbol name, then the ogr-...
              // generic name.
              // If none provided or found then use 0: solid fill
          
              const char *pszName = OGR_ST_GetParamStr(hBrushStyle,
                                                        OGRSTBrushId,
                                                        &bIsNull);
              c->styles[0]->symbol = msOGRGetSymbolId(&(map->symbolset),
                                                      pszName, NULL, MS_FALSE);
          }
      }
      else if (eStylePartType == OGRSTCSymbol)
      {
          OGRStyleToolH hSymbolStyle = hStylePart;

          /* We need 1 style */
          if (msMaybeAllocateClassStyle(c, 0))
          {
              OGR_ST_Destroy(hStylePart);
              return(MS_FAILURE);
          }

          const char *pszColor = OGR_ST_GetParamStr(hSymbolStyle,
                                                    OGRSTSymbolColor,
                                                    &bIsNull);
          if (!bIsNull && OGR_ST_GetRGBFromString(hSymbolStyle,
                                                  pszColor,
                                                  &r, &g, &b, &t))
          {
              MS_INIT_COLOR(c->styles[0]->color, r, g, b, t);
          }

#if GDAL_VERSION_NUM >= 1600
          pszColor = OGR_ST_GetParamStr(hSymbolStyle,
                                        OGRSTSymbolOColor,
                                        &bIsNull);
          if (!bIsNull && OGR_ST_GetRGBFromString(hSymbolStyle,
                                                  pszColor,
                                                  &r, &g, &b, &t))
          {
              MS_INIT_COLOR(c->styles[0]->outlinecolor, r, g, b, t);
          }
#endif /* GDAL_VERSION_NUM >= 1600 */
          c->styles[0]->angle = OGR_ST_GetParamNum(hSymbolStyle,
                                                   OGRSTSymbolAngle,
                                                   &bIsNull);
          dfTmp = OGR_ST_GetParamNum(hSymbolStyle, OGRSTSymbolSize, &bIsNull);
          if (!bIsNull)
            c->styles[0]->size = dfTmp;

          // Symbol name mapping:
          // First look for the native symbol name, then the ogr-...
          // generic name, and in last resort try "default-marker" if
          // provided by user.
          const char *pszName = OGR_ST_GetParamStr(hSymbolStyle,
                                                   OGRSTSymbolId,
                                                   &bIsNull);
          if (bIsNull)
              pszName = NULL;

          try_addimage_if_notfound = MS_FALSE;
#ifdef USE_CURL
          if (pszName && strncasecmp(pszName, "http", 4) == 0)
            try_addimage_if_notfound =MS_TRUE;
#endif
          if (!c->styles[0]->symbolname)
            c->styles[0]->symbol = msOGRGetSymbolId(&(map->symbolset),
                                                    pszName,
                                                    "default-marker", try_addimage_if_notfound);
      }

      OGR_ST_Destroy(hStylePart);
      
    }
    return MS_SUCCESS;
}
#endif /* USE_OGR */



/**********************************************************************
* msOGRLayerGetAutoStyle()
*
* Fills a classObj with style info from the specified shape.
* For optimal results, this should be called immediately after
* GetNextShape() or GetShape() so that the shape doesn't have to be read
* twice.
*
* The returned classObj is a ref. to a static structure valid only until
* the next call and that shouldn't be freed by the caller.
**********************************************************************/
static int msOGRLayerGetAutoStyle(mapObj *map, layerObj *layer, classObj *c,
                                  shapeObj* shape)
{
#ifdef USE_OGR
  msOGRFileInfo *psInfo =(msOGRFileInfo*)layer->layerinfo;

  if (psInfo == NULL || psInfo->hLayer == NULL)
  {
    msSetError(MS_MISCERR, "Assertion failed: OGR layer not opened!!!",
               "msOGRLayerGetAutoStyle()");
    return(MS_FAILURE);
  }

  if( layer->tileindex != NULL )
  {
      if( (psInfo->poCurTile == NULL || shape->tileindex != psInfo->poCurTile->nTileId)
          && msOGRFileReadTile( layer, psInfo ) != MS_SUCCESS )
          return MS_FAILURE;
      
      psInfo = psInfo->poCurTile;
  }

/* ------------------------------------------------------------------
* Read shape or reuse ref. to last shape read.
* ------------------------------------------------------------------ */
  ACQUIRE_OGR_LOCK;
  if (psInfo->hLastFeature == NULL ||
      psInfo->last_record_index_read != shape->resultindex)
  {
      RELEASE_OGR_LOCK;
      msSetError(MS_MISCERR,
                 "Assertion failed: AutoStyle not requested on loaded shape.",
                 "msOGRLayerGetAutoStyle()");
      return(MS_FAILURE);
  }

/* ------------------------------------------------------------------
* Reset style info in the class to defaults
* the only members we don't touch are name, expression, and join/query stuff
* ------------------------------------------------------------------ */
  resetClassStyle(c);
  if (msMaybeAllocateClassStyle(c, 0)) {
      RELEASE_OGR_LOCK;
      return(MS_FAILURE);
  }

  // __TODO__ label cache incompatible with styleitem feature.
  layer->labelcache = MS_OFF;

  int nRetVal = MS_SUCCESS;
  if (psInfo->hLastFeature)
  {
      OGRStyleMgrH hStyleMgr = OGR_SM_Create(NULL);
      OGR_SM_InitFromFeature(hStyleMgr, psInfo->hLastFeature);
      nRetVal = msOGRUpdateStyle(hStyleMgr, map, layer, c);
      OGR_SM_Destroy(hStyleMgr);
  }

  RELEASE_OGR_LOCK;
  return nRetVal;
#else
/* ------------------------------------------------------------------
* OGR Support not included...
* ------------------------------------------------------------------ */

  msSetError(MS_MISCERR, "OGR support is not available.",
             "msOGRLayerGetAutoStyle()");
  return(MS_FAILURE);

#endif /* USE_OGR */
}


/**********************************************************************
* msOGRUpdateStyleFromString()
*
* Fills a classObj with style info from the specified style string.
* For optimal results, this should be called immediately after
* GetNextShape() or GetShape() so that the shape doesn't have to be read
* twice.
*
* The returned classObj is a ref. to a static structure valid only until
* the next call and that shouldn't be freed by the caller.
**********************************************************************/
int msOGRUpdateStyleFromString(mapObj *map, layerObj *layer, classObj *c,
                                  const char *stylestring)
{
#ifdef USE_OGR
/* ------------------------------------------------------------------
* Reset style info in the class to defaults
* the only members we don't touch are name, expression, and join/query stuff
* ------------------------------------------------------------------ */
    resetClassStyle(c);
    if (msMaybeAllocateClassStyle(c, 0)) {
      return(MS_FAILURE);
    }

    // __TODO__ label cache incompatible with styleitem feature.
    layer->labelcache = MS_OFF;

    int nRetVal = MS_SUCCESS;

    ACQUIRE_OGR_LOCK;

    OGRStyleMgrH hStyleMgr = OGR_SM_Create(NULL);
    OGR_SM_InitStyleString(hStyleMgr, stylestring);
    nRetVal = msOGRUpdateStyle(hStyleMgr, map, layer, c);
    OGR_SM_Destroy(hStyleMgr);
    
    RELEASE_OGR_LOCK;
    return nRetVal;
#else
/* ------------------------------------------------------------------
* OGR Support not included...
* ------------------------------------------------------------------ */

  msSetError(MS_MISCERR, "OGR support is not available.",
             "msOGRLayerGetAutoStyle()");
  return(MS_FAILURE);

#endif /* USE_OGR */
}

/************************************************************************/
/* msOGRLCleanup() */
/************************************************************************/

void msOGRCleanup( void )

{
#if defined(USE_OGR)
    ACQUIRE_OGR_LOCK;
    if( bOGRDriversRegistered == MS_TRUE )
    {
        CPLPopErrorHandler();
        OGRCleanupAll();
        bOGRDriversRegistered = MS_FALSE;
    }
    RELEASE_OGR_LOCK;
#endif
}

/************************************************************************/
/* msOGREscapeSQLParam */
/************************************************************************/
char *msOGREscapeSQLParam(layerObj *layer, const char *pszString)
{
    char* pszEscapedStr =NULL;
#ifdef USE_OGR
    if(layer && pszString && strlen(pszString) > 0)
    {
        char* pszEscapedOGRStr = CPLEscapeString(pszString, strlen(pszString),
CPLES_SQL );
pszEscapedStr = msStrdup(pszEscapedOGRStr);
        CPLFree(pszEscapedOGRStr);
    }
    return pszEscapedStr;
#else
/* ------------------------------------------------------------------
* OGR Support not included...
* ------------------------------------------------------------------ */

  msSetError(MS_MISCERR, "OGR support is not available.",
             "msOGREscapeSQLParam()");
  return NULL;

#endif /* USE_OGR */
}


/************************************************************************/
/* msOGREscapeSQLParam */
/************************************************************************/
char *msOGREscapePropertyName(layerObj *layer, const char *pszString)
{
    char* pszEscapedStr =NULL;
    int i =0;
#ifdef USE_OGR
    if(layer && pszString && strlen(pszString) > 0)
    {
        unsigned char ch;
        for(i=0; (ch = ((unsigned char*)pszString)[i]) != '\0'; i++)
        {
            if ( !(isalnum(ch) || ch == '_' || ch > 127) )
            {
                return msStrdup("invalid_property_name");
            }
        }
        pszEscapedStr = msStrdup(pszString);
    }
    return pszEscapedStr;
#else
/* ------------------------------------------------------------------
* OGR Support not included...
* ------------------------------------------------------------------ */

  msSetError(MS_MISCERR, "OGR support is not available.",
             "msOGREscapePropertyName()");
  return NULL;

#endif /* USE_OGR */
}
/************************************************************************/
/* msOGRLayerInitializeVirtualTable() */
/************************************************************************/
int
msOGRLayerInitializeVirtualTable(layerObj *layer)
{
    assert(layer != NULL);
    assert(layer->vtable != NULL);

    layer->vtable->LayerInitItemInfo = msOGRLayerInitItemInfo;
    layer->vtable->LayerFreeItemInfo = msOGRLayerFreeItemInfo;
    layer->vtable->LayerOpen = msOGRLayerOpenVT;
    layer->vtable->LayerIsOpen = msOGRLayerIsOpen;
    layer->vtable->LayerWhichShapes = msOGRLayerWhichShapes;
    layer->vtable->LayerNextShape = msOGRLayerNextShape;
    layer->vtable->LayerGetShape = msOGRLayerGetShape;
    layer->vtable->LayerClose = msOGRLayerClose;
    layer->vtable->LayerGetItems = msOGRLayerGetItems;
    layer->vtable->LayerGetExtent = msOGRLayerGetExtent;
    layer->vtable->LayerGetAutoStyle = msOGRLayerGetAutoStyle;
    /* layer->vtable->LayerCloseConnection, use default */
    layer->vtable->LayerApplyFilterToLayer = msLayerApplyCondSQLFilterToLayer;
    layer->vtable->LayerSetTimeFilter = msLayerMakeBackticsTimeFilter;
    /* layer->vtable->LayerCreateItems, use default */
    /* layer->vtable->LayerGetNumFeatures, use default */
    /* layer->vtable->LayerGetAutoProjection, use defaut*/

    layer->vtable->LayerEscapeSQLParam = msOGREscapeSQLParam;
    layer->vtable->LayerEscapePropertyName = msOGREscapePropertyName;

    return MS_SUCCESS;
}

/************************************************************************/
/* msOGRShapeFromWKT() */
/************************************************************************/
shapeObj *msOGRShapeFromWKT(const char *string)
{
#ifdef USE_OGR
    OGRGeometryH hGeom = NULL;
    shapeObj *shape=NULL;
    
    if(!string)
        return NULL;
    
    if( OGR_G_CreateFromWkt( (char **)&string, NULL, &hGeom ) != OGRERR_NONE )
    {
        msSetError(MS_OGRERR, "Failed to parse WKT string.",
                   "msOGRShapeFromWKT()" );
        return NULL;
    }

    /* Initialize a corresponding shapeObj */

    shape = (shapeObj *) malloc(sizeof(shapeObj));
    msInitShape(shape);

    /* translate WKT into an OGRGeometry. */
  
    if( msOGRGeometryToShape( hGeom, shape,
                              wkbFlatten(OGR_G_GetGeometryType(hGeom)) )
                              == MS_FAILURE )
    {
        free( shape );
        return NULL;
    }

    OGR_G_DestroyGeometry( hGeom );

    return shape;
#else
  msSetError(MS_OGRERR, "OGR support is not available.","msOGRShapeFromWKT()");
  return NULL;
#endif
}

/************************************************************************/
/* msOGRShapeToWKT() */
/************************************************************************/
char *msOGRShapeToWKT(shapeObj *shape)
{
#ifdef USE_OGR
    OGRGeometryH hGeom = NULL;
    int i;
    char *wkt = NULL;

    if(!shape)
        return NULL;

    if( shape->type == MS_SHAPE_POINT && shape->numlines == 1
        && shape->line[0].numpoints == 1 )
    {
        hGeom = OGR_G_CreateGeometry( wkbPoint );
        OGR_G_SetPoint_2D( hGeom, 0,
                           shape->line[0].point[0].x,
                           shape->line[0].point[0].y );
    }
    else if( shape->type == MS_SHAPE_POINT && shape->numlines == 1
             && shape->line[0].numpoints > 1 )
    {
        hGeom = OGR_G_CreateGeometry( wkbMultiPoint );
        for( i = 0; i < shape->line[0].numpoints; i++ )
        {
            OGRGeometryH hPoint;
            
            hPoint = OGR_G_CreateGeometry( wkbPoint );
            OGR_G_SetPoint_2D( hPoint, 0,
                               shape->line[0].point[i].x,
                               shape->line[0].point[i].y );
            OGR_G_AddGeometryDirectly( hGeom, hPoint );
        }
    }
    else if( shape->type == MS_SHAPE_LINE && shape->numlines == 1 )
    {
        hGeom = OGR_G_CreateGeometry( wkbLineString );
        for( i = 0; i < shape->line[0].numpoints; i++ )
        {
            OGR_G_AddPoint_2D( hGeom,
                               shape->line[0].point[i].x,
                               shape->line[0].point[i].y );
        }
    }
    else if( shape->type == MS_SHAPE_LINE && shape->numlines > 1 )
    {
        OGRGeometryH hMultiLine = OGR_G_CreateGeometry( wkbMultiLineString );
        int iLine;

        for( iLine = 0; iLine < shape->numlines; iLine++ )
        {
            hGeom = OGR_G_CreateGeometry( wkbLineString );
            for( i = 0; i < shape->line[iLine].numpoints; i++ )
            {
                OGR_G_AddPoint_2D( hGeom,
                                   shape->line[iLine].point[i].x,
                                   shape->line[iLine].point[i].y );
            }

            OGR_G_AddGeometryDirectly( hMultiLine, hGeom );
        }

        hGeom = hMultiLine;
    }
    else if( shape->type == MS_SHAPE_POLYGON )
    {
        int iLine;

        /* actually, it is pretty hard to be sure rings 1+ are interior */
        hGeom = OGR_G_CreateGeometry( wkbPolygon );
        for( iLine = 0; iLine < shape->numlines; iLine++ )
        {
            OGRGeometryH hRing;
            hRing = OGR_G_CreateGeometry( wkbLinearRing );
            
            for( i = 0; i < shape->line[iLine].numpoints; i++ )
            {
                OGR_G_AddPoint_2D( hRing,
                                   shape->line[iLine].point[i].x,
                                   shape->line[iLine].point[i].y );
            }
            OGR_G_AddGeometryDirectly( hGeom, hRing );
        }
    }
    else
    {
        msSetError(MS_OGRERR, "OGR support is not available.", "msOGRShapeToWKT()");
    }

    if( hGeom != NULL )
    {
        char *pszOGRWkt;

        OGR_G_ExportToWkt( hGeom, &pszOGRWkt );
        wkt = msStrdup( pszOGRWkt );
        CPLFree( pszOGRWkt );
    }

    return wkt;
#else
    msSetError(MS_OGRERR, "OGR support is not available.", "msOGRShapeToWKT()");
    return NULL;
#endif
}
Something went wrong with that request. Please try again.