Check-in Differences
Not logged in

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Difference From 9bca3f7859551e1e To 5543845dedfc10c2

2018-01-14
17:16
fixing for building on MinGW check-in: ef518a87ff user: sandro tags: trunk
2018-01-06
11:45
supporting spatialite_dem (contributed by Mark Johnson) check-in: 5543845ded user: sandro tags: trunk
2017-09-25
16:18
supporting extended version infos: -v or --version argument check-in: 3366873e1a user: sandro tags: trunk
2014-12-16
12:48
updating to automake 1.14.1 check-in: 574499a88a user: sandro tags: trunk
2014-11-28
18:31
fixing several typos reported by LinuxMinded check-in: 9bca3f7859 user: sandro tags: trunk
2014-11-22
21:18
switching to 4.2.1 release candidate 1 check-in: f2d2cf93c6 user: sandro tags: trunk

Changes to Makefile-static-MinGW.

     7      7   
     8      8   all: ./static_bin/spatialite.exe ./static_bin/spatialite_tool.exe \
     9      9   	./static_bin/spatialite_network.exe ./static_bin/shp_doctor.exe \
    10     10   	./static_bin/exif_loader.exe ./static_bin/spatialite_osm_net.exe \
    11     11   	./static_bin/spatialite_osm_map.exe ./static_bin/spatialite_gml.exe \
    12     12   	./static_bin/spatialite_osm_raw.exe ./static_bin/spatialite_osm_filter.exe \
    13     13   	./static_bin/spatialite_convert.exe ./static_bin/spatialite_dxf.exe \
    14         -	./static_bin/spatialite_osm_overpass.exe \
           14  +	./static_bin/spatialite_osm_overpass.exe ./static_bin/shp_sanitize.exe \
    15     15   	./static_bin/spatialite_xml_collapse.exe \
    16     16   	./static_bin/spatialite_xml_validator.exe \
    17     17   	./static_bin/spatialite_xml_load.exe \
    18     18   	./static_bin/spatialite_xml_print.exe
    19     19   
    20     20   ./static_bin/spatialite.exe: shell.o 
    21     21   	$(GG) shell.o -o ./static_bin/spatialite.exe \
    22     22   	/usr/local/lib/libspatialite.a \
    23     23   	/usr/local/lib/libsqlite3.a \
    24         -	/usr/local/lib/liblwgeom.a \
           24  +	/usr/local/lib/librttopo.a \
    25     25   	/usr/local/lib/libxml2.a \
    26     26   	/usr/local/lib/liblzma.a \
    27     27   	/usr/local/lib/libproj.a \
    28     28   	/usr/local/lib/libgeos_c.a \
    29     29   	/usr/local/lib/libgeos.a \
    30     30   	/usr/local/lib/libfreexl.a \
    31     31   	/usr/local/lib/libz.a \
................................................................................
    34     34   	strip --strip-all ./static_bin/spatialite.exe
    35     35   
    36     36   ./static_bin/spatialite_tool.exe: spatialite_tool.o
    37     37   	$(GG) spatialite_tool.o -o \
    38     38   	./static_bin/spatialite_tool.exe \
    39     39   	/usr/local/lib/libspatialite.a \
    40     40   	/usr/local/lib/libsqlite3.a \
    41         -	/usr/local/lib/liblwgeom.a \
           41  +	/usr/local/lib/librttopo.a \
    42     42   	/usr/local/lib/libxml2.a \
    43     43   	/usr/local/lib/liblzma.a \
    44     44   	/usr/local/lib/libproj.a \
    45     45   	/usr/local/lib/libgeos_c.a \
    46     46   	/usr/local/lib/libgeos.a \
    47     47   	/usr/local/lib/libfreexl.a \
    48     48   	/usr/local/lib/libz.a \
................................................................................
    51     51   	strip --strip-all ./static_bin/spatialite_tool.exe
    52     52   
    53     53   ./static_bin/spatialite_convert.exe: spatialite_convert.o
    54     54   	$(GG) spatialite_convert.o -o \
    55     55   	./static_bin/spatialite_convert.exe \
    56     56   	/usr/local/lib/libspatialite.a \
    57     57   	/usr/local/lib/libsqlite3.a \
    58         -	/usr/local/lib/liblwgeom.a \
           58  +	/usr/local/lib/librttopo.a \
    59     59   	/usr/local/lib/libxml2.a \
    60     60   	/usr/local/lib/liblzma.a \
    61     61   	/usr/local/lib/libproj.a \
    62     62   	/usr/local/lib/libgeos_c.a \
    63     63   	/usr/local/lib/libgeos.a \
    64     64   	/usr/local/lib/libfreexl.a \
    65     65   	/usr/local/lib/libz.a \
................................................................................
    68     68   	strip --strip-all ./static_bin/spatialite_convert.exe
    69     69   
    70     70   ./static_bin/spatialite_dxf.exe: spatialite_dxf.o
    71     71   	$(GG) spatialite_dxf.o -o \
    72     72   	./static_bin/spatialite_dxf.exe \
    73     73   	/usr/local/lib/libspatialite.a \
    74     74   	/usr/local/lib/libsqlite3.a \
    75         -	/usr/local/lib/liblwgeom.a \
           75  +	/usr/local/lib/librttopo.a \
    76     76   	/usr/local/lib/libxml2.a \
    77     77   	/usr/local/lib/liblzma.a \
    78     78   	/usr/local/lib/libproj.a \
    79     79   	/usr/local/lib/libgeos_c.a \
    80     80   	/usr/local/lib/libgeos.a \
    81     81   	/usr/local/lib/libfreexl.a \
    82     82   	/usr/local/lib/libz.a \
................................................................................
    84     84   	-lm -lmsimg32 -lws2_32 -static-libstdc++ -static-libgcc
    85     85   	strip --strip-all ./static_bin/spatialite_dxf.exe
    86     86   
    87     87   ./static_bin/spatialite_network.exe: spatialite_network.o
    88     88   	$(GG) spatialite_network.o -o ./static_bin/spatialite_network.exe \
    89     89   	/usr/local/lib/libspatialite.a \
    90     90   	/usr/local/lib/libsqlite3.a \
    91         -	/usr/local/lib/liblwgeom.a \
           91  +	/usr/local/lib/librttopo.a \
    92     92   	/usr/local/lib/libxml2.a \
    93     93   	/usr/local/lib/liblzma.a \
    94     94   	/usr/local/lib/libproj.a \
    95     95   	/usr/local/lib/libgeos_c.a \
    96     96   	/usr/local/lib/libgeos.a \
    97     97   	/usr/local/lib/libfreexl.a \
    98     98   	/usr/local/lib/libz.a \
................................................................................
   100    100   	-lm -lmsimg32 -lws2_32 -static-libstdc++ -static-libgcc
   101    101   	strip --strip-all ./static_bin/spatialite_network.exe
   102    102   
   103    103   ./static_bin/shp_doctor.exe: shp_doctor.o
   104    104   	$(GG) shp_doctor.o -o ./static_bin/shp_doctor.exe \
   105    105   	/usr/local/lib/libspatialite.a \
   106    106   	/usr/local/lib/libsqlite3.a \
   107         -	/usr/local/lib/liblwgeom.a \
          107  +	/usr/local/lib/librttopo.a \
   108    108   	/usr/local/lib/libxml2.a \
   109    109   	/usr/local/lib/liblzma.a \
   110    110   	/usr/local/lib/libproj.a \
   111    111   	/usr/local/lib/libgeos_c.a \
   112    112   	/usr/local/lib/libgeos.a \
   113    113   	/usr/local/lib/libfreexl.a \
   114    114   	/usr/local/lib/libz.a \
   115    115   	/usr/local/lib/libiconv.a \
   116    116   	-lm -lmsimg32 -lws2_32 -static-libstdc++ -static-libgcc
   117    117   	strip --strip-all ./static_bin/shp_doctor.exe
   118    118   	
          119  +./static_bin/shp_sanitize.exe: shp_sanitize.o
          120  +	$(GG) shp_sanitize.o -o ./static_bin/shp_sanitize.exe \
          121  +	/usr/local/lib/libspatialite.a \
          122  +	/usr/local/lib/libsqlite3.a \
          123  +	/usr/local/lib/librttopo.a \
          124  +	/usr/local/lib/libxml2.a \
          125  +	/usr/local/lib/liblzma.a \
          126  +	/usr/local/lib/libproj.a \
          127  +	/usr/local/lib/libgeos_c.a \
          128  +	/usr/local/lib/libgeos.a \
          129  +	/usr/local/lib/libfreexl.a \
          130  +	/usr/local/lib/libz.a \
          131  +	/usr/local/lib/libiconv.a \
          132  +	-lm -lmsimg32 -lws2_32 -static-libstdc++ -static-libgcc
          133  +	strip --strip-all ./static_bin/shp_sanitize.exe
          134  +	
   119    135   ./static_bin/exif_loader.exe: exif_loader.o
   120    136   	$(GG) exif_loader.o -o ./static_bin/exif_loader.exe \
   121    137   	/usr/local/lib/libspatialite.a \
   122    138   	/usr/local/lib/libsqlite3.a \
   123         -	/usr/local/lib/liblwgeom.a \
          139  +	/usr/local/lib/librttopo.a \
   124    140   	/usr/local/lib/libxml2.a \
   125    141   	/usr/local/lib/liblzma.a \
   126    142   	/usr/local/lib/libproj.a \
   127    143   	/usr/local/lib/libgeos_c.a \
   128    144   	/usr/local/lib/libgeos.a \
   129    145   	/usr/local/lib/libfreexl.a \
   130    146   	/usr/local/lib/libz.a \
................................................................................
   132    148   	-lm -lmsimg32 -lws2_32 -static-libstdc++ -static-libgcc
   133    149   	strip --strip-all ./static_bin/exif_loader.exe
   134    150   	
   135    151   ./static_bin/spatialite_osm_net.exe: spatialite_osm_net.o
   136    152   	$(GG) spatialite_osm_net.o -o ./static_bin/spatialite_osm_net.exe \
   137    153   	/usr/local/lib/libspatialite.a \
   138    154   	/usr/local/lib/libsqlite3.a \
   139         -	/usr/local/lib/liblwgeom.a \
          155  +	/usr/local/lib/librttopo.a \
   140    156   	/usr/local/lib/libxml2.a \
   141    157   	/usr/local/lib/liblzma.a \
   142    158   	/usr/local/lib/libproj.a \
   143    159   	/usr/local/lib/libgeos_c.a \
   144    160   	/usr/local/lib/libgeos.a \
   145    161   	/usr/local/lib/libfreexl.a \
   146    162   	/usr/local/lib/libreadosm.a \
................................................................................
   150    166   	-lm -lmsimg32 -lws2_32 -static-libstdc++ -static-libgcc
   151    167   	strip --strip-all ./static_bin/spatialite_osm_net.exe
   152    168   
   153    169   ./static_bin/spatialite_osm_map.exe: spatialite_osm_map.o
   154    170   	$(GG) spatialite_osm_map.o -o ./static_bin/spatialite_osm_map.exe \
   155    171   	/usr/local/lib/libspatialite.a \
   156    172   	/usr/local/lib/libsqlite3.a \
   157         -	/usr/local/lib/liblwgeom.a \
          173  +	/usr/local/lib/librttopo.a \
   158    174   	/usr/local/lib/libxml2.a \
   159    175   	/usr/local/lib/liblzma.a \
   160    176   	/usr/local/lib/libproj.a \
   161    177   	/usr/local/lib/libgeos_c.a \
   162    178   	/usr/local/lib/libgeos.a \
   163    179   	/usr/local/lib/libiconv.a \
   164    180   	/usr/local/lib/libfreexl.a \
................................................................................
   168    184   	-lm -lmsimg32 -lws2_32 -static-libstdc++ -static-libgcc
   169    185   	strip --strip-all ./static_bin/spatialite_osm_map.exe
   170    186   
   171    187   ./static_bin/spatialite_gml.exe: spatialite_gml.o
   172    188   	$(GG) spatialite_gml.o -o ./static_bin/spatialite_gml.exe \
   173    189   	/usr/local/lib/libspatialite.a \
   174    190   	/usr/local/lib/libsqlite3.a \
   175         -	/usr/local/lib/liblwgeom.a \
          191  +	/usr/local/lib/librttopo.a \
   176    192   	/usr/local/lib/libxml2.a \
   177    193   	/usr/local/lib/liblzma.a \
   178    194   	/usr/local/lib/libproj.a \
   179    195   	/usr/local/lib/libgeos_c.a \
   180    196   	/usr/local/lib/libgeos.a \
   181    197   	/usr/local/lib/libfreexl.a \
   182    198   	/usr/local/lib/libz.a \
................................................................................
   185    201   	-lm -lmsimg32 -lws2_32 -static-libstdc++ -static-libgcc
   186    202   	strip --strip-all ./static_bin/spatialite_gml.exe
   187    203   
   188    204   ./static_bin/spatialite_osm_raw.exe: spatialite_osm_raw.o
   189    205   	$(GG) spatialite_osm_raw.o -o ./static_bin/spatialite_osm_raw.exe \
   190    206   	/usr/local/lib/libspatialite.a \
   191    207   	/usr/local/lib/libsqlite3.a \
   192         -	/usr/local/lib/liblwgeom.a \
          208  +	/usr/local/lib/librttopo.a \
   193    209   	/usr/local/lib/libxml2.a \
   194    210   	/usr/local/lib/liblzma.a \
   195    211   	/usr/local/lib/libproj.a \
   196    212   	/usr/local/lib/libgeos_c.a \
   197    213   	/usr/local/lib/libgeos.a \
   198    214   	/usr/local/lib/libfreexl.a \
   199    215   	/usr/local/lib/libreadosm.a \
................................................................................
   203    219   	-lm -lmsimg32 -lws2_32 -static-libstdc++ -static-libgcc
   204    220   	strip --strip-all ./static_bin/spatialite_osm_raw.exe
   205    221   
   206    222   ./static_bin/spatialite_osm_filter.exe: spatialite_osm_filter.o
   207    223   	$(GG) spatialite_osm_filter.o -o ./static_bin/spatialite_osm_filter.exe \
   208    224   	/usr/local/lib/libspatialite.a \
   209    225   	/usr/local/lib/libsqlite3.a \
   210         -	/usr/local/lib/liblwgeom.a \
          226  +	/usr/local/lib/librttopo.a \
   211    227   	/usr/local/lib/libxml2.a \
   212    228   	/usr/local/lib/liblzma.a \
   213    229   	/usr/local/lib/libproj.a \
   214    230   	/usr/local/lib/libgeos_c.a \
   215    231   	/usr/local/lib/libgeos.a \
   216    232   	/usr/local/lib/libfreexl.a \
   217    233   	/usr/local/lib/libz.a \
................................................................................
   219    235   	-lm -lmsimg32 -lws2_32 -static-libstdc++ -static-libgcc 
   220    236   	strip --strip-all ./static_bin/spatialite_osm_filter.exe
   221    237   
   222    238   ./static_bin/spatialite_osm_overpass.exe: spatialite_osm_overpass.o
   223    239   	$(GG) spatialite_osm_overpass.o -o ./static_bin/spatialite_osm_overpass.exe \
   224    240   	/usr/local/lib/libspatialite.a \
   225    241   	/usr/local/lib/libsqlite3.a \
   226         -	/usr/local/lib/liblwgeom.a \
          242  +	/usr/local/lib/librttopo.a \
   227    243   	/usr/local/lib/libxml2.a \
   228    244   	/usr/local/lib/liblzma.a \
   229    245   	/usr/local/lib/libproj.a \
   230    246   	/usr/local/lib/libgeos_c.a \
   231    247   	/usr/local/lib/libgeos.a \
   232    248   	/usr/local/lib/libfreexl.a \
   233    249   	/usr/local/lib/libz.a \
................................................................................
   235    251   	-lm -lmsimg32 -lws2_32 -static-libstdc++ -static-libgcc 
   236    252   	strip --strip-all ./static_bin/spatialite_osm_overpass.exe
   237    253   
   238    254   ./static_bin/spatialite_xml_collapse.exe: spatialite_xml_collapse.o
   239    255   	$(GG) spatialite_xml_collapse.o -o ./static_bin/spatialite_xml_collapse.exe \
   240    256   	/usr/local/lib/libspatialite.a \
   241    257   	/usr/local/lib/libsqlite3.a \
   242         -	/usr/local/lib/liblwgeom.a \
          258  +	/usr/local/lib/librttopo.a \
   243    259   	/usr/local/lib/libxml2.a \
   244    260   	/usr/local/lib/liblzma.a \
   245    261   	/usr/local/lib/libproj.a \
   246    262   	/usr/local/lib/libgeos_c.a \
   247    263   	/usr/local/lib/libgeos.a \
   248    264   	/usr/local/lib/libfreexl.a \
   249    265   	/usr/local/lib/libz.a \
................................................................................
   260    276   	-lm -lws2_32 -static-libgcc 
   261    277   	strip --strip-all ./static_bin/spatialite_xml_validator.exe
   262    278   
   263    279   ./static_bin/spatialite_xml_load.exe: spatialite_xml_load.o
   264    280   	$(GG) spatialite_xml_load.o -o ./static_bin/spatialite_xml_load.exe \
   265    281   	/usr/local/lib/libspatialite.a \
   266    282   	/usr/local/lib/libsqlite3.a \
   267         -	/usr/local/lib/liblwgeom.a \
          283  +	/usr/local/lib/librttopo.a \
   268    284   	/usr/local/lib/libxml2.a \
   269    285   	/usr/local/lib/liblzma.a \
   270    286   	/usr/local/lib/libproj.a \
   271    287   	/usr/local/lib/libgeos_c.a \
   272    288   	/usr/local/lib/libgeos.a \
   273    289   	/usr/local/lib/libfreexl.a \
   274    290   	/usr/local/lib/libexpat.a \
................................................................................
   277    293   	-lm -lmsimg32 -lws2_32 -static-libstdc++ -static-libgcc 
   278    294   	strip --strip-all ./static_bin/spatialite_xml_load.exe
   279    295   
   280    296   ./static_bin/spatialite_xml_print.exe: spatialite_xml_print.o
   281    297   	$(GG) spatialite_xml_print.o -o ./static_bin/spatialite_xml_print.exe \
   282    298   	/usr/local/lib/libspatialite.a \
   283    299   	/usr/local/lib/libsqlite3.a \
   284         -	/usr/local/lib/liblwgeom.a \
          300  +	/usr/local/lib/librttopo.a \
   285    301   	/usr/local/lib/libxml2.a \
   286    302   	/usr/local/lib/liblzma.a \
   287    303   	/usr/local/lib/libproj.a \
   288    304   	/usr/local/lib/libgeos_c.a \
   289    305   	/usr/local/lib/libgeos.a \
   290    306   	/usr/local/lib/libfreexl.a \
   291    307   	/usr/local/lib/libz.a \
................................................................................
   300    316   	$(CC) $(CFLAGS) spatialite_tool.c -c
   301    317   
   302    318   spatialite_network.o:
   303    319   	$(CC) $(CFLAGS) spatialite_network.c -c
   304    320   
   305    321   shp_doctor.o:
   306    322   	$(CC) $(CFLAGS) shp_doctor.c -c
          323  +
          324  +shp_sanitize.o:
          325  +	$(CC) $(CFLAGS) shp_sanitize.c -c
   307    326   	
   308    327   exif_loader.o:
   309    328   	$(CC) $(CFLAGS) exif_loader.c -c
   310    329   	
   311    330   spatialite_osm_net.o:
   312    331   	$(CC) $(CFLAGS) spatialite_osm_net.c -c
   313    332   	

Added Makefile-static-mingw32.

            1  +# SandroFurieri (c) 2009
            2  +# Makefile Spatialite statically linked CLI-tools [Win MSYS/MinGW]
            3  +
            4  +CFLAGS = -Wall -Wextra -Wunused -pedantic -I/mingw32/local/include
            5  +GG = g++ -static
            6  +CC = gcc -static
            7  +
            8  +all: ./static_bin/spatialite.exe ./static_bin/spatialite_tool.exe \
            9  +	./static_bin/spatialite_network.exe ./static_bin/shp_doctor.exe \
           10  +	./static_bin/exif_loader.exe ./static_bin/spatialite_osm_net.exe \
           11  +	./static_bin/spatialite_osm_map.exe ./static_bin/spatialite_gml.exe \
           12  +	./static_bin/spatialite_osm_raw.exe ./static_bin/spatialite_osm_filter.exe \
           13  +	./static_bin/spatialite_convert.exe ./static_bin/spatialite_dxf.exe \
           14  +	./static_bin/spatialite_osm_overpass.exe ./static_bin/shp_sanitize.exe \
           15  +	./static_bin/spatialite_xml_collapse.exe \
           16  +	./static_bin/spatialite_xml_validator.exe \
           17  +	./static_bin/spatialite_xml_load.exe \
           18  +	./static_bin/spatialite_xml2utf8.exe \
           19  +	./static_bin/spatialite_xml_print.exe
           20  +
           21  +./static_bin/spatialite.exe: shell.o 
           22  +	$(GG) shell.o -o ./static_bin/spatialite.exe \
           23  +	/mingw32/local/lib/libspatialite.a \
           24  +	/mingw32/local/lib/libsqlite3.a \
           25  +	/mingw32/local/lib/librttopo.a \
           26  +	/mingw32/local/lib/libxml2.a \
           27  +	/mingw32/local/lib/liblzma.a \
           28  +	/mingw32/local/lib/libproj.a \
           29  +	/mingw32/local/lib/libgeos_c.a \
           30  +	/mingw32/local/lib/libgeos.a \
           31  +	/mingw32/local/lib/libfreexl.a \
           32  +	/mingw32/local/lib/libz.a \
           33  +	/mingw32/local/lib/libiconv.a \
           34  +	-lm -lmsimg32 -lws2_32 -static-libstdc++ -static-libgcc
           35  +	strip --strip-all ./static_bin/spatialite.exe
           36  +
           37  +./static_bin/spatialite_tool.exe: spatialite_tool.o
           38  +	$(GG) spatialite_tool.o -o \
           39  +	./static_bin/spatialite_tool.exe \
           40  +	/mingw32/local/lib/libspatialite.a \
           41  +	/mingw32/local/lib/libsqlite3.a \
           42  +	/mingw32/local/lib/librttopo.a \
           43  +	/mingw32/local/lib/libxml2.a \
           44  +	/mingw32/local/lib/liblzma.a \
           45  +	/mingw32/local/lib/libproj.a \
           46  +	/mingw32/local/lib/libgeos_c.a \
           47  +	/mingw32/local/lib/libgeos.a \
           48  +	/mingw32/local/lib/libfreexl.a \
           49  +	/mingw32/local/lib/libz.a \
           50  +	/mingw32/local/lib/libiconv.a \
           51  +	-lm -lmsimg32 -lws2_32 -static-libstdc++ -static-libgcc
           52  +	strip --strip-all ./static_bin/spatialite_tool.exe
           53  +
           54  +./static_bin/spatialite_convert.exe: spatialite_convert.o
           55  +	$(GG) spatialite_convert.o -o \
           56  +	./static_bin/spatialite_convert.exe \
           57  +	/mingw32/local/lib/libspatialite.a \
           58  +	/mingw32/local/lib/libsqlite3.a \
           59  +	/mingw32/local/lib/librttopo.a \
           60  +	/mingw32/local/lib/libxml2.a \
           61  +	/mingw32/local/lib/liblzma.a \
           62  +	/mingw32/local/lib/libproj.a \
           63  +	/mingw32/local/lib/libgeos_c.a \
           64  +	/mingw32/local/lib/libgeos.a \
           65  +	/mingw32/local/lib/libfreexl.a \
           66  +	/mingw32/local/lib/libz.a \
           67  +	/mingw32/local/lib/libiconv.a \
           68  +	-lm -lmsimg32 -lws2_32 -static-libstdc++ -static-libgcc
           69  +	strip --strip-all ./static_bin/spatialite_convert.exe
           70  +
           71  +./static_bin/spatialite_dxf.exe: spatialite_dxf.o
           72  +	$(GG) spatialite_dxf.o -o \
           73  +	./static_bin/spatialite_dxf.exe \
           74  +	/mingw32/local/lib/libspatialite.a \
           75  +	/mingw32/local/lib/libsqlite3.a \
           76  +	/mingw32/local/lib/librttopo.a \
           77  +	/mingw32/local/lib/libxml2.a \
           78  +	/mingw32/local/lib/liblzma.a \
           79  +	/mingw32/local/lib/libproj.a \
           80  +	/mingw32/local/lib/libgeos_c.a \
           81  +	/mingw32/local/lib/libgeos.a \
           82  +	/mingw32/local/lib/libfreexl.a \
           83  +	/mingw32/local/lib/libz.a \
           84  +	/mingw32/local/lib/libiconv.a \
           85  +	-lm -lmsimg32 -lws2_32 -static-libstdc++ -static-libgcc
           86  +	strip --strip-all ./static_bin/spatialite_dxf.exe
           87  +
           88  +./static_bin/spatialite_network.exe: spatialite_network.o
           89  +	$(GG) spatialite_network.o -o ./static_bin/spatialite_network.exe \
           90  +	/mingw32/local/lib/libspatialite.a \
           91  +	/mingw32/local/lib/libsqlite3.a \
           92  +	/mingw32/local/lib/librttopo.a \
           93  +	/mingw32/local/lib/libxml2.a \
           94  +	/mingw32/local/lib/liblzma.a \
           95  +	/mingw32/local/lib/libproj.a \
           96  +	/mingw32/local/lib/libgeos_c.a \
           97  +	/mingw32/local/lib/libgeos.a \
           98  +	/mingw32/local/lib/libfreexl.a \
           99  +	/mingw32/local/lib/libz.a \
          100  +	/mingw32/local/lib/libiconv.a \
          101  +	-lm -lmsimg32 -lws2_32 -static-libstdc++ -static-libgcc
          102  +	strip --strip-all ./static_bin/spatialite_network.exe
          103  +
          104  +./static_bin/shp_doctor.exe: shp_doctor.o
          105  +	$(GG) shp_doctor.o -o ./static_bin/shp_doctor.exe \
          106  +	/mingw32/local/lib/libspatialite.a \
          107  +	/mingw32/local/lib/libsqlite3.a \
          108  +	/mingw32/local/lib/librttopo.a \
          109  +	/mingw32/local/lib/libxml2.a \
          110  +	/mingw32/local/lib/liblzma.a \
          111  +	/mingw32/local/lib/libproj.a \
          112  +	/mingw32/local/lib/libgeos_c.a \
          113  +	/mingw32/local/lib/libgeos.a \
          114  +	/mingw32/local/lib/libfreexl.a \
          115  +	/mingw32/local/lib/libz.a \
          116  +	/mingw32/local/lib/libiconv.a \
          117  +	-lm -lmsimg32 -lws2_32 -static-libstdc++ -static-libgcc
          118  +	strip --strip-all ./static_bin/shp_doctor.exe
          119  +	
          120  +./static_bin/shp_sanitize.exe: shp_sanitize.o
          121  +	$(GG) shp_sanitize.o -o ./static_bin/shp_sanitize.exe \
          122  +	/mingw32/local/lib/libspatialite.a \
          123  +	/mingw32/local/lib/libsqlite3.a \
          124  +	/mingw32/local/lib/librttopo.a \
          125  +	/mingw32/local/lib/libxml2.a \
          126  +	/mingw32/local/lib/liblzma.a \
          127  +	/mingw32/local/lib/libproj.a \
          128  +	/mingw32/local/lib/libgeos_c.a \
          129  +	/mingw32/local/lib/libgeos.a \
          130  +	/mingw32/local/lib/libfreexl.a \
          131  +	/mingw32/local/lib/libz.a \
          132  +	/mingw32/local/lib/libiconv.a \
          133  +	-lm -lmsimg32 -lws2_32 -static-libstdc++ -static-libgcc
          134  +	strip --strip-all ./static_bin/shp_sanitize.exe
          135  +	
          136  +./static_bin/exif_loader.exe: exif_loader.o
          137  +	$(GG) exif_loader.o -o ./static_bin/exif_loader.exe \
          138  +	/mingw32/local/lib/libspatialite.a \
          139  +	/mingw32/local/lib/libsqlite3.a \
          140  +	/mingw32/local/lib/librttopo.a \
          141  +	/mingw32/local/lib/libxml2.a \
          142  +	/mingw32/local/lib/liblzma.a \
          143  +	/mingw32/local/lib/libproj.a \
          144  +	/mingw32/local/lib/libgeos_c.a \
          145  +	/mingw32/local/lib/libgeos.a \
          146  +	/mingw32/local/lib/libfreexl.a \
          147  +	/mingw32/local/lib/libz.a \
          148  +	/mingw32/local/lib/libiconv.a \
          149  +	-lm -lmsimg32 -lws2_32 -static-libstdc++ -static-libgcc
          150  +	strip --strip-all ./static_bin/exif_loader.exe
          151  +	
          152  +./static_bin/spatialite_osm_net.exe: spatialite_osm_net.o
          153  +	$(GG) spatialite_osm_net.o -o ./static_bin/spatialite_osm_net.exe \
          154  +	/mingw32/local/lib/libspatialite.a \
          155  +	/mingw32/local/lib/libsqlite3.a \
          156  +	/mingw32/local/lib/librttopo.a \
          157  +	/mingw32/local/lib/libxml2.a \
          158  +	/mingw32/local/lib/liblzma.a \
          159  +	/mingw32/local/lib/libproj.a \
          160  +	/mingw32/local/lib/libgeos_c.a \
          161  +	/mingw32/local/lib/libgeos.a \
          162  +	/mingw32/local/lib/libfreexl.a \
          163  +	/mingw32/local/lib/libreadosm.a \
          164  +	/mingw32/local/lib/libiconv.a \
          165  +	/mingw32/local/lib/libexpat.a \
          166  +	/mingw32/local/lib/libz.a \
          167  +	-lm -lmsimg32 -lws2_32 -static-libstdc++ -static-libgcc
          168  +	strip --strip-all ./static_bin/spatialite_osm_net.exe
          169  +
          170  +./static_bin/spatialite_osm_map.exe: spatialite_osm_map.o
          171  +	$(GG) spatialite_osm_map.o -o ./static_bin/spatialite_osm_map.exe \
          172  +	/mingw32/local/lib/libspatialite.a \
          173  +	/mingw32/local/lib/libsqlite3.a \
          174  +	/mingw32/local/lib/librttopo.a \
          175  +	/mingw32/local/lib/libxml2.a \
          176  +	/mingw32/local/lib/liblzma.a \
          177  +	/mingw32/local/lib/libproj.a \
          178  +	/mingw32/local/lib/libgeos_c.a \
          179  +	/mingw32/local/lib/libgeos.a \
          180  +	/mingw32/local/lib/libiconv.a \
          181  +	/mingw32/local/lib/libfreexl.a \
          182  +	/mingw32/local/lib/libreadosm.a \
          183  +	/mingw32/local/lib/libexpat.a \
          184  +	/mingw32/local/lib/libz.a \
          185  +	-lm -lmsimg32 -lws2_32 -static-libstdc++ -static-libgcc
          186  +	strip --strip-all ./static_bin/spatialite_osm_map.exe
          187  +
          188  +./static_bin/spatialite_gml.exe: spatialite_gml.o
          189  +	$(GG) spatialite_gml.o -o ./static_bin/spatialite_gml.exe \
          190  +	/mingw32/local/lib/libspatialite.a \
          191  +	/mingw32/local/lib/libsqlite3.a \
          192  +	/mingw32/local/lib/librttopo.a \
          193  +	/mingw32/local/lib/libxml2.a \
          194  +	/mingw32/local/lib/liblzma.a \
          195  +	/mingw32/local/lib/libproj.a \
          196  +	/mingw32/local/lib/libgeos_c.a \
          197  +	/mingw32/local/lib/libgeos.a \
          198  +	/mingw32/local/lib/libfreexl.a \
          199  +	/mingw32/local/lib/libz.a \
          200  +	/mingw32/local/lib/libiconv.a \
          201  +	/mingw32/local/lib/libexpat.a \
          202  +	-lm -lmsimg32 -lws2_32 -static-libstdc++ -static-libgcc
          203  +	strip --strip-all ./static_bin/spatialite_gml.exe
          204  +
          205  +./static_bin/spatialite_osm_raw.exe: spatialite_osm_raw.o
          206  +	$(GG) spatialite_osm_raw.o -o ./static_bin/spatialite_osm_raw.exe \
          207  +	/mingw32/local/lib/libspatialite.a \
          208  +	/mingw32/local/lib/libsqlite3.a \
          209  +	/mingw32/local/lib/librttopo.a \
          210  +	/mingw32/local/lib/libxml2.a \
          211  +	/mingw32/local/lib/liblzma.a \
          212  +	/mingw32/local/lib/libproj.a \
          213  +	/mingw32/local/lib/libgeos_c.a \
          214  +	/mingw32/local/lib/libgeos.a \
          215  +	/mingw32/local/lib/libfreexl.a \
          216  +	/mingw32/local/lib/libreadosm.a \
          217  +	/mingw32/local/lib/libiconv.a \
          218  +	/mingw32/local/lib/libexpat.a \
          219  +	/mingw32/local/lib/libz.a \
          220  +	-lm -lmsimg32 -lws2_32 -static-libstdc++ -static-libgcc
          221  +	strip --strip-all ./static_bin/spatialite_osm_raw.exe
          222  +
          223  +./static_bin/spatialite_osm_filter.exe: spatialite_osm_filter.o
          224  +	$(GG) spatialite_osm_filter.o -o ./static_bin/spatialite_osm_filter.exe \
          225  +	/mingw32/local/lib/libspatialite.a \
          226  +	/mingw32/local/lib/libsqlite3.a \
          227  +	/mingw32/local/lib/librttopo.a \
          228  +	/mingw32/local/lib/libxml2.a \
          229  +	/mingw32/local/lib/liblzma.a \
          230  +	/mingw32/local/lib/libproj.a \
          231  +	/mingw32/local/lib/libgeos_c.a \
          232  +	/mingw32/local/lib/libgeos.a \
          233  +	/mingw32/local/lib/libfreexl.a \
          234  +	/mingw32/local/lib/libz.a \
          235  +	/mingw32/local/lib/libiconv.a \
          236  +	-lm -lmsimg32 -lws2_32 -static-libstdc++ -static-libgcc 
          237  +	strip --strip-all ./static_bin/spatialite_osm_filter.exe
          238  +
          239  +./static_bin/spatialite_osm_overpass.exe: spatialite_osm_overpass.o
          240  +	$(GG) spatialite_osm_overpass.o -o ./static_bin/spatialite_osm_overpass.exe \
          241  +	/mingw32/local/lib/libspatialite.a \
          242  +	/mingw32/local/lib/libsqlite3.a \
          243  +	/mingw32/local/lib/librttopo.a \
          244  +	/mingw32/local/lib/libxml2.a \
          245  +	/mingw32/local/lib/liblzma.a \
          246  +	/mingw32/local/lib/libproj.a \
          247  +	/mingw32/local/lib/libgeos_c.a \
          248  +	/mingw32/local/lib/libgeos.a \
          249  +	/mingw32/local/lib/libfreexl.a \
          250  +	/mingw32/local/lib/libz.a \
          251  +	/mingw32/local/lib/libiconv.a \
          252  +	-lm -lmsimg32 -lws2_32 -static-libstdc++ -static-libgcc 
          253  +	strip --strip-all ./static_bin/spatialite_osm_overpass.exe
          254  +
          255  +./static_bin/spatialite_xml_collapse.exe: spatialite_xml_collapse.o
          256  +	$(GG) spatialite_xml_collapse.o -o ./static_bin/spatialite_xml_collapse.exe \
          257  +	/mingw32/local/lib/libspatialite.a \
          258  +	/mingw32/local/lib/libsqlite3.a \
          259  +	/mingw32/local/lib/librttopo.a \
          260  +	/mingw32/local/lib/libxml2.a \
          261  +	/mingw32/local/lib/liblzma.a \
          262  +	/mingw32/local/lib/libproj.a \
          263  +	/mingw32/local/lib/libgeos_c.a \
          264  +	/mingw32/local/lib/libgeos.a \
          265  +	/mingw32/local/lib/libfreexl.a \
          266  +	/mingw32/local/lib/libz.a \
          267  +	/mingw32/local/lib/libiconv.a \
          268  +	-lm -lmsimg32 -lws2_32 -static-libstdc++ -static-libgcc 
          269  +	strip --strip-all ./static_bin/spatialite_xml_collapse.exe
          270  +
          271  +./static_bin/spatialite_xml_validator.exe: spatialite_xml_validator.o
          272  +	$(CC) spatialite_xml_validator.o -o ./static_bin/spatialite_xml_validator.exe \
          273  +	/mingw32/local/lib/libxml2.a \
          274  +	/mingw32/local/lib/liblzma.a \
          275  +	/mingw32/local/lib/libz.a \
          276  +	/mingw32/local/lib/libiconv.a \
          277  +	-lm -lws2_32 -static-libgcc 
          278  +	strip --strip-all ./static_bin/spatialite_xml_validator.exe
          279  +
          280  +./static_bin/spatialite_xml_load.exe: spatialite_xml_load.o
          281  +	$(GG) spatialite_xml_load.o -o ./static_bin/spatialite_xml_load.exe \
          282  +	/mingw32/local/lib/libspatialite.a \
          283  +	/mingw32/local/lib/libsqlite3.a \
          284  +	/mingw32/local/lib/librttopo.a \
          285  +	/mingw32/local/lib/libxml2.a \
          286  +	/mingw32/local/lib/liblzma.a \
          287  +	/mingw32/local/lib/libproj.a \
          288  +	/mingw32/local/lib/libgeos_c.a \
          289  +	/mingw32/local/lib/libgeos.a \
          290  +	/mingw32/local/lib/libfreexl.a \
          291  +	/mingw32/local/lib/libexpat.a \
          292  +	/mingw32/local/lib/libz.a \
          293  +	/mingw32/local/lib/libiconv.a \
          294  +	-lm -lmsimg32 -lws2_32 -static-libstdc++ -static-libgcc 
          295  +	strip --strip-all ./static_bin/spatialite_xml_load.exe
          296  +
          297  +./static_bin/spatialite_xml2utf8.exe: spatialite_xml2utf8.o
          298  +	$(CC) spatialite_xml2utf8.o -o ./static_bin/spatialite_xml2utf8.exe \
          299  +	/mingw32/local/lib/libiconv.a \
          300  +	-static-libgcc 
          301  +	strip --strip-all ./static_bin/spatialite_xml2utf8.exe
          302  +
          303  +./static_bin/spatialite_xml_print.exe: spatialite_xml_print.o
          304  +	$(GG) spatialite_xml_print.o -o ./static_bin/spatialite_xml_print.exe \
          305  +	/mingw32/local/lib/libspatialite.a \
          306  +	/mingw32/local/lib/libsqlite3.a \
          307  +	/mingw32/local/lib/librttopo.a \
          308  +	/mingw32/local/lib/libxml2.a \
          309  +	/mingw32/local/lib/liblzma.a \
          310  +	/mingw32/local/lib/libproj.a \
          311  +	/mingw32/local/lib/libgeos_c.a \
          312  +	/mingw32/local/lib/libgeos.a \
          313  +	/mingw32/local/lib/libfreexl.a \
          314  +	/mingw32/local/lib/libz.a \
          315  +	/mingw32/local/lib/libiconv.a \
          316  +	-lm -lmsimg32 -lws2_32 -static-libstdc++ -static-libgcc 
          317  +	strip --strip-all ./static_bin/spatialite_xml_print.exe
          318  +
          319  +shell.o: 
          320  +	$(CC) $(CFLAGS) shell.c -c
          321  +	
          322  +spatialite_tool.o:
          323  +	$(CC) $(CFLAGS) spatialite_tool.c -c
          324  +
          325  +spatialite_network.o:
          326  +	$(CC) $(CFLAGS) spatialite_network.c -c
          327  +
          328  +shp_doctor.o:
          329  +	$(CC) $(CFLAGS) shp_doctor.c -c
          330  +
          331  +shp_sanitize.o:
          332  +	$(CC) $(CFLAGS) shp_sanitize.c -c
          333  +	
          334  +exif_loader.o:
          335  +	$(CC) $(CFLAGS) exif_loader.c -c
          336  +	
          337  +spatialite_osm_net.o:
          338  +	$(CC) $(CFLAGS) spatialite_osm_net.c -c
          339  +	
          340  +spatialite_osm_map.o:
          341  +	$(CC) $(CFLAGS) spatialite_osm_map.c -c
          342  +
          343  +spatialite_gml.o:
          344  +	$(CC) $(CFLAGS) spatialite_gml.c -c
          345  +
          346  +spatialite_osm_raw.o:
          347  +	$(CC) $(CFLAGS) spatialite_osm_raw.c -c
          348  +
          349  +spatialite_osm_filter.o:
          350  +	$(CC) $(CFLAGS) spatialite_osm_filter.c -c
          351  +
          352  +spatialite_osm_overpass.o:
          353  +	$(CC) $(CFLAGS) spatialite_osm_overpass.c -c
          354  +
          355  +spatialite_xml_collapse.o:
          356  +	$(CC) $(CFLAGS) spatialite_xml_collapse.c -c
          357  +
          358  +spatialite_xml_validator.o:
          359  +	$(CC) $(CFLAGS) spatialite_xml_validator.c -c
          360  +
          361  +spatialite_xml_load.o:
          362  +	$(CC) $(CFLAGS) spatialite_xml_load.c -c
          363  +
          364  +spatialite_xml2utf8.o:
          365  +	$(CC) $(CFLAGS) spatialite_xml2utf8.c -c
          366  +
          367  +
          368  +spatialite_xml_print.o:
          369  +	$(CC) $(CFLAGS) spatialite_xml_print.c -c

Added Makefile-static-mingw64.

            1  +# SandroFurieri (c) 2009
            2  +# Makefile Spatialite statically linked CLI-tools [Win MSYS/MinGW]
            3  +
            4  +CFLAGS = -Wall -Wextra -Wunused -pedantic -I/mingw64/local/include
            5  +GG = g++ -static
            6  +CC = gcc -static
            7  +
            8  +all: ./static_bin/spatialite.exe ./static_bin/spatialite_tool.exe \
            9  +	./static_bin/spatialite_network.exe ./static_bin/shp_doctor.exe \
           10  +	./static_bin/exif_loader.exe ./static_bin/spatialite_osm_net.exe \
           11  +	./static_bin/spatialite_osm_map.exe ./static_bin/spatialite_gml.exe \
           12  +	./static_bin/spatialite_osm_raw.exe ./static_bin/spatialite_osm_filter.exe \
           13  +	./static_bin/spatialite_convert.exe ./static_bin/spatialite_dxf.exe \
           14  +	./static_bin/spatialite_osm_overpass.exe ./static_bin/shp_sanitize.exe \
           15  +	./static_bin/spatialite_xml_collapse.exe \
           16  +	./static_bin/spatialite_xml_validator.exe \
           17  +	./static_bin/spatialite_xml_load.exe \
           18  +	./static_bin/spatialite_xml2utf8.exe \
           19  +	./static_bin/spatialite_xml_print.exe
           20  +
           21  +./static_bin/spatialite.exe: shell.o 
           22  +	$(GG) shell.o -o ./static_bin/spatialite.exe \
           23  +	/mingw64/local/lib/libspatialite.a \
           24  +	/mingw64/local/lib/libsqlite3.a \
           25  +	/mingw64/local/lib/librttopo.a \
           26  +	/mingw64/local/lib/libxml2.a \
           27  +	/mingw64/local/lib/liblzma.a \
           28  +	/mingw64/local/lib/libproj.a \
           29  +	/mingw64/local/lib/libgeos_c.a \
           30  +	/mingw64/local/lib/libgeos.a \
           31  +	/mingw64/local/lib/libfreexl.a \
           32  +	/mingw64/local/lib/libz.a \
           33  +	/mingw64/local/lib/libiconv.a \
           34  +	-lm -lmsimg32 -lws2_32 -static-libstdc++ -static-libgcc
           35  +	strip --strip-all ./static_bin/spatialite.exe
           36  +
           37  +./static_bin/spatialite_tool.exe: spatialite_tool.o
           38  +	$(GG) spatialite_tool.o -o \
           39  +	./static_bin/spatialite_tool.exe \
           40  +	/mingw64/local/lib/libspatialite.a \
           41  +	/mingw64/local/lib/libsqlite3.a \
           42  +	/mingw64/local/lib/librttopo.a \
           43  +	/mingw64/local/lib/libxml2.a \
           44  +	/mingw64/local/lib/liblzma.a \
           45  +	/mingw64/local/lib/libproj.a \
           46  +	/mingw64/local/lib/libgeos_c.a \
           47  +	/mingw64/local/lib/libgeos.a \
           48  +	/mingw64/local/lib/libfreexl.a \
           49  +	/mingw64/local/lib/libz.a \
           50  +	/mingw64/local/lib/libiconv.a \
           51  +	-lm -lmsimg32 -lws2_32 -static-libstdc++ -static-libgcc
           52  +	strip --strip-all ./static_bin/spatialite_tool.exe
           53  +
           54  +./static_bin/spatialite_convert.exe: spatialite_convert.o
           55  +	$(GG) spatialite_convert.o -o \
           56  +	./static_bin/spatialite_convert.exe \
           57  +	/mingw64/local/lib/libspatialite.a \
           58  +	/mingw64/local/lib/libsqlite3.a \
           59  +	/mingw64/local/lib/librttopo.a \
           60  +	/mingw64/local/lib/libxml2.a \
           61  +	/mingw64/local/lib/liblzma.a \
           62  +	/mingw64/local/lib/libproj.a \
           63  +	/mingw64/local/lib/libgeos_c.a \
           64  +	/mingw64/local/lib/libgeos.a \
           65  +	/mingw64/local/lib/libfreexl.a \
           66  +	/mingw64/local/lib/libz.a \
           67  +	/mingw64/local/lib/libiconv.a \
           68  +	-lm -lmsimg32 -lws2_32 -static-libstdc++ -static-libgcc
           69  +	strip --strip-all ./static_bin/spatialite_convert.exe
           70  +
           71  +./static_bin/spatialite_dxf.exe: spatialite_dxf.o
           72  +	$(GG) spatialite_dxf.o -o \
           73  +	./static_bin/spatialite_dxf.exe \
           74  +	/mingw64/local/lib/libspatialite.a \
           75  +	/mingw64/local/lib/libsqlite3.a \
           76  +	/mingw64/local/lib/librttopo.a \
           77  +	/mingw64/local/lib/libxml2.a \
           78  +	/mingw64/local/lib/liblzma.a \
           79  +	/mingw64/local/lib/libproj.a \
           80  +	/mingw64/local/lib/libgeos_c.a \
           81  +	/mingw64/local/lib/libgeos.a \
           82  +	/mingw64/local/lib/libfreexl.a \
           83  +	/mingw64/local/lib/libz.a \
           84  +	/mingw64/local/lib/libiconv.a \
           85  +	-lm -lmsimg32 -lws2_32 -static-libstdc++ -static-libgcc
           86  +	strip --strip-all ./static_bin/spatialite_dxf.exe
           87  +
           88  +./static_bin/spatialite_network.exe: spatialite_network.o
           89  +	$(GG) spatialite_network.o -o ./static_bin/spatialite_network.exe \
           90  +	/mingw64/local/lib/libspatialite.a \
           91  +	/mingw64/local/lib/libsqlite3.a \
           92  +	/mingw64/local/lib/librttopo.a \
           93  +	/mingw64/local/lib/libxml2.a \
           94  +	/mingw64/local/lib/liblzma.a \
           95  +	/mingw64/local/lib/libproj.a \
           96  +	/mingw64/local/lib/libgeos_c.a \
           97  +	/mingw64/local/lib/libgeos.a \
           98  +	/mingw64/local/lib/libfreexl.a \
           99  +	/mingw64/local/lib/libz.a \
          100  +	/mingw64/local/lib/libiconv.a \
          101  +	-lm -lmsimg32 -lws2_32 -static-libstdc++ -static-libgcc
          102  +	strip --strip-all ./static_bin/spatialite_network.exe
          103  +
          104  +./static_bin/shp_doctor.exe: shp_doctor.o
          105  +	$(GG) shp_doctor.o -o ./static_bin/shp_doctor.exe \
          106  +	/mingw64/local/lib/libspatialite.a \
          107  +	/mingw64/local/lib/libsqlite3.a \
          108  +	/mingw64/local/lib/librttopo.a \
          109  +	/mingw64/local/lib/libxml2.a \
          110  +	/mingw64/local/lib/liblzma.a \
          111  +	/mingw64/local/lib/libproj.a \
          112  +	/mingw64/local/lib/libgeos_c.a \
          113  +	/mingw64/local/lib/libgeos.a \
          114  +	/mingw64/local/lib/libfreexl.a \
          115  +	/mingw64/local/lib/libz.a \
          116  +	/mingw64/local/lib/libiconv.a \
          117  +	-lm -lmsimg32 -lws2_32 -static-libstdc++ -static-libgcc
          118  +	strip --strip-all ./static_bin/shp_doctor.exe
          119  +	
          120  +./static_bin/shp_sanitize.exe: shp_sanitize.o
          121  +	$(GG) shp_sanitize.o -o ./static_bin/shp_sanitize.exe \
          122  +	/mingw64/local/lib/libspatialite.a \
          123  +	/mingw64/local/lib/libsqlite3.a \
          124  +	/mingw64/local/lib/librttopo.a \
          125  +	/mingw64/local/lib/libxml2.a \
          126  +	/mingw64/local/lib/liblzma.a \
          127  +	/mingw64/local/lib/libproj.a \
          128  +	/mingw64/local/lib/libgeos_c.a \
          129  +	/mingw64/local/lib/libgeos.a \
          130  +	/mingw64/local/lib/libfreexl.a \
          131  +	/mingw64/local/lib/libz.a \
          132  +	/mingw64/local/lib/libiconv.a \
          133  +	-lm -lmsimg32 -lws2_32 -static-libstdc++ -static-libgcc
          134  +	strip --strip-all ./static_bin/shp_sanitize.exe
          135  +	
          136  +./static_bin/exif_loader.exe: exif_loader.o
          137  +	$(GG) exif_loader.o -o ./static_bin/exif_loader.exe \
          138  +	/mingw64/local/lib/libspatialite.a \
          139  +	/mingw64/local/lib/libsqlite3.a \
          140  +	/mingw64/local/lib/librttopo.a \
          141  +	/mingw64/local/lib/libxml2.a \
          142  +	/mingw64/local/lib/liblzma.a \
          143  +	/mingw64/local/lib/libproj.a \
          144  +	/mingw64/local/lib/libgeos_c.a \
          145  +	/mingw64/local/lib/libgeos.a \
          146  +	/mingw64/local/lib/libfreexl.a \
          147  +	/mingw64/local/lib/libz.a \
          148  +	/mingw64/local/lib/libiconv.a \
          149  +	-lm -lmsimg32 -lws2_32 -static-libstdc++ -static-libgcc
          150  +	strip --strip-all ./static_bin/exif_loader.exe
          151  +	
          152  +./static_bin/spatialite_osm_net.exe: spatialite_osm_net.o
          153  +	$(GG) spatialite_osm_net.o -o ./static_bin/spatialite_osm_net.exe \
          154  +	/mingw64/local/lib/libspatialite.a \
          155  +	/mingw64/local/lib/libsqlite3.a \
          156  +	/mingw64/local/lib/librttopo.a \
          157  +	/mingw64/local/lib/libxml2.a \
          158  +	/mingw64/local/lib/liblzma.a \
          159  +	/mingw64/local/lib/libproj.a \
          160  +	/mingw64/local/lib/libgeos_c.a \
          161  +	/mingw64/local/lib/libgeos.a \
          162  +	/mingw64/local/lib/libfreexl.a \
          163  +	/mingw64/local/lib/libreadosm.a \
          164  +	/mingw64/local/lib/libiconv.a \
          165  +	/mingw64/local/lib/libexpat.a \
          166  +	/mingw64/local/lib/libz.a \
          167  +	-lm -lmsimg32 -lws2_32 -static-libstdc++ -static-libgcc
          168  +	strip --strip-all ./static_bin/spatialite_osm_net.exe
          169  +
          170  +./static_bin/spatialite_osm_map.exe: spatialite_osm_map.o
          171  +	$(GG) spatialite_osm_map.o -o ./static_bin/spatialite_osm_map.exe \
          172  +	/mingw64/local/lib/libspatialite.a \
          173  +	/mingw64/local/lib/libsqlite3.a \
          174  +	/mingw64/local/lib/librttopo.a \
          175  +	/mingw64/local/lib/libxml2.a \
          176  +	/mingw64/local/lib/liblzma.a \
          177  +	/mingw64/local/lib/libproj.a \
          178  +	/mingw64/local/lib/libgeos_c.a \
          179  +	/mingw64/local/lib/libgeos.a \
          180  +	/mingw64/local/lib/libiconv.a \
          181  +	/mingw64/local/lib/libfreexl.a \
          182  +	/mingw64/local/lib/libreadosm.a \
          183  +	/mingw64/local/lib/libexpat.a \
          184  +	/mingw64/local/lib/libz.a \
          185  +	-lm -lmsimg32 -lws2_32 -static-libstdc++ -static-libgcc
          186  +	strip --strip-all ./static_bin/spatialite_osm_map.exe
          187  +
          188  +./static_bin/spatialite_gml.exe: spatialite_gml.o
          189  +	$(GG) spatialite_gml.o -o ./static_bin/spatialite_gml.exe \
          190  +	/mingw64/local/lib/libspatialite.a \
          191  +	/mingw64/local/lib/libsqlite3.a \
          192  +	/mingw64/local/lib/librttopo.a \
          193  +	/mingw64/local/lib/libxml2.a \
          194  +	/mingw64/local/lib/liblzma.a \
          195  +	/mingw64/local/lib/libproj.a \
          196  +	/mingw64/local/lib/libgeos_c.a \
          197  +	/mingw64/local/lib/libgeos.a \
          198  +	/mingw64/local/lib/libfreexl.a \
          199  +	/mingw64/local/lib/libz.a \
          200  +	/mingw64/local/lib/libiconv.a \
          201  +	/mingw64/local/lib/libexpat.a \
          202  +	-lm -lmsimg32 -lws2_32 -static-libstdc++ -static-libgcc
          203  +	strip --strip-all ./static_bin/spatialite_gml.exe
          204  +
          205  +./static_bin/spatialite_osm_raw.exe: spatialite_osm_raw.o
          206  +	$(GG) spatialite_osm_raw.o -o ./static_bin/spatialite_osm_raw.exe \
          207  +	/mingw64/local/lib/libspatialite.a \
          208  +	/mingw64/local/lib/libsqlite3.a \
          209  +	/mingw64/local/lib/librttopo.a \
          210  +	/mingw64/local/lib/libxml2.a \
          211  +	/mingw64/local/lib/liblzma.a \
          212  +	/mingw64/local/lib/libproj.a \
          213  +	/mingw64/local/lib/libgeos_c.a \
          214  +	/mingw64/local/lib/libgeos.a \
          215  +	/mingw64/local/lib/libfreexl.a \
          216  +	/mingw64/local/lib/libreadosm.a \
          217  +	/mingw64/local/lib/libiconv.a \
          218  +	/mingw64/local/lib/libexpat.a \
          219  +	/mingw64/local/lib/libz.a \
          220  +	-lm -lmsimg32 -lws2_32 -static-libstdc++ -static-libgcc
          221  +	strip --strip-all ./static_bin/spatialite_osm_raw.exe
          222  +
          223  +./static_bin/spatialite_osm_filter.exe: spatialite_osm_filter.o
          224  +	$(GG) spatialite_osm_filter.o -o ./static_bin/spatialite_osm_filter.exe \
          225  +	/mingw64/local/lib/libspatialite.a \
          226  +	/mingw64/local/lib/libsqlite3.a \
          227  +	/mingw64/local/lib/librttopo.a \
          228  +	/mingw64/local/lib/libxml2.a \
          229  +	/mingw64/local/lib/liblzma.a \
          230  +	/mingw64/local/lib/libproj.a \
          231  +	/mingw64/local/lib/libgeos_c.a \
          232  +	/mingw64/local/lib/libgeos.a \
          233  +	/mingw64/local/lib/libfreexl.a \
          234  +	/mingw64/local/lib/libz.a \
          235  +	/mingw64/local/lib/libiconv.a \
          236  +	-lm -lmsimg32 -lws2_32 -static-libstdc++ -static-libgcc 
          237  +	strip --strip-all ./static_bin/spatialite_osm_filter.exe
          238  +
          239  +./static_bin/spatialite_osm_overpass.exe: spatialite_osm_overpass.o
          240  +	$(GG) spatialite_osm_overpass.o -o ./static_bin/spatialite_osm_overpass.exe \
          241  +	/mingw64/local/lib/libspatialite.a \
          242  +	/mingw64/local/lib/libsqlite3.a \
          243  +	/mingw64/local/lib/librttopo.a \
          244  +	/mingw64/local/lib/libxml2.a \
          245  +	/mingw64/local/lib/liblzma.a \
          246  +	/mingw64/local/lib/libproj.a \
          247  +	/mingw64/local/lib/libgeos_c.a \
          248  +	/mingw64/local/lib/libgeos.a \
          249  +	/mingw64/local/lib/libfreexl.a \
          250  +	/mingw64/local/lib/libz.a \
          251  +	/mingw64/local/lib/libiconv.a \
          252  +	-lm -lmsimg32 -lws2_32 -static-libstdc++ -static-libgcc 
          253  +	strip --strip-all ./static_bin/spatialite_osm_overpass.exe
          254  +
          255  +./static_bin/spatialite_xml_collapse.exe: spatialite_xml_collapse.o
          256  +	$(GG) spatialite_xml_collapse.o -o ./static_bin/spatialite_xml_collapse.exe \
          257  +	/mingw64/local/lib/libspatialite.a \
          258  +	/mingw64/local/lib/libsqlite3.a \
          259  +	/mingw64/local/lib/librttopo.a \
          260  +	/mingw64/local/lib/libxml2.a \
          261  +	/mingw64/local/lib/liblzma.a \
          262  +	/mingw64/local/lib/libproj.a \
          263  +	/mingw64/local/lib/libgeos_c.a \
          264  +	/mingw64/local/lib/libgeos.a \
          265  +	/mingw64/local/lib/libfreexl.a \
          266  +	/mingw64/local/lib/libz.a \
          267  +	/mingw64/local/lib/libiconv.a \
          268  +	-lm -lmsimg32 -lws2_32 -static-libstdc++ -static-libgcc 
          269  +	strip --strip-all ./static_bin/spatialite_xml_collapse.exe
          270  +
          271  +./static_bin/spatialite_xml_validator.exe: spatialite_xml_validator.o
          272  +	$(CC) spatialite_xml_validator.o -o ./static_bin/spatialite_xml_validator.exe \
          273  +	/mingw64/local/lib/libxml2.a \
          274  +	/mingw64/local/lib/liblzma.a \
          275  +	/mingw64/local/lib/libz.a \
          276  +	/mingw64/local/lib/libiconv.a \
          277  +	-lm -lws2_32 -static-libgcc 
          278  +	strip --strip-all ./static_bin/spatialite_xml_validator.exe
          279  +
          280  +./static_bin/spatialite_xml_load.exe: spatialite_xml_load.o
          281  +	$(GG) spatialite_xml_load.o -o ./static_bin/spatialite_xml_load.exe \
          282  +	/mingw64/local/lib/libspatialite.a \
          283  +	/mingw64/local/lib/libsqlite3.a \
          284  +	/mingw64/local/lib/librttopo.a \
          285  +	/mingw64/local/lib/libxml2.a \
          286  +	/mingw64/local/lib/liblzma.a \
          287  +	/mingw64/local/lib/libproj.a \
          288  +	/mingw64/local/lib/libgeos_c.a \
          289  +	/mingw64/local/lib/libgeos.a \
          290  +	/mingw64/local/lib/libfreexl.a \
          291  +	/mingw64/local/lib/libexpat.a \
          292  +	/mingw64/local/lib/libz.a \
          293  +	/mingw64/local/lib/libiconv.a \
          294  +	-lm -lmsimg32 -lws2_32 -static-libstdc++ -static-libgcc 
          295  +	strip --strip-all ./static_bin/spatialite_xml_load.exe
          296  +
          297  +./static_bin/spatialite_xml2utf8.exe: spatialite_xml2utf8.o
          298  +	$(CC) spatialite_xml2utf8.o -o ./static_bin/spatialite_xml2utf8.exe \
          299  +	/mingw64/local/lib/libiconv.a \
          300  +	-static-libgcc 
          301  +	strip --strip-all ./static_bin/spatialite_xml_load.exe
          302  +
          303  +./static_bin/spatialite_xml_print.exe: spatialite_xml_print.o
          304  +	$(GG) spatialite_xml_print.o -o ./static_bin/spatialite_xml_print.exe \
          305  +	/mingw64/local/lib/libspatialite.a \
          306  +	/mingw64/local/lib/libsqlite3.a \
          307  +	/mingw64/local/lib/librttopo.a \
          308  +	/mingw64/local/lib/libxml2.a \
          309  +	/mingw64/local/lib/liblzma.a \
          310  +	/mingw64/local/lib/libproj.a \
          311  +	/mingw64/local/lib/libgeos_c.a \
          312  +	/mingw64/local/lib/libgeos.a \
          313  +	/mingw64/local/lib/libfreexl.a \
          314  +	/mingw64/local/lib/libz.a \
          315  +	/mingw64/local/lib/libiconv.a \
          316  +	-lm -lmsimg32 -lws2_32 -static-libstdc++ -static-libgcc 
          317  +	strip --strip-all ./static_bin/spatialite_xml_print.exe
          318  +
          319  +shell.o: 
          320  +	$(CC) $(CFLAGS) shell.c -c
          321  +	
          322  +spatialite_tool.o:
          323  +	$(CC) $(CFLAGS) spatialite_tool.c -c
          324  +
          325  +spatialite_network.o:
          326  +	$(CC) $(CFLAGS) spatialite_network.c -c
          327  +
          328  +shp_doctor.o:
          329  +	$(CC) $(CFLAGS) shp_doctor.c -c
          330  +
          331  +shp_sanitize.o:
          332  +	$(CC) $(CFLAGS) shp_sanitize.c -c
          333  +	
          334  +exif_loader.o:
          335  +	$(CC) $(CFLAGS) exif_loader.c -c
          336  +	
          337  +spatialite_osm_net.o:
          338  +	$(CC) $(CFLAGS) spatialite_osm_net.c -c
          339  +	
          340  +spatialite_osm_map.o:
          341  +	$(CC) $(CFLAGS) spatialite_osm_map.c -c
          342  +
          343  +spatialite_gml.o:
          344  +	$(CC) $(CFLAGS) spatialite_gml.c -c
          345  +
          346  +spatialite_osm_raw.o:
          347  +	$(CC) $(CFLAGS) spatialite_osm_raw.c -c
          348  +
          349  +spatialite_osm_filter.o:
          350  +	$(CC) $(CFLAGS) spatialite_osm_filter.c -c
          351  +
          352  +spatialite_osm_overpass.o:
          353  +	$(CC) $(CFLAGS) spatialite_osm_overpass.c -c
          354  +
          355  +spatialite_xml_collapse.o:
          356  +	$(CC) $(CFLAGS) spatialite_xml_collapse.c -c
          357  +
          358  +spatialite_xml_validator.o:
          359  +	$(CC) $(CFLAGS) spatialite_xml_validator.c -c
          360  +
          361  +spatialite_xml_load.o:
          362  +	$(CC) $(CFLAGS) spatialite_xml_load.c -c
          363  +
          364  +spatialite_xml2utf8.o:
          365  +	$(CC) $(CFLAGS) spatialite_xml2utf8.c -c
          366  +
          367  +spatialite_xml_print.o:
          368  +	$(CC) $(CFLAGS) spatialite_xml_print.c -c

Changes to Makefile.am.

     1      1   ACLOCAL_AMFLAGS = -I m4
     2      2   
     3      3   if NO_READOSM
     4      4   bin_PROGRAMS = spatialite \
     5      5   	spatialite_tool \
     6      6   	spatialite_network \
     7         -	shp_doctor \
            7  +	shp_doctor shp_sanitize \
     8      8   	exif_loader \
     9      9   	spatialite_osm_filter \
    10     10   	spatialite_gml \
    11     11   	spatialite_convert \
    12     12   	spatialite_dxf \
    13     13   	spatialite_xml_validator \
    14     14   	spatialite_xml_load \
           15  +	spatialite_xml2utf8 \
    15     16   	spatialite_xml_collapse \
    16     17   	spatialite_xml_print \
    17         -	spatialite_osm_overpass
           18  +	spatialite_osm_overpass \
           19  +	spatialite_dem
    18     20   else
    19     21   bin_PROGRAMS = spatialite \
    20     22   	spatialite_tool \
    21     23   	spatialite_network \
    22         -	shp_doctor \
           24  +	shp_doctor shp_sanitize \
    23     25   	exif_loader \
    24     26   	spatialite_osm_net \
    25     27   	spatialite_osm_map \
    26     28   	spatialite_osm_raw \
    27     29   	spatialite_osm_filter \
    28     30   	spatialite_gml \
    29     31   	spatialite_convert \
    30     32   	spatialite_dxf \
    31     33   	spatialite_xml_validator \
    32     34   	spatialite_xml_load \
           35  +	spatialite_xml2utf8 \
    33     36   	spatialite_xml_collapse \
    34     37   	spatialite_xml_print \
    35         -	spatialite_osm_overpass
           38  +	spatialite_osm_overpass \
           39  +	spatialite_dem
    36     40   endif
    37     41   
    38         -AM_CPPFLAGS = @CFLAGS@ @LIBXML2_CFLAGS@
           42  +AM_CPPFLAGS = @CFLAGS@ @CPPFLAGS@ @LIBXML2_CFLAGS@
    39     43   AM_CPPFLAGS += -I$(top_srcdir)
    40     44   
    41     45   spatialite_SOURCES = shell.c
    42     46   spatialite_tool_SOURCES = spatialite_tool.c
    43     47   spatialite_network_SOURCES = spatialite_network.c
    44     48   shp_doctor_SOURCES = shp_doctor.c
           49  +shp_sanitize_SOURCES = shp_sanitize.c
    45     50   exif_loader_SOURCES = exif_loader.c
    46     51   spatialite_xml_validator_SOURCES = spatialite_xml_validator.c
    47     52   spatialite_xml_load_SOURCES = spatialite_xml_load.c
           53  +spatialite_xml2utf8_SOURCES = spatialite_xml2utf8.c
    48     54   spatialite_xml_collapse_SOURCES = spatialite_xml_collapse.c
    49     55   spatialite_xml_print_SOURCES = spatialite_xml_print.c 
    50     56   if NO_READOSM
    51     57   else
    52     58   spatialite_osm_net_SOURCES = spatialite_osm_net.c
    53     59   spatialite_osm_map_SOURCES = spatialite_osm_map.c
    54     60   spatialite_osm_raw_SOURCES = spatialite_osm_raw.c
    55     61   endif
    56     62   spatialite_osm_filter_SOURCES = spatialite_osm_filter.c
    57     63   spatialite_gml_SOURCES = spatialite_gml.c
    58     64   spatialite_osm_overpass_SOURCES = spatialite_osm_overpass.c
           65  +spatialite_dem_SOURCES = spatialite_dem.c
    59     66   
    60     67   spatialite_osm_map_LDADD = @LIBSPATIALITE_LIBS@ \
    61     68   	@LIBFREEXL_LIBS@ @LIBREADOSM_LIBS@ 
    62     69   spatialite_osm_overpass_LDADD = @LIBSPATIALITE_LIBS@ \
    63     70   	@LIBFREEXL_LIBS@ @LIBXML2_LIBS@ 
    64     71   spatialite_osm_raw_LDADD = @LIBSPATIALITE_LIBS@ \
    65     72   	@LIBFREEXL_LIBS@ @LIBREADOSM_LIBS@
    66     73   spatialite_osm_net_LDADD = @LIBSPATIALITE_LIBS@ \
    67     74   	@LIBFREEXL_LIBS@ @LIBREADOSM_LIBS@
    68     75   spatialite_gml_LDADD = @LIBSPATIALITE_LIBS@ \
    69     76   	@LIBFREEXL_LIBS@ \
    70     77   	-lexpat 
           78  +spatialite_dem_LDADD = @LIBSPATIALITE_LIBS@ 
    71     79   spatialite_LDADD = @LIBSPATIALITE_LIBS@ \
    72     80   	@LIBFREEXL_LIBS@ \
    73     81   	@READLINE_LIBS@
    74     82   spatialite_xml_validator_LDADD = @LIBXML2_LIBS@
    75     83   spatialite_xml_load_LDADD = @LIBSPATIALITE_LIBS@ \
    76     84   	-lexpat
    77     85   spatialite_xml_collapse_LDADD = @LIBSPATIALITE_LIBS@
................................................................................
    78     86   spatialite_xml_print_LADD = @LIBSPATIALIATE_LIBS@
    79     87   LDADD = @LIBSPATIALITE_LIBS@ \
    80     88   	@LIBFREEXL_LIBS@
    81     89   
    82     90   EXTRA_DIST = makefile.vc nmake.opt \
    83     91   	config-msvc.h \
    84     92   	Makefile-static-MinGW \
           93  +	Makefile-static-mingw32 \
           94  +	Makefile-static-mingw64 \
    85     95   	Makefile-static-Linux \
    86     96   	Makefile-static-MacOsX
    87     97   
    88         -AUTOMAKE_OPTIONS = dist-zip
           98  +AUTOMAKE_OPTIONS = dist-zip foreign
    89     99   

Changes to Makefile.in.

     1         -# Makefile.in generated by automake 1.13.4 from Makefile.am.
            1  +# Makefile.in generated by automake 1.15 from Makefile.am.
     2      2   # @configure_input@
     3      3   
     4         -# Copyright (C) 1994-2013 Free Software Foundation, Inc.
            4  +# Copyright (C) 1994-2014 Free Software Foundation, Inc.
     5      5   
     6      6   # This Makefile.in is free software; the Free Software Foundation
     7      7   # gives unlimited permission to copy and/or distribute it,
     8      8   # with or without modifications, as long as this notice is preserved.
     9      9   
    10     10   # This program is distributed in the hope that it will be useful,
    11     11   # but WITHOUT ANY WARRANTY, to the extent permitted by law; without
    12     12   # even the implied warranty of MERCHANTABILITY or FITNESS FOR A
    13     13   # PARTICULAR PURPOSE.
    14     14   
    15     15   @SET_MAKE@
    16     16   
    17     17   VPATH = @srcdir@
    18         -am__is_gnu_make = test -n '$(MAKEFILE_LIST)' && test -n '$(MAKELEVEL)'
           18  +am__is_gnu_make = { \
           19  +  if test -z '$(MAKELEVEL)'; then \
           20  +    false; \
           21  +  elif test -n '$(MAKE_HOST)'; then \
           22  +    true; \
           23  +  elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \
           24  +    true; \
           25  +  else \
           26  +    false; \
           27  +  fi; \
           28  +}
    19     29   am__make_running_with_option = \
    20     30     case $${target_option-} in \
    21     31         ?) ;; \
    22     32         *) echo "am__make_running_with_option: internal error: invalid" \
    23     33                 "target option '$${target_option-}' specified" >&2; \
    24     34            exit 1;; \
    25     35     esac; \
................................................................................
    77     87   PRE_UNINSTALL = :
    78     88   POST_UNINSTALL = :
    79     89   build_triplet = @build@
    80     90   host_triplet = @host@
    81     91   @NO_READOSM_FALSE@bin_PROGRAMS = spatialite$(EXEEXT) \
    82     92   @NO_READOSM_FALSE@	spatialite_tool$(EXEEXT) \
    83     93   @NO_READOSM_FALSE@	spatialite_network$(EXEEXT) \
    84         -@NO_READOSM_FALSE@	shp_doctor$(EXEEXT) exif_loader$(EXEEXT) \
           94  +@NO_READOSM_FALSE@	shp_doctor$(EXEEXT) shp_sanitize$(EXEEXT) \
           95  +@NO_READOSM_FALSE@	exif_loader$(EXEEXT) \
    85     96   @NO_READOSM_FALSE@	spatialite_osm_net$(EXEEXT) \
    86     97   @NO_READOSM_FALSE@	spatialite_osm_map$(EXEEXT) \
    87     98   @NO_READOSM_FALSE@	spatialite_osm_raw$(EXEEXT) \
    88     99   @NO_READOSM_FALSE@	spatialite_osm_filter$(EXEEXT) \
    89    100   @NO_READOSM_FALSE@	spatialite_gml$(EXEEXT) \
    90    101   @NO_READOSM_FALSE@	spatialite_convert$(EXEEXT) \
    91    102   @NO_READOSM_FALSE@	spatialite_dxf$(EXEEXT) \
    92    103   @NO_READOSM_FALSE@	spatialite_xml_validator$(EXEEXT) \
    93    104   @NO_READOSM_FALSE@	spatialite_xml_load$(EXEEXT) \
          105  +@NO_READOSM_FALSE@	spatialite_xml2utf8$(EXEEXT) \
    94    106   @NO_READOSM_FALSE@	spatialite_xml_collapse$(EXEEXT) \
    95    107   @NO_READOSM_FALSE@	spatialite_xml_print$(EXEEXT) \
    96         -@NO_READOSM_FALSE@	spatialite_osm_overpass$(EXEEXT)
          108  +@NO_READOSM_FALSE@	spatialite_osm_overpass$(EXEEXT) \
          109  +@NO_READOSM_FALSE@	spatialite_dem$(EXEEXT)
    97    110   @NO_READOSM_TRUE@bin_PROGRAMS = spatialite$(EXEEXT) \
    98    111   @NO_READOSM_TRUE@	spatialite_tool$(EXEEXT) \
    99    112   @NO_READOSM_TRUE@	spatialite_network$(EXEEXT) \
   100         -@NO_READOSM_TRUE@	shp_doctor$(EXEEXT) exif_loader$(EXEEXT) \
          113  +@NO_READOSM_TRUE@	shp_doctor$(EXEEXT) shp_sanitize$(EXEEXT) \
          114  +@NO_READOSM_TRUE@	exif_loader$(EXEEXT) \
   101    115   @NO_READOSM_TRUE@	spatialite_osm_filter$(EXEEXT) \
   102    116   @NO_READOSM_TRUE@	spatialite_gml$(EXEEXT) \
   103    117   @NO_READOSM_TRUE@	spatialite_convert$(EXEEXT) \
   104    118   @NO_READOSM_TRUE@	spatialite_dxf$(EXEEXT) \
   105    119   @NO_READOSM_TRUE@	spatialite_xml_validator$(EXEEXT) \
   106    120   @NO_READOSM_TRUE@	spatialite_xml_load$(EXEEXT) \
          121  +@NO_READOSM_TRUE@	spatialite_xml2utf8$(EXEEXT) \
   107    122   @NO_READOSM_TRUE@	spatialite_xml_collapse$(EXEEXT) \
   108    123   @NO_READOSM_TRUE@	spatialite_xml_print$(EXEEXT) \
   109         -@NO_READOSM_TRUE@	spatialite_osm_overpass$(EXEEXT)
          124  +@NO_READOSM_TRUE@	spatialite_osm_overpass$(EXEEXT) \
          125  +@NO_READOSM_TRUE@	spatialite_dem$(EXEEXT)
   110    126   subdir = .
   111         -DIST_COMMON = INSTALL NEWS README AUTHORS ChangeLog \
   112         -	$(srcdir)/Makefile.in $(srcdir)/Makefile.am \
   113         -	$(top_srcdir)/configure $(am__configure_deps) \
   114         -	$(srcdir)/config.h.in depcomp COPYING config.guess config.sub \
   115         -	install-sh missing ltmain.sh
   116    127   ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
   117    128   am__aclocal_m4_deps = $(top_srcdir)/m4/libtool.m4 \
   118    129   	$(top_srcdir)/m4/ltoptions.m4 $(top_srcdir)/m4/ltsugar.m4 \
   119    130   	$(top_srcdir)/m4/ltversion.m4 $(top_srcdir)/m4/lt~obsolete.m4 \
   120    131   	$(top_srcdir)/configure.ac
   121    132   am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
   122    133   	$(ACLOCAL_M4)
          134  +DIST_COMMON = $(srcdir)/Makefile.am $(top_srcdir)/configure \
          135  +	$(am__configure_deps) $(am__DIST_COMMON)
   123    136   am__CONFIG_DISTCLEAN_FILES = config.status config.cache config.log \
   124    137    configure.lineno config.status.lineno
   125    138   mkinstalldirs = $(install_sh) -d
   126    139   CONFIG_HEADER = config.h
   127    140   CONFIG_CLEAN_FILES =
   128    141   CONFIG_CLEAN_VPATH_FILES =
   129    142   am__installdirs = "$(DESTDIR)$(bindir)"
................................................................................
   136    149   am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@)
   137    150   am__v_lt_0 = --silent
   138    151   am__v_lt_1 = 
   139    152   am_shp_doctor_OBJECTS = shp_doctor.$(OBJEXT)
   140    153   shp_doctor_OBJECTS = $(am_shp_doctor_OBJECTS)
   141    154   shp_doctor_LDADD = $(LDADD)
   142    155   shp_doctor_DEPENDENCIES =
          156  +am_shp_sanitize_OBJECTS = shp_sanitize.$(OBJEXT)
          157  +shp_sanitize_OBJECTS = $(am_shp_sanitize_OBJECTS)
          158  +shp_sanitize_LDADD = $(LDADD)
          159  +shp_sanitize_DEPENDENCIES =
   143    160   am_spatialite_OBJECTS = shell.$(OBJEXT)
   144    161   spatialite_OBJECTS = $(am_spatialite_OBJECTS)
   145    162   spatialite_DEPENDENCIES =
   146    163   spatialite_convert_SOURCES = spatialite_convert.c
   147    164   spatialite_convert_OBJECTS = spatialite_convert.$(OBJEXT)
   148    165   spatialite_convert_LDADD = $(LDADD)
   149    166   spatialite_convert_DEPENDENCIES =
          167  +am_spatialite_dem_OBJECTS = spatialite_dem.$(OBJEXT)
          168  +spatialite_dem_OBJECTS = $(am_spatialite_dem_OBJECTS)
          169  +spatialite_dem_DEPENDENCIES =
   150    170   spatialite_dxf_SOURCES = spatialite_dxf.c
   151    171   spatialite_dxf_OBJECTS = spatialite_dxf.$(OBJEXT)
   152    172   spatialite_dxf_LDADD = $(LDADD)
   153    173   spatialite_dxf_DEPENDENCIES =
   154    174   am_spatialite_gml_OBJECTS = spatialite_gml.$(OBJEXT)
   155    175   spatialite_gml_OBJECTS = $(am_spatialite_gml_OBJECTS)
   156    176   spatialite_gml_DEPENDENCIES =
................................................................................
   182    202   @NO_READOSM_FALSE@	spatialite_osm_raw.$(OBJEXT)
   183    203   spatialite_osm_raw_OBJECTS = $(am_spatialite_osm_raw_OBJECTS)
   184    204   spatialite_osm_raw_DEPENDENCIES =
   185    205   am_spatialite_tool_OBJECTS = spatialite_tool.$(OBJEXT)
   186    206   spatialite_tool_OBJECTS = $(am_spatialite_tool_OBJECTS)
   187    207   spatialite_tool_LDADD = $(LDADD)
   188    208   spatialite_tool_DEPENDENCIES =
          209  +am_spatialite_xml2utf8_OBJECTS = spatialite_xml2utf8.$(OBJEXT)
          210  +spatialite_xml2utf8_OBJECTS = $(am_spatialite_xml2utf8_OBJECTS)
          211  +spatialite_xml2utf8_LDADD = $(LDADD)
          212  +spatialite_xml2utf8_DEPENDENCIES =
   189    213   am_spatialite_xml_collapse_OBJECTS =  \
   190    214   	spatialite_xml_collapse.$(OBJEXT)
   191    215   spatialite_xml_collapse_OBJECTS =  \
   192    216   	$(am_spatialite_xml_collapse_OBJECTS)
   193    217   spatialite_xml_collapse_DEPENDENCIES =
   194    218   am_spatialite_xml_load_OBJECTS = spatialite_xml_load.$(OBJEXT)
   195    219   spatialite_xml_load_OBJECTS = $(am_spatialite_xml_load_OBJECTS)
................................................................................
   234    258   	$(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \
   235    259   	$(AM_LDFLAGS) $(LDFLAGS) -o $@
   236    260   AM_V_CCLD = $(am__v_CCLD_@AM_V@)
   237    261   am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@)
   238    262   am__v_CCLD_0 = @echo "  CCLD    " $@;
   239    263   am__v_CCLD_1 = 
   240    264   SOURCES = $(exif_loader_SOURCES) $(shp_doctor_SOURCES) \
   241         -	$(spatialite_SOURCES) spatialite_convert.c spatialite_dxf.c \
   242         -	$(spatialite_gml_SOURCES) $(spatialite_network_SOURCES) \
   243         -	$(spatialite_osm_filter_SOURCES) $(spatialite_osm_map_SOURCES) \
   244         -	$(spatialite_osm_net_SOURCES) \
          265  +	$(shp_sanitize_SOURCES) $(spatialite_SOURCES) \
          266  +	spatialite_convert.c $(spatialite_dem_SOURCES) \
          267  +	spatialite_dxf.c $(spatialite_gml_SOURCES) \
          268  +	$(spatialite_network_SOURCES) $(spatialite_osm_filter_SOURCES) \
          269  +	$(spatialite_osm_map_SOURCES) $(spatialite_osm_net_SOURCES) \
   245    270   	$(spatialite_osm_overpass_SOURCES) \
   246    271   	$(spatialite_osm_raw_SOURCES) $(spatialite_tool_SOURCES) \
          272  +	$(spatialite_xml2utf8_SOURCES) \
   247    273   	$(spatialite_xml_collapse_SOURCES) \
   248    274   	$(spatialite_xml_load_SOURCES) $(spatialite_xml_print_SOURCES) \
   249    275   	$(spatialite_xml_validator_SOURCES)
   250    276   DIST_SOURCES = $(exif_loader_SOURCES) $(shp_doctor_SOURCES) \
   251         -	$(spatialite_SOURCES) spatialite_convert.c spatialite_dxf.c \
   252         -	$(spatialite_gml_SOURCES) $(spatialite_network_SOURCES) \
   253         -	$(spatialite_osm_filter_SOURCES) \
          277  +	$(shp_sanitize_SOURCES) $(spatialite_SOURCES) \
          278  +	spatialite_convert.c $(spatialite_dem_SOURCES) \
          279  +	spatialite_dxf.c $(spatialite_gml_SOURCES) \
          280  +	$(spatialite_network_SOURCES) $(spatialite_osm_filter_SOURCES) \
   254    281   	$(am__spatialite_osm_map_SOURCES_DIST) \
   255    282   	$(am__spatialite_osm_net_SOURCES_DIST) \
   256    283   	$(spatialite_osm_overpass_SOURCES) \
   257    284   	$(am__spatialite_osm_raw_SOURCES_DIST) \
   258         -	$(spatialite_tool_SOURCES) $(spatialite_xml_collapse_SOURCES) \
          285  +	$(spatialite_tool_SOURCES) $(spatialite_xml2utf8_SOURCES) \
          286  +	$(spatialite_xml_collapse_SOURCES) \
   259    287   	$(spatialite_xml_load_SOURCES) $(spatialite_xml_print_SOURCES) \
   260    288   	$(spatialite_xml_validator_SOURCES)
   261    289   am__can_run_installinfo = \
   262    290     case $$AM_UPDATE_INFO_DIR in \
   263    291       n|no|NO) false;; \
   264    292       *) (install-info --version) >/dev/null 2>&1;; \
   265    293     esac
................................................................................
   281    309     unique=`for i in $$list; do \
   282    310       if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
   283    311     done | $(am__uniquify_input)`
   284    312   ETAGS = etags
   285    313   CTAGS = ctags
   286    314   CSCOPE = cscope
   287    315   AM_RECURSIVE_TARGETS = cscope
          316  +am__DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/config.h.in AUTHORS \
          317  +	COPYING ChangeLog INSTALL NEWS README compile config.guess \
          318  +	config.sub depcomp install-sh ltmain.sh missing
   288    319   DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
   289    320   distdir = $(PACKAGE)-$(VERSION)
   290    321   top_distdir = $(distdir)
   291    322   am__remove_distdir = \
   292    323     if test -d "$(distdir)"; then \
   293    324       find "$(distdir)" -type d ! -perm -200 -exec chmod u+w {} ';' \
   294    325         && rm -rf "$(distdir)" \
................................................................................
   376    407   PACKAGE_VERSION = @PACKAGE_VERSION@
   377    408   PATH_SEPARATOR = @PATH_SEPARATOR@
   378    409   PKG_CONFIG = @PKG_CONFIG@
   379    410   PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@
   380    411   PKG_CONFIG_PATH = @PKG_CONFIG_PATH@
   381    412   RANLIB = @RANLIB@
   382    413   READLINE_LIBS = @READLINE_LIBS@
          414  +RTTOPO_CFLAGS = @RTTOPO_CFLAGS@
          415  +RTTOPO_LIBS = @RTTOPO_LIBS@
   383    416   SED = @SED@
   384    417   SET_MAKE = @SET_MAKE@
   385    418   SHELL = @SHELL@
   386    419   STRIP = @STRIP@
   387    420   VERSION = @VERSION@
   388    421   abs_builddir = @abs_builddir@
   389    422   abs_srcdir = @abs_srcdir@
................................................................................
   435    468   srcdir = @srcdir@
   436    469   sysconfdir = @sysconfdir@
   437    470   target_alias = @target_alias@
   438    471   top_build_prefix = @top_build_prefix@
   439    472   top_builddir = @top_builddir@
   440    473   top_srcdir = @top_srcdir@
   441    474   ACLOCAL_AMFLAGS = -I m4
   442         -AM_CPPFLAGS = @CFLAGS@ @LIBXML2_CFLAGS@ -I$(top_srcdir)
          475  +AM_CPPFLAGS = @CFLAGS@ @CPPFLAGS@ @LIBXML2_CFLAGS@ -I$(top_srcdir)
   443    476   spatialite_SOURCES = shell.c
   444    477   spatialite_tool_SOURCES = spatialite_tool.c
   445    478   spatialite_network_SOURCES = spatialite_network.c
   446    479   shp_doctor_SOURCES = shp_doctor.c
          480  +shp_sanitize_SOURCES = shp_sanitize.c
   447    481   exif_loader_SOURCES = exif_loader.c
   448    482   spatialite_xml_validator_SOURCES = spatialite_xml_validator.c
   449    483   spatialite_xml_load_SOURCES = spatialite_xml_load.c
          484  +spatialite_xml2utf8_SOURCES = spatialite_xml2utf8.c
   450    485   spatialite_xml_collapse_SOURCES = spatialite_xml_collapse.c
   451    486   spatialite_xml_print_SOURCES = spatialite_xml_print.c 
   452    487   @NO_READOSM_FALSE@spatialite_osm_net_SOURCES = spatialite_osm_net.c
   453    488   @NO_READOSM_FALSE@spatialite_osm_map_SOURCES = spatialite_osm_map.c
   454    489   @NO_READOSM_FALSE@spatialite_osm_raw_SOURCES = spatialite_osm_raw.c
   455    490   spatialite_osm_filter_SOURCES = spatialite_osm_filter.c
   456    491   spatialite_gml_SOURCES = spatialite_gml.c
   457    492   spatialite_osm_overpass_SOURCES = spatialite_osm_overpass.c
          493  +spatialite_dem_SOURCES = spatialite_dem.c
   458    494   spatialite_osm_map_LDADD = @LIBSPATIALITE_LIBS@ \
   459    495   	@LIBFREEXL_LIBS@ @LIBREADOSM_LIBS@ 
   460    496   
   461    497   spatialite_osm_overpass_LDADD = @LIBSPATIALITE_LIBS@ \
   462    498   	@LIBFREEXL_LIBS@ @LIBXML2_LIBS@ 
   463    499   
   464    500   spatialite_osm_raw_LDADD = @LIBSPATIALITE_LIBS@ \
................................................................................
   467    503   spatialite_osm_net_LDADD = @LIBSPATIALITE_LIBS@ \
   468    504   	@LIBFREEXL_LIBS@ @LIBREADOSM_LIBS@
   469    505   
   470    506   spatialite_gml_LDADD = @LIBSPATIALITE_LIBS@ \
   471    507   	@LIBFREEXL_LIBS@ \
   472    508   	-lexpat 
   473    509   
          510  +spatialite_dem_LDADD = @LIBSPATIALITE_LIBS@ 
   474    511   spatialite_LDADD = @LIBSPATIALITE_LIBS@ \
   475    512   	@LIBFREEXL_LIBS@ \
   476    513   	@READLINE_LIBS@
   477    514   
   478    515   spatialite_xml_validator_LDADD = @LIBXML2_LIBS@
   479    516   spatialite_xml_load_LDADD = @LIBSPATIALITE_LIBS@ \
   480    517   	-lexpat
................................................................................
   483    520   spatialite_xml_print_LADD = @LIBSPATIALIATE_LIBS@
   484    521   LDADD = @LIBSPATIALITE_LIBS@ \
   485    522   	@LIBFREEXL_LIBS@
   486    523   
   487    524   EXTRA_DIST = makefile.vc nmake.opt \
   488    525   	config-msvc.h \
   489    526   	Makefile-static-MinGW \
          527  +	Makefile-static-mingw32 \
          528  +	Makefile-static-mingw64 \
   490    529   	Makefile-static-Linux \
   491    530   	Makefile-static-MacOsX
   492    531   
   493         -AUTOMAKE_OPTIONS = dist-zip
          532  +AUTOMAKE_OPTIONS = dist-zip foreign
   494    533   all: config.h
   495    534   	$(MAKE) $(AM_MAKEFLAGS) all-am
   496    535   
   497    536   .SUFFIXES:
   498    537   .SUFFIXES: .c .lo .o .obj
   499    538   am--refresh: Makefile
   500    539   	@:
   501    540   $(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am  $(am__configure_deps)
   502    541   	@for dep in $?; do \
   503    542   	  case '$(am__configure_deps)' in \
   504    543   	    *$$dep*) \
   505         -	      echo ' cd $(srcdir) && $(AUTOMAKE) --gnu'; \
   506         -	      $(am__cd) $(srcdir) && $(AUTOMAKE) --gnu \
          544  +	      echo ' cd $(srcdir) && $(AUTOMAKE) --foreign'; \
          545  +	      $(am__cd) $(srcdir) && $(AUTOMAKE) --foreign \
   507    546   		&& exit 0; \
   508    547   	      exit 1;; \
   509    548   	  esac; \
   510    549   	done; \
   511         -	echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu Makefile'; \
          550  +	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign Makefile'; \
   512    551   	$(am__cd) $(top_srcdir) && \
   513         -	  $(AUTOMAKE) --gnu Makefile
   514         -.PRECIOUS: Makefile
          552  +	  $(AUTOMAKE) --foreign Makefile
   515    553   Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
   516    554   	@case '$?' in \
   517    555   	  *config.status*) \
   518    556   	    echo ' $(SHELL) ./config.status'; \
   519    557   	    $(SHELL) ./config.status;; \
   520    558   	  *) \
   521    559   	    echo ' cd $(top_builddir) && $(SHELL) ./config.status $@ $(am__depfiles_maybe)'; \
................................................................................
   528    566   $(top_srcdir)/configure: @MAINTAINER_MODE_TRUE@ $(am__configure_deps)
   529    567   	$(am__cd) $(srcdir) && $(AUTOCONF)
   530    568   $(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps)
   531    569   	$(am__cd) $(srcdir) && $(ACLOCAL) $(ACLOCAL_AMFLAGS)
   532    570   $(am__aclocal_m4_deps):
   533    571   
   534    572   config.h: stamp-h1
   535         -	@if test ! -f $@; then rm -f stamp-h1; else :; fi
   536         -	@if test ! -f $@; then $(MAKE) $(AM_MAKEFLAGS) stamp-h1; else :; fi
          573  +	@test -f $@ || rm -f stamp-h1
          574  +	@test -f $@ || $(MAKE) $(AM_MAKEFLAGS) stamp-h1
   537    575   
   538    576   stamp-h1: $(srcdir)/config.h.in $(top_builddir)/config.status
   539    577   	@rm -f stamp-h1
   540    578   	cd $(top_builddir) && $(SHELL) ./config.status config.h
   541    579   $(srcdir)/config.h.in: @MAINTAINER_MODE_TRUE@ $(am__configure_deps) 
   542    580   	($(am__cd) $(top_srcdir) && $(AUTOHEADER))
   543    581   	rm -f stamp-h1
................................................................................
   598    636   exif_loader$(EXEEXT): $(exif_loader_OBJECTS) $(exif_loader_DEPENDENCIES) $(EXTRA_exif_loader_DEPENDENCIES) 
   599    637   	@rm -f exif_loader$(EXEEXT)
   600    638   	$(AM_V_CCLD)$(LINK) $(exif_loader_OBJECTS) $(exif_loader_LDADD) $(LIBS)
   601    639   
   602    640   shp_doctor$(EXEEXT): $(shp_doctor_OBJECTS) $(shp_doctor_DEPENDENCIES) $(EXTRA_shp_doctor_DEPENDENCIES) 
   603    641   	@rm -f shp_doctor$(EXEEXT)
   604    642   	$(AM_V_CCLD)$(LINK) $(shp_doctor_OBJECTS) $(shp_doctor_LDADD) $(LIBS)
          643  +
          644  +shp_sanitize$(EXEEXT): $(shp_sanitize_OBJECTS) $(shp_sanitize_DEPENDENCIES) $(EXTRA_shp_sanitize_DEPENDENCIES) 
          645  +	@rm -f shp_sanitize$(EXEEXT)
          646  +	$(AM_V_CCLD)$(LINK) $(shp_sanitize_OBJECTS) $(shp_sanitize_LDADD) $(LIBS)
   605    647   
   606    648   spatialite$(EXEEXT): $(spatialite_OBJECTS) $(spatialite_DEPENDENCIES) $(EXTRA_spatialite_DEPENDENCIES) 
   607    649   	@rm -f spatialite$(EXEEXT)
   608    650   	$(AM_V_CCLD)$(LINK) $(spatialite_OBJECTS) $(spatialite_LDADD) $(LIBS)
   609    651   
   610    652   spatialite_convert$(EXEEXT): $(spatialite_convert_OBJECTS) $(spatialite_convert_DEPENDENCIES) $(EXTRA_spatialite_convert_DEPENDENCIES) 
   611    653   	@rm -f spatialite_convert$(EXEEXT)
   612    654   	$(AM_V_CCLD)$(LINK) $(spatialite_convert_OBJECTS) $(spatialite_convert_LDADD) $(LIBS)
          655  +
          656  +spatialite_dem$(EXEEXT): $(spatialite_dem_OBJECTS) $(spatialite_dem_DEPENDENCIES) $(EXTRA_spatialite_dem_DEPENDENCIES) 
          657  +	@rm -f spatialite_dem$(EXEEXT)
          658  +	$(AM_V_CCLD)$(LINK) $(spatialite_dem_OBJECTS) $(spatialite_dem_LDADD) $(LIBS)
   613    659   
   614    660   spatialite_dxf$(EXEEXT): $(spatialite_dxf_OBJECTS) $(spatialite_dxf_DEPENDENCIES) $(EXTRA_spatialite_dxf_DEPENDENCIES) 
   615    661   	@rm -f spatialite_dxf$(EXEEXT)
   616    662   	$(AM_V_CCLD)$(LINK) $(spatialite_dxf_OBJECTS) $(spatialite_dxf_LDADD) $(LIBS)
   617    663   
   618    664   spatialite_gml$(EXEEXT): $(spatialite_gml_OBJECTS) $(spatialite_gml_DEPENDENCIES) $(EXTRA_spatialite_gml_DEPENDENCIES) 
   619    665   	@rm -f spatialite_gml$(EXEEXT)
................................................................................
   642    688   spatialite_osm_raw$(EXEEXT): $(spatialite_osm_raw_OBJECTS) $(spatialite_osm_raw_DEPENDENCIES) $(EXTRA_spatialite_osm_raw_DEPENDENCIES) 
   643    689   	@rm -f spatialite_osm_raw$(EXEEXT)
   644    690   	$(AM_V_CCLD)$(LINK) $(spatialite_osm_raw_OBJECTS) $(spatialite_osm_raw_LDADD) $(LIBS)
   645    691   
   646    692   spatialite_tool$(EXEEXT): $(spatialite_tool_OBJECTS) $(spatialite_tool_DEPENDENCIES) $(EXTRA_spatialite_tool_DEPENDENCIES) 
   647    693   	@rm -f spatialite_tool$(EXEEXT)
   648    694   	$(AM_V_CCLD)$(LINK) $(spatialite_tool_OBJECTS) $(spatialite_tool_LDADD) $(LIBS)
          695  +
          696  +spatialite_xml2utf8$(EXEEXT): $(spatialite_xml2utf8_OBJECTS) $(spatialite_xml2utf8_DEPENDENCIES) $(EXTRA_spatialite_xml2utf8_DEPENDENCIES) 
          697  +	@rm -f spatialite_xml2utf8$(EXEEXT)
          698  +	$(AM_V_CCLD)$(LINK) $(spatialite_xml2utf8_OBJECTS) $(spatialite_xml2utf8_LDADD) $(LIBS)
   649    699   
   650    700   spatialite_xml_collapse$(EXEEXT): $(spatialite_xml_collapse_OBJECTS) $(spatialite_xml_collapse_DEPENDENCIES) $(EXTRA_spatialite_xml_collapse_DEPENDENCIES) 
   651    701   	@rm -f spatialite_xml_collapse$(EXEEXT)
   652    702   	$(AM_V_CCLD)$(LINK) $(spatialite_xml_collapse_OBJECTS) $(spatialite_xml_collapse_LDADD) $(LIBS)
   653    703   
   654    704   spatialite_xml_load$(EXEEXT): $(spatialite_xml_load_OBJECTS) $(spatialite_xml_load_DEPENDENCIES) $(EXTRA_spatialite_xml_load_DEPENDENCIES) 
   655    705   	@rm -f spatialite_xml_load$(EXEEXT)
................................................................................
   668    718   
   669    719   distclean-compile:
   670    720   	-rm -f *.tab.c
   671    721   
   672    722   @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/exif_loader.Po@am__quote@
   673    723   @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/shell.Po@am__quote@
   674    724   @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/shp_doctor.Po@am__quote@
          725  +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/shp_sanitize.Po@am__quote@
   675    726   @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/spatialite_convert.Po@am__quote@
          727  +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/spatialite_dem.Po@am__quote@
   676    728   @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/spatialite_dxf.Po@am__quote@
   677    729   @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/spatialite_gml.Po@am__quote@
   678    730   @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/spatialite_network.Po@am__quote@
   679    731   @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/spatialite_osm_filter.Po@am__quote@
   680    732   @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/spatialite_osm_map.Po@am__quote@
   681    733   @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/spatialite_osm_net.Po@am__quote@
   682    734   @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/spatialite_osm_overpass.Po@am__quote@
   683    735   @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/spatialite_osm_raw.Po@am__quote@
   684    736   @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/spatialite_tool.Po@am__quote@
          737  +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/spatialite_xml2utf8.Po@am__quote@
   685    738   @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/spatialite_xml_collapse.Po@am__quote@
   686    739   @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/spatialite_xml_load.Po@am__quote@
   687    740   @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/spatialite_xml_print.Po@am__quote@
   688    741   @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/spatialite_xml_validator.Po@am__quote@
   689    742   
   690    743   .c.o:
   691    744   @am__fastdepCC_TRUE@	$(AM_V_CC)$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $<
   692    745   @am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
   693    746   @AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
   694    747   @AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
   695         -@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(COMPILE) -c $<
          748  +@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ $<
   696    749   
   697    750   .c.obj:
   698    751   @am__fastdepCC_TRUE@	$(AM_V_CC)$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'`
   699    752   @am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
   700    753   @AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
   701    754   @AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
   702         -@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(COMPILE) -c `$(CYGPATH_W) '$<'`
          755  +@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'`
   703    756   
   704    757   .c.lo:
   705    758   @am__fastdepCC_TRUE@	$(AM_V_CC)$(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $<
   706    759   @am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo
   707    760   @AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@
   708    761   @AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
   709    762   @am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $<
................................................................................
   812    865   	|| find "$(distdir)" -type d ! -perm -755 \
   813    866   		-exec chmod u+rwx,go+rx {} \; -o \
   814    867   	  ! -type d ! -perm -444 -links 1 -exec chmod a+r {} \; -o \
   815    868   	  ! -type d ! -perm -400 -exec chmod a+r {} \; -o \
   816    869   	  ! -type d ! -perm -444 -exec $(install_sh) -c -m a+r {} {} \; \
   817    870   	|| chmod -R a+r "$(distdir)"
   818    871   dist-gzip: distdir
   819         -	tardir=$(distdir) && $(am__tar) | GZIP=$(GZIP_ENV) gzip -c >$(distdir).tar.gz
          872  +	tardir=$(distdir) && $(am__tar) | eval GZIP= gzip $(GZIP_ENV) -c >$(distdir).tar.gz
   820    873   	$(am__post_remove_distdir)
   821    874   
   822    875   dist-bzip2: distdir
   823    876   	tardir=$(distdir) && $(am__tar) | BZIP2=$${BZIP2--9} bzip2 -c >$(distdir).tar.bz2
   824    877   	$(am__post_remove_distdir)
   825    878   
   826    879   dist-lzip: distdir
................................................................................
   828    881   	$(am__post_remove_distdir)
   829    882   
   830    883   dist-xz: distdir
   831    884   	tardir=$(distdir) && $(am__tar) | XZ_OPT=$${XZ_OPT--e} xz -c >$(distdir).tar.xz
   832    885   	$(am__post_remove_distdir)
   833    886   
   834    887   dist-tarZ: distdir
          888  +	@echo WARNING: "Support for distribution archives compressed with" \
          889  +		       "legacy program 'compress' is deprecated." >&2
          890  +	@echo WARNING: "It will be removed altogether in Automake 2.0" >&2
   835    891   	tardir=$(distdir) && $(am__tar) | compress -c >$(distdir).tar.Z
   836    892   	$(am__post_remove_distdir)
   837    893   
   838    894   dist-shar: distdir
   839         -	shar $(distdir) | GZIP=$(GZIP_ENV) gzip -c >$(distdir).shar.gz
          895  +	@echo WARNING: "Support for shar distribution archives is" \
          896  +	               "deprecated." >&2
          897  +	@echo WARNING: "It will be removed altogether in Automake 2.0" >&2
          898  +	shar $(distdir) | eval GZIP= gzip $(GZIP_ENV) -c >$(distdir).shar.gz
   840    899   	$(am__post_remove_distdir)
   841    900   dist-zip: distdir
   842    901   	-rm -f $(distdir).zip
   843    902   	zip -rq $(distdir).zip $(distdir)
   844    903   	$(am__post_remove_distdir)
   845    904   
   846    905   dist dist-all:
................................................................................
   849    908   
   850    909   # This target untars the dist file and tries a VPATH configuration.  Then
   851    910   # it guarantees that the distribution is self-contained by making another
   852    911   # tarfile.
   853    912   distcheck: dist
   854    913   	case '$(DIST_ARCHIVES)' in \
   855    914   	*.tar.gz*) \
   856         -	  GZIP=$(GZIP_ENV) gzip -dc $(distdir).tar.gz | $(am__untar) ;;\
          915  +	  eval GZIP= gzip $(GZIP_ENV) -dc $(distdir).tar.gz | $(am__untar) ;;\
   857    916   	*.tar.bz2*) \
   858    917   	  bzip2 -dc $(distdir).tar.bz2 | $(am__untar) ;;\
   859    918   	*.tar.lz*) \
   860    919   	  lzip -dc $(distdir).tar.lz | $(am__untar) ;;\
   861    920   	*.tar.xz*) \
   862    921   	  xz -dc $(distdir).tar.xz | $(am__untar) ;;\
   863    922   	*.tar.Z*) \
   864    923   	  uncompress -c $(distdir).tar.Z | $(am__untar) ;;\
   865    924   	*.shar.gz*) \
   866         -	  GZIP=$(GZIP_ENV) gzip -dc $(distdir).shar.gz | unshar ;;\
          925  +	  eval GZIP= gzip $(GZIP_ENV) -dc $(distdir).shar.gz | unshar ;;\
   867    926   	*.zip*) \
   868    927   	  unzip $(distdir).zip ;;\
   869    928   	esac
   870    929   	chmod -R a-w $(distdir)
   871    930   	chmod u+w $(distdir)
   872         -	mkdir $(distdir)/_build $(distdir)/_inst
          931  +	mkdir $(distdir)/_build $(distdir)/_build/sub $(distdir)/_inst
   873    932   	chmod a-w $(distdir)
   874    933   	test -d $(distdir)/_build || exit 0; \
   875    934   	dc_install_base=`$(am__cd) $(distdir)/_inst && pwd | sed -e 's,^[^:\\/]:[\\/],/,'` \
   876    935   	  && dc_destdir="$${TMPDIR-/tmp}/am-dc-$$$$/" \
   877    936   	  && am__cwd=`pwd` \
   878         -	  && $(am__cd) $(distdir)/_build \
   879         -	  && ../configure --srcdir=.. --prefix="$$dc_install_base" \
          937  +	  && $(am__cd) $(distdir)/_build/sub \
          938  +	  && ../../configure \
   880    939   	    $(AM_DISTCHECK_CONFIGURE_FLAGS) \
   881    940   	    $(DISTCHECK_CONFIGURE_FLAGS) \
          941  +	    --srcdir=../.. --prefix="$$dc_install_base" \
   882    942   	  && $(MAKE) $(AM_MAKEFLAGS) \
   883    943   	  && $(MAKE) $(AM_MAKEFLAGS) dvi \
   884    944   	  && $(MAKE) $(AM_MAKEFLAGS) check \
   885    945   	  && $(MAKE) $(AM_MAKEFLAGS) install \
   886    946   	  && $(MAKE) $(AM_MAKEFLAGS) installcheck \
   887    947   	  && $(MAKE) $(AM_MAKEFLAGS) uninstall \
   888    948   	  && $(MAKE) $(AM_MAKEFLAGS) distuninstallcheck_dir="$$dc_install_base" \
................................................................................
  1055   1115   	install-exec-am install-html install-html-am install-info \
  1056   1116   	install-info-am install-man install-pdf install-pdf-am \
  1057   1117   	install-ps install-ps-am install-strip installcheck \
  1058   1118   	installcheck-am installdirs maintainer-clean \
  1059   1119   	maintainer-clean-generic mostlyclean mostlyclean-compile \
  1060   1120   	mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \
  1061   1121   	tags tags-am uninstall uninstall-am uninstall-binPROGRAMS
         1122  +
         1123  +.PRECIOUS: Makefile
  1062   1124   
  1063   1125   
  1064   1126   # Tell versions [3.59,3.63) of GNU make to not export all variables.
  1065   1127   # Otherwise a system limit (for SysV at least) may be exceeded.
  1066   1128   .NOEXPORT:

Changes to aclocal.m4.

     1         -# generated automatically by aclocal 1.13.4 -*- Autoconf -*-
            1  +# generated automatically by aclocal 1.15 -*- Autoconf -*-
     2      2   
     3         -# Copyright (C) 1996-2013 Free Software Foundation, Inc.
            3  +# Copyright (C) 1996-2014 Free Software Foundation, Inc.
     4      4   
     5      5   # This file is free software; the Free Software Foundation
     6      6   # gives unlimited permission to copy and/or distribute it,
     7      7   # with or without modifications, as long as this notice is preserved.
     8      8   
     9      9   # This program is distributed in the hope that it will be useful,
    10     10   # but WITHOUT ANY WARRANTY, to the extent permitted by law; without
................................................................................
    16     16     [m4_copy([m4_PACKAGE_VERSION], [AC_AUTOCONF_VERSION])])dnl
    17     17   m4_if(m4_defn([AC_AUTOCONF_VERSION]), [2.69],,
    18     18   [m4_warning([this file was generated for autoconf 2.69.
    19     19   You have another version of autoconf.  It may work, but is not guaranteed to.
    20     20   If you have problems, you may need to regenerate the build system entirely.
    21     21   To do so, use the procedure documented by the package, typically 'autoreconf'.])])
    22     22   
    23         -# pkg.m4 - Macros to locate and utilise pkg-config.            -*- Autoconf -*-
    24         -# serial 1 (pkg-config-0.24)
    25         -# 
    26         -# Copyright © 2004 Scott James Remnant <scott@netsplit.com>.
    27         -#
    28         -# This program is free software; you can redistribute it and/or modify
    29         -# it under the terms of the GNU General Public License as published by
    30         -# the Free Software Foundation; either version 2 of the License, or
    31         -# (at your option) any later version.
    32         -#
    33         -# This program is distributed in the hope that it will be useful, but
    34         -# WITHOUT ANY WARRANTY; without even the implied warranty of
    35         -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    36         -# General Public License for more details.
    37         -#
    38         -# You should have received a copy of the GNU General Public License
    39         -# along with this program; if not, write to the Free Software
    40         -# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
    41         -#
    42         -# As a special exception to the GNU General Public License, if you
    43         -# distribute this file as part of a program that contains a
    44         -# configuration script generated by Autoconf, you may include it under
    45         -# the same distribution terms that you use for the rest of that program.
    46         -
    47         -# PKG_PROG_PKG_CONFIG([MIN-VERSION])
    48         -# ----------------------------------
           23  +dnl pkg.m4 - Macros to locate and utilise pkg-config.   -*- Autoconf -*-
           24  +dnl serial 11 (pkg-config-0.29.1)
           25  +dnl
           26  +dnl Copyright © 2004 Scott James Remnant <scott@netsplit.com>.
           27  +dnl Copyright © 2012-2015 Dan Nicholson <dbn.lists@gmail.com>
           28  +dnl
           29  +dnl This program is free software; you can redistribute it and/or modify
           30  +dnl it under the terms of the GNU General Public License as published by
           31  +dnl the Free Software Foundation; either version 2 of the License, or
           32  +dnl (at your option) any later version.
           33  +dnl
           34  +dnl This program is distributed in the hope that it will be useful, but
           35  +dnl WITHOUT ANY WARRANTY; without even the implied warranty of
           36  +dnl MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
           37  +dnl General Public License for more details.
           38  +dnl
           39  +dnl You should have received a copy of the GNU General Public License
           40  +dnl along with this program; if not, write to the Free Software
           41  +dnl Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
           42  +dnl 02111-1307, USA.
           43  +dnl
           44  +dnl As a special exception to the GNU General Public License, if you
           45  +dnl distribute this file as part of a program that contains a
           46  +dnl configuration script generated by Autoconf, you may include it under
           47  +dnl the same distribution terms that you use for the rest of that
           48  +dnl program.
           49  +
           50  +dnl PKG_PREREQ(MIN-VERSION)
           51  +dnl -----------------------
           52  +dnl Since: 0.29
           53  +dnl
           54  +dnl Verify that the version of the pkg-config macros are at least
           55  +dnl MIN-VERSION. Unlike PKG_PROG_PKG_CONFIG, which checks the user's
           56  +dnl installed version of pkg-config, this checks the developer's version
           57  +dnl of pkg.m4 when generating configure.
           58  +dnl
           59  +dnl To ensure that this macro is defined, also add:
           60  +dnl m4_ifndef([PKG_PREREQ],
           61  +dnl     [m4_fatal([must install pkg-config 0.29 or later before running autoconf/autogen])])
           62  +dnl
           63  +dnl See the "Since" comment for each macro you use to see what version
           64  +dnl of the macros you require.
           65  +m4_defun([PKG_PREREQ],
           66  +[m4_define([PKG_MACROS_VERSION], [0.29.1])
           67  +m4_if(m4_version_compare(PKG_MACROS_VERSION, [$1]), -1,
           68  +    [m4_fatal([pkg.m4 version $1 or higher is required but ]PKG_MACROS_VERSION[ found])])
           69  +])dnl PKG_PREREQ
           70  +
           71  +dnl PKG_PROG_PKG_CONFIG([MIN-VERSION])
           72  +dnl ----------------------------------
           73  +dnl Since: 0.16
           74  +dnl
           75  +dnl Search for the pkg-config tool and set the PKG_CONFIG variable to
           76  +dnl first found in the path. Checks that the version of pkg-config found
           77  +dnl is at least MIN-VERSION. If MIN-VERSION is not specified, 0.9.0 is
           78  +dnl used since that's the first version where most current features of
           79  +dnl pkg-config existed.
    49     80   AC_DEFUN([PKG_PROG_PKG_CONFIG],
    50     81   [m4_pattern_forbid([^_?PKG_[A-Z_]+$])
    51     82   m4_pattern_allow([^PKG_CONFIG(_(PATH|LIBDIR|SYSROOT_DIR|ALLOW_SYSTEM_(CFLAGS|LIBS)))?$])
    52     83   m4_pattern_allow([^PKG_CONFIG_(DISABLE_UNINSTALLED|TOP_BUILD_DIR|DEBUG_SPEW)$])
    53     84   AC_ARG_VAR([PKG_CONFIG], [path to pkg-config utility])
    54     85   AC_ARG_VAR([PKG_CONFIG_PATH], [directories to add to pkg-config's search path])
    55     86   AC_ARG_VAR([PKG_CONFIG_LIBDIR], [path overriding pkg-config's built-in search path])
................................................................................
    63     94   	if $PKG_CONFIG --atleast-pkgconfig-version $_pkg_min_version; then
    64     95   		AC_MSG_RESULT([yes])
    65     96   	else
    66     97   		AC_MSG_RESULT([no])
    67     98   		PKG_CONFIG=""
    68     99   	fi
    69    100   fi[]dnl
    70         -])# PKG_PROG_PKG_CONFIG
          101  +])dnl PKG_PROG_PKG_CONFIG
    71    102   
    72         -# PKG_CHECK_EXISTS(MODULES, [ACTION-IF-FOUND], [ACTION-IF-NOT-FOUND])
    73         -#
    74         -# Check to see whether a particular set of modules exists.  Similar
    75         -# to PKG_CHECK_MODULES(), but does not set variables or print errors.
    76         -#
    77         -# Please remember that m4 expands AC_REQUIRE([PKG_PROG_PKG_CONFIG])
    78         -# only at the first occurence in configure.ac, so if the first place
    79         -# it's called might be skipped (such as if it is within an "if", you
    80         -# have to call PKG_CHECK_EXISTS manually
    81         -# --------------------------------------------------------------
          103  +dnl PKG_CHECK_EXISTS(MODULES, [ACTION-IF-FOUND], [ACTION-IF-NOT-FOUND])
          104  +dnl -------------------------------------------------------------------
          105  +dnl Since: 0.18
          106  +dnl
          107  +dnl Check to see whether a particular set of modules exists. Similar to
          108  +dnl PKG_CHECK_MODULES(), but does not set variables or print errors.
          109  +dnl
          110  +dnl Please remember that m4 expands AC_REQUIRE([PKG_PROG_PKG_CONFIG])
          111  +dnl only at the first occurence in configure.ac, so if the first place
          112  +dnl it's called might be skipped (such as if it is within an "if", you
          113  +dnl have to call PKG_CHECK_EXISTS manually
    82    114   AC_DEFUN([PKG_CHECK_EXISTS],
    83    115   [AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl
    84    116   if test -n "$PKG_CONFIG" && \
    85    117       AC_RUN_LOG([$PKG_CONFIG --exists --print-errors "$1"]); then
    86    118     m4_default([$2], [:])
    87    119   m4_ifvaln([$3], [else
    88    120     $3])dnl
    89    121   fi])
    90    122   
    91         -# _PKG_CONFIG([VARIABLE], [COMMAND], [MODULES])
    92         -# ---------------------------------------------
          123  +dnl _PKG_CONFIG([VARIABLE], [COMMAND], [MODULES])
          124  +dnl ---------------------------------------------
          125  +dnl Internal wrapper calling pkg-config via PKG_CONFIG and setting
          126  +dnl pkg_failed based on the result.
    93    127   m4_define([_PKG_CONFIG],
    94    128   [if test -n "$$1"; then
    95    129       pkg_cv_[]$1="$$1"
    96    130    elif test -n "$PKG_CONFIG"; then
    97    131       PKG_CHECK_EXISTS([$3],
    98    132                        [pkg_cv_[]$1=`$PKG_CONFIG --[]$2 "$3" 2>/dev/null`
    99    133   		      test "x$?" != "x0" && pkg_failed=yes ],
   100    134   		     [pkg_failed=yes])
   101    135    else
   102    136       pkg_failed=untried
   103    137   fi[]dnl
   104         -])# _PKG_CONFIG
          138  +])dnl _PKG_CONFIG
   105    139   
   106         -# _PKG_SHORT_ERRORS_SUPPORTED
   107         -# -----------------------------
          140  +dnl _PKG_SHORT_ERRORS_SUPPORTED
          141  +dnl ---------------------------
          142  +dnl Internal check to see if pkg-config supports short errors.
   108    143   AC_DEFUN([_PKG_SHORT_ERRORS_SUPPORTED],
   109    144   [AC_REQUIRE([PKG_PROG_PKG_CONFIG])
   110    145   if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then
   111    146           _pkg_short_errors_supported=yes
   112    147   else
   113    148           _pkg_short_errors_supported=no
   114    149   fi[]dnl
   115         -])# _PKG_SHORT_ERRORS_SUPPORTED
          150  +])dnl _PKG_SHORT_ERRORS_SUPPORTED
   116    151   
   117    152   
   118         -# PKG_CHECK_MODULES(VARIABLE-PREFIX, MODULES, [ACTION-IF-FOUND],
   119         -# [ACTION-IF-NOT-FOUND])
   120         -#
   121         -#
   122         -# Note that if there is a possibility the first call to
   123         -# PKG_CHECK_MODULES might not happen, you should be sure to include an
   124         -# explicit call to PKG_PROG_PKG_CONFIG in your configure.ac
   125         -#
   126         -#
   127         -# --------------------------------------------------------------
          153  +dnl PKG_CHECK_MODULES(VARIABLE-PREFIX, MODULES, [ACTION-IF-FOUND],
          154  +dnl   [ACTION-IF-NOT-FOUND])
          155  +dnl --------------------------------------------------------------
          156  +dnl Since: 0.4.0
          157  +dnl
          158  +dnl Note that if there is a possibility the first call to
          159  +dnl PKG_CHECK_MODULES might not happen, you should be sure to include an
          160  +dnl explicit call to PKG_PROG_PKG_CONFIG in your configure.ac
   128    161   AC_DEFUN([PKG_CHECK_MODULES],
   129    162   [AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl
   130    163   AC_ARG_VAR([$1][_CFLAGS], [C compiler flags for $1, overriding pkg-config])dnl
   131    164   AC_ARG_VAR([$1][_LIBS], [linker flags for $1, overriding pkg-config])dnl
   132    165   
   133    166   pkg_failed=no
   134    167   AC_MSG_CHECKING([for $1])
................................................................................
   174    207           ])
   175    208   else
   176    209   	$1[]_CFLAGS=$pkg_cv_[]$1[]_CFLAGS
   177    210   	$1[]_LIBS=$pkg_cv_[]$1[]_LIBS
   178    211           AC_MSG_RESULT([yes])
   179    212   	$3
   180    213   fi[]dnl
   181         -])# PKG_CHECK_MODULES
          214  +])dnl PKG_CHECK_MODULES
   182    215   
   183    216   
   184         -# PKG_INSTALLDIR(DIRECTORY)
   185         -# -------------------------
   186         -# Substitutes the variable pkgconfigdir as the location where a module
   187         -# should install pkg-config .pc files. By default the directory is
   188         -# $libdir/pkgconfig, but the default can be changed by passing
   189         -# DIRECTORY. The user can override through the --with-pkgconfigdir
   190         -# parameter.
          217  +dnl PKG_CHECK_MODULES_STATIC(VARIABLE-PREFIX, MODULES, [ACTION-IF-FOUND],
          218  +dnl   [ACTION-IF-NOT-FOUND])
          219  +dnl ---------------------------------------------------------------------
          220  +dnl Since: 0.29
          221  +dnl
          222  +dnl Checks for existence of MODULES and gathers its build flags with
          223  +dnl static libraries enabled. Sets VARIABLE-PREFIX_CFLAGS from --cflags
          224  +dnl and VARIABLE-PREFIX_LIBS from --libs.
          225  +dnl
          226  +dnl Note that if there is a possibility the first call to
          227  +dnl PKG_CHECK_MODULES_STATIC might not happen, you should be sure to
          228  +dnl include an explicit call to PKG_PROG_PKG_CONFIG in your
          229  +dnl configure.ac.
          230  +AC_DEFUN([PKG_CHECK_MODULES_STATIC],
          231  +[AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl
          232  +_save_PKG_CONFIG=$PKG_CONFIG
          233  +PKG_CONFIG="$PKG_CONFIG --static"
          234  +PKG_CHECK_MODULES($@)
          235  +PKG_CONFIG=$_save_PKG_CONFIG[]dnl
          236  +])dnl PKG_CHECK_MODULES_STATIC
          237  +
          238  +
          239  +dnl PKG_INSTALLDIR([DIRECTORY])
          240  +dnl -------------------------
          241  +dnl Since: 0.27
          242  +dnl
          243  +dnl Substitutes the variable pkgconfigdir as the location where a module
          244  +dnl should install pkg-config .pc files. By default the directory is
          245  +dnl $libdir/pkgconfig, but the default can be changed by passing
          246  +dnl DIRECTORY. The user can override through the --with-pkgconfigdir
          247  +dnl parameter.
   191    248   AC_DEFUN([PKG_INSTALLDIR],
   192    249   [m4_pushdef([pkg_default], [m4_default([$1], ['${libdir}/pkgconfig'])])
   193    250   m4_pushdef([pkg_description],
   194    251       [pkg-config installation directory @<:@]pkg_default[@:>@])
   195    252   AC_ARG_WITH([pkgconfigdir],
   196    253       [AS_HELP_STRING([--with-pkgconfigdir], pkg_description)],,
   197    254       [with_pkgconfigdir=]pkg_default)
   198    255   AC_SUBST([pkgconfigdir], [$with_pkgconfigdir])
   199    256   m4_popdef([pkg_default])
   200    257   m4_popdef([pkg_description])
   201         -]) dnl PKG_INSTALLDIR
          258  +])dnl PKG_INSTALLDIR
   202    259   
   203    260   
   204         -# PKG_NOARCH_INSTALLDIR(DIRECTORY)
   205         -# -------------------------
   206         -# Substitutes the variable noarch_pkgconfigdir as the location where a
   207         -# module should install arch-independent pkg-config .pc files. By
   208         -# default the directory is $datadir/pkgconfig, but the default can be
   209         -# changed by passing DIRECTORY. The user can override through the
   210         -# --with-noarch-pkgconfigdir parameter.
          261  +dnl PKG_NOARCH_INSTALLDIR([DIRECTORY])
          262  +dnl --------------------------------
          263  +dnl Since: 0.27
          264  +dnl
          265  +dnl Substitutes the variable noarch_pkgconfigdir as the location where a
          266  +dnl module should install arch-independent pkg-config .pc files. By
          267  +dnl default the directory is $datadir/pkgconfig, but the default can be
          268  +dnl changed by passing DIRECTORY. The user can override through the
          269  +dnl --with-noarch-pkgconfigdir parameter.
   211    270   AC_DEFUN([PKG_NOARCH_INSTALLDIR],
   212    271   [m4_pushdef([pkg_default], [m4_default([$1], ['${datadir}/pkgconfig'])])
   213    272   m4_pushdef([pkg_description],
   214    273       [pkg-config arch-independent installation directory @<:@]pkg_default[@:>@])
   215    274   AC_ARG_WITH([noarch-pkgconfigdir],
   216    275       [AS_HELP_STRING([--with-noarch-pkgconfigdir], pkg_description)],,
   217    276       [with_noarch_pkgconfigdir=]pkg_default)
   218    277   AC_SUBST([noarch_pkgconfigdir], [$with_noarch_pkgconfigdir])
   219    278   m4_popdef([pkg_default])
   220    279   m4_popdef([pkg_description])
   221         -]) dnl PKG_NOARCH_INSTALLDIR
          280  +])dnl PKG_NOARCH_INSTALLDIR
   222    281   
   223    282   
   224         -# PKG_CHECK_VAR(VARIABLE, MODULE, CONFIG-VARIABLE,
   225         -# [ACTION-IF-FOUND], [ACTION-IF-NOT-FOUND])
   226         -# -------------------------------------------
   227         -# Retrieves the value of the pkg-config variable for the given module.
          283  +dnl PKG_CHECK_VAR(VARIABLE, MODULE, CONFIG-VARIABLE,
          284  +dnl [ACTION-IF-FOUND], [ACTION-IF-NOT-FOUND])
          285  +dnl -------------------------------------------
          286  +dnl Since: 0.28
          287  +dnl
          288  +dnl Retrieves the value of the pkg-config variable for the given module.
   228    289   AC_DEFUN([PKG_CHECK_VAR],
   229    290   [AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl
   230    291   AC_ARG_VAR([$1], [value of $3 for $2, overriding pkg-config])dnl
   231    292   
   232    293   _PKG_CONFIG([$1], [variable="][$3]["], [$2])
   233    294   AS_VAR_COPY([$1], [pkg_cv_][$1])
   234    295   
   235    296   AS_VAR_IF([$1], [""], [$5], [$4])dnl
   236         -])# PKG_CHECK_VAR
          297  +])dnl PKG_CHECK_VAR
   237    298   
   238         -# Copyright (C) 2002-2013 Free Software Foundation, Inc.
          299  +# Copyright (C) 2002-2014 Free Software Foundation, Inc.
   239    300   #
   240    301   # This file is free software; the Free Software Foundation
   241    302   # gives unlimited permission to copy and/or distribute it,
   242    303   # with or without modifications, as long as this notice is preserved.
   243    304   
   244    305   # AM_AUTOMAKE_VERSION(VERSION)
   245    306   # ----------------------------
   246    307   # Automake X.Y traces this macro to ensure aclocal.m4 has been
   247    308   # generated from the m4 files accompanying Automake X.Y.
   248    309   # (This private macro should not be called outside this file.)
   249    310   AC_DEFUN([AM_AUTOMAKE_VERSION],
   250         -[am__api_version='1.13'
          311  +[am__api_version='1.15'
   251    312   dnl Some users find AM_AUTOMAKE_VERSION and mistake it for a way to
   252    313   dnl require some minimum version.  Point them to the right macro.
   253         -m4_if([$1], [1.13.4], [],
          314  +m4_if([$1], [1.15], [],
   254    315         [AC_FATAL([Do not call $0, use AM_INIT_AUTOMAKE([$1]).])])dnl
   255    316   ])
   256    317   
   257    318   # _AM_AUTOCONF_VERSION(VERSION)
   258    319   # -----------------------------
   259    320   # aclocal traces this macro to find the Autoconf version.
   260    321   # This is a private macro too.  Using m4_define simplifies
................................................................................
   262    323   m4_define([_AM_AUTOCONF_VERSION], [])
   263    324   
   264    325   # AM_SET_CURRENT_AUTOMAKE_VERSION
   265    326   # -------------------------------
   266    327   # Call AM_AUTOMAKE_VERSION and AM_AUTOMAKE_VERSION so they can be traced.
   267    328   # This function is AC_REQUIREd by AM_INIT_AUTOMAKE.
   268    329   AC_DEFUN([AM_SET_CURRENT_AUTOMAKE_VERSION],
   269         -[AM_AUTOMAKE_VERSION([1.13.4])dnl
          330  +[AM_AUTOMAKE_VERSION([1.15])dnl
   270    331   m4_ifndef([AC_AUTOCONF_VERSION],
   271    332     [m4_copy([m4_PACKAGE_VERSION], [AC_AUTOCONF_VERSION])])dnl
   272    333   _AM_AUTOCONF_VERSION(m4_defn([AC_AUTOCONF_VERSION]))])
   273    334   
   274    335   # AM_AUX_DIR_EXPAND                                         -*- Autoconf -*-
   275    336   
   276         -# Copyright (C) 2001-2013 Free Software Foundation, Inc.
          337  +# Copyright (C) 2001-2014 Free Software Foundation, Inc.
   277    338   #
   278    339   # This file is free software; the Free Software Foundation
   279    340   # gives unlimited permission to copy and/or distribute it,
   280    341   # with or without modifications, as long as this notice is preserved.
   281    342   
   282    343   # For projects using AC_CONFIG_AUX_DIR([foo]), Autoconf sets
   283    344   # $ac_aux_dir to '$srcdir/foo'.  In other projects, it is set to
................................................................................
   314    375   # configure, and could therefore not use this "fixed" $ac_aux_dir.
   315    376   #
   316    377   # Another solution, used here, is to always expand $ac_aux_dir to an
   317    378   # absolute PATH.  The drawback is that using absolute paths prevent a
   318    379   # configured tree to be moved without reconfiguration.
   319    380   
   320    381   AC_DEFUN([AM_AUX_DIR_EXPAND],
   321         -[dnl Rely on autoconf to set up CDPATH properly.
   322         -AC_PREREQ([2.50])dnl
   323         -# expand $ac_aux_dir to an absolute path
   324         -am_aux_dir=`cd $ac_aux_dir && pwd`
          382  +[AC_REQUIRE([AC_CONFIG_AUX_DIR_DEFAULT])dnl
          383  +# Expand $ac_aux_dir to an absolute path.
          384  +am_aux_dir=`cd "$ac_aux_dir" && pwd`
   325    385   ])
   326    386   
   327    387   # AM_CONDITIONAL                                            -*- Autoconf -*-
   328    388   
   329         -# Copyright (C) 1997-2013 Free Software Foundation, Inc.
          389  +# Copyright (C) 1997-2014 Free Software Foundation, Inc.
   330    390   #
   331    391   # This file is free software; the Free Software Foundation
   332    392   # gives unlimited permission to copy and/or distribute it,
   333    393   # with or without modifications, as long as this notice is preserved.
   334    394   
   335    395   # AM_CONDITIONAL(NAME, SHELL-CONDITION)
   336    396   # -------------------------------------
................................................................................
   353    413   fi
   354    414   AC_CONFIG_COMMANDS_PRE(
   355    415   [if test -z "${$1_TRUE}" && test -z "${$1_FALSE}"; then
   356    416     AC_MSG_ERROR([[conditional "$1" was never defined.
   357    417   Usually this means the macro was only invoked conditionally.]])
   358    418   fi])])
   359    419   
   360         -# Copyright (C) 1999-2013 Free Software Foundation, Inc.
          420  +# Copyright (C) 1999-2014 Free Software Foundation, Inc.
   361    421   #
   362    422   # This file is free software; the Free Software Foundation
   363    423   # gives unlimited permission to copy and/or distribute it,
   364    424   # with or without modifications, as long as this notice is preserved.
   365    425   
   366    426   
   367    427   # There are a few dirty hacks below to avoid letting 'AC_PROG_CC' be
................................................................................
   544    604   _AM_SUBST_NOTMAKE([AMDEPBACKSLASH])dnl
   545    605   AC_SUBST([am__nodep])dnl
   546    606   _AM_SUBST_NOTMAKE([am__nodep])dnl
   547    607   ])
   548    608   
   549    609   # Generate code to set up dependency tracking.              -*- Autoconf -*-
   550    610   
   551         -# Copyright (C) 1999-2013 Free Software Foundation, Inc.
          611  +# Copyright (C) 1999-2014 Free Software Foundation, Inc.
   552    612   #
   553    613   # This file is free software; the Free Software Foundation
   554    614   # gives unlimited permission to copy and/or distribute it,
   555    615   # with or without modifications, as long as this notice is preserved.
   556    616   
   557    617   
   558    618   # _AM_OUTPUT_DEPENDENCY_COMMANDS
................................................................................
   620    680   [AC_CONFIG_COMMANDS([depfiles],
   621    681        [test x"$AMDEP_TRUE" != x"" || _AM_OUTPUT_DEPENDENCY_COMMANDS],
   622    682        [AMDEP_TRUE="$AMDEP_TRUE" ac_aux_dir="$ac_aux_dir"])
   623    683   ])
   624    684   
   625    685   # Do all the work for Automake.                             -*- Autoconf -*-
   626    686   
   627         -# Copyright (C) 1996-2013 Free Software Foundation, Inc.
          687  +# Copyright (C) 1996-2014 Free Software Foundation, Inc.
   628    688   #
   629    689   # This file is free software; the Free Software Foundation
   630    690   # gives unlimited permission to copy and/or distribute it,
   631    691   # with or without modifications, as long as this notice is preserved.
   632    692   
   633    693   # This macro actually does too much.  Some checks are only needed if
   634    694   # your package does certain things.  But this isn't really a big deal.
          695  +
          696  +dnl Redefine AC_PROG_CC to automatically invoke _AM_PROG_CC_C_O.
          697  +m4_define([AC_PROG_CC],
          698  +m4_defn([AC_PROG_CC])
          699  +[_AM_PROG_CC_C_O
          700  +])
   635    701   
   636    702   # AM_INIT_AUTOMAKE(PACKAGE, VERSION, [NO-DEFINE])
   637    703   # AM_INIT_AUTOMAKE([OPTIONS])
   638    704   # -----------------------------------------------
   639    705   # The call with PACKAGE and VERSION arguments is the old style
   640    706   # call (pre autoconf-2.50), which is being phased out.  PACKAGE
   641    707   # and VERSION should now be passed to AC_INIT and removed from
................................................................................
   704    770   AC_REQUIRE([AM_PROG_INSTALL_STRIP])dnl
   705    771   AC_REQUIRE([AC_PROG_MKDIR_P])dnl
   706    772   # For better backward compatibility.  To be removed once Automake 1.9.x
   707    773   # dies out for good.  For more background, see:
   708    774   # <http://lists.gnu.org/archive/html/automake/2012-07/msg00001.html>
   709    775   # <http://lists.gnu.org/archive/html/automake/2012-07/msg00014.html>
   710    776   AC_SUBST([mkdir_p], ['$(MKDIR_P)'])
   711         -# We need awk for the "check" target.  The system "awk" is bad on
   712         -# some platforms.
          777  +# We need awk for the "check" target (and possibly the TAP driver).  The
          778  +# system "awk" is bad on some platforms.
   713    779   AC_REQUIRE([AC_PROG_AWK])dnl
   714    780   AC_REQUIRE([AC_PROG_MAKE_SET])dnl
   715    781   AC_REQUIRE([AM_SET_LEADING_DOT])dnl
   716    782   _AM_IF_OPTION([tar-ustar], [_AM_PROG_TAR([ustar])],
   717    783   	      [_AM_IF_OPTION([tar-pax], [_AM_PROG_TAR([pax])],
   718    784   			     [_AM_PROG_TAR([v7])])])
   719    785   _AM_IF_OPTION([no-dependencies],,
................................................................................
   737    803   AC_REQUIRE([AM_SILENT_RULES])dnl
   738    804   dnl The testsuite driver may need to know about EXEEXT, so add the
   739    805   dnl 'am__EXEEXT' conditional if _AM_COMPILER_EXEEXT was seen.  This
   740    806   dnl macro is hooked onto _AC_COMPILER_EXEEXT early, see below.
   741    807   AC_CONFIG_COMMANDS_PRE(dnl
   742    808   [m4_provide_if([_AM_COMPILER_EXEEXT],
   743    809     [AM_CONDITIONAL([am__EXEEXT], [test -n "$EXEEXT"])])])dnl
          810  +
          811  +# POSIX will say in a future version that running "rm -f" with no argument
          812  +# is OK; and we want to be able to make that assumption in our Makefile
          813  +# recipes.  So use an aggressive probe to check that the usage we want is
          814  +# actually supported "in the wild" to an acceptable degree.
          815  +# See automake bug#10828.
          816  +# To make any issue more visible, cause the running configure to be aborted
          817  +# by default if the 'rm' program in use doesn't match our expectations; the
          818  +# user can still override this though.
          819  +if rm -f && rm -fr && rm -rf; then : OK; else
          820  +  cat >&2 <<'END'
          821  +Oops!
          822  +
          823  +Your 'rm' program seems unable to run without file operands specified
          824  +on the command line, even when the '-f' option is present.  This is contrary
          825  +to the behaviour of most rm programs out there, and not conforming with
          826  +the upcoming POSIX standard: <http://austingroupbugs.net/view.php?id=542>
          827  +
          828  +Please tell bug-automake@gnu.org about your system, including the value
          829  +of your $PATH and any error possibly output before this message.  This
          830  +can help us improve future automake versions.
          831  +
          832  +END
          833  +  if test x"$ACCEPT_INFERIOR_RM_PROGRAM" = x"yes"; then
          834  +    echo 'Configuration will proceed anyway, since you have set the' >&2
          835  +    echo 'ACCEPT_INFERIOR_RM_PROGRAM variable to "yes"' >&2
          836  +    echo >&2
          837  +  else
          838  +    cat >&2 <<'END'
          839  +Aborting the configuration process, to ensure you take notice of the issue.
          840  +
          841  +You can download and install GNU coreutils to get an 'rm' implementation
          842  +that behaves properly: <http://www.gnu.org/software/coreutils/>.
          843  +
          844  +If you want to complete the configuration process using your problematic
          845  +'rm' anyway, export the environment variable ACCEPT_INFERIOR_RM_PROGRAM
          846  +to "yes", and re-run configure.
          847  +
          848  +END
          849  +    AC_MSG_ERROR([Your 'rm' program is bad, sorry.])
          850  +  fi
          851  +fi
          852  +dnl The trailing newline in this macro's definition is deliberate, for
          853  +dnl backward compatibility and to allow trailing 'dnl'-style comments
          854  +dnl after the AM_INIT_AUTOMAKE invocation. See automake bug#16841.
   744    855   ])
   745    856   
   746    857   dnl Hook into '_AC_COMPILER_EXEEXT' early to learn its expansion.  Do not
   747    858   dnl add the conditional right here, as _AC_COMPILER_EXEEXT may be further
   748    859   dnl mangled by Autoconf and run in a shell conditional statement.
   749    860   m4_define([_AC_COMPILER_EXEEXT],
   750    861   m4_defn([_AC_COMPILER_EXEEXT])[m4_provide([_AM_COMPILER_EXEEXT])])
   751         -
   752    862   
   753    863   # When config.status generates a header, we must update the stamp-h file.
   754    864   # This file resides in the same directory as the config header
   755    865   # that is generated.  The stamp files are numbered to have different names.
   756    866   
   757    867   # Autoconf calls _AC_AM_CONFIG_HEADER_HOOK (when defined) in the
   758    868   # loop where config.status creates the headers, so we can generate
................................................................................
   767    877         break ;;
   768    878       * )
   769    879         _am_stamp_count=`expr $_am_stamp_count + 1` ;;
   770    880     esac
   771    881   done
   772    882   echo "timestamp for $_am_arg" >`AS_DIRNAME(["$_am_arg"])`/stamp-h[]$_am_stamp_count])
   773    883   
   774         -# Copyright (C) 2001-2013 Free Software Foundation, Inc.
          884  +# Copyright (C) 2001-2014 Free Software Foundation, Inc.
   775    885   #
   776    886   # This file is free software; the Free Software Foundation
   777    887   # gives unlimited permission to copy and/or distribute it,
   778    888   # with or without modifications, as long as this notice is preserved.
   779    889   
   780    890   # AM_PROG_INSTALL_SH
   781    891   # ------------------
   782    892   # Define $install_sh.
   783    893   AC_DEFUN([AM_PROG_INSTALL_SH],
   784    894   [AC_REQUIRE([AM_AUX_DIR_EXPAND])dnl
   785         -if test x"${install_sh}" != xset; then
          895  +if test x"${install_sh+set}" != xset; then
   786    896     case $am_aux_dir in
   787    897     *\ * | *\	*)
   788    898       install_sh="\${SHELL} '$am_aux_dir/install-sh'" ;;
   789    899     *)
   790    900       install_sh="\${SHELL} $am_aux_dir/install-sh"
   791    901     esac
   792    902   fi
   793    903   AC_SUBST([install_sh])])
   794    904   
   795         -# Copyright (C) 2003-2013 Free Software Foundation, Inc.
          905  +# Copyright (C) 2003-2014 Free Software Foundation, Inc.
   796    906   #
   797    907   # This file is free software; the Free Software Foundation
   798    908   # gives unlimited permission to copy and/or distribute it,
   799    909   # with or without modifications, as long as this notice is preserved.
   800    910   
   801    911   # Check whether the underlying file-system supports filenames
   802    912   # with a leading dot.  For instance MS-DOS doesn't.
................................................................................
   810    920   fi
   811    921   rmdir .tst 2>/dev/null
   812    922   AC_SUBST([am__leading_dot])])
   813    923   
   814    924   # Add --enable-maintainer-mode option to configure.         -*- Autoconf -*-
   815    925   # From Jim Meyering
   816    926   
   817         -# Copyright (C) 1996-2013 Free Software Foundation, Inc.
          927  +# Copyright (C) 1996-2014 Free Software Foundation, Inc.
   818    928   #
   819    929   # This file is free software; the Free Software Foundation
   820    930   # gives unlimited permission to copy and/or distribute it,
   821    931   # with or without modifications, as long as this notice is preserved.
   822    932   
   823    933   # AM_MAINTAINER_MODE([DEFAULT-MODE])
   824    934   # ----------------------------------
................................................................................
   845    955     MAINT=$MAINTAINER_MODE_TRUE
   846    956     AC_SUBST([MAINT])dnl
   847    957   ]
   848    958   )
   849    959   
   850    960   # Check to see how 'make' treats includes.	            -*- Autoconf -*-
   851    961   
   852         -# Copyright (C) 2001-2013 Free Software Foundation, Inc.
          962  +# Copyright (C) 2001-2014 Free Software Foundation, Inc.
   853    963   #
   854    964   # This file is free software; the Free Software Foundation
   855    965   # gives unlimited permission to copy and/or distribute it,
   856    966   # with or without modifications, as long as this notice is preserved.
   857    967   
   858    968   # AM_MAKE_INCLUDE()
   859    969   # -----------------
................................................................................
   895   1005   AC_SUBST([am__quote])
   896   1006   AC_MSG_RESULT([$_am_result])
   897   1007   rm -f confinc confmf
   898   1008   ])
   899   1009   
   900   1010   # Fake the existence of programs that GNU maintainers use.  -*- Autoconf -*-
   901   1011   
   902         -# Copyright (C) 1997-2013 Free Software Foundation, Inc.
         1012  +# Copyright (C) 1997-2014 Free Software Foundation, Inc.
   903   1013   #
   904   1014   # This file is free software; the Free Software Foundation
   905   1015   # gives unlimited permission to copy and/or distribute it,
   906   1016   # with or without modifications, as long as this notice is preserved.
   907   1017   
   908   1018   # AM_MISSING_PROG(NAME, PROGRAM)
   909   1019   # ------------------------------
................................................................................
   936   1046   fi
   937   1047   ])
   938   1048   
   939   1049   #  -*- Autoconf -*-
   940   1050   # Obsolete and "removed" macros, that must however still report explicit
   941   1051   # error messages when used, to smooth transition.
   942   1052   #
   943         -# Copyright (C) 1996-2013 Free Software Foundation, Inc.
         1053  +# Copyright (C) 1996-2014 Free Software Foundation, Inc.
   944   1054   #
   945   1055   # This file is free software; the Free Software Foundation
   946   1056   # gives unlimited permission to copy and/or distribute it,
   947   1057   # with or without modifications, as long as this notice is preserved.
   948   1058   
   949   1059   AC_DEFUN([AM_CONFIG_HEADER],
   950   1060   [AC_DIAGNOSE([obsolete],
................................................................................
   963   1073   
   964   1074   AC_DEFUN([AM_C_PROTOTYPES],
   965   1075            [AC_FATAL([automatic de-ANSI-fication support has been removed])])
   966   1076   AU_DEFUN([fp_C_PROTOTYPES], [AM_C_PROTOTYPES])
   967   1077   
   968   1078   # Helper functions for option handling.                     -*- Autoconf -*-
   969   1079   
   970         -# Copyright (C) 2001-2013 Free Software Foundation, Inc.
         1080  +# Copyright (C) 2001-2014 Free Software Foundation, Inc.
   971   1081   #
   972   1082   # This file is free software; the Free Software Foundation
   973   1083   # gives unlimited permission to copy and/or distribute it,
   974   1084   # with or without modifications, as long as this notice is preserved.
   975   1085   
   976   1086   # _AM_MANGLE_OPTION(NAME)
   977   1087   # -----------------------
................................................................................
   991   1101   [m4_foreach_w([_AM_Option], [$1], [_AM_SET_OPTION(_AM_Option)])])
   992   1102   
   993   1103   # _AM_IF_OPTION(OPTION, IF-SET, [IF-NOT-SET])
   994   1104   # -------------------------------------------
   995   1105   # Execute IF-SET if OPTION is set, IF-NOT-SET otherwise.
   996   1106   AC_DEFUN([_AM_IF_OPTION],
   997   1107   [m4_ifset(_AM_MANGLE_OPTION([$1]), [$2], [$3])])
         1108  +
         1109  +# Copyright (C) 1999-2014 Free Software Foundation, Inc.
         1110  +#
         1111  +# This file is free software; the Free Software Foundation
         1112  +# gives unlimited permission to copy and/or distribute it,
         1113  +# with or without modifications, as long as this notice is preserved.
         1114  +
         1115  +# _AM_PROG_CC_C_O
         1116  +# ---------------
         1117  +# Like AC_PROG_CC_C_O, but changed for automake.  We rewrite AC_PROG_CC
         1118  +# to automatically call this.
         1119  +AC_DEFUN([_AM_PROG_CC_C_O],
         1120  +[AC_REQUIRE([AM_AUX_DIR_EXPAND])dnl
         1121  +AC_REQUIRE_AUX_FILE([compile])dnl
         1122  +AC_LANG_PUSH([C])dnl
         1123  +AC_CACHE_CHECK(
         1124  +  [whether $CC understands -c and -o together],
         1125  +  [am_cv_prog_cc_c_o],
         1126  +  [AC_LANG_CONFTEST([AC_LANG_PROGRAM([])])
         1127  +  # Make sure it works both with $CC and with simple cc.
         1128  +  # Following AC_PROG_CC_C_O, we do the test twice because some
         1129  +  # compilers refuse to overwrite an existing .o file with -o,
         1130  +  # though they will create one.
         1131  +  am_cv_prog_cc_c_o=yes
         1132  +  for am_i in 1 2; do
         1133  +    if AM_RUN_LOG([$CC -c conftest.$ac_ext -o conftest2.$ac_objext]) \
         1134  +         && test -f conftest2.$ac_objext; then
         1135  +      : OK
         1136  +    else
         1137  +      am_cv_prog_cc_c_o=no
         1138  +      break
         1139  +    fi
         1140  +  done
         1141  +  rm -f core conftest*
         1142  +  unset am_i])
         1143  +if test "$am_cv_prog_cc_c_o" != yes; then
         1144  +   # Losing compiler, so override with the script.
         1145  +   # FIXME: It is wrong to rewrite CC.
         1146  +   # But if we don't then we get into trouble of one sort or another.
         1147  +   # A longer-term fix would be to have automake use am__CC in this case,
         1148  +   # and then we could set am__CC="\$(top_srcdir)/compile \$(CC)"
         1149  +   CC="$am_aux_dir/compile $CC"
         1150  +fi
         1151  +AC_LANG_POP([C])])
         1152  +
         1153  +# For backward compatibility.
         1154  +AC_DEFUN_ONCE([AM_PROG_CC_C_O], [AC_REQUIRE([AC_PROG_CC])])
         1155  +
         1156  +# Copyright (C) 2001-2014 Free Software Foundation, Inc.
         1157  +#
         1158  +# This file is free software; the Free Software Foundation
         1159  +# gives unlimited permission to copy and/or distribute it,
         1160  +# with or without modifications, as long as this notice is preserved.
         1161  +
         1162  +# AM_RUN_LOG(COMMAND)
         1163  +# -------------------
         1164  +# Run COMMAND, save the exit status in ac_status, and log it.
         1165  +# (This has been adapted from Autoconf's _AC_RUN_LOG macro.)
         1166  +AC_DEFUN([AM_RUN_LOG],
         1167  +[{ echo "$as_me:$LINENO: $1" >&AS_MESSAGE_LOG_FD
         1168  +   ($1) >&AS_MESSAGE_LOG_FD 2>&AS_MESSAGE_LOG_FD
         1169  +   ac_status=$?
         1170  +   echo "$as_me:$LINENO: \$? = $ac_status" >&AS_MESSAGE_LOG_FD
         1171  +   (exit $ac_status); }])
   998   1172   
   999   1173   # Check to make sure that the build environment is sane.    -*- Autoconf -*-
  1000   1174   
  1001         -# Copyright (C) 1996-2013 Free Software Foundation, Inc.
         1175  +# Copyright (C) 1996-2014 Free Software Foundation, Inc.
  1002   1176   #
  1003   1177   # This file is free software; the Free Software Foundation
  1004   1178   # gives unlimited permission to copy and/or distribute it,
  1005   1179   # with or without modifications, as long as this notice is preserved.
  1006   1180   
  1007   1181   # AM_SANITY_CHECK
  1008   1182   # ---------------
................................................................................
  1075   1249        # Hide warnings about reused PIDs.
  1076   1250        wait $am_sleep_pid 2>/dev/null
  1077   1251      fi
  1078   1252      AC_MSG_RESULT([done])])
  1079   1253   rm -f conftest.file
  1080   1254   ])
  1081   1255   
  1082         -# Copyright (C) 2009-2013 Free Software Foundation, Inc.
         1256  +# Copyright (C) 2009-2014 Free Software Foundation, Inc.
  1083   1257   #
  1084   1258   # This file is free software; the Free Software Foundation
  1085   1259   # gives unlimited permission to copy and/or distribute it,
  1086   1260   # with or without modifications, as long as this notice is preserved.
  1087   1261   
  1088   1262   # AM_SILENT_RULES([DEFAULT])
  1089   1263   # --------------------------
................................................................................
  1135   1309   AM_SUBST_NOTMAKE([AM_DEFAULT_V])dnl
  1136   1310   AC_SUBST([AM_DEFAULT_VERBOSITY])dnl
  1137   1311   AM_BACKSLASH='\'
  1138   1312   AC_SUBST([AM_BACKSLASH])dnl
  1139   1313   _AM_SUBST_NOTMAKE([AM_BACKSLASH])dnl
  1140   1314   ])
  1141   1315   
  1142         -# Copyright (C) 2001-2013 Free Software Foundation, Inc.
         1316  +# Copyright (C) 2001-2014 Free Software Foundation, Inc.
  1143   1317   #
  1144   1318   # This file is free software; the Free Software Foundation
  1145   1319   # gives unlimited permission to copy and/or distribute it,
  1146   1320   # with or without modifications, as long as this notice is preserved.
  1147   1321   
  1148   1322   # AM_PROG_INSTALL_STRIP
  1149   1323   # ---------------------
................................................................................
  1163   1337   dnl Don't test for $cross_compiling = yes, because it might be 'maybe'.
  1164   1338   if test "$cross_compiling" != no; then
  1165   1339     AC_CHECK_TOOL([STRIP], [strip], :)
  1166   1340   fi
  1167   1341   INSTALL_STRIP_PROGRAM="\$(install_sh) -c -s"
  1168   1342   AC_SUBST([INSTALL_STRIP_PROGRAM])])
  1169   1343   
  1170         -# Copyright (C) 2006-2013 Free Software Foundation, Inc.
         1344  +# Copyright (C) 2006-2014 Free Software Foundation, Inc.
  1171   1345   #
  1172   1346   # This file is free software; the Free Software Foundation
  1173   1347   # gives unlimited permission to copy and/or distribute it,
  1174   1348   # with or without modifications, as long as this notice is preserved.
  1175   1349   
  1176   1350   # _AM_SUBST_NOTMAKE(VARIABLE)
  1177   1351   # ---------------------------
................................................................................
  1182   1356   # AM_SUBST_NOTMAKE(VARIABLE)
  1183   1357   # --------------------------
  1184   1358   # Public sister of _AM_SUBST_NOTMAKE.
  1185   1359   AC_DEFUN([AM_SUBST_NOTMAKE], [_AM_SUBST_NOTMAKE($@)])
  1186   1360   
  1187   1361   # Check how to create a tarball.                            -*- Autoconf -*-
  1188   1362   
  1189         -# Copyright (C) 2004-2013 Free Software Foundation, Inc.
         1363  +# Copyright (C) 2004-2014 Free Software Foundation, Inc.
  1190   1364   #
  1191   1365   # This file is free software; the Free Software Foundation
  1192   1366   # gives unlimited permission to copy and/or distribute it,
  1193   1367   # with or without modifications, as long as this notice is preserved.
  1194   1368   
  1195   1369   # _AM_PROG_TAR(FORMAT)
  1196   1370   # --------------------

Added compile.

            1  +/usr/share/automake-1.15/compile

Changes to config.h.

     1      1   /* config.h.  Generated from config.h.in by configure.  */
     2      2   /* config.h.in.  Generated from configure.ac by autoheader.  */
     3      3   
     4      4   /* Should be defined in order to enable LIBXML2 support. */
     5      5   #define ENABLE_LIBXML2 1
            6  +
            7  +/* Should be defined in order to enable RTTOPO support. */
            8  +#define ENABLE_RTTOPO 1
     6      9   
     7     10   /* depending on SQLite library version. */
     8     11   #define HAVE_DECL_SQLITE_CONFIG_URI 1
     9     12   
    10     13   /* depending on SQLite library version. */
    11     14   #define HAVE_DECL_SQLITE_DBSTATUS_CACHE_HIT 1
    12     15   
................................................................................
    83     86   #define HAVE_INTTYPES_H 1
    84     87   
    85     88   /* Define to 1 if you have the `expat' library (-lexpat). */
    86     89   #define HAVE_LIBEXPAT 1
    87     90   
    88     91   /* Define to 1 if you have the `proj' library (-lproj). */
    89     92   #define HAVE_LIBPROJ 1
           93  +
           94  +/* Define to 1 if you have the `sqlite3' library (-lsqlite3). */
           95  +#define HAVE_LIBSQLITE3 1
    90     96   
    91     97   /* Define to 1 if you have the `localtime_r' function. */
    92     98   #define HAVE_LOCALTIME_R 1
    93     99   
    94    100   /* Define to 1 if `lstat' has the bug that it succeeds when given the
    95    101      zero-length file name argument. */
    96    102   /* #undef HAVE_LSTAT_EMPTY_STRING_BUG */
................................................................................
   105    111   #define HAVE_MEMORY_H 1
   106    112   
   107    113   /* Define to 1 if you have the `memset' function. */
   108    114   #define HAVE_MEMSET 1
   109    115   
   110    116   /* Define to 1 if you have the `readline' function. */
   111    117   #define HAVE_READLINE 1
          118  +
          119  +/* Define to 1 if you have the <sqlite3ext.h> header file. */
          120  +#define HAVE_SQLITE3EXT_H 1
          121  +
          122  +/* Define to 1 if you have the <sqlite3.h> header file. */
          123  +#define HAVE_SQLITE3_H 1
   112    124   
   113    125   /* Define to 1 if you have the `sqrt' function. */
   114    126   /* #undef HAVE_SQRT */
   115    127   
   116    128   /* Define to 1 if `stat' has the bug that it succeeds when given the
   117    129      zero-length file name argument. */
   118    130   /* #undef HAVE_STAT_EMPTY_STRING_BUG */
................................................................................
   182    194   /* Define to the address where bug reports for this package should be sent. */
   183    195   #define PACKAGE_BUGREPORT "a.furieri@lqt.it"
   184    196   
   185    197   /* Define to the full name of this package. */
   186    198   #define PACKAGE_NAME "spatialite-tools"
   187    199   
   188    200   /* Define to the full name and version of this package. */
   189         -#define PACKAGE_STRING "spatialite-tools 4.2.1-rc1"
          201  +#define PACKAGE_STRING "spatialite-tools 4.5.0-devel"
   190    202   
   191    203   /* Define to the one symbol short name of this package. */
   192    204   #define PACKAGE_TARNAME "spatialite-tools"
   193    205   
   194    206   /* Define to the home page for this package. */
   195    207   #define PACKAGE_URL ""
   196    208   
   197    209   /* Define to the version of this package. */
   198         -#define PACKAGE_VERSION "4.2.1-rc1"
          210  +#define PACKAGE_VERSION "4.5.0-devel"
   199    211   
   200    212   /* must be defined when using libspatialite-amalgamation */
   201    213   /* #undef SPATIALITE_AMALGAMATION */
   202    214   
   203    215   /* Define to 1 if you have the ANSI C header files. */
   204    216   #define STDC_HEADERS 1
   205    217   
................................................................................
   206    218   /* Define to 1 if you can safely include both <sys/time.h> and <time.h>. */
   207    219   #define TIME_WITH_SYS_TIME 1
   208    220   
   209    221   /* Define to 1 if your <sys/time.h> declares `struct tm'. */
   210    222   /* #undef TM_IN_SYS_TIME */
   211    223   
   212    224   /* Version number of package */
   213         -#define VERSION "4.2.1-rc1"
          225  +#define VERSION "4.5.0-devel"
   214    226   
   215    227   /* Define to empty if `const' does not conform to ANSI C. */
   216    228   /* #undef const */
   217    229   
   218    230   /* Define to `long int' if <sys/types.h> does not define. */
   219    231   /* #undef off_t */
   220    232   
   221    233   /* Define to `unsigned int' if <sys/types.h> does not define. */
   222    234   /* #undef size_t */
   223    235   
   224    236   /* Define to empty if the keyword `volatile' does not work. Warning: valid
   225    237      code using `volatile' can become incorrect without. Disable with care. */
   226    238   /* #undef volatile */

Changes to config.h.in.

     1      1   /* config.h.in.  Generated from configure.ac by autoheader.  */
     2      2   
     3      3   /* Should be defined in order to enable LIBXML2 support. */
     4      4   #undef ENABLE_LIBXML2
            5  +
            6  +/* Should be defined in order to enable RTTOPO support. */
            7  +#undef ENABLE_RTTOPO
     5      8   
     6      9   /* depending on SQLite library version. */
     7     10   #undef HAVE_DECL_SQLITE_CONFIG_URI
     8     11   
     9     12   /* depending on SQLite library version. */
    10     13   #undef HAVE_DECL_SQLITE_DBSTATUS_CACHE_HIT
    11     14   
................................................................................
    82     85   #undef HAVE_INTTYPES_H
    83     86   
    84     87   /* Define to 1 if you have the `expat' library (-lexpat). */
    85     88   #undef HAVE_LIBEXPAT
    86     89   
    87     90   /* Define to 1 if you have the `proj' library (-lproj). */
    88     91   #undef HAVE_LIBPROJ
           92  +
           93  +/* Define to 1 if you have the `sqlite3' library (-lsqlite3). */
           94  +#undef HAVE_LIBSQLITE3
    89     95   
    90     96   /* Define to 1 if you have the `localtime_r' function. */
    91     97   #undef HAVE_LOCALTIME_R
    92     98   
    93     99   /* Define to 1 if `lstat' has the bug that it succeeds when given the
    94    100      zero-length file name argument. */
    95    101   #undef HAVE_LSTAT_EMPTY_STRING_BUG
................................................................................
   104    110   #undef HAVE_MEMORY_H
   105    111   
   106    112   /* Define to 1 if you have the `memset' function. */
   107    113   #undef HAVE_MEMSET
   108    114   
   109    115   /* Define to 1 if you have the `readline' function. */
   110    116   #undef HAVE_READLINE
          117  +
          118  +/* Define to 1 if you have the <sqlite3ext.h> header file. */
          119  +#undef HAVE_SQLITE3EXT_H
          120  +
          121  +/* Define to 1 if you have the <sqlite3.h> header file. */
          122  +#undef HAVE_SQLITE3_H
   111    123   
   112    124   /* Define to 1 if you have the `sqrt' function. */
   113    125   #undef HAVE_SQRT
   114    126   
   115    127   /* Define to 1 if `stat' has the bug that it succeeds when given the
   116    128      zero-length file name argument. */
   117    129   #undef HAVE_STAT_EMPTY_STRING_BUG

Changes to configure.

     1      1   #! /bin/sh
     2      2   # Guess values for system-dependent variables and create Makefiles.
     3         -# Generated by GNU Autoconf 2.69 for spatialite-tools 4.2.1-rc1.
            3  +# Generated by GNU Autoconf 2.69 for spatialite-tools 4.5.0-devel.
     4      4   #
     5      5   # Report bugs to <a.furieri@lqt.it>.
     6      6   #
     7      7   #
     8      8   # Copyright (C) 1992-1996, 1998-2012 Free Software Foundation, Inc.
     9      9   #
    10     10   #
................................................................................
   586    586   subdirs=
   587    587   MFLAGS=
   588    588   MAKEFLAGS=
   589    589   
   590    590   # Identity of this package.
   591    591   PACKAGE_NAME='spatialite-tools'
   592    592   PACKAGE_TARNAME='spatialite-tools'
   593         -PACKAGE_VERSION='4.2.1-rc1'
   594         -PACKAGE_STRING='spatialite-tools 4.2.1-rc1'
          593  +PACKAGE_VERSION='4.5.0-devel'
          594  +PACKAGE_STRING='spatialite-tools 4.5.0-devel'
   595    595   PACKAGE_BUGREPORT='a.furieri@lqt.it'
   596    596   PACKAGE_URL=''
   597    597   
   598    598   # Factoring default headers for most tests.
   599    599   ac_includes_default="\
   600    600   #include <stdio.h>
   601    601   #ifdef HAVE_SYS_TYPES_H
................................................................................
   630    630   #ifdef HAVE_UNISTD_H
   631    631   # include <unistd.h>
   632    632   #endif"
   633    633   
   634    634   ac_subst_vars='am__EXEEXT_FALSE
   635    635   am__EXEEXT_TRUE
   636    636   LTLIBOBJS
          637  +RTTOPO_LIBS
          638  +RTTOPO_CFLAGS
   637    639   LIBXML2_LIBS
   638    640   LIBXML2_CFLAGS
   639    641   NO_READOSM_FALSE
   640    642   NO_READOSM_TRUE
   641    643   LIBREADOSM_CFLAGS
   642    644   LIBREADOSM_LIBS
   643    645   LIBFREEXL_LIBS
................................................................................
   789    791   with_sysroot
   790    792   enable_libtool_lock
   791    793   enable_readline
   792    794   with_geosconfig
   793    795   enable_freexl
   794    796   enable_readosm
   795    797   enable_libxml2
          798  +enable_rttopo
   796    799   '
   797    800         ac_precious_vars='build_alias
   798    801   host_alias
   799    802   target_alias
   800    803   CC
   801    804   CFLAGS
   802    805   LDFLAGS
................................................................................
   813    816   LIBSPATIALITE_CFLAGS
   814    817   LIBSPATIALITE_LIBS
   815    818   LIBFREEXL_CFLAGS
   816    819   LIBFREEXL_LIBS
   817    820   LIBREADOSM_CFLAGS
   818    821   LIBREADOSM_LIBS
   819    822   LIBXML2_CFLAGS
   820         -LIBXML2_LIBS'
          823  +LIBXML2_LIBS
          824  +RTTOPO_CFLAGS
          825  +RTTOPO_LIBS'
   821    826   
   822    827   
   823    828   # Initialize some variables set by options.
   824    829   ac_init_help=
   825    830   ac_init_version=false
   826    831   ac_unrecognized_opts=
   827    832   ac_unrecognized_sep=
................................................................................
  1354   1359   #
  1355   1360   # Report the --help message.
  1356   1361   #
  1357   1362   if test "$ac_init_help" = "long"; then
  1358   1363     # Omit some internal or obsolete options to make the list less imposing.
  1359   1364     # This message is too long to be a string in the A/UX 3.1 sh.
  1360   1365     cat <<_ACEOF
  1361         -\`configure' configures spatialite-tools 4.2.1-rc1 to adapt to many kinds of systems.
         1366  +\`configure' configures spatialite-tools 4.5.0-devel to adapt to many kinds of systems.
  1362   1367   
  1363   1368   Usage: $0 [OPTION]... [VAR=VALUE]...
  1364   1369   
  1365   1370   To assign environment variables (e.g., CC, CFLAGS...), specify them as
  1366   1371   VAR=VALUE.  See below for descriptions of some of the useful variables.
  1367   1372   
  1368   1373   Defaults for the options are specified in brackets.
................................................................................
  1425   1430     --build=BUILD     configure for building on BUILD [guessed]
  1426   1431     --host=HOST       cross-compile to build programs to run on HOST [BUILD]
  1427   1432   _ACEOF
  1428   1433   fi
  1429   1434   
  1430   1435   if test -n "$ac_init_help"; then
  1431   1436     case $ac_init_help in
  1432         -     short | recursive ) echo "Configuration of spatialite-tools 4.2.1-rc1:";;
         1437  +     short | recursive ) echo "Configuration of spatialite-tools 4.5.0-devel:";;
  1433   1438      esac
  1434   1439     cat <<\_ACEOF
  1435   1440   
  1436   1441   Optional Features:
  1437   1442     --disable-option-checking  ignore unrecognized --enable/--with options
  1438   1443     --disable-FEATURE       do not include FEATURE (same as --enable-FEATURE=no)
  1439   1444     --enable-FEATURE[=ARG]  include FEATURE [ARG=yes]
................................................................................
  1451   1456     --enable-fast-install[=PKGS]
  1452   1457                             optimize for fast installation [default=yes]
  1453   1458     --disable-libtool-lock  avoid locking (might break parallel builds)
  1454   1459     --enable-readline       use readline in shell tool (yes, no) [default=yes]
  1455   1460     --enable-freexl         enables FreeXL inclusion [default=yes]
  1456   1461     --enable-readosm        enables ReadOSM inclusion [default=yes]
  1457   1462     --enable-libxml2        enables libxml2 inclusion [default=yes]
         1463  +  --enable-rttopo         enables librttopo inclusion [default=yes]
  1458   1464   
  1459   1465   Optional Packages:
  1460   1466     --with-PACKAGE[=ARG]    use PACKAGE [ARG=yes]
  1461   1467     --without-PACKAGE       do not use PACKAGE (same as --with-PACKAGE=no)
  1462   1468     --with-pic              try to use only PIC/non-PIC objects [default=use
  1463   1469                             both]
  1464   1470     --with-gnu-ld           assume the C compiler uses GNU ld [default=no]
................................................................................
  1495   1501                 C compiler flags for LIBREADOSM, overriding pkg-config
  1496   1502     LIBREADOSM_LIBS
  1497   1503                 linker flags for LIBREADOSM, overriding pkg-config
  1498   1504     LIBXML2_CFLAGS
  1499   1505                 C compiler flags for LIBXML2, overriding pkg-config
  1500   1506     LIBXML2_LIBS
  1501   1507                 linker flags for LIBXML2, overriding pkg-config
         1508  +  RTTOPO_CFLAGS
         1509  +              C compiler flags for RTTOPO, overriding pkg-config
         1510  +  RTTOPO_LIBS linker flags for RTTOPO, overriding pkg-config
  1502   1511   
  1503   1512   Use these variables to override the choices made by `configure' or to help
  1504   1513   it to find libraries and programs with nonstandard names/locations.
  1505   1514   
  1506   1515   Report bugs to <a.furieri@lqt.it>.
  1507   1516   _ACEOF
  1508   1517   ac_status=$?
................................................................................
  1562   1571       cd "$ac_pwd" || { ac_status=$?; break; }
  1563   1572     done
  1564   1573   fi
  1565   1574   
  1566   1575   test -n "$ac_init_help" && exit $ac_status
  1567   1576   if $ac_init_version; then
  1568   1577     cat <<\_ACEOF
  1569         -spatialite-tools configure 4.2.1-rc1
         1578  +spatialite-tools configure 4.5.0-devel
  1570   1579   generated by GNU Autoconf 2.69
  1571   1580   
  1572   1581   Copyright (C) 2012 Free Software Foundation, Inc.
  1573   1582   This configure script is free software; the Free Software Foundation
  1574   1583   gives unlimited permission to copy, distribute and modify it.
  1575   1584   _ACEOF
  1576   1585     exit
................................................................................
  2152   2161     eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
  2153   2162   
  2154   2163   } # ac_fn_c_check_decl
  2155   2164   cat >config.log <<_ACEOF
  2156   2165   This file contains any messages produced by compilers while
  2157   2166   running configure, to aid debugging if configure makes a mistake.
  2158   2167   
  2159         -It was created by spatialite-tools $as_me 4.2.1-rc1, which was
         2168  +It was created by spatialite-tools $as_me 4.5.0-devel, which was
  2160   2169   generated by GNU Autoconf 2.69.  Invocation command line was
  2161   2170   
  2162   2171     $ $0 $@
  2163   2172   
  2164   2173   _ACEOF
  2165   2174   exec 5>>config.log
  2166   2175   {
................................................................................
  2508   2517   ac_cpp='$CPP $CPPFLAGS'
  2509   2518   ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
  2510   2519   ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
  2511   2520   ac_compiler_gnu=$ac_cv_c_compiler_gnu
  2512   2521   
  2513   2522   
  2514   2523   
  2515         -am__api_version='1.13'
         2524  +am__api_version='1.15'
  2516   2525   
  2517   2526   ac_aux_dir=
  2518   2527   for ac_dir in "$srcdir" "$srcdir/.." "$srcdir/../.."; do
  2519   2528     if test -f "$ac_dir/install-sh"; then
  2520   2529       ac_aux_dir=$ac_dir
  2521   2530       ac_install_sh="$ac_aux_dir/install-sh -c"
  2522   2531       break
................................................................................
  2709   2718   test "$program_suffix" != NONE &&
  2710   2719     program_transform_name="s&\$&$program_suffix&;$program_transform_name"
  2711   2720   # Double any \ or $.
  2712   2721   # By default was `s,x,x', remove it if useless.
  2713   2722   ac_script='s/[\\$]/&&/g;s/;s,x,x,$//'
  2714   2723   program_transform_name=`$as_echo "$program_transform_name" | sed "$ac_script"`
  2715   2724   
  2716         -# expand $ac_aux_dir to an absolute path
  2717         -am_aux_dir=`cd $ac_aux_dir && pwd`
         2725  +# Expand $ac_aux_dir to an absolute path.
         2726  +am_aux_dir=`cd "$ac_aux_dir" && pwd`
  2718   2727   
  2719   2728   if test x"${MISSING+set}" != xset; then
  2720   2729     case $am_aux_dir in
  2721   2730     *\ * | *\	*)
  2722   2731       MISSING="\${SHELL} \"$am_aux_dir/missing\"" ;;
  2723   2732     *)
  2724   2733       MISSING="\${SHELL} $am_aux_dir/missing" ;;
................................................................................
  2729   2738     am_missing_run="$MISSING "
  2730   2739   else
  2731   2740     am_missing_run=
  2732   2741     { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: 'missing' script is too old or missing" >&5
  2733   2742   $as_echo "$as_me: WARNING: 'missing' script is too old or missing" >&2;}
  2734   2743   fi
  2735   2744   
  2736         -if test x"${install_sh}" != xset; then
         2745  +if test x"${install_sh+set}" != xset; then
  2737   2746     case $am_aux_dir in
  2738   2747     *\ * | *\	*)
  2739   2748       install_sh="\${SHELL} '$am_aux_dir/install-sh'" ;;
  2740   2749     *)
  2741   2750       install_sh="\${SHELL} $am_aux_dir/install-sh"
  2742   2751     esac
  2743   2752   fi
................................................................................
  3023   3032       CYGPATH_W=echo
  3024   3033     fi
  3025   3034   fi
  3026   3035   
  3027   3036   
  3028   3037   # Define the identity of the package.
  3029   3038    PACKAGE='spatialite-tools'
  3030         - VERSION='4.2.1-rc1'
         3039  + VERSION='4.5.0-devel'
  3031   3040   
  3032   3041   
  3033   3042   cat >>confdefs.h <<_ACEOF
  3034   3043   #define PACKAGE "$PACKAGE"
  3035   3044   _ACEOF
  3036   3045   
  3037   3046   
................................................................................
  3057   3066   
  3058   3067   # For better backward compatibility.  To be removed once Automake 1.9.x
  3059   3068   # dies out for good.  For more background, see:
  3060   3069   # <http://lists.gnu.org/archive/html/automake/2012-07/msg00001.html>
  3061   3070   # <http://lists.gnu.org/archive/html/automake/2012-07/msg00014.html>
  3062   3071   mkdir_p='$(MKDIR_P)'
  3063   3072   
  3064         -# We need awk for the "check" target.  The system "awk" is bad on
  3065         -# some platforms.
         3073  +# We need awk for the "check" target (and possibly the TAP driver).  The
         3074  +# system "awk" is bad on some platforms.
  3066   3075   # Always define AMTAR for backward compatibility.  Yes, it's still used
  3067   3076   # in the wild :-(  We should find a proper way to deprecate it ...
  3068   3077   AMTAR='$${TAR-tar}'
  3069   3078   
  3070   3079   
  3071   3080   # We'll loop over all known methods to create a tar archive until one works.
  3072   3081   _am_tools='gnutar  pax cpio none'
................................................................................
  3073   3082   
  3074   3083   am__tar='$${TAR-tar} chof - "$$tardir"' am__untar='$${TAR-tar} xf -'
  3075   3084   
  3076   3085   
  3077   3086   
  3078   3087   
  3079   3088   
         3089  +
         3090  +# POSIX will say in a future version that running "rm -f" with no argument
         3091  +# is OK; and we want to be able to make that assumption in our Makefile
         3092  +# recipes.  So use an aggressive probe to check that the usage we want is
         3093  +# actually supported "in the wild" to an acceptable degree.
         3094  +# See automake bug#10828.
         3095  +# To make any issue more visible, cause the running configure to be aborted
         3096  +# by default if the 'rm' program in use doesn't match our expectations; the
         3097  +# user can still override this though.
         3098  +if rm -f && rm -fr && rm -rf; then : OK; else
         3099  +  cat >&2 <<'END'
         3100  +Oops!
         3101  +
         3102  +Your 'rm' program seems unable to run without file operands specified
         3103  +on the command line, even when the '-f' option is present.  This is contrary
         3104  +to the behaviour of most rm programs out there, and not conforming with
         3105  +the upcoming POSIX standard: <http://austingroupbugs.net/view.php?id=542>
         3106  +
         3107  +Please tell bug-automake@gnu.org about your system, including the value
         3108  +of your $PATH and any error possibly output before this message.  This
         3109  +can help us improve future automake versions.
         3110  +
         3111  +END
         3112  +  if test x"$ACCEPT_INFERIOR_RM_PROGRAM" = x"yes"; then
         3113  +    echo 'Configuration will proceed anyway, since you have set the' >&2
         3114  +    echo 'ACCEPT_INFERIOR_RM_PROGRAM variable to "yes"' >&2
         3115  +    echo >&2
         3116  +  else
         3117  +    cat >&2 <<'END'
         3118  +Aborting the configuration process, to ensure you take notice of the issue.
         3119  +
         3120  +You can download and install GNU coreutils to get an 'rm' implementation
         3121  +that behaves properly: <http://www.gnu.org/software/coreutils/>.
         3122  +
         3123  +If you want to complete the configuration process using your problematic
         3124  +'rm' anyway, export the environment variable ACCEPT_INFERIOR_RM_PROGRAM
         3125  +to "yes", and re-run configure.
         3126  +
         3127  +END
         3128  +    as_fn_error $? "Your 'rm' program is bad, sorry." "$LINENO" 5
         3129  +  fi
         3130  +fi
  3080   3131   
  3081   3132   
  3082   3133   { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to enable maintainer-specific portions of Makefiles" >&5
  3083   3134   $as_echo_n "checking whether to enable maintainer-specific portions of Makefiles... " >&6; }
  3084   3135       # Check whether --enable-maintainer-mode was given.
  3085   3136   if test "${enable_maintainer_mode+set}" = set; then :
  3086   3137     enableval=$enable_maintainer_mode; USE_MAINTAINER_MODE=$enableval
................................................................................
  3101   3152     MAINT=$MAINTAINER_MODE_TRUE
  3102   3153   
  3103   3154   
  3104   3155   ac_config_headers="$ac_config_headers config.h"
  3105   3156   
  3106   3157   
  3107   3158   # supporting SPATIALITE_AMALGAMATION
         3159  +
  3108   3160   
  3109   3161   
  3110   3162   
  3111   3163   
  3112   3164   
  3113   3165   
  3114   3166   
................................................................................
  3975   4027   fi
  3976   4028   
  3977   4029   ac_ext=c
  3978   4030   ac_cpp='$CPP $CPPFLAGS'
  3979   4031   ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
  3980   4032   ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
  3981   4033   ac_compiler_gnu=$ac_cv_c_compiler_gnu
         4034  +
         4035  +ac_ext=c
         4036  +ac_cpp='$CPP $CPPFLAGS'
         4037  +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
         4038  +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
         4039  +ac_compiler_gnu=$ac_cv_c_compiler_gnu
         4040  +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC understands -c and -o together" >&5
         4041  +$as_echo_n "checking whether $CC understands -c and -o together... " >&6; }
         4042  +if ${am_cv_prog_cc_c_o+:} false; then :
         4043  +  $as_echo_n "(cached) " >&6
         4044  +else
         4045  +  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
         4046  +/* end confdefs.h.  */
         4047  +
         4048  +int
         4049  +main ()
         4050  +{
         4051  +
         4052  +  ;
         4053  +  return 0;
         4054  +}
         4055  +_ACEOF
         4056  +  # Make sure it works both with $CC and with simple cc.
         4057  +  # Following AC_PROG_CC_C_O, we do the test twice because some
         4058  +  # compilers refuse to overwrite an existing .o file with -o,
         4059  +  # though they will create one.
         4060  +  am_cv_prog_cc_c_o=yes
         4061  +  for am_i in 1 2; do
         4062  +    if { echo "$as_me:$LINENO: $CC -c conftest.$ac_ext -o conftest2.$ac_objext" >&5
         4063  +   ($CC -c conftest.$ac_ext -o conftest2.$ac_objext) >&5 2>&5
         4064  +   ac_status=$?
         4065  +   echo "$as_me:$LINENO: \$? = $ac_status" >&5
         4066  +   (exit $ac_status); } \
         4067  +         && test -f conftest2.$ac_objext; then
         4068  +      : OK
         4069  +    else
         4070  +      am_cv_prog_cc_c_o=no
         4071  +      break
         4072  +    fi
         4073  +  done
         4074  +  rm -f core conftest*
         4075  +  unset am_i
         4076  +fi
         4077  +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $am_cv_prog_cc_c_o" >&5
         4078  +$as_echo "$am_cv_prog_cc_c_o" >&6; }
         4079  +if test "$am_cv_prog_cc_c_o" != yes; then
         4080  +   # Losing compiler, so override with the script.
         4081  +   # FIXME: It is wrong to rewrite CC.
         4082  +   # But if we don't then we get into trouble of one sort or another.
         4083  +   # A longer-term fix would be to have automake use am__CC in this case,
         4084  +   # and then we could set am__CC="\$(top_srcdir)/compile \$(CC)"
         4085  +   CC="$am_aux_dir/compile $CC"
         4086  +fi
         4087  +ac_ext=c
         4088  +ac_cpp='$CPP $CPPFLAGS'
         4089  +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
         4090  +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
         4091  +ac_compiler_gnu=$ac_cv_c_compiler_gnu
         4092  +
  3982   4093   
  3983   4094   depcc="$CC"   am_compiler_list=
  3984   4095   
  3985   4096   { $as_echo "$as_me:${as_lineno-$LINENO}: checking dependency style of $depcc" >&5
  3986   4097   $as_echo_n "checking dependency style of $depcc... " >&6; }
  3987   4098   if ${am_cv_CC_dependencies_compiler_type+:} false; then :
  3988   4099     $as_echo_n "(cached) " >&6
................................................................................
  4667   4778     cat >>confdefs.h <<_ACEOF
  4668   4779   #define HAVE_UNISTD_H 1
  4669   4780   _ACEOF
  4670   4781   
  4671   4782   else
  4672   4783     as_fn_error $? "cannot find unistd.h, bailing out" "$LINENO" 5
  4673   4784   fi
         4785  +
         4786  +done
         4787  +
         4788  +for ac_header in sqlite3.h
         4789  +do :
         4790  +  ac_fn_c_check_header_mongrel "$LINENO" "sqlite3.h" "ac_cv_header_sqlite3_h" "$ac_includes_default"
         4791  +if test "x$ac_cv_header_sqlite3_h" = xyes; then :
         4792  +  cat >>confdefs.h <<_ACEOF
         4793  +#define HAVE_SQLITE3_H 1
         4794  +_ACEOF
         4795  +
         4796  +else
         4797  +  as_fn_error $? "cannot find sqlite3.h, bailing out" "$LINENO" 5
         4798  +fi
         4799  +
         4800  +done
         4801  +
         4802  +for ac_header in sqlite3ext.h
         4803  +do :
         4804  +  ac_fn_c_check_header_mongrel "$LINENO" "sqlite3ext.h" "ac_cv_header_sqlite3ext_h" "$ac_includes_default"
         4805  +if test "x$ac_cv_header_sqlite3ext_h" = xyes; then :
         4806  +  cat >>confdefs.h <<_ACEOF
         4807  +#define HAVE_SQLITE3EXT_H 1
         4808  +_ACEOF
         4809  +
         4810  +else
         4811  +  as_fn_error $? "cannot find sqlite3ext.h, bailing out" "$LINENO" 5
         4812  +fi
  4674   4813   
  4675   4814   done
  4676   4815   
  4677   4816   
  4678   4817   # Checks for programs.
  4679   4818   ac_ext=cpp
  4680   4819   ac_cpp='$CXXCPP $CPPFLAGS'
................................................................................
  5595   5734   fi
  5596   5735   
  5597   5736   ac_ext=c
  5598   5737   ac_cpp='$CPP $CPPFLAGS'
  5599   5738   ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
  5600   5739   ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
  5601   5740   ac_compiler_gnu=$ac_cv_c_compiler_gnu
         5741  +
         5742  +ac_ext=c
         5743  +ac_cpp='$CPP $CPPFLAGS'
         5744  +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
         5745  +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
         5746  +ac_compiler_gnu=$ac_cv_c_compiler_gnu
         5747  +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC understands -c and -o together" >&5
         5748  +$as_echo_n "checking whether $CC understands -c and -o together... " >&6; }
         5749  +if ${am_cv_prog_cc_c_o+:} false; then :
         5750  +  $as_echo_n "(cached) " >&6
         5751  +else
         5752  +  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
         5753  +/* end confdefs.h.  */
         5754  +
         5755  +int
         5756  +main ()
         5757  +{
         5758  +
         5759  +  ;
         5760  +  return 0;
         5761  +}
         5762  +_ACEOF
         5763  +  # Make sure it works both with $CC and with simple cc.
         5764  +  # Following AC_PROG_CC_C_O, we do the test twice because some
         5765  +  # compilers refuse to overwrite an existing .o file with -o,
         5766  +  # though they will create one.
         5767  +  am_cv_prog_cc_c_o=yes
         5768  +  for am_i in 1 2; do
         5769  +    if { echo "$as_me:$LINENO: $CC -c conftest.$ac_ext -o conftest2.$ac_objext" >&5
         5770  +   ($CC -c conftest.$ac_ext -o conftest2.$ac_objext) >&5 2>&5
         5771  +   ac_status=$?
         5772  +   echo "$as_me:$LINENO: \$? = $ac_status" >&5
         5773  +   (exit $ac_status); } \
         5774  +         && test -f conftest2.$ac_objext; then
         5775  +      : OK
         5776  +    else
         5777  +      am_cv_prog_cc_c_o=no
         5778  +      break
         5779  +    fi
         5780  +  done
         5781  +  rm -f core conftest*
         5782  +  unset am_i
         5783  +fi
         5784  +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $am_cv_prog_cc_c_o" >&5
         5785  +$as_echo "$am_cv_prog_cc_c_o" >&6; }
         5786  +if test "$am_cv_prog_cc_c_o" != yes; then
         5787  +   # Losing compiler, so override with the script.
         5788  +   # FIXME: It is wrong to rewrite CC.
         5789  +   # But if we don't then we get into trouble of one sort or another.
         5790  +   # A longer-term fix would be to have automake use am__CC in this case,
         5791  +   # and then we could set am__CC="\$(top_srcdir)/compile \$(CC)"
         5792  +   CC="$am_aux_dir/compile $CC"
         5793  +fi
         5794  +ac_ext=c
         5795  +ac_cpp='$CPP $CPPFLAGS'
         5796  +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
         5797  +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
         5798  +ac_compiler_gnu=$ac_cv_c_compiler_gnu
         5799  +
  5602   5800   
  5603   5801   depcc="$CC"   am_compiler_list=
  5604   5802   
  5605   5803   { $as_echo "$as_me:${as_lineno-$LINENO}: checking dependency style of $depcc" >&5
  5606   5804   $as_echo_n "checking dependency style of $depcc... " >&6; }
  5607   5805   if ${am_cv_CC_dependencies_compiler_type+:} false; then :
  5608   5806     $as_echo_n "(cached) " >&6
................................................................................
 17083  17281     cat >>confdefs.h <<_ACEOF
 17084  17282   #define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1
 17085  17283   _ACEOF
 17086  17284   
 17087  17285   fi
 17088  17286   done
 17089  17287   
        17288  +
        17289  +# Checks for installed libraries
        17290  +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for sqlite3_prepare_v2 in -lsqlite3" >&5
        17291  +$as_echo_n "checking for sqlite3_prepare_v2 in -lsqlite3... " >&6; }
        17292  +if ${ac_cv_lib_sqlite3_sqlite3_prepare_v2+:} false; then :
        17293  +  $as_echo_n "(cached) " >&6
        17294  +else
        17295  +  ac_check_lib_save_LIBS=$LIBS
        17296  +LIBS="-lsqlite3 -lm $LIBS"
        17297  +cat confdefs.h - <<_ACEOF >conftest.$ac_ext
        17298  +/* end confdefs.h.  */
        17299  +
        17300  +/* Override any GCC internal prototype to avoid an error.
        17301  +   Use char because int might match the return type of a GCC
        17302  +   builtin and then its argument prototype would still apply.  */
        17303  +#ifdef __cplusplus
        17304  +extern "C"
        17305  +#endif
        17306  +char sqlite3_prepare_v2 ();
        17307  +int
        17308  +main ()
        17309  +{
        17310  +return sqlite3_prepare_v2 ();
        17311  +  ;
        17312  +  return 0;
        17313  +}
        17314  +_ACEOF
        17315  +if ac_fn_c_try_link "$LINENO"; then :
        17316  +  ac_cv_lib_sqlite3_sqlite3_prepare_v2=yes
        17317  +else
        17318  +  ac_cv_lib_sqlite3_sqlite3_prepare_v2=no
        17319  +fi
        17320  +rm -f core conftest.err conftest.$ac_objext \
        17321  +    conftest$ac_exeext conftest.$ac_ext
        17322  +LIBS=$ac_check_lib_save_LIBS
        17323  +fi
        17324  +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_sqlite3_sqlite3_prepare_v2" >&5
        17325  +$as_echo "$ac_cv_lib_sqlite3_sqlite3_prepare_v2" >&6; }
        17326  +if test "x$ac_cv_lib_sqlite3_sqlite3_prepare_v2" = xyes; then :
        17327  +  cat >>confdefs.h <<_ACEOF
        17328  +#define HAVE_LIBSQLITE3 1
        17329  +_ACEOF
        17330  +
        17331  +  LIBS="-lsqlite3 $LIBS"
        17332  +
        17333  +else
        17334  +  as_fn_error $? "'libsqlite3' is required but it doesn't seem to be installed on this system." "$LINENO" 5
        17335  +fi
        17336  +
 17090  17337   
 17091  17338   ac_config_files="$ac_config_files Makefile"
 17092  17339   
 17093  17340   
 17094  17341   #-----------------------------------------------------------------------
 17095  17342   #   --enable-readline
 17096  17343   #
................................................................................
 17866  18113   else
 17867  18114   	LIBREADOSM_CFLAGS=$pkg_cv_LIBREADOSM_CFLAGS
 17868  18115   	LIBREADOSM_LIBS=$pkg_cv_LIBREADOSM_LIBS
 17869  18116           { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
 17870  18117   $as_echo "yes" >&6; }
 17871  18118   
 17872  18119   fi
        18120  +  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for library containing readosm_version" >&5
        18121  +$as_echo_n "checking for library containing readosm_version... " >&6; }
        18122  +if ${ac_cv_search_readosm_version+:} false; then :
        18123  +  $as_echo_n "(cached) " >&6
        18124  +else
        18125  +  ac_func_search_save_LIBS=$LIBS
        18126  +cat confdefs.h - <<_ACEOF >conftest.$ac_ext
        18127  +/* end confdefs.h.  */
        18128  +
        18129  +/* Override any GCC internal prototype to avoid an error.
        18130  +   Use char because int might match the return type of a GCC
        18131  +   builtin and then its argument prototype would still apply.  */
        18132  +#ifdef __cplusplus
        18133  +extern "C"
        18134  +#endif
        18135  +char readosm_version ();
        18136  +int
        18137  +main ()
        18138  +{
        18139  +return readosm_version ();
        18140  +  ;
        18141  +  return 0;
        18142  +}
        18143  +_ACEOF
        18144  +for ac_lib in '' readosm; do
        18145  +  if test -z "$ac_lib"; then
        18146  +    ac_res="none required"
        18147  +  else
        18148  +    ac_res=-l$ac_lib
        18149  +    LIBS="-l$ac_lib  $ac_func_search_save_LIBS"
        18150  +  fi
        18151  +  if ac_fn_c_try_link "$LINENO"; then :
        18152  +  ac_cv_search_readosm_version=$ac_res
        18153  +fi
        18154  +rm -f core conftest.err conftest.$ac_objext \
        18155  +    conftest$ac_exeext
        18156  +  if ${ac_cv_search_readosm_version+:} false; then :
        18157  +  break
        18158  +fi
        18159  +done
        18160  +if ${ac_cv_search_readosm_version+:} false; then :
        18161  +
        18162  +else
        18163  +  ac_cv_search_readosm_version=no
        18164  +fi
        18165  +rm conftest.$ac_ext
        18166  +LIBS=$ac_func_search_save_LIBS
        18167  +fi
        18168  +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_search_readosm_version" >&5
        18169  +$as_echo "$ac_cv_search_readosm_version" >&6; }
        18170  +ac_res=$ac_cv_search_readosm_version
        18171  +if test "$ac_res" != no; then :
        18172  +  test "$ac_res" = "none required" || LIBS="$ac_res $LIBS"
        18173  +
        18174  +else
        18175  +  as_fn_error $? "'libreadosm' (>= v.1.1.0) is required but an older version was found." "$LINENO" 5
        18176  +fi
        18177  +
 17873  18178   
 17874  18179   
 17875  18180   else
 17876  18181     $as_echo "#define OMIT_READOSM 1" >>confdefs.h
 17877  18182   
 17878  18183     NOREADOSM="true"
 17879  18184   fi
................................................................................
 17969  18274   $as_echo "yes" >&6; }
 17970  18275   
 17971  18276   fi
 17972  18277   
 17973  18278   
 17974  18279     $as_echo "#define ENABLE_LIBXML2 1" >>confdefs.h
 17975  18280   
        18281  +fi
        18282  +
        18283  +#-----------------------------------------------------------------------
        18284  +#   --enable-rttopo
        18285  +#
        18286  +# Check whether --enable-rttopo was given.
        18287  +if test "${enable_rttopo+set}" = set; then :
        18288  +  enableval=$enable_rttopo;
        18289  +else
        18290  +  enable_rttopo=yes
        18291  +fi
        18292  +
        18293  +if test x"$enable_rttopo" != "xno"; then
        18294  +
        18295  +pkg_failed=no
        18296  +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for RTTOPO" >&5
        18297  +$as_echo_n "checking for RTTOPO... " >&6; }
        18298  +
        18299  +if test -n "$RTTOPO_CFLAGS"; then
        18300  +    pkg_cv_RTTOPO_CFLAGS="$RTTOPO_CFLAGS"
        18301  + elif test -n "$PKG_CONFIG"; then
        18302  +    if test -n "$PKG_CONFIG" && \
        18303  +    { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"rttopo\""; } >&5
        18304  +  ($PKG_CONFIG --exists --print-errors "rttopo") 2>&5
        18305  +  ac_status=$?
        18306  +  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
        18307  +  test $ac_status = 0; }; then
        18308  +  pkg_cv_RTTOPO_CFLAGS=`$PKG_CONFIG --cflags "rttopo" 2>/dev/null`
        18309  +		      test "x$?" != "x0" && pkg_failed=yes
        18310  +else
        18311  +  pkg_failed=yes
        18312  +fi
        18313  + else
        18314  +    pkg_failed=untried
        18315  +fi
        18316  +if test -n "$RTTOPO_LIBS"; then
        18317  +    pkg_cv_RTTOPO_LIBS="$RTTOPO_LIBS"
        18318  + elif test -n "$PKG_CONFIG"; then
        18319  +    if test -n "$PKG_CONFIG" && \
        18320  +    { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"rttopo\""; } >&5
        18321  +  ($PKG_CONFIG --exists --print-errors "rttopo") 2>&5
        18322  +  ac_status=$?
        18323  +  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
        18324  +  test $ac_status = 0; }; then
        18325  +  pkg_cv_RTTOPO_LIBS=`$PKG_CONFIG --libs "rttopo" 2>/dev/null`
        18326  +		      test "x$?" != "x0" && pkg_failed=yes
        18327  +else
        18328  +  pkg_failed=yes
        18329  +fi
        18330  + else
        18331  +    pkg_failed=untried
        18332  +fi
        18333  +
        18334  +
        18335  +
        18336  +if test $pkg_failed = yes; then
        18337  +   	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
        18338  +$as_echo "no" >&6; }
        18339  +
        18340  +if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then
        18341  +        _pkg_short_errors_supported=yes
        18342  +else
        18343  +        _pkg_short_errors_supported=no
        18344  +fi
        18345  +        if test $_pkg_short_errors_supported = yes; then
        18346  +	        RTTOPO_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "rttopo" 2>&1`
        18347  +        else
        18348  +	        RTTOPO_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "rttopo" 2>&1`
        18349  +        fi
        18350  +	# Put the nasty error message in config.log where it belongs
        18351  +	echo "$RTTOPO_PKG_ERRORS" >&5
        18352  +
        18353  +	as_fn_error $? "'librttopo' is required but it doesn't seem to be installed on this system." "$LINENO" 5
        18354  +elif test $pkg_failed = untried; then
        18355  +     	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
        18356  +$as_echo "no" >&6; }
        18357  +	as_fn_error $? "'librttopo' is required but it doesn't seem to be installed on this system." "$LINENO" 5
        18358  +else
        18359  +	RTTOPO_CFLAGS=$pkg_cv_RTTOPO_CFLAGS
        18360  +	RTTOPO_LIBS=$pkg_cv_RTTOPO_LIBS
        18361  +        { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
        18362  +$as_echo "yes" >&6; }
        18363  +
        18364  +fi
        18365  +
        18366  +
        18367  +  $as_echo "#define ENABLE_RTTOPO 1" >>confdefs.h
        18368  +
 17976  18369   fi
 17977  18370   
 17978  18371   # checks for SQLite version-depending constants
 17979  18372   ac_fn_c_check_decl "$LINENO" "SQLITE_CONFIG_URI" "ac_cv_have_decl_SQLITE_CONFIG_URI" "#include <sqlite3.h>
 17980  18373   "
 17981  18374   if test "x$ac_cv_have_decl_SQLITE_CONFIG_URI" = xyes; then :
 17982  18375     $as_echo "#define HAVE_DECL_SQLITE_CONFIG_URI 1" >>confdefs.h
................................................................................
 18630  19023   test $as_write_fail = 0 && chmod +x $CONFIG_STATUS || ac_write_fail=1
 18631  19024   
 18632  19025   cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
 18633  19026   # Save the log message, to keep $0 and so on meaningful, and to
 18634  19027   # report actual input values of CONFIG_FILES etc. instead of their
 18635  19028   # values after options handling.
 18636  19029   ac_log="
 18637         -This file was extended by spatialite-tools $as_me 4.2.1-rc1, which was
        19030  +This file was extended by spatialite-tools $as_me 4.5.0-devel, which was
 18638  19031   generated by GNU Autoconf 2.69.  Invocation command line was
 18639  19032   
 18640  19033     CONFIG_FILES    = $CONFIG_FILES
 18641  19034     CONFIG_HEADERS  = $CONFIG_HEADERS
 18642  19035     CONFIG_LINKS    = $CONFIG_LINKS
 18643  19036     CONFIG_COMMANDS = $CONFIG_COMMANDS
 18644  19037     $ $0 $@
................................................................................
 18696  19089   
 18697  19090   Report bugs to <a.furieri@lqt.it>."
 18698  19091   
 18699  19092   _ACEOF
 18700  19093   cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
 18701  19094   ac_cs_config="`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`"
 18702  19095   ac_cs_version="\\
 18703         -spatialite-tools config.status 4.2.1-rc1
        19096  +spatialite-tools config.status 4.5.0-devel
 18704  19097   configured by $0, generated by GNU Autoconf 2.69,
 18705  19098     with options \\"\$ac_cs_config\\"
 18706  19099   
 18707  19100   Copyright (C) 2012 Free Software Foundation, Inc.
 18708  19101   This config.status script is free software; the Free Software Foundation
 18709  19102   gives unlimited permission to copy, distribute and modify it."
 18710  19103   

Changes to configure.ac.

     1      1   #                                               -*- Autoconf -*-
     2      2   # Process this file with autoconf to produce a configure script.
     3      3   
     4      4   AC_PREREQ(2.61)
     5         -AC_INIT(spatialite-tools, 4.2.1-rc1, a.furieri@lqt.it)
            5  +AC_INIT(spatialite-tools, 4.5.0-devel, a.furieri@lqt.it)
     6      6   AC_LANG(C)
     7      7   AC_CONFIG_MACRO_DIR([m4])
     8      8   
     9      9   AM_INIT_AUTOMAKE
    10     10   AM_MAINTAINER_MODE
    11     11   AM_CONFIG_HEADER(config.h)
    12     12   
................................................................................
    15     15   	    [must be defined when using libspatialite-amalgamation])
    16     16   AH_TEMPLATE([OMIT_FREEXL],
    17     17               [Should be defined in order to disable FREEXL support.])
    18     18   AH_TEMPLATE([OMIT_READOSM],
    19     19               [Should be defined in order to disable ReadOSM support.])
    20     20   AH_TEMPLATE([ENABLE_LIBXML2],
    21     21               [Should be defined in order to enable LIBXML2 support.])
           22  +AH_TEMPLATE([ENABLE_RTTOPO],
           23  +            [Should be defined in order to enable RTTOPO support.])
    22     24   AH_TEMPLATE([HAVE_DECL_SQLITE_CONFIG_URI],
    23     25               [depending on SQLite library version.])
    24     26   AH_TEMPLATE([HAVE_DECL_SQLITE_DBSTATUS_LOOKASIDE_USED],
    25     27               [depending on SQLite library version.])
    26     28   AH_TEMPLATE([HAVE_DECL_SQLITE_DBSTATUS_LOOKASIDE_HIT],
    27     29               [depending on SQLite library version.])
    28     30   AH_TEMPLATE([HAVE_DECL_SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE],
................................................................................
    63     65   AC_CHECK_HEADERS(float.h,, [AC_MSG_ERROR([cannot find float.h, bailing out])])
    64     66   AC_CHECK_HEADERS(fcntl.h,, [AC_MSG_ERROR([cannot find fcntl.h, bailing out])])
    65     67   AC_CHECK_HEADERS(inttypes.h,, [AC_MSG_ERROR([cannot find inttypes.h, bailing out])])
    66     68   AC_CHECK_HEADERS(stddef.h,, [AC_MSG_ERROR([cannot find stddef.h, bailing out])])
    67     69   AC_CHECK_HEADERS(stdint.h,, [AC_MSG_ERROR([cannot find stdint.h, bailing out])])
    68     70   AC_CHECK_HEADERS(sys/time.h,, [AC_MSG_ERROR([cannot find sys/time.h, bailing out])])
    69     71   AC_CHECK_HEADERS(unistd.h,, [AC_MSG_ERROR([cannot find unistd.h, bailing out])])
           72  +AC_CHECK_HEADERS(sqlite3.h,, [AC_MSG_ERROR([cannot find sqlite3.h, bailing out])])
           73  +AC_CHECK_HEADERS(sqlite3ext.h,, [AC_MSG_ERROR([cannot find sqlite3ext.h, bailing out])])
    70     74   
    71     75   # Checks for programs.
    72     76   AC_PROG_CXX
    73     77   AC_PROG_CC
    74     78   AC_PROG_CPP
    75     79   AC_PROG_INSTALL
    76     80   AC_PROG_LN_S
................................................................................
    89     93   # Checks for library functions.
    90     94   AC_FUNC_LSTAT
    91     95   AC_FUNC_LSTAT_FOLLOWS_SLASHED_SYMLINK
    92     96   AC_FUNC_MEMCMP
    93     97   AC_FUNC_STAT
    94     98   AC_FUNC_STRFTIME
    95     99   AC_CHECK_FUNCS([memset sqrt strcasecmp strerror strncasecmp strstr fdatasync ftruncate getcwd gettimeofday localtime_r memmove strerror])
          100  + 
          101  +# Checks for installed libraries
          102  +AC_CHECK_LIB(sqlite3,sqlite3_prepare_v2,,AC_MSG_ERROR(['libsqlite3' is required but it doesn't seem to be installed on this system.]),-lm)
    96    103   
    97    104   AC_CONFIG_FILES([Makefile])
    98    105   
    99    106   #-----------------------------------------------------------------------
   100    107   #   --enable-readline
   101    108   #
   102    109   AC_ARG_ENABLE(readline, [AS_HELP_STRING(
................................................................................
   186    193   #   --enable-readosm
   187    194   #
   188    195   AC_ARG_ENABLE(readosm, [AS_HELP_STRING(
   189    196     [--enable-readosm], [enables ReadOSM inclusion [default=yes]])],
   190    197     [], [enable_readosm=yes])
   191    198   if test x"$enable_readosm" != "xno"; then
   192    199     AC_SUBST(LIBREADOSM_LIBS)PKG_CHECK_MODULES([LIBREADOSM], [readosm], , AC_MSG_ERROR(['libreadosm' is required but it doesn't seem to be installed on this system.]))
          200  +  AC_SEARCH_LIBS(readosm_version,readosm,,AC_MSG_ERROR(['libreadosm' (>= v.1.1.0) is required but an older version was found.]))
   193    201     AC_SUBST(LIBREADOSM_CFLAGS)
   194    202     AC_SUBST(LIBREADOSM_LIBS)
   195    203   else
   196    204     AC_DEFINE(OMIT_READOSM)
   197    205     NOREADOSM="true"
   198    206   fi
   199    207   
................................................................................
   207    215     [], [enable_libxml2=yes])
   208    216   if test x"$enable_libxml2" != "xno"; then
   209    217     PKG_CHECK_MODULES([LIBXML2], [libxml-2.0], , AC_MSG_ERROR(['libxml2' is required but it doesn't seem to be installed on this system.]))
   210    218     AC_SUBST(LIBXML2_CFLAGS)
   211    219     AC_SUBST(LIBXML2_LIBS)
   212    220     AC_DEFINE(ENABLE_LIBXML2)
   213    221   fi
          222  +
          223  +#-----------------------------------------------------------------------
          224  +#   --enable-rttopo
          225  +#
          226  +AC_ARG_ENABLE(rttopo, [AS_HELP_STRING(
          227  +  [--enable-rttopo], [enables librttopo inclusion [default=yes]])],
          228  +  [], [enable_rttopo=yes])
          229  +if test x"$enable_rttopo" != "xno"; then
          230  +  PKG_CHECK_MODULES([RTTOPO], [rttopo], , AC_MSG_ERROR(['librttopo' is required but it doesn't seem to be installed on this system.]))
          231  +  AC_SUBST(RTTOPO_CFLAGS)
          232  +  AC_SUBST(RTTOPO_LIBS)
          233  +  AC_DEFINE(ENABLE_RTTOPO)
          234  +fi
   214    235   
   215    236   # checks for SQLite version-depending constants
   216    237   AC_CHECK_DECL([SQLITE_CONFIG_URI],
   217    238     [AC_DEFINE(HAVE_DECL_SQLITE_CONFIG_URI)],[],[[#include <sqlite3.h>]])
   218    239   AC_CHECK_DECL([SQLITE_DBSTATUS_LOOKASIDE_USED],
   219    240     [AC_DEFINE(HAVE_DECL_SQLITE_DBSTATUS_LOOKASIDE_USED)],[],[[#include <sqlite3.h>]])
   220    241   AC_CHECK_DECL([SQLITE_DBSTATUS_LOOKASIDE_HIT],

Changes to exif_loader.c.

  1425   1425         }
  1426   1426       sqlite3_free_table (results);
  1427   1427   
  1428   1428       if (count > 0)
  1429   1429   	return;
  1430   1430   
  1431   1431   /* all right, it's empty: proceeding to initialize */
  1432         -    strcpy (sql, "SELECT InitSpatialMetadata(1)");
         1432  +    strcpy (sql, "SELECT InitSpatialMetadataFull(1)");
  1433   1433       ret = sqlite3_exec (db, sql, NULL, NULL, &err_msg);
  1434   1434       if (ret != SQLITE_OK)
  1435   1435         {
  1436         -	  fprintf (stderr, "InitSpatialMetadata() error: %s\n", err_msg);
         1436  +	  fprintf (stderr, "InitSpatialMetadataFull() error: %s\n", err_msg);
  1437   1437   	  sqlite3_free (err_msg);
  1438   1438   	  return;
  1439   1439         }
  1440   1440   }
         1441  +
         1442  +static void
         1443  +do_version ()
         1444  +{
         1445  +/* printing version infos */
         1446  +	fprintf( stderr, "\nVersion infos\n");
         1447  +	fprintf( stderr, "===========================================\n");
         1448  +    fprintf (stderr, "exif_loader .: %s\n", VERSION);
         1449  +	fprintf (stderr, "target CPU ..: %s\n", spatialite_target_cpu ());
         1450  +    fprintf (stderr, "libspatialite: %s\n", spatialite_version ());
         1451  +    fprintf (stderr, "libsqlite3 ..: %s\n", sqlite3_libversion ());
         1452  +    fprintf (stderr, "\n");
         1453  +}
  1441   1454   
  1442   1455   static void
  1443   1456   do_help ()
  1444   1457   {
  1445   1458   /* printing the argument list */
  1446   1459       fprintf (stderr, "\n\nusage: exif_loader ARGLIST\n");
  1447   1460       fprintf (stderr,
  1448   1461   	     "==============================================================\n");
  1449   1462       fprintf (stderr,
  1450   1463   	     "-h or --help                    print this help message\n");
         1464  +    fprintf (stderr, "-v or --version                 print version infos\n");
  1451   1465       fprintf (stderr,
  1452   1466   	     "-d or --db-path    pathname     the SpatiaLite db path\n");
  1453   1467       fprintf (stderr,
  1454   1468   	     "-D or --dir        dir_path     the DIR path containing EXIF files\n");
  1455   1469       fprintf (stderr, "-f or --file-path  file_name    a single EXIF file\n\n");
  1456   1470       fprintf (stderr, "you can specify the following options as well\n");
  1457   1471       fprintf (stderr, "--any-exif         *default*\n");
................................................................................
  1497   1511   		continue;
  1498   1512   	    }
  1499   1513   	  if (strcasecmp (argv[i], "--help") == 0
  1500   1514   	      || strcmp (argv[i], "-h") == 0)
  1501   1515   	    {
  1502   1516   		do_help ();
  1503   1517   		return -1;
         1518  +	    }
         1519  +	  if (strcasecmp (argv[i], "--version") == 0
         1520  +	      || strcmp (argv[i], "-v") == 0)
         1521  +	    {
         1522  +		do_version ();
         1523  +		return -1;
  1504   1524   	    }
  1505   1525   	  if (strcasecmp (argv[i], "--db-path") == 0)
  1506   1526   	    {
  1507   1527   		next_arg = ARG_DB_PATH;
  1508   1528   		continue;
  1509   1529   	    }
  1510   1530   	  if (strcmp (argv[i], "-d") == 0)
................................................................................
  1613   1633   	fprintf (stderr, "sqlite3_close() error: %s\n",
  1614   1634   		 sqlite3_errmsg (handle));
  1615   1635       spatialite_cleanup_ex (cache);
  1616   1636       if (cnt)
  1617   1637   	fprintf (stderr,
  1618   1638   		 "\n\n***   %d EXIF photo%s successfully inserted into the DB\n",
  1619   1639   		 cnt, (cnt > 1) ? "s where" : " was");
  1620         -spatialite_shutdown();
         1640  +    spatialite_shutdown ();
  1621   1641       return 0;
  1622   1642   }

Changes to makefile.vc.

     3      3   # NMAKE Makefile to build SpatiaLite-tools on Windows
     4      4   #
     5      5   !INCLUDE nmake.opt
     6      6   
     7      7   SPATIALITE_EXE            = spatialite.exe
     8      8   EXIF_LOADER_EXE           = exif_loader.exe
     9      9   SHP_DOCTOR_EXE            = shp_doctor.exe
           10  +SHP_SANITIZE_EXE            = shp_sanitize.exe
    10     11   SPATIALITE_NETWORK_EXE    = spatialite_network.exe
    11     12   SPATIALITE_TOOL_EXE       = spatialite_tool.exe
    12     13   SPATIALITE_OSM_NET_EXE    = spatialite_osm_net.exe
    13     14   SPATIALITE_OSM_MAP_EXE    = spatialite_osm_map.exe
    14     15   SPATIALITE_OSM_RAW_EXE    = spatialite_osm_raw.exe
    15     16   SPATIALITE_OSM_FILTER_EXE = spatialite_osm_filter.exe
    16     17   SPATIALITE_GML_EXE        = spatialite_gml.exe
................................................................................
    19     20   
    20     21   default:	all
    21     22   
    22     23   all: $(SPATIALITE_EXE) $(SHP_DOCTOR_EXE) $(SPATIALITE_TOOL_EXE) \
    23     24   	$(SPATIALITE_NETWORK_EXE) $(EXIF_LOADER_EXE) \
    24     25   	$(SPATIALITE_OSM_NET_EXE) $(SPATIALITE_OSM_MAP_EXE) \
    25     26   	$(SPATIALITE_GML_EXE) $(SPATIALITE_OSM_RAW_EXE) \
    26         -	$(SPATIALITE_OSM_FILTER_EXE)
           27  +	$(SPATIALITE_OSM_FILTER_EXE) $(SHP_SANITIZE_EXE)
    27     28   
    28     29   $(SPATIALITE_EXE): shell.obj
    29     30   	cl shell.obj C:\OSGeo4W\lib\proj_i.lib \
    30     31   		C:\OSGeo4W\lib\iconv.lib C:\OSGeo4W\lib\geos_c.lib \
    31     32   		C:\OSGeo4W\lib\spatialite_i.lib C:\OSGeo4W\lib\sqlite3_i.lib \
    32     33   		/Fe$(SPATIALITE_EXE)
    33     34   	if exist $(SPATIALITE_EXE).manifest mt -manifest \
................................................................................
    43     44   $(SHP_DOCTOR_EXE):	shp_doctor.obj
    44     45   	cl shp_doctor.obj  C:\OSGeo4W\lib\proj_i.lib \
    45     46   		C:\OSGeo4W\lib\iconv.lib C:\OSGeo4W\lib\geos_c.lib \
    46     47   		C:\OSGeo4W\lib\spatialite_i.lib C:\OSGeo4W\lib\sqlite3_i.lib 
    47     48   	if exist $(SHP_DOCTOR_EXE).manifest mt -manifest \
    48     49   		$(SHP_DOCTOR_EXE).manifest -outputresource:$(SHP_DOCTOR_EXE);1
    49     50   
           51  +$(SHP_SANITIZE_EXE):	shp_sanitize.obj
           52  +	cl shp_sanitize.obj  C:\OSGeo4W\lib\proj_i.lib \
           53  +		C:\OSGeo4W\lib\iconv.lib C:\OSGeo4W\lib\geos_c.lib \
           54  +		C:\OSGeo4W\lib\spatialite_i.lib C:\OSGeo4W\lib\sqlite3_i.lib 
           55  +	if exist $(SHP_SANITIZE_EXE).manifest mt -manifest \
           56  +		$(SHP_SANITIZE_EXE).manifest -outputresource:$(SHP_SANITIZE_EXE);1
           57  +
    50     58   $(SPATIALITE_NETWORK_EXE):	spatialite_network.obj
    51     59   	cl spatialite_network.obj C:\OSGeo4W\lib\proj_i.lib \
    52     60   		C:\OSGeo4W\lib\iconv.lib \
    53     61   		C:\OSGeo4W\lib\spatialite_i.lib C:\OSGeo4W\lib\sqlite3_i.lib 
    54     62   	if exist $(SPATIALITE_NETWORK_EXE).manifest mt -manifest \
    55     63   		$(SPATIALITE_TOOL_EXE).manifest \
    56     64   		-outputresource:$(SPATIALITE_TOOL_EXE);1

Changes to shell.c.

    67     67   #include <stdarg.h>
    68     68   
    69     69   #ifdef _WIN32
    70     70   #define strcasecmp	_stricmp
    71     71   #endif /* not WIN32 */
    72     72   
    73     73   #if !defined(_WIN32) && !defined(WIN32)
    74         -# include <signal.h>
    75         -# if !defined(__RTP__) && !defined(_WRS_KERNEL)
    76         -#  include <pwd.h>
    77         -# endif
    78         -# include <unistd.h>
    79         -# include <sys/types.h>
           74  +#include <signal.h>
           75  +#if !defined(__RTP__) && !defined(_WRS_KERNEL)
           76  +#include <pwd.h>
           77  +#endif
           78  +#include <unistd.h>
           79  +#include <sys/types.h>
    80     80   #endif
    81     81   
    82     82   #ifdef HAVE_EDITLINE
    83         -# include <editline/editline.h>
           83  +#include <editline/editline.h>
    84     84   #endif
    85     85   #if defined(HAVE_READLINE) && HAVE_READLINE==1
    86         -# include <readline/readline.h>
    87         -# include <readline/history.h>
           86  +#include <readline/readline.h>
           87  +#include <readline/history.h>
    88     88   #endif
    89     89   #if !defined(HAVE_EDITLINE) && (!defined(HAVE_READLINE) || HAVE_READLINE!=1)
    90         -# define readline(p) local_getline(p,stdin,0)
    91         -# define add_history(X)
    92         -# define read_history(X)
    93         -# define write_history(X)
    94         -# define stifle_history(X)
           90  +#define readline(p) local_getline(p,stdin,0)
           91  +#define add_history(X)
           92  +#define read_history(X)
           93  +#define write_history(X)
           94  +#define stifle_history(X)
    95     95   #endif
    96     96   
    97     97   #if defined(_WIN32) || defined(WIN32)
    98         -# include <io.h>
           98  +#include <io.h>
    99     99   #define isatty(h) _isatty(h)
   100    100   #define access(f,m) _access((f),(m))
   101    101   #undef popen
   102    102   #define popen(a,b) _popen((a),(b))
   103    103   #undef pclose
   104    104   #define pclose(x) _pclose(x)
   105    105   #else
   106    106   /* Make sure isatty() has a prototype.
   107    107   */
   108         -extern int isatty(int);
          108  +extern int isatty (int);
   109    109   #endif
   110    110   
   111    111   #if defined(_WIN32_WCE)
   112    112   /* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
   113    113    * thus we always assume that we have a console. That can be
   114    114    * overridden with the -batch command line option.
   115    115    */
................................................................................
   134    134   
   135    135   /* Saved resource information for the beginning of an operation */
   136    136   static struct rusage sBegin;
   137    137   
   138    138   /*
   139    139   ** Begin timing an operation
   140    140   */
   141         -static void beginTimer(void){
   142         -  if( enableTimer ){
   143         -    getrusage(RUSAGE_SELF, &sBegin);
   144         -  }
          141  +static void
          142  +beginTimer (void)
          143  +{
          144  +    if (enableTimer)
          145  +      {
          146  +	  getrusage (RUSAGE_SELF, &sBegin);
          147  +      }
   145    148   }
   146    149   
   147    150   /* Return the difference of two time_structs in seconds */
   148         -static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
   149         -  return (pEnd->tv_usec - pStart->tv_usec)*0.000001 + 
   150         -         (double)(pEnd->tv_sec - pStart->tv_sec);
          151  +static double
          152  +timeDiff (struct timeval *pStart, struct timeval *pEnd)
          153  +{
          154  +    return (pEnd->tv_usec - pStart->tv_usec) * 0.000001 +
          155  +	(double) (pEnd->tv_sec - pStart->tv_sec);
   151    156   }
   152    157   
   153    158   /*
   154    159   ** Print the timing results.
   155    160   */
   156         -static void endTimer(void){
   157         -  if( enableTimer ){
   158         -    struct rusage sEnd;
   159         -    getrusage(RUSAGE_SELF, &sEnd);
   160         -    printf("CPU Time: user %f sys %f\n",
   161         -       timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
   162         -       timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
   163         -  }
          161  +static void
          162  +endTimer (void)
          163  +{
          164  +    if (enableTimer)
          165  +      {
          166  +	  struct rusage sEnd;
          167  +	  getrusage (RUSAGE_SELF, &sEnd);
          168  +	  printf ("CPU Time: user %f sys %f\n",
          169  +		  timeDiff (&sBegin.ru_utime, &sEnd.ru_utime),
          170  +		  timeDiff (&sBegin.ru_stime, &sEnd.ru_stime));
          171  +      }
   164    172   }
   165    173   
   166    174   #define BEGIN_TIMER beginTimer()
   167    175   #define END_TIMER endTimer()
   168    176   #define HAS_TIMER 1
   169    177   
   170    178   #elif (defined(_WIN32) || defined(WIN32))
................................................................................
   171    179   
   172    180   #include <windows.h>
   173    181   
   174    182   /* Saved resource information for the beginning of an operation */
   175    183   static HANDLE hProcess;
   176    184   static FILETIME ftKernelBegin;
   177    185   static FILETIME ftUserBegin;
   178         -typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME, LPFILETIME, LPFILETIME);
          186  +typedef BOOL (WINAPI * GETPROCTIMES) (HANDLE, LPFILETIME, LPFILETIME,
          187  +				      LPFILETIME, LPFILETIME);
   179    188   static GETPROCTIMES getProcessTimesAddr = NULL;
   180    189   
   181    190   /*
   182    191   ** Check to see if we have timer support.  Return 1 if necessary
   183    192   ** support found (or found previously).
   184    193   */
   185         -static int hasTimer(void){
   186         -  if( getProcessTimesAddr ){
   187         -    return 1;
   188         -  } else {
   189         -    /* GetProcessTimes() isn't supported in WIN95 and some other Windows versions.
   190         -    ** See if the version we are running on has it, and if it does, save off
   191         -    ** a pointer to it and the current process handle.
   192         -    */
   193         -    hProcess = GetCurrentProcess();
   194         -    if( hProcess ){
   195         -      HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
   196         -      if( NULL != hinstLib ){
   197         -        getProcessTimesAddr = (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
   198         -        if( NULL != getProcessTimesAddr ){
   199         -          return 1;
   200         -        }
   201         -        FreeLibrary(hinstLib); 
   202         -      }
   203         -    }
   204         -  }
   205         -  return 0;
   206         -}
   207         -
   208         -/*
   209         -** Begin timing an operation
   210         -*/
   211         -static void beginTimer(void){
   212         -  if( enableTimer && getProcessTimesAddr ){
   213         -    FILETIME ftCreation, ftExit;
   214         -    getProcessTimesAddr(hProcess, &ftCreation, &ftExit, &ftKernelBegin, &ftUserBegin);
   215         -  }
          194  +static int
          195  +hasTimer (void)
          196  +{
          197  +    if (getProcessTimesAddr)
          198  +      {
          199  +	  return 1;
          200  +      }
          201  +    else
          202  +      {
          203  +	  /* GetProcessTimes() isn't supported in WIN95 and some other Windows versions.
          204  +	   ** See if the version we are running on has it, and if it does, save off
          205  +	   ** a pointer to it and the current process handle.
          206  +	   */
          207  +	  hProcess = GetCurrentProcess ();
          208  +	  if (hProcess)
          209  +	    {
          210  +		HINSTANCE hinstLib = LoadLibrary (TEXT ("Kernel32.dll"));
          211  +		if (NULL != hinstLib)
          212  +		  {
          213  +		      getProcessTimesAddr =
          214  +			  (GETPROCTIMES) GetProcAddress (hinstLib,
          215  +							 "GetProcessTimes");
          216  +		      if (NULL != getProcessTimesAddr)
          217  +			{
          218  +			    return 1;
          219  +			}
          220  +		      FreeLibrary (hinstLib);
          221  +		  }
          222  +	    }
          223  +      }
          224  +    return 0;
          225  +}
          226  +
          227  +/*
          228  +** Begin timing an operation
          229  +*/
          230  +static void
          231  +beginTimer (void)
          232  +{
          233  +    if (enableTimer && getProcessTimesAddr)
          234  +      {
          235  +	  FILETIME ftCreation, ftExit;
          236  +	  getProcessTimesAddr (hProcess, &ftCreation, &ftExit, &ftKernelBegin,
          237  +			       &ftUserBegin);
          238  +      }
   216    239   }
   217    240   
   218    241   /* Return the difference of two FILETIME structs in seconds */
   219         -static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
   220         -  sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
   221         -  sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
   222         -  return (double) ((i64End - i64Start) / 10000000.0);
          242  +static double
          243  +timeDiff (FILETIME * pStart, FILETIME * pEnd)
          244  +{
          245  +    sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
          246  +    sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
          247  +    return (double) ((i64End - i64Start) / 10000000.0);
   223    248   }
   224    249   
   225    250   /*
   226    251   ** Print the timing results.
   227    252   */
   228         -static void endTimer(void){
   229         -  if( enableTimer && getProcessTimesAddr){
   230         -    FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
   231         -    getProcessTimesAddr(hProcess, &ftCreation, &ftExit, &ftKernelEnd, &ftUserEnd);
   232         -    printf("CPU Time: user %f sys %f\n",
   233         -       timeDiff(&ftUserBegin, &ftUserEnd),
   234         -       timeDiff(&ftKernelBegin, &ftKernelEnd));
   235         -  }
          253  +static void
          254  +endTimer (void)
          255  +{
          256  +    if (enableTimer && getProcessTimesAddr)
          257  +      {
          258  +	  FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
          259  +	  getProcessTimesAddr (hProcess, &ftCreation, &ftExit, &ftKernelEnd,
          260  +			       &ftUserEnd);
          261  +	  printf ("CPU Time: user %f sys %f\n",
          262  +		  timeDiff (&ftUserBegin, &ftUserEnd), timeDiff (&ftKernelBegin,
          263  +								 &ftKernelEnd));
          264  +      }
   236    265   }
   237    266   
   238    267   #define BEGIN_TIMER beginTimer()
   239    268   #define END_TIMER endTimer()
   240    269   #define HAS_TIMER hasTimer()
   241    270   
   242    271   #else
   243         -#define BEGIN_TIMER 
          272  +#define BEGIN_TIMER
   244    273   #define END_TIMER
   245    274   #define HAS_TIMER 0
   246    275   #endif
   247    276   
   248    277   /* sandro: 3 September 2012 
   249    278   ** If the following flag is set, then SQL Log is enabled
   250    279   */
................................................................................
   293    322   */
   294    323   static char *Argv0;
   295    324   
   296    325   /*
   297    326   ** Prompt strings. Initialized in main. Settable with
   298    327   **   .prompt main continue
   299    328   */
   300         -static char mainPrompt[20];     /* First line prompt. default: "spatialite> "*/
   301         -static char continuePrompt[20]; /* Continuation prompt. default: "   ...> " */
          329  +static char mainPrompt[20];	/* First line prompt. default: "spatialite> " */
          330  +static char continuePrompt[20];	/* Continuation prompt. default: "   ...> " */
   302    331   
   303    332   /*
   304    333   ** Write I/O traces to the following stream.
   305    334   */
   306    335   #ifdef SQLITE_ENABLE_IOTRACE
   307    336   static FILE *iotrace = 0;
   308    337   #endif
................................................................................
   310    339   /*
   311    340   ** This routine works like printf in that its first argument is a
   312    341   ** format string and subsequent arguments are values to be substituted
   313    342   ** in place of % fields.  The result of formatting this string
   314    343   ** is written to iotrace.
   315    344   */
   316    345   #ifdef SQLITE_ENABLE_IOTRACE
   317         -static void iotracePrintf(const char *zFormat, ...){
   318         -  va_list ap;
   319         -  char *z;
   320         -  if( iotrace==0 ) return;
   321         -  va_start(ap, zFormat);
   322         -  z = sqlite3_vmprintf(zFormat, ap);
   323         -  va_end(ap);
   324         -  fprintf(iotrace, "%s", z);
   325         -  sqlite3_free(z);
          346  +static void
          347  +iotracePrintf (const char *zFormat, ...)
          348  +{
          349  +    va_list ap;
          350  +    char *z;
          351  +    if (iotrace == 0)
          352  +	return;
          353  +    va_start (ap, zFormat);
          354  +    z = sqlite3_vmprintf (zFormat, ap);
          355  +    va_end (ap);
          356  +    fprintf (iotrace, "%s", z);
          357  +    sqlite3_free (z);
   326    358   }
   327    359   #endif
   328    360   
   329    361   
   330    362   
   331    363   /* 
   332    364       Sandro Furieri 2013-04-29
   333    365        WFS progress handler callback
   334    366   */
   335         -static void wfs_page_done(int features, void *ptr)
          367  +static void
          368  +wfs_page_done (int features, void *ptr)
   336    369   {
          370  +    if (ptr != NULL)
          371  +	ptr = NULL;		/* silencing stupid compiler warnings */
   337    372       if (isatty (1))
   338         -    {
   339         -	printf("WFS Features loaded since now: %d\r", features);
   340         -	fflush(stdout);
   341         -    }
          373  +      {
          374  +	  printf ("WFS Features loaded since now: %d\r", features);
          375  +	  fflush (stdout);
          376  +      }
   342    377   }
   343    378   
   344    379   /* 
   345    380       Sandro Furieri 2008-11-20
   346    381        implementing AUTO FDO
   347    382   */
   348    383   
................................................................................
   720    755       utf8buf[maxlen - utf8len] = '\0';
   721    756       memcpy (buf, utf8buf, (maxlen - utf8len) + 1);
   722    757       free (utf8buf);
   723    758   }
   724    759   
   725    760   /* sandro 2013-11-17 */
   726    761   static void
   727         -split_drop_name(const char *str, char **prefix, char **table)
          762  +split_drop_name (const char *str, char **prefix, char **table)
   728    763   {
   729    764       int len1;
   730    765       int len2;
   731    766       const char *pt = NULL;
   732    767       const char *p = str;
   733    768       *prefix = NULL;
   734    769       *table = NULL;
   735    770       while (*p != '\0')
   736         -    {
   737         -        if (*p == '.')
   738         -        {
   739         -            pt = p;
   740         -            break;
   741         -        }
   742         -        p++;
   743         -    }
          771  +      {
          772  +	  if (*p == '.')
          773  +	    {
          774  +		pt = p;
          775  +		break;
          776  +	    }
          777  +	  p++;
          778  +      }
   744    779       if (pt == NULL)
   745         -        return;
          780  +	return;
   746    781       len1 = pt - str;
   747         -    len2 = strlen(pt + 1);
          782  +    len2 = strlen (pt + 1);
   748    783       if (len1 > 0 && len2 > 0)
   749         -    {
   750         -        *prefix = malloc(len1 + 1);
   751         -        memcpy(*prefix, str, len1);
   752         -        *(*prefix + len1) = '\0';
   753         -        *table = malloc(len2 + 1);
   754         -        strcpy(*table, pt + 1);
   755         -    }
          784  +      {
          785  +	  *prefix = malloc (len1 + 1);
          786  +	  memcpy (*prefix, str, len1);
          787  +	  *(*prefix + len1) = '\0';
          788  +	  *table = malloc (len2 + 1);
          789  +	  strcpy (*table, pt + 1);
          790  +      }
   756    791   }
          792  +
   757    793   /* end sandro 2013-11-17 */
   758    794   
   759    795   static void
   760    796   convert_input_to_utf8 (char *buf, int maxlen)
   761    797   {
   762    798   /* converting from required charset to UTF8 */
   763    799       char *utf8buf = 0;
................................................................................
   797    833   /* end Sandro Furieri 11 July 2008 */
   798    834   
   799    835   
   800    836   
   801    837   /*
   802    838   ** Determines if a string is a number of not.
   803    839   */
   804         -static int isNumber(const char *z, int *realnum){
   805         -  if( *z=='-' || *z=='+' ) z++;
   806         -  if( !IsDigit(*z) ){
   807         -    return 0;
   808         -  }
   809         -  z++;
   810         -  if( realnum ) *realnum = 0;
   811         -  while( IsDigit(*z) ){ z++; }
   812         -  if( *z=='.' ){
          840  +static int
          841  +isNumber (const char *z, int *realnum)
          842  +{
          843  +    if (*z == '-' || *z == '+')
          844  +	z++;
          845  +    if (!IsDigit (*z))
          846  +      {
          847  +	  return 0;
          848  +      }
   813    849       z++;
   814         -    if( !IsDigit(*z) ) return 0;
   815         -    while( IsDigit(*z) ){ z++; }
   816         -    if( realnum ) *realnum = 1;
   817         -  }
   818         -  if( *z=='e' || *z=='E' ){
   819         -    z++;
   820         -    if( *z=='+' || *z=='-' ) z++;
   821         -    if( !IsDigit(*z) ) return 0;
   822         -    while( IsDigit(*z) ){ z++; }
   823         -    if( realnum ) *realnum = 1;
   824         -  }
   825         -  return *z==0;
          850  +    if (realnum)
          851  +	*realnum = 0;
          852  +    while (IsDigit (*z))
          853  +      {
          854  +	  z++;
          855  +      }
          856  +    if (*z == '.')
          857  +      {
          858  +	  z++;
          859  +	  if (!IsDigit (*z))
          860  +	      return 0;
          861  +	  while (IsDigit (*z))
          862  +	    {
          863  +		z++;
          864  +	    }
          865  +	  if (realnum)
          866  +	      *realnum = 1;
          867  +      }
          868  +    if (*z == 'e' || *z == 'E')
          869  +      {
          870  +	  z++;
          871  +	  if (*z == '+' || *z == '-')
          872  +	      z++;
          873  +	  if (!IsDigit (*z))
          874  +	      return 0;
          875  +	  while (IsDigit (*z))
          876  +	    {
          877  +		z++;
          878  +	    }
          879  +	  if (realnum)
          880  +	      *realnum = 1;
          881  +      }
          882  +    return *z == 0;
   826    883   }
   827    884   
   828    885   /*
   829    886   ** A global char* and an SQL function to access its current value 
   830    887   ** from within an SQL statement. This program used to use the 
   831    888   ** sqlite_exec_printf() API to substitue a string into an SQL statement.
   832    889   ** The correct way to do this with sqlite3 is to use the bind API, but
   833    890   ** since the shell is built around the callback paradigm it would be a lot
   834    891   ** of work. Instead just use this hack, which is quite harmless.
   835    892   */
   836    893   static const char *zShellStatic = 0;
   837         -static void shellstaticFunc(
   838         -  sqlite3_context *context,
   839         -  int argc,
   840         -  sqlite3_value **argv
   841         -){
   842         -  assert( 0==argc );
   843         -  assert( zShellStatic );
   844         -  UNUSED_PARAMETER(argc);
   845         -  UNUSED_PARAMETER(argv);
   846         -  sqlite3_result_text(context, zShellStatic, -1, SQLITE_STATIC);
          894  +static void
          895  +shellstaticFunc (sqlite3_context * context, int argc, sqlite3_value ** argv)
          896  +{
          897  +    assert (0 == argc);
          898  +    assert (zShellStatic);
          899  +    UNUSED_PARAMETER (argc);
          900  +    UNUSED_PARAMETER (argv);
          901  +    sqlite3_result_text (context, zShellStatic, -1, SQLITE_STATIC);
   847    902   }
   848    903   
   849    904   
   850    905   /*
   851    906   ** This routine reads a line of text from FILE in, stores
   852    907   ** the text in memory obtained from malloc() and returns a pointer
   853    908   ** to the text.  NULL is returned at end of file, or if malloc()
   854    909   ** fails.
   855    910   **
   856    911   ** The interface is like "readline" but no command-line editing
   857    912   ** is done.
   858    913   */
   859         -static char *local_getline(char *zPrompt, FILE *in, int csvFlag){
   860         -  char *zLine;
   861         -  int nLine;
   862         -  int n;
   863         -  int inQuote = 0;
   864         -
   865         -  if( zPrompt && *zPrompt ){
   866         -    printf("%s",zPrompt);
   867         -    fflush(stdout);
   868         -  }
   869         -  nLine = 100;
   870         -  zLine = malloc( nLine );
   871         -  if( zLine==0 ) return 0;
   872         -  n = 0;
   873         -  while( 1 ){
   874         -    if( n+100>nLine ){
   875         -      nLine = nLine*2 + 100;
   876         -      zLine = realloc(zLine, nLine);
   877         -      if( zLine==0 ) return 0;
   878         -    }
   879         -    if( fgets(&zLine[n], nLine - n, in)==0 ){
   880         -      if( n==0 ){
   881         -        free(zLine);
   882         -        return 0;
   883         -      }
   884         -      zLine[n] = 0;
   885         -      break;
   886         -    }
   887         -    while( zLine[n] ){
   888         -      if( zLine[n]=='"' ) inQuote = !inQuote;
   889         -      n++;
   890         -    }
   891         -    if( n>0 && zLine[n-1]=='\n' && (!inQuote || !csvFlag) ){
   892         -      n--;
   893         -      if( n>0 && zLine[n-1]=='\r' ) n--;
   894         -      zLine[n] = 0;
   895         -      break;
   896         -    }
   897         -  }
   898         -  zLine = realloc( zLine, n+1 );
   899         -  return zLine;
          914  +static char *
          915  +local_getline (char *zPrompt, FILE * in, int csvFlag)
          916  +{
          917  +    char *zLine;
          918  +    int nLine;
          919  +    int n;
          920  +    int inQuote = 0;
          921  +
          922  +    if (zPrompt && *zPrompt)
          923  +      {
          924  +	  printf ("%s", zPrompt);
          925  +	  fflush (stdout);
          926  +      }
          927  +    nLine = 100;
          928  +    zLine = malloc (nLine);
          929  +    if (zLine == 0)
          930  +	return 0;
          931  +    n = 0;
          932  +    while (1)
          933  +      {
          934  +	  if (n + 100 > nLine)
          935  +	    {
          936  +		nLine = nLine * 2 + 100;
          937  +		zLine = realloc (zLine, nLine);
          938  +		if (zLine == 0)
          939  +		    return 0;
          940  +	    }
          941  +	  if (fgets (&zLine[n], nLine - n, in) == 0)
          942  +	    {
          943  +		if (n == 0)
          944  +		  {
          945  +		      free (zLine);
          946  +		      return 0;
          947  +		  }
          948  +		zLine[n] = 0;
          949  +		break;
          950  +	    }
          951  +	  while (zLine[n])
          952  +	    {
          953  +		if (zLine[n] == '"')
          954  +		    inQuote = !inQuote;
          955  +		n++;
          956  +	    }
          957  +	  if (n > 0 && zLine[n - 1] == '\n' && (!inQuote || !csvFlag))
          958  +	    {
          959  +		n--;
          960  +		if (n > 0 && zLine[n - 1] == '\r')
          961  +		    n--;
          962  +		zLine[n] = 0;
          963  +		break;
          964  +	    }
          965  +      }
          966  +    zLine = realloc (zLine, n + 1);
          967  +    return zLine;
   900    968   }
   901    969   
   902    970   /*
   903    971   ** Retrieve a single line of input text.
   904    972   **
   905    973   ** zPrior is a string of prior text retrieved.  If not the empty
   906    974   ** string, then issue a continuation prompt.
   907    975   */
   908         -static char *one_input_line(const char *zPrior, FILE *in){
   909         -  char *zPrompt;
   910         -  char *zResult;
   911         -  if( in!=0 ){
   912         -    return local_getline(0, in, 0);
   913         -  }
   914         -  if( zPrior && zPrior[0] ){
   915         -    zPrompt = continuePrompt;
   916         -  }else{
   917         -    zPrompt = mainPrompt;
   918         -  }
   919         -  zResult = readline(zPrompt);
          976  +static char *
          977  +one_input_line (const char *zPrior, FILE * in)
          978  +{
          979  +    char *zPrompt;
          980  +    char *zResult;
          981  +    if (in != 0)
          982  +      {
          983  +	  return local_getline (0, in, 0);
          984  +      }
          985  +    if (zPrior && zPrior[0])
          986  +      {
          987  +	  zPrompt = continuePrompt;
          988  +      }
          989  +    else
          990  +      {
          991  +	  zPrompt = mainPrompt;
          992  +      }
          993  +    zResult = readline (zPrompt);
   920    994   #if defined(HAVE_READLINE) && HAVE_READLINE==1
   921         -  if( zResult && *zResult ) add_history(zResult);
          995  +    if (zResult && *zResult)
          996  +	add_history (zResult);
   922    997   #endif
   923         -  return zResult;
          998  +    return zResult;
   924    999   }
   925   1000   
   926         -struct previous_mode_data {
   927         -  int valid;        /* Is there legit data in here? */
   928         -  int mode;
   929         -  int showHeader;
   930         -  int colWidth[100];
         1001  +struct previous_mode_data
         1002  +{
         1003  +    int valid;			/* Is there legit data in here? */
         1004  +    int mode;
         1005  +    int showHeader;
         1006  +    int colWidth[100];
   931   1007   };
   932   1008   
   933   1009   /*
   934   1010   ** An pointer to an instance of this structure is passed from
   935   1011   ** the main program to the callback.  This is used to communicate
   936   1012   ** state and mode information.
   937   1013   */
   938         -struct callback_data {
   939         -  sqlite3 *db;           /* The database */
   940         -  int echoOn;            /* True to echo input commands */
   941         -  int statsOn;           /* True to display memory stats before each finalize */
   942         -  int cnt;               /* Number of records displayed so far */
   943         -  FILE *out;             /* Write results here */
   944         -  FILE *traceOut;        /* Output for sqlite3_trace() */
   945         -  int nErr;              /* Number of errors seen */
   946         -  int mode;              /* An output mode setting */
   947         -  int writableSchema;    /* True if PRAGMA writable_schema=ON */
   948         -  int showHeader;        /* True to show column names in List or Column mode */
   949         -  char *zDestTable;      /* Name of destination table when MODE_Insert */
   950         -  char separator[20];    /* Separator character for MODE_List */
   951         -  int colWidth[100];     /* Requested width of each column when in column mode*/
   952         -  int actualWidth[100];  /* Actual width of each column */
   953         -  char nullvalue[20];    /* The text to print when a NULL comes back from
   954         -                         ** the database */
   955         -  struct previous_mode_data explainPrev;
   956         -                         /* Holds the mode information just before
   957         -                         ** .explain ON */
   958         -  char outfile[FILENAME_MAX]; /* Filename for *out */
   959         -  const char *zDbFilename;    /* name of the database file */
   960         -  const char *zVfs;           /* Name of VFS to use */
   961         -  sqlite3_stmt *pStmt;   /* Current statement if any. */
   962         -  FILE *pLog;            /* Write log output here */
         1014  +struct callback_data
         1015  +{
         1016  +    sqlite3 *db;		/* The database */
         1017  +    int echoOn;			/* True to echo input commands */
         1018  +    int statsOn;		/* True to display memory stats before each finalize */
         1019  +    int cnt;			/* Number of records displayed so far */
         1020  +    FILE *out;			/* Write results here */
         1021  +    FILE *traceOut;		/* Output for sqlite3_trace() */
         1022  +    int nErr;			/* Number of errors seen */
         1023  +    int mode;			/* An output mode setting */
         1024  +    int writableSchema;		/* True if PRAGMA writable_schema=ON */
         1025  +    int showHeader;		/* True to show column names in List or Column mode */
         1026  +    char *zDestTable;		/* Name of destination table when MODE_Insert */
         1027  +    char separator[20];		/* Separator character for MODE_List */
         1028  +    int colWidth[100];		/* Requested width of each column when in column mode */
         1029  +    int actualWidth[100];	/* Actual width of each column */
         1030  +    char nullvalue[20];		/* The text to print when a NULL comes back from
         1031  +				 ** the database */
         1032  +    struct previous_mode_data explainPrev;
         1033  +    /* Holds the mode information just before
         1034  +     ** .explain ON */
         1035  +    char outfile[FILENAME_MAX];	/* Filename for *out */
         1036  +    const char *zDbFilename;	/* name of the database file */
         1037  +    const char *zVfs;		/* Name of VFS to use */
         1038  +    sqlite3_stmt *pStmt;	/* Current statement if any. */
         1039  +    FILE *pLog;			/* Write log output here */
   963   1040   };
   964   1041   
   965   1042   /*
   966   1043   ** These are the allowed modes.
   967   1044   */
   968         -#define MODE_Line     0  /* One column per line.  Blank line between records */
   969         -#define MODE_Column   1  /* One record per line in neat columns */
   970         -#define MODE_List     2  /* One record per line with a separator */
   971         -#define MODE_Semi     3  /* Same as MODE_List but append ";" to each line */
   972         -#define MODE_Html     4  /* Generate an XHTML table */
   973         -#define MODE_Insert   5  /* Generate SQL "insert" statements */
   974         -#define MODE_Tcl      6  /* Generate ANSI-C or TCL quoted elements */
   975         -#define MODE_Csv      7  /* Quote strings, numbers are plain */
   976         -#define MODE_Explain  8  /* Like MODE_Column, but do not truncate data */
         1045  +#define MODE_Line     0		/* One column per line.  Blank line between records */
         1046  +#define MODE_Column   1		/* One record per line in neat columns */
         1047  +#define MODE_List     2		/* One record per line with a separator */
         1048  +#define MODE_Semi     3		/* Same as MODE_List but append ";" to each line */
         1049  +#define MODE_Html     4		/* Generate an XHTML table */
         1050  +#define MODE_Insert   5		/* Generate SQL "insert" statements */
         1051  +#define MODE_Tcl      6		/* Generate ANSI-C or TCL quoted elements */
         1052  +#define MODE_Csv      7		/* Quote strings, numbers are plain */
         1053  +#define MODE_Explain  8		/* Like MODE_Column, but do not truncate data */
   977   1054   
   978   1055   static const char *modeDescr[] = {
   979         -  "line",
   980         -  "column",
   981         -  "list",
   982         -  "semi",
   983         -  "html",
   984         -  "insert",
   985         -  "tcl",
   986         -  "csv",
   987         -  "explain",
         1056  +    "line",
         1057  +    "column",
         1058  +    "list",
         1059  +    "semi",
         1060  +    "html",
         1061  +    "insert",
         1062  +    "tcl",
         1063  +    "csv",
         1064  +    "explain",
   988   1065   };
   989   1066   
   990   1067   /*
   991   1068   ** Number of elements in an array
   992   1069   */
   993   1070   #define ArraySize(X)  (int)(sizeof(X)/sizeof(X[0]))
   994   1071   
   995   1072   /*
   996   1073   ** Compute a string length that is limited to what can be stored in
   997   1074   ** lower 30 bits of a 32-bit signed integer.
   998   1075   */
   999         -static int strlen30(const char *z){
  1000         -  const char *z2 = z;
  1001         -  while( *z2 ){ z2++; }
  1002         -  return 0x3fffffff & (int)(z2 - z);
         1076  +static int
         1077  +strlen30 (const char *z)
         1078  +{
         1079  +    const char *z2 = z;
         1080  +    while (*z2)
         1081  +      {
         1082  +	  z2++;
         1083  +      }
         1084  +    return 0x3fffffff & (int) (z2 - z);
  1003   1085   }
  1004   1086   
  1005   1087   /*
  1006   1088   ** A callback for the sqlite3_log() interface.
  1007   1089   */
  1008         -static void shellLog(void *pArg, int iErrCode, const char *zMsg){
  1009         -  struct callback_data *p = (struct callback_data*)pArg;
  1010         -  if( p->pLog==0 ) return;
  1011         -  fprintf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
  1012         -  fflush(p->pLog);
         1090  +static void
         1091  +shellLog (void *pArg, int iErrCode, const char *zMsg)
         1092  +{
         1093  +    struct callback_data *p = (struct callback_data *) pArg;
         1094  +    if (p->pLog == 0)
         1095  +	return;
         1096  +    fprintf (p->pLog, "(%d) %s\n", iErrCode, zMsg);
         1097  +    fflush (p->pLog);
  1013   1098   }
  1014   1099   
  1015   1100   /*
  1016   1101   ** Output the given string as a hex-encoded blob (eg. X'1234' )
  1017   1102   */
  1018         -static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
  1019         -  int i;
  1020         -  char *zBlob = (char *)pBlob;
  1021         -  fprintf(out,"X'");
  1022         -  for(i=0; i<nBlob; i++){ fprintf(out,"%02x",zBlob[i]&0xff); }
  1023         -  fprintf(out,"'");
         1103  +static void
         1104  +output_hex_blob (FILE * out, const void *pBlob, int nBlob)
         1105  +{
         1106  +    int i;
         1107  +    char *zBlob = (char *) pBlob;
         1108  +    fprintf (out, "X'");
         1109  +    for (i = 0; i < nBlob; i++)
         1110  +      {
         1111  +	  fprintf (out, "%02x", zBlob[i] & 0xff);
         1112  +      }
         1113  +    fprintf (out, "'");
  1024   1114   }
  1025   1115   
  1026   1116   /*
  1027   1117   ** Output the given string as a quoted string using SQL quoting conventions.
  1028   1118   */
  1029         -static void output_quoted_string(FILE *out, const char *z){
  1030         -  int i;
  1031         -  int nSingle = 0;
  1032         -  for(i=0; z[i]; i++){
  1033         -    if( z[i]=='\'' ) nSingle++;
  1034         -  }
  1035         -  if( nSingle==0 ){
  1036         -    fprintf(out,"'%s'",z);
  1037         -  }else{
  1038         -    fprintf(out,"'");
  1039         -    while( *z ){
  1040         -      for(i=0; z[i] && z[i]!='\''; i++){}
  1041         -      if( i==0 ){
  1042         -        fprintf(out,"''");
  1043         -        z++;
  1044         -      }else if( z[i]=='\'' ){
  1045         -        fprintf(out,"%.*s''",i,z);
  1046         -        z += i+1;
  1047         -      }else{
  1048         -        fprintf(out,"%s",z);
  1049         -        break;
  1050         -      }
  1051         -    }
  1052         -    fprintf(out,"'");
  1053         -  }
         1119  +static void
         1120  +output_quoted_string (FILE * out, const char *z)
         1121  +{
         1122  +    int i;
         1123  +    int nSingle = 0;
         1124  +    for (i = 0; z[i]; i++)
         1125  +      {
         1126  +	  if (z[i] == '\'')
         1127  +	      nSingle++;
         1128  +      }
         1129  +    if (nSingle == 0)
         1130  +      {
         1131  +	  fprintf (out, "'%s'", z);
         1132  +      }
         1133  +    else
         1134  +      {
         1135  +	  fprintf (out, "'");
         1136  +	  while (*z)
         1137  +	    {
         1138  +		for (i = 0; z[i] && z[i] != '\''; i++)
         1139  +		  {
         1140  +		  }
         1141  +		if (i == 0)
         1142  +		  {
         1143  +		      fprintf (out, "''");
         1144  +		      z++;
         1145  +		  }
         1146  +		else if (z[i] == '\'')
         1147  +		  {
         1148  +		      fprintf (out, "%.*s''", i, z);
         1149  +		      z += i + 1;
         1150  +		  }
         1151  +		else
         1152  +		  {
         1153  +		      fprintf (out, "%s", z);
         1154  +		      break;
         1155  +		  }
         1156  +	    }
         1157  +	  fprintf (out, "'");
         1158  +      }
  1054   1159   }
  1055   1160   
  1056   1161   /*
  1057   1162   ** Output the given string as a quoted according to C or TCL quoting rules.
  1058   1163   */
  1059         -static void output_c_string(FILE *out, const char *z){
  1060         -  unsigned int c;
  1061         -  fputc('"', out);
  1062         -  while( (c = *(z++))!=0 ){
  1063         -    if( c=='\\' ){
  1064         -      fputc(c, out);
  1065         -      fputc(c, out);
  1066         -    }else if( c=='\t' ){
  1067         -      fputc('\\', out);
  1068         -      fputc('t', out);
  1069         -    }else if( c=='\n' ){
  1070         -      fputc('\\', out);
  1071         -      fputc('n', out);
  1072         -    }else if( c=='\r' ){
  1073         -      fputc('\\', out);
  1074         -      fputc('r', out);
  1075         -    }else if( !isprint(c) ){
  1076         -      fprintf(out, "\\%03o", c&0xff);
  1077         -    }else{
  1078         -      fputc(c, out);
  1079         -    }
  1080         -  }
  1081         -  fputc('"', out);
         1164  +static void
         1165  +output_c_string (FILE * out, const char *z)
         1166  +{
         1167  +    unsigned int c;
         1168  +    fputc ('"', out);
         1169  +    while ((c = *(z++)) != 0)
         1170  +      {
         1171  +	  if (c == '\\')
         1172  +	    {
         1173  +		fputc (c, out);
         1174  +		fputc (c, out);
         1175  +	    }
         1176  +	  else if (c == '\t')
         1177  +	    {
         1178  +		fputc ('\\', out);
         1179  +		fputc ('t', out);
         1180  +	    }
         1181  +	  else if (c == '\n')
         1182  +	    {
         1183  +		fputc ('\\', out);
         1184  +		fputc ('n', out);
         1185  +	    }
         1186  +	  else if (c == '\r')
         1187  +	    {
         1188  +		fputc ('\\', out);
         1189  +		fputc ('r', out);
         1190  +	    }
         1191  +	  else if (!isprint (c))
         1192  +	    {
         1193  +		fprintf (out, "\\%03o", c & 0xff);
         1194  +	    }
         1195  +	  else
         1196  +	    {
         1197  +		fputc (c, out);
         1198  +	    }
         1199  +      }
         1200  +    fputc ('"', out);
  1082   1201   }
  1083   1202   
  1084   1203   /*
  1085   1204   ** Output the given string with characters that are special to
  1086   1205   ** HTML escaped.
  1087   1206   */
  1088         -static void output_html_string(FILE *out, const char *z){
  1089         -  int i;
  1090         -  while( *z ){
  1091         -    for(i=0;   z[i] 
  1092         -            && z[i]!='<' 
  1093         -            && z[i]!='&' 
  1094         -            && z[i]!='>' 
  1095         -            && z[i]!='\"' 
  1096         -            && z[i]!='\'';
  1097         -        i++){}
  1098         -    if( i>0 ){
  1099         -      fprintf(out,"%.*s",i,z);
  1100         -    }
  1101         -    if( z[i]=='<' ){
  1102         -      fprintf(out,"&lt;");
  1103         -    }else if( z[i]=='&' ){
  1104         -      fprintf(out,"&amp;");
  1105         -    }else if( z[i]=='>' ){
  1106         -      fprintf(out,"&gt;");
  1107         -    }else if( z[i]=='\"' ){
  1108         -      fprintf(out,"&quot;");
  1109         -    }else if( z[i]=='\'' ){
  1110         -      fprintf(out,"&#39;");
  1111         -    }else{
  1112         -      break;
  1113         -    }
  1114         -    z += i + 1;
  1115         -  }
         1207  +static void
         1208  +output_html_string (FILE * out, const char *z)
         1209  +{
         1210  +    int i;
         1211  +    while (*z)
         1212  +      {
         1213  +	  for (i = 0; z[i]
         1214  +	       && z[i] != '<'
         1215  +	       && z[i] != '&'
         1216  +	       && z[i] != '>' && z[i] != '\"' && z[i] != '\''; i++)
         1217  +	    {
         1218  +	    }
         1219  +	  if (i > 0)
         1220  +	    {
         1221  +		fprintf (out, "%.*s", i, z);
         1222  +	    }
         1223  +	  if (z[i] == '<')
         1224  +	    {
         1225  +		fprintf (out, "&lt;");
         1226  +	    }
         1227  +	  else if (z[i] == '&')
         1228  +	    {
         1229  +		fprintf (out, "&amp;");
         1230  +	    }
         1231  +	  else if (z[i] == '>')
         1232  +	    {
         1233  +		fprintf (out, "&gt;");
         1234  +	    }
         1235  +	  else if (z[i] == '\"')
         1236  +	    {
         1237  +		fprintf (out, "&quot;");
         1238  +	    }
         1239  +	  else if (z[i] == '\'')
         1240  +	    {
         1241  +		fprintf (out, "&#39;");
         1242  +	    }
         1243  +	  else
         1244  +	    {
         1245  +		break;
         1246  +	    }
         1247  +	  z += i + 1;
         1248  +      }
  1116   1249   }
  1117   1250   
  1118   1251   /*
  1119   1252   ** If a field contains any character identified by a 1 in the following
  1120   1253   ** array, then the string must be quoted for CSV.
  1121   1254   */
  1122   1255   static const char needCsvQuote[] = {
  1123         -  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,   
  1124         -  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,   
  1125         -  1, 0, 1, 0, 0, 0, 0, 1,   0, 0, 0, 0, 0, 0, 0, 0, 
  1126         -  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0, 
  1127         -  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0, 
  1128         -  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0, 
  1129         -  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0, 
  1130         -  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 1, 
  1131         -  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,   
  1132         -  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,   
  1133         -  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,   
  1134         -  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,   
  1135         -  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,   
  1136         -  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,   
  1137         -  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,   
  1138         -  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,   
         1256  +    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
         1257  +    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
         1258  +    1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
         1259  +    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
         1260  +    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
         1261  +    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
         1262  +    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
         1263  +    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
         1264  +    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
         1265  +    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
         1266  +    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
         1267  +    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
         1268  +    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
         1269  +    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
         1270  +    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
         1271  +    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  1139   1272   };
  1140   1273   
  1141   1274   /*
  1142   1275   ** Output a single term of CSV.  Actually, p->separator is used for
  1143   1276   ** the separator, which may or may not be a comma.  p->nullvalue is
  1144   1277   ** the null value.  Strings are quoted if necessary.
  1145   1278   */
  1146         -static void output_csv(struct callback_data *p, const char *z, int bSep){
  1147         -  FILE *out = p->out;
  1148         -  if( z==0 ){
  1149         -    fprintf(out,"%s",p->nullvalue);
  1150         -  }else{
  1151         -    int i;
  1152         -    int nSep = strlen30(p->separator);
  1153         -    for(i=0; z[i]; i++){
  1154         -      if( needCsvQuote[((unsigned char*)z)[i]] 
  1155         -         || (z[i]==p->separator[0] && 
  1156         -             (nSep==1 || memcmp(z, p->separator, nSep)==0)) ){
  1157         -        i = 0;
  1158         -        break;
  1159         -      }
  1160         -    }
  1161         -    if( i==0 ){
  1162         -      putc('"', out);
  1163         -      for(i=0; z[i]; i++){
  1164         -        if( z[i]=='"' ) putc('"', out);
  1165         -        putc(z[i], out);
  1166         -      }
  1167         -      putc('"', out);
  1168         -    }else{
  1169         -      fprintf(out, "%s", z);
  1170         -    }
  1171         -  }
  1172         -  if( bSep ){
  1173         -    fprintf(p->out, "%s", p->separator);
  1174         -  }
         1279  +static void
         1280  +output_csv (struct callback_data *p, const char *z, int bSep)
         1281  +{
         1282  +    FILE *out = p->out;
         1283  +    if (z == 0)
         1284  +      {
         1285  +	  fprintf (out, "%s", p->nullvalue);
         1286  +      }
         1287  +    else
         1288  +      {
         1289  +	  int i;
         1290  +	  int nSep = strlen30 (p->separator);
         1291  +	  for (i = 0; z[i]; i++)
         1292  +	    {
         1293  +		if (needCsvQuote[((unsigned char *) z)[i]]
         1294  +		    || (z[i] == p->separator[0] &&
         1295  +			(nSep == 1 || memcmp (z, p->separator, nSep) == 0)))
         1296  +		  {
         1297  +		      i = 0;
         1298  +		      break;
         1299  +		  }
         1300  +	    }
         1301  +	  if (i == 0)
         1302  +	    {
         1303  +		putc ('"', out);
         1304  +		for (i = 0; z[i]; i++)
         1305  +		  {
         1306  +		      if (z[i] == '"')
         1307  +			  putc ('"', out);
         1308  +		      putc (z[i], out);
         1309  +		  }
         1310  +		putc ('"', out);
         1311  +	    }
         1312  +	  else
         1313  +	    {
         1314  +		fprintf (out, "%s", z);
         1315  +	    }
         1316  +      }
         1317  +    if (bSep)
         1318  +      {
         1319  +	  fprintf (p->out, "%s", p->separator);
         1320  +      }
  1175   1321   }
  1176   1322   
  1177   1323   #ifdef SIGINT
  1178   1324   /*
  1179   1325   ** This routine runs when the user presses Ctrl-C
  1180   1326   */
  1181         -static void interrupt_handler(int NotUsed){
  1182         -  UNUSED_PARAMETER(NotUsed);
  1183         -  seenInterrupt = 1;
  1184         -  if( db ) sqlite3_interrupt(db);
         1327  +static void
         1328  +interrupt_handler (int NotUsed)
         1329  +{
         1330  +    UNUSED_PARAMETER (NotUsed);
         1331  +    seenInterrupt = 1;
         1332  +    if (db)
         1333  +	sqlite3_interrupt (db);
  1185   1334   }
  1186   1335   #endif
  1187   1336   
  1188   1337   /*
  1189   1338   ** This is the callback routine that the shell
  1190   1339   ** invokes for each row of a query result.
  1191   1340   */
  1192         -static int shell_callback(void *pArg, int nArg, char **azArg, char **azCol, int *aiType){
  1193         -  int i;
         1341  +static int
         1342  +shell_callback (void *pArg, int nArg, char **azArg, char **azCol, int *aiType)
         1343  +{
         1344  +    int i;
  1194   1345   /* Sandro Furieri 11 July 2008 - supporting full UNICODE */
  1195   1346       char *buf = NULL;
  1196   1347       int len;
  1197   1348   /* end Sandro Furieri 11 July 2008 */
  1198         -  struct callback_data *p = (struct callback_data*)pArg;
         1349  +    struct callback_data *p = (struct callback_data *) pArg;
  1199   1350   
  1200         -  switch( p->mode ){
  1201         -    case MODE_Line: {
  1202         -      int w = 5;
  1203         -      if( azArg==0 ) break;
  1204         -      for(i=0; i<nArg; i++){
  1205         -        int len = strlen30(azCol[i] ? azCol[i] : "");
  1206         -        if( len>w ) w = len;
  1207         -      }
  1208         -      if( p->cnt++>0 ) fprintf(p->out,"\n");
  1209         -      for(i=0; i<nArg; i++){
         1351  +    switch (p->mode)
         1352  +      {
         1353  +      case MODE_Line:
         1354  +	  {
         1355  +	      int w = 5;
         1356  +	      if (azArg == 0)
         1357  +		  break;
         1358  +	      for (i = 0; i < nArg; i++)
         1359  +		{
         1360  +		    int len = strlen30 (azCol[i] ? azCol[i] : "");
         1361  +		    if (len > w)
         1362  +			w = len;
         1363  +		}
         1364  +	      if (p->cnt++ > 0)
         1365  +		  fprintf (p->out, "\n");
         1366  +	      for (i = 0; i < nArg; i++)
         1367  +		{
  1210   1368   /* Sandro Furieri 11 July 2008
  1211   1369           fprintf(p->out,"%*s = %s\n", w, azCol[i],
  1212   1370                   azArg[i] ? azArg[i] : p->nullvalue);
  1213   1371    */
  1214         -	    if (azArg[i] == 0)
  1215         -		fprintf (p->out, "%*s = %s\n", w, azCol[i],
  1216         -			 p->nullvalue);
  1217         -	    else
  1218         -	      {
  1219         -		  len = strlen (azArg[i]) + 1;
  1220         -		  if (buf)
  1221         -		      free (buf);
  1222         -		  buf = malloc (len * 4);
  1223         -		  strcpy (buf, azArg[i]);
  1224         -		  convert_from_utf8 (buf, len * 4);
  1225         -		  fprintf (p->out, "%*s = %s\n", w, azCol[i],
  1226         -			   azArg[i] ? buf : p->nullvalue);
  1227         -                  free(buf);
  1228         -                  buf = NULL;
  1229         -	      }
         1372  +		    if (azArg[i] == 0)
         1373  +			fprintf (p->out, "%*s = %s\n", w, azCol[i],
         1374  +				 p->nullvalue);
         1375  +		    else
         1376  +		      {
         1377  +			  len = strlen (azArg[i]) + 1;
         1378  +			  if (buf)
         1379  +			      free (buf);
         1380  +			  buf = malloc (len * 4);
         1381  +			  strcpy (buf, azArg[i]);
         1382  +			  convert_from_utf8 (buf, len * 4);
         1383  +			  fprintf (p->out, "%*s = %s\n", w, azCol[i],
         1384  +				   azArg[i] ? buf : p->nullvalue);
         1385  +			  free (buf);
         1386  +			  buf = NULL;
         1387  +		      }
  1230   1388   /* end Sandro Furieri 11 July 2008 */
  1231         -      }
  1232         -      break;
  1233         -    }
  1234         -    case MODE_Explain:
  1235         -    case MODE_Column: {
  1236         -      if( p->cnt++==0 ){
  1237         -        for(i=0; i<nArg; i++){
  1238         -          int w, n;
  1239         -          if( i<ArraySize(p->colWidth) ){
  1240         -            w = p->colWidth[i];
  1241         -          }else{
  1242         -            w = 0;
  1243         -          }
  1244         -          if( w<=0 ){
  1245         -            w = strlen30(azCol[i] ? azCol[i] : "");
  1246         -            if( w<10 ) w = 10;
  1247         -            n = strlen30(azArg && azArg[i] ? azArg[i] : p->nullvalue);
  1248         -            if( w<n ) w = n;
  1249         -          }
  1250         -          if( i<ArraySize(p->actualWidth) ){
  1251         -            p->actualWidth[i] = w;
  1252         -          }
  1253         -          if( p->showHeader ){
  1254         -            fprintf(p->out,"%-*.*s%s",w,w,azCol[i], i==nArg-1 ? "\n": "  ");
  1255         -          }
  1256         -        }
  1257         -        if( p->showHeader ){
  1258         -          for(i=0; i<nArg; i++){
  1259         -            int w;
  1260         -            if( i<ArraySize(p->actualWidth) ){
  1261         -               w = p->actualWidth[i];
  1262         -            }else{
  1263         -               w = 10;
  1264         -            }
  1265         -            fprintf(p->out,"%-*.*s%s",w,w,"-----------------------------------"
  1266         -                   "----------------------------------------------------------",
  1267         -                    i==nArg-1 ? "\n": "  ");
  1268         -          }
  1269         -        }
  1270         -      }
  1271         -      if( azArg==0 ) break;
  1272         -      for(i=0; i<nArg; i++){
  1273         -        int w;
  1274         -        if( i<ArraySize(p->actualWidth) ){
  1275         -           w = p->actualWidth[i];
  1276         -        }else{
  1277         -           w = 10;
  1278         -        }
  1279         -        if( p->mode==MODE_Explain && azArg[i] && 
  1280         -           strlen30(azArg[i])>w ){
  1281         -          w = strlen30(azArg[i]);
  1282         -        }
         1389  +		}
         1390  +	      break;
         1391  +	  }
         1392  +      case MODE_Explain:
         1393  +      case MODE_Column:
         1394  +	  {
         1395  +	      if (p->cnt++ == 0)
         1396  +		{
         1397  +		    for (i = 0; i < nArg; i++)
         1398  +		      {
         1399  +			  int w, n;
         1400  +			  if (i < ArraySize (p->colWidth))
         1401  +			    {
         1402  +				w = p->colWidth[i];
         1403  +			    }
         1404  +			  else
         1405  +			    {
         1406  +				w = 0;
         1407  +			    }
         1408  +			  if (w <= 0)
         1409  +			    {
         1410  +				w = strlen30 (azCol[i] ? azCol[i] : "");
         1411  +				if (w < 10)
         1412  +				    w = 10;
         1413  +				n = strlen30 (azArg
         1414  +					      && azArg[i] ? azArg[i] :
         1415  +					      p->nullvalue);
         1416  +				if (w < n)
         1417  +				    w = n;
         1418  +			    }
         1419  +			  if (i < ArraySize (p->actualWidth))
         1420  +			    {
         1421  +				p->actualWidth[i] = w;
         1422  +			    }
         1423  +			  if (p->showHeader)
         1424  +			    {
         1425  +				fprintf (p->out, "%-*.*s%s", w, w, azCol[i],
         1426  +					 i == nArg - 1 ? "\n" : "  ");
         1427  +			    }
         1428  +		      }
         1429  +		    if (p->showHeader)
         1430  +		      {
         1431  +			  for (i = 0; i < nArg; i++)
         1432  +			    {
         1433  +				int w;
         1434  +				if (i < ArraySize (p->actualWidth))
         1435  +				  {
         1436  +				      w = p->actualWidth[i];
         1437  +				  }
         1438  +				else
         1439  +				  {
         1440  +				      w = 10;
         1441  +				  }
         1442  +				fprintf (p->out, "%-*.*s%s", w, w,
         1443  +					 "-----------------------------------"
         1444  +					 "----------------------------------------------------------",
         1445  +					 i == nArg - 1 ? "\n" : "  ");
         1446  +			    }
         1447  +		      }
         1448  +		}
         1449  +	      if (azArg == 0)
         1450  +		  break;
         1451  +	      for (i = 0; i < nArg; i++)
         1452  +		{
         1453  +		    int w;
         1454  +		    if (i < ArraySize (p->actualWidth))
         1455  +		      {
         1456  +			  w = p->actualWidth[i];
         1457  +		      }
         1458  +		    else
         1459  +		      {
         1460  +			  w = 10;
         1461  +		      }
         1462  +		    if (p->mode == MODE_Explain && azArg[i] &&
         1463  +			strlen30 (azArg[i]) > w)
         1464  +		      {
         1465  +			  w = strlen30 (azArg[i]);
         1466  +		      }
  1283   1467   /* Sandro Furieri 11 July 2008
  1284   1468           fprintf(p->out,"%-*.*s%s",w,w,
  1285   1469               azArg[i] ? azArg[i] : p->nullvalue, i==nArg-1 ? "\n": "  ");
  1286   1470   */
  1287         -	    if (azArg[i] == 0)
  1288         -		fprintf (p->out, "%-*.*s%s", w, w, p->nullvalue,
  1289         -			 i == nArg - 1 ? "\n" : "  ");
  1290         -	    else
  1291         -	      {
  1292         -		  len = strlen (azArg[i]) + 1;
  1293         -		  if (buf)
  1294         -		      free (buf);
  1295         -		  buf = malloc (len * 4);
  1296         -		  strcpy (buf, azArg[i]);
  1297         -		  convert_from_utf8 (buf, len * 4);
  1298         -		  fprintf (p->out, "%-*.*s%s", w, w,
  1299         -			   azArg[i] ? buf : p->nullvalue,
  1300         -			   i == nArg - 1 ? "\n" : "  ");
  1301         -                  free(buf);
  1302         -                  buf = NULL;
  1303         -	      }
         1471  +		    if (azArg[i] == 0)
         1472  +			fprintf (p->out, "%-*.*s%s", w, w, p->nullvalue,
         1473  +				 i == nArg - 1 ? "\n" : "  ");
         1474  +		    else
         1475  +		      {
         1476  +			  len = strlen (azArg[i]) + 1;
         1477  +			  if (buf)
         1478  +			      free (buf);
         1479  +			  buf = malloc (len * 4);
         1480  +			  strcpy (buf, azArg[i]);
         1481  +			  convert_from_utf8 (buf, len * 4);
         1482  +			  fprintf (p->out, "%-*.*s%s", w, w,
         1483  +				   azArg[i] ? buf : p->nullvalue,
         1484  +				   i == nArg - 1 ? "\n" : "  ");
         1485  +			  free (buf);
         1486  +			  buf = NULL;
         1487  +		      }
  1304   1488   /* end Sandro Furieri 11 July 2008 */
  1305         -        fprintf(p->out,"%-*.*s%s",w,w,
  1306         -            azArg[i] ? azArg[i] : p->nullvalue, i==nArg-1 ? "\n": "  ");
  1307         -      }
  1308         -      break;
  1309         -    }
  1310         -    case MODE_Semi:
  1311         -    case MODE_List: {
  1312         -      if( p->cnt++==0 && p->showHeader ){
  1313         -        for(i=0; i<nArg; i++){
  1314         -          fprintf(p->out,"%s%s",azCol[i], i==nArg-1 ? "\n" : p->separator);
  1315         -        }
  1316         -      }
  1317         -      if( azArg==0 ) break;
  1318         -      for(i=0; i<nArg; i++){
         1489  +		    fprintf (p->out, "%-*.*s%s", w, w,
         1490  +			     azArg[i] ? azArg[i] : p->nullvalue,
         1491  +			     i == nArg - 1 ? "\n" : "  ");
         1492  +		}
         1493  +	      break;
         1494  +	  }
         1495  +      case MODE_Semi:
         1496  +      case MODE_List:
         1497  +	  {
         1498  +	      if (p->cnt++ == 0 && p->showHeader)
         1499  +		{
         1500  +		    for (i = 0; i < nArg; i++)
         1501  +		      {
         1502  +			  fprintf (p->out, "%s%s", azCol[i],
         1503  +				   i == nArg - 1 ? "\n" : p->separator);
         1504  +		      }
         1505  +		}
         1506  +	      if (azArg == 0)
         1507  +		  break;
         1508  +	      for (i = 0; i < nArg; i++)
         1509  +		{
  1319   1510   /* Sandro Furieri 11 July 2008
  1320   1511           char *z = azArg[i];
  1321   1512           if( z==0 ) z = p->nullvalue;
  1322   1513   */
  1323         -	    char *z;
  1324         -	    if (azArg[i] == 0)
  1325         -		z = p->nullvalue;
  1326         -	    else
  1327         -	      {
  1328         -		  len = strlen (azArg[i]) + 1;
  1329         -		  if (buf)
  1330         -		      free (buf);
  1331         -		  buf = malloc (len * 4);
  1332         -		  z = buf;
  1333         -		  strcpy (buf, azArg[i]);
  1334         -		  convert_from_utf8 (buf, len * 4);
  1335         -	      }
         1514  +		    char *z;
         1515  +		    if (azArg[i] == 0)
         1516  +			z = p->nullvalue;
         1517  +		    else
         1518  +		      {
         1519  +			  len = strlen (azArg[i]) + 1;
         1520  +			  if (buf)
         1521  +			      free (buf);
         1522  +			  buf = malloc (len * 4);
         1523  +			  z = buf;
         1524  +			  strcpy (buf, azArg[i]);
         1525  +			  convert_from_utf8 (buf, len * 4);
         1526  +		      }
  1336   1527   /* end Sandro Furieri 11 July 2008 */
  1337         -        fprintf(p->out, "%s", z);
  1338         -        if (buf)
  1339         -            free(buf);
  1340         -        buf = NULL;
  1341         -        if( i<nArg-1 ){
  1342         -          fprintf(p->out, "%s", p->separator);
  1343         -        }else if( p->mode==MODE_Semi ){
  1344         -          fprintf(p->out, ";\n");
  1345         -        }else{
  1346         -          fprintf(p->out, "\n");
  1347         -        }
  1348         -      }
  1349         -      break;
  1350         -    }
  1351         -    case MODE_Html: {
  1352         -      if( p->cnt++==0 && p->showHeader ){
  1353         -        fprintf(p->out,"<TR>");
  1354         -        for(i=0; i<nArg; i++){
  1355         -          fprintf(p->out,"<TH>");
  1356         -          output_html_string(p->out, azCol[i]);
  1357         -          fprintf(p->out,"</TH>\n");
  1358         -        }
  1359         -        fprintf(p->out,"</TR>\n");
  1360         -      }
  1361         -      if( azArg==0 ) break;
  1362         -      fprintf(p->out,"<TR>");
  1363         -      for(i=0; i<nArg; i++){
  1364         -        fprintf(p->out,"<TD>");
         1528  +		    fprintf (p->out, "%s", z);
         1529  +		    if (buf)
         1530  +			free (buf);
         1531  +		    buf = NULL;
         1532  +		    if (i < nArg - 1)
         1533  +		      {
         1534  +			  fprintf (p->out, "%s", p->separator);
         1535  +		      }
         1536  +		    else if (p->mode == MODE_Semi)
         1537  +		      {
         1538  +			  fprintf (p->out, ";\n");
         1539  +		      }
         1540  +		    else
         1541  +		      {
         1542  +			  fprintf (p->out, "\n");
         1543  +		      }
         1544  +		}
         1545  +	      break;
         1546  +	  }
         1547  +      case MODE_Html:
         1548  +	  {
         1549  +	      if (p->cnt++ == 0 && p->showHeader)
         1550  +		{
         1551  +		    fprintf (p->out, "<TR>");
         1552  +		    for (i = 0; i < nArg; i++)
         1553  +		      {
         1554  +			  fprintf (p->out, "<TH>");
         1555  +			  output_html_string (p->out, azCol[i]);
         1556  +			  fprintf (p->out, "</TH>\n");
         1557  +		      }
         1558  +		    fprintf (p->out, "</TR>\n");
         1559  +		}
         1560  +	      if (azArg == 0)
         1561  +		  break;
         1562  +	      fprintf (p->out, "<TR>");
         1563  +	      for (i = 0; i < nArg; i++)
         1564  +		{
         1565  +		    fprintf (p->out, "<TD>");
  1365   1566   /* Sandro Furieri 11 July 2008
  1366   1567           output_html_string(p->out, azArg[i] ? azArg[i] : p->nullvalue);
  1367   1568   */
  1368         -	    if (azArg[i] == 0)
  1369         -		output_html_string (p->out, p->nullvalue);
  1370         -	    else
  1371         -	      {
  1372         -		  len = strlen (azArg[i]) + 1;
  1373         -		  if (buf)
  1374         -		      free (buf);
  1375         -		  buf = malloc (len * 4);
  1376         -		  strcpy (buf, azArg[i]);
  1377         -		  convert_from_utf8 (buf, len * 4);
  1378         -		  output_html_string (p->out,
  1379         -				      azArg[i] ? buf : p->nullvalue);
  1380         -                  free(buf);
  1381         -                  buf = NULL;
  1382         -	      }
         1569  +		    if (azArg[i] == 0)
         1570  +			output_html_string (p->out, p->nullvalue);
         1571  +		    else
         1572  +		      {
         1573  +			  len = strlen (azArg[i]) + 1;
         1574  +			  if (buf)
         1575  +			      free (buf);
         1576  +			  buf = malloc (len * 4);
         1577  +			  strcpy (buf, azArg[i]);
         1578  +			  convert_from_utf8 (buf, len * 4);
         1579  +			  output_html_string (p->out,
         1580  +					      azArg[i] ? buf : p->nullvalue);
         1581  +			  free (buf);
         1582  +			  buf = NULL;
         1583  +		      }
  1383   1584   /* end Sandro Furieri 11 July 2008 */
  1384         -        fprintf(p->out,"</TD>\n");
  1385         -      }
  1386         -      fprintf(p->out,"</TR>\n");
  1387         -      break;
  1388         -    }
  1389         -    case MODE_Tcl: {
  1390         -      if( p->cnt++==0 && p->showHeader ){
  1391         -        for(i=0; i<nArg; i++){
  1392         -          output_c_string(p->out,azCol[i] ? azCol[i] : "");
  1393         -          fprintf(p->out, "%s", p->separator);
  1394         -        }
  1395         -        fprintf(p->out,"\n");
  1396         -      }
  1397         -      if( azArg==0 ) break;
  1398         -      for(i=0; i<nArg; i++){
         1585  +		    fprintf (p->out, "</TD>\n");
         1586  +		}
         1587  +	      fprintf (p->out, "</TR>\n");
         1588  +	      break;
         1589  +	  }
         1590  +      case MODE_Tcl:
         1591  +	  {
         1592  +	      if (p->cnt++ == 0 && p->showHeader)
         1593  +		{
         1594  +		    for (i = 0; i < nArg; i++)
         1595  +		      {
         1596  +			  output_c_string (p->out, azCol[i] ? azCol[i] : "");
         1597  +			  fprintf (p->out, "%s", p->separator);
         1598  +		      }
         1599  +		    fprintf (p->out, "\n");
         1600  +		}
         1601  +	      if (azArg == 0)
         1602  +		  break;
         1603  +	      for (i = 0; i < nArg; i++)
         1604  +		{
  1399   1605   /* Sandro Furieri 11 July 2008
  1400   1606           output_c_string(p->out, azArg[i] ? azArg[i] : p->nullvalue);
  1401   1607   */
  1402         -	    if (azArg[i] == 0)
  1403         -		output_c_string (p->out, p->nullvalue);
  1404         -	    else
  1405         -	      {
  1406         -		  len = strlen (azArg[i]) + 1;
  1407         -		  if (buf)
  1408         -		      free (buf);
  1409         -		  buf = malloc (len * 4);
  1410         -		  strcpy (buf, azArg[i]);
  1411         -		  convert_from_utf8 (buf, len * 4);
  1412         -		  output_c_string (p->out,
  1413         -				   azArg[i] ? buf : p->nullvalue);
  1414         -                  free(buf);
  1415         -                  buf = NULL;
  1416         -	      }
         1608  +		    if (azArg[i] == 0)
         1609  +			output_c_string (p->out, p->nullvalue);
         1610  +		    else
         1611  +		      {
         1612  +			  len = strlen (azArg[i]) + 1;
         1613  +			  if (buf)
         1614  +			      free (buf);
         1615  +			  buf = malloc (len * 4);
         1616  +			  strcpy (buf, azArg[i]);
         1617  +			  convert_from_utf8 (buf, len * 4);
         1618  +			  output_c_string (p->out,
         1619  +					   azArg[i] ? buf : p->nullvalue);
         1620  +			  free (buf);
         1621  +			  buf = NULL;
         1622  +		      }
  1417   1623   /* end Sandro Furieri 11 July 2008 */
  1418         -        fprintf(p->out, "%s", p->separator);
  1419         -      }
  1420         -      fprintf(p->out,"\n");
  1421         -      break;
  1422         -    }
  1423         -    case MODE_Csv: {
  1424         -      if( p->cnt++==0 && p->showHeader ){
  1425         -        for(i=0; i<nArg; i++){
  1426         -          output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
  1427         -        }
  1428         -        fprintf(p->out,"\n");
  1429         -      }
  1430         -      if( azArg==0 ) break;
  1431         -      for(i=0; i<nArg; i++){
         1624  +		    fprintf (p->out, "%s", p->separator);
         1625  +		}
         1626  +	      fprintf (p->out, "\n");
         1627  +	      break;
         1628  +	  }
         1629  +      case MODE_Csv:
         1630  +	  {
         1631  +	      if (p->cnt++ == 0 && p->showHeader)
         1632  +		{
         1633  +		    for (i = 0; i < nArg; i++)
         1634  +		      {
         1635  +			  output_csv (p, azCol[i] ? azCol[i] : "",
         1636  +				      i < nArg - 1);
         1637  +		      }
         1638  +		    fprintf (p->out, "\n");
         1639  +		}
         1640  +	      if (azArg == 0)
         1641  +		  break;
         1642  +	      for (i = 0; i < nArg; i++)
         1643  +		{
  1432   1644   /* Sandro Furieri 11 July 2008
  1433   1645           output_csv(p, azArg[i], i<nArg-1);
  1434   1646   */
  1435   1647   		    if (azArg[i] == 0)
  1436   1648   			output_csv (p, azArg[i], i < nArg - 1);
  1437   1649   		    else
  1438   1650   		      {
................................................................................
  1439   1651   			  len = strlen (azArg[i]) + 1;
  1440   1652   			  if (buf)
  1441   1653   			      free (buf);
  1442   1654   			  buf = malloc (len * 4);
  1443   1655   			  strcpy (buf, azArg[i]);
  1444   1656   			  convert_from_utf8 (buf, len * 4);
  1445   1657   			  output_csv (p, buf, i < nArg - 1);
  1446         -                          free(buf);
  1447         -                          buf = NULL;
         1658  +			  free (buf);
         1659  +			  buf = NULL;
  1448   1660   		      }
  1449   1661   /* end Sandro Furieri 11 July 2008 */
  1450         -      }
  1451         -      fprintf(p->out,"\n");
  1452         -      break;
  1453         -    }
  1454         -    case MODE_Insert: {
  1455         -      p->cnt++;
  1456         -      if( azArg==0 ) break;
  1457         -      fprintf(p->out,"INSERT INTO %s VALUES(",p->zDestTable);
  1458         -      for(i=0; i<nArg; i++){
  1459         -        char *zSep = i>0 ? ",": "";
  1460         -        if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
  1461         -          fprintf(p->out,"%sNULL",zSep);
  1462         -        }else if( aiType && aiType[i]==SQLITE_TEXT ){
  1463         -          if( zSep[0] ) fprintf(p->out,"%s",zSep);
         1662  +		}
         1663  +	      fprintf (p->out, "\n");
         1664  +	      break;
         1665  +	  }
         1666  +      case MODE_Insert:
         1667  +	  {
         1668  +	      p->cnt++;
         1669  +	      if (azArg == 0)
         1670  +		  break;
         1671  +	      fprintf (p->out, "INSERT INTO %s VALUES(", p->zDestTable);
         1672  +	      for (i = 0; i < nArg; i++)
         1673  +		{
         1674  +		    char *zSep = i > 0 ? "," : "";
         1675  +		    if ((azArg[i] == 0) || (aiType && aiType[i] == SQLITE_NULL))
         1676  +		      {
         1677  +			  fprintf (p->out, "%sNULL", zSep);
         1678  +		      }
         1679  +		    else if (aiType && aiType[i] == SQLITE_TEXT)
         1680  +		      {
         1681  +			  if (zSep[0])
         1682  +			      fprintf (p->out, "%s", zSep);
  1464   1683   /* Sandro Furieri 11 July 2008
  1465   1684             output_quoted_string(p->out, azArg[i]);
  1466   1685   */
  1467         -		  if (azArg[i] == 0)
  1468         -		      output_quoted_string (p->out, azArg[i]);
  1469         -		  else
  1470         -		    {
  1471         -			len = strlen (azArg[i]) + 1;
  1472         -			if (buf)
  1473         -			    free (buf);
  1474         -			buf = malloc (len * 4);
  1475         -			strcpy (buf, azArg[i]);
  1476         -			convert_from_utf8 (buf, len * 4);
  1477         -			output_quoted_string (p->out, buf);
  1478         -                        free(buf);
  1479         -                        buf = NULL;
  1480         -		    }
         1686  +			  if (azArg[i] == 0)
         1687  +			      output_quoted_string (p->out, azArg[i]);
         1688  +			  else
         1689  +			    {
         1690  +				len = strlen (azArg[i]) + 1;
         1691  +				if (buf)
         1692  +				    free (buf);
         1693  +				buf = malloc (len * 4);
         1694  +				strcpy (buf, azArg[i]);
         1695  +				convert_from_utf8 (buf, len * 4);
         1696  +				output_quoted_string (p->out, buf);
         1697  +				free (buf);
         1698  +				buf = NULL;
         1699  +			    }
  1481   1700   /* end Sandro Furieri 11 July 2008 */
  1482         -        }else if( aiType && (aiType[i]==SQLITE_INTEGER || aiType[i]==SQLITE_FLOAT) ){
  1483         -          fprintf(p->out,"%s%s",zSep, azArg[i]);
  1484         -        }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
  1485         -          const void *pBlob = sqlite3_column_blob(p->pStmt, i);
  1486         -          int nBlob = sqlite3_column_bytes(p->pStmt, i);
  1487         -          if( zSep[0] ) fprintf(p->out,"%s",zSep);
  1488         -          output_hex_blob(p->out, pBlob, nBlob);
  1489         -        }else if( isNumber(azArg[i], 0) ){
  1490         -          fprintf(p->out,"%s%s",zSep, azArg[i]);
  1491         -        }else{
  1492         -          if( zSep[0] ) fprintf(p->out,"%s",zSep);
  1493         -          output_quoted_string(p->out, azArg[i]);
  1494         -        }
  1495         -      }
  1496         -      fprintf(p->out,");\n");
  1497         -      break;
  1498         -    }
  1499         -  }
  1500         -  return 0;
         1701  +		      }
         1702  +		    else if (aiType
         1703  +			     && (aiType[i] == SQLITE_INTEGER
         1704  +				 || aiType[i] == SQLITE_FLOAT))
         1705  +		      {
         1706  +			  fprintf (p->out, "%s%s", zSep, azArg[i]);
         1707  +		      }
         1708  +		    else if (aiType && aiType[i] == SQLITE_BLOB && p->pStmt)
         1709  +		      {
         1710  +			  const void *pBlob = sqlite3_column_blob (p->pStmt, i);
         1711  +			  int nBlob = sqlite3_column_bytes (p->pStmt, i);
         1712  +			  if (zSep[0])
         1713  +			      fprintf (p->out, "%s", zSep);
         1714  +			  output_hex_blob (p->out, pBlob, nBlob);
         1715  +		      }
         1716  +		    else if (isNumber (azArg[i], 0))
         1717  +		      {
         1718  +			  fprintf (p->out, "%s%s", zSep, azArg[i]);
         1719  +		      }
         1720  +		    else
         1721  +		      {
         1722  +			  if (zSep[0])
         1723  +			      fprintf (p->out, "%s", zSep);
         1724  +			  output_quoted_string (p->out, azArg[i]);
         1725  +		      }
         1726  +		}
         1727  +	      fprintf (p->out, ");\n");
         1728  +	      break;
         1729  +	  }
         1730  +      }
         1731  +    return 0;
  1501   1732   }
  1502   1733   
  1503   1734   /*
  1504   1735   ** This is the callback routine that the SQLite library
  1505   1736   ** invokes for each row of a query result.
  1506   1737   */
  1507         -static int callback(void *pArg, int nArg, char **azArg, char **azCol){
  1508         -  /* since we don't have type info, call the shell_callback with a NULL value */
  1509         -  return shell_callback(pArg, nArg, azArg, azCol, NULL);
         1738  +static int
         1739  +callback (void *pArg, int nArg, char **azArg, char **azCol)
         1740  +{
         1741  +    /* since we don't have type info, call the shell_callback with a NULL value */
         1742  +    return shell_callback (pArg, nArg, azArg, azCol, NULL);
  1510   1743   }
  1511   1744   
  1512   1745   /*
  1513   1746   ** Set the destination table field of the callback_data structure to
  1514   1747   ** the name of the table given.  Escape any quote characters in the
  1515   1748   ** table name.
  1516   1749   */
  1517         -static void set_table_name(struct callback_data *p, const char *zName){
  1518         -  int i, n;
  1519         -  int needQuote;
  1520         -  char *z;
  1521         -
  1522         -  if( p->zDestTable ){
  1523         -    free(p->zDestTable);
  1524         -    p->zDestTable = 0;
  1525         -  }
  1526         -  if( zName==0 ) return;
  1527         -  needQuote = !isalpha((unsigned char)*zName) && *zName!='_';
  1528         -  for(i=n=0; zName[i]; i++, n++){
  1529         -    if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ){
  1530         -      needQuote = 1;
  1531         -      if( zName[i]=='\'' ) n++;
  1532         -    }
  1533         -  }
  1534         -  if( needQuote ) n += 2;
  1535         -  z = p->zDestTable = malloc( n+1 );
  1536         -  if( z==0 ){
  1537         -    fprintf(stderr,"Error: out of memory\n");
  1538         -    exit(1);
  1539         -  }
  1540         -  n = 0;
  1541         -  if( needQuote ) z[n++] = '\'';
  1542         -  for(i=0; zName[i]; i++){
  1543         -    z[n++] = zName[i];
  1544         -    if( zName[i]=='\'' ) z[n++] = '\'';
  1545         -  }
  1546         -  if( needQuote ) z[n++] = '\'';
  1547         -  z[n] = 0;
         1750  +static void
         1751  +set_table_name (struct callback_data *p, const char *zName)
         1752  +{
         1753  +    int i, n;
         1754  +    int needQuote;
         1755  +    char *z;
         1756  +
         1757  +    if (p->zDestTable)
         1758  +      {
         1759  +	  free (p->zDestTable);
         1760  +	  p->zDestTable = 0;
         1761  +      }
         1762  +    if (zName == 0)
         1763  +	return;
         1764  +    needQuote = !isalpha ((unsigned char) *zName) && *zName != '_';
         1765  +    for (i = n = 0; zName[i]; i++, n++)
         1766  +      {
         1767  +	  if (!isalnum ((unsigned char) zName[i]) && zName[i] != '_')
         1768  +	    {
         1769  +		needQuote = 1;
         1770  +		if (zName[i] == '\'')
         1771  +		    n++;
         1772  +	    }
         1773  +      }
         1774  +    if (needQuote)
         1775  +	n += 2;
         1776  +    z = p->zDestTable = malloc (n + 1);
         1777  +    if (z == 0)
         1778  +      {
         1779  +	  fprintf (stderr, "Error: out of memory\n");
         1780  +	  exit (1);
         1781  +      }
         1782  +    n = 0;
         1783  +    if (needQuote)
         1784  +	z[n++] = '\'';
         1785  +    for (i = 0; zName[i]; i++)
         1786  +      {
         1787  +	  z[n++] = zName[i];
         1788  +	  if (zName[i] == '\'')
         1789  +	      z[n++] = '\'';
         1790  +      }
         1791  +    if (needQuote)
         1792  +	z[n++] = '\'';
         1793  +    z[n] = 0;
  1548   1794   }
  1549   1795   
  1550   1796   /* zIn is either a pointer to a NULL-terminated string in memory obtained
  1551   1797   ** from malloc(), or a NULL pointer. The string pointed to by zAppend is
  1552   1798   ** added to zIn, and the result returned in memory obtained from malloc().
  1553   1799   ** zIn, if it was not NULL, is freed.
  1554   1800   **
  1555   1801   ** If the third argument, quote, is not '\0', then it is used as a 
  1556   1802   ** quote character for zAppend.
  1557   1803   */
  1558         -static char *appendText(char *zIn, char const *zAppend, char quote){
  1559         -  int len;
  1560         -  int i;
  1561         -  int nAppend = strlen30(zAppend);
  1562         -  int nIn = (zIn?strlen30(zIn):0);
  1563         -
  1564         -  len = nAppend+nIn+1;
  1565         -  if( quote ){
  1566         -    len += 2;
  1567         -    for(i=0; i<nAppend; i++){
  1568         -      if( zAppend[i]==quote ) len++;
  1569         -    }
  1570         -  }
  1571         -
  1572         -  zIn = (char *)realloc(zIn, len);
  1573         -  if( !zIn ){
  1574         -    return 0;
  1575         -  }
  1576         -
  1577         -  if( quote ){
  1578         -    char *zCsr = &zIn[nIn];
  1579         -    *zCsr++ = quote;
  1580         -    for(i=0; i<nAppend; i++){
  1581         -      *zCsr++ = zAppend[i];
  1582         -      if( zAppend[i]==quote ) *zCsr++ = quote;
  1583         -    }
  1584         -    *zCsr++ = quote;
  1585         -    *zCsr++ = '\0';
  1586         -    assert( (zCsr-zIn)==len );
  1587         -  }else{
  1588         -    memcpy(&zIn[nIn], zAppend, nAppend);
  1589         -    zIn[len-1] = '\0';
  1590         -  }
  1591         -
  1592         -  return zIn;
         1804  +static char *
         1805  +appendText (char *zIn, char const *zAppend, char quote)
         1806  +{
         1807  +    int len;
         1808  +    int i;
         1809  +    int nAppend = strlen30 (zAppend);
         1810  +    int nIn = (zIn ? strlen30 (zIn) : 0);
         1811  +
         1812  +    len = nAppend + nIn + 1;
         1813  +    if (quote)
         1814  +      {
         1815  +	  len += 2;
         1816  +	  for (i = 0; i < nAppend; i++)
         1817  +	    {
         1818  +		if (zAppend[i] == quote)
         1819  +		    len++;
         1820  +	    }
         1821  +      }
         1822  +
         1823  +    zIn = (char *) realloc (zIn, len);
         1824  +    if (!zIn)
         1825  +      {
         1826  +	  return 0;
         1827  +      }
         1828  +
         1829  +    if (quote)
         1830  +      {
         1831  +	  char *zCsr = &zIn[nIn];
         1832  +	  *zCsr++ = quote;
         1833  +	  for (i = 0; i < nAppend; i++)
         1834  +	    {
         1835  +		*zCsr++ = zAppend[i];
         1836  +		if (zAppend[i] == quote)
         1837  +		    *zCsr++ = quote;
         1838  +	    }
         1839  +	  *zCsr++ = quote;
         1840  +	  *zCsr++ = '\0';
         1841  +	  assert ((zCsr - zIn) == len);
         1842  +      }
         1843  +    else
         1844  +      {
         1845  +	  memcpy (&zIn[nIn], zAppend, nAppend);
         1846  +	  zIn[len - 1] = '\0';
         1847  +      }
         1848  +
         1849  +    return zIn;
  1593   1850   }
  1594   1851   
  1595   1852   
  1596   1853   /*
  1597   1854   ** Execute a query statement that will generate SQL output.  Print
  1598   1855   ** the result columns, comma-separated, on a line and then add a
  1599   1856   ** semicolon terminator to the end of that line.
  1600   1857   **
  1601   1858   ** If the number of columns is 1 and that column contains text "--"
  1602   1859   ** then write the semicolon on a separate line.  That way, if a 
  1603   1860   ** "--" comment occurs at the end of the statement, the comment
  1604   1861   ** won't consume the semicolon terminator.
  1605   1862   */
  1606         -static int run_table_dump_query(
  1607         -  struct callback_data *p, /* Query context */
  1608         -  const char *zSelect,     /* SELECT statement to extract content */
  1609         -  const char *zFirstRow    /* Print before first row, if not NULL */
  1610         -){
  1611         -  sqlite3_stmt *pSelect;
  1612         -  int rc;
  1613         -  int nResult;
  1614         -  int i;
  1615         -  const char *z;
  1616         -  rc = sqlite3_prepare(p->db, zSelect, -1, &pSelect, 0);
  1617         -  if( rc!=SQLITE_OK || !pSelect ){
  1618         -    fprintf(p->out, "/**** ERROR: (%d) %s *****/\n", rc, sqlite3_errmsg(p->db));
  1619         -    p->nErr++;
  1620         -    return rc;
  1621         -  }
  1622         -  rc = sqlite3_step(pSelect);
  1623         -  nResult = sqlite3_column_count(pSelect);
  1624         -  while( rc==SQLITE_ROW ){
  1625         -    if( zFirstRow ){
  1626         -      fprintf(p->out, "%s", zFirstRow);
  1627         -      zFirstRow = 0;
  1628         -    }
  1629         -    z = (const char*)sqlite3_column_text(pSelect, 0);
  1630         -    fprintf(p->out, "%s", z);
  1631         -    for(i=1; i<nResult; i++){ 
  1632         -      fprintf(p->out, ",%s", sqlite3_column_text(pSelect, i));
  1633         -    }
  1634         -    if( z==0 ) z = "";
  1635         -    while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
  1636         -    if( z[0] ){
  1637         -      fprintf(p->out, "\n;\n");
  1638         -    }else{
  1639         -      fprintf(p->out, ";\n");
  1640         -    }    
  1641         -    rc = sqlite3_step(pSelect);
  1642         -  }
  1643         -  rc = sqlite3_finalize(pSelect);
  1644         -  if( rc!=SQLITE_OK ){
  1645         -    fprintf(p->out, "/**** ERROR: (%d) %s *****/\n", rc, sqlite3_errmsg(p->db));
  1646         -    p->nErr++;
  1647         -  }
  1648         -  return rc;
         1863  +static int
         1864  +run_table_dump_query (struct callback_data *p,	/* Query context */
         1865  +		      const char *zSelect,	/* SELECT statement to extract content */
         1866  +		      const char *zFirstRow	/* Print before first row, if not NULL */
         1867  +    )
         1868  +{
         1869  +    sqlite3_stmt *pSelect;
         1870  +    int rc;
         1871  +    int nResult;
         1872  +    int i;
         1873  +    const char *z;
         1874  +    rc = sqlite3_prepare (p->db, zSelect, -1, &pSelect, 0);
         1875  +    if (rc != SQLITE_OK || !pSelect)
         1876  +      {
         1877  +	  fprintf (p->out, "/**** ERROR: (%d) %s *****/\n", rc,
         1878  +		   sqlite3_errmsg (p->db));
         1879  +	  p->nErr++;
         1880  +	  return rc;
         1881  +      }
         1882  +    rc = sqlite3_step (pSelect);
         1883  +    nResult = sqlite3_column_count (pSelect);
         1884  +    while (rc == SQLITE_ROW)
         1885  +      {
         1886  +	  if (zFirstRow)
         1887  +	    {
         1888  +		fprintf (p->out, "%s", zFirstRow);
         1889  +		zFirstRow = 0;
         1890  +	    }
         1891  +	  z = (const char *) sqlite3_column_text (pSelect, 0);
         1892  +	  fprintf (p->out, "%s", z);
         1893  +	  for (i = 1; i < nResult; i++)
         1894  +	    {
         1895  +		fprintf (p->out, ",%s", sqlite3_column_text (pSelect, i));
         1896  +	    }
         1897  +	  if (z == 0)
         1898  +	      z = "";
         1899  +	  while (z[0] && (z[0] != '-' || z[1] != '-'))
         1900  +	      z++;
         1901  +	  if (z[0])
         1902  +	    {
         1903  +		fprintf (p->out, "\n;\n");
         1904  +	    }
         1905  +	  else
         1906  +	    {
         1907  +		fprintf (p->out, ";\n");
         1908  +	    }
         1909  +	  rc = sqlite3_step (pSelect);
         1910  +      }
         1911  +    rc = sqlite3_finalize (pSelect);
         1912  +    if (rc != SQLITE_OK)
         1913  +      {
         1914  +	  fprintf (p->out, "/**** ERROR: (%d) %s *****/\n", rc,
         1915  +		   sqlite3_errmsg (p->db));
         1916  +	  p->nErr++;
         1917  +      }
         1918  +    return rc;
  1649   1919   }
  1650   1920   
  1651   1921   /*
  1652   1922   ** Allocate space and save off current error string.
  1653   1923   */
  1654         -static char *save_err_msg(
  1655         -  sqlite3 *db            /* Database to query */
  1656         -){
  1657         -  int nErrMsg = 1+strlen30(sqlite3_errmsg(db));
  1658         -  char *zErrMsg = sqlite3_malloc(nErrMsg);
  1659         -  if( zErrMsg ){
  1660         -    memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg);
  1661         -  }
  1662         -  return zErrMsg;
         1924  +static char *
         1925  +save_err_msg (sqlite3 * db	/* Database to query */
         1926  +    )
         1927  +{
         1928  +    int nErrMsg = 1 + strlen30 (sqlite3_errmsg (db));
         1929  +    char *zErrMsg = sqlite3_malloc (nErrMsg);
         1930  +    if (zErrMsg)
         1931  +      {
         1932  +	  memcpy (zErrMsg, sqlite3_errmsg (db), nErrMsg);
         1933  +      }
         1934  +    return zErrMsg;
  1663   1935   }
  1664   1936   
  1665   1937   /*
  1666   1938   ** Display memory stats.
  1667   1939   */
  1668         -static int display_stats(
  1669         -  sqlite3 *db,                /* Database to query */
  1670         -  struct callback_data *pArg, /* Pointer to struct callback_data */
  1671         -  int bReset                  /* True to reset the stats */
  1672         -){
  1673         -  int iCur;
  1674         -  int iHiwtr;
         1940  +static int
         1941  +display_stats (sqlite3 * db,	/* Database to query */
         1942  +	       struct callback_data *pArg,	/* Pointer to struct callback_data */
         1943  +	       int bReset	/* True to reset the stats */
         1944  +    )
         1945  +{
         1946  +    int iCur;
         1947  +    int iHiwtr;
  1675   1948   
  1676         -  if( pArg && pArg->out ){
  1677         -    
  1678         -    iHiwtr = iCur = -1;
  1679         -    sqlite3_status(SQLITE_STATUS_MEMORY_USED, &iCur, &iHiwtr, bReset);
  1680         -    fprintf(pArg->out, "Memory Used:                         %d (max %d) bytes\n", iCur, iHiwtr);
  1681         -    iHiwtr = iCur = -1;
  1682         -    sqlite3_status(SQLITE_STATUS_MALLOC_COUNT, &iCur, &iHiwtr, bReset);
  1683         -    fprintf(pArg->out, "Number of Outstanding Allocations:   %d (max %d)\n", iCur, iHiwtr);
         1949  +    if (pArg && pArg->out)
         1950  +      {
         1951  +
         1952  +	  iHiwtr = iCur = -1;
         1953  +	  sqlite3_status (SQLITE_STATUS_MEMORY_USED, &iCur, &iHiwtr, bReset);
         1954  +	  fprintf (pArg->out,
         1955  +		   "Memory Used:                         %d (max %d) bytes\n",
         1956  +		   iCur, iHiwtr);
         1957  +	  iHiwtr = iCur = -1;
         1958  +	  sqlite3_status (SQLITE_STATUS_MALLOC_COUNT, &iCur, &iHiwtr, bReset);
         1959  +	  fprintf (pArg->out,
         1960  +		   "Number of Outstanding Allocations:   %d (max %d)\n", iCur,
         1961  +		   iHiwtr);
  1684   1962   /*
  1685   1963   ** Not currently used by the CLI.
  1686   1964   **    iHiwtr = iCur = -1;
  1687   1965   **    sqlite3_status(SQLITE_STATUS_PAGECACHE_USED, &iCur, &iHiwtr, bReset);
  1688   1966   **    fprintf(pArg->out, "Number of Pcache Pages Used:         %d (max %d) pages\n", iCur, iHiwtr);
  1689   1967   */
  1690         -    iHiwtr = iCur = -1;
  1691         -    sqlite3_status(SQLITE_STATUS_PAGECACHE_OVERFLOW, &iCur, &iHiwtr, bReset);
  1692         -    fprintf(pArg->out, "Number of Pcache Overflow Bytes:     %d (max %d) bytes\n", iCur, iHiwtr);
         1968  +	  iHiwtr = iCur = -1;
         1969  +	  sqlite3_status (SQLITE_STATUS_PAGECACHE_OVERFLOW, &iCur, &iHiwtr,
         1970  +			  bReset);
         1971  +	  fprintf (pArg->out,
         1972  +		   "Number of Pcache Overflow Bytes:     %d (max %d) bytes\n",
         1973  +		   iCur, iHiwtr);
  1693   1974   /*
  1694   1975   ** Not currently used by the CLI.
  1695   1976   **    iHiwtr = iCur = -1;
  1696   1977   **    sqlite3_status(SQLITE_STATUS_SCRATCH_USED, &iCur, &iHiwtr, bReset);
  1697   1978   **    fprintf(pArg->out, "Number of Scratch Allocations Used:  %d (max %d)\n", iCur, iHiwtr);
  1698   1979   */
  1699         -    iHiwtr = iCur = -1;
  1700         -    sqlite3_status(SQLITE_STATUS_SCRATCH_OVERFLOW, &iCur, &iHiwtr, bReset);
  1701         -    fprintf(pArg->out, "Number of Scratch Overflow Bytes:    %d (max %d) bytes\n", iCur, iHiwtr);
  1702         -    iHiwtr = iCur = -1;
  1703         -    sqlite3_status(SQLITE_STATUS_MALLOC_SIZE, &iCur, &iHiwtr, bReset);
  1704         -    fprintf(pArg->out, "Largest Allocation:                  %d bytes\n", iHiwtr);
  1705         -    iHiwtr = iCur = -1;
  1706         -    sqlite3_status(SQLITE_STATUS_PAGECACHE_SIZE, &iCur, &iHiwtr, bReset);
  1707         -    fprintf(pArg->out, "Largest Pcache Allocation:           %d bytes\n", iHiwtr);
  1708         -    iHiwtr = iCur = -1;
  1709         -    sqlite3_status(SQLITE_STATUS_SCRATCH_SIZE, &iCur, &iHiwtr, bReset);
  1710         -    fprintf(pArg->out, "Largest Scratch Allocation:          %d bytes\n", iHiwtr);
         1980  +	  iHiwtr = iCur = -1;
         1981  +	  sqlite3_status (SQLITE_STATUS_SCRATCH_OVERFLOW, &iCur, &iHiwtr,
         1982  +			  bReset);
         1983  +	  fprintf (pArg->out,
         1984  +		   "Number of Scratch Overflow Bytes:    %d (max %d) bytes\n",
         1985  +		   iCur, iHiwtr);
         1986  +	  iHiwtr = iCur = -1;
         1987  +	  sqlite3_status (SQLITE_STATUS_MALLOC_SIZE, &iCur, &iHiwtr, bReset);
         1988  +	  fprintf (pArg->out, "Largest Allocation:                  %d bytes\n",
         1989  +		   iHiwtr);
         1990  +	  iHiwtr = iCur = -1;
         1991  +	  sqlite3_status (SQLITE_STATUS_PAGECACHE_SIZE, &iCur, &iHiwtr, bReset);
         1992  +	  fprintf (pArg->out, "Largest Pcache Allocation:           %d bytes\n",
         1993  +		   iHiwtr);
         1994  +	  iHiwtr = iCur = -1;
         1995  +	  sqlite3_status (SQLITE_STATUS_SCRATCH_SIZE, &iCur, &iHiwtr, bReset);
         1996  +	  fprintf (pArg->out, "Largest Scratch Allocation:          %d bytes\n",
         1997  +		   iHiwtr);
  1711   1998   #ifdef YYTRACKMAXSTACKDEPTH
  1712         -    iHiwtr = iCur = -1;
  1713         -    sqlite3_status(SQLITE_STATUS_PARSER_STACK, &iCur, &iHiwtr, bReset);
  1714         -    fprintf(pArg->out, "Deepest Parser Stack:                %d (max %d)\n", iCur, iHiwtr);
         1999  +	  iHiwtr = iCur = -1;
         2000  +	  sqlite3_status (SQLITE_STATUS_PARSER_STACK, &iCur, &iHiwtr, bReset);
         2001  +	  fprintf (pArg->out,
         2002  +		   "Deepest Parser Stack:                %d (max %d)\n", iCur,
         2003  +		   iHiwtr);
  1715   2004   #endif
  1716         -  }
         2005  +      }
  1717   2006   
  1718   2007   /* Sandro Furieri 1 November 2012 - depending on SQLite version */
  1719         -  if( pArg && pArg->out && db ){
  1720         -    iHiwtr = iCur = -1;
         2008  +    if (pArg && pArg->out && db)
         2009  +      {
         2010  +	  iHiwtr = iCur = -1;
  1721   2011   #ifdef HAVE_DECL_SQLITE_DBSTATUS_LOOKASIDE_USED
  1722         -    sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED, &iCur, &iHiwtr, bReset);
  1723         -    fprintf(pArg->out, "Lookaside Slots Used:                %d (max %d)\n", iCur, iHiwtr);
         2012  +	  sqlite3_db_status (db, SQLITE_DBSTATUS_LOOKASIDE_USED, &iCur, &iHiwtr,
         2013  +			     bReset);
         2014  +	  fprintf (pArg->out,
         2015  +		   "Lookaside Slots Used:                %d (max %d)\n", iCur,
         2016  +		   iHiwtr);
  1724   2017   #else
  1725         -    fprintf(pArg->out, "Lookaside Slots Used:                n.a.\n");
         2018  +	  fprintf (pArg->out, "Lookaside Slots Used:                n.a.\n");
  1726   2019   #endif
  1727   2020   #ifdef HAVE_DECL_SQLITE_DBSTATUS_LOOKASIDE_HIT
  1728         -    sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT, &iCur, &iHiwtr, bReset);
  1729         -    fprintf(pArg->out, "Successful lookaside attempts:       %d\n", iHiwtr);
         2021  +	  sqlite3_db_status (db, SQLITE_DBSTATUS_LOOKASIDE_HIT, &iCur, &iHiwtr,
         2022  +			     bReset);
         2023  +	  fprintf (pArg->out, "Successful lookaside attempts:       %d\n",
         2024  +		   iHiwtr);
  1730   2025   #else
  1731         -    fprintf(pArg->out, "Successful lookaside attempts:       n.a.\n");
         2026  +	  fprintf (pArg->out, "Successful lookaside attempts:       n.a.\n");
  1732   2027   #endif
  1733   2028   #ifdef HAVE_DECL_SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE
  1734         -    sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE, &iCur, &iHiwtr, bReset);
  1735         -    fprintf(pArg->out, "Lookaside failures due to size:      %d\n", iHiwtr);
         2029  +	  sqlite3_db_status (db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE, &iCur,
         2030  +			     &iHiwtr, bReset);
         2031  +	  fprintf (pArg->out, "Lookaside failures due to size:      %d\n",
         2032  +		   iHiwtr);
  1736   2033   #else
  1737         -    fprintf(pArg->out, "Lookaside failures due to size:      n.a.\n");
         2034  +	  fprintf (pArg->out, "Lookaside failures due to size:      n.a.\n");
  1738   2035   #endif
  1739   2036   #ifdef HAVE_DECL_SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL
  1740         -    sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL, &iCur, &iHiwtr, bReset);
  1741         -    fprintf(pArg->out, "Lookaside failures due to OOM:       %d\n", iHiwtr);
         2037  +	  sqlite3_db_status (db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL, &iCur,
         2038  +			     &iHiwtr, bReset);
         2039  +	  fprintf (pArg->out, "Lookaside failures due to OOM:       %d\n",
         2040  +		   iHiwtr);
  1742   2041   #else
  1743         -    fprintf(pArg->out, "Lookaside failures due to OOM:       n.a.\n");
         2042  +	  fprintf (pArg->out, "Lookaside failures due to OOM:       n.a.\n");
  1744   2043   #endif
  1745         -    iHiwtr = iCur = -1;
         2044  +	  iHiwtr = iCur = -1;
  1746   2045   #ifdef HAVE_DECL_SQLITE_DBSTATUS_CACHE_USED
  1747         -    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
  1748         -    fprintf(pArg->out, "Pager Heap Usage:                    %d bytes\n", iCur);  
         2046  +	  sqlite3_db_status (db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr,
         2047  +			     bReset);
         2048  +	  fprintf (pArg->out, "Pager Heap Usage:                    %d bytes\n",
         2049  +		   iCur);
  1749   2050   #else
  1750         -    fprintf(pArg->out, "Pager Heap Usage:                    n.a.\n");  
  1751         -#endif  
  1752         -    iHiwtr = iCur = -1;
         2051  +	  fprintf (pArg->out, "Pager Heap Usage:                    n.a.\n");
         2052  +#endif
         2053  +	  iHiwtr = iCur = -1;
  1753   2054   #ifdef HAVE_DECL_SQLITE_DBSTATUS_CACHE_HIT
  1754         -    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
  1755         -    fprintf(pArg->out, "Page cache hits:                     %d\n", iCur);
         2055  +	  sqlite3_db_status (db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
         2056  +	  fprintf (pArg->out, "Page cache hits:                     %d\n",
         2057  +		   iCur);
  1756   2058   #else
  1757         -    fprintf(pArg->out, "Page cache hits:                     n.a.\n");
         2059  +	  fprintf (pArg->out, "Page cache hits:                     n.a.\n");
  1758   2060   #endif
  1759         -    iHiwtr = iCur = -1;
         2061  +	  iHiwtr = iCur = -1;
  1760   2062   #ifdef HAVE_DECL_SQLITE_DBSTATUS_CACHE_MISS
  1761         -    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
  1762         -    fprintf(pArg->out, "Page cache misses:                   %d\n", iCur); 
         2063  +	  sqlite3_db_status (db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
         2064  +	  fprintf (pArg->out, "Page cache misses:                   %d\n",
         2065  +		   iCur);
  1763   2066   #else
  1764         -    fprintf(pArg->out, "Page cache misses:                   n.a.\n"); 
         2067  +	  fprintf (pArg->out, "Page cache misses:                   n.a.\n");
  1765   2068   #endif
  1766         -    iHiwtr = iCur = -1;
         2069  +	  iHiwtr = iCur = -1;
  1767   2070   #ifdef HAVE_DECL_SQLITE_DBSTATUS_CACHE_WRITE
  1768         -    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
  1769         -    fprintf(pArg->out, "Page cache writes:                   %d\n", iCur); 
         2071  +	  sqlite3_db_status (db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr,
         2072  +			     1);
         2073  +	  fprintf (pArg->out, "Page cache writes:                   %d\n",
         2074  +		   iCur);
  1770   2075   #else
  1771         -    fprintf(pArg->out, "Page cache writes:                   n.a.\n"); 
         2076  +	  fprintf (pArg->out, "Page cache writes:                   n.a.\n");
  1772   2077   #endif
  1773         -    iHiwtr = iCur = -1;
         2078  +	  iHiwtr = iCur = -1;
  1774   2079   #ifdef HAVE_DECL_SQLITE_DBSTATUS_SCHEMA_USED
  1775         -    sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
  1776         -    fprintf(pArg->out, "Schema Heap Usage:                   %d bytes\n", iCur);
         2080  +	  sqlite3_db_status (db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr,
         2081  +			     bReset);
         2082  +	  fprintf (pArg->out, "Schema Heap Usage:                   %d bytes\n",
         2083  +		   iCur);
  1777   2084   #else
  1778         -    fprintf(pArg->out, "Schema Heap Usage:                   n.a.\n");
  1779         -#endif 
  1780         -    iHiwtr = iCur = -1;
         2085  +	  fprintf (pArg->out, "Schema Heap Usage:                   n.a.\n");
         2086  +#endif
         2087  +	  iHiwtr = iCur = -1;
  1781   2088   #ifdef HAVE_DECL_SQLITE_DBSTATUS_STMT_USED
  1782         -    sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
  1783         -    fprintf(pArg->out, "Statement Heap/Lookaside Usage:      %d bytes\n", iCur); 
         2089  +	  sqlite3_db_status (db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr,
         2090  +			     bReset);
         2091  +	  fprintf (pArg->out, "Statement Heap/Lookaside Usage:      %d bytes\n",
         2092  +		   iCur);
  1784   2093   #else
  1785         -    fprintf(pArg->out, "Statement Heap/Lookaside Usage:      n.a.\n");
         2094  +	  fprintf (pArg->out, "Statement Heap/Lookaside Usage:      n.a.\n");
  1786   2095   #endif
  1787         -  }
         2096  +      }
  1788   2097   
  1789         -  if( pArg && pArg->out && db && pArg->pStmt ){
         2098  +    if (pArg && pArg->out && db && pArg->pStmt)
         2099  +      {
  1790   2100   #ifdef HAVE_DECL_SQLITE_STMTSTATUS_FULLSCAN_STEP
  1791         -    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP, bReset);
  1792         -    fprintf(pArg->out, "Fullscan Steps:                      %d\n", iCur);
         2101  +	  iCur =
         2102  +	      sqlite3_stmt_status (pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
         2103  +				   bReset);
         2104  +	  fprintf (pArg->out, "Fullscan Steps:                      %d\n",
         2105  +		   iCur);
  1793   2106   #else
  1794         -    fprintf(pArg->out, "Fullscan Steps:                      n.a.\n");
         2107  +	  fprintf (pArg->out, "Fullscan Steps:                      n.a.\n");
  1795   2108   #endif
  1796   2109   #ifdef HAVE_DECL_SQLITE_STMTSTATUS_SORT
  1797         -    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
  1798         -    fprintf(pArg->out, "Sort Operations:                     %d\n", iCur);
         2110  +	  iCur =
         2111  +	      sqlite3_stmt_status (pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
         2112  +	  fprintf (pArg->out, "Sort Operations:                     %d\n",
         2113  +		   iCur);
  1799   2114   #else
  1800         -    fprintf(pArg->out, "Sort Operations:                     n.a.\n");
         2115  +	  fprintf (pArg->out, "Sort Operations:                     n.a.\n");
  1801   2116   #endif
  1802   2117   #ifdef HAVE_DECL_SQLITE_STMTSTATUS_AUTOINDEX
  1803         -    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX, bReset);
  1804         -    fprintf(pArg->out, "Autoindex Inserts:                   %d\n", iCur);
         2118  +	  iCur =
         2119  +	      sqlite3_stmt_status (pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,
         2120  +				   bReset);
         2121  +	  fprintf (pArg->out, "Autoindex Inserts:                   %d\n",
         2122  +		   iCur);
  1805   2123   #else
  1806         -    fprintf(pArg->out, "Autoindex Inserts:                   n.a.\n");
         2124  +	  fprintf (pArg->out, "Autoindex Inserts:                   n.a.\n");
  1807   2125   #endif
  1808         -  }
         2126  +      }
  1809   2127   /* end sandro 1 November 2012 */
  1810   2128   
  1811         -  return 0;
         2129  +    return 0;
  1812   2130   }
  1813   2131   
  1814   2132   /*
  1815   2133   ** Execute a statement or set of statements.  Print 
  1816   2134   ** any result rows/columns depending on the current mode 
  1817   2135   ** set via the supplied callback.
  1818   2136   **
  1819   2137   ** This is very similar to SQLite's built-in sqlite3_exec() 
  1820   2138   ** function except it takes a slightly different callback 
  1821   2139   ** and callback data argument.
  1822   2140   */
  1823         -static int shell_exec(
  1824         -  sqlite3 *db,                                /* An open database */
  1825         -  const char *zSql,                           /* SQL to be evaluated */
  1826         -  int (*xCallback)(void*,int,char**,char**,int*),   /* Callback function */
  1827         -                                              /* (not the same as sqlite3_exec) */
  1828         -  struct callback_data *pArg,                 /* Pointer to struct callback_data */
  1829         -  char **pzErrMsg                             /* Error msg written here */
  1830         -){
  1831         -  sqlite3_stmt *pStmt = NULL;     /* Statement to execute. */
  1832         -  int rc = SQLITE_OK;             /* Return Code */
  1833         -  int rc2;
  1834         -  const char *zLeftover;          /* Tail of unprocessed SQL */
  1835         -
  1836         -  if( pzErrMsg ){
  1837         -    *pzErrMsg = NULL;
  1838         -  }
  1839         -
  1840         -  while( zSql[0] && (SQLITE_OK == rc) ){
  1841         -    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
  1842         -    if( SQLITE_OK != rc ){
  1843         -      if( pzErrMsg ){
  1844         -        *pzErrMsg = save_err_msg(db);
  1845         -      }
  1846         -    }else{
  1847         -      if( !pStmt ){
  1848         -        /* this happens for a comment or white-space */
  1849         -        zSql = zLeftover;
  1850         -        while( IsSpace(zSql[0]) ) zSql++;
  1851         -        continue;
  1852         -      }
  1853         -
  1854         -      /* save off the prepared statment handle and reset row count */
  1855         -      if( pArg ){
  1856         -        pArg->pStmt = pStmt;
  1857         -        pArg->cnt = 0;
  1858         -      }
  1859         -
  1860         -      /* echo the sql statement if echo on */
  1861         -      if( pArg && pArg->echoOn ){
  1862         -        const char *zStmtSql = sqlite3_sql(pStmt);
  1863         -        fprintf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql);
  1864         -      }
  1865         -
  1866         -      /* Output TESTCTRL_EXPLAIN text of requested */
  1867         -      if( pArg && pArg->mode==MODE_Explain ){
         2141  +static int
         2142  +shell_exec (sqlite3 * db,	/* An open database */
         2143  +	    const char *zSql,	/* SQL to be evaluated */
         2144  +	    int (*xCallback) (void *, int, char **, char **, int *),	/* Callback function */
         2145  +	    /* (not the same as sqlite3_exec) */
         2146  +	    struct callback_data *pArg,	/* Pointer to struct callback_data */
         2147  +	    char **pzErrMsg	/* Error msg written here */
         2148  +    )
         2149  +{
         2150  +    sqlite3_stmt *pStmt = NULL;	/* Statement to execute. */
         2151  +    int rc = SQLITE_OK;		/* Return Code */
         2152  +    int rc2;
         2153  +    const char *zLeftover;	/* Tail of unprocessed SQL */
         2154  +
         2155  +    if (pzErrMsg)
         2156  +      {
         2157  +	  *pzErrMsg = NULL;
         2158  +      }
         2159  +
         2160  +    while (zSql[0] && (SQLITE_OK == rc))
         2161  +      {
         2162  +	  rc = sqlite3_prepare_v2 (db, zSql, -1, &pStmt, &zLeftover);
         2163  +	  if (SQLITE_OK != rc)
         2164  +	    {
         2165  +		if (pzErrMsg)
         2166  +		  {
         2167  +		      *pzErrMsg = save_err_msg (db);
         2168  +		  }
         2169  +	    }
         2170  +	  else
         2171  +	    {
         2172  +		if (!pStmt)
         2173  +		  {
         2174  +		      /* this happens for a comment or white-space */
         2175  +		      zSql = zLeftover;
         2176  +		      while (IsSpace (zSql[0]))
         2177  +			  zSql++;
         2178  +		      continue;
         2179  +		  }
         2180  +
         2181  +		/* save off the prepared statment handle and reset row count */
         2182  +		if (pArg)
         2183  +		  {
         2184  +		      pArg->pStmt = pStmt;
         2185  +		      pArg->cnt = 0;
         2186  +		  }
         2187  +
         2188  +		/* echo the sql statement if echo on */
         2189  +		if (pArg && pArg->echoOn)
         2190  +		  {
         2191  +		      const char *zStmtSql = sqlite3_sql (pStmt);
         2192  +		      fprintf (pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql);
         2193  +		  }
         2194  +
         2195  +		/* Output TESTCTRL_EXPLAIN text of requested */
         2196  +		if (pArg && pArg->mode == MODE_Explain)
         2197  +		  {
  1868   2198   /* Sandro Furieri 1 November 2012 - depending on SQLite version */
  1869   2199   #ifdef HAVE_DECL_SQLITE_TESTCTRL_EXPLAIN_STMT
  1870         -        const char *zExplain = 0;
  1871         -        sqlite3_test_control(SQLITE_TESTCTRL_EXPLAIN_STMT, pStmt, &zExplain);
  1872         -        if( zExplain && zExplain[0] ){
  1873         -          fprintf(pArg->out, "%s", zExplain);
  1874         -        }
         2200  +		      const char *zExplain = 0;
         2201  +		      sqlite3_test_control (SQLITE_TESTCTRL_EXPLAIN_STMT, pStmt,
         2202  +					    &zExplain);
         2203  +		      if (zExplain && zExplain[0])
         2204  +			{
         2205  +			    fprintf (pArg->out, "%s", zExplain);
         2206  +			}
  1875   2207   #else
  1876         -          fprintf(pArg->out, "TESTCTRL_EXPLAIN: unsupported");
         2208  +		      fprintf (pArg->out, "TESTCTRL_EXPLAIN: unsupported");
  1877   2209   #endif
  1878   2210   /* end sandro 1 November 2012 */
  1879         -      }
  1880         -
  1881         -      /* perform the first step.  this will tell us if we
  1882         -      ** have a result set or not and how wide it is.
  1883         -      */
  1884         -      rc = sqlite3_step(pStmt);
  1885         -      /* if we have a result set... */
  1886         -      if( SQLITE_ROW == rc ){
  1887         -        /* if we have a callback... */
  1888         -        if( xCallback ){
  1889         -          /* allocate space for col name ptr, value ptr, and type */
  1890         -          int nCol = sqlite3_column_count(pStmt);
  1891         -          void *pData = sqlite3_malloc(3*nCol*sizeof(const char*) + 1);
  1892         -          if( !pData ){
  1893         -            rc = SQLITE_NOMEM;
  1894         -          }else{
  1895         -            char **azCols = (char **)pData;      /* Names of result columns */
  1896         -            char **azVals = &azCols[nCol];       /* Results */
  1897         -            int *aiTypes = (int *)&azVals[nCol]; /* Result types */
  1898         -            int i;
  1899         -            assert(sizeof(int) <= sizeof(char *)); 
  1900         -            /* save off ptrs to column names */
  1901         -            for(i=0; i<nCol; i++){
  1902         -              azCols[i] = (char *)sqlite3_column_name(pStmt, i);
  1903         -            }
  1904         -            do{
  1905         -              /* extract the data and data types */
  1906         -              for(i=0; i<nCol; i++){
  1907         -                azVals[i] = (char *)sqlite3_column_text(pStmt, i);
  1908         -                aiTypes[i] = sqlite3_column_type(pStmt, i);
  1909         -                if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
  1910         -                  rc = SQLITE_NOMEM;
  1911         -                  break; /* from for */
  1912         -                }
  1913         -              } /* end for */
  1914         -
  1915         -              /* if data and types extracted successfully... */
  1916         -              if( SQLITE_ROW == rc ){ 
  1917         -                /* call the supplied callback with the result row data */
  1918         -                if( xCallback(pArg, nCol, azVals, azCols, aiTypes) ){
  1919         -                  rc = SQLITE_ABORT;
  1920         -                }else{
  1921         -                  rc = sqlite3_step(pStmt);
  1922         -                }
  1923         -              }
  1924         -            } while( SQLITE_ROW == rc );
  1925         -            sqlite3_free(pData);
  1926         -          }
  1927         -        }else{
  1928         -          do{
  1929         -            rc = sqlite3_step(pStmt);
  1930         -          } while( rc == SQLITE_ROW );
  1931         -        }
  1932         -      }
  1933         -
  1934         -      /* print usage stats if stats on */
  1935         -      if( pArg && pArg->statsOn ){
  1936         -        display_stats(db, pArg, 0);
  1937         -      }
  1938         -
  1939         -      /* Finalize the statement just executed. If this fails, save a 
  1940         -      ** copy of the error message. Otherwise, set zSql to point to the
  1941         -      ** next statement to execute. */
  1942         -      rc2 = sqlite3_finalize(pStmt);
  1943         -      if( rc!=SQLITE_NOMEM ) rc = rc2;
  1944         -      if( rc==SQLITE_OK ){
  1945         -        zSql = zLeftover;
  1946         -        while( IsSpace(zSql[0]) ) zSql++;
  1947         -      }else if( pzErrMsg ){
  1948         -        *pzErrMsg = save_err_msg(db);
  1949         -      }
  1950         -
  1951         -      /* clear saved stmt handle */
  1952         -      if( pArg ){
  1953         -        pArg->pStmt = NULL;
  1954         -      }
  1955         -    }
  1956         -  } /* end while */
  1957         -
  1958         -  return rc;
         2211  +		  }
         2212  +
         2213  +		/* perform the first step.  this will tell us if we
         2214  +		 ** have a result set or not and how wide it is.
         2215  +		 */
         2216  +		rc = sqlite3_step (pStmt);
         2217  +		/* if we have a result set... */
         2218  +		if (SQLITE_ROW == rc)
         2219  +		  {
         2220  +		      /* if we have a callback... */
         2221  +		      if (xCallback)
         2222  +			{
         2223  +			    /* allocate space for col name ptr, value ptr, and type */
         2224  +			    int nCol = sqlite3_column_count (pStmt);
         2225  +			    void *pData =
         2226  +				sqlite3_malloc (3 * nCol *
         2227  +						sizeof (const char *) + 1);
         2228  +			    if (!pData)
         2229  +			      {
         2230  +				  rc = SQLITE_NOMEM;
         2231  +			      }
         2232  +			    else
         2233  +			      {
         2234  +				  char **azCols = (char **) pData;	/* Names of result columns */
         2235  +				  char **azVals = &azCols[nCol];	/* Results */
         2236  +				  int *aiTypes = (int *) &azVals[nCol];	/* Result types */
         2237  +				  int i;
         2238  +				  assert (sizeof (int) <= sizeof (char *));
         2239  +				  /* save off ptrs to column names */
         2240  +				  for (i = 0; i < nCol; i++)
         2241  +				    {
         2242  +					azCols[i] =
         2243  +					    (char *) sqlite3_column_name (pStmt,
         2244  +									  i);
         2245  +				    }
         2246  +				  do
         2247  +				    {
         2248  +					/* extract the data and data types */
         2249  +					for (i = 0; i < nCol; i++)
         2250  +					  {
         2251  +					      azVals[i] =
         2252  +						  (char *)
         2253  +						  sqlite3_column_text (pStmt,
         2254  +								       i);
         2255  +					      aiTypes[i] =
         2256  +						  sqlite3_column_type (pStmt,
         2257  +								       i);
         2258  +					      if (!azVals[i]
         2259  +						  && (aiTypes[i] !=
         2260  +						      SQLITE_NULL))
         2261  +						{
         2262  +						    rc = SQLITE_NOMEM;
         2263  +						    break;	/* from for */
         2264  +						}
         2265  +					  }	/* end for */
         2266  +
         2267  +					/* if data and types extracted successfully... */
         2268  +					if (SQLITE_ROW == rc)
         2269  +					  {
         2270  +					      /* call the supplied callback with the result row data */
         2271  +					      if (xCallback
         2272  +						  (pArg, nCol, azVals, azCols,
         2273  +						   aiTypes))
         2274  +						{
         2275  +						    rc = SQLITE_ABORT;
         2276  +						}
         2277  +					      else
         2278  +						{
         2279  +						    rc = sqlite3_step (pStmt);
         2280  +						}
         2281  +					  }
         2282  +				    }
         2283  +				  while (SQLITE_ROW == rc);
         2284  +				  sqlite3_free (pData);
         2285  +			      }
         2286  +			}
         2287  +		      else
         2288  +			{
         2289  +			    do
         2290  +			      {
         2291  +				  rc = sqlite3_step (pStmt);
         2292  +			      }
         2293  +			    while (rc == SQLITE_ROW);
         2294  +			}
         2295  +		  }
         2296  +
         2297  +		/* print usage stats if stats on */
         2298  +		if (pArg && pArg->statsOn)
         2299  +		  {
         2300  +		      display_stats (db, pArg, 0);
         2301  +		  }
         2302  +
         2303  +		/* Finalize the statement just executed. If this fails, save a 
         2304  +		 ** copy of the error message. Otherwise, set zSql to point to the
         2305  +		 ** next statement to execute. */
         2306  +		rc2 = sqlite3_finalize (pStmt);
         2307  +		if (rc != SQLITE_NOMEM)
         2308  +		    rc = rc2;
         2309  +		if (rc == SQLITE_OK)
         2310  +		  {
         2311  +		      zSql = zLeftover;
         2312  +		      while (IsSpace (zSql[0]))
         2313  +			  zSql++;
         2314  +		  }
         2315  +		else if (pzErrMsg)
         2316  +		  {
         2317  +		      *pzErrMsg = save_err_msg (db);
         2318  +		  }
         2319  +
         2320  +		/* clear saved stmt handle */
         2321  +		if (pArg)
         2322  +		  {
         2323  +		      pArg->pStmt = NULL;
         2324  +		  }
         2325  +	    }
         2326  +      }				/* end while */
         2327  +
         2328  +    return rc;
  1959   2329   }
  1960   2330   
  1961   2331   
  1962   2332   /*
  1963   2333   ** This is a different callback routine used for dumping the database.
  1964   2334   ** Each row received by this callback consists of a table name,
  1965   2335   ** the table type ("index" or "table") and SQL to create the table.
  1966   2336   ** This routine should print text sufficient to recreate the table.
  1967   2337   */
  1968         -static int dump_callback(void *pArg, int nArg, char **azArg, char **azCol){
  1969         -  int rc;
  1970         -  const char *zTable;
  1971         -  const char *zType;
  1972         -  const char *zSql;
  1973         -  const char *zPrepStmt = 0;
  1974         -  struct callback_data *p = (struct callback_data *)pArg;
  1975         -
  1976         -  UNUSED_PARAMETER(azCol);
  1977         -  if( nArg!=3 ) return 1;
  1978         -  zTable = azArg[0];
  1979         -  zType = azArg[1];
  1980         -  zSql = azArg[2];
  1981         -  
  1982         -  if( strcmp(zTable, "sqlite_sequence")==0 ){
  1983         -    zPrepStmt = "DELETE FROM sqlite_sequence;\n";
  1984         -  }else if( strcmp(zTable, "sqlite_stat1")==0 ){
  1985         -    fprintf(p->out, "ANALYZE sqlite_master;\n");
  1986         -  }else if( strncmp(zTable, "sqlite_", 7)==0 ){
  1987         -    return 0;
  1988         -  }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
  1989         -    char *zIns;
  1990         -    if( !p->writableSchema ){
  1991         -      fprintf(p->out, "PRAGMA writable_schema=ON;\n");
  1992         -      p->writableSchema = 1;
  1993         -    }
  1994         -    zIns = sqlite3_mprintf(
  1995         -       "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"
  1996         -       "VALUES('table','%q','%q',0,'%q');",
  1997         -       zTable, zTable, zSql);
  1998         -    fprintf(p->out, "%s\n", zIns);
  1999         -    sqlite3_free(zIns);
  2000         -    return 0;
  2001         -  }else{
  2002         -    fprintf(p->out, "%s;\n", zSql);
  2003         -  }
  2004         -
  2005         -  if( strcmp(zType, "table")==0 ){
  2006         -    sqlite3_stmt *pTableInfo = 0;
  2007         -    char *zSelect = 0;
  2008         -    char *zTableInfo = 0;
  2009         -    char *zTmp = 0;
  2010         -    int nRow = 0;
  2011         -   
  2012         -    zTableInfo = appendText(zTableInfo, "PRAGMA table_info(", 0);
  2013         -    zTableInfo = appendText(zTableInfo, zTable, '"');
  2014         -    zTableInfo = appendText(zTableInfo, ");", 0);
  2015         -
  2016         -    rc = sqlite3_prepare(p->db, zTableInfo, -1, &pTableInfo, 0);
  2017         -    free(zTableInfo);
  2018         -    if( rc!=SQLITE_OK || !pTableInfo ){
  2019         -      return 1;
  2020         -    }
  2021         -
  2022         -    zSelect = appendText(zSelect, "SELECT 'INSERT INTO ' || ", 0);
  2023         -    /* Always quote the table name, even if it appears to be pure ascii,
  2024         -    ** in case it is a keyword. Ex:  INSERT INTO "table" ... */
  2025         -    zTmp = appendText(zTmp, zTable, '"');
  2026         -    if( zTmp ){
  2027         -      zSelect = appendText(zSelect, zTmp, '\'');
  2028         -      free(zTmp);
  2029         -    }
  2030         -    zSelect = appendText(zSelect, " || ' VALUES(' || ", 0);
  2031         -    rc = sqlite3_step(pTableInfo);
  2032         -    while( rc==SQLITE_ROW ){
  2033         -      const char *zText = (const char *)sqlite3_column_text(pTableInfo, 1);
  2034         -      zSelect = appendText(zSelect, "quote(", 0);
  2035         -      zSelect = appendText(zSelect, zText, '"');
  2036         -      rc = sqlite3_step(pTableInfo);
  2037         -      if( rc==SQLITE_ROW ){
  2038         -        zSelect = appendText(zSelect, "), ", 0);
  2039         -      }else{
  2040         -        zSelect = appendText(zSelect, ") ", 0);
  2041         -      }
  2042         -      nRow++;
  2043         -    }
  2044         -    rc = sqlite3_finalize(pTableInfo);
  2045         -    if( rc!=SQLITE_OK || nRow==0 ){
  2046         -      free(zSelect);
  2047         -      return 1;
  2048         -    }
  2049         -    zSelect = appendText(zSelect, "|| ')' FROM  ", 0);
  2050         -    zSelect = appendText(zSelect, zTable, '"');
  2051         -
  2052         -    rc = run_table_dump_query(p, zSelect, zPrepStmt);
  2053         -    if( rc==SQLITE_CORRUPT ){
  2054         -      zSelect = appendText(zSelect, " ORDER BY rowid DESC", 0);
  2055         -      run_table_dump_query(p, zSelect, 0);
  2056         -    }
  2057         -    free(zSelect);
  2058         -  }
  2059         -  return 0;
         2338  +static int
         2339  +dump_callback (void *pArg, int nArg, char **azArg, char **azCol)
         2340  +{
         2341  +    int rc;
         2342  +    const char *zTable;
         2343  +    const char *zType;
         2344  +    const char *zSql;
         2345  +    const char *zPrepStmt = 0;
         2346  +    struct callback_data *p = (struct callback_data *) pArg;
         2347  +
         2348  +    UNUSED_PARAMETER (azCol);
         2349  +    if (nArg != 3)
         2350  +	return 1;
         2351  +    zTable = azArg[0];
         2352  +    zType = azArg[1];
         2353  +    zSql = azArg[2];
         2354  +
         2355  +    if (strcmp (zTable, "sqlite_sequence") == 0)
         2356  +      {
         2357  +	  zPrepStmt = "DELETE FROM sqlite_sequence;\n";
         2358  +      }
         2359  +    else if (strcmp (zTable, "sqlite_stat1") == 0)
         2360  +      {
         2361  +	  fprintf (p->out, "ANALYZE sqlite_master;\n");
         2362  +      }
         2363  +    else if (strncmp (zTable, "sqlite_", 7) == 0)
         2364  +      {
         2365  +	  return 0;
         2366  +      }
         2367  +    else if (strncmp (zSql, "CREATE VIRTUAL TABLE", 20) == 0)
         2368  +      {
         2369  +	  char *zIns;
         2370  +	  if (!p->writableSchema)
         2371  +	    {
         2372  +		fprintf (p->out, "PRAGMA writable_schema=ON;\n");
         2373  +		p->writableSchema = 1;
         2374  +	    }
         2375  +	  zIns =
         2376  +	      sqlite3_mprintf
         2377  +	      ("INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"
         2378  +	       "VALUES('table','%q','%q',0,'%q');", zTable, zTable, zSql);
         2379  +	  fprintf (p->out, "%s\n", zIns);
         2380  +	  sqlite3_free (zIns);
         2381  +	  return 0;
         2382  +      }
         2383  +    else
         2384  +      {
         2385  +	  fprintf (p->out, "%s;\n", zSql);
         2386  +      }
         2387  +
         2388  +    if (strcmp (zType, "table") == 0)
         2389  +      {
         2390  +	  sqlite3_stmt *pTableInfo = 0;
         2391  +	  char *zSelect = 0;
         2392  +	  char *zTableInfo = 0;
         2393  +	  char *zTmp = 0;
         2394  +	  int nRow = 0;
         2395  +
         2396  +	  zTableInfo = appendText (zTableInfo, "PRAGMA table_info(", 0);
         2397  +	  zTableInfo = appendText (zTableInfo, zTable, '"');
         2398  +	  zTableInfo = appendText (zTableInfo, ");", 0);
         2399  +
         2400  +	  rc = sqlite3_prepare (p->db, zTableInfo, -1, &pTableInfo, 0);
         2401  +	  free (zTableInfo);
         2402  +	  if (rc != SQLITE_OK || !pTableInfo)
         2403  +	    {
         2404  +		return 1;
         2405  +	    }
         2406  +
         2407  +	  zSelect = appendText (zSelect, "SELECT 'INSERT INTO ' || ", 0);
         2408  +	  /* Always quote the table name, even if it appears to be pure ascii,
         2409  +	   ** in case it is a keyword. Ex:  INSERT INTO "table" ... */
         2410  +	  zTmp = appendText (zTmp, zTable, '"');
         2411  +	  if (zTmp)
         2412  +	    {
         2413  +		zSelect = appendText (zSelect, zTmp, '\'');
         2414  +		free (zTmp);
         2415  +	    }
         2416  +	  zSelect = appendText (zSelect, " || ' VALUES(' || ", 0);
         2417  +	  rc = sqlite3_step (pTableInfo);
         2418  +	  while (rc == SQLITE_ROW)
         2419  +	    {
         2420  +		const char *zText =
         2421  +		    (const char *) sqlite3_column_text (pTableInfo, 1);
         2422  +		zSelect = appendText (zSelect, "quote(", 0);
         2423  +		zSelect = appendText (zSelect, zText, '"');
         2424  +		rc = sqlite3_step (pTableInfo);
         2425  +		if (rc == SQLITE_ROW)
         2426  +		  {
         2427  +		      zSelect = appendText (zSelect, "), ", 0);
         2428  +		  }
         2429  +		else
         2430  +		  {
         2431  +		      zSelect = appendText (zSelect, ") ", 0);
         2432  +		  }
         2433  +		nRow++;
         2434  +	    }
         2435  +	  rc = sqlite3_finalize (pTableInfo);
         2436  +	  if (rc != SQLITE_OK || nRow == 0)
         2437  +	    {
         2438  +		free (zSelect);
         2439  +		return 1;
         2440  +	    }
         2441  +	  zSelect = appendText (zSelect, "|| ')' FROM  ", 0);
         2442  +	  zSelect = appendText (zSelect, zTable, '"');
         2443  +
         2444  +	  rc = run_table_dump_query (p, zSelect, zPrepStmt);
         2445  +	  if (rc == SQLITE_CORRUPT)
         2446  +	    {
         2447  +		zSelect = appendText (zSelect, " ORDER BY rowid DESC", 0);
         2448  +		run_table_dump_query (p, zSelect, 0);
         2449  +	    }
         2450  +	  free (zSelect);
         2451  +      }
         2452  +    return 0;
  2060   2453   }
  2061   2454   
  2062   2455   static void
  2063   2456   spatialite_autocreate (sqlite3 * db)
  2064   2457   {
  2065   2458   /* attempting to perform self-initialization for a newly created DB */
  2066   2459       int ret;
................................................................................
  2086   2479         }
  2087   2480       sqlite3_free_table (results);
  2088   2481   
  2089   2482       if (count > 0)
  2090   2483   	return;
  2091   2484   
  2092   2485   /* all right, it's empty: proceding to initialize */
  2093         -    strcpy (sql, "SELECT InitSpatialMetadata(1)");
         2486  +    strcpy (sql, "SELECT InitSpatialMetadataFull(1)");
  2094   2487       ret = sqlite3_exec (db, sql, NULL, NULL, &err_msg);
  2095   2488       if (ret != SQLITE_OK)
  2096   2489         {
  2097         -	  fprintf (stderr, "InitSpatialMetadata() error: %s\n", err_msg);
         2490  +	  fprintf (stderr, "InitSpatialMetadataFull() error: %s\n", err_msg);
  2098   2491   	  sqlite3_free (err_msg);
  2099   2492   	  return;
  2100   2493         }
  2101   2494       spatial_ref_sys_init (db, 1);
  2102   2495   }
  2103   2496   
  2104   2497   /*
  2105   2498   ** Run zQuery.  Use dump_callback() as the callback routine so that
  2106   2499   ** the contents of the query are output as SQL statements.
  2107   2500   **
  2108   2501   ** If we get a SQLITE_CORRUPT error, rerun the query after appending
  2109   2502   ** "ORDER BY rowid DESC" to the end.
  2110   2503   */
  2111         -static int run_schema_dump_query(
  2112         -  struct callback_data *p, 
  2113         -  const char *zQuery
  2114         -){
  2115         -  int rc;
  2116         -  char *zErr = 0;
  2117         -  rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
  2118         -  if( rc==SQLITE_CORRUPT ){
  2119         -    char *zQ2;
  2120         -    int len = strlen30(zQuery);
  2121         -    fprintf(p->out, "/****** CORRUPTION ERROR *******/\n");
  2122         -    if( zErr ){
  2123         -      fprintf(p->out, "/****** %s ******/\n", zErr);
  2124         -      sqlite3_free(zErr);
  2125         -      zErr = 0;
  2126         -    }
  2127         -    zQ2 = malloc( len+100 );
  2128         -    if( zQ2==0 ) return rc;
  2129         -    sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
  2130         -    rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
  2131         -    if( rc ){
  2132         -      fprintf(p->out, "/****** ERROR: %s ******/\n", zErr);
  2133         -    }else{
  2134         -      rc = SQLITE_CORRUPT;
  2135         -    }
  2136         -    sqlite3_free(zErr);
  2137         -    free(zQ2);
  2138         -  }
  2139         -  return rc;
         2504  +static int
         2505  +run_schema_dump_query (struct callback_data *p, const char *zQuery)
         2506  +{
         2507  +    int rc;
         2508  +    char *zErr = 0;
         2509  +    rc = sqlite3_exec (p->db, zQuery, dump_callback, p, &zErr);
         2510  +    if (rc == SQLITE_CORRUPT)
         2511  +      {
         2512  +	  char *zQ2;
         2513  +	  int len = strlen30 (zQuery);
         2514  +	  fprintf (p->out, "/****** CORRUPTION ERROR *******/\n");
         2515  +	  if (zErr)
         2516  +	    {
         2517  +		fprintf (p->out, "/****** %s ******/\n", zErr);
         2518  +		sqlite3_free (zErr);
         2519  +		zErr = 0;
         2520  +	    }
         2521  +	  zQ2 = malloc (len + 100);
         2522  +	  if (zQ2 == 0)
         2523  +	      return rc;
         2524  +	  sqlite3_snprintf (len + 100, zQ2, "%s ORDER BY rowid DESC", zQuery);
         2525  +	  rc = sqlite3_exec (p->db, zQ2, dump_callback, p, &zErr);
         2526  +	  if (rc)
         2527  +	    {
         2528  +		fprintf (p->out, "/****** ERROR: %s ******/\n", zErr);
         2529  +	    }
         2530  +	  else
         2531  +	    {
         2532  +		rc = SQLITE_CORRUPT;
         2533  +	    }
         2534  +	  sqlite3_free (zErr);
         2535  +	  free (zQ2);
         2536  +      }
         2537  +    return rc;
  2140   2538   }
  2141   2539   
  2142   2540   /*
  2143   2541   ** Text of a help message
  2144   2542   */
  2145   2543   static char zHelp[] =
  2146         -  ".backup ?DB? FILE      Backup DB (default \"main\") to FILE\n"
  2147         -  ".bail ON|OFF           Stop after hitting an error.  Default OFF\n"
  2148         -  ".databases             List names and files of attached databases\n"
  2149         -  ".dump ?TABLE? ...      Dump the database in an SQL text format\n"
  2150         -  "                         If TABLE specified, only dump tables matching\n"
  2151         -  "                         LIKE pattern TABLE.\n"
  2152         -  ".echo ON|OFF           Turn command echo on or off\n"
  2153         -  ".exit                  Exit this program\n"
  2154         -  ".explain ?ON|OFF?      Turn output mode suitable for EXPLAIN on or off.\n"
  2155         -  "                         With no args, it turns EXPLAIN on.\n"
  2156         -  ".header(s) ON|OFF      Turn display of headers on or off\n"
  2157         -  ".help                  Show this message\n"
  2158         -  ".import FILE TABLE     Import data from FILE into TABLE\n"
  2159         -  ".indices ?TABLE?       Show names of all indices\n"
  2160         -  "                         If TABLE specified, only show indices for tables\n"
  2161         -  "                         matching LIKE pattern TABLE.\n"
         2544  +    ".backup ?DB? FILE      Backup DB (default \"main\") to FILE\n"
         2545  +    ".bail ON|OFF           Stop after hitting an error.  Default OFF\n"
         2546  +    ".databases             List names and files of attached databases\n"
         2547  +    ".dump ?TABLE? ...      Dump the database in an SQL text format\n"
         2548  +    "                         If TABLE specified, only dump tables matching\n"
         2549  +    "                         LIKE pattern TABLE.\n"
         2550  +    ".echo ON|OFF           Turn command echo on or off\n"
         2551  +    ".exit                  Exit this program\n"
         2552  +    ".explain ?ON|OFF?      Turn output mode suitable for EXPLAIN on or off.\n"
         2553  +    "                         With no args, it turns EXPLAIN on.\n"
         2554  +    ".header(s) ON|OFF      Turn display of headers on or off\n"
         2555  +    ".help                  Show this message\n"
         2556  +    ".import FILE TABLE     Import data from FILE into TABLE\n"
         2557  +    ".indices ?TABLE?       Show names of all indices\n"
         2558  +    "                         If TABLE specified, only show indices for tables\n"
         2559  +    "                         matching LIKE pattern TABLE.\n"
  2162   2560   #ifdef SQLITE_ENABLE_IOTRACE
  2163         -  ".iotrace FILE          Enable I/O diagnostic logging to FILE\n"
         2561  +    ".iotrace FILE          Enable I/O diagnostic logging to FILE\n"
  2164   2562   #endif
  2165   2563   #ifndef SQLITE_OMIT_LOAD_EXTENSION
  2166         -  ".load FILE ?ENTRY?     Load an extension library\n"
  2167         -#endif
  2168         -  ".log FILE|off          Turn logging on or off.  FILE can be stderr/stdout\n"
  2169         -  ".mode MODE ?TABLE?     Set output mode where MODE is one of:\n"
  2170         -  "                         csv      Comma-separated values\n"
  2171         -  "                         column   Left-aligned columns.  (See .width)\n"
  2172         -  "                         html     HTML <table> code\n"
  2173         -  "                         insert   SQL insert statements for TABLE\n"
  2174         -  "                         line     One value per line\n"
  2175         -  "                         list     Values delimited by .separator string\n"
  2176         -  "                         tabs     Tab-separated values\n"
  2177         -  "                         tcl      TCL list elements\n"
  2178         -  ".nullvalue STRING      Print STRING in place of NULL values\n"
  2179         -  ".output FILENAME       Send output to FILENAME\n"
  2180         -  ".output stdout         Send output to the screen\n"
  2181         -  ".prompt MAIN CONTINUE  Replace the standard prompts\n"
  2182         -  ".quit                  Exit this program\n"
  2183         -  ".read FILENAME         Execute SQL in FILENAME\n"
  2184         -  ".restore ?DB? FILE     Restore content of DB (default \"main\") from FILE\n"
  2185         -  ".schema ?TABLE?        Show the CREATE statements\n"
  2186         -  "                         If TABLE specified, only show tables matching\n"
  2187         -  "                         LIKE pattern TABLE.\n"
  2188         -  ".separator STRING      Change separator used by output mode and .import\n"
  2189         -  ".shell CMD ARGS...     Run CMD ARGS... in a system shell\n"
  2190         -  ".show                  Show the current values for various settings\n"
  2191         -  ".stats ON|OFF          Turn stats on or off\n"
  2192         -  ".system CMD ARGS...    Run CMD ARGS... in a system shell\n"
  2193         -  ".tables ?TABLE?        List names of tables\n"
  2194         -  "                         If TABLE specified, only list tables matching\n"
  2195         -  "                         LIKE pattern TABLE.\n"
  2196         -  ".timeout MS            Try opening locked tables for MS milliseconds\n"
  2197         -  ".trace FILE|off        Output each SQL statement as it is run\n"
  2198         -  ".vfsname ?AUX?         Print the name of the VFS stack\n"
  2199         -  ".width NUM1 NUM2 ...   Set column widths for \"column\" mode\n"
  2200         -;
         2564  +    ".load FILE ?ENTRY?     Load an extension library\n"
         2565  +#endif
         2566  +    ".log FILE|off          Turn logging on or off.  FILE can be stderr/stdout\n"
         2567  +    ".mode MODE ?TABLE?     Set output mode where MODE is one of:\n"
         2568  +    "                         csv      Comma-separated values\n"
         2569  +    "                         column   Left-aligned columns.  (See .width)\n"
         2570  +    "                         html     HTML <table> code\n"
         2571  +    "                         insert   SQL insert statements for TABLE\n"
         2572  +    "                         line     One value per line\n"
         2573  +    "                         list     Values delimited by .separator string\n"
         2574  +    "                         tabs     Tab-separated values\n"
         2575  +    "                         tcl      TCL list elements\n"
         2576  +    ".nullvalue STRING      Print STRING in place of NULL values\n"
         2577  +    ".output FILENAME       Send output to FILENAME\n"
         2578  +    ".output stdout         Send output to the screen\n"
         2579  +    ".prompt MAIN CONTINUE  Replace the standard prompts\n"
         2580  +    ".quit                  Exit this program\n"
         2581  +    ".read FILENAME         Execute SQL in FILENAME\n"
         2582  +    ".restore ?DB? FILE     Restore content of DB (default \"main\") from FILE\n"
         2583  +    ".schema ?TABLE?        Show the CREATE statements\n"
         2584  +    "                         If TABLE specified, only show tables matching\n"
         2585  +    "                         LIKE pattern TABLE.\n"
         2586  +    ".separator STRING      Change separator used by output mode and .import\n"
         2587  +    ".shell CMD ARGS...     Run CMD ARGS... in a system shell\n"
         2588  +    ".show                  Show the current values for various settings\n"
         2589  +    ".stats ON|OFF          Turn stats on or off\n"
         2590  +    ".system CMD ARGS...    Run CMD ARGS... in a system shell\n"
         2591  +    ".tables ?TABLE?        List names of tables\n"
         2592  +    "                         If TABLE specified, only list tables matching\n"
         2593  +    "                         LIKE pattern TABLE.\n"
         2594  +    ".timeout MS            Try opening locked tables for MS milliseconds\n"
         2595  +    ".trace FILE|off        Output each SQL statement as it is run\n"
         2596  +    ".vfsname ?AUX?         Print the name of the VFS stack\n"
         2597  +    ".width NUM1 NUM2 ...   Set column widths for \"column\" mode\n";
  2201   2598   
  2202   2599   static char zTimerHelp[] =
  2203         -  ".timer ON|OFF          Turn the CPU timer measurement on or off\n"
         2600  +    ".timer ON|OFF          Turn the CPU timer measurement on or off\n"
  2204   2601   /* Sandro Furieri 2008-06-20 */
  2205   2602       "\n====================== SpatiaLite ========================================\n\n"
  2206   2603       ".charset          Report the current locale charset setting\n\n"
  2207   2604       ".charset <charset-name>\n"
  2208   2605       "                  Set the charset encoding according to the command shell\n"
  2209   2606       "                  e.g.: when working on Windows Command Prompt, if you notice\n"
  2210   2607       "                        'strange' chars, a very good idea may be to type\n"
................................................................................
  2216   2613       ".remdupl <table>  Removes any duplicated row from a TABLE\n\n"
  2217   2614       ".elemgeo <args>   derives a new table from the original one, so to ensure that\n"
  2218   2615       "                  only elementary Geometries (one for each row) will be present\n"
  2219   2616       "                  arg_list: in_tbl geom out_tbl out_pk out_old_id\n\n"
  2220   2617       ".loadshp <args>   Loads a SHAPEFILE into a SpatiaLite table\n"
  2221   2618       "                  arg_list: shp_path table_name charset [SRID] [column_name]\n"
  2222   2619       "                      [pk_column] [geom_type] [2d | 3d] [compressed]\n"
  2223         -    "                      [with_spatial_index] [text_dates]\n"
         2620  +    "                      [with_spatial_index] [text_dates] [colname_case]\n"
  2224   2621       "                      geom_type={ AUTO | LINESTRING[ Z | M | ZM ]\n"
  2225   2622       "                                 | MULTILINESTRING[ Z | M | ZM ]\n"
  2226   2623       "                                 | POLYGON[ Z | M | ZM ]\n"
  2227   2624       "                                 | MULTIPOLYGON[ Z | M | ZM ] }\n\n"
  2228   2625       ".dumpshp <args>   Dumps a SpatiaLite table into a SHAPEFILE\n"
  2229   2626       "                  arg_list: table_name column_name shp_path charset [geom_type]\n"
         2627  +    "                      [colname_case]\n"
  2230   2628       "                      geom_type={ POINT | LINESTRING | POLYGON | MULTIPOINT }\n\n"
  2231   2629       ".loaddbf <args>   Loads a DBF into a SpatiaLite table\n"
  2232         -    "                  arg_list: dbf_path table_name charset [pk_column] [text_dates]\n\n"
         2630  +    "                  arg_list: dbf_path table_name charset [pk_column]\n"
         2631  +    "                      [text_dates] [colname_case]\n\n"
  2233   2632       ".dumpdbf <args>   Dumps a SpatiaLite table into a DBF\n"
  2234         -    "                  arg_list: table_name dbf_path charset\n\n"
         2633  +    "                  arg_list: table_name dbf_path charset [colname_case]\n\n"
  2235   2634   #ifndef OMIT_FREEXL		/* FreeXL is enabled */
  2236   2635       ".loadxl <args>    Loads a XL spreadsheet (.xls) into a SpatiaLite table\n"
  2237   2636       "                  arg_list: xl_path table_name \n"
  2238   2637       "                      [worksheet_index [first_line_titles{0/1}]]\n\n"
  2239   2638   #endif /* end FreeXL support */
  2240   2639       ".dumpkml <args>   Dumps a SpatiaLite table as a KML file\n"
  2241   2640       "                  arg_list: table_name geom_column kml_path\n"
................................................................................
  2262   2661       "                      [swap] [page_size] [with_spatial_index]\n\n"
  2263   2662       ".loaddxf <args>   Loads data from some DXF source into SpatiaLite tables\n"
  2264   2663       "                  arg_list: DXF_path [srid] [append] [dims] [mode]\n"
  2265   2664       "                      [rings] [table_prefix] [layer_name]\n"
  2266   2665       "                  append={Y|N} dims={AUTO|2D|3D} mode={DISTINCT|MIXED}\n"
  2267   2666       "                  rings={NONE|LINKED|UNLINKED}\n\n"
  2268   2667   /* end Sandro Furieri 2008-06-20 */
  2269         -;
         2668  +    ;
  2270   2669   
  2271   2670   /* Forward reference */
  2272         -static int process_input(struct callback_data *p, FILE *in, char *in_charset);
         2671  +static int process_input (struct callback_data *p, FILE * in, char *in_charset);
  2273   2672   
  2274   2673   /*
  2275   2674   ** Make sure the database is open.  If it is not, then open it.  If
  2276   2675   ** the database fails to open, print an error message and exit.
  2277   2676   */
  2278         -static void open_db(struct callback_data *p){
  2279         -  if( p->db==0 ){
  2280         -    sqlite3_initialize();
  2281         -    sqlite3_open(p->zDbFilename, &p->db);
  2282         -    db = p->db;
  2283         -    if( db && sqlite3_errcode(db)==SQLITE_OK ){
  2284         -      sqlite3_create_function(db, "shellstatic", 0, SQLITE_UTF8, 0,
  2285         -          shellstaticFunc, 0, 0);
  2286         -    }
  2287         -    if( db==0 || SQLITE_OK!=sqlite3_errcode(db) ){
  2288         -      fprintf(stderr,"Error: unable to open database \"%s\": %s\n", 
  2289         -          p->zDbFilename, sqlite3_errmsg(db));
  2290         -      exit(1);
  2291         -    }
  2292         -    spatialite_init_ex (p->db, splite_cache, (splite_silent == 0) ? 1 : 0);
         2677  +static void
         2678  +open_db (struct callback_data *p)
         2679  +{
         2680  +    if (p->db == 0)
         2681  +      {
         2682  +	  sqlite3_initialize ();
         2683  +	  sqlite3_open (p->zDbFilename, &p->db);
         2684  +	  db = p->db;
         2685  +	  if (db && sqlite3_errcode (db) == SQLITE_OK)
         2686  +	    {
         2687  +		sqlite3_create_function (db, "shellstatic", 0, SQLITE_UTF8, 0,
         2688  +					 shellstaticFunc, 0, 0);
         2689  +	    }
         2690  +	  if (db == 0 || SQLITE_OK != sqlite3_errcode (db))
         2691  +	    {
         2692  +		fprintf (stderr, "Error: unable to open database \"%s\": %s\n",
         2693  +			 p->zDbFilename, sqlite3_errmsg (db));
         2694  +		exit (1);
         2695  +	    }
         2696  +	  spatialite_init_ex (p->db, splite_cache,
         2697  +			      (splite_silent == 0) ? 1 : 0);
  2293   2698   #ifndef SQLITE_OMIT_LOAD_EXTENSION
  2294         -    sqlite3_enable_load_extension(p->db, 1);
         2699  +	  sqlite3_enable_load_extension (p->db, 1);
  2295   2700   #endif
  2296   2701   
  2297   2702   /* Sandro Furieri 2009-11-08 */
  2298   2703   	  sqlite3_exec (p->db, "PRAGMA foreign_keys = 1", NULL, 0, NULL);
  2299   2704   /* end Sandro Furieri 2008-11-08 */
  2300   2705   /* Sandro Furieri 2010-08-07 */
  2301   2706   	  spatialite_autocreate (p->db);
  2302   2707   /* end Sandro Furieri 2010-08-07 */
  2303         -  }
         2708  +      }
  2304   2709   }
  2305   2710   
  2306   2711   /*
  2307   2712   ** Do C-language style dequoting.
  2308   2713   **
  2309   2714   **    \t    -> tab
  2310   2715   **    \n    -> newline
  2311   2716   **    \r    -> carriage return
  2312   2717   **    \NNN  -> ascii character NNN in octal
  2313   2718   **    \\    -> backslash
  2314   2719   */
  2315         -static void resolve_backslashes(char *z){
  2316         -  int i, j;
  2317         -  char c;
  2318         -  for(i=j=0; (c = z[i])!=0; i++, j++){
  2319         -    if( c=='\\' ){
  2320         -      c = z[++i];
  2321         -      if( c=='n' ){
  2322         -        c = '\n';
  2323         -      }else if( c=='t' ){
  2324         -        c = '\t';
  2325         -      }else if( c=='r' ){
  2326         -        c = '\r';
  2327         -      }else if( c>='0' && c<='7' ){
  2328         -        c -= '0';
  2329         -        if( z[i+1]>='0' && z[i+1]<='7' ){
  2330         -          i++;
  2331         -          c = (c<<3) + z[i] - '0';
  2332         -          if( z[i+1]>='0' && z[i+1]<='7' ){
  2333         -            i++;
  2334         -            c = (c<<3) + z[i] - '0';
  2335         -          }
  2336         -        }
  2337         -      }
  2338         -    }
  2339         -    z[j] = c;
  2340         -  }
  2341         -  z[j] = 0;
         2720  +static void
         2721  +resolve_backslashes (char *z)
         2722  +{
         2723  +    int i, j;
         2724  +    char c;
         2725  +    for (i = j = 0; (c = z[i]) != 0; i++, j++)
         2726  +      {
         2727  +	  if (c == '\\')
         2728  +	    {
         2729  +		c = z[++i];
         2730  +		if (c == 'n')
         2731  +		  {
         2732  +		      c = '\n';
         2733  +		  }
         2734  +		else if (c == 't')
         2735  +		  {
         2736  +		      c = '\t';
         2737  +		  }
         2738  +		else if (c == 'r')
         2739  +		  {
         2740  +		      c = '\r';
         2741  +		  }
         2742  +		else if (c >= '0' && c <= '7')
         2743  +		  {
         2744  +		      c -= '0';
         2745  +		      if (z[i + 1] >= '0' && z[i + 1] <= '7')
         2746  +			{
         2747  +			    i++;
         2748  +			    c = (c << 3) + z[i] - '0';
         2749  +			    if (z[i + 1] >= '0' && z[i + 1] <= '7')
         2750  +			      {
         2751  +				  i++;
         2752  +				  c = (c << 3) + z[i] - '0';
         2753  +			      }
         2754  +			}
         2755  +		  }
         2756  +	    }
         2757  +	  z[j] = c;
         2758  +      }
         2759  +    z[j] = 0;
  2342   2760   }
  2343   2761   
  2344   2762   /*
  2345   2763   ** Interpret zArg as a boolean value.  Return either 0 or 1.
  2346   2764   */
  2347         -static int booleanValue(char *zArg){
  2348         -  int val = atoi(zArg);
  2349         -  int j;
  2350         -  for(j=0; zArg[j]; j++){
  2351         -    zArg[j] = ToLower(zArg[j]);
  2352         -  }
  2353         -  if( strcmp(zArg,"on")==0 ){
  2354         -    val = 1;
  2355         -  }else if( strcmp(zArg,"yes")==0 ){
  2356         -    val = 1;
  2357         -  }
  2358         -  return val;
         2765  +static int
         2766  +booleanValue (char *zArg)
         2767  +{
         2768  +    int val = atoi (zArg);
         2769  +    int j;
         2770  +    for (j = 0; zArg[j]; j++)
         2771  +      {
         2772  +	  zArg[j] = ToLower (zArg[j]);
         2773  +      }
         2774  +    if (strcmp (zArg, "on") == 0)
         2775  +      {
         2776  +	  val = 1;
         2777  +      }
         2778  +    else if (strcmp (zArg, "yes") == 0)
         2779  +      {
         2780  +	  val = 1;
         2781  +      }
         2782  +    return val;
  2359   2783   }
  2360   2784   
  2361   2785   /*
  2362   2786   ** Close an output file, assuming it is not stderr or stdout
  2363   2787   */
  2364         -static void output_file_close(FILE *f){
  2365         -  if( f && f!=stdout && f!=stderr ) fclose(f);
         2788  +static void
         2789  +output_file_close (FILE * f)
         2790  +{
         2791  +    if (f && f != stdout && f != stderr)
         2792  +	fclose (f);
  2366   2793   }
  2367   2794   
  2368   2795   /*
  2369   2796   ** Try to open an output file.   The names "stdout" and "stderr" are
  2370   2797   ** recognized and do the right thing.  NULL is returned if the output 
  2371   2798   ** filename is "off".
  2372   2799   */
  2373         -static FILE *output_file_open(const char *zFile){
  2374         -  FILE *f;
  2375         -  if( strcmp(zFile,"stdout")==0 ){
  2376         -    f = stdout;
  2377         -  }else if( strcmp(zFile, "stderr")==0 ){
  2378         -    f = stderr;
  2379         -  }else if( strcmp(zFile, "off")==0 ){
  2380         -    f = 0;
  2381         -  }else{
  2382         -    f = fopen(zFile, "wb");
  2383         -    if( f==0 ){
  2384         -      fprintf(stderr, "Error: cannot open \"%s\"\n", zFile);
  2385         -    }
  2386         -  }
  2387         -  return f;
         2800  +static FILE *
         2801  +output_file_open (const char *zFile)
         2802  +{
         2803  +    FILE *f;
         2804  +    if (strcmp (zFile, "stdout") == 0)
         2805  +      {
         2806  +	  f = stdout;
         2807  +      }
         2808  +    else if (strcmp (zFile, "stderr") == 0)
         2809  +      {
         2810  +	  f = stderr;
         2811  +      }
         2812  +    else if (strcmp (zFile, "off") == 0)
         2813  +      {
         2814  +	  f = 0;
         2815  +      }
         2816  +    else
         2817  +      {
         2818  +	  f = fopen (zFile, "wb");
         2819  +	  if (f == 0)
         2820  +	    {
         2821  +		fprintf (stderr, "Error: cannot open \"%s\"\n", zFile);
         2822  +	    }
         2823  +      }
         2824  +    return f;
  2388   2825   }
  2389   2826   
  2390   2827   /*
  2391   2828   ** A routine for handling output from sqlite3_trace().
  2392   2829   */
  2393         -static void sql_trace_callback(void *pArg, const char *z){
  2394         -  FILE *f = (FILE*)pArg;
  2395         -  if( f ) fprintf(f, "%s\n", z);
         2830  +static void
         2831  +sql_trace_callback (void *pArg, const char *z)
         2832  +{
         2833  +    FILE *f = (FILE *) pArg;
         2834  +    if (f)
         2835  +	fprintf (f, "%s\n", z);
  2396   2836   }
  2397   2837   
  2398   2838   /*
  2399   2839   ** A no-op routine that runs with the ".breakpoint" doc-command.  This is
  2400   2840   ** a useful spot to set a debugger breakpoint.
  2401   2841   */
  2402         -static void test_breakpoint(void){
  2403         -  static int nCall = 0;
  2404         -  nCall++;
         2842  +static void
         2843  +test_breakpoint (void)
         2844  +{
         2845  +    static int nCall = 0;
         2846  +    nCall++;
  2405   2847   }
  2406   2848   
  2407   2849   /*
  2408   2850   ** If an input line begins with "." then invoke this routine to
  2409   2851   ** process that line.
  2410   2852   **
  2411   2853   ** Return 1 on error, 2 to exit, and 0 otherwise.
  2412   2854   */
  2413         -static int do_meta_command(char *zLine, struct callback_data *p){
  2414         -  int i = 1;
  2415         -  int nArg = 0;
  2416         -  int n, c;
  2417         -  int rc = 0;
  2418         -  char *azArg[50];
  2419         -
  2420         -  /* Parse the input line into tokens.
  2421         -  */
  2422         -  while( zLine[i] && nArg<ArraySize(azArg) ){
  2423         -    while( IsSpace(zLine[i]) ){ i++; }
  2424         -    if( zLine[i]==0 ) break;
  2425         -    if( zLine[i]=='\'' || zLine[i]=='"' ){
  2426         -      int delim = zLine[i++];
  2427         -      azArg[nArg++] = &zLine[i];
  2428         -      while( zLine[i] && zLine[i]!=delim ){ i++; }
  2429         -      if( zLine[i]==delim ){
  2430         -        zLine[i++] = 0;
  2431         -      }
  2432         -      if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
  2433         -    }else{
  2434         -      azArg[nArg++] = &zLine[i];
  2435         -      while( zLine[i] && !IsSpace(zLine[i]) ){ i++; }
  2436         -      if( zLine[i] ) zLine[i++] = 0;
  2437         -      resolve_backslashes(azArg[nArg-1]);
  2438         -    }
  2439         -  }
  2440         -
  2441         -  /* Process the input line.
  2442         -  */
  2443         -  if( nArg==0 ) return 0; /* no tokens, no error */
  2444         -  n = strlen30(azArg[0]);
  2445         -  c = azArg[0][0];
         2855  +static int
         2856  +do_meta_command (char *zLine, struct callback_data *p)
         2857  +{
         2858  +    int i = 1;
         2859  +    int nArg = 0;
         2860  +    int n, c;
         2861  +    int rc = 0;
         2862  +    char *azArg[50];
         2863  +
         2864  +    /* Parse the input line into tokens.
         2865  +     */
         2866  +    while (zLine[i] && nArg < ArraySize (azArg))
         2867  +      {
         2868  +	  while (IsSpace (zLine[i]))
         2869  +	    {
         2870  +		i++;
         2871  +	    }
         2872  +	  if (zLine[i] == 0)
         2873  +	      break;
         2874  +	  if (zLine[i] == '\'' || zLine[i] == '"')
         2875  +	    {
         2876  +		int delim = zLine[i++];
         2877  +		azArg[nArg++] = &zLine[i];
         2878  +		while (zLine[i] && zLine[i] != delim)
         2879  +		  {
         2880  +		      i++;
         2881  +		  }
         2882  +		if (zLine[i] == delim)
         2883  +		  {
         2884  +		      zLine[i++] = 0;
         2885  +		  }
         2886  +		if (delim == '"')
         2887  +		    resolve_backslashes (azArg[nArg - 1]);
         2888  +	    }
         2889  +	  else
         2890  +	    {
         2891  +		azArg[nArg++] = &zLine[i];
         2892  +		while (zLine[i] && !IsSpace (zLine[i]))
         2893  +		  {
         2894  +		      i++;
         2895  +		  }
         2896  +		if (zLine[i])
         2897  +		    zLine[i++] = 0;
         2898  +		resolve_backslashes (azArg[nArg - 1]);
         2899  +	    }
         2900  +      }
         2901  +
         2902  +    /* Process the input line.
         2903  +     */
         2904  +    if (nArg == 0)
         2905  +	return 0;		/* no tokens, no error */
         2906  +    n = strlen30 (azArg[0]);
         2907  +    c = azArg[0][0];
  2446   2908   
  2447   2909   #ifndef SQLITE_OMIT_LOAD_EXTENSION
  2448         -  if( c=='l' && strncmp(azArg[0], "load", n)==0 && nArg>=2 ){
  2449         -    const char *zFile, *zProc;
  2450         -    char *zErrMsg = 0;
  2451         -    zFile = azArg[1];
  2452         -    zProc = nArg>=3 ? azArg[2] : 0;
  2453         -    open_db(p);
  2454         -    rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
  2455         -    if( rc!=SQLITE_OK ){
  2456         -      fprintf(stderr, "Error: %s\n", zErrMsg);
  2457         -      sqlite3_free(zErrMsg);
  2458         -      rc = 1;
  2459         -    }
  2460         -  }else
         2910  +    if (c == 'l' && strncmp (azArg[0], "load", n) == 0 && nArg >= 2)
         2911  +      {
         2912  +	  const char *zFile, *zProc;
         2913  +	  char *zErrMsg = 0;
         2914  +	  zFile = azArg[1];
         2915  +	  zProc = nArg >= 3 ? azArg[2] : 0;
         2916  +	  open_db (p);
         2917  +	  rc = sqlite3_load_extension (p->db, zFile, zProc, &zErrMsg);
         2918  +	  if (rc != SQLITE_OK)
         2919  +	    {
         2920  +		fprintf (stderr, "Error: %s\n", zErrMsg);
         2921  +		sqlite3_free (zErrMsg);
         2922  +		rc = 1;
         2923  +	    }
         2924  +      }
         2925  +    else
  2461   2926   #endif
  2462   2927   
  2463   2928   /* Sandro Furieri 2008-06-20 */
  2464         -    if (c == 'c' && n > 1 && strncmp (azArg[0], "charset", n) == 0 && nArg == 1)
         2929  +    if (c == 'c' && n > 1 && strncmp (azArg[0], "charset", n) == 0
         2930  +	    && nArg == 1)
  2465   2931         {
  2466   2932   	  /* reporting the charset */
  2467   2933   	  if (*spatialite_charset == '\0')
  2468   2934   	    {
  2469   2935   		printf
  2470   2936   		    ("the shell's default LOCALE CHARSET is currently in use\n");
  2471   2937   		fflush (stdout);
................................................................................
  2480   2946       else if (c == 'c' && n > 1 && strncmp (azArg[0], "charset", n) == 0
  2481   2947   	     && nArg == 2)
  2482   2948         {
  2483   2949   	  /* setting the charset */
  2484   2950   	  create_utf8_converter (azArg[1]);
  2485   2951         }
  2486   2952       else if (c == 'd' && n > 1 && strncmp (azArg[0], "dumpshp", n) == 0
  2487         -	     && (nArg == 5 || nArg == 6))
         2953  +	     && (nArg == 5 || nArg == 6 || nArg == 7))
  2488   2954         {
  2489   2955   	  /* dumping a spatial table to SHAPEFILE */
  2490   2956   	  char *table = azArg[1];
  2491   2957   	  char *column = azArg[2];
  2492   2958   	  char *shp_path = azArg[3];
  2493   2959   	  char *outCS = azArg[4];
  2494   2960   	  char *type = NULL;
  2495   2961   	  int rows;
  2496         -	  if (nArg == 6)
         2962  +	  int colname_case = GAIA_DBF_COLNAME_CASE_IGNORE;
         2963  +	  if (nArg >= 6)
  2497   2964   	      type = azArg[5];
         2965  +	  if (nArg >= 7)
         2966  +	    {
         2967  +		const char *pColnameCase = azArg[6];
         2968  +		if (strcasecmp (pColnameCase, "UPPER") == 0
         2969  +		    || strcasecmp (pColnameCase, "UPPERCASE") == 0)
         2970  +		    colname_case = GAIA_DBF_COLNAME_UPPERCASE;
         2971  +		else if (strcasecmp (pColnameCase, "LOWER") == 0
         2972  +			 || strcasecmp (pColnameCase, "LOWERCASE") == 0)
         2973  +		    colname_case = GAIA_DBF_COLNAME_LOWERCASE;
         2974  +		else
         2975  +		    colname_case = GAIA_DBF_COLNAME_CASE_IGNORE;
         2976  +	    }
  2498   2977   	  open_db (p);
  2499         -	  dump_shapefile (p->db, table, column, shp_path, outCS, type, 1, &rows,
  2500         -			  NULL);
         2978  +	  dump_shapefile_ex (p->db, table, column, shp_path, outCS, type, 1,
         2979  +			     &rows, colname_case, NULL);
  2501   2980         }
  2502   2981       else if (c == 'd' && n > 1 && strncmp (azArg[0], "dumpdbf", n) == 0
  2503         -	     && (nArg == 4))
         2982  +	     && (nArg == 4 || nArg == 5))
  2504   2983         {
  2505   2984   	  /* dumping a spatial table to DBF */
  2506   2985   	  char *table = azArg[1];
  2507   2986   	  char *dbf_path = azArg[2];
  2508   2987   	  char *outCS = azArg[3];
         2988  +	  int rows;
         2989  +	  int colname_case = GAIA_DBF_COLNAME_CASE_IGNORE;
         2990  +	  if (nArg >= 5)
         2991  +	    {
         2992  +		const char *pColnameCase = azArg[4];
         2993  +		if (strcasecmp (pColnameCase, "UPPER") == 0
         2994  +		    || strcasecmp (pColnameCase, "UPPERCASE") == 0)
         2995  +		    colname_case = GAIA_DBF_COLNAME_UPPERCASE;
         2996  +		else if (strcasecmp (pColnameCase, "LOWER") == 0
         2997  +			 || strcasecmp (pColnameCase, "LOWERCASE") == 0)
         2998  +		    colname_case = GAIA_DBF_COLNAME_LOWERCASE;
         2999  +		else
         3000  +		    colname_case = GAIA_DBF_COLNAME_CASE_IGNORE;
         3001  +	    }
  2509   3002   	  open_db (p);
  2510         -	  dump_dbf (p->db, table, dbf_path, outCS, NULL);
         3003  +	  dump_dbf_ex2 (p->db, table, dbf_path, outCS, &rows, colname_case,
         3004  +			NULL);
  2511   3005         }
  2512   3006       else if (c == 'd' && n > 1 && strncmp (azArg[0], "dumpkml", n) == 0
  2513   3007   	     && (nArg == 4 || nArg == 5 || nArg == 6 || nArg == 7))
  2514   3008         {
  2515   3009   	  /* dumping a spatial table as KML file */
  2516   3010   	  char *table = azArg[1];
  2517   3011   	  char *geom = azArg[2];
................................................................................
  2558   3052   	  if (nArg == 6)
  2559   3053   	      precision = atoi (azArg[5]);
  2560   3054   	  open_db (p);
  2561   3055   	  dump_geojson (p->db, table, geom, gml_path, precision, format);
  2562   3056         }
  2563   3057       else if (c == 'l' && n > 1 && strncmp (azArg[0], "loadshp", n) == 0
  2564   3058   	     && (nArg == 4 || nArg == 5 || nArg == 6 || nArg == 7 ||
  2565         -		 nArg == 8 || nArg == 9 || nArg == 10 || nArg == 11 || nArg == 12))
         3059  +		 nArg == 8 || nArg == 9 || nArg == 10 || nArg == 11
         3060  +		 || nArg == 12 || nArg == 13))
  2566   3061         {
  2567   3062   	  char *shp_path = azArg[1];
  2568   3063   	  char *table = azArg[2];
  2569   3064   	  char *inCS = azArg[3];
  2570   3065   	  int srid = -1;
  2571   3066   	  int coerce2d = 0;
  2572   3067   	  int compressed = 0;
  2573   3068   	  int with_spatial_index = 0;
  2574   3069   	  int text_dates = 0;
         3070  +	  int colname_case = GAIA_DBF_COLNAME_LOWERCASE;
  2575   3071   	  char *column = NULL;
  2576   3072   	  char *gtype = NULL;
  2577         -          char *pk = NULL;
         3073  +	  char *pk = NULL;
  2578   3074   	  int rows;
  2579   3075   	  if (nArg >= 5)
  2580   3076   	      srid = atoi (azArg[4]);
  2581   3077   	  if (nArg >= 6)
  2582   3078   	      column = azArg[5];
  2583   3079   	  if (nArg >= 7)
  2584   3080   	      pk = azArg[6];
................................................................................
  2586   3082   	      gtype = azArg[7];
  2587   3083   	  if (nArg >= 9)
  2588   3084   	    {
  2589   3085   		if (strcasecmp (azArg[8], "2d") == 0)
  2590   3086   		    coerce2d = 1;
  2591   3087   	    }
  2592   3088   	  if (nArg >= 10)
  2593         -	  {
         3089  +	    {
  2594   3090   		if (strcasecmp (azArg[9], "compressed") == 0)
  2595   3091   		    compressed = 1;
  2596         -	  }
  2597         -	  if (nArg == 11)
  2598         -	      with_spatial_index = 1;
  2599         -	  if (nArg == 12)
  2600         -	      text_dates = atoi(azArg[11]);
  2601         -	  open_db (p);
  2602         -	  load_shapefile_ex2 (p->db, shp_path, table, inCS, srid, column, gtype, pk,
  2603         -			     coerce2d, compressed, 1, with_spatial_index, text_dates,
  2604         -			     &rows, NULL);
         3092  +		if (strcasecmp (azArg[9], "yes") == 0)
         3093  +		    compressed = 1;
         3094  +		if (strcasecmp (azArg[9], "true") == 0)
         3095  +		    compressed = 1;
         3096  +		if (strcasecmp (azArg[9], "1") == 0)
         3097  +		    compressed = 1;
         3098  +	    }
         3099  +	  if (nArg >= 11)
         3100  +	    {
         3101  +		if (strcasecmp (azArg[10], "with_spatial_index") == 0)
         3102  +		    with_spatial_index = 1;
         3103  +		if (strcasecmp (azArg[10], "yes") == 0)
         3104  +		    with_spatial_index = 1;
         3105  +		if (strcasecmp (azArg[10], "true") == 0)
         3106  +		    with_spatial_index = 1;
         3107  +		if (strcasecmp (azArg[10], "1") == 0)
         3108  +		    with_spatial_index = 1;
         3109  +	    }
         3110  +	  if (nArg >= 12)
         3111  +	    {
         3112  +		if (strcasecmp (azArg[11], "text_dates") == 0)
         3113  +		    text_dates = 1;
         3114  +		if (strcasecmp (azArg[11], "yes") == 0)
         3115  +		    text_dates = 1;
         3116  +		if (strcasecmp (azArg[11], "true") == 0)
         3117  +		    text_dates = 1;
         3118  +		if (strcasecmp (azArg[11], "1") == 0)
         3119  +		    text_dates = 1;
         3120  +	    }
         3121  +	  if (nArg >= 13)
         3122  +	    {
         3123  +		const char *pColnameCase = azArg[12];
         3124  +		if (strcasecmp (pColnameCase, "UPPER") == 0
         3125  +		    || strcasecmp (pColnameCase, "UPPERCASE") == 0)
         3126  +		    colname_case = GAIA_DBF_COLNAME_UPPERCASE;
         3127  +		else if (strcasecmp (pColnameCase, "SAME") == 0
         3128  +			 || strcasecmp (pColnameCase, "SAMECASE") == 0)
         3129  +		    colname_case = GAIA_DBF_COLNAME_CASE_IGNORE;
         3130  +		else
         3131  +		    colname_case = GAIA_DBF_COLNAME_LOWERCASE;
         3132  +	    }
         3133  +	  open_db (p);
         3134  +	  load_shapefile_ex3 (p->db, shp_path, table, inCS, srid, column, gtype,
         3135  +			      pk, coerce2d, compressed, 1, with_spatial_index,
         3136  +			      text_dates, &rows, colname_case, NULL);
  2605   3137         }
  2606   3138       else if (c == 'l' && n > 1 && strncmp (azArg[0], "loaddbf", n) == 0
  2607         -	     && (nArg == 4 || nArg == 5 || nArg == 6))
         3139  +	     && (nArg == 4 || nArg == 5 || nArg == 6 || nArg == 7))
  2608   3140         {
  2609   3141   	  char *dbf_path = azArg[1];
  2610   3142   	  char *table = azArg[2];
  2611   3143   	  char *inCS = azArg[3];
  2612         -      char *pk = NULL;
  2613         -      int text_dates = 0;
         3144  +	  char *pk = NULL;
         3145  +	  int text_dates = 0;
         3146  +	  int colname_case = GAIA_DBF_COLNAME_LOWERCASE;
  2614   3147   	  int rows;
  2615         -      if (nArg == 5)
  2616         -          pk = azArg[4];
  2617         -      if (nArg == 6)
  2618         -          text_dates = atoi(azArg[5]);
         3148  +	  if (nArg >= 5)
         3149  +	      pk = azArg[4];
         3150  +	  if (nArg >= 6)
         3151  +	    {
         3152  +		if (strcasecmp (azArg[5], "text_dates") == 0)
         3153  +		    text_dates = 1;
         3154  +		if (strcasecmp (azArg[5], "yes") == 0)
         3155  +		    text_dates = 1;
         3156  +		if (strcasecmp (azArg[5], "true") == 0)
         3157  +		    text_dates = 1;
         3158  +		if (strcasecmp (azArg[5], "1") == 0)
         3159  +		    text_dates = 1;
         3160  +	    }
         3161  +	  if (nArg >= 7)
         3162  +	    {
         3163  +		const char *pColnameCase = azArg[6];
         3164  +		if (strcasecmp (pColnameCase, "UPPER") == 0
         3165  +		    || strcasecmp (pColnameCase, "UPPERCASE") == 0)
         3166  +		    colname_case = GAIA_DBF_COLNAME_UPPERCASE;
         3167  +		else if (strcasecmp (pColnameCase, "SAME") == 0
         3168  +			 || strcasecmp (pColnameCase, "SAMECASE") == 0)
         3169  +		    colname_case = GAIA_DBF_COLNAME_CASE_IGNORE;
         3170  +		else
         3171  +		    colname_case = GAIA_DBF_COLNAME_LOWERCASE;
         3172  +	    }
  2619   3173   	  open_db (p);
  2620         -	  load_dbf_ex2 (p->db, dbf_path, table, pk, inCS, 1, text_dates, &rows, NULL);
         3174  +	  load_dbf_ex3 (p->db, dbf_path, table, pk, inCS, 1, text_dates, &rows,
         3175  +			colname_case, NULL);
  2621   3176         }
  2622   3177   #ifndef OMIT_FREEXL		/* FREEXL is enabled */
  2623   3178       else if (c == 'l' && n > 1 && strncmp (azArg[0], "loadxl", n) == 0
  2624   3179   	     && (nArg == 3 || nArg == 4 || nArg == 5))
  2625   3180         {
  2626   3181   	  unsigned int rows;
  2627   3182   	  char *xl_path = azArg[1];
................................................................................
  2638   3193   	  open_db (p);
  2639   3194   	  load_XL (p->db, xl_path, table, worksheet, firstLine, &rows, NULL);
  2640   3195         }
  2641   3196   #endif /* end FREEXL support */
  2642   3197       else if (c == 'l' && n > 1 && strncmp (azArg[0], "loadwfs", n) == 0
  2643   3198   	     && (nArg == 4 || nArg == 5 || nArg == 6 || nArg == 7 || nArg == 8))
  2644   3199         {
  2645         -          char *path_or_url = azArg[1];
  2646         -          char *layer_name = azArg[2];
  2647         -          char *table = azArg[3];
  2648         -          int swap_axes = 0;
  2649         -          int with_spatial_index = 0;
  2650         -          int page_size = -1;
  2651         -          char *pk = NULL;
  2652         -          char *err_msg = NULL;
  2653         -          int rows;
         3200  +	  char *path_or_url = azArg[1];
         3201  +	  char *layer_name = azArg[2];
         3202  +	  char *table = azArg[3];
         3203  +	  int swap_axes = 0;
         3204  +	  int with_spatial_index = 0;
         3205  +	  int page_size = -1;
         3206  +	  char *pk = NULL;
         3207  +	  char *err_msg = NULL;
         3208  +	  int rows;
  2654   3209   	  if (nArg >= 5)
  2655   3210   	      pk = azArg[4];
  2656   3211   	  if (nArg >= 6)
  2657         -          {
  2658         -              if (strcasecmp(azArg[5], "swap") == 0 ||
  2659         -                  strcasecmp(azArg[5], "swap_axis") == 0 ||
  2660         -                  strcasecmp(azArg[5], "swap_axes") == 0)
  2661         -                  swap_axes = 1;
  2662         -          }
         3212  +	    {
         3213  +		if (strcasecmp (azArg[5], "swap") == 0 ||
         3214  +		    strcasecmp (azArg[5], "swap_axis") == 0 ||
         3215  +		    strcasecmp (azArg[5], "swap_axes") == 0)
         3216  +		    swap_axes = 1;
         3217  +	    }
  2663   3218   	  if (nArg >= 7)
  2664         -	      page_size = atoi(azArg[6]);
         3219  +	      page_size = atoi (azArg[6]);
  2665   3220   	  if (nArg == 8)
  2666   3221   	      with_spatial_index = 1;
  2667   3222   	  open_db (p);
  2668         -	  if (load_from_wfs_paged (p->db, path_or_url, NULL, layer_name, swap_axes, table, pk, with_spatial_index, 
  2669         -        page_size, &rows, &err_msg, wfs_page_done, NULL) == 0)
  2670         -		{
  2671         -			fprintf(stderr, "Unable to load data from WFS:\n");
  2672         -			fprintf(stderr, "%s\n\n", err_msg);
  2673         -		}
  2674         -		else
  2675         -			fprintf(stderr, "inserted %d rows from WFS into table \"%s\"\n\n", rows, table);
  2676         -		if (err_msg)
  2677         -			free(err_msg);
         3223  +	  if (load_from_wfs_paged
         3224  +	      (p->db, path_or_url, NULL, layer_name, swap_axes, table, pk,
         3225  +	       with_spatial_index, page_size, &rows, &err_msg, wfs_page_done,
         3226  +	       NULL) == 0)
         3227  +	    {
         3228  +		fprintf (stderr, "Unable to load data from WFS:\n");
         3229  +		fprintf (stderr, "%s\n\n", err_msg);
         3230  +	    }
         3231  +	  else
         3232  +	      fprintf (stderr,
         3233  +		       "inserted %d rows from WFS into table \"%s\"\n\n", rows,
         3234  +		       table);
         3235  +	  if (err_msg)
         3236  +	      free (err_msg);
  2678   3237         }
  2679   3238       else if (c == 'l' && n > 1 && strncmp (azArg[0], "loaddxf", n) == 0
  2680   3239   	     && (nArg == 2 || (nArg >= 3 && nArg <= 9)))
  2681   3240         {
  2682   3241   	  char *dxf_path = azArg[1];
  2683   3242   	  int srid = -1;
  2684         -  	  int append = 0;
  2685         -          int special_rings = GAIA_DXF_RING_NONE;
  2686         -          int mode = GAIA_DXF_IMPORT_BY_LAYER;
  2687         -          int force_dims = GAIA_DXF_AUTO_2D_3D;
  2688         -          char *prefix = NULL;
  2689         -          char *layer_name = NULL;
  2690         -          gaiaDxfParserPtr dxf = NULL;
         3243  +	  int append = 0;
         3244  +	  int special_rings = GAIA_DXF_RING_NONE;
         3245  +	  int mode = GAIA_DXF_IMPORT_BY_LAYER;
         3246  +	  int force_dims = GAIA_DXF_AUTO_2D_3D;
         3247  +	  char *prefix = NULL;
         3248  +	  char *layer_name = NULL;
         3249  +	  gaiaDxfParserPtr dxf = NULL;
  2691   3250   	  if (nArg >= 3)
  2692         -	      srid = atoi(azArg[2]);
         3251  +	      srid = atoi (azArg[2]);
  2693   3252   	  if (nArg >= 4)
  2694         -          {
  2695         -              if (strcasecmp(azArg[3], "y") == 0 ||
  2696         -                  strcasecmp(azArg[3], "yes") == 0)
  2697         -                  append = 1;
  2698         -          }
         3253  +	    {
         3254  +		if (strcasecmp (azArg[3], "y") == 0 ||
         3255  +		    strcasecmp (azArg[3], "yes") == 0)
         3256  +		    append = 1;
         3257  +	    }
  2699   3258   	  if (nArg >= 5)
  2700         -          {
  2701         -              if (strcasecmp(azArg[4], "2D") == 0)
  2702         -                  force_dims = GAIA_DXF_FORCE_2D;
  2703         -              if (strcasecmp(azArg[4], "3D") == 0)
  2704         -                  force_dims = GAIA_DXF_FORCE_3D;
  2705         -          }
         3259  +	    {
         3260  +		if (strcasecmp (azArg[4], "2D") == 0)
         3261  +		    force_dims = GAIA_DXF_FORCE_2D;
         3262  +		if (strcasecmp (azArg[4], "3D") == 0)
         3263  +		    force_dims = GAIA_DXF_FORCE_3D;
         3264  +	    }
  2706   3265   	  if (nArg >= 6)
  2707         -          {
  2708         -              if (strcasecmp(azArg[5], "mixed") == 0)
  2709         -                  mode = GAIA_DXF_IMPORT_MIXED;
  2710         -          }
         3266  +	    {
         3267  +		if (strcasecmp (azArg[5], "mixed") == 0)
         3268  +		    mode = GAIA_DXF_IMPORT_MIXED;
         3269  +	    }
  2711   3270   	  if (nArg >= 7)
  2712         -          {
  2713         -              if (strcasecmp(azArg[6], "linked") == 0)
  2714         -                  special_rings = GAIA_DXF_RING_LINKED;
  2715         -              if (strcasecmp(azArg[6], "unlinked") == 0)
  2716         -                  special_rings = GAIA_DXF_RING_UNLINKED;
  2717         -          }
  2718         -          if (nArg >= 8)
  2719         -          {
  2720         -              if (strlen(azArg[7]) > 0)
  2721         -                  prefix = azArg[7];
  2722         -          }
  2723         -          if (nArg == 9)
  2724         -          {
  2725         -              if (strlen(azArg[8]) > 0)
  2726         -                  layer_name = azArg[8];
  2727         -          }
  2728         -	  open_db (p);
  2729         -      /* creating a DXF parser */
  2730         -          dxf = gaiaCreateDxfParser (srid, force_dims, prefix, layer_name,
  2731         -                special_rings);
  2732         -          if (dxf == NULL)
  2733         -              goto stop_dxf;
  2734         -      /* attempting to parse the DXF input file */
  2735         -          if (gaiaParseDxfFile_r (splite_cache, dxf, dxf_path))
  2736         -          {
  2737         -      /* loading into the DB */
  2738         -              if (!gaiaLoadFromDxfParser (p->db, dxf, mode, append))
  2739         -                  fprintf (stderr, "DB error while loading: %s\n", dxf_path);
  2740         -          }
  2741         -          else
  2742         -              fprintf (stderr, "Unable to parse: %s\n", dxf_path);
  2743         -          fprintf(stderr, "\n*** DXF file successfully loaded\n"); 
  2744         -stop_dxf:
  2745         -      /* destroying the DXF parser */
  2746         -          gaiaDestroyDxfParser (dxf);
         3271  +	    {
         3272  +		if (strcasecmp (azArg[6], "linked") == 0)
         3273  +		    special_rings = GAIA_DXF_RING_LINKED;
         3274  +		if (strcasecmp (azArg[6], "unlinked") == 0)
         3275  +		    special_rings = GAIA_DXF_RING_UNLINKED;
         3276  +	    }
         3277  +	  if (nArg >= 8)
         3278  +	    {
         3279  +		if (strlen (azArg[7]) > 0)
         3280  +		    prefix = azArg[7];
         3281  +	    }
         3282  +	  if (nArg == 9)
         3283  +	    {
         3284  +		if (strlen (azArg[8]) > 0)
         3285  +		    layer_name = azArg[8];
         3286  +	    }
         3287  +	  open_db (p);
         3288  +	  /* creating a DXF parser */
         3289  +	  dxf = gaiaCreateDxfParser (srid, force_dims, prefix, layer_name,
         3290  +				     special_rings);
         3291  +	  if (dxf == NULL)
         3292  +	      goto stop_dxf;
         3293  +	  /* attempting to parse the DXF input file */
         3294  +	  if (gaiaParseDxfFile_r (splite_cache, dxf, dxf_path))
         3295  +	    {
         3296  +		/* loading into the DB */
         3297  +		if (!gaiaLoadFromDxfParser (p->db, dxf, mode, append))
         3298  +		    fprintf (stderr, "DB error while loading: %s\n", dxf_path);
         3299  +	    }
         3300  +	  else
         3301  +	      fprintf (stderr, "Unable to parse: %s\n", dxf_path);
         3302  +	  fprintf (stderr, "\n*** DXF file successfully loaded\n");
         3303  +	stop_dxf:
         3304  +	  /* destroying the DXF parser */
         3305  +	  gaiaDestroyDxfParser (dxf);
  2747   3306         }
  2748   3307       else if (c == 'r' && strncmp (azArg[0], "read", n) == 0)
  2749   3308         {
  2750   3309   	  FILE *alt;
  2751         -	  if (nArg != 3)
         3310  +	  char *arg2 = NULL;
         3311  +	  if (nArg == 2)
         3312  +	      ;
         3313  +	  else if (nArg == 3)
         3314  +	      arg2 = azArg[2];
         3315  +	  else
  2752   3316   	    {
  2753   3317   		fprintf (stderr,
  2754   3318   			 "invalid arguments: .read script_path charset\n");
  2755   3319   		return rc;
  2756   3320   	    }
  2757   3321   	  alt = fopen (azArg[1], "rb");
  2758   3322   	  if (alt == 0)
  2759   3323   	    {
  2760   3324   		fprintf (stderr, "can't open \"%s\"\n", azArg[1]);
  2761   3325   	    }
  2762   3326   	  else
  2763   3327   	    {
  2764         -		process_input (p, alt, azArg[2]);
         3328  +		process_input (p, alt, arg2);
  2765   3329   		fclose (alt);
  2766   3330   	    }
  2767   3331         }
  2768   3332       else if (c == 'c' && strncmp (azArg[0], "chkdupl", n) == 0 && nArg == 2)
  2769   3333         {
  2770   3334   	  int rows;
  2771   3335   	  char *table = azArg[1];
................................................................................
  2781   3345       else if (c == 'c' && strncmp (azArg[0], "checkgeom", n) == 0 && nArg == 4)
  2782   3346         {
  2783   3347   	  char *table = azArg[1];
  2784   3348   	  char *geometry = azArg[2];
  2785   3349   	  char *report = azArg[3];
  2786   3350   	  char *err_msg = NULL;
  2787   3351   	  open_db (p);
  2788         -	  if (!check_geometry_column (p->db, table, geometry, report, NULL, NULL, &err_msg))
  2789         -          {
  2790         -              fprintf(stderr, "check_geometry_column error:\n");
  2791         -              fprintf(stderr, "%s\n\n", err_msg);
  2792         -          }
  2793         -          if (err_msg)
  2794         -              free(err_msg);
         3352  +	  if (!check_geometry_column
         3353  +	      (p->db, table, geometry, report, NULL, NULL, &err_msg))
         3354  +	    {
         3355  +		fprintf (stderr, "check_geometry_column error:\n");
         3356  +		fprintf (stderr, "%s\n\n", err_msg);
         3357  +	    }
         3358  +	  if (err_msg)
         3359  +	      free (err_msg);
  2795   3360         }
  2796   3361       else if (c == 'c' && strncmp (azArg[0], "checkgeom", n) == 0 && nArg == 2)
  2797   3362         {
  2798   3363   	  char *output_dir = azArg[1];
  2799   3364   	  char *err_msg = NULL;
  2800   3365   	  open_db (p);
  2801   3366   	  if (!check_all_geometry_columns (p->db, output_dir, NULL, &err_msg))
  2802         -          {
  2803         -              fprintf(stderr, "check_all_geometry_columns error:\n");
  2804         -              fprintf(stderr, "%s\n\n", err_msg);
  2805         -          }
  2806         -          if (err_msg)
  2807         -              free(err_msg);
         3367  +	    {
         3368  +		fprintf (stderr, "check_all_geometry_columns error:\n");
         3369  +		fprintf (stderr, "%s\n\n", err_msg);
         3370  +	    }
         3371  +	  if (err_msg)
         3372  +	      free (err_msg);
  2808   3373         }
  2809   3374       else if (c == 's' && strncmp (azArg[0], "sanegeom", n) == 0 && nArg == 5)
  2810   3375         {
  2811   3376   	  char *table = azArg[1];
  2812   3377   	  char *geometry = azArg[2];
  2813   3378   	  char *tmp_table = azArg[3];
  2814   3379   	  char *report = azArg[4];
  2815   3380   	  char *err_msg = NULL;
  2816   3381   	  open_db (p);
  2817         -	  if (!sanitize_geometry_column (p->db, table, geometry, tmp_table, report, NULL, NULL, NULL, NULL, &err_msg))
  2818         -          {
  2819         -              fprintf(stderr, "sanitize_geometry_column error:\n");
  2820         -              fprintf(stderr, "%s\n\n", err_msg);
  2821         -          }
  2822         -          if (err_msg)
  2823         -              free(err_msg);
         3382  +	  if (!sanitize_geometry_column
         3383  +	      (p->db, table, geometry, tmp_table, report, NULL, NULL, NULL,
         3384  +	       NULL, &err_msg))
         3385  +	    {
         3386  +		fprintf (stderr, "sanitize_geometry_column error:\n");
         3387  +		fprintf (stderr, "%s\n\n", err_msg);
         3388  +	    }
         3389  +	  if (err_msg)
         3390  +	      free (err_msg);
  2824   3391         }
  2825   3392       else if (c == 's' && strncmp (azArg[0], "sanegeom", n) == 0 && nArg == 3)
  2826   3393         {
  2827   3394   	  char *tmp_prefix = azArg[1];
  2828   3395   	  char *output_dir = azArg[2];
  2829   3396   	  char *err_msg = NULL;
  2830   3397   	  open_db (p);
  2831         -	  if (!sanitize_all_geometry_columns (p->db, tmp_prefix, output_dir, NULL, &err_msg))
  2832         -          {
  2833         -              fprintf(stderr, "sanitize_all_geometry_columns error:\n");
  2834         -              fprintf(stderr, "%s\n\n", err_msg);
  2835         -          }
  2836         -          if (err_msg)
  2837         -              free(err_msg);
         3398  +	  if (!sanitize_all_geometry_columns
         3399  +	      (p->db, tmp_prefix, output_dir, NULL, &err_msg))
         3400  +	    {
         3401  +		fprintf (stderr, "sanitize_all_geometry_columns error:\n");
         3402  +		fprintf (stderr, "%s\n\n", err_msg);
         3403  +	    }
         3404  +	  if (err_msg)
         3405  +	      free (err_msg);
  2838   3406         }
  2839   3407       else if (c == 'e' && strncmp (azArg[0], "elemgeo", n) == 0 && nArg == 6)
  2840   3408         {
  2841   3409   	  char *inTable = azArg[1];
  2842   3410   	  char *geom = azArg[2];
  2843   3411   	  char *outTable = azArg[3];
  2844   3412   	  char *pKey = azArg[4];
................................................................................
  2848   3416         }
  2849   3417       else if (c == 's' && strncmp (azArg[0], "sqllog", n) == 0 && nArg > 1)
  2850   3418         {
  2851   3419   	  sql_log_enabled = booleanValue (azArg[1]);
  2852   3420         }
  2853   3421       else if (c == 'd' && strncmp (azArg[0], "dropgeo", n) == 0 && nArg > 1)
  2854   3422         {
  2855         -          char *prefix;
  2856         -          char *table;
  2857         -          int ret;
  2858         -          int cnt0 = sqlite3_total_changes(p->db);
  2859         -          split_drop_name(azArg[1], &prefix, &table);
  2860         -          if (prefix != NULL && table != NULL)
  2861         -              ret = gaiaDropTableEx (p->db, prefix, table);
  2862         -          else
         3423  +	  char *prefix;
         3424  +	  char *table;
         3425  +	  int ret;
         3426  +	  int cnt0 = sqlite3_total_changes (p->db);
         3427  +	  split_drop_name (azArg[1], &prefix, &table);
         3428  +	  if (prefix != NULL && table != NULL)
         3429  +	      ret = gaiaDropTableEx (p->db, prefix, table);
         3430  +	  else
  2863   3431   	      ret = gaiaDropTable (p->db, azArg[1]);
  2864         -          if (ret)
  2865         -          {
  2866         -              int cnt1 = sqlite3_total_changes(p->db);
  2867         -              if (cnt1 > cnt0)
  2868         -                  fprintf(stderr, "SpatialTable %s successfully removed\n", azArg[1]);
  2869         -              else
  2870         -                  fprintf(stderr, "SpatialTable %s seems not to exist\n", azArg[1]);
  2871         -          }
  2872         -          else
  2873         -              fprintf(stderr, "ERROR: unable to remove SpatialTable %s\n", azArg[1]);
  2874         -          if (prefix != NULL)
  2875         -              free(prefix);
  2876         -          if (table != NULL)
  2877         -              free(table);
  2878         -      } else
         3432  +	  if (ret)
         3433  +	    {
         3434  +		int cnt1 = sqlite3_total_changes (p->db);
         3435  +		if (cnt1 > cnt0)
         3436  +		    fprintf (stderr, "SpatialTable %s successfully removed\n",
         3437  +			     azArg[1]);
         3438  +		else
         3439  +		    fprintf (stderr, "SpatialTable %s seems not to exist\n",
         3440  +			     azArg[1]);
         3441  +	    }
         3442  +	  else
         3443  +	      fprintf (stderr, "ERROR: unable to remove SpatialTable %s\n",
         3444  +		       azArg[1]);
         3445  +	  if (prefix != NULL)
         3446  +	      free (prefix);
         3447  +	  if (table != NULL)
         3448  +	      free (table);
         3449  +      }
         3450  +    else
  2879   3451   /* end sandro 2008-06-20 */
  2880         -  if( c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0 && nArg>1 && nArg<4){
  2881         -    const char *zDestFile;
  2882         -    const char *zDb;
  2883         -    sqlite3 *pDest;
  2884         -    sqlite3_backup *pBackup;
  2885         -    if( nArg==2 ){
  2886         -      zDestFile = azArg[1];
  2887         -      zDb = "main";
  2888         -    }else{
  2889         -      zDestFile = azArg[2];
  2890         -      zDb = azArg[1];
  2891         -    }
  2892         -    rc = sqlite3_open(zDestFile, &pDest);
  2893         -    if( rc!=SQLITE_OK ){
  2894         -      fprintf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
  2895         -      sqlite3_close(pDest);
  2896         -      return 1;
  2897         -    }
  2898         -    open_db(p);
  2899         -    pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
  2900         -    if( pBackup==0 ){
  2901         -      fprintf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
  2902         -      sqlite3_close(pDest);
  2903         -      return 1;
  2904         -    }
  2905         -    while(  (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
  2906         -    sqlite3_backup_finish(pBackup);
  2907         -    if( rc==SQLITE_DONE ){
  2908         -      rc = 0;
  2909         -    }else{
  2910         -      fprintf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
  2911         -      rc = 1;
  2912         -    }
  2913         -    sqlite3_close(pDest);
  2914         -  }else if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 && nArg>1 && nArg<3 ){
  2915         -    bail_on_error = booleanValue(azArg[1]);
  2916         -  }else
  2917         -
  2918         -  /* The undocumented ".breakpoint" command causes a call to the no-op
  2919         -  ** routine named test_breakpoint().
  2920         -  */
  2921         -  if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
  2922         -    test_breakpoint();
  2923         -  }else
  2924         -
  2925         -  if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 && nArg==1 ){
  2926         -    struct callback_data data;
  2927         -    char *zErrMsg = 0;
  2928         -    open_db(p);
  2929         -    memcpy(&data, p, sizeof(data));
  2930         -    data.showHeader = 1;
  2931         -    data.mode = MODE_Column;
  2932         -    data.colWidth[0] = 3;
  2933         -    data.colWidth[1] = 15;
  2934         -    data.colWidth[2] = 58;
  2935         -    data.cnt = 0;
  2936         -    sqlite3_exec(p->db, "PRAGMA database_list; ", callback, &data, &zErrMsg);
  2937         -    if( zErrMsg ){
  2938         -      fprintf(stderr,"Error: %s\n", zErrMsg);
  2939         -      sqlite3_free(zErrMsg);
  2940         -      rc = 1;
  2941         -    }
  2942         -  }else
  2943         -
  2944         -  if( c=='d' && strncmp(azArg[0], "dump", n)==0 && nArg<3 ){
  2945         -    open_db(p);
  2946         -    /* When playing back a "dump", the content might appear in an order
  2947         -    ** which causes immediate foreign key constraints to be violated.
  2948         -    ** So disable foreign-key constraint enforcement to prevent problems. */
  2949         -    fprintf(p->out, "PRAGMA foreign_keys=OFF;\n");
  2950         -    fprintf(p->out, "BEGIN TRANSACTION;\n");
  2951         -    p->writableSchema = 0;
  2952         -    sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
  2953         -    p->nErr = 0;
  2954         -    if( nArg==1 ){
  2955         -      run_schema_dump_query(p, 
  2956         -        "SELECT name, type, sql FROM sqlite_master "
  2957         -        "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'"
  2958         -      );
  2959         -      run_schema_dump_query(p, 
  2960         -        "SELECT name, type, sql FROM sqlite_master "
  2961         -        "WHERE name=='sqlite_sequence'"
  2962         -      );
  2963         -      run_table_dump_query(p,
  2964         -        "SELECT sql FROM sqlite_master "
  2965         -        "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0
  2966         -      );
  2967         -    }else{
  2968         -      int i;
  2969         -      for(i=1; i<nArg; i++){
  2970         -        zShellStatic = azArg[i];
  2971         -        run_schema_dump_query(p,
  2972         -          "SELECT name, type, sql FROM sqlite_master "
  2973         -          "WHERE tbl_name LIKE shellstatic() AND type=='table'"
  2974         -          "  AND sql NOT NULL");
  2975         -        run_table_dump_query(p,
  2976         -          "SELECT sql FROM sqlite_master "
  2977         -          "WHERE sql NOT NULL"
  2978         -          "  AND type IN ('index','trigger','view')"
  2979         -          "  AND tbl_name LIKE shellstatic()", 0
  2980         -        );
  2981         -        zShellStatic = 0;
  2982         -      }
  2983         -    }
  2984         -    if( p->writableSchema ){
  2985         -      fprintf(p->out, "PRAGMA writable_schema=OFF;\n");
  2986         -      p->writableSchema = 0;
  2987         -    }
  2988         -    sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
  2989         -    sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
  2990         -    fprintf(p->out, p->nErr ? "ROLLBACK; -- due to errors\n" : "COMMIT;\n");
  2991         -  }else
  2992         -
  2993         -  if( c=='e' && strncmp(azArg[0], "echo", n)==0 && nArg>1 && nArg<3 ){
  2994         -    p->echoOn = booleanValue(azArg[1]);
  2995         -  }else
  2996         -
  2997         -  if( c=='e' && strncmp(azArg[0], "exit", n)==0  && nArg==1 ){
  2998         -    rc = 2;
  2999         -  }else
  3000         -
  3001         -  if( c=='e' && strncmp(azArg[0], "explain", n)==0 && nArg<3 ){
  3002         -    int val = nArg>=2 ? booleanValue(azArg[1]) : 1;
  3003         -    if(val == 1) {
  3004         -      if(!p->explainPrev.valid) {
  3005         -        p->explainPrev.valid = 1;
  3006         -        p->explainPrev.mode = p->mode;
  3007         -        p->explainPrev.showHeader = p->showHeader;
  3008         -        memcpy(p->explainPrev.colWidth,p->colWidth,sizeof(p->colWidth));
  3009         -      }
  3010         -      /* We could put this code under the !p->explainValid
  3011         -      ** condition so that it does not execute if we are already in
  3012         -      ** explain mode. However, always executing it allows us an easy
  3013         -      ** was to reset to explain mode in case the user previously
  3014         -      ** did an .explain followed by a .width, .mode or .header
  3015         -      ** command.
  3016         -      */
  3017         -      p->mode = MODE_Explain;
  3018         -      p->showHeader = 1;
  3019         -      memset(p->colWidth,0,ArraySize(p->colWidth));
  3020         -      p->colWidth[0] = 4;                  /* addr */
  3021         -      p->colWidth[1] = 13;                 /* opcode */
  3022         -      p->colWidth[2] = 4;                  /* P1 */
  3023         -      p->colWidth[3] = 4;                  /* P2 */
  3024         -      p->colWidth[4] = 4;                  /* P3 */
  3025         -      p->colWidth[5] = 13;                 /* P4 */
  3026         -      p->colWidth[6] = 2;                  /* P5 */
  3027         -      p->colWidth[7] = 13;                  /* Comment */
  3028         -    }else if (p->explainPrev.valid) {
  3029         -      p->explainPrev.valid = 0;
  3030         -      p->mode = p->explainPrev.mode;
  3031         -      p->showHeader = p->explainPrev.showHeader;
  3032         -      memcpy(p->colWidth,p->explainPrev.colWidth,sizeof(p->colWidth));
  3033         -    }
  3034         -  }else
  3035         -
  3036         -  if( c=='h' && (strncmp(azArg[0], "header", n)==0 ||
  3037         -                 strncmp(azArg[0], "headers", n)==0) && nArg>1 && nArg<3 ){
  3038         -    p->showHeader = booleanValue(azArg[1]);
  3039         -  }else
  3040         -
  3041         -  if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
  3042         -    fprintf(stderr,"%s",zHelp);
  3043         -    if( HAS_TIMER ){
  3044         -      fprintf(stderr,"%s",zTimerHelp);
  3045         -    }
  3046         -  }else
  3047         -
  3048         -  if( c=='i' && strncmp(azArg[0], "import", n)==0 && nArg==3 ){
  3049         -    char *zTable = azArg[2];    /* Insert data into this table */
  3050         -    char *zFile = azArg[1];     /* The file from which to extract data */
  3051         -    sqlite3_stmt *pStmt = NULL; /* A statement */
  3052         -    int nCol;                   /* Number of columns in the table */
  3053         -    int nByte;                  /* Number of bytes in an SQL string */
  3054         -    int i, j;                   /* Loop counters */
  3055         -    int nSep;                   /* Number of bytes in p->separator[] */
  3056         -    char *zSql;                 /* An SQL statement */
  3057         -    char *zLine;                /* A single line of input from the file */
  3058         -    char **azCol;               /* zLine[] broken up into columns */
  3059         -    char *zCommit;              /* How to commit changes */   
  3060         -    FILE *in;                   /* The input file */
  3061         -    int lineno = 0;             /* Line number of input file */
  3062         -
  3063         -    open_db(p);
  3064         -    nSep = strlen30(p->separator);
  3065         -    if( nSep==0 ){
  3066         -      fprintf(stderr, "Error: non-null separator required for import\n");
  3067         -      return 1;
  3068         -    }
  3069         -    zSql = sqlite3_mprintf("SELECT * FROM %s", zTable);
  3070         -    if( zSql==0 ){
  3071         -      fprintf(stderr, "Error: out of memory\n");
  3072         -      return 1;
  3073         -    }
  3074         -    nByte = strlen30(zSql);
  3075         -    rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
  3076         -    sqlite3_free(zSql);
  3077         -    if( rc ){
  3078         -      if (pStmt) sqlite3_finalize(pStmt);
  3079         -      fprintf(stderr,"Error: %s\n", sqlite3_errmsg(db));
  3080         -      return 1;
  3081         -    }
  3082         -    nCol = sqlite3_column_count(pStmt);
  3083         -    sqlite3_finalize(pStmt);
  3084         -    pStmt = 0;
  3085         -    if( nCol==0 ) return 0; /* no columns, no error */
  3086         -    zSql = malloc( nByte + 20 + nCol*2 );
  3087         -    if( zSql==0 ){
  3088         -      fprintf(stderr, "Error: out of memory\n");
  3089         -      return 1;
  3090         -    }
  3091         -    sqlite3_snprintf(nByte+20, zSql, "INSERT INTO %s VALUES(?", zTable);
  3092         -    j = strlen30(zSql);
  3093         -    for(i=1; i<nCol; i++){
  3094         -      zSql[j++] = ',';
  3095         -      zSql[j++] = '?';
  3096         -    }
  3097         -    zSql[j++] = ')';
  3098         -    zSql[j] = 0;
  3099         -    rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
  3100         -    free(zSql);
  3101         -    if( rc ){
  3102         -      fprintf(stderr, "Error: %s\n", sqlite3_errmsg(db));
  3103         -      if (pStmt) sqlite3_finalize(pStmt);
  3104         -      return 1;
  3105         -    }
  3106         -    in = fopen(zFile, "rb");
  3107         -    if( in==0 ){
  3108         -      fprintf(stderr, "Error: cannot open \"%s\"\n", zFile);
  3109         -      sqlite3_finalize(pStmt);
  3110         -      return 1;
  3111         -    }
  3112         -    azCol = malloc( sizeof(azCol[0])*(nCol+1) );
  3113         -    if( azCol==0 ){
  3114         -      fprintf(stderr, "Error: out of memory\n");
  3115         -      fclose(in);
  3116         -      sqlite3_finalize(pStmt);
  3117         -      return 1;
  3118         -    }
  3119         -    sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
  3120         -    zCommit = "COMMIT";
  3121         -    while( (zLine = local_getline(0, in, 1))!=0 ){
  3122         -      char *z, c;
  3123         -      int inQuote = 0;
  3124         -      lineno++;
  3125         -      azCol[0] = zLine;
  3126         -      for(i=0, z=zLine; (c = *z)!=0; z++){
  3127         -        if( c=='"' ) inQuote = !inQuote;
  3128         -        if( c=='\n' ) lineno++;
  3129         -        if( !inQuote && c==p->separator[0] && strncmp(z,p->separator,nSep)==0 ){
  3130         -          *z = 0;
  3131         -          i++;
  3132         -          if( i<nCol ){
  3133         -            azCol[i] = &z[nSep];
  3134         -            z += nSep-1;
  3135         -          }
  3136         -        }
  3137         -      } /* end for */
  3138         -      *z = 0;
  3139         -      if( i+1!=nCol ){
  3140         -        fprintf(stderr,
  3141         -                "Error: %s line %d: expected %d columns of data but found %d\n",
  3142         -                zFile, lineno, nCol, i+1);
  3143         -        zCommit = "ROLLBACK";
  3144         -        free(zLine);
  3145         -        rc = 1;
  3146         -        break; /* from while */
  3147         -      }
  3148         -      for(i=0; i<nCol; i++){
  3149         -        if( azCol[i][0]=='"' ){
  3150         -          int k;
  3151         -          for(z=azCol[i], j=1, k=0; z[j]; j++){
  3152         -            if( z[j]=='"' ){ j++; if( z[j]==0 ) break; }
  3153         -            z[k++] = z[j];
  3154         -          }
  3155         -          z[k] = 0;
  3156         -        }
  3157         -        sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC);
  3158         -      }
  3159         -      sqlite3_step(pStmt);
  3160         -      rc = sqlite3_reset(pStmt);
  3161         -      free(zLine);
  3162         -      if( rc!=SQLITE_OK ){
  3163         -        fprintf(stderr,"Error: %s\n", sqlite3_errmsg(db));
  3164         -        zCommit = "ROLLBACK";
  3165         -        rc = 1;
  3166         -        break; /* from while */
  3167         -      }
  3168         -    } /* end while */
  3169         -    free(azCol);
  3170         -    fclose(in);
  3171         -    sqlite3_finalize(pStmt);
  3172         -    sqlite3_exec(p->db, zCommit, 0, 0, 0);
  3173         -  }else
  3174         -
  3175         -  if( c=='i' && strncmp(azArg[0], "indices", n)==0 && nArg<3 ){
  3176         -    struct callback_data data;
  3177         -    char *zErrMsg = 0;
  3178         -    open_db(p);
  3179         -    memcpy(&data, p, sizeof(data));
  3180         -    data.showHeader = 0;
  3181         -    data.mode = MODE_List;
  3182         -    if( nArg==1 ){
  3183         -      rc = sqlite3_exec(p->db,
  3184         -        "SELECT name FROM sqlite_master "
  3185         -        "WHERE type='index' AND name NOT LIKE 'sqlite_%' "
  3186         -        "UNION ALL "
  3187         -        "SELECT name FROM sqlite_temp_master "
  3188         -        "WHERE type='index' "
  3189         -        "ORDER BY 1",
  3190         -        callback, &data, &zErrMsg
  3191         -      );
  3192         -    }else{
  3193         -      zShellStatic = azArg[1];
  3194         -      rc = sqlite3_exec(p->db,
  3195         -        "SELECT name FROM sqlite_master "
  3196         -        "WHERE type='index' AND tbl_name LIKE shellstatic() "
  3197         -        "UNION ALL "
  3198         -        "SELECT name FROM sqlite_temp_master "
  3199         -        "WHERE type='index' AND tbl_name LIKE shellstatic() "
  3200         -        "ORDER BY 1",
  3201         -        callback, &data, &zErrMsg
  3202         -      );
  3203         -      zShellStatic = 0;
  3204         -    }
  3205         -    if( zErrMsg ){
  3206         -      fprintf(stderr,"Error: %s\n", zErrMsg);
  3207         -      sqlite3_free(zErrMsg);
  3208         -      rc = 1;
  3209         -    }else if( rc != SQLITE_OK ){
  3210         -      fprintf(stderr,"Error: querying sqlite_master and sqlite_temp_master\n");
  3211         -      rc = 1;
  3212         -    }
  3213         -  }else
  3214         -
         3452  +    if (c == 'b' && n >= 3 && strncmp (azArg[0], "backup", n) == 0
         3453  +	    && nArg > 1 && nArg < 4)
         3454  +      {
         3455  +	  const char *zDestFile;
         3456  +	  const char *zDb;
         3457  +	  sqlite3 *pDest;
         3458  +	  sqlite3_backup *pBackup;
         3459  +	  if (nArg == 2)
         3460  +	    {
         3461  +		zDestFile = azArg[1];
         3462  +		zDb = "main";
         3463  +	    }
         3464  +	  else
         3465  +	    {
         3466  +		zDestFile = azArg[2];
         3467  +		zDb = azArg[1];
         3468  +	    }
         3469  +	  rc = sqlite3_open (zDestFile, &pDest);
         3470  +	  if (rc != SQLITE_OK)
         3471  +	    {
         3472  +		fprintf (stderr, "Error: cannot open \"%s\"\n", zDestFile);
         3473  +		sqlite3_close (pDest);
         3474  +		return 1;
         3475  +	    }
         3476  +	  open_db (p);
         3477  +	  pBackup = sqlite3_backup_init (pDest, "main", p->db, zDb);
         3478  +	  if (pBackup == 0)
         3479  +	    {
         3480  +		fprintf (stderr, "Error: %s\n", sqlite3_errmsg (pDest));
         3481  +		sqlite3_close (pDest);
         3482  +		return 1;
         3483  +	    }
         3484  +	  while ((rc = sqlite3_backup_step (pBackup, 100)) == SQLITE_OK)
         3485  +	    {
         3486  +	    }
         3487  +	  sqlite3_backup_finish (pBackup);
         3488  +	  if (rc == SQLITE_DONE)
         3489  +	    {
         3490  +		rc = 0;
         3491  +	    }
         3492  +	  else
         3493  +	    {
         3494  +		fprintf (stderr, "Error: %s\n", sqlite3_errmsg (pDest));
         3495  +		rc = 1;
         3496  +	    }
         3497  +	  sqlite3_close (pDest);
         3498  +      }
         3499  +    else if (c == 'b' && n >= 3 && strncmp (azArg[0], "bail", n) == 0
         3500  +	     && nArg > 1 && nArg < 3)
         3501  +      {
         3502  +	  bail_on_error = booleanValue (azArg[1]);
         3503  +      }
         3504  +    else
         3505  +	/* The undocumented ".breakpoint" command causes a call to the no-op
         3506  +	 ** routine named test_breakpoint().
         3507  +	 */
         3508  +    if (c == 'b' && n >= 3 && strncmp (azArg[0], "breakpoint", n) == 0)
         3509  +      {
         3510  +	  test_breakpoint ();
         3511  +      }
         3512  +    else if (c == 'd' && n > 1 && strncmp (azArg[0], "databases", n) == 0
         3513  +	     && nArg == 1)
         3514  +      {
         3515  +	  struct callback_data data;
         3516  +	  char *zErrMsg = 0;
         3517  +	  open_db (p);
         3518  +	  memcpy (&data, p, sizeof (data));
         3519  +	  data.showHeader = 1;
         3520  +	  data.mode = MODE_Column;
         3521  +	  data.colWidth[0] = 3;
         3522  +	  data.colWidth[1] = 15;
         3523  +	  data.colWidth[2] = 58;
         3524  +	  data.cnt = 0;
         3525  +	  sqlite3_exec (p->db, "PRAGMA database_list; ", callback, &data,
         3526  +			&zErrMsg);
         3527  +	  if (zErrMsg)
         3528  +	    {
         3529  +		fprintf (stderr, "Error: %s\n", zErrMsg);
         3530  +		sqlite3_free (zErrMsg);
         3531  +		rc = 1;
         3532  +	    }
         3533  +      }
         3534  +    else if (c == 'd' && strncmp (azArg[0], "dump", n) == 0 && nArg < 3)
         3535  +      {
         3536  +	  open_db (p);
         3537  +	  /* When playing back a "dump", the content might appear in an order
         3538  +	   ** which causes immediate foreign key constraints to be violated.
         3539  +	   ** So disable foreign-key constraint enforcement to prevent problems. */
         3540  +	  fprintf (p->out, "PRAGMA foreign_keys=OFF;\n");
         3541  +	  fprintf (p->out, "BEGIN TRANSACTION;\n");
         3542  +	  p->writableSchema = 0;
         3543  +	  sqlite3_exec (p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0,
         3544  +			0, 0);
         3545  +	  p->nErr = 0;
         3546  +	  if (nArg == 1)
         3547  +	    {
         3548  +		run_schema_dump_query (p,
         3549  +				       "SELECT name, type, sql FROM sqlite_master "
         3550  +				       "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'");
         3551  +		run_schema_dump_query (p,
         3552  +				       "SELECT name, type, sql FROM sqlite_master "
         3553  +				       "WHERE name=='sqlite_sequence'");
         3554  +		run_table_dump_query (p,
         3555  +				      "SELECT sql FROM sqlite_master "
         3556  +				      "WHERE sql NOT NULL AND type IN ('index','trigger','view')",
         3557  +				      0);
         3558  +	    }
         3559  +	  else
         3560  +	    {
         3561  +		int i;
         3562  +		for (i = 1; i < nArg; i++)
         3563  +		  {
         3564  +		      zShellStatic = azArg[i];
         3565  +		      run_schema_dump_query (p,
         3566  +					     "SELECT name, type, sql FROM sqlite_master "
         3567  +					     "WHERE tbl_name LIKE shellstatic() AND type=='table'"
         3568  +					     "  AND sql NOT NULL");
         3569  +		      run_table_dump_query (p,
         3570  +					    "SELECT sql FROM sqlite_master "
         3571  +					    "WHERE sql NOT NULL"
         3572  +					    "  AND type IN ('index','trigger','view')"
         3573  +					    "  AND tbl_name LIKE shellstatic()",
         3574  +					    0);
         3575  +		      zShellStatic = 0;
         3576  +		  }
         3577  +	    }
         3578  +	  if (p->writableSchema)
         3579  +	    {
         3580  +		fprintf (p->out, "PRAGMA writable_schema=OFF;\n");
         3581  +		p->writableSchema = 0;
         3582  +	    }
         3583  +	  sqlite3_exec (p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
         3584  +	  sqlite3_exec (p->db, "RELEASE dump;", 0, 0, 0);
         3585  +	  fprintf (p->out,
         3586  +		   p->nErr ? "ROLLBACK; -- due to errors\n" : "COMMIT;\n");
         3587  +      }
         3588  +    else if (c == 'e' && strncmp (azArg[0], "echo", n) == 0 && nArg > 1
         3589  +	     && nArg < 3)
         3590  +      {
         3591  +	  p->echoOn = booleanValue (azArg[1]);
         3592  +      }
         3593  +    else if (c == 'e' && strncmp (azArg[0], "exit", n) == 0 && nArg == 1)
         3594  +      {
         3595  +	  rc = 2;
         3596  +      }
         3597  +    else if (c == 'e' && strncmp (azArg[0], "explain", n) == 0 && nArg < 3)
         3598  +      {
         3599  +	  int val = nArg >= 2 ? booleanValue (azArg[1]) : 1;
         3600  +	  if (val == 1)
         3601  +	    {
         3602  +		if (!p->explainPrev.valid)
         3603  +		  {
         3604  +		      p->explainPrev.valid = 1;
         3605  +		      p->explainPrev.mode = p->mode;
         3606  +		      p->explainPrev.showHeader = p->showHeader;
         3607  +		      memcpy (p->explainPrev.colWidth, p->colWidth,
         3608  +			      sizeof (p->colWidth));
         3609  +		  }
         3610  +		/* We could put this code under the !p->explainValid
         3611  +		 ** condition so that it does not execute if we are already in
         3612  +		 ** explain mode. However, always executing it allows us an easy
         3613  +		 ** was to reset to explain mode in case the user previously
         3614  +		 ** did an .explain followed by a .width, .mode or .header
         3615  +		 ** command.
         3616  +		 */
         3617  +		p->mode = MODE_Explain;
         3618  +		p->showHeader = 1;
         3619  +		memset (p->colWidth, 0, ArraySize (p->colWidth));
         3620  +		p->colWidth[0] = 4;	/* addr */
         3621  +		p->colWidth[1] = 13;	/* opcode */
         3622  +		p->colWidth[2] = 4;	/* P1 */
         3623  +		p->colWidth[3] = 4;	/* P2 */
         3624  +		p->colWidth[4] = 4;	/* P3 */
         3625  +		p->colWidth[5] = 13;	/* P4 */
         3626  +		p->colWidth[6] = 2;	/* P5 */
         3627  +		p->colWidth[7] = 13;	/* Comment */
         3628  +	    }
         3629  +	  else if (p->explainPrev.valid)
         3630  +	    {
         3631  +		p->explainPrev.valid = 0;
         3632  +		p->mode = p->explainPrev.mode;
         3633  +		p->showHeader = p->explainPrev.showHeader;
         3634  +		memcpy (p->colWidth, p->explainPrev.colWidth,
         3635  +			sizeof (p->colWidth));
         3636  +	    }
         3637  +      }
         3638  +    else if (c == 'h' && (strncmp (azArg[0], "header", n) == 0 ||
         3639  +			  strncmp (azArg[0], "headers", n) == 0) && nArg > 1
         3640  +	     && nArg < 3)
         3641  +      {
         3642  +	  p->showHeader = booleanValue (azArg[1]);
         3643  +      }
         3644  +    else if (c == 'h' && strncmp (azArg[0], "help", n) == 0)
         3645  +      {
         3646  +	  fprintf (stderr, "%s", zHelp);
         3647  +	  if (HAS_TIMER)
         3648  +	    {
         3649  +		fprintf (stderr, "%s", zTimerHelp);
         3650  +	    }
         3651  +      }
         3652  +    else if (c == 'i' && strncmp (azArg[0], "import", n) == 0 && nArg == 3)
         3653  +      {
         3654  +	  char *zTable = azArg[2];	/* Insert data into this table */
         3655  +	  char *zFile = azArg[1];	/* The file from which to extract data */
         3656  +	  sqlite3_stmt *pStmt = NULL;	/* A statement */
         3657  +	  int nCol;		/* Number of columns in the table */
         3658  +	  int nByte;		/* Number of bytes in an SQL string */
         3659  +	  int i, j;		/* Loop counters */
         3660  +	  int nSep;		/* Number of bytes in p->separator[] */
         3661  +	  char *zSql;		/* An SQL statement */
         3662  +	  char *zLine;		/* A single line of input from the file */
         3663  +	  char **azCol;		/* zLine[] broken up into columns */
         3664  +	  char *zCommit;	/* How to commit changes */
         3665  +	  FILE *in;		/* The input file */
         3666  +	  int lineno = 0;	/* Line number of input file */
         3667  +
         3668  +	  open_db (p);
         3669  +	  nSep = strlen30 (p->separator);
         3670  +	  if (nSep == 0)
         3671  +	    {
         3672  +		fprintf (stderr,
         3673  +			 "Error: non-null separator required for import\n");
         3674  +		return 1;
         3675  +	    }
         3676  +	  zSql = sqlite3_mprintf ("SELECT * FROM %s", zTable);
         3677  +	  if (zSql == 0)
         3678  +	    {
         3679  +		fprintf (stderr, "Error: out of memory\n");
         3680  +		return 1;
         3681  +	    }
         3682  +	  nByte = strlen30 (zSql);
         3683  +	  rc = sqlite3_prepare (p->db, zSql, -1, &pStmt, 0);
         3684  +	  sqlite3_free (zSql);
         3685  +	  if (rc)
         3686  +	    {
         3687  +		if (pStmt)
         3688  +		    sqlite3_finalize (pStmt);
         3689  +		fprintf (stderr, "Error: %s\n", sqlite3_errmsg (db));
         3690  +		return 1;
         3691  +	    }
         3692  +	  nCol = sqlite3_column_count (pStmt);
         3693  +	  sqlite3_finalize (pStmt);
         3694  +	  pStmt = 0;
         3695  +	  if (nCol == 0)
         3696  +	      return 0;		/* no columns, no error */
         3697  +	  zSql = malloc (nByte + 20 + nCol * 2);
         3698  +	  if (zSql == 0)
         3699  +	    {
         3700  +		fprintf (stderr, "Error: out of memory\n");
         3701  +		return 1;
         3702  +	    }
         3703  +	  sqlite3_snprintf (nByte + 20, zSql, "INSERT INTO %s VALUES(?",
         3704  +			    zTable);
         3705  +	  j = strlen30 (zSql);
         3706  +	  for (i = 1; i < nCol; i++)
         3707  +	    {
         3708  +		zSql[j++] = ',';
         3709  +		zSql[j++] = '?';
         3710  +	    }
         3711  +	  zSql[j++] = ')';
         3712  +	  zSql[j] = 0;
         3713  +	  rc = sqlite3_prepare (p->db, zSql, -1, &pStmt, 0);
         3714  +	  free (zSql);
         3715  +	  if (rc)
         3716  +	    {
         3717  +		fprintf (stderr, "Error: %s\n", sqlite3_errmsg (db));
         3718  +		if (pStmt)
         3719  +		    sqlite3_finalize (pStmt);
         3720  +		return 1;
         3721  +	    }
         3722  +	  in = fopen (zFile, "rb");
         3723  +	  if (in == 0)
         3724  +	    {
         3725  +		fprintf (stderr, "Error: cannot open \"%s\"\n", zFile);
         3726  +		sqlite3_finalize (pStmt);
         3727  +		return 1;
         3728  +	    }
         3729  +	  azCol = malloc (sizeof (azCol[0]) * (nCol + 1));
         3730  +	  if (azCol == 0)
         3731  +	    {
         3732  +		fprintf (stderr, "Error: out of memory\n");
         3733  +		fclose (in);
         3734  +		sqlite3_finalize (pStmt);
         3735  +		return 1;
         3736  +	    }
         3737  +	  sqlite3_exec (p->db, "BEGIN", 0, 0, 0);
         3738  +	  zCommit = "COMMIT";
         3739  +	  while ((zLine = local_getline (0, in, 1)) != 0)
         3740  +	    {
         3741  +		char *z, c;
         3742  +		int inQuote = 0;
         3743  +		lineno++;
         3744  +		azCol[0] = zLine;
         3745  +		for (i = 0, z = zLine; (c = *z) != 0; z++)
         3746  +		  {
         3747  +		      if (c == '"')
         3748  +			  inQuote = !inQuote;
         3749  +		      if (c == '\n')
         3750  +			  lineno++;
         3751  +		      if (!inQuote && c == p->separator[0]
         3752  +			  && strncmp (z, p->separator, nSep) == 0)
         3753  +			{
         3754  +			    *z = 0;
         3755  +			    i++;
         3756  +			    if (i < nCol)
         3757  +			      {
         3758  +				  azCol[i] = &z[nSep];
         3759  +				  z += nSep - 1;
         3760  +			      }
         3761  +			}
         3762  +		  }		/* end for */
         3763  +		*z = 0;
         3764  +		if (i + 1 != nCol)
         3765  +		  {
         3766  +		      fprintf (stderr,
         3767  +			       "Error: %s line %d: expected %d columns of data but found %d\n",
         3768  +			       zFile, lineno, nCol, i + 1);
         3769  +		      zCommit = "ROLLBACK";
         3770  +		      free (zLine);
         3771  +		      rc = 1;
         3772  +		      break;	/* from while */
         3773  +		  }
         3774  +		for (i = 0; i < nCol; i++)
         3775  +		  {
         3776  +		      if (azCol[i][0] == '"')
         3777  +			{
         3778  +			    int k;
         3779  +			    for (z = azCol[i], j = 1, k = 0; z[j]; j++)
         3780  +			      {
         3781  +				  if (z[j] == '"')
         3782  +				    {
         3783  +					j++;
         3784  +					if (z[j] == 0)
         3785  +					    break;
         3786  +				    }
         3787  +				  z[k++] = z[j];
         3788  +			      }
         3789  +			    z[k] = 0;
         3790  +			}
         3791  +		      sqlite3_bind_text (pStmt, i + 1, azCol[i], -1,
         3792  +					 SQLITE_STATIC);
         3793  +		  }
         3794  +		sqlite3_step (pStmt);
         3795  +		rc = sqlite3_reset (pStmt);
         3796  +		free (zLine);
         3797  +		if (rc != SQLITE_OK)
         3798  +		  {
         3799  +		      fprintf (stderr, "Error: %s\n", sqlite3_errmsg (db));
         3800  +		      zCommit = "ROLLBACK";
         3801  +		      rc = 1;
         3802  +		      break;	/* from while */
         3803  +		  }
         3804  +	    }			/* end while */
         3805  +	  free (azCol);
         3806  +	  fclose (in);
         3807  +	  sqlite3_finalize (pStmt);
         3808  +	  sqlite3_exec (p->db, zCommit, 0, 0, 0);
         3809  +      }
         3810  +    else if (c == 'i' && strncmp (azArg[0], "indices", n) == 0 && nArg < 3)
         3811  +      {
         3812  +	  struct callback_data data;
         3813  +	  char *zErrMsg = 0;
         3814  +	  open_db (p);
         3815  +	  memcpy (&data, p, sizeof (data));
         3816  +	  data.showHeader = 0;
         3817  +	  data.mode = MODE_List;
         3818  +	  if (nArg == 1)
         3819  +	    {
         3820  +		rc = sqlite3_exec (p->db,
         3821  +				   "SELECT name FROM sqlite_master "
         3822  +				   "WHERE type='index' AND name NOT LIKE 'sqlite_%' "
         3823  +				   "UNION ALL "
         3824  +				   "SELECT name FROM sqlite_temp_master "
         3825  +				   "WHERE type='index' "
         3826  +				   "ORDER BY 1", callback, &data, &zErrMsg);
         3827  +	    }
         3828  +	  else
         3829  +	    {
         3830  +		zShellStatic = azArg[1];
         3831  +		rc = sqlite3_exec (p->db,
         3832  +				   "SELECT name FROM sqlite_master "
         3833  +				   "WHERE type='index' AND tbl_name LIKE shellstatic() "
         3834  +				   "UNION ALL "
         3835  +				   "SELECT name FROM sqlite_temp_master "
         3836  +				   "WHERE type='index' AND tbl_name LIKE shellstatic() "
         3837  +				   "ORDER BY 1", callback, &data, &zErrMsg);
         3838  +		zShellStatic = 0;
         3839  +	    }
         3840  +	  if (zErrMsg)
         3841  +	    {
         3842  +		fprintf (stderr, "Error: %s\n", zErrMsg);
         3843  +		sqlite3_free (zErrMsg);
         3844  +		rc = 1;
         3845  +	    }
         3846  +	  else if (rc != SQLITE_OK)
         3847  +	    {
         3848  +		fprintf (stderr,
         3849  +			 "Error: querying sqlite_master and sqlite_temp_master\n");
         3850  +		rc = 1;
         3851  +	    }
         3852  +      }
         3853  +    else
  3215   3854   #ifdef SQLITE_ENABLE_IOTRACE
  3216         -  if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
  3217         -    extern void (*sqlite3IoTrace)(const char*, ...);
  3218         -    if( iotrace && iotrace!=stdout ) fclose(iotrace);
  3219         -    iotrace = 0;
  3220         -    if( nArg<2 ){
  3221         -      sqlite3IoTrace = 0;
  3222         -    }else if( strcmp(azArg[1], "-")==0 ){
  3223         -      sqlite3IoTrace = iotracePrintf;
  3224         -      iotrace = stdout;
  3225         -    }else{
  3226         -      iotrace = fopen(azArg[1], "w");
  3227         -      if( iotrace==0 ){
  3228         -        fprintf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
  3229         -        sqlite3IoTrace = 0;
  3230         -        rc = 1;
  3231         -      }else{
  3232         -        sqlite3IoTrace = iotracePrintf;
  3233         -      }
  3234         -    }
  3235         -  }else
  3236         -#endif
  3237         -
  3238         -  if( c=='l' && strncmp(azArg[0], "log", n)==0 && nArg>=2 ){
  3239         -    const char *zFile = azArg[1];
  3240         -    output_file_close(p->pLog);
  3241         -    p->pLog = output_file_open(zFile);
  3242         -  }else
  3243         -
  3244         -  if( c=='m' && strncmp(azArg[0], "mode", n)==0 && nArg==2 ){
  3245         -    int n2 = strlen30(azArg[1]);
  3246         -    if( (n2==4 && strncmp(azArg[1],"line",n2)==0)
  3247         -        ||
  3248         -        (n2==5 && strncmp(azArg[1],"lines",n2)==0) ){
  3249         -      p->mode = MODE_Line;
  3250         -    }else if( (n2==6 && strncmp(azArg[1],"column",n2)==0)
  3251         -              ||
  3252         -              (n2==7 && strncmp(azArg[1],"columns",n2)==0) ){
  3253         -      p->mode = MODE_Column;
  3254         -    }else if( n2==4 && strncmp(azArg[1],"list",n2)==0 ){
  3255         -      p->mode = MODE_List;
  3256         -    }else if( n2==4 && strncmp(azArg[1],"html",n2)==0 ){
  3257         -      p->mode = MODE_Html;
  3258         -    }else if( n2==3 && strncmp(azArg[1],"tcl",n2)==0 ){
  3259         -      p->mode = MODE_Tcl;
  3260         -    }else if( n2==3 && strncmp(azArg[1],"csv",n2)==0 ){
  3261         -      p->mode = MODE_Csv;
  3262         -      sqlite3_snprintf(sizeof(p->separator), p->separator, ",");
  3263         -    }else if( n2==4 && strncmp(azArg[1],"tabs",n2)==0 ){
  3264         -      p->mode = MODE_List;
  3265         -      sqlite3_snprintf(sizeof(p->separator), p->separator, "\t");
  3266         -    }else if( n2==6 && strncmp(azArg[1],"insert",n2)==0 ){
  3267         -      p->mode = MODE_Insert;
  3268         -      set_table_name(p, "table");
  3269         -    }else {
  3270         -      fprintf(stderr,"Error: mode should be one of: "
  3271         -         "column csv html insert line list tabs tcl\n");
  3272         -      rc = 1;
  3273         -    }
  3274         -  }else
  3275         -
  3276         -  if( c=='m' && strncmp(azArg[0], "mode", n)==0 && nArg==3 ){
  3277         -    int n2 = strlen30(azArg[1]);
  3278         -    if( n2==6 && strncmp(azArg[1],"insert",n2)==0 ){
  3279         -      p->mode = MODE_Insert;
  3280         -      set_table_name(p, azArg[2]);
  3281         -    }else {
  3282         -      fprintf(stderr, "Error: invalid arguments: "
  3283         -        " \"%s\". Enter \".help\" for help\n", azArg[2]);
  3284         -      rc = 1;
  3285         -    }
  3286         -  }else
  3287         -
  3288         -  if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 && nArg==2 ) {
  3289         -    sqlite3_snprintf(sizeof(p->nullvalue), p->nullvalue,
  3290         -                     "%.*s", (int)ArraySize(p->nullvalue)-1, azArg[1]);
  3291         -  }else
  3292         -
  3293         -  if( c=='o' && strncmp(azArg[0], "output", n)==0 && nArg==2 ){
  3294         -    if( p->outfile[0]=='|' ){
  3295         -      pclose(p->out);
  3296         -    }else{
  3297         -      output_file_close(p->out);
  3298         -    }
  3299         -    p->outfile[0] = 0;
  3300         -    if( azArg[1][0]=='|' ){
  3301         -      p->out = popen(&azArg[1][1], "w");
  3302         -      if( p->out==0 ){
  3303         -        fprintf(stderr,"Error: cannot open pipe \"%s\"\n", &azArg[1][1]);
  3304         -        p->out = stdout;
  3305         -        rc = 1;
  3306         -      }else{
  3307         -        sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", azArg[1]);
  3308         -      }
  3309         -    }else{
  3310         -      p->out = output_file_open(azArg[1]);
  3311         -      if( p->out==0 ){
  3312         -        if( strcmp(azArg[1],"off")!=0 ){
  3313         -          fprintf(stderr,"Error: cannot write to \"%s\"\n", azArg[1]);
  3314         -        }
  3315         -        p->out = stdout;
  3316         -        rc = 1;
  3317         -      } else {
  3318         -        sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", azArg[1]);
  3319         -      }
  3320         -    }
  3321         -  }else
  3322         -
  3323         -  if( c=='p' && strncmp(azArg[0], "prompt", n)==0 && (nArg==2 || nArg==3)){
  3324         -    if( nArg >= 2) {
  3325         -      strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
  3326         -    }
  3327         -    if( nArg >= 3) {
  3328         -      strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
  3329         -    }
  3330         -  }else
  3331         -
  3332         -  if( c=='q' && strncmp(azArg[0], "quit", n)==0 && nArg==1 ){
  3333         -    rc = 2;
  3334         -  }else
  3335         -
  3336         -  if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 && nArg==2 ){
  3337         -    FILE *alt = fopen(azArg[1], "rb");
  3338         -    if( alt==0 ){
  3339         -      fprintf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
  3340         -      rc = 1;
  3341         -    }else{
  3342         -      rc = process_input(p, alt, 0);
  3343         -      fclose(alt);
  3344         -    }
  3345         -  }else
  3346         -
  3347         -  if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 && nArg>1 && nArg<4){
  3348         -    const char *zSrcFile;
  3349         -    const char *zDb;
  3350         -    sqlite3 *pSrc;
  3351         -    sqlite3_backup *pBackup;
  3352         -    int nTimeout = 0;
  3353         -
  3354         -    if( nArg==2 ){
  3355         -      zSrcFile = azArg[1];
  3356         -      zDb = "main";
  3357         -    }else{
  3358         -      zSrcFile = azArg[2];
  3359         -      zDb = azArg[1];
  3360         -    }
  3361         -    rc = sqlite3_open(zSrcFile, &pSrc);
  3362         -    if( rc!=SQLITE_OK ){
  3363         -      fprintf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
  3364         -      sqlite3_close(pSrc);
  3365         -      return 1;
  3366         -    }
  3367         -    open_db(p);
  3368         -    pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
  3369         -    if( pBackup==0 ){
  3370         -      fprintf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
  3371         -      sqlite3_close(pSrc);
  3372         -      return 1;
  3373         -    }
  3374         -    while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
  3375         -          || rc==SQLITE_BUSY  ){
  3376         -      if( rc==SQLITE_BUSY ){
  3377         -        if( nTimeout++ >= 3 ) break;
  3378         -        sqlite3_sleep(100);
  3379         -      }
  3380         -    }
  3381         -    sqlite3_backup_finish(pBackup);
  3382         -    if( rc==SQLITE_DONE ){
  3383         -      rc = 0;
  3384         -    }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
  3385         -      fprintf(stderr, "Error: source database is busy\n");
  3386         -      rc = 1;
  3387         -    }else{
  3388         -      fprintf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
  3389         -      rc = 1;
  3390         -    }
  3391         -    sqlite3_close(pSrc);
  3392         -  }else
  3393         -
  3394         -  if( c=='s' && strncmp(azArg[0], "schema", n)==0 && nArg<3 ){
  3395         -    struct callback_data data;
  3396         -    char *zErrMsg = 0;
  3397         -    open_db(p);
  3398         -    memcpy(&data, p, sizeof(data));
  3399         -    data.showHeader = 0;
  3400         -    data.mode = MODE_Semi;
  3401         -    if( nArg>1 ){
  3402         -      int i;
  3403         -      for(i=0; azArg[1][i]; i++) azArg[1][i] = ToLower(azArg[1][i]);
  3404         -      if( strcmp(azArg[1],"sqlite_master")==0 ){
  3405         -        char *new_argv[2], *new_colv[2];
  3406         -        new_argv[0] = "CREATE TABLE sqlite_master (\n"
  3407         -                      "  type text,\n"
  3408         -                      "  name text,\n"
  3409         -                      "  tbl_name text,\n"
  3410         -                      "  rootpage integer,\n"
  3411         -                      "  sql text\n"
  3412         -                      ")";
  3413         -        new_argv[1] = 0;
  3414         -        new_colv[0] = "sql";
  3415         -        new_colv[1] = 0;
  3416         -        callback(&data, 1, new_argv, new_colv);
  3417         -        rc = SQLITE_OK;
  3418         -      }else if( strcmp(azArg[1],"sqlite_temp_master")==0 ){
  3419         -        char *new_argv[2], *new_colv[2];
  3420         -        new_argv[0] = "CREATE TEMP TABLE sqlite_temp_master (\n"
  3421         -                      "  type text,\n"
  3422         -                      "  name text,\n"
  3423         -                      "  tbl_name text,\n"
  3424         -                      "  rootpage integer,\n"
  3425         -                      "  sql text\n"
  3426         -                      ")";
  3427         -        new_argv[1] = 0;
  3428         -        new_colv[0] = "sql";
  3429         -        new_colv[1] = 0;
  3430         -        callback(&data, 1, new_argv, new_colv);
  3431         -        rc = SQLITE_OK;
  3432         -      }else{
  3433         -        zShellStatic = azArg[1];
  3434         -        rc = sqlite3_exec(p->db,
  3435         -          "SELECT sql FROM "
  3436         -          "  (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
  3437         -          "     FROM sqlite_master UNION ALL"
  3438         -          "   SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
  3439         -          "WHERE lower(tbl_name) LIKE shellstatic()"
  3440         -          "  AND type!='meta' AND sql NOTNULL "
  3441         -          "ORDER BY substr(type,2,1), "
  3442         -                  " CASE type WHEN 'view' THEN rowid ELSE name END",
  3443         -          callback, &data, &zErrMsg);
  3444         -        zShellStatic = 0;
  3445         -      }
  3446         -    }else{
  3447         -      rc = sqlite3_exec(p->db,
  3448         -         "SELECT sql FROM "
  3449         -         "  (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
  3450         -         "     FROM sqlite_master UNION ALL"
  3451         -         "   SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
  3452         -         "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%'"
  3453         -         "ORDER BY substr(type,2,1),"
  3454         -                  " CASE type WHEN 'view' THEN rowid ELSE name END",
  3455         -         callback, &data, &zErrMsg
  3456         -      );
  3457         -    }
  3458         -    if( zErrMsg ){
  3459         -      fprintf(stderr,"Error: %s\n", zErrMsg);
  3460         -      sqlite3_free(zErrMsg);
  3461         -      rc = 1;
  3462         -    }else if( rc != SQLITE_OK ){
  3463         -      fprintf(stderr,"Error: querying schema information\n");
  3464         -      rc = 1;
  3465         -    }else{
  3466         -      rc = 0;
  3467         -    }
  3468         -  }else
  3469         -
  3470         -  if( c=='s' && strncmp(azArg[0], "separator", n)==0 && nArg==2 ){
  3471         -    sqlite3_snprintf(sizeof(p->separator), p->separator,
  3472         -                     "%.*s", (int)sizeof(p->separator)-1, azArg[1]);
  3473         -  }else
  3474         -
  3475         -  if( c=='s'
  3476         -   && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
  3477         -  ){
  3478         -    char *zCmd;
  3479         -    int i;
  3480         -    if( nArg<2 ){
  3481         -      fprintf(stderr, "Usage: .system COMMAND\n");
  3482         -      rc = 1;
  3483         -    }
  3484         -    else {
  3485         -      zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
  3486         -      for(i=2; i<nArg; i++){
  3487         -        zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
  3488         -                               zCmd, azArg[i]);
  3489         -      }
  3490         -      (void)system(zCmd);
  3491         -      sqlite3_free(zCmd);
  3492         -    }
  3493         -  }else
  3494         -
  3495         -
  3496         -  if( c=='s' && strncmp(azArg[0], "show", n)==0 && nArg==1 ){
  3497         -    int i;
  3498         -    fprintf(p->out,"%9.9s: %s\n","echo", p->echoOn ? "on" : "off");
  3499         -    fprintf(p->out,"%9.9s: %s\n","explain", p->explainPrev.valid ? "on" :"off");
  3500         -    fprintf(p->out,"%9.9s: %s\n","headers", p->showHeader ? "on" : "off");
  3501         -    fprintf(p->out,"%9.9s: %s\n","mode", modeDescr[p->mode]);
  3502         -    fprintf(p->out,"%9.9s: ", "nullvalue");
  3503         -      output_c_string(p->out, p->nullvalue);
  3504         -      fprintf(p->out, "\n");
  3505         -    fprintf(p->out,"%9.9s: %s\n","output",
  3506         -            strlen30(p->outfile) ? p->outfile : "stdout");
  3507         -    fprintf(p->out,"%9.9s: ", "separator");
  3508         -      output_c_string(p->out, p->separator);
  3509         -      fprintf(p->out, "\n");
  3510         -    fprintf(p->out,"%9.9s: %s\n","stats", p->statsOn ? "on" : "off");
  3511         -    fprintf(p->out,"%9.9s: ","width");
  3512         -    for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) {
  3513         -      fprintf(p->out,"%d ",p->colWidth[i]);
  3514         -    }
  3515         -    fprintf(p->out,"\n");
  3516         -  }else
  3517         -
  3518         -  if( c=='s' && strncmp(azArg[0], "stats", n)==0 && nArg>1 && nArg<3 ){
  3519         -    p->statsOn = booleanValue(azArg[1]);
  3520         -  }else
  3521         -
  3522         -  if( c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0 && nArg<3 ){
  3523         -    sqlite3_stmt *pStmt;
  3524         -    char **azResult;
  3525         -    int nRow, nAlloc;
  3526         -    char *zSql = 0;
  3527         -    int ii;
  3528         -    open_db(p);
  3529         -    rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
  3530         -    if( rc ) return rc;
  3531         -    zSql = sqlite3_mprintf(
  3532         -        "SELECT name FROM sqlite_master"
  3533         -        " WHERE type IN ('table','view')"
  3534         -        "   AND name NOT LIKE 'sqlite_%%'"
  3535         -        "   AND name LIKE ?1");
  3536         -    while( sqlite3_step(pStmt)==SQLITE_ROW ){
  3537         -      const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
  3538         -      if( zDbName==0 || strcmp(zDbName,"main")==0 ) continue;
  3539         -      if( strcmp(zDbName,"temp")==0 ){
  3540         -        zSql = sqlite3_mprintf(
  3541         -                 "%z UNION ALL "
  3542         -                 "SELECT 'temp.' || name FROM sqlite_temp_master"
  3543         -                 " WHERE type IN ('table','view')"
  3544         -                 "   AND name NOT LIKE 'sqlite_%%'"
  3545         -                 "   AND name LIKE ?1", zSql);
  3546         -      }else{
  3547         -        zSql = sqlite3_mprintf(
  3548         -                 "%z UNION ALL "
  3549         -                 "SELECT '%q.' || name FROM \"%w\".sqlite_master"
  3550         -                 " WHERE type IN ('table','view')"
  3551         -                 "   AND name NOT LIKE 'sqlite_%%'"
  3552         -                 "   AND name LIKE ?1", zSql, zDbName, zDbName);
  3553         -      }
  3554         -    }
  3555         -    sqlite3_finalize(pStmt);
  3556         -    zSql = sqlite3_mprintf("%z ORDER BY 1", zSql);
  3557         -    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  3558         -    sqlite3_free(zSql);
  3559         -    if( rc ) return rc;
  3560         -    nRow = nAlloc = 0;
  3561         -    azResult = 0;
  3562         -    if( nArg>1 ){
  3563         -      sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
  3564         -    }else{
  3565         -      sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
  3566         -    }
  3567         -    while( sqlite3_step(pStmt)==SQLITE_ROW ){
  3568         -      if( nRow>=nAlloc ){
  3569         -        char **azNew;
  3570         -        int n = nAlloc*2 + 10;
  3571         -        azNew = sqlite3_realloc(azResult, sizeof(azResult[0])*n);
  3572         -        if( azNew==0 ){
  3573         -          fprintf(stderr, "Error: out of memory\n");
  3574         -          break;
  3575         -        }
  3576         -        nAlloc = n;
  3577         -        azResult = azNew;
  3578         -      }
  3579         -      azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
  3580         -      if( azResult[nRow] ) nRow++;
  3581         -    }
  3582         -    sqlite3_finalize(pStmt);        
  3583         -    if( nRow>0 ){
  3584         -      int len, maxlen = 0;
  3585         -      int i, j;
  3586         -      int nPrintCol, nPrintRow;
  3587         -      for(i=0; i<nRow; i++){
  3588         -        len = strlen30(azResult[i]);
  3589         -        if( len>maxlen ) maxlen = len;
  3590         -      }
  3591         -      nPrintCol = 80/(maxlen+2);
  3592         -      if( nPrintCol<1 ) nPrintCol = 1;
  3593         -      nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
  3594         -      for(i=0; i<nPrintRow; i++){
  3595         -        for(j=i; j<nRow; j+=nPrintRow){
  3596         -          char *zSp = j<nPrintRow ? "" : "  ";
  3597         -          printf("%s%-*s", zSp, maxlen, azResult[j] ? azResult[j] : "");
  3598         -        }
  3599         -        printf("\n");
  3600         -      }
  3601         -    }
  3602         -    for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
  3603         -    sqlite3_free(azResult);
  3604         -  }else
  3605         -
  3606         -  if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 && nArg>=2 ){
  3607         -    static const struct {
  3608         -       const char *zCtrlName;   /* Name of a test-control option */
  3609         -       int ctrlCode;            /* Integer code for that option */
  3610         -    } aCtrl[] = {
  3611         -      { "prng_save",             SQLITE_TESTCTRL_PRNG_SAVE              },
  3612         -      { "prng_restore",          SQLITE_TESTCTRL_PRNG_RESTORE           },
  3613         -      { "prng_reset",            SQLITE_TESTCTRL_PRNG_RESET             },
  3614         -      { "bitvec_test",           SQLITE_TESTCTRL_BITVEC_TEST            },
  3615         -      { "fault_install",         SQLITE_TESTCTRL_FAULT_INSTALL          },
  3616         -      { "benign_malloc_hooks",   SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS    },
  3617         -      { "pending_byte",          SQLITE_TESTCTRL_PENDING_BYTE           },
  3618         -      { "assert",                SQLITE_TESTCTRL_ASSERT                 },
  3619         -      { "always",                SQLITE_TESTCTRL_ALWAYS                 },
  3620         -      { "reserve",               SQLITE_TESTCTRL_RESERVE                },
  3621         -      { "optimizations",         SQLITE_TESTCTRL_OPTIMIZATIONS          },
  3622         -      { "iskeyword",             SQLITE_TESTCTRL_ISKEYWORD              },
  3623         -      { "scratchmalloc",         SQLITE_TESTCTRL_SCRATCHMALLOC          },
  3624         -    };
  3625         -    int testctrl = -1;
  3626         -    int rc = 0;
  3627         -    int i, n;
  3628         -    open_db(p);
  3629         -
  3630         -    /* convert testctrl text option to value. allow any unique prefix
  3631         -    ** of the option name, or a numerical value. */
  3632         -    n = strlen30(azArg[1]);
  3633         -    for(i=0; i<(int)(sizeof(aCtrl)/sizeof(aCtrl[0])); i++){
  3634         -      if( strncmp(azArg[1], aCtrl[i].zCtrlName, n)==0 ){
  3635         -        if( testctrl<0 ){
  3636         -          testctrl = aCtrl[i].ctrlCode;
  3637         -        }else{
  3638         -          fprintf(stderr, "ambiguous option name: \"%s\"\n", azArg[1]);
  3639         -          testctrl = -1;
  3640         -          break;
  3641         -        }
  3642         -      }
  3643         -    }
  3644         -    if( testctrl<0 ) testctrl = atoi(azArg[1]);
  3645         -    if( (testctrl<SQLITE_TESTCTRL_FIRST) || (testctrl>SQLITE_TESTCTRL_LAST) ){
  3646         -      fprintf(stderr,"Error: invalid testctrl option: %s\n", azArg[1]);
  3647         -    }else{
  3648         -      switch(testctrl){
  3649         -
  3650         -        /* sqlite3_test_control(int, db, int) */
  3651         -        case SQLITE_TESTCTRL_OPTIMIZATIONS:
  3652         -        case SQLITE_TESTCTRL_RESERVE:             
  3653         -          if( nArg==3 ){
  3654         -            int opt = (int)strtol(azArg[2], 0, 0);        
  3655         -            rc = sqlite3_test_control(testctrl, p->db, opt);
  3656         -            printf("%d (0x%08x)\n", rc, rc);
  3657         -          } else {
  3658         -            fprintf(stderr,"Error: testctrl %s takes a single int option\n",
  3659         -                    azArg[1]);
  3660         -          }
  3661         -          break;
  3662         -
  3663         -        /* sqlite3_test_control(int) */
  3664         -        case SQLITE_TESTCTRL_PRNG_SAVE:           
  3665         -        case SQLITE_TESTCTRL_PRNG_RESTORE:        
  3666         -        case SQLITE_TESTCTRL_PRNG_RESET:
  3667         -          if( nArg==2 ){
  3668         -            rc = sqlite3_test_control(testctrl);
  3669         -            printf("%d (0x%08x)\n", rc, rc);
  3670         -          } else {
  3671         -            fprintf(stderr,"Error: testctrl %s takes no options\n", azArg[1]);
  3672         -          }
  3673         -          break;
  3674         -
  3675         -        /* sqlite3_test_control(int, uint) */
  3676         -        case SQLITE_TESTCTRL_PENDING_BYTE:        
  3677         -          if( nArg==3 ){
  3678         -            unsigned int opt = (unsigned int)atoi(azArg[2]);        
  3679         -            rc = sqlite3_test_control(testctrl, opt);
  3680         -            printf("%d (0x%08x)\n", rc, rc);
  3681         -          } else {
  3682         -            fprintf(stderr,"Error: testctrl %s takes a single unsigned"
  3683         -                           " int option\n", azArg[1]);
  3684         -          }
  3685         -          break;
  3686         -          
  3687         -        /* sqlite3_test_control(int, int) */
  3688         -        case SQLITE_TESTCTRL_ASSERT:              
  3689         -        case SQLITE_TESTCTRL_ALWAYS:              
  3690         -          if( nArg==3 ){
  3691         -            int opt = atoi(azArg[2]);        
  3692         -            rc = sqlite3_test_control(testctrl, opt);
  3693         -            printf("%d (0x%08x)\n", rc, rc);
  3694         -          } else {
  3695         -            fprintf(stderr,"Error: testctrl %s takes a single int option\n",
  3696         -                            azArg[1]);
  3697         -          }
  3698         -          break;
  3699         -
  3700         -        /* sqlite3_test_control(int, char *) */
         3855  +    if (c == 'i' && strncmp (azArg[0], "iotrace", n) == 0)
         3856  +      {
         3857  +	  extern void (*sqlite3IoTrace) (const char *, ...);
         3858  +	  if (iotrace && iotrace != stdout)
         3859  +	      fclose (iotrace);
         3860  +	  iotrace = 0;
         3861  +	  if (nArg < 2)
         3862  +	    {
         3863  +		sqlite3IoTrace = 0;
         3864  +	    }
         3865  +	  else if (strcmp (azArg[1], "-") == 0)
         3866  +	    {
         3867  +		sqlite3IoTrace = iotracePrintf;
         3868  +		iotrace = stdout;
         3869  +	    }
         3870  +	  else
         3871  +	    {
         3872  +		iotrace = fopen (azArg[1], "w");
         3873  +		if (iotrace == 0)
         3874  +		  {
         3875  +		      fprintf (stderr, "Error: cannot open \"%s\"\n", azArg[1]);
         3876  +		      sqlite3IoTrace = 0;
         3877  +		      rc = 1;
         3878  +		  }
         3879  +		else
         3880  +		  {
         3881  +		      sqlite3IoTrace = iotracePrintf;
         3882  +		  }
         3883  +	    }
         3884  +      }
         3885  +    else
         3886  +#endif
         3887  +
         3888  +    if (c == 'l' && strncmp (azArg[0], "log", n) == 0 && nArg >= 2)
         3889  +      {
         3890  +	  const char *zFile = azArg[1];
         3891  +	  output_file_close (p->pLog);
         3892  +	  p->pLog = output_file_open (zFile);
         3893  +      }
         3894  +    else if (c == 'm' && strncmp (azArg[0], "mode", n) == 0 && nArg == 2)
         3895  +      {
         3896  +	  int n2 = strlen30 (azArg[1]);
         3897  +	  if ((n2 == 4 && strncmp (azArg[1], "line", n2) == 0)
         3898  +	      || (n2 == 5 && strncmp (azArg[1], "lines", n2) == 0))
         3899  +	    {
         3900  +		p->mode = MODE_Line;
         3901  +	    }
         3902  +	  else if ((n2 == 6 && strncmp (azArg[1], "column", n2) == 0)
         3903  +		   || (n2 == 7 && strncmp (azArg[1], "columns", n2) == 0))
         3904  +	    {
         3905  +		p->mode = MODE_Column;
         3906  +	    }
         3907  +	  else if (n2 == 4 && strncmp (azArg[1], "list", n2) == 0)
         3908  +	    {
         3909  +		p->mode = MODE_List;
         3910  +	    }
         3911  +	  else if (n2 == 4 && strncmp (azArg[1], "html", n2) == 0)
         3912  +	    {
         3913  +		p->mode = MODE_Html;
         3914  +	    }
         3915  +	  else if (n2 == 3 && strncmp (azArg[1], "tcl", n2) == 0)
         3916  +	    {
         3917  +		p->mode = MODE_Tcl;
         3918  +	    }
         3919  +	  else if (n2 == 3 && strncmp (azArg[1], "csv", n2) == 0)
         3920  +	    {
         3921  +		p->mode = MODE_Csv;
         3922  +		sqlite3_snprintf (sizeof (p->separator), p->separator, ",");
         3923  +	    }
         3924  +	  else if (n2 == 4 && strncmp (azArg[1], "tabs", n2) == 0)
         3925  +	    {
         3926  +		p->mode = MODE_List;
         3927  +		sqlite3_snprintf (sizeof (p->separator), p->separator, "\t");
         3928  +	    }
         3929  +	  else if (n2 == 6 && strncmp (azArg[1], "insert", n2) == 0)
         3930  +	    {
         3931  +		p->mode = MODE_Insert;
         3932  +		set_table_name (p, "table");
         3933  +	    }
         3934  +	  else
         3935  +	    {
         3936  +		fprintf (stderr, "Error: mode should be one of: "
         3937  +			 "column csv html insert line list tabs tcl\n");
         3938  +		rc = 1;
         3939  +	    }
         3940  +      }
         3941  +    else if (c == 'm' && strncmp (azArg[0], "mode", n) == 0 && nArg == 3)
         3942  +      {
         3943  +	  int n2 = strlen30 (azArg[1]);
         3944  +	  if (n2 == 6 && strncmp (azArg[1], "insert", n2) == 0)
         3945  +	    {
         3946  +		p->mode = MODE_Insert;
         3947  +		set_table_name (p, azArg[2]);
         3948  +	    }
         3949  +	  else
         3950  +	    {
         3951  +		fprintf (stderr, "Error: invalid arguments: "
         3952  +			 " \"%s\". Enter \".help\" for help\n", azArg[2]);
         3953  +		rc = 1;
         3954  +	    }
         3955  +      }
         3956  +    else if (c == 'n' && strncmp (azArg[0], "nullvalue", n) == 0 && nArg == 2)
         3957  +      {
         3958  +	  sqlite3_snprintf (sizeof (p->nullvalue), p->nullvalue,
         3959  +			    "%.*s", (int) ArraySize (p->nullvalue) - 1,
         3960  +			    azArg[1]);
         3961  +      }
         3962  +    else if (c == 'o' && strncmp (azArg[0], "output", n) == 0 && nArg == 2)
         3963  +      {
         3964  +	  if (p->outfile[0] == '|')
         3965  +	    {
         3966  +		pclose (p->out);
         3967  +	    }
         3968  +	  else
         3969  +	    {
         3970  +		output_file_close (p->out);
         3971  +	    }
         3972  +	  p->outfile[0] = 0;
         3973  +	  if (azArg[1][0] == '|')
         3974  +	    {
         3975  +		p->out = popen (&azArg[1][1], "w");
         3976  +		if (p->out == 0)
         3977  +		  {
         3978  +		      fprintf (stderr, "Error: cannot open pipe \"%s\"\n",
         3979  +			       &azArg[1][1]);
         3980  +		      p->out = stdout;
         3981  +		      rc = 1;
         3982  +		  }
         3983  +		else
         3984  +		  {
         3985  +		      sqlite3_snprintf (sizeof (p->outfile), p->outfile, "%s",
         3986  +					azArg[1]);
         3987  +		  }
         3988  +	    }
         3989  +	  else
         3990  +	    {
         3991  +		p->out = output_file_open (azArg[1]);
         3992  +		if (p->out == 0)
         3993  +		  {
         3994  +		      if (strcmp (azArg[1], "off") != 0)
         3995  +			{
         3996  +			    fprintf (stderr, "Error: cannot write to \"%s\"\n",
         3997  +				     azArg[1]);
         3998  +			}
         3999  +		      p->out = stdout;
         4000  +		      rc = 1;
         4001  +		  }
         4002  +		else
         4003  +		  {
         4004  +		      sqlite3_snprintf (sizeof (p->outfile), p->outfile, "%s",
         4005  +					azArg[1]);
         4006  +		  }
         4007  +	    }
         4008  +      }
         4009  +    else if (c == 'p' && strncmp (azArg[0], "prompt", n) == 0
         4010  +	     && (nArg == 2 || nArg == 3))
         4011  +      {
         4012  +	  if (nArg >= 2)
         4013  +	    {
         4014  +		strncpy (mainPrompt, azArg[1],
         4015  +			 (int) ArraySize (mainPrompt) - 1);
         4016  +	    }
         4017  +	  if (nArg >= 3)
         4018  +	    {
         4019  +		strncpy (continuePrompt, azArg[2],
         4020  +			 (int) ArraySize (continuePrompt) - 1);
         4021  +	    }
         4022  +      }
         4023  +    else if (c == 'q' && strncmp (azArg[0], "quit", n) == 0 && nArg == 1)
         4024  +      {
         4025  +	  rc = 2;
         4026  +      }
         4027  +    else if (c == 'r' && n >= 3 && strncmp (azArg[0], "read", n) == 0
         4028  +	     && nArg > 0)
         4029  +      {
         4030  +	  FILE *alt = fopen (azArg[1], "rb");
         4031  +	  if (alt == 0)
         4032  +	    {
         4033  +		fprintf (stderr, "Error: cannot open \"%s\"\n", azArg[1]);
         4034  +		rc = 1;
         4035  +	    }
         4036  +	  else
         4037  +	    {
         4038  +		rc = process_input (p, alt, 0);
         4039  +		fclose (alt);
         4040  +	    }
         4041  +      }
         4042  +    else if (c == 'r' && n >= 3 && strncmp (azArg[0], "restore", n) == 0
         4043  +	     && nArg > 1 && nArg < 4)
         4044  +      {
         4045  +	  const char *zSrcFile;
         4046  +	  const char *zDb;
         4047  +	  sqlite3 *pSrc;
         4048  +	  sqlite3_backup *pBackup;
         4049  +	  int nTimeout = 0;
         4050  +
         4051  +	  if (nArg == 2)
         4052  +	    {
         4053  +		zSrcFile = azArg[1];
         4054  +		zDb = "main";
         4055  +	    }
         4056  +	  else
         4057  +	    {
         4058  +		zSrcFile = azArg[2];
         4059  +		zDb = azArg[1];
         4060  +	    }
         4061  +	  rc = sqlite3_open (zSrcFile, &pSrc);
         4062  +	  if (rc != SQLITE_OK)
         4063  +	    {
         4064  +		fprintf (stderr, "Error: cannot open \"%s\"\n", zSrcFile);
         4065  +		sqlite3_close (pSrc);
         4066  +		return 1;
         4067  +	    }
         4068  +	  open_db (p);
         4069  +	  pBackup = sqlite3_backup_init (p->db, zDb, pSrc, "main");
         4070  +	  if (pBackup == 0)
         4071  +	    {
         4072  +		fprintf (stderr, "Error: %s\n", sqlite3_errmsg (p->db));
         4073  +		sqlite3_close (pSrc);
         4074  +		return 1;
         4075  +	    }
         4076  +	  while ((rc = sqlite3_backup_step (pBackup, 100)) == SQLITE_OK
         4077  +		 || rc == SQLITE_BUSY)
         4078  +	    {
         4079  +		if (rc == SQLITE_BUSY)
         4080  +		  {
         4081  +		      if (nTimeout++ >= 3)
         4082  +			  break;
         4083  +		      sqlite3_sleep (100);
         4084  +		  }
         4085  +	    }
         4086  +	  sqlite3_backup_finish (pBackup);
         4087  +	  if (rc == SQLITE_DONE)
         4088  +	    {
         4089  +		rc = 0;
         4090  +	    }
         4091  +	  else if (rc == SQLITE_BUSY || rc == SQLITE_LOCKED)
         4092  +	    {
         4093  +		fprintf (stderr, "Error: source database is busy\n");
         4094  +		rc = 1;
         4095  +	    }
         4096  +	  else
         4097  +	    {
         4098  +		fprintf (stderr, "Error: %s\n", sqlite3_errmsg (p->db));
         4099  +		rc = 1;
         4100  +	    }
         4101  +	  sqlite3_close (pSrc);
         4102  +      }
         4103  +    else if (c == 's' && strncmp (azArg[0], "schema", n) == 0 && nArg < 3)
         4104  +      {
         4105  +	  struct callback_data data;
         4106  +	  char *zErrMsg = 0;
         4107  +	  open_db (p);
         4108  +	  memcpy (&data, p, sizeof (data));
         4109  +	  data.showHeader = 0;
         4110  +	  data.mode = MODE_Semi;
         4111  +	  if (nArg > 1)
         4112  +	    {
         4113  +		int i;
         4114  +		for (i = 0; azArg[1][i]; i++)
         4115  +		    azArg[1][i] = ToLower (azArg[1][i]);
         4116  +		if (strcmp (azArg[1], "sqlite_master") == 0)
         4117  +		  {
         4118  +		      char *new_argv[2], *new_colv[2];
         4119  +		      new_argv[0] = "CREATE TABLE sqlite_master (\n"
         4120  +			  "  type text,\n"
         4121  +			  "  name text,\n"
         4122  +			  "  tbl_name text,\n"
         4123  +			  "  rootpage integer,\n" "  sql text\n" ")";
         4124  +		      new_argv[1] = 0;
         4125  +		      new_colv[0] = "sql";
         4126  +		      new_colv[1] = 0;
         4127  +		      callback (&data, 1, new_argv, new_colv);
         4128  +		      rc = SQLITE_OK;
         4129  +		  }
         4130  +		else if (strcmp (azArg[1], "sqlite_temp_master") == 0)
         4131  +		  {
         4132  +		      char *new_argv[2], *new_colv[2];
         4133  +		      new_argv[0] = "CREATE TEMP TABLE sqlite_temp_master (\n"
         4134  +			  "  type text,\n"
         4135  +			  "  name text,\n"
         4136  +			  "  tbl_name text,\n"
         4137  +			  "  rootpage integer,\n" "  sql text\n" ")";
         4138  +		      new_argv[1] = 0;
         4139  +		      new_colv[0] = "sql";
         4140  +		      new_colv[1] = 0;
         4141  +		      callback (&data, 1, new_argv, new_colv);
         4142  +		      rc = SQLITE_OK;
         4143  +		  }
         4144  +		else
         4145  +		  {
         4146  +		      zShellStatic = azArg[1];
         4147  +		      rc = sqlite3_exec (p->db,
         4148  +					 "SELECT sql FROM "
         4149  +					 "  (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
         4150  +					 "     FROM sqlite_master UNION ALL"
         4151  +					 "   SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
         4152  +					 "WHERE lower(tbl_name) LIKE shellstatic()"
         4153  +					 "  AND type!='meta' AND sql NOTNULL "
         4154  +					 "ORDER BY substr(type,2,1), "
         4155  +					 " CASE type WHEN 'view' THEN rowid ELSE name END",
         4156  +					 callback, &data, &zErrMsg);
         4157  +		      zShellStatic = 0;
         4158  +		  }
         4159  +	    }
         4160  +	  else
         4161  +	    {
         4162  +		rc = sqlite3_exec (p->db,
         4163  +				   "SELECT sql FROM "
         4164  +				   "  (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
         4165  +				   "     FROM sqlite_master UNION ALL"
         4166  +				   "   SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
         4167  +				   "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%'"
         4168  +				   "ORDER BY substr(type,2,1),"
         4169  +				   " CASE type WHEN 'view' THEN rowid ELSE name END",
         4170  +				   callback, &data, &zErrMsg);
         4171  +	    }
         4172  +	  if (zErrMsg)
         4173  +	    {
         4174  +		fprintf (stderr, "Error: %s\n", zErrMsg);
         4175  +		sqlite3_free (zErrMsg);
         4176  +		rc = 1;
         4177  +	    }
         4178  +	  else if (rc != SQLITE_OK)
         4179  +	    {
         4180  +		fprintf (stderr, "Error: querying schema information\n");
         4181  +		rc = 1;
         4182  +	    }
         4183  +	  else
         4184  +	    {
         4185  +		rc = 0;
         4186  +	    }
         4187  +      }
         4188  +    else if (c == 's' && strncmp (azArg[0], "separator", n) == 0 && nArg == 2)
         4189  +      {
         4190  +	  sqlite3_snprintf (sizeof (p->separator), p->separator,
         4191  +			    "%.*s", (int) sizeof (p->separator) - 1, azArg[1]);
         4192  +      }
         4193  +    else if (c == 's'
         4194  +	     && (strncmp (azArg[0], "shell", n) == 0
         4195  +		 || strncmp (azArg[0], "system", n) == 0))
         4196  +      {
         4197  +	  char *zCmd;
         4198  +	  int i;
         4199  +	  if (nArg < 2)
         4200  +	    {
         4201  +		fprintf (stderr, "Usage: .system COMMAND\n");
         4202  +		rc = 1;
         4203  +	    }
         4204  +	  else
         4205  +	    {
         4206  +		zCmd =
         4207  +		    sqlite3_mprintf (strchr (azArg[1], ' ') ==
         4208  +				     0 ? "%s" : "\"%s\"", azArg[1]);
         4209  +		for (i = 2; i < nArg; i++)
         4210  +		  {
         4211  +		      zCmd =
         4212  +			  sqlite3_mprintf (strchr (azArg[i], ' ') ==
         4213  +					   0 ? "%z %s" : "%z \"%s\"", zCmd,
         4214  +					   azArg[i]);
         4215  +		  }
         4216  +		(void) system (zCmd);
         4217  +		sqlite3_free (zCmd);
         4218  +	    }
         4219  +      }
         4220  +    else if (c == 's' && strncmp (azArg[0], "show", n) == 0 && nArg == 1)
         4221  +      {
         4222  +	  int i;
         4223  +	  fprintf (p->out, "%9.9s: %s\n", "echo", p->echoOn ? "on" : "off");
         4224  +	  fprintf (p->out, "%9.9s: %s\n", "explain",
         4225  +		   p->explainPrev.valid ? "on" : "off");
         4226  +	  fprintf (p->out, "%9.9s: %s\n", "headers",
         4227  +		   p->showHeader ? "on" : "off");
         4228  +	  fprintf (p->out, "%9.9s: %s\n", "mode", modeDescr[p->mode]);
         4229  +	  fprintf (p->out, "%9.9s: ", "nullvalue");
         4230  +	  output_c_string (p->out, p->nullvalue);
         4231  +	  fprintf (p->out, "\n");
         4232  +	  fprintf (p->out, "%9.9s: %s\n", "output",
         4233  +		   strlen30 (p->outfile) ? p->outfile : "stdout");
         4234  +	  fprintf (p->out, "%9.9s: ", "separator");
         4235  +	  output_c_string (p->out, p->separator);
         4236  +	  fprintf (p->out, "\n");
         4237  +	  fprintf (p->out, "%9.9s: %s\n", "stats", p->statsOn ? "on" : "off");
         4238  +	  fprintf (p->out, "%9.9s: ", "width");
         4239  +	  for (i = 0; i < (int) ArraySize (p->colWidth) && p->colWidth[i] != 0;
         4240  +	       i++)
         4241  +	    {
         4242  +		fprintf (p->out, "%d ", p->colWidth[i]);
         4243  +	    }
         4244  +	  fprintf (p->out, "\n");
         4245  +      }
         4246  +    else if (c == 's' && strncmp (azArg[0], "stats", n) == 0 && nArg > 1
         4247  +	     && nArg < 3)
         4248  +      {
         4249  +	  p->statsOn = booleanValue (azArg[1]);
         4250  +      }
         4251  +    else if (c == 't' && n > 1 && strncmp (azArg[0], "tables", n) == 0
         4252  +	     && nArg < 3)
         4253  +      {
         4254  +	  sqlite3_stmt *pStmt;
         4255  +	  char **azResult;
         4256  +	  int nRow, nAlloc;
         4257  +	  char *zSql = 0;
         4258  +	  int ii;
         4259  +	  open_db (p);
         4260  +	  rc = sqlite3_prepare_v2 (p->db, "PRAGMA database_list", -1, &pStmt,
         4261  +				   0);
         4262  +	  if (rc)
         4263  +	      return rc;
         4264  +	  zSql = sqlite3_mprintf ("SELECT name FROM sqlite_master"
         4265  +				  " WHERE type IN ('table','view')"
         4266  +				  "   AND name NOT LIKE 'sqlite_%%'"
         4267  +				  "   AND name LIKE ?1");
         4268  +	  while (sqlite3_step (pStmt) == SQLITE_ROW)
         4269  +	    {
         4270  +		const char *zDbName =
         4271  +		    (const char *) sqlite3_column_text (pStmt, 1);
         4272  +		if (zDbName == 0 || strcmp (zDbName, "main") == 0)
         4273  +		    continue;
         4274  +		if (strcmp (zDbName, "temp") == 0)
         4275  +		  {
         4276  +		      zSql = sqlite3_mprintf ("%z UNION ALL "
         4277  +					      "SELECT 'temp.' || name FROM sqlite_temp_master"
         4278  +					      " WHERE type IN ('table','view')"
         4279  +					      "   AND name NOT LIKE 'sqlite_%%'"
         4280  +					      "   AND name LIKE ?1", zSql);
         4281  +		  }
         4282  +		else
         4283  +		  {
         4284  +		      zSql = sqlite3_mprintf ("%z UNION ALL "
         4285  +					      "SELECT '%q.' || name FROM \"%w\".sqlite_master"
         4286  +					      " WHERE type IN ('table','view')"
         4287  +					      "   AND name NOT LIKE 'sqlite_%%'"
         4288  +					      "   AND name LIKE ?1", zSql,
         4289  +					      zDbName, zDbName);
         4290  +		  }
         4291  +	    }
         4292  +	  sqlite3_finalize (pStmt);
         4293  +	  zSql = sqlite3_mprintf ("%z ORDER BY 1", zSql);
         4294  +	  rc = sqlite3_prepare_v2 (p->db, zSql, -1, &pStmt, 0);
         4295  +	  sqlite3_free (zSql);
         4296  +	  if (rc)
         4297  +	      return rc;
         4298  +	  nRow = nAlloc = 0;
         4299  +	  azResult = 0;
         4300  +	  if (nArg > 1)
         4301  +	    {
         4302  +		sqlite3_bind_text (pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
         4303  +	    }
         4304  +	  else
         4305  +	    {
         4306  +		sqlite3_bind_text (pStmt, 1, "%", -1, SQLITE_STATIC);
         4307  +	    }
         4308  +	  while (sqlite3_step (pStmt) == SQLITE_ROW)
         4309  +	    {
         4310  +		if (nRow >= nAlloc)
         4311  +		  {
         4312  +		      char **azNew;
         4313  +		      int n = nAlloc * 2 + 10;
         4314  +		      azNew =
         4315  +			  sqlite3_realloc (azResult, sizeof (azResult[0]) * n);
         4316  +		      if (azNew == 0)
         4317  +			{
         4318  +			    fprintf (stderr, "Error: out of memory\n");
         4319  +			    break;
         4320  +			}
         4321  +		      nAlloc = n;
         4322  +		      azResult = azNew;
         4323  +		  }
         4324  +		azResult[nRow] =
         4325  +		    sqlite3_mprintf ("%s", sqlite3_column_text (pStmt, 0));
         4326  +		if (azResult[nRow])
         4327  +		    nRow++;
         4328  +	    }
         4329  +	  sqlite3_finalize (pStmt);
         4330  +	  if (nRow > 0)
         4331  +	    {
         4332  +		int len, maxlen = 0;
         4333  +		int i, j;
         4334  +		int nPrintCol, nPrintRow;
         4335  +		for (i = 0; i < nRow; i++)
         4336  +		  {
         4337  +		      len = strlen30 (azResult[i]);
         4338  +		      if (len > maxlen)
         4339  +			  maxlen = len;
         4340  +		  }
         4341  +		nPrintCol = 80 / (maxlen + 2);
         4342  +		if (nPrintCol < 1)
         4343  +		    nPrintCol = 1;
         4344  +		nPrintRow = (nRow + nPrintCol - 1) / nPrintCol;
         4345  +		for (i = 0; i < nPrintRow; i++)
         4346  +		  {
         4347  +		      for (j = i; j < nRow; j += nPrintRow)
         4348  +			{
         4349  +			    char *zSp = j < nPrintRow ? "" : "  ";
         4350  +			    printf ("%s%-*s", zSp, maxlen,
         4351  +				    azResult[j] ? azResult[j] : "");
         4352  +			}
         4353  +		      printf ("\n");
         4354  +		  }
         4355  +	    }
         4356  +	  for (ii = 0; ii < nRow; ii++)
         4357  +	      sqlite3_free (azResult[ii]);
         4358  +	  sqlite3_free (azResult);
         4359  +      }
         4360  +    else if (c == 't' && n >= 8 && strncmp (azArg[0], "testctrl", n) == 0
         4361  +	     && nArg >= 2)
         4362  +      {
         4363  +	  static const struct
         4364  +	  {
         4365  +	      const char *zCtrlName;	/* Name of a test-control option */
         4366  +	      int ctrlCode;	/* Integer code for that option */
         4367  +	  } aCtrl[] =
         4368  +	  {
         4369  +	      {
         4370  +	      "prng_save", SQLITE_TESTCTRL_PRNG_SAVE},
         4371  +	      {
         4372  +	      "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE},
         4373  +	      {
         4374  +	      "prng_reset", SQLITE_TESTCTRL_PRNG_RESET},
         4375  +	      {
         4376  +	      "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST},
         4377  +	      {
         4378  +	      "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL},
         4379  +	      {
         4380  +	      "benign_malloc_hooks", SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS},
         4381  +	      {
         4382  +	      "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE},
         4383  +	      {
         4384  +	      "assert", SQLITE_TESTCTRL_ASSERT},
         4385  +	      {
         4386  +	      "always", SQLITE_TESTCTRL_ALWAYS},
         4387  +	      {
         4388  +	      "reserve", SQLITE_TESTCTRL_RESERVE},
         4389  +	      {
         4390  +	      "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS},
         4391  +	      {
         4392  +	      "iskeyword", SQLITE_TESTCTRL_ISKEYWORD},
         4393  +	      {
         4394  +	  "scratchmalloc", SQLITE_TESTCTRL_SCRATCHMALLOC},};
         4395  +	  int testctrl = -1;
         4396  +	  int rc = 0;
         4397  +	  int i, n;
         4398  +	  open_db (p);
         4399  +
         4400  +	  /* convert testctrl text option to value. allow any unique prefix
         4401  +	   ** of the option name, or a numerical value. */
         4402  +	  n = strlen30 (azArg[1]);
         4403  +	  for (i = 0; i < (int) (sizeof (aCtrl) / sizeof (aCtrl[0])); i++)
         4404  +	    {
         4405  +		if (strncmp (azArg[1], aCtrl[i].zCtrlName, n) == 0)
         4406  +		  {
         4407  +		      if (testctrl < 0)
         4408  +			{
         4409  +			    testctrl = aCtrl[i].ctrlCode;
         4410  +			}
         4411  +		      else
         4412  +			{
         4413  +			    fprintf (stderr, "ambiguous option name: \"%s\"\n",
         4414  +				     azArg[1]);
         4415  +			    testctrl = -1;
         4416  +			    break;
         4417  +			}
         4418  +		  }
         4419  +	    }
         4420  +	  if (testctrl < 0)
         4421  +	      testctrl = atoi (azArg[1]);
         4422  +	  if ((testctrl < SQLITE_TESTCTRL_FIRST)
         4423  +	      || (testctrl > SQLITE_TESTCTRL_LAST))
         4424  +	    {
         4425  +		fprintf (stderr, "Error: invalid testctrl option: %s\n",
         4426  +			 azArg[1]);
         4427  +	    }
         4428  +	  else
         4429  +	    {
         4430  +		switch (testctrl)
         4431  +		  {
         4432  +
         4433  +		      /* sqlite3_test_control(int, db, int) */
         4434  +		  case SQLITE_TESTCTRL_OPTIMIZATIONS:
         4435  +		  case SQLITE_TESTCTRL_RESERVE:
         4436  +		      if (nArg == 3)
         4437  +			{
         4438  +			    int opt = (int) strtol (azArg[2], 0, 0);
         4439  +			    rc = sqlite3_test_control (testctrl, p->db, opt);
         4440  +			    printf ("%d (0x%08x)\n", rc, rc);
         4441  +			}
         4442  +		      else
         4443  +			{
         4444  +			    fprintf (stderr,
         4445  +				     "Error: testctrl %s takes a single int option\n",
         4446  +				     azArg[1]);
         4447  +			}
         4448  +		      break;
         4449  +
         4450  +		      /* sqlite3_test_control(int) */
         4451  +		  case SQLITE_TESTCTRL_PRNG_SAVE:
         4452  +		  case SQLITE_TESTCTRL_PRNG_RESTORE:
         4453  +		  case SQLITE_TESTCTRL_PRNG_RESET:
         4454  +		      if (nArg == 2)
         4455  +			{
         4456  +			    rc = sqlite3_test_control (testctrl);
         4457  +			    printf ("%d (0x%08x)\n", rc, rc);
         4458  +			}
         4459  +		      else
         4460  +			{
         4461  +			    fprintf (stderr,
         4462  +				     "Error: testctrl %s takes no options\n",
         4463  +				     azArg[1]);
         4464  +			}
         4465  +		      break;
         4466  +
         4467  +		      /* sqlite3_test_control(int, uint) */
         4468  +		  case SQLITE_TESTCTRL_PENDING_BYTE:
         4469  +		      if (nArg == 3)
         4470  +			{
         4471  +			    unsigned int opt = (unsigned int) atoi (azArg[2]);
         4472  +			    rc = sqlite3_test_control (testctrl, opt);
         4473  +			    printf ("%d (0x%08x)\n", rc, rc);
         4474  +			}
         4475  +		      else
         4476  +			{
         4477  +			    fprintf (stderr,
         4478  +				     "Error: testctrl %s takes a single unsigned"
         4479  +				     " int option\n", azArg[1]);
         4480  +			}
         4481  +		      break;
         4482  +
         4483  +		      /* sqlite3_test_control(int, int) */
         4484  +		  case SQLITE_TESTCTRL_ASSERT:
         4485  +		  case SQLITE_TESTCTRL_ALWAYS:
         4486  +		      if (nArg == 3)
         4487  +			{
         4488  +			    int opt = atoi (azArg[2]);
         4489  +			    rc = sqlite3_test_control (testctrl, opt);
         4490  +			    printf ("%d (0x%08x)\n", rc, rc);
         4491  +			}
         4492  +		      else
         4493  +			{
         4494  +			    fprintf (stderr,
         4495  +				     "Error: testctrl %s takes a single int option\n",
         4496  +				     azArg[1]);
         4497  +			}
         4498  +		      break;
         4499  +
         4500  +		      /* sqlite3_test_control(int, char *) */
  3701   4501   #ifdef SQLITE_N_KEYWORD
  3702         -        case SQLITE_TESTCTRL_ISKEYWORD:           
  3703         -          if( nArg==3 ){
  3704         -            const char *opt = azArg[2];        
  3705         -            rc = sqlite3_test_control(testctrl, opt);
  3706         -            printf("%d (0x%08x)\n", rc, rc);
  3707         -          } else {
  3708         -            fprintf(stderr,"Error: testctrl %s takes a single char * option\n",
  3709         -                            azArg[1]);
  3710         -          }
  3711         -          break;
  3712         -#endif
  3713         -
  3714         -        case SQLITE_TESTCTRL_BITVEC_TEST:         
  3715         -        case SQLITE_TESTCTRL_FAULT_INSTALL:       
  3716         -        case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: 
  3717         -        case SQLITE_TESTCTRL_SCRATCHMALLOC:       
  3718         -        default:
  3719         -          fprintf(stderr,"Error: CLI support for testctrl %s not implemented\n",
  3720         -                  azArg[1]);
  3721         -          break;
  3722         -      }
  3723         -    }
  3724         -  }else
  3725         -
  3726         -  if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 && nArg==2 ){
  3727         -    open_db(p);
  3728         -    sqlite3_busy_timeout(p->db, atoi(azArg[1]));
  3729         -  }else
  3730         -    
  3731         -  if( HAS_TIMER && c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0
  3732         -   && nArg==2
  3733         -  ){
  3734         -    enableTimer = booleanValue(azArg[1]);
  3735         -  }else
  3736         -  
  3737         -  if( c=='t' && strncmp(azArg[0], "trace", n)==0 && nArg>1 ){
  3738         -    open_db(p);
  3739         -    output_file_close(p->traceOut);
  3740         -    p->traceOut = output_file_open(azArg[1]);
         4502  +		  case SQLITE_TESTCTRL_ISKEYWORD:
         4503  +		      if (nArg == 3)
         4504  +			{
         4505  +			    const char *opt = azArg[2];
         4506  +			    rc = sqlite3_test_control (testctrl, opt);
         4507  +			    printf ("%d (0x%08x)\n", rc, rc);
         4508  +			}
         4509  +		      else
         4510  +			{
         4511  +			    fprintf (stderr,
         4512  +				     "Error: testctrl %s takes a single char * option\n",
         4513  +				     azArg[1]);
         4514  +			}
         4515  +		      break;
         4516  +#endif
         4517  +
         4518  +		  case SQLITE_TESTCTRL_BITVEC_TEST:
         4519  +		  case SQLITE_TESTCTRL_FAULT_INSTALL:
         4520  +		  case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS:
         4521  +		  case SQLITE_TESTCTRL_SCRATCHMALLOC:
         4522  +		  default:
         4523  +		      fprintf (stderr,
         4524  +			       "Error: CLI support for testctrl %s not implemented\n",
         4525  +			       azArg[1]);
         4526  +		      break;
         4527  +		  }
         4528  +	    }
         4529  +      }
         4530  +    else if (c == 't' && n > 4 && strncmp (azArg[0], "timeout", n) == 0
         4531  +	     && nArg == 2)
         4532  +      {
         4533  +	  open_db (p);
         4534  +	  sqlite3_busy_timeout (p->db, atoi (azArg[1]));
         4535  +      }
         4536  +    else if (HAS_TIMER && c == 't' && n >= 5
         4537  +	     && strncmp (azArg[0], "timer", n) == 0 && nArg == 2)
         4538  +      {
         4539  +	  enableTimer = booleanValue (azArg[1]);
         4540  +      }
         4541  +    else if (c == 't' && strncmp (azArg[0], "trace", n) == 0 && nArg > 1)
         4542  +      {
         4543  +	  open_db (p);
         4544  +	  output_file_close (p->traceOut);
         4545  +	  p->traceOut = output_file_open (azArg[1]);
  3741   4546   #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
  3742         -    if( p->traceOut==0 ){
  3743         -      sqlite3_trace(p->db, 0, 0);
  3744         -    }else{
  3745         -      sqlite3_trace(p->db, sql_trace_callback, p->traceOut);
  3746         -    }
         4547  +	  if (p->traceOut == 0)
         4548  +	    {
         4549  +		sqlite3_trace (p->db, 0, 0);
         4550  +	    }
         4551  +	  else
         4552  +	    {
         4553  +		sqlite3_trace (p->db, sql_trace_callback, p->traceOut);
         4554  +	    }
  3747   4555   #endif
  3748         -  }else
  3749         -
  3750         -  if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
  3751         -    printf("SQLite %s %s\n" /*extra-version-info*/,
  3752         -        sqlite3_libversion(), sqlite3_sourceid());
  3753         -  }else
  3754         -
  3755         -  if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
  3756         -    const char *zDbName = nArg==2 ? azArg[1] : "main";
  3757         -    char *zVfsName = 0;
  3758         -    if( p->db ){
         4556  +      }
         4557  +    else if (c == 'v' && strncmp (azArg[0], "version", n) == 0)
         4558  +      {
         4559  +	  printf ("SQLite %s %s\n" /*extra-version-info */ ,
         4560  +		  sqlite3_libversion (), sqlite3_sourceid ());
         4561  +      }
         4562  +    else if (c == 'v' && strncmp (azArg[0], "vfsname", n) == 0)
         4563  +      {
         4564  +	  const char *zDbName = nArg == 2 ? azArg[1] : "main";
         4565  +	  char *zVfsName = 0;
         4566  +	  if (p->db)
         4567  +	    {
  3759   4568   /* Sandro Furieri 1 November 2012 - depending on SQLite version */
  3760   4569   #ifdef HAVE_DECL_SQLITE_FCNTL_VFSNAME
  3761         -      sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
  3762         -      if( zVfsName ){
  3763         -        printf("%s\n", zVfsName);
  3764         -        sqlite3_free(zVfsName);
  3765         -      }
         4570  +		sqlite3_file_control (p->db, zDbName, SQLITE_FCNTL_VFSNAME,
         4571  +				      &zVfsName);
         4572  +		if (zVfsName)
         4573  +		  {
         4574  +		      printf ("%s\n", zVfsName);
         4575  +		      sqlite3_free (zVfsName);
         4576  +		  }
  3766   4577   #else
  3767         -        printf("FCNTL_VFSNAME: unsupported\n");
         4578  +		printf ("FCNTL_VFSNAME: unsupported\n");
  3768   4579   #endif
  3769   4580   /* end sandro 1 November 2012 */
  3770         -    }
  3771         -  }else
         4581  +	    }
         4582  +      }
         4583  +    else if (c == 'w' && strncmp (azArg[0], "width", n) == 0 && nArg > 1)
         4584  +      {
         4585  +	  int j;
         4586  +	  assert (nArg <= ArraySize (azArg));
         4587  +	  for (j = 1; j < nArg && j < ArraySize (p->colWidth); j++)
         4588  +	    {
         4589  +		p->colWidth[j - 1] = atoi (azArg[j]);
         4590  +	    }
         4591  +      }
         4592  +    else
  3772   4593   
  3773         -  if( c=='w' && strncmp(azArg[0], "width", n)==0 && nArg>1 ){
  3774         -    int j;
  3775         -    assert( nArg<=ArraySize(azArg) );
  3776         -    for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){
  3777         -      p->colWidth[j-1] = atoi(azArg[j]);
  3778         -    }
  3779         -  }else
         4594  +      {
         4595  +	  fprintf (stderr, "Error: unknown command or invalid arguments: "
         4596  +		   " \"%s\". Enter \".help\" for help\n", azArg[0]);
         4597  +	  rc = 1;
         4598  +      }
  3780   4599   
  3781         -  {
  3782         -    fprintf(stderr, "Error: unknown command or invalid arguments: "
  3783         -      " \"%s\". Enter \".help\" for help\n", azArg[0]);
  3784         -    rc = 1;
  3785         -  }
  3786         -
  3787         -  return rc;
         4600  +    return rc;
  3788   4601   }
  3789   4602   
  3790   4603   /*
  3791   4604   ** Return TRUE if a semicolon occurs anywhere in the first N characters
  3792   4605   ** of string z[].
  3793   4606   */
  3794         -static int _contains_semicolon(const char *z, int N){
  3795         -  int i;
  3796         -  for(i=0; i<N; i++){  if( z[i]==';' ) return 1; }
  3797         -  return 0;
         4607  +static int
         4608  +_contains_semicolon (const char *z, int N)
         4609  +{
         4610  +    int i;
         4611  +    for (i = 0; i < N; i++)
         4612  +      {
         4613  +	  if (z[i] == ';')
         4614  +	      return 1;
         4615  +      }
         4616  +    return 0;
  3798   4617   }
  3799   4618   
  3800   4619   /*
  3801   4620   ** Test to see if a line consists entirely of whitespace.
  3802   4621   */
  3803         -static int _all_whitespace(const char *z){
  3804         -  for(; *z; z++){
  3805         -    if( IsSpace(z[0]) ) continue;
  3806         -    if( *z=='/' && z[1]=='*' ){
  3807         -      z += 2;
  3808         -      while( *z && (*z!='*' || z[1]!='/') ){ z++; }
  3809         -      if( *z==0 ) return 0;
  3810         -      z++;
  3811         -      continue;
  3812         -    }
  3813         -    if( *z=='-' && z[1]=='-' ){
  3814         -      z += 2;
  3815         -      while( *z && *z!='\n' ){ z++; }
  3816         -      if( *z==0 ) return 1;
  3817         -      continue;
  3818         -    }
  3819         -    return 0;
  3820         -  }
  3821         -  return 1;
         4622  +static int
         4623  +_all_whitespace (const char *z)
         4624  +{
         4625  +    for (; *z; z++)
         4626  +      {
         4627  +	  if (IsSpace (z[0]))
         4628  +	      continue;
         4629  +	  if (*z == '/' && z[1] == '*')
         4630  +	    {
         4631  +		z += 2;
         4632  +		while (*z && (*z != '*' || z[1] != '/'))
         4633  +		  {
         4634  +		      z++;
         4635  +		  }
         4636  +		if (*z == 0)
         4637  +		    return 0;
         4638  +		z++;
         4639  +		continue;
         4640  +	    }
         4641  +	  if (*z == '-' && z[1] == '-')
         4642  +	    {
         4643  +		z += 2;
         4644  +		while (*z && *z != '\n')
         4645  +		  {
         4646  +		      z++;
         4647  +		  }
         4648  +		if (*z == 0)
         4649  +		    return 1;
         4650  +		continue;
         4651  +	    }
         4652  +	  return 0;
         4653  +      }
         4654  +    return 1;
  3822   4655   }
  3823   4656   
  3824   4657   /*
  3825   4658   ** Return TRUE if the line typed in is an SQL command terminator other
  3826   4659   ** than a semi-colon.  The SQL Server style "go" command is understood
  3827   4660   ** as is the Oracle "/".
  3828   4661   */
  3829         -static int _is_command_terminator(const char *zLine){
  3830         -  while( IsSpace(zLine[0]) ){ zLine++; };
  3831         -  if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){
  3832         -    return 1;  /* Oracle */
  3833         -  }
  3834         -  if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o'
  3835         -         && _all_whitespace(&zLine[2]) ){
  3836         -    return 1;  /* SQL Server */
  3837         -  }
  3838         -  return 0;
         4662  +static int
         4663  +_is_command_terminator (const char *zLine)
         4664  +{
         4665  +    while (IsSpace (zLine[0]))
         4666  +      {
         4667  +	  zLine++;
         4668  +      };
         4669  +    if (zLine[0] == '/' && _all_whitespace (&zLine[1]))
         4670  +      {
         4671  +	  return 1;		/* Oracle */
         4672  +      }
         4673  +    if (ToLower (zLine[0]) == 'g' && ToLower (zLine[1]) == 'o'
         4674  +	&& _all_whitespace (&zLine[2]))
         4675  +      {
         4676  +	  return 1;		/* SQL Server */
         4677  +      }
         4678  +    return 0;
  3839   4679   }
  3840   4680   
  3841   4681   /*
  3842   4682   ** Return true if zSql is a complete SQL statement.  Return false if it
  3843   4683   ** ends in the middle of a string literal or C-style comment.
  3844   4684   */
  3845         -static int _is_complete(char *zSql, int nSql){
  3846         -  int rc;
  3847         -  if( zSql==0 ) return 1;
  3848         -  zSql[nSql] = ';';
  3849         -  zSql[nSql+1] = 0;
  3850         -  rc = sqlite3_complete(zSql);
  3851         -  zSql[nSql] = 0;
  3852         -  return rc;
         4685  +static int
         4686  +_is_complete (char *zSql, int nSql)
         4687  +{
         4688  +    int rc;
         4689  +    if (zSql == 0)
         4690  +	return 1;
         4691  +    zSql[nSql] = ';';
         4692  +    zSql[nSql + 1] = 0;
         4693  +    rc = sqlite3_complete (zSql);
         4694  +    zSql[nSql] = 0;
         4695  +    return rc;
  3853   4696   }
  3854   4697   
  3855   4698   /*
  3856   4699   ** Read input from *in and process it.  If *in==0 then input
  3857   4700   ** is interactive - the user is typing it it.  Otherwise, input
  3858   4701   ** is coming from a file or device.  A prompt is issued and history
  3859   4702   ** is saved only if input is interactive.  An interrupt signal will
  3860   4703   ** cause this routine to exit immediately, unless input is interactive.
  3861   4704   **
  3862   4705   ** Return the number of errors.
  3863   4706   */
  3864         -static int process_input(struct callback_data *p, FILE *in, char *in_charset){
  3865         -  char *zLine = 0;
  3866         -  char *zSql = 0;
         4707  +static int
         4708  +process_input (struct callback_data *p, FILE * in, char *in_charset)
         4709  +{
         4710  +    char *zLine = 0;
         4711  +    char *zSql = 0;
  3867   4712   /* Sandro Furieri - 11 July 2008 - supporting UNICODE */
  3868         -  int utf8len;
  3869         -  char *utf8Sql = 0;
         4713  +    int utf8len;
         4714  +    char *utf8Sql = 0;
  3870   4715   /* End Sandro Furieri - 11 July 2008 */
  3871   4716   /* Sandro Furieri - 3 September 2012 - supporting SqlLog */
  3872         -  sqlite3_int64 sqllog_pk;
         4717  +    sqlite3_int64 sqllog_pk;
  3873   4718   /* End Sandro Furieri - 3 September 2012 - supporting SqlLog */
  3874         -  int nSql = 0;
  3875         -  int nSqlPrior = 0;
  3876         -  char *zErrMsg;
  3877         -  int rc;
  3878         -  int errCnt = 0;
  3879         -  int lineno = 0;
  3880         -  int startline = 0;
         4719  +    int nSql = 0;
         4720  +    int nSqlPrior = 0;
         4721  +    char *zErrMsg;
         4722  +    int rc;
         4723  +    int errCnt = 0;
         4724  +    int lineno = 0;
         4725  +    int startline = 0;
  3881   4726   
  3882   4727   /* Sandro Furieri - 11 July 2008 - supporting UNICODE */
  3883         -  if (in_charset)
  3884         -    create_input_utf8_converter (in_charset);
         4728  +    if (in_charset)
         4729  +	create_input_utf8_converter (in_charset);
  3885   4730   /* End Sandro Furieri - 11 July 2008 */
  3886   4731   
  3887         -  while( errCnt==0 || !bail_on_error || (in==0 && stdin_is_interactive) ){
  3888         -    fflush(p->out);
  3889         -    free(zLine);
  3890         -    zLine = one_input_line(zSql, in);
  3891         -    if( zLine==0 ){
  3892         -      /* End of input */
  3893         -      if( stdin_is_interactive ) printf("\n");
  3894         -      break;
  3895         -    }
  3896         -    if( seenInterrupt ){
  3897         -      if( in!=0 ) break;
  3898         -      seenInterrupt = 0;
  3899         -    }
  3900         -    lineno++;
  3901         -    if( (zSql==0 || zSql[0]==0) && _all_whitespace(zLine) ) continue;
  3902         -    if( zLine && zLine[0]=='.' && nSql==0 ){
  3903         -      if( p->echoOn ) printf("%s\n", zLine);
  3904         -      rc = do_meta_command(zLine, p);
  3905         -      if( rc==2 ){ /* exit requested */
  3906         -        break;
  3907         -      }else if( rc ){
  3908         -        errCnt++;
  3909         -      }
  3910         -      continue;
  3911         -    }
  3912         -    if( _is_command_terminator(zLine) && _is_complete(zSql, nSql) ){
  3913         -      memcpy(zLine,";",2);
  3914         -    }
  3915         -    nSqlPrior = nSql;
  3916         -    if( zSql==0 ){
  3917         -      int i;
  3918         -      for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
  3919         -      if( zLine[i]!=0 ){
  3920         -        nSql = strlen30(zLine);
  3921         -        zSql = malloc( nSql+3 );
  3922         -        if( zSql==0 ){
  3923         -          fprintf(stderr, "Error: out of memory\n");
  3924         -          exit(1);
  3925         -        }
  3926         -        memcpy(zSql, zLine, nSql+1);
  3927         -        startline = lineno;
  3928         -      }
  3929         -    }else{
  3930         -      int len = strlen30(zLine);
  3931         -      zSql = realloc( zSql, nSql + len + 4 );
  3932         -      if( zSql==0 ){
  3933         -        fprintf(stderr,"Error: out of memory\n");
  3934         -        exit(1);
  3935         -      }
  3936         -      zSql[nSql++] = '\n';
  3937         -      memcpy(&zSql[nSql], zLine, len+1);
  3938         -      nSql += len;
  3939         -    }
  3940         -    if( zSql && _contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
  3941         -                && sqlite3_complete(zSql) ){
  3942         -      p->cnt = 0;
  3943         -      open_db(p);
         4732  +    while (errCnt == 0 || !bail_on_error || (in == 0 && stdin_is_interactive))
         4733  +      {
         4734  +	  fflush (stderr);
         4735  +	  fflush (p->out);
         4736  +	  free (zLine);
         4737  +	  zLine = one_input_line (zSql, in);
         4738  +	  if (zLine == 0)
         4739  +	    {
         4740  +		/* End of input */
         4741  +		if (stdin_is_interactive)
         4742  +		    printf ("\n");
         4743  +		break;
         4744  +	    }
         4745  +	  if (seenInterrupt)
         4746  +	    {
         4747  +		if (in != 0)
         4748  +		    break;
         4749  +		seenInterrupt = 0;
         4750  +	    }
         4751  +	  lineno++;
         4752  +	  if ((zSql == 0 || zSql[0] == 0) && _all_whitespace (zLine))
         4753  +	      continue;
         4754  +	  if (zLine && zLine[0] == '.' && nSql == 0)
         4755  +	    {
         4756  +		if (p->echoOn)
         4757  +		    printf ("%s\n", zLine);
         4758  +		rc = do_meta_command (zLine, p);
         4759  +		if (rc == 2)
         4760  +		  {		/* exit requested */
         4761  +		      break;
         4762  +		  }
         4763  +		else if (rc)
         4764  +		  {
         4765  +		      errCnt++;
         4766  +		  }
         4767  +		continue;
         4768  +	    }
         4769  +	  if (_is_command_terminator (zLine) && _is_complete (zSql, nSql))
         4770  +	    {
         4771  +		memcpy (zLine, ";", 2);
         4772  +	    }
         4773  +	  nSqlPrior = nSql;
         4774  +	  if (zSql == 0)
         4775  +	    {
         4776  +		int i;
         4777  +		for (i = 0; zLine[i] && IsSpace (zLine[i]); i++)
         4778  +		  {
         4779  +		  }
         4780  +		if (zLine[i] != 0)
         4781  +		  {
         4782  +		      nSql = strlen30 (zLine);
         4783  +		      zSql = malloc (nSql + 3);
         4784  +		      if (zSql == 0)
         4785  +			{
         4786  +			    fprintf (stderr, "Error: out of memory\n");
         4787  +			    exit (1);
         4788  +			}
         4789  +		      memcpy (zSql, zLine, nSql + 1);
         4790  +		      startline = lineno;
         4791  +		  }
         4792  +	    }
         4793  +	  else
         4794  +	    {
         4795  +		int len = strlen30 (zLine);
         4796  +		zSql = realloc (zSql, nSql + len + 4);
         4797  +		if (zSql == 0)
         4798  +		  {
         4799  +		      fprintf (stderr, "Error: out of memory\n");
         4800  +		      exit (1);
         4801  +		  }
         4802  +		zSql[nSql++] = '\n';
         4803  +		memcpy (&zSql[nSql], zLine, len + 1);
         4804  +		nSql += len;
         4805  +	    }
         4806  +	  if (zSql && _contains_semicolon (&zSql[nSqlPrior], nSql - nSqlPrior)
         4807  +	      && sqlite3_complete (zSql))
         4808  +	    {
         4809  +		p->cnt = 0;
         4810  +		open_db (p);
  3944   4811   /* Sandro Furieri - 11 July 2008
  3945   4812         BEGIN_TIMER;
  3946   4813         rc = shell_exec(p->db, zSql, shell_callback, p, &zErrMsg);
  3947   4814         END_TIMER;
  3948   4815   */
  3949         -      utf8len = strlen (zSql) * 4;
  3950         -      utf8Sql = malloc (utf8len);
  3951         -      if (utf8Sql == 0)
  3952         -      {
  3953         -          fprintf (stderr, "%s: out of memory!\n", Argv0);
  3954         -          exit (1);
  3955         -      }
  3956         -      strncpy (utf8Sql, zSql, utf8len - 1);
  3957         -      utf8Sql[utf8len - 1] = '\0';
  3958         -      if (!in_charset)
  3959         -      {	
  3960         -      /* assuming input is locale_charset encoded */
  3961         -          convert_to_utf8 (utf8Sql, utf8len);
  3962         -      }
  3963         -      else
  3964         -      {
  3965         -      /* input has an explicit charset */
  3966         -          convert_input_to_utf8 (utf8Sql, utf8len);
  3967         -      }
  3968         -      if (sql_log_enabled)
  3969         -          gaiaInsertIntoSqlLog(p->db, "spatialite CLI", utf8Sql, &sqllog_pk);
  3970         -      BEGIN_TIMER;
  3971         -      rc = sqlite3_exec (p->db, utf8Sql, callback, p, &zErrMsg);
  3972         -      END_TIMER;
  3973         -      if (sql_log_enabled)
  3974         -          gaiaUpdateSqlLog(p->db, sqllog_pk, (rc == SQLITE_OK) ? 1 : 0, zErrMsg); 
  3975         -      free (utf8Sql);
         4816  +		utf8len = strlen (zSql) * 4;
         4817  +		utf8Sql = malloc (utf8len);
         4818  +		if (utf8Sql == 0)
         4819  +		  {
         4820  +		      fprintf (stderr, "%s: out of memory!\n", Argv0);
         4821  +		      exit (1);
         4822  +		  }
         4823  +		strncpy (utf8Sql, zSql, utf8len - 1);
         4824  +		utf8Sql[utf8len - 1] = '\0';
         4825  +		if (!in_charset)
         4826  +		  {
         4827  +		      /* assuming input is locale_charset encoded */
         4828  +		      convert_to_utf8 (utf8Sql, utf8len);
         4829  +		  }
         4830  +		else
         4831  +		  {
         4832  +		      /* input has an explicit charset */
         4833  +		      convert_input_to_utf8 (utf8Sql, utf8len);
         4834  +		  }
         4835  +		if (sql_log_enabled)
         4836  +		    gaiaInsertIntoSqlLog (p->db, "spatialite CLI", utf8Sql,
         4837  +					  &sqllog_pk);
         4838  +		BEGIN_TIMER;
         4839  +		rc = sqlite3_exec (p->db, utf8Sql, callback, p, &zErrMsg);
         4840  +		END_TIMER;
         4841  +		if (sql_log_enabled)
         4842  +		    gaiaUpdateSqlLog (p->db, sqllog_pk,
         4843  +				      (rc == SQLITE_OK) ? 1 : 0, zErrMsg);
         4844  +		free (utf8Sql);
  3976   4845   /* End Sandro Furieri - 11 July 2008 */
  3977         -      if( rc || zErrMsg ){
  3978         -        char zPrefix[100];
  3979         -        if( in!=0 || !stdin_is_interactive ){
  3980         -          sqlite3_snprintf(sizeof(zPrefix), zPrefix, 
  3981         -                           "Error: near line %d:", startline);
  3982         -        }else{
  3983         -          sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:");
  3984         -        }
  3985         -        if( zErrMsg!=0 ){
  3986         -          fprintf(stderr, "%s %s\n", zPrefix, zErrMsg);
  3987         -          sqlite3_free(zErrMsg);
  3988         -          zErrMsg = 0;
  3989         -        }else{
  3990         -          fprintf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
  3991         -        }
  3992         -        errCnt++;
  3993         -      }
  3994         -      free(zSql);
  3995         -      zSql = 0;
  3996         -      nSql = 0;
  3997         -    }
  3998         -  }
  3999         -  if( zSql ){
  4000         -    if( !_all_whitespace(zSql) ){
  4001         -      fprintf(stderr, "Error: incomplete SQL: %s\n", zSql);
  4002         -    }
  4003         -    free(zSql);
  4004         -  }
  4005         -  free(zLine);
         4846  +		if (rc || zErrMsg)
         4847  +		  {
         4848  +		      char zPrefix[100];
         4849  +		      if (in != 0 || !stdin_is_interactive)
         4850  +			{
         4851  +			    sqlite3_snprintf (sizeof (zPrefix), zPrefix,
         4852  +					      "Error: near line %d:",
         4853  +					      startline);
         4854  +			}
         4855  +		      else
         4856  +			{
         4857  +			    sqlite3_snprintf (sizeof (zPrefix), zPrefix,
         4858  +					      "Error:");
         4859  +			}
         4860  +		      if (zErrMsg != 0)
         4861  +			{
         4862  +			    fprintf (stderr, "%s %s\n", zPrefix, zErrMsg);
         4863  +			    sqlite3_free (zErrMsg);
         4864  +			    zErrMsg = 0;
         4865  +			}
         4866  +		      else
         4867  +			{
         4868  +			    fprintf (stderr, "%s %s\n", zPrefix,
         4869  +				     sqlite3_errmsg (p->db));
         4870  +			}
         4871  +		      errCnt++;
         4872  +		  }
         4873  +		free (zSql);
         4874  +		zSql = 0;
         4875  +		nSql = 0;
         4876  +	    }
         4877  +      }
         4878  +    if (zSql)
         4879  +      {
         4880  +	  if (!_all_whitespace (zSql))
         4881  +	    {
         4882  +		fprintf (stderr, "Error: incomplete SQL: %s\n", zSql);
         4883  +	    }
         4884  +	  free (zSql);
         4885  +      }
         4886  +    free (zLine);
  4006   4887   
  4007   4888   /* Sandro Furieri - 11 July 2008 */
  4008         -  if (in_charset_to_utf8)
  4009         -  {
  4010         -  /* destroying input converter, if exists */
  4011         -      iconv_close (in_charset_to_utf8);
  4012         -      in_charset_to_utf8 = NULL;	
  4013         -   }	
         4889  +    if (in_charset_to_utf8)
         4890  +      {
         4891  +	  /* destroying input converter, if exists */
         4892  +	  iconv_close (in_charset_to_utf8);
         4893  +	  in_charset_to_utf8 = NULL;
         4894  +      }
  4014   4895   /* End Sandro Furieri - 11 July 2008 */
  4015   4896   
  4016         -  return errCnt;
         4897  +    return errCnt;
  4017   4898   }
  4018   4899   
  4019   4900   /*
  4020   4901   ** Return a pathname which is the user's home directory.  A
  4021   4902   ** 0 return indicates an error of some kind.
  4022   4903   */
  4023         -static char *find_home_dir(void){
  4024         -  static char *home_dir = NULL;
  4025         -  if( home_dir ) return home_dir;
         4904  +static char *
         4905  +find_home_dir (void)
         4906  +{
         4907  +    static char *home_dir = NULL;
         4908  +    if (home_dir)
         4909  +	return home_dir;
  4026   4910   
  4027   4911   #if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) && !defined(__RTP__) && !defined(_WRS_KERNEL)
  4028         -  {
  4029         -    struct passwd *pwent;
  4030         -    uid_t uid = getuid();
  4031         -    if( (pwent=getpwuid(uid)) != NULL) {
  4032         -      home_dir = pwent->pw_dir;
         4912  +    {
         4913  +	struct passwd *pwent;
         4914  +	uid_t uid = getuid ();
         4915  +	if ((pwent = getpwuid (uid)) != NULL)
         4916  +	  {
         4917  +	      home_dir = pwent->pw_dir;
         4918  +	  }
  4033   4919       }
  4034         -  }
  4035   4920   #endif
  4036   4921   
  4037   4922   #if defined(_WIN32_WCE)
  4038         -  /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
  4039         -   */
  4040         -  home_dir = "/";
         4923  +    /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
         4924  +     */
         4925  +    home_dir = "/";
  4041   4926   #else
  4042   4927   
  4043   4928   #if defined(_WIN32) || defined(WIN32)
  4044         -  if (!home_dir) {
  4045         -    home_dir = getenv("USERPROFILE");
  4046         -  }
         4929  +    if (!home_dir)
         4930  +      {
         4931  +	  home_dir = getenv ("USERPROFILE");
         4932  +      }
  4047   4933   #endif
  4048   4934   
  4049         -  if (!home_dir) {
  4050         -    home_dir = getenv("HOME");
  4051         -  }
         4935  +    if (!home_dir)
         4936  +      {
         4937  +	  home_dir = getenv ("HOME");
         4938  +      }
  4052   4939   
  4053   4940   #if defined(_WIN32) || defined(WIN32)
  4054         -  if (!home_dir) {
  4055         -    char *zDrive, *zPath;
  4056         -    int n;
  4057         -    zDrive = getenv("HOMEDRIVE");
  4058         -    zPath = getenv("HOMEPATH");
  4059         -    if( zDrive && zPath ){
  4060         -      n = strlen30(zDrive) + strlen30(zPath) + 1;
  4061         -      home_dir = malloc( n );
  4062         -      if( home_dir==0 ) return 0;
  4063         -      sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
  4064         -      return home_dir;
  4065         -    }
  4066         -    home_dir = "c:\\";
  4067         -  }
         4941  +    if (!home_dir)
         4942  +      {
         4943  +	  char *zDrive, *zPath;
         4944  +	  int n;
         4945  +	  zDrive = getenv ("HOMEDRIVE");
         4946  +	  zPath = getenv ("HOMEPATH");
         4947  +	  if (zDrive && zPath)
         4948  +	    {
         4949  +		n = strlen30 (zDrive) + strlen30 (zPath) + 1;
         4950  +		home_dir = malloc (n);
         4951  +		if (home_dir == 0)
         4952  +		    return 0;
         4953  +		sqlite3_snprintf (n, home_dir, "%s%s", zDrive, zPath);
         4954  +		return home_dir;
         4955  +	    }
         4956  +	  home_dir = "c:\\";
         4957  +      }
  4068   4958   #endif
  4069   4959   
  4070   4960   #endif /* !_WIN32_WCE */
  4071   4961   
  4072         -  if( home_dir ){
  4073         -    int n = strlen30(home_dir) + 1;
  4074         -    char *z = malloc( n );
  4075         -    if( z ) memcpy(z, home_dir, n);
  4076         -    home_dir = z;
  4077         -  }
         4962  +    if (home_dir)
         4963  +      {
         4964  +	  int n = strlen30 (home_dir) + 1;
         4965  +	  char *z = malloc (n);
         4966  +	  if (z)
         4967  +	      memcpy (z, home_dir, n);
         4968  +	  home_dir = z;
         4969  +      }
  4078   4970   
  4079         -  return home_dir;
         4971  +    return home_dir;
  4080   4972   }
  4081   4973   
  4082   4974   /*
  4083   4975   ** Read input from the file given by sqliterc_override.  Or if that
  4084   4976   ** parameter is NULL, take input from ~/.sqliterc
  4085   4977   **
  4086   4978   ** Returns the number of errors.
  4087   4979   */
  4088         -static int process_sqliterc(
  4089         -  struct callback_data *p,        /* Configuration data */
  4090         -  const char *sqliterc_override   /* Name of config file. NULL to use default */
  4091         -){
  4092         -  char *home_dir = NULL;
  4093         -  const char *sqliterc = sqliterc_override;
  4094         -  char *zBuf = 0;
  4095         -  FILE *in = NULL;
  4096         -  int rc = 0;
         4980  +static int
         4981  +process_sqliterc (struct callback_data *p,	/* Configuration data */
         4982  +		  const char *sqliterc_override	/* Name of config file. NULL to use default */
         4983  +    )
         4984  +{
         4985  +    char *home_dir = NULL;
         4986  +    const char *sqliterc = sqliterc_override;
         4987  +    char *zBuf = 0;
         4988  +    FILE *in = NULL;
         4989  +    int rc = 0;
  4097   4990   
  4098         -  if (sqliterc == NULL) {
  4099         -    home_dir = find_home_dir();
  4100         -    if( home_dir==0 ){
         4991  +    if (sqliterc == NULL)
         4992  +      {
         4993  +	  home_dir = find_home_dir ();
         4994  +	  if (home_dir == 0)
         4995  +	    {
  4101   4996   #if !defined(__RTP__) && !defined(_WRS_KERNEL)
  4102         -      fprintf(stderr,"%s: Error: cannot locate your home directory\n", Argv0);
         4997  +		fprintf (stderr,
         4998  +			 "%s: Error: cannot locate your home directory\n",
         4999  +			 Argv0);
  4103   5000   #endif
  4104         -      return 1;
  4105         -    }
  4106         -    sqlite3_initialize();
  4107         -    zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
  4108         -    sqliterc = zBuf;
  4109         -  }
  4110         -  in = fopen(sqliterc,"rb");
  4111         -  if( in ){
  4112         -    if( stdin_is_interactive ){
  4113         -      fprintf(stderr,"-- Loading resources from %s\n",sqliterc);
  4114         -    }
  4115         -    rc = process_input(p,in, 0);
  4116         -    fclose(in);
  4117         -  }
  4118         -  sqlite3_free(zBuf);
  4119         -  return rc;
         5001  +		return 1;
         5002  +	    }
         5003  +	  sqlite3_initialize ();
         5004  +	  zBuf = sqlite3_mprintf ("%s/.sqliterc", home_dir);
         5005  +	  sqliterc = zBuf;
         5006  +      }
         5007  +    in = fopen (sqliterc, "rb");
         5008  +    if (in)
         5009  +      {
         5010  +	  if (stdin_is_interactive)
         5011  +	    {
         5012  +		fprintf (stderr, "-- Loading resources from %s\n", sqliterc);
         5013  +	    }
         5014  +	  rc = process_input (p, in, 0);
         5015  +	  fclose (in);
         5016  +      }
         5017  +    sqlite3_free (zBuf);
         5018  +    return rc;
  4120   5019   }
  4121   5020   
  4122   5021   /*
  4123   5022   ** Show available command line options
  4124   5023   */
  4125         -static const char zOptions[] = 
  4126         -  "   -bail                stop after hitting an error\n"
  4127         -  "   -batch               force batch I/O\n"
  4128         -  "   -column              set output mode to 'column'\n"
  4129         -  "   -cmd command         run \"command\" before reading stdin\n"
  4130         -  "   -csv                 set output mode to 'csv'\n"
  4131         -  "   -echo                print commands before execution\n"
  4132         -  "   -init filename       read/process named file\n"
  4133         -  "   -[no]header          turn headers on or off\n"
  4134         -  "   -help                show this message\n"
  4135         -  "   -html                set output mode to HTML\n"
  4136         -  "   -interactive         force interactive I/O\n"
  4137         -  "   -line                set output mode to 'line'\n"
  4138         -  "   -list                set output mode to 'list'\n"
  4139         -  "   -silent              suppress the welcome message\n"
         5024  +static const char zOptions[] =
         5025  +    "   -bail                stop after hitting an error\n"
         5026  +    "   -batch               force batch I/O\n"
         5027  +    "   -column              set output mode to 'column'\n"
         5028  +    "   -cmd command         run \"command\" before reading stdin\n"
         5029  +    "   -csv                 set output mode to 'csv'\n"
         5030  +    "   -echo                print commands before execution\n"
         5031  +    "   -init filename       read/process named file\n"
         5032  +    "   -[no]header          turn headers on or off\n"
         5033  +    "   -help                show this message\n"
         5034  +    "   -html                set output mode to HTML\n"
         5035  +    "   -interactive         force interactive I/O\n"
         5036  +    "   -line                set output mode to 'line'\n"
         5037  +    "   -list                set output mode to 'list'\n"
         5038  +    "   -silent              suppress the welcome message\n"
  4140   5039   #ifdef SQLITE_ENABLE_MULTIPLEX
  4141         -  "   -multiplex           enable the multiplexor VFS\n"
         5040  +    "   -multiplex           enable the multiplexor VFS\n"
  4142   5041   #endif
  4143         -  "   -nullvalue 'text'    set text string for NULL values\n"
  4144         -  "   -separator 'x'       set output field separator (|)\n"
  4145         -  "   -stats               print memory stats before each finalize\n"
  4146         -  "   -version             show SQLite version\n"
  4147         -  "   -vfs NAME            use NAME as the default VFS\n"
         5042  +    "   -nullvalue 'text'    set text string for NULL values\n"
         5043  +    "   -separator 'x'       set output field separator (|)\n"
         5044  +    "   -stats               print memory stats before each finalize\n"
         5045  +    "   -version             show SQLite version\n"
         5046  +    "   -vfs NAME            use NAME as the default VFS\n"
  4148   5047   #ifdef SQLITE_ENABLE_VFSTRACE
  4149         -  "   -vfstrace            enable tracing of all VFS calls\n"
         5048  +    "   -vfstrace            enable tracing of all VFS calls\n"
  4150   5049   #endif
  4151         -;
  4152         -static void usage(int showDetail){
  4153         -  fprintf(stderr,
  4154         -      "Usage: %s [OPTIONS] FILENAME [SQL]\n"  
  4155         -      "FILENAME is the name of an SQLite database. A new database is created\n"
  4156         -      "if the file does not previously exist.\n", Argv0);
  4157         -  if( showDetail ){
  4158         -    fprintf(stderr, "OPTIONS include:\n%s", zOptions);
  4159         -  }else{
  4160         -    fprintf(stderr, "Use the -help option for additional information\n");
  4161         -  }
  4162         -  exit(1);
         5050  +    ;
         5051  +static void
         5052  +usage (int showDetail)
         5053  +{
         5054  +    fprintf (stderr,
         5055  +	     "Usage: %s [OPTIONS] FILENAME [SQL]\n"
         5056  +	     "FILENAME is the name of an SQLite database. A new database is created\n"
         5057  +	     "if the file does not previously exist.\n", Argv0);
         5058  +    if (showDetail)
         5059  +      {
         5060  +	  fprintf (stderr, "OPTIONS include:\n%s", zOptions);
         5061  +      }
         5062  +    else
         5063  +      {
         5064  +	  fprintf (stderr, "Use the -help option for additional information\n");
         5065  +      }
         5066  +    exit (1);
  4163   5067   }
  4164   5068   
  4165   5069   /*
  4166   5070   ** Initialize the state information in data
  4167   5071   */
  4168         -static void main_init(struct callback_data *data) {
  4169         -  memset(data, 0, sizeof(*data));
  4170         -  data->mode = MODE_List;
  4171         -  memcpy(data->separator,"|", 2);
  4172         -  data->showHeader = 0;
         5072  +static void
         5073  +main_init (struct callback_data *data)
         5074  +{
         5075  +    memset (data, 0, sizeof (*data));
         5076  +    data->mode = MODE_List;
         5077  +    memcpy (data->separator, "|", 2);
         5078  +    data->showHeader = 0;
  4173   5079   /* Sandro Furieri 1 November 2012 - depending on SQLite version */
  4174   5080   #ifdef HAVE_DECL_SQLITE_CONFIG_URI
  4175         -  sqlite3_config(SQLITE_CONFIG_URI, 1);
         5081  +    sqlite3_config (SQLITE_CONFIG_URI, 1);
  4176   5082   #endif
  4177   5083   /* end sandro 1 November 2012 */
  4178         -  sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
  4179         -  sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"spatialite> ");
  4180         -  sqlite3_snprintf(sizeof(continuePrompt), continuePrompt,"   ...> ");
  4181         -  sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);
         5084  +    sqlite3_config (SQLITE_CONFIG_LOG, shellLog, data);
         5085  +    sqlite3_snprintf (sizeof (mainPrompt), mainPrompt, "spatialite> ");
         5086  +    sqlite3_snprintf (sizeof (continuePrompt), continuePrompt, "   ...> ");
         5087  +    sqlite3_config (SQLITE_CONFIG_SINGLETHREAD);
  4182   5088   }
  4183   5089   
  4184         -int main(int argc, char **argv){
  4185         -  char *zErrMsg = 0;
  4186         -  struct callback_data data;
  4187         -  const char *zInitFile = 0;
  4188         -  char *zFirstCmd = 0;
  4189         -  int i;
  4190         -  int rc = 0;
  4191         -  
         5090  +int
         5091  +main (int argc, char **argv)
         5092  +{
         5093  +    char *zErrMsg = 0;
         5094  +    struct callback_data data;
         5095  +    const char *zInitFile = 0;
         5096  +    char *zFirstCmd = 0;
         5097  +    int i;
         5098  +    int rc = 0;
         5099  +
  4192   5100   /* initializing the SpatiaLite's internal cache */
  4193         -  splite_cache = spatialite_alloc_connection ();
         5101  +    splite_cache = spatialite_alloc_connection ();
  4194   5102   
         5103  +/*
         5104  + * sandro: 2015-06-26
         5105  + * 
         5106  + * disabling version check as suggested by Fedora and Debian maintainers
         5107  + * 
  4195   5108     if( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)!=0 ){
  4196   5109       fprintf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
  4197   5110               sqlite3_sourceid(), SQLITE_SOURCE_ID);
  4198   5111       exit(1);
  4199   5112     }
  4200         -  Argv0 = argv[0];
  4201         -  main_init(&data);
         5113  +*/
         5114  +
         5115  +    Argv0 = argv[0];
         5116  +    main_init (&data);
  4202   5117   /*
  4203   5118   Sandro Furieri 30 May 2008
  4204   5119   ===========================
  4205   5120   registering the SpatiaLite extension
  4206   5121   2013-08-30: supporting "silent mode"
  4207   5122   */
  4208         -  for(i=1; i<argc && argv[i][0]=='-'; i++){
  4209         -    char *z = argv[i];
  4210         -    if( z[1]=='-' ){ z++; }
  4211         -    if( strcmp(z,"-silent")==0 ){ splite_silent = 1;}
  4212         -	}
         5123  +    for (i = 1; i < argc && argv[i][0] == '-'; i++)
         5124  +      {
         5125  +	  char *z = argv[i];
         5126  +	  if (z[1] == '-')
         5127  +	    {
         5128  +		z++;
         5129  +	    }
         5130  +	  if (strcmp (z, "-silent") == 0)
         5131  +	    {
         5132  +		splite_silent = 1;
         5133  +	    }
         5134  +      }
  4213   5135   
  4214         -  stdin_is_interactive = isatty(0);
         5136  +    stdin_is_interactive = isatty (0);
  4215   5137   
  4216         -  /* Make sure we have a valid signal handler early, before anything
  4217         -  ** else is done.
  4218         -  */
         5138  +    /* Make sure we have a valid signal handler early, before anything
         5139  +     ** else is done.
         5140  +     */
  4219   5141   #ifdef SIGINT
  4220         -  signal(SIGINT, interrupt_handler);
         5142  +    signal (SIGINT, interrupt_handler);
  4221   5143   #endif
  4222   5144   
  4223         -  /* Do an initial pass through the command-line argument to locate
  4224         -  ** the name of the database file, the name of the initialization file,
  4225         -  ** the size of the alternative malloc heap,
  4226         -  ** and the first command to execute.
  4227         -  */
  4228         -  for(i=1; i<argc-1; i++){
  4229         -    char *z;
  4230         -    if( argv[i][0]!='-' ) break;
  4231         -    z = argv[i];
  4232         -    if( z[1]=='-' ) z++;
  4233         -    if( strcmp(z,"-separator")==0
  4234         -     || strcmp(z,"-nullvalue")==0
  4235         -     || strcmp(z,"-cmd")==0
  4236         -    ){
  4237         -      i++;
  4238         -    }else if( strcmp(z,"-init")==0 ){
  4239         -      i++;
  4240         -      zInitFile = argv[i];
  4241         -    /* Need to check for batch mode here to so we can avoid printing
  4242         -    ** informational messages (like from process_sqliterc) before 
  4243         -    ** we do the actual processing of arguments later in a second pass.
  4244         -    */
  4245         -    }else if( strcmp(z,"-batch")==0 ){
  4246         -      stdin_is_interactive = 0;
  4247         -    }else if( strcmp(z,"-heap")==0 ){
         5145  +    /* Do an initial pass through the command-line argument to locate
         5146  +     ** the name of the database file, the name of the initialization file,
         5147  +     ** the size of the alternative malloc heap,
         5148  +     ** and the first command to execute.
         5149  +     */
         5150  +    for (i = 1; i < argc - 1; i++)
         5151  +      {
         5152  +	  char *z;
         5153  +	  if (argv[i][0] != '-')
         5154  +	      break;
         5155  +	  z = argv[i];
         5156  +	  if (z[1] == '-')
         5157  +	      z++;
         5158  +	  if (strcmp (z, "-separator") == 0
         5159  +	      || strcmp (z, "-nullvalue") == 0 || strcmp (z, "-cmd") == 0)
         5160  +	    {
         5161  +		i++;
         5162  +	    }
         5163  +	  else if (strcmp (z, "-init") == 0)
         5164  +	    {
         5165  +		i++;
         5166  +		zInitFile = argv[i];
         5167  +		/* Need to check for batch mode here to so we can avoid printing
         5168  +		 ** informational messages (like from process_sqliterc) before 
         5169  +		 ** we do the actual processing of arguments later in a second pass.
         5170  +		 */
         5171  +	    }
         5172  +	  else if (strcmp (z, "-batch") == 0)
         5173  +	    {
         5174  +		stdin_is_interactive = 0;
         5175  +	    }
         5176  +	  else if (strcmp (z, "-heap") == 0)
         5177  +	    {
  4248   5178   #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
  4249         -      int j, c;
  4250         -      const char *zSize;
  4251         -      sqlite3_int64 szHeap;
         5179  +		int j, c;
         5180  +		const char *zSize;
         5181  +		sqlite3_int64 szHeap;
  4252   5182   
  4253         -      zSize = argv[++i];
  4254         -      szHeap = atoi(zSize);
  4255         -      for(j=0; (c = zSize[j])!=0; j++){
  4256         -        if( c=='M' ){ szHeap *= 1000000; break; }
  4257         -        if( c=='K' ){ szHeap *= 1000; break; }
  4258         -        if( c=='G' ){ szHeap *= 1000000000; break; }
  4259         -      }
  4260         -      if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
  4261         -      sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
         5183  +		zSize = argv[++i];
         5184  +		szHeap = atoi (zSize);
         5185  +		for (j = 0; (c = zSize[j]) != 0; j++)
         5186  +		  {
         5187  +		      if (c == 'M')
         5188  +			{
         5189  +			    szHeap *= 1000000;
         5190  +			    break;
         5191  +			}
         5192  +		      if (c == 'K')
         5193  +			{
         5194  +			    szHeap *= 1000;
         5195  +			    break;
         5196  +			}
         5197  +		      if (c == 'G')
         5198  +			{
         5199  +			    szHeap *= 1000000000;
         5200  +			    break;
         5201  +			}
         5202  +		  }
         5203  +		if (szHeap > 0x7fff0000)
         5204  +		    szHeap = 0x7fff0000;
         5205  +		sqlite3_config (SQLITE_CONFIG_HEAP, malloc ((int) szHeap),
         5206  +				(int) szHeap, 64);
  4262   5207   #endif
  4263   5208   #ifdef SQLITE_ENABLE_VFSTRACE
  4264         -    }else if( strcmp(z,"-vfstrace")==0 ){
  4265         -      extern int vfstrace_register(
  4266         -         const char *zTraceName,
  4267         -         const char *zOldVfsName,
  4268         -         int (*xOut)(const char*,void*),
  4269         -         void *pOutArg,
  4270         -         int makeDefault
  4271         -      );
  4272         -      vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
         5209  +	    }
         5210  +	  else if (strcmp (z, "-vfstrace") == 0)
         5211  +	    {
         5212  +		extern int vfstrace_register (const char *zTraceName,
         5213  +					      const char *zOldVfsName,
         5214  +					      int (*xOut) (const char *,
         5215  +							   void *),
         5216  +					      void *pOutArg, int makeDefault);
         5217  +		vfstrace_register ("trace", 0,
         5218  +				   (int (*)(const char *, void *)) fputs,
         5219  +				   stderr, 1);
  4273   5220   #endif
  4274   5221   #ifdef SQLITE_ENABLE_MULTIPLEX
  4275         -    }else if( strcmp(z,"-multiplex")==0 ){
  4276         -      extern int sqlite3_multiple_initialize(const char*,int);
  4277         -      sqlite3_multiplex_initialize(0, 1);
         5222  +	    }
         5223  +	  else if (strcmp (z, "-multiplex") == 0)
         5224  +	    {
         5225  +		extern int sqlite3_multiple_initialize (const char *, int);
         5226  +		sqlite3_multiplex_initialize (0, 1);
  4278   5227   #endif
  4279         -    }else if( strcmp(z,"-vfs")==0 ){
  4280         -      sqlite3_vfs *pVfs = sqlite3_vfs_find(argv[++i]);
  4281         -      if( pVfs ){
  4282         -        sqlite3_vfs_register(pVfs, 1);
  4283         -      }else{
  4284         -        fprintf(stderr, "no such VFS: \"%s\"\n", argv[i]);
  4285         -        exit(1);
         5228  +	    }
         5229  +	  else if (strcmp (z, "-vfs") == 0)
         5230  +	    {
         5231  +		sqlite3_vfs *pVfs = sqlite3_vfs_find (argv[++i]);
         5232  +		if (pVfs)
         5233  +		  {
         5234  +		      sqlite3_vfs_register (pVfs, 1);
         5235  +		  }
         5236  +		else
         5237  +		  {
         5238  +		      fprintf (stderr, "no such VFS: \"%s\"\n", argv[i]);
         5239  +		      exit (1);
         5240  +		  }
         5241  +	    }
         5242  +      }
         5243  +    if (i < argc)
         5244  +      {
         5245  +	  data.zDbFilename = argv[i++];
  4286   5246         }
  4287         -    }
  4288         -  }
  4289         -  if( i<argc ){
  4290         -    data.zDbFilename = argv[i++];
  4291         -  }else{
         5247  +    else
         5248  +      {
  4292   5249   #ifndef SQLITE_OMIT_MEMORYDB
  4293         -    data.zDbFilename = ":memory:";
         5250  +	  data.zDbFilename = ":memory:";
  4294   5251   #else
  4295         -    data.zDbFilename = 0;
         5252  +	  data.zDbFilename = 0;
  4296   5253   #endif
  4297         -  }
  4298         -  if( i<argc ){
  4299         -    zFirstCmd = argv[i++];
  4300         -  }
  4301         -  if( i<argc ){
  4302         -    fprintf(stderr,"%s: Error: too many options: \"%s\"\n", Argv0, argv[i]);
  4303         -    fprintf(stderr,"Use -help for a list of options.\n");
  4304         -    return 1;
  4305         -  }
  4306         -  data.out = stdout;
         5254  +      }
         5255  +    if (i < argc)
         5256  +      {
         5257  +	  zFirstCmd = argv[i++];
         5258  +      }
         5259  +    if (i < argc)
         5260  +      {
         5261  +	  fprintf (stderr, "%s: Error: too many options: \"%s\"\n", Argv0,
         5262  +		   argv[i]);
         5263  +	  fprintf (stderr, "Use -help for a list of options.\n");
         5264  +	  return 1;
         5265  +      }
         5266  +    data.out = stdout;
  4307   5267   
  4308   5268   #ifdef SQLITE_OMIT_MEMORYDB
  4309         -  if( data.zDbFilename==0 ){
  4310         -    fprintf(stderr,"%s: Error: no database filename specified\n", Argv0);
  4311         -    return 1;
  4312         -  }
         5269  +    if (data.zDbFilename == 0)
         5270  +      {
         5271  +	  fprintf (stderr, "%s: Error: no database filename specified\n",
         5272  +		   Argv0);
         5273  +	  return 1;
         5274  +      }
  4313   5275   #endif
  4314   5276   
  4315         -  /* Go ahead and open the database file if it already exists.  If the
  4316         -  ** file does not exist, delay opening it.  This prevents empty database
  4317         -  ** files from being created if a user mistypes the database name argument
  4318         -  ** to the sqlite command-line tool.
  4319         -  */
  4320         -  if( access(data.zDbFilename, 0)==0 ){
  4321         -    open_db(&data);
  4322         -  }
         5277  +    /* Go ahead and open the database file if it already exists.  If the
         5278  +     ** file does not exist, delay opening it.  This prevents empty database
         5279  +     ** files from being created if a user mistypes the database name argument
         5280  +     ** to the sqlite command-line tool.
         5281  +     */
         5282  +    if (access (data.zDbFilename, 0) == 0)
         5283  +      {
         5284  +	  open_db (&data);
         5285  +      }
  4323   5286   
  4324         -  /* Process the initialization file if there is one.  If no -init option
  4325         -  ** is given on the command line, look for a file named ~/.sqliterc and
  4326         -  ** try to process it.
  4327         -  */
  4328         -  rc = process_sqliterc(&data,zInitFile);
  4329         -  if( rc>0 ){
  4330         -    return rc;
  4331         -  }
         5287  +    /* Process the initialization file if there is one.  If no -init option
         5288  +     ** is given on the command line, look for a file named ~/.sqliterc and
         5289  +     ** try to process it.
         5290  +     */
         5291  +    rc = process_sqliterc (&data, zInitFile);
         5292  +    if (rc > 0)
         5293  +      {
         5294  +	  return rc;
         5295  +      }
  4332   5296   
  4333         -  /* Make a second pass through the command-line argument and set
  4334         -  ** options.  This second pass is delayed until after the initialization
  4335         -  ** file is processed so that the command-line arguments will override
  4336         -  ** settings in the initialization file.
  4337         -  */
  4338         -  for(i=1; i<argc && argv[i][0]=='-'; i++){
  4339         -    char *z = argv[i];
  4340         -    if( z[1]=='-' ){ z++; }
  4341         -    if( strcmp(z,"-init")==0 ){
  4342         -      i++;
  4343         -    }else if( strcmp(z,"-html")==0 ){
  4344         -      data.mode = MODE_Html;
  4345         -    }else if( strcmp(z,"-list")==0 ){
  4346         -      data.mode = MODE_List;
  4347         -    }else if( strcmp(z,"-line")==0 ){
  4348         -      data.mode = MODE_Line;
  4349         -    }else if( strcmp(z,"-column")==0 ){
  4350         -      data.mode = MODE_Column;
  4351         -    }else if( strcmp(z,"-csv")==0 ){
  4352         -      data.mode = MODE_Csv;
  4353         -      memcpy(data.separator,",",2);
  4354         -    }else if( strcmp(z,"-separator")==0 ){
  4355         -      i++;
  4356         -      if(i>=argc){
  4357         -        fprintf(stderr,"%s: Error: missing argument for option: %s\n",
  4358         -                        Argv0, z);
  4359         -        fprintf(stderr,"Use -help for a list of options.\n");
  4360         -        return 1;
  4361         -      }
  4362         -      sqlite3_snprintf(sizeof(data.separator), data.separator,
  4363         -                       "%.*s",(int)sizeof(data.separator)-1,argv[i]);
  4364         -    }else if( strcmp(z,"-nullvalue")==0 ){
  4365         -      i++;
  4366         -      if(i>=argc){
  4367         -        fprintf(stderr,"%s: Error: missing argument for option: %s\n",
  4368         -                        Argv0, z);
  4369         -        fprintf(stderr,"Use -help for a list of options.\n");
  4370         -        return 1;
  4371         -      }
  4372         -      sqlite3_snprintf(sizeof(data.nullvalue), data.nullvalue,
  4373         -                       "%.*s",(int)sizeof(data.nullvalue)-1,argv[i]);
  4374         -    }else if( strcmp(z,"-header")==0 ){
  4375         -      data.showHeader = 1;
  4376         -    }else if( strcmp(z,"-noheader")==0 ){
  4377         -      data.showHeader = 0;
  4378         -    }else if( strcmp(z,"-echo")==0 ){
  4379         -      data.echoOn = 1;
  4380         -    }else if( strcmp(z,"-stats")==0 ){
  4381         -      data.statsOn = 1;
  4382         -    }else if( strcmp(z,"-bail")==0 ){
  4383         -      bail_on_error = 1;
  4384         -    }else if( strcmp(z,"-silent")==0 ){
         5297  +    /* Make a second pass through the command-line argument and set
         5298  +     ** options.  This second pass is delayed until after the initialization
         5299  +     ** file is processed so that the command-line arguments will override
         5300  +     ** settings in the initialization file.
         5301  +     */
         5302  +    for (i = 1; i < argc && argv[i][0] == '-'; i++)
         5303  +      {
         5304  +	  char *z = argv[i];
         5305  +	  if (z[1] == '-')
         5306  +	    {
         5307  +		z++;
         5308  +	    }
         5309  +	  if (strcmp (z, "-init") == 0)
         5310  +	    {
         5311  +		i++;
         5312  +	    }
         5313  +	  else if (strcmp (z, "-html") == 0)
         5314  +	    {
         5315  +		data.mode = MODE_Html;
         5316  +	    }
         5317  +	  else if (strcmp (z, "-list") == 0)
         5318  +	    {
         5319  +		data.mode = MODE_List;
         5320  +	    }
         5321  +	  else if (strcmp (z, "-line") == 0)
         5322  +	    {
         5323  +		data.mode = MODE_Line;
         5324  +	    }
         5325  +	  else if (strcmp (z, "-column") == 0)
         5326  +	    {
         5327  +		data.mode = MODE_Column;
         5328  +	    }
         5329  +	  else if (strcmp (z, "-csv") == 0)
         5330  +	    {
         5331  +		data.mode = MODE_Csv;
         5332  +		memcpy (data.separator, ",", 2);
         5333  +	    }
         5334  +	  else if (strcmp (z, "-separator") == 0)
         5335  +	    {
         5336  +		i++;
         5337  +		if (i >= argc)
         5338  +		  {
         5339  +		      fprintf (stderr,
         5340  +			       "%s: Error: missing argument for option: %s\n",
         5341  +			       Argv0, z);
         5342  +		      fprintf (stderr, "Use -help for a list of options.\n");
         5343  +		      return 1;
         5344  +		  }
         5345  +		sqlite3_snprintf (sizeof (data.separator), data.separator,
         5346  +				  "%.*s", (int) sizeof (data.separator) - 1,
         5347  +				  argv[i]);
         5348  +	    }
         5349  +	  else if (strcmp (z, "-nullvalue") == 0)
         5350  +	    {
         5351  +		i++;
         5352  +		if (i >= argc)
         5353  +		  {
         5354  +		      fprintf (stderr,
         5355  +			       "%s: Error: missing argument for option: %s\n",
         5356  +			       Argv0, z);
         5357  +		      fprintf (stderr, "Use -help for a list of options.\n");
         5358  +		      return 1;
         5359  +		  }
         5360  +		sqlite3_snprintf (sizeof (data.nullvalue), data.nullvalue,
         5361  +				  "%.*s", (int) sizeof (data.nullvalue) - 1,
         5362  +				  argv[i]);
         5363  +	    }
         5364  +	  else if (strcmp (z, "-header") == 0)
         5365  +	    {
         5366  +		data.showHeader = 1;
         5367  +	    }
         5368  +	  else if (strcmp (z, "-noheader") == 0)
         5369  +	    {
         5370  +		data.showHeader = 0;
         5371  +	    }
         5372  +	  else if (strcmp (z, "-echo") == 0)
         5373  +	    {
         5374  +		data.echoOn = 1;
         5375  +	    }
         5376  +	  else if (strcmp (z, "-stats") == 0)
         5377  +	    {
         5378  +		data.statsOn = 1;
         5379  +	    }
         5380  +	  else if (strcmp (z, "-bail") == 0)
         5381  +	    {
         5382  +		bail_on_error = 1;
         5383  +	    }
         5384  +	  else if (strcmp (z, "-silent") == 0)
         5385  +	    {
  4385   5386   /* sandro 2013-08-30 */
  4386         -      splite_silent = 1;
         5387  +		splite_silent = 1;
  4387   5388   /* end sandro */
  4388         -    }else if( strcmp(z,"-version")==0 ){
  4389         -      printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
  4390         -      return 0;
  4391         -    }else if( strcmp(z,"-interactive")==0 ){
  4392         -      stdin_is_interactive = 1;
  4393         -    }else if( strcmp(z,"-batch")==0 ){
  4394         -      stdin_is_interactive = 0;
  4395         -    }else if( strcmp(z,"-heap")==0 ){
  4396         -      i++;
  4397         -    }else if( strcmp(z,"-vfs")==0 ){
  4398         -      i++;
         5389  +	    }
         5390  +	  else if (strcmp (z, "-version") == 0)
         5391  +	    {
         5392  +		printf ("%s %s\n", sqlite3_libversion (), sqlite3_sourceid ());
         5393  +		return 0;
         5394  +	    }
         5395  +	  else if (strcmp (z, "-interactive") == 0)
         5396  +	    {
         5397  +		stdin_is_interactive = 1;
         5398  +	    }
         5399  +	  else if (strcmp (z, "-batch") == 0)
         5400  +	    {
         5401  +		stdin_is_interactive = 0;
         5402  +	    }
         5403  +	  else if (strcmp (z, "-heap") == 0)
         5404  +	    {
         5405  +		i++;
         5406  +	    }
         5407  +	  else if (strcmp (z, "-vfs") == 0)
         5408  +	    {
         5409  +		i++;
  4399   5410   #ifdef SQLITE_ENABLE_VFSTRACE
  4400         -    }else if( strcmp(z,"-vfstrace")==0 ){
  4401         -      i++;
         5411  +	    }
         5412  +	  else if (strcmp (z, "-vfstrace") == 0)
         5413  +	    {
         5414  +		i++;
  4402   5415   #endif
  4403   5416   #ifdef SQLITE_ENABLE_MULTIPLEX
  4404         -    }else if( strcmp(z,"-multiplex")==0 ){
  4405         -      i++;
         5417  +	    }
         5418  +	  else if (strcmp (z, "-multiplex") == 0)
         5419  +	    {
         5420  +		i++;
  4406   5421   #endif
  4407         -    }else if( strcmp(z,"-help")==0 ){
  4408         -      usage(1);
  4409         -    }else if( strcmp(z,"-cmd")==0 ){
  4410         -      if( i==argc-1 ) break;
  4411         -      i++;
  4412         -      z = argv[i];
  4413         -      if( z[0]=='.' ){
  4414         -        rc = do_meta_command(z, &data);
  4415         -        if( rc && bail_on_error ) return rc;
  4416         -      }else{
  4417         -        open_db(&data);
  4418         -        rc = shell_exec(data.db, z, shell_callback, &data, &zErrMsg);
  4419         -        if( zErrMsg!=0 ){
  4420         -          fprintf(stderr,"Error: %s\n", zErrMsg);
  4421         -          if( bail_on_error ) return rc!=0 ? rc : 1;
  4422         -        }else if( rc!=0 ){
  4423         -          fprintf(stderr,"Error: unable to process SQL \"%s\"\n", z);
  4424         -          if( bail_on_error ) return rc;
  4425         -        }
  4426         -      }
  4427         -    }else{
  4428         -      fprintf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
  4429         -      fprintf(stderr,"Use -help for a list of options.\n");
  4430         -      return 1;
  4431         -    }
  4432         -  }
         5422  +	    }
         5423  +	  else if (strcmp (z, "-help") == 0)
         5424  +	    {
         5425  +		usage (1);
         5426  +	    }
         5427  +	  else if (strcmp (z, "-cmd") == 0)
         5428  +	    {
         5429  +		if (i == argc - 1)
         5430  +		    break;
         5431  +		i++;
         5432  +		z = argv[i];
         5433  +		if (z[0] == '.')
         5434  +		  {
         5435  +		      rc = do_meta_command (z, &data);
         5436  +		      if (rc && bail_on_error)
         5437  +			  return rc;
         5438  +		  }
         5439  +		else
         5440  +		  {
         5441  +		      open_db (&data);
         5442  +		      rc = shell_exec (data.db, z, shell_callback, &data,
         5443  +				       &zErrMsg);
         5444  +		      if (zErrMsg != 0)
         5445  +			{
         5446  +			    fprintf (stderr, "Error: %s\n", zErrMsg);
         5447  +			    if (bail_on_error)
         5448  +				return rc != 0 ? rc : 1;
         5449  +			}
         5450  +		      else if (rc != 0)
         5451  +			{
         5452  +			    fprintf (stderr,
         5453  +				     "Error: unable to process SQL \"%s\"\n",
         5454  +				     z);
         5455  +			    if (bail_on_error)
         5456  +				return rc;
         5457  +			}
         5458  +		  }
         5459  +	    }
         5460  +	  else
         5461  +	    {
         5462  +		fprintf (stderr, "%s: Error: unknown option: %s\n", Argv0, z);
         5463  +		fprintf (stderr, "Use -help for a list of options.\n");
         5464  +		return 1;
         5465  +	    }
         5466  +      }
  4433   5467   
  4434         -  if( zFirstCmd ){
  4435         -    /* Run just the command that follows the database name
  4436         -    */
  4437         -    if( zFirstCmd[0]=='.' ){
  4438         -      rc = do_meta_command(zFirstCmd, &data);
  4439         -    }else{
  4440         -      open_db(&data);
  4441         -      rc = shell_exec(data.db, zFirstCmd, shell_callback, &data, &zErrMsg);
  4442         -      if( zErrMsg!=0 ){
  4443         -        fprintf(stderr,"Error: %s\n", zErrMsg);
  4444         -        return rc!=0 ? rc : 1;
  4445         -      }else if( rc!=0 ){
  4446         -        fprintf(stderr,"Error: unable to process SQL \"%s\"\n", zFirstCmd);
  4447         -        return rc;
         5468  +    if (zFirstCmd)
         5469  +      {
         5470  +	  /* Run just the command that follows the database name
         5471  +	   */
         5472  +	  if (zFirstCmd[0] == '.')
         5473  +	    {
         5474  +		rc = do_meta_command (zFirstCmd, &data);
         5475  +	    }
         5476  +	  else
         5477  +	    {
         5478  +		open_db (&data);
         5479  +		rc = shell_exec (data.db, zFirstCmd, shell_callback, &data,
         5480  +				 &zErrMsg);
         5481  +		if (zErrMsg != 0)
         5482  +		  {
         5483  +		      fprintf (stderr, "Error: %s\n", zErrMsg);
         5484  +		      return rc != 0 ? rc : 1;
         5485  +		  }
         5486  +		else if (rc != 0)
         5487  +		  {
         5488  +		      fprintf (stderr, "Error: unable to process SQL \"%s\"\n",
         5489  +			       zFirstCmd);
         5490  +		      return rc;
         5491  +		  }
         5492  +	    }
  4448   5493         }
  4449         -    }
  4450         -  }else{
  4451         -    /* Run commands received from standard input
  4452         -    */
  4453         -    if( stdin_is_interactive ){
  4454         -      char *zHome;
  4455         -      char *zHistory = 0;
  4456         -      int nHistory;
         5494  +    else
         5495  +      {
         5496  +	  /* Run commands received from standard input
         5497  +	   */
         5498  +	  if (stdin_is_interactive)
         5499  +	    {
         5500  +		char *zHome;
         5501  +		char *zHistory = 0;
         5502  +		int nHistory;
  4457   5503   /* Sandro Furieri 2008-11-20
  4458   5504         printf(
  4459   5505           "SQLite version %s %.19s\n" 
  4460   5506           "Enter \".help\" for instructions\n"
  4461   5507           "Enter SQL statements terminated with a \";\"\n",
  4462   5508           sqlite3_libversion(), sqlite3_sourceid()
  4463   5509         );
  4464   5510   */
  4465         -     open_db(&data);
  4466         -     if (isatty (1))
  4467         -          printf ("SQLite version ......: %s\n",
  4468         -     sqlite3_libversion ());
  4469         -     auto_fdo_start (data.db);
  4470         -     if (isatty (1))
  4471         -         printf ("Enter \".help\" for instructions\n");
         5511  +		open_db (&data);
         5512  +		if (isatty (1))
         5513  +		    printf ("SQLite version ......: %s\n",
         5514  +			    sqlite3_libversion ());
         5515  +		auto_fdo_start (data.db);
         5516  +		if (isatty (1))
         5517  +		    printf ("Enter \".help\" for instructions\n");
  4472   5518   /* end Sandro Furieri 2008-11-20 */
  4473         -      printf(
  4474         -        "SQLite version %s %.19s\n" /*extra-version-info*/
  4475         -        "Enter \".help\" for instructions\n"
  4476         -        "Enter SQL statements terminated with a \";\"\n",
  4477         -        sqlite3_libversion(), sqlite3_sourceid()
  4478         -      );
  4479         -      zHome = find_home_dir();
  4480         -      if( zHome ){
  4481         -        nHistory = strlen30(zHome) + 20;
  4482         -        if( (zHistory = malloc(nHistory))!=0 ){
  4483         -          sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
  4484         -        }
  4485         -      }
         5519  +		printf ("SQLite version %s %.19s\n"	/*extra-version-info */
         5520  +			"Enter \".help\" for instructions\n"
         5521  +			"Enter SQL statements terminated with a \";\"\n",
         5522  +			sqlite3_libversion (), sqlite3_sourceid ());
         5523  +		zHome = find_home_dir ();
         5524  +		if (zHome)
         5525  +		  {
         5526  +		      nHistory = strlen30 (zHome) + 20;
         5527  +		      if ((zHistory = malloc (nHistory)) != 0)
         5528  +			{
         5529  +			    sqlite3_snprintf (nHistory, zHistory,
         5530  +					      "%s/.sqlite_history", zHome);
         5531  +			}
         5532  +		  }
  4486   5533   #if defined(HAVE_READLINE) && HAVE_READLINE==1
  4487         -      if( zHistory ) read_history(zHistory);
         5534  +		if (zHistory)
         5535  +		    read_history (zHistory);
  4488   5536   #endif
  4489         -      rc = process_input(&data, 0, 0);
  4490         -      if( zHistory ){
  4491         -        stifle_history(100);
  4492         -        write_history(zHistory);
  4493         -        free(zHistory);
         5537  +		rc = process_input (&data, 0, 0);
         5538  +		if (zHistory)
         5539  +		  {
         5540  +		      stifle_history (100);
         5541  +		      write_history (zHistory);
         5542  +		      free (zHistory);
         5543  +		  }
         5544  +	    }
         5545  +	  else
         5546  +	    {
         5547  +		rc = process_input (&data, stdin, 0);
         5548  +	    }
  4494   5549         }
  4495         -    }else{
  4496         -      rc = process_input(&data, stdin, 0);
  4497         -    }
  4498         -  }
  4499         -  set_table_name(&data, 0);
         5550  +    set_table_name (&data, 0);
  4500   5551       if (data.db)
  4501   5552         {
  4502   5553   /* Sandro Furieri 2008-11-20 */
  4503   5554   	  auto_fdo_stop (data.db);
  4504   5555   /* end Sandro Furieri 2008-11-20 */
         5556  +
         5557  +/* Sandro Furieri 2015-09-14 */
         5558  +	  spatialite_finalize_topologies (splite_cache);
         5559  +/* end Sandro Furieri 2015-09-14 */
         5560  +
  4505   5561   	  if (sqlite3_close (data.db) != SQLITE_OK)
  4506   5562   	    {
  4507   5563   		fprintf (stderr, "error closing database: %s\n",
  4508   5564   			 sqlite3_errmsg (data.db));
  4509   5565   	    }
  4510   5566         }
  4511   5567   
  4512   5568   
  4513   5569   /*
  4514   5570   Sandro Furieri 30 May 2008
  4515   5571   ===========================
  4516   5572   memory cleanup for SpatiaLite extension
  4517   5573   */
  4518         -    
  4519         -  spatialite_cleanup_ex (splite_cache);
  4520         -  spatialite_shutdown ();
         5574  +
         5575  +    spatialite_cleanup_ex (splite_cache);
         5576  +    spatialite_shutdown ();
  4521   5577   
  4522         -  return rc;
         5578  +    return rc;
  4523   5579   }

Changes to shp_doctor.c.

    44     44   #ifdef SPATIALITE_AMALGAMATION
    45     45   #include <spatialite/sqlite3.h>
    46     46   #else
    47     47   #include <sqlite3.h>
    48     48   #endif
    49     49   
    50     50   #include <spatialite/gaiageo.h>
           51  +#include <spatialite.h>
    51     52   
    52     53   #define ARG_NONE		0
    53     54   #define ARG_IN_PATH		1
    54     55   
    55     56   #if defined(_WIN32) && !defined(__MINGW32__)
    56     57   #define strcasecmp	_stricmp
    57     58   #endif /* not WIN32 */
................................................................................
  1463   1464       printf ("\nThis DBF is corrupted / has an invalid format");
  1464   1465       if (fl_dbf)
  1465   1466   	fclose (fl_dbf);
  1466   1467       if (buf_dbf)
  1467   1468   	free (buf_dbf);
  1468   1469       return;
  1469   1470   }
         1471  +
         1472  +static void
         1473  +do_version ()
         1474  +{
         1475  +/* printing version infos */
         1476  +	fprintf( stderr, "\nVersion infos\n");
         1477  +	fprintf( stderr, "===========================================\n");
         1478  +    fprintf (stderr, "shp_doctor ..: %s\n", VERSION);
         1479  +	fprintf (stderr, "target CPU ..: %s\n", spatialite_target_cpu ());
         1480  +    fprintf (stderr, "libspatialite: %s\n", spatialite_version ());
         1481  +    fprintf (stderr, "libsqlite3 ..: %s\n", sqlite3_libversion ());
         1482  +    fprintf (stderr, "\n");
         1483  +}
  1470   1484   
  1471   1485   static void
  1472   1486   do_help ()
  1473   1487   {
  1474   1488   /* printing the argument list */
  1475   1489       fprintf (stderr, "\n\nusage: shp_doctor ARGLIST\n");
  1476   1490       fprintf (stderr,
  1477   1491   	     "==============================================================\n");
  1478   1492       fprintf (stderr,
  1479   1493   	     "-h or --help                      print this help message\n");
         1494  +    fprintf (stderr, "-v or --version                   print version infos\n");
  1480   1495       fprintf (stderr,
  1481   1496   	     "-i or --in-path pathname          the SHP path [no suffix]\n");
  1482   1497       fprintf (stderr, "                                              or\n");
  1483   1498       fprintf (stderr,
  1484   1499   	     "                                  the full DBF path [-dbf]\n");
  1485   1500       fprintf (stderr, "\nyou can specify the following options as well\n");
  1486   1501       fprintf (stderr, "--analyze                 *default*\n");
................................................................................
  1518   1533   		continue;
  1519   1534   	    }
  1520   1535   	  if (strcasecmp (argv[i], "--help") == 0
  1521   1536   	      || strcmp (argv[i], "-h") == 0)
  1522   1537   	    {
  1523   1538   		do_help ();
  1524   1539   		return -1;
         1540  +	    }
         1541  +	  if (strcasecmp (argv[i], "--version") == 0
         1542  +	      || strcmp (argv[i], "-v") == 0)
         1543  +	    {
         1544  +		do_version ();
         1545  +		return -1;
  1525   1546   	    }
  1526   1547   	  if (strcasecmp (argv[i], "--in-path") == 0)
  1527   1548   	    {
  1528   1549   		next_arg = ARG_IN_PATH;
  1529   1550   		continue;
  1530   1551   	    }
  1531   1552   	  if (strcmp (argv[i], "-i") == 0)

Added shp_sanitize.c.

            1  +/* 
            2  +/ shp_sanitize
            3  +/
            4  +/ an analysis / sanitizing tool for  broken SHAPEFILES
            5  +/
            6  +/ version 1.0, 2016 April 25
            7  +/
            8  +/ Author: Sandro Furieri a.furieri@lqt.it
            9  +/
           10  +/ Copyright (C) 2016  Alessandro Furieri
           11  +/
           12  +/    This program is free software: you can redistribute it and/or modify
           13  +/    it under the terms of the GNU General Public License as published by
           14  +/    the Free Software Foundation, either version 3 of the License, or
           15  +/    (at your option) any later version.
           16  +/
           17  +/    This program is distributed in the hope that it will be useful,
           18  +/    but WITHOUT ANY WARRANTY; without even the implied warranty of
           19  +/    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
           20  +/    GNU General Public License for more details.
           21  +/
           22  +/    You should have received a copy of the GNU General Public License
           23  +/    along with this program.  If not, see <http://www.gnu.org/licenses/>.
           24  +/
           25  +*/
           26  +
           27  +#ifndef _WIN32
           28  +#include <unistd.h>
           29  +#endif
           30  +
           31  +#if defined(_WIN32) && !defined(__MINGW32__)
           32  +/* MSVC strictly requires this include [off_t] */
           33  +#include <sys/types.h>
           34  +#endif
           35  +
           36  +#include <stdlib.h>
           37  +#include <stdio.h>
           38  +#include <string.h>
           39  +#include <float.h>
           40  +#include <errno.h>
           41  +#include <sys/stat.h>
           42  +#include <sys/types.h>
           43  +
           44  +#include <sys/types.h>
           45  +#if defined(_WIN32) && !defined(__MINGW32__)
           46  +#include <io.h>
           47  +#include <direct.h>
           48  +#else
           49  +#include <dirent.h>
           50  +#endif
           51  +
           52  +#if defined(_WIN32) && !defined(__MINGW32__)
           53  +#include "config-msvc.h"
           54  +#else
           55  +#include "config.h"
           56  +#endif
           57  +
           58  +#ifdef SPATIALITE_AMALGAMATION
           59  +#include <spatialite/sqlite3.h>
           60  +#else
           61  +#include <sqlite3.h>
           62  +#endif
           63  +
           64  +#include <spatialite/gaiageo.h>
           65  +#include <spatialite.h>
           66  +
           67  +#define ARG_NONE		0
           68  +#define ARG_IN_DIR		1
           69  +#define ARG_OUT_DIR		2
           70  +
           71  +#define SUFFIX_DISCARD	0
           72  +#define SUFFIX_SHP		1
           73  +#define SUFFIX_SHX		2
           74  +#define SUFFIX_DBF		3
           75  +
           76  +#define SHAPEFILE_NO_DATA 1e-38
           77  +
           78  +#if defined(_WIN32) && !defined(__MINGW32__)
           79  +#define strcasecmp	_stricmp
           80  +#endif /* not WIN32 */
           81  +
           82  +struct shp_entry
           83  +{
           84  +/* an item of the SHP list */
           85  +    char *base_name;
           86  +    char *file_name;
           87  +    int has_shp;
           88  +    int has_shx;
           89  +    int has_dbf;
           90  +    struct shp_entry *next;
           91  +};
           92  +
           93  +struct shp_list
           94  +{
           95  +/* the SHP list */
           96  +    struct shp_entry *first;
           97  +    struct shp_entry *last;
           98  +};
           99  +
          100  +static struct shp_list *
          101  +alloc_shp_list (void)
          102  +{
          103  +/* allocating an empty SHP list */
          104  +    struct shp_list *list = malloc (sizeof (struct shp_list));
          105  +    list->first = NULL;
          106  +    list->last = NULL;
          107  +    return list;
          108  +}
          109  +
          110  +static void
          111  +free_shp_list (struct shp_list *list)
          112  +{
          113  +/* memory cleanup: freeing an SHP list */
          114  +    struct shp_entry *pi;
          115  +    struct shp_entry *pin;
          116  +    if (list == NULL)
          117  +	return;
          118  +
          119  +    pi = list->first;
          120  +    while (pi != NULL)
          121  +      {
          122  +	  pin = pi->next;
          123  +	  if (pi->base_name != NULL)
          124  +	      sqlite3_free (pi->base_name);
          125  +	  if (pi->file_name != NULL)
          126  +	      sqlite3_free (pi->file_name);
          127  +	  free (pi);
          128  +	  pi = pin;
          129  +      }
          130  +    free (list);
          131  +}
          132  +
          133  +static void
          134  +do_add_shapefile (struct shp_list *list, char *base_name, char *file_name,
          135  +		  int suffix)
          136  +{
          137  +/* adding a possible SHP to the list */
          138  +    struct shp_entry *pi;
          139  +    if (list == NULL)
          140  +	return;
          141  +
          142  +    pi = list->first;
          143  +    while (pi != NULL)
          144  +      {
          145  +	  /* searching if already defined */
          146  +	  if (strcmp (pi->base_name, base_name) == 0)
          147  +	    {
          148  +		switch (suffix)
          149  +		  {
          150  +		  case SUFFIX_SHP:
          151  +		      pi->has_shp = 1;
          152  +		      break;
          153  +		  case SUFFIX_SHX:
          154  +		      pi->has_shx = 1;
          155  +		      break;
          156  +		  case SUFFIX_DBF:
          157  +		      pi->has_dbf = 1;
          158  +		      break;
          159  +		  };
          160  +		sqlite3_free (base_name);
          161  +		sqlite3_free (file_name);
          162  +		return;
          163  +	    }
          164  +	  pi = pi->next;
          165  +      }
          166  +
          167  +/* adding a new SHP entry */
          168  +    pi = malloc (sizeof (struct shp_entry));
          169  +    pi->base_name = base_name;
          170  +    pi->file_name = file_name;
          171  +    pi->has_shp = 0;
          172  +    pi->has_shx = 0;
          173  +    pi->has_dbf = 0;
          174  +    pi->next = NULL;
          175  +
          176  +    switch (suffix)
          177  +      {
          178  +      case SUFFIX_SHP:
          179  +	  pi->has_shp = 1;
          180  +	  break;
          181  +      case SUFFIX_SHX:
          182  +	  pi->has_shx = 1;
          183  +	  break;
          184  +      case SUFFIX_DBF:
          185  +	  pi->has_dbf = 1;
          186  +	  break;
          187  +      };
          188  +
          189  +    if (list->first == NULL)
          190  +	list->first = pi;
          191  +    if (list->last != NULL)
          192  +	list->last->next = pi;
          193  +    list->last = pi;
          194  +}
          195  +
          196  +static int
          197  +test_valid_shp (struct shp_entry *p)
          198  +{
          199  +/* testing for a valid SHP candidate */
          200  +    if (p == NULL)
          201  +	return 0;
          202  +    if (p->has_shp && p->has_shx && p->has_dbf)
          203  +	return 1;
          204  +    return 0;
          205  +}
          206  +
          207  +static gaiaShapefilePtr
          208  +allocShapefile ()
          209  +{
          210  +/* allocates and initializes the Shapefile object */
          211  +    gaiaShapefilePtr shp = malloc (sizeof (gaiaShapefile));
          212  +    shp->endian_arch = 1;
          213  +    shp->Path = NULL;
          214  +    shp->Shape = -1;
          215  +    shp->EffectiveType = GAIA_UNKNOWN;
          216  +    shp->EffectiveDims = GAIA_XY;
          217  +    shp->flShp = NULL;
          218  +    shp->flShx = NULL;
          219  +    shp->flDbf = NULL;
          220  +    shp->Dbf = NULL;
          221  +    shp->ShpBfsz = 0;
          222  +    shp->BufShp = NULL;
          223  +    shp->BufDbf = NULL;
          224  +    shp->DbfHdsz = 0;
          225  +    shp->DbfReclen = 0;
          226  +    shp->DbfSize = 0;
          227  +    shp->DbfRecno = 0;
          228  +    shp->ShpSize = 0;
          229  +    shp->ShxSize = 0;
          230  +    shp->MinX = DBL_MAX;
          231  +    shp->MinY = DBL_MAX;
          232  +    shp->MaxX = -DBL_MAX;
          233  +    shp->MaxY = -DBL_MAX;
          234  +    shp->Valid = 0;
          235  +    shp->IconvObj = NULL;
          236  +    shp->LastError = NULL;
          237  +    return shp;
          238  +}
          239  +
          240  +static void
          241  +freeShapefile (gaiaShapefilePtr shp)
          242  +{
          243  +/* frees all memory allocations related to the Shapefile object */
          244  +    if (shp->Path)
          245  +	free (shp->Path);
          246  +    if (shp->flShp)
          247  +	fclose (shp->flShp);
          248  +    if (shp->flShx)
          249  +	fclose (shp->flShx);
          250  +    if (shp->flDbf)
          251  +	fclose (shp->flDbf);
          252  +    if (shp->Dbf)
          253  +	gaiaFreeDbfList (shp->Dbf);
          254  +    if (shp->BufShp)
          255  +	free (shp->BufShp);
          256  +    if (shp->BufDbf)
          257  +	free (shp->BufDbf);
          258  +    if (shp->LastError)
          259  +	free (shp->LastError);
          260  +    free (shp);
          261  +}
          262  +
          263  +static void
          264  +openShpRead (gaiaShapefilePtr shp, const char *path, double *MinX, double *MinY,
          265  +	     double *MaxX, double *MaxY, int *mismatching)
          266  +{
          267  +/* trying to open the shapefile and initial checkings */
          268  +    FILE *fl_shx = NULL;
          269  +    FILE *fl_shp = NULL;
          270  +    FILE *fl_dbf = NULL;
          271  +    char xpath[1024];
          272  +    int rd;
          273  +    unsigned char buf_shx[256];
          274  +    unsigned char *buf_shp = NULL;
          275  +    int buf_size = 1024;
          276  +    int shape;
          277  +    unsigned char bf[1024];
          278  +    int dbf_size;
          279  +    int dbf_reclen = 0;
          280  +    int off_dbf;
          281  +    int ind;
          282  +    char field_name[2048];
          283  +    char *sys_err;
          284  +    char errMsg[1024];
          285  +    double minx;
          286  +    double miny;
          287  +    double maxx;
          288  +    double maxy;
          289  +    int len;
          290  +    int endian_arch = gaiaEndianArch ();
          291  +    gaiaDbfListPtr dbf_list = NULL;
          292  +    if (shp->flShp != NULL || shp->flShx != NULL || shp->flDbf != NULL)
          293  +      {
          294  +	  sprintf (errMsg,
          295  +		   "attempting to reopen an already opened Shapefile\n");
          296  +	  goto unsupported_conversion;
          297  +      }
          298  +    sprintf (xpath, "%s.shx", path);
          299  +    fl_shx = fopen (xpath, "rb");
          300  +    if (!fl_shx)
          301  +      {
          302  +	  sys_err = strerror (errno);
          303  +	  sprintf (errMsg, "unable to open '%s' for reading: %s", xpath,
          304  +		   sys_err);
          305  +	  goto no_file;
          306  +      }
          307  +    sprintf (xpath, "%s.shp", path);
          308  +    fl_shp = fopen (xpath, "rb");
          309  +    if (!fl_shp)
          310  +      {
          311  +	  sys_err = strerror (errno);
          312  +	  sprintf (errMsg, "unable to open '%s' for reading: %s", xpath,
          313  +		   sys_err);
          314  +	  goto no_file;
          315  +      }
          316  +    sprintf (xpath, "%s.dbf", path);
          317  +    fl_dbf = fopen (xpath, "rb");
          318  +    if (!fl_dbf)
          319  +      {
          320  +	  sys_err = strerror (errno);
          321  +	  sprintf (errMsg, "unable to open '%s' for reading: %s", xpath,
          322  +		   sys_err);
          323  +	  goto no_file;
          324  +      }
          325  +/* reading SHX file header */
          326  +    rd = fread (buf_shx, sizeof (unsigned char), 100, fl_shx);
          327  +    if (rd != 100)
          328  +	goto error;
          329  +    if (gaiaImport32 (buf_shx + 0, GAIA_BIG_ENDIAN, endian_arch) != 9994)	/* checks the SHX magic number */
          330  +	goto error;
          331  +    *MinX = gaiaImport64 (buf_shx + 36, GAIA_LITTLE_ENDIAN, endian_arch);
          332  +    *MinY = gaiaImport64 (buf_shx + 44, GAIA_LITTLE_ENDIAN, endian_arch);
          333  +    *MaxX = gaiaImport64 (buf_shx + 52, GAIA_LITTLE_ENDIAN, endian_arch);
          334  +    *MaxY = gaiaImport64 (buf_shx + 60, GAIA_LITTLE_ENDIAN, endian_arch);
          335  +/* reading SHP file header */
          336  +    buf_shp = malloc (sizeof (unsigned char) * buf_size);
          337  +    rd = fread (buf_shp, sizeof (unsigned char), 100, fl_shp);
          338  +    if (rd != 100)
          339  +	goto error;
          340  +    if (gaiaImport32 (buf_shp + 0, GAIA_BIG_ENDIAN, endian_arch) != 9994)	/* checks the SHP magic number */
          341  +	goto error;
          342  +    minx = gaiaImport64 (buf_shp + 36, GAIA_LITTLE_ENDIAN, endian_arch);
          343  +    miny = gaiaImport64 (buf_shp + 44, GAIA_LITTLE_ENDIAN, endian_arch);
          344  +    maxx = gaiaImport64 (buf_shp + 52, GAIA_LITTLE_ENDIAN, endian_arch);
          345  +    maxy = gaiaImport64 (buf_shp + 60, GAIA_LITTLE_ENDIAN, endian_arch);
          346  +    *mismatching = 0;
          347  +    if (*MinX != minx || *MinY != miny || *MaxX != maxx || *MaxY != maxy)
          348  +      {
          349  +	  fprintf (stderr,
          350  +		   "\t\tHEADERS: found mismatching BBOX between .shx and .shp\n");
          351  +	  *mismatching = 1;
          352  +      }
          353  +    shape = gaiaImport32 (buf_shp + 32, GAIA_LITTLE_ENDIAN, endian_arch);
          354  +    if (shape == GAIA_SHP_POINT || shape == GAIA_SHP_POINTZ
          355  +	|| shape == GAIA_SHP_POINTM || shape == GAIA_SHP_POLYLINE
          356  +	|| shape == GAIA_SHP_POLYLINEZ || shape == GAIA_SHP_POLYLINEM
          357  +	|| shape == GAIA_SHP_POLYGON || shape == GAIA_SHP_POLYGONZ
          358  +	|| shape == GAIA_SHP_POLYGONM || shape == GAIA_SHP_MULTIPOINT
          359  +	|| shape == GAIA_SHP_MULTIPOINTZ || shape == GAIA_SHP_MULTIPOINTM)
          360  +	;
          361  +    else
          362  +	goto unsupported;
          363  +/* reading DBF file header */
          364  +    rd = fread (bf, sizeof (unsigned char), 32, fl_dbf);
          365  +    if (rd != 32)
          366  +	goto error;
          367  +    switch (*bf)
          368  +      {
          369  +	  /* checks the DBF magic number */
          370  +      case 0x03:
          371  +      case 0x83:
          372  +	  break;
          373  +      case 0x02:
          374  +      case 0xF8:
          375  +	  sprintf (errMsg, "'%s'\ninvalid magic number %02x [FoxBASE format]",
          376  +		   path, *bf);
          377  +	  goto dbf_bad_magic;
          378  +      case 0xF5:
          379  +	  sprintf (errMsg,
          380  +		   "'%s'\ninvalid magic number %02x [FoxPro 2.x (or earlier) format]",
          381  +		   path, *bf);
          382  +	  goto dbf_bad_magic;
          383  +      case 0x30:
          384  +      case 0x31:
          385  +      case 0x32:
          386  +	  sprintf (errMsg,
          387  +		   "'%s'\ninvalid magic number %02x [Visual FoxPro format]",
          388  +		   path, *bf);
          389  +	  goto dbf_bad_magic;
          390  +      case 0x43:
          391  +      case 0x63:
          392  +      case 0xBB:
          393  +      case 0xCB:
          394  +	  sprintf (errMsg, "'%s'\ninvalid magic number %02x [dBASE IV format]",
          395  +		   path, *bf);
          396  +	  goto dbf_bad_magic;
          397  +      default:
          398  +	  sprintf (errMsg, "'%s'\ninvalid magic number %02x [unknown format]",
          399  +		   path, *bf);
          400  +	  goto dbf_bad_magic;
          401  +      };
          402  +    dbf_size = gaiaImport16 (bf + 8, GAIA_LITTLE_ENDIAN, endian_arch);
          403  +    dbf_reclen = gaiaImport16 (bf + 10, GAIA_LITTLE_ENDIAN, endian_arch);
          404  +    dbf_size--;
          405  +    off_dbf = 0;
          406  +    dbf_list = gaiaAllocDbfList ();
          407  +    for (ind = 32; ind < dbf_size; ind += 32)
          408  +      {
          409  +	  /* fetches DBF fields definitions */
          410  +	  rd = fread (bf, sizeof (unsigned char), 32, fl_dbf);
          411  +	  if (rd != 32)
          412  +	      goto error;
          413  +	  if (*(bf + 11) == 'M')
          414  +	    {
          415  +		/* skipping any MEMO field */
          416  +		memcpy (field_name, bf, 11);
          417  +		field_name[11] = '\0';
          418  +		off_dbf += *(bf + 16);
          419  +		fprintf (stderr,
          420  +			 "WARNING: column \"%s\" is of the MEMO type and will be ignored\n",
          421  +			 field_name);
          422  +		continue;
          423  +	    }
          424  +	  memcpy (field_name, bf, 11);
          425  +	  field_name[11] = '\0';
          426  +	  gaiaAddDbfField (dbf_list, field_name, *(bf + 11), off_dbf,
          427  +			   *(bf + 16), *(bf + 17));
          428  +	  off_dbf += *(bf + 16);
          429  +      }
          430  +    if (!gaiaIsValidDbfList (dbf_list))
          431  +      {
          432  +	  /* invalid DBF */
          433  +	  goto illegal_dbf;
          434  +      }
          435  +    len = strlen (path);
          436  +    shp->Path = malloc (len + 1);
          437  +    strcpy (shp->Path, path);
          438  +    shp->ReadOnly = 1;
          439  +    shp->Shape = shape;
          440  +    switch (shape)
          441  +      {
          442  +	  /* setting up a prudential geometry type */
          443  +      case GAIA_SHP_POINT:
          444  +      case GAIA_SHP_POINTZ:
          445  +      case GAIA_SHP_POINTM:
          446  +	  shp->EffectiveType = GAIA_POINT;
          447  +	  break;
          448  +      case GAIA_SHP_POLYLINE:
          449  +      case GAIA_SHP_POLYLINEZ:
          450  +      case GAIA_SHP_POLYLINEM:
          451  +	  shp->EffectiveType = GAIA_MULTILINESTRING;
          452  +	  break;
          453  +      case GAIA_SHP_POLYGON:
          454  +      case GAIA_SHP_POLYGONZ:
          455  +      case GAIA_SHP_POLYGONM:
          456  +	  shp->EffectiveType = GAIA_MULTIPOLYGON;
          457  +	  break;
          458  +      case GAIA_SHP_MULTIPOINT:
          459  +      case GAIA_SHP_MULTIPOINTZ:
          460  +      case GAIA_SHP_MULTIPOINTM:
          461  +	  shp->EffectiveType = GAIA_MULTIPOINT;
          462  +	  break;
          463  +      }
          464  +    switch (shape)
          465  +      {
          466  +	  /* setting up a prudential dimension model */
          467  +      case GAIA_SHP_POINTZ:
          468  +      case GAIA_SHP_POLYLINEZ:
          469  +      case GAIA_SHP_POLYGONZ:
          470  +      case GAIA_SHP_MULTIPOINTZ:
          471  +	  shp->EffectiveDims = GAIA_XY_Z_M;
          472  +	  break;
          473  +      case GAIA_SHP_POINTM:
          474  +      case GAIA_SHP_POLYLINEM:
          475  +      case GAIA_SHP_POLYGONM:
          476  +      case GAIA_SHP_MULTIPOINTM:
          477  +	  shp->EffectiveDims = GAIA_XY_M;
          478  +	  break;
          479  +      default:
          480  +	  shp->EffectiveDims = GAIA_XY;
          481  +	  break;
          482  +      }
          483  +    shp->flShp = fl_shp;
          484  +    shp->flShx = fl_shx;
          485  +    shp->flDbf = fl_dbf;
          486  +    shp->Dbf = dbf_list;
          487  +/* saving the SHP buffer */
          488  +    shp->BufShp = buf_shp;
          489  +    shp->ShpBfsz = buf_size;
          490  +/* allocating DBF buffer */
          491  +    shp->BufDbf = malloc (sizeof (unsigned char) * dbf_reclen);
          492  +    shp->DbfHdsz = dbf_size + 1;
          493  +    shp->DbfReclen = dbf_reclen;
          494  +    shp->Valid = 1;
          495  +    shp->endian_arch = endian_arch;
          496  +    return;
          497  +  unsupported_conversion:
          498  +/* illegal charset */
          499  +    if (shp->LastError)
          500  +	free (shp->LastError);
          501  +    len = strlen (errMsg);
          502  +    shp->LastError = malloc (len + 1);
          503  +    strcpy (shp->LastError, errMsg);
          504  +    return;
          505  +  no_file:
          506  +/* one of shapefile's files can't be accessed */
          507  +    if (shp->LastError)
          508  +	free (shp->LastError);
          509  +    len = strlen (errMsg);
          510  +    shp->LastError = malloc (len + 1);
          511  +    strcpy (shp->LastError, errMsg);
          512  +    if (fl_shx)
          513  +	fclose (fl_shx);
          514  +    if (fl_shp)
          515  +	fclose (fl_shp);
          516  +    if (fl_dbf)
          517  +	fclose (fl_dbf);
          518  +    return;
          519  +  dbf_bad_magic:
          520  +/* the DBF has an invalid magin number */
          521  +    if (shp->LastError)
          522  +	free (shp->LastError);
          523  +    len = strlen (errMsg);
          524  +    shp->LastError = malloc (len + 1);
          525  +    strcpy (shp->LastError, errMsg);
          526  +    gaiaFreeDbfList (dbf_list);
          527  +    if (buf_shp)
          528  +	free (buf_shp);
          529  +    fclose (fl_shx);
          530  +    fclose (fl_shp);
          531  +    fclose (fl_dbf);
          532  +    return;
          533  +  error:
          534  +/* the shapefile is invalid or corrupted */
          535  +    if (shp->LastError)
          536  +	free (shp->LastError);
          537  +    sprintf (errMsg, "'%s' is corrupted / has invalid format", path);
          538  +    len = strlen (errMsg);
          539  +    shp->LastError = malloc (len + 1);
          540  +    strcpy (shp->LastError, errMsg);
          541  +    gaiaFreeDbfList (dbf_list);
          542  +    if (buf_shp)
          543  +	free (buf_shp);
          544  +    fclose (fl_shx);
          545  +    fclose (fl_shp);
          546  +    fclose (fl_dbf);
          547  +    return;
          548  +  unsupported:
          549  +/* the shapefile has an unrecognized shape type */
          550  +    if (shp->LastError)
          551  +	free (shp->LastError);
          552  +    sprintf (errMsg, "'%s' shape=%d is not supported", path, shape);
          553  +    len = strlen (errMsg);
          554  +    shp->LastError = malloc (len + 1);
          555  +    strcpy (shp->LastError, errMsg);
          556  +    gaiaFreeDbfList (dbf_list);
          557  +    if (buf_shp)
          558  +	free (buf_shp);
          559  +    fclose (fl_shx);
          560  +    fclose (fl_shp);
          561  +    if (fl_dbf)
          562  +	fclose (fl_dbf);
          563  +    return;
          564  +  illegal_dbf:
          565  +/* the DBF-file contains unsupported data types */
          566  +    if (shp->LastError)
          567  +	free (shp->LastError);
          568  +    sprintf (errMsg, "'%s.dbf' contains unsupported data types", path);
          569  +    len = strlen (errMsg);
          570  +    shp->LastError = malloc (len + 1);
          571  +    strcpy (shp->LastError, errMsg);
          572  +    gaiaFreeDbfList (dbf_list);
          573  +    if (buf_shp)
          574  +	free (buf_shp);
          575  +    fclose (fl_shx);
          576  +    fclose (fl_shp);
          577  +    if (fl_dbf)
          578  +	fclose (fl_dbf);
          579  +    return;
          580  +}
          581  +
          582  +static int
          583  +readShpEntity (gaiaShapefilePtr shp, int current_row, int *shplen, double *minx,
          584  +	       double *miny, double *maxx, double *maxy)
          585  +{
          586  +/* trying to read an entity from shapefile */
          587  +    unsigned char buf[512];
          588  +    int len;
          589  +    int rd;
          590  +    int skpos;
          591  +    int offset;
          592  +    int off_shp;
          593  +    int sz;
          594  +    char errMsg[1024];
          595  +    int shape;
          596  +    int endian_arch = gaiaEndianArch ();
          597  +
          598  +/* positioning and reading the SHX file */
          599  +    offset = 100 + (current_row * 8);	/* 100 bytes for the header + current row displacement; each SHX row = 8 bytes */
          600  +    skpos = fseek (shp->flShx, offset, SEEK_SET);
          601  +    if (skpos != 0)
          602  +	goto eof;
          603  +    rd = fread (buf, sizeof (unsigned char), 8, shp->flShx);
          604  +    if (rd != 8)
          605  +	goto eof;
          606  +    off_shp = gaiaImport32 (buf, GAIA_BIG_ENDIAN, shp->endian_arch);
          607  +/* positioning and reading the DBF file */
          608  +    offset = shp->DbfHdsz + (current_row * shp->DbfReclen);
          609  +    skpos = fseek (shp->flDbf, offset, SEEK_SET);
          610  +    if (skpos != 0)
          611  +	goto error;
          612  +    rd = fread (shp->BufDbf, sizeof (unsigned char), shp->DbfReclen,
          613  +		shp->flDbf);
          614  +    if (rd != shp->DbfReclen)
          615  +	goto error;
          616  +    if (*(shp->BufDbf) == '*')
          617  +	goto dbf_deleted;
          618  +/* positioning and reading corresponding SHP entity - geometry */
          619  +    offset = off_shp * 2;
          620  +    skpos = fseek (shp->flShp, offset, SEEK_SET);
          621  +    if (skpos != 0)
          622  +	goto error;
          623  +    rd = fread (buf, sizeof (unsigned char), 8, shp->flShp);
          624  +    if (rd != 8)
          625  +	goto error;
          626  +    sz = gaiaImport32 (buf + 4, GAIA_BIG_ENDIAN, shp->endian_arch);
          627  +    if ((sz * 2) > shp->ShpBfsz)
          628  +      {
          629  +	  /* current buffer is too small; we need to allocate a bigger buffer */
          630  +	  free (shp->BufShp);
          631  +	  shp->ShpBfsz = sz * 2;
          632  +	  shp->BufShp = malloc (sizeof (unsigned char) * shp->ShpBfsz);
          633  +      }
          634  +    /* reading the raw Geometry */
          635  +    rd = fread (shp->BufShp, sizeof (unsigned char), sz * 2, shp->flShp);
          636  +    if (rd != sz * 2)
          637  +	goto error;
          638  +    *shplen = rd;
          639  +
          640  +/* retrieving the feature's BBOX */
          641  +    shape = gaiaImport32 (shp->BufShp + 0, GAIA_LITTLE_ENDIAN, endian_arch);
          642  +    *minx = DBL_MAX;
          643  +    *miny = DBL_MAX;
          644  +    *maxx = DBL_MAX;
          645  +    *maxy = DBL_MAX;
          646  +    if (shape == GAIA_SHP_POINT || shape == GAIA_SHP_POINTZ
          647  +	|| shape == GAIA_SHP_POINTM)
          648  +      {
          649  +	  *minx =
          650  +	      gaiaImport64 (shp->BufShp + 4, GAIA_LITTLE_ENDIAN, endian_arch);
          651  +	  *maxx = *minx;
          652  +	  *miny =
          653  +	      gaiaImport64 (shp->BufShp + 12, GAIA_LITTLE_ENDIAN, endian_arch);
          654  +	  *maxy = *miny;
          655  +      }
          656  +    if (shape == GAIA_SHP_POLYLINE || shape == GAIA_SHP_POLYLINEZ
          657  +	|| shape == GAIA_SHP_POLYLINEM || shape == GAIA_SHP_POLYGON
          658  +	|| shape == GAIA_SHP_POLYGONZ || shape == GAIA_SHP_POLYGONM
          659  +	|| shape == GAIA_SHP_MULTIPOINT || shape == GAIA_SHP_MULTIPOINTZ
          660  +	|| shape == GAIA_SHP_MULTIPOINTM)
          661  +      {
          662  +	  *minx =
          663  +	      gaiaImport64 (shp->BufShp + 4, GAIA_LITTLE_ENDIAN, endian_arch);
          664  +	  *miny =
          665  +	      gaiaImport64 (shp->BufShp + 12, GAIA_LITTLE_ENDIAN, endian_arch);
          666  +	  *maxx =
          667  +	      gaiaImport64 (shp->BufShp + 20, GAIA_LITTLE_ENDIAN, endian_arch);
          668  +	  *maxy =
          669  +	      gaiaImport64 (shp->BufShp + 28, GAIA_LITTLE_ENDIAN, endian_arch);
          670  +      }
          671  +    return 1;
          672  +
          673  +  eof:
          674  +    if (shp->LastError)
          675  +	free (shp->LastError);
          676  +    shp->LastError = NULL;
          677  +    return 0;
          678  +  error:
          679  +    if (shp->LastError)
          680  +	free (shp->LastError);
          681  +    sprintf (errMsg, "'%s' is corrupted / has invalid format", shp->Path);
          682  +    len = strlen (errMsg);
          683  +    shp->LastError = malloc (len + 1);
          684  +    strcpy (shp->LastError, errMsg);
          685  +    return 0;
          686  +  dbf_deleted:
          687  +    if (shp->LastError)
          688  +	free (shp->LastError);
          689  +    shp->LastError = NULL;
          690  +    return -1;
          691  +}
          692  +
          693  +struct shp_ring_item
          694  +{
          695  +/* a RING item [to be reassembled into a (Multi)Polygon] */
          696  +    gaiaRingPtr Ring;
          697  +    int IsExterior;
          698  +    gaiaRingPtr Mother;
          699  +    struct shp_ring_item *Next;
          700  +};
          701  +
          702  +struct shp_ring_collection
          703  +{
          704  +/* a collection of RING items */
          705  +    struct shp_ring_item *First;
          706  +    struct shp_ring_item *Last;
          707  +};
          708  +
          709  +static void
          710  +shp_free_rings (struct shp_ring_collection *ringsColl)
          711  +{
          712  +/* memory cleanup: rings collection */
          713  +    struct shp_ring_item *p;
          714  +    struct shp_ring_item *pN;
          715  +    p = ringsColl->First;
          716  +    while (p)
          717  +      {
          718  +	  pN = p->Next;
          719  +	  if (p->Ring)
          720  +	      gaiaFreeRing (p->Ring);
          721  +	  free (p);
          722  +	  p = pN;
          723  +      }
          724  +}
          725  +
          726  +static void
          727  +shp_add_ring (struct shp_ring_collection *ringsColl, gaiaRingPtr ring)
          728  +{
          729  +/* inserting a ring into the rings collection */
          730  +    struct shp_ring_item *p = malloc (sizeof (struct shp_ring_item));
          731  +    p->Ring = ring;
          732  +    gaiaMbrRing (ring);
          733  +    gaiaClockwise (ring);
          734  +/* accordingly to SHP rules interior/exterior depends on direction */
          735  +    p->IsExterior = ring->Clockwise;
          736  +    p->Mother = NULL;
          737  +    p->Next = NULL;
          738  +/* updating the linked list */
          739  +    if (ringsColl->First == NULL)
          740  +	ringsColl->First = p;
          741  +    if (ringsColl->Last != NULL)
          742  +	ringsColl->Last->Next = p;
          743  +    ringsColl->Last = p;
          744  +}
          745  +
          746  +static int
          747  +shp_check_rings (gaiaRingPtr exterior, gaiaRingPtr candidate)
          748  +{
          749  +/* 
          750  +/ speditively checks if the candidate could be an interior Ring
          751  +/ contained into the exterior Ring
          752  +*/
          753  +    double z;
          754  +    double m;
          755  +    double x0;
          756  +    double y0;
          757  +    double x1;
          758  +    double y1;
          759  +    int mid;
          760  +    int ret0;
          761  +    int ret1;
          762  +    if (candidate->DimensionModel == GAIA_XY_Z)
          763  +      {
          764  +	  gaiaGetPointXYZ (candidate->Coords, 0, &x0, &y0, &z);
          765  +      }
          766  +    else if (candidate->DimensionModel == GAIA_XY_M)
          767  +      {
          768  +	  gaiaGetPointXYM (candidate->Coords, 0, &x0, &y0, &m);
          769  +      }
          770  +    else if (candidate->DimensionModel == GAIA_XY_Z_M)
          771  +      {
          772  +	  gaiaGetPointXYZM (candidate->Coords, 0, &x0, &y0, &z, &m);
          773  +      }
          774  +    else
          775  +      {
          776  +	  gaiaGetPoint (candidate->Coords, 0, &x0, &y0);
          777  +      }
          778  +    mid = candidate->Points / 2;
          779  +    if (candidate->DimensionModel == GAIA_XY_Z)
          780  +      {
          781  +	  gaiaGetPointXYZ (candidate->Coords, mid, &x1, &y1, &z);
          782  +      }
          783  +    else if (candidate->DimensionModel == GAIA_XY_M)
          784  +      {
          785  +	  gaiaGetPointXYM (candidate->Coords, mid, &x1, &y1, &m);
          786  +      }
          787  +    else if (candidate->DimensionModel == GAIA_XY_Z_M)
          788  +      {
          789  +	  gaiaGetPointXYZM (candidate->Coords, mid, &x1, &y1, &z, &m);
          790  +      }
          791  +    else
          792  +      {
          793  +	  gaiaGetPoint (candidate->Coords, mid, &x1, &y1);
          794  +      }
          795  +
          796  +/* testing if the first point falls on the exterior ring surface */
          797  +    ret0 = gaiaIsPointOnRingSurface (exterior, x0, y0);
          798  +/* testing if the second point falls on the exterior ring surface */
          799  +    ret1 = gaiaIsPointOnRingSurface (exterior, x1, y1);
          800  +    if (ret0 || ret1)
          801  +	return 1;
          802  +    return 0;
          803  +}
          804  +
          805  +static int
          806  +shp_mbr_contains (gaiaRingPtr r1, gaiaRingPtr r2)
          807  +{
          808  +/* checks if the first Ring contains the second one - MBR based */
          809  +    int ok_1 = 0;
          810  +    int ok_2 = 0;
          811  +    int ok_3 = 0;
          812  +    int ok_4 = 0;
          813  +    if (r2->MinX >= r1->MinX && r2->MinX <= r1->MaxX)
          814  +	ok_1 = 1;
          815  +    if (r2->MaxX >= r1->MinX && r2->MaxX <= r1->MaxX)
          816  +	ok_2 = 1;
          817  +    if (r2->MinY >= r1->MinY && r2->MinY <= r1->MaxY)
          818  +	ok_3 = 1;
          819  +    if (r2->MaxY >= r1->MinY && r2->MaxY <= r1->MaxY)
          820  +	ok_4 = 1;
          821  +    if (ok_1 && ok_2 && ok_3 && ok_4)
          822  +	return 1;
          823  +    return 0;
          824  +}
          825  +
          826  +static void
          827  +shp_arrange_rings (struct shp_ring_collection *ringsColl)
          828  +{
          829  +/* 
          830  +/ arranging Rings so to associate any interior ring
          831  +/ to the containing exterior ring
          832  +*/
          833  +    struct shp_ring_item *pInt;
          834  +    struct shp_ring_item *pExt;
          835  +    pExt = ringsColl->First;
          836  +    while (pExt != NULL)
          837  +      {
          838  +	  /* looping on Exterior Rings */
          839  +	  if (pExt->IsExterior)
          840  +	    {
          841  +		pInt = ringsColl->First;
          842  +		while (pInt != NULL)
          843  +		  {
          844  +		      /* looping on Interior Rings */
          845  +		      if (pInt->IsExterior == 0 && pInt->Mother == NULL
          846  +			  && shp_mbr_contains (pExt->Ring, pInt->Ring))
          847  +			{
          848  +			    /* ok, matches */
          849  +			    if (shp_check_rings (pExt->Ring, pInt->Ring))
          850  +				pInt->Mother = pExt->Ring;
          851  +			}
          852  +		      pInt = pInt->Next;
          853  +		  }
          854  +	    }
          855  +	  pExt = pExt->Next;
          856  +      }
          857  +    pExt = ringsColl->First;
          858  +    while (pExt != NULL)
          859  +      {
          860  +	  if (pExt->IsExterior == 0 && pExt->Mother == NULL)
          861  +	    {
          862  +		/* orphan ring: promoting to Exterior */
          863  +		pExt->IsExterior = 1;
          864  +	    }
          865  +	  pExt = pExt->Next;
          866  +      }
          867  +}
          868  +
          869  +static void
          870  +shp_build_area (struct shp_ring_collection *ringsColl, gaiaGeomCollPtr geom)
          871  +{
          872  +/* building the final (Multi)Polygon Geometry */
          873  +    gaiaPolygonPtr polyg;
          874  +    struct shp_ring_item *pExt;
          875  +    struct shp_ring_item *pInt;
          876  +    pExt = ringsColl->First;
          877  +    while (pExt != NULL)
          878  +      {
          879  +	  if (pExt->IsExterior)
          880  +	    {
          881  +		/* creating a new Polygon */
          882  +		polyg = gaiaInsertPolygonInGeomColl (geom, pExt->Ring);
          883  +		pInt = ringsColl->First;
          884  +		while (pInt != NULL)
          885  +		  {
          886  +		      if (pExt->Ring == pInt->Mother)
          887  +			{
          888  +			    /* adding an interior ring to current POLYGON */
          889  +			    gaiaAddRingToPolyg (polyg, pInt->Ring);
          890  +			    /* releasing Ring ownership */
          891  +			    pInt->Ring = NULL;
          892  +			}
          893  +		      pInt = pInt->Next;
          894  +		  }
          895  +		/* releasing Ring ownership */
          896  +		pExt->Ring = NULL;
          897  +	    }
          898  +	  pExt = pExt->Next;
          899  +      }
          900  +}
          901  +
          902  +static gaiaGeomCollPtr
          903  +do_parse_geometry (const unsigned char *bufshp, int buflen, int eff_dims,
          904  +		   int eff_type, int *nullshape)
          905  +{
          906  +/* attempting to parse a Geometry from the SHP */
          907  +    gaiaGeomCollPtr geom = NULL;
          908  +    int shape;
          909  +    double x;
          910  +    double y;
          911  +    double z;
          912  +    double m;
          913  +    int points;
          914  +    int n;
          915  +    int n1;
          916  +    int base;
          917  +    int baseZ;
          918  +    int baseM;
          919  +    int start;
          920  +    int end;
          921  +    int iv;
          922  +    int ind;
          923  +    int max_size;
          924  +    int min_size;
          925  +    int hasM;
          926  +    int sz;
          927  +    gaiaLinestringPtr line = NULL;
          928  +    gaiaRingPtr ring = NULL;
          929  +    int endian_arch = gaiaEndianArch ();
          930  +    struct shp_ring_collection ringsColl;
          931  +/* initializing the RING collection */
          932  +    ringsColl.First = NULL;
          933  +    ringsColl.Last = NULL;
          934  +
          935  +    shape = gaiaImport32 (bufshp + 0, GAIA_LITTLE_ENDIAN, endian_arch);
          936  +    if (shape == GAIA_SHP_NULL)
          937  +      {
          938  +	  *nullshape = 1;
          939  +	  return NULL;
          940  +      }
          941  +    *nullshape = 0;
          942  +
          943  +    if (shape == GAIA_SHP_POINT)
          944  +      {
          945  +	  /* shape point */
          946  +	  x = gaiaImport64 (bufshp + 4, GAIA_LITTLE_ENDIAN, endian_arch);
          947  +	  y = gaiaImport64 (bufshp + 12, GAIA_LITTLE_ENDIAN, endian_arch);
          948  +	  if (eff_dims == GAIA_XY_Z)
          949  +	    {
          950  +		geom = gaiaAllocGeomCollXYZ ();
          951  +		gaiaAddPointToGeomCollXYZ (geom, x, y, 0.0);
          952  +	    }
          953  +	  else if (eff_dims == GAIA_XY_M)
          954  +	    {
          955  +		geom = gaiaAllocGeomCollXYM ();
          956  +		gaiaAddPointToGeomCollXYM (geom, x, y, 0.0);
          957  +	    }
          958  +	  else if (eff_dims == GAIA_XY_Z_M)
          959  +	    {
          960  +		geom = gaiaAllocGeomCollXYZM ();
          961  +		gaiaAddPointToGeomCollXYZM (geom, x, y, 0.0, 0.0);
          962  +	    }
          963  +	  else
          964  +	    {
          965  +		geom = gaiaAllocGeomColl ();
          966  +		gaiaAddPointToGeomColl (geom, x, y);
          967  +	    }
          968  +	  geom->DeclaredType = GAIA_POINT;
          969  +      }
          970  +    if (shape == GAIA_SHP_POINTZ)
          971  +      {
          972  +	  /* shape point Z */
          973  +	  x = gaiaImport64 (bufshp + 4, GAIA_LITTLE_ENDIAN, endian_arch);
          974  +	  y = gaiaImport64 (bufshp + 12, GAIA_LITTLE_ENDIAN, endian_arch);
          975  +	  z = gaiaImport64 (bufshp + 20, GAIA_LITTLE_ENDIAN, endian_arch);
          976  +	  if (buflen == 28)
          977  +	      m = 0.0;
          978  +	  else
          979  +	      m = gaiaImport64 (bufshp + 28, GAIA_LITTLE_ENDIAN, endian_arch);
          980  +	  if (eff_dims == GAIA_XY_Z)
          981  +	    {
          982  +		geom = gaiaAllocGeomCollXYZ ();
          983  +		gaiaAddPointToGeomCollXYZ (geom, x, y, z);
          984  +	    }
          985  +	  else if (eff_dims == GAIA_XY_M)
          986  +	    {
          987  +		geom = gaiaAllocGeomCollXYM ();
          988  +		gaiaAddPointToGeomCollXYM (geom, x, y, m);
          989  +	    }
          990  +	  else if (eff_dims == GAIA_XY_Z_M)
          991  +	    {
          992  +		geom = gaiaAllocGeomCollXYZM ();
          993  +		gaiaAddPointToGeomCollXYZM (geom, x, y, z, m);
          994  +	    }
          995  +	  else
          996  +	    {
          997  +		geom = gaiaAllocGeomColl ();
          998  +		gaiaAddPointToGeomColl (geom, x, y);
          999  +	    }
         1000  +	  geom->DeclaredType = GAIA_POINT;
         1001  +      }
         1002  +    if (shape == GAIA_SHP_POINTM)
         1003  +      {
         1004  +	  /* shape point M */
         1005  +	  x = gaiaImport64 (bufshp + 4, GAIA_LITTLE_ENDIAN, endian_arch);
         1006  +	  y = gaiaImport64 (bufshp + 12, GAIA_LITTLE_ENDIAN, endian_arch);
         1007  +	  m = gaiaImport64 (bufshp + 20, GAIA_LITTLE_ENDIAN, endian_arch);
         1008  +	  if (eff_dims == GAIA_XY_Z)
         1009  +	    {
         1010  +		geom = gaiaAllocGeomCollXYZ ();
         1011  +		gaiaAddPointToGeomCollXYZ (geom, x, y, 0.0);
         1012  +	    }
         1013  +	  else if (eff_dims == GAIA_XY_M)
         1014  +	    {
         1015  +		geom = gaiaAllocGeomCollXYM ();
         1016  +		gaiaAddPointToGeomCollXYM (geom, x, y, m);
         1017  +	    }
         1018  +	  else if (eff_dims == GAIA_XY_Z_M)
         1019  +	    {
         1020  +		geom = gaiaAllocGeomCollXYZM ();
         1021  +		gaiaAddPointToGeomCollXYZM (geom, x, y, 0.0, m);
         1022  +	    }
         1023  +	  else
         1024  +	    {
         1025  +		geom = gaiaAllocGeomColl ();
         1026  +		gaiaAddPointToGeomColl (geom, x, y);
         1027  +	    }
         1028  +	  geom->DeclaredType = GAIA_POINT;
         1029  +      }
         1030  +    if (shape == GAIA_SHP_POLYLINE)
         1031  +      {
         1032  +	  /* shape polyline */
         1033  +	  n = gaiaImport32 (bufshp + 36, GAIA_LITTLE_ENDIAN, endian_arch);
         1034  +	  n1 = gaiaImport32 (bufshp + 40, GAIA_LITTLE_ENDIAN, endian_arch);
         1035  +	  base = 44 + (n * 4);
         1036  +	  start = 0;
         1037  +	  for (ind = 0; ind < n; ind++)
         1038  +	    {
         1039  +		if (ind < (n - 1))
         1040  +		    end =
         1041  +			gaiaImport32 (bufshp + 44 + ((ind + 1) * 4),
         1042  +				      GAIA_LITTLE_ENDIAN, endian_arch);
         1043  +		else
         1044  +		    end = n1;
         1045  +		points = end - start;
         1046  +		if (eff_dims == GAIA_XY_Z)
         1047  +		    line = gaiaAllocLinestringXYZ (points);
         1048  +		else if (eff_dims == GAIA_XY_M)
         1049  +		    line = gaiaAllocLinestringXYM (points);
         1050  +		else if (eff_dims == GAIA_XY_Z_M)
         1051  +		    line = gaiaAllocLinestringXYZM (points);
         1052  +		else
         1053  +		    line = gaiaAllocLinestring (points);
         1054  +		points = 0;
         1055  +		for (iv = start; iv < end; iv++)
         1056  +		  {
         1057  +		      x = gaiaImport64 (bufshp + base + (iv * 16),
         1058  +					GAIA_LITTLE_ENDIAN, endian_arch);
         1059  +		      y = gaiaImport64 (bufshp + base + (iv * 16) +
         1060  +					8, GAIA_LITTLE_ENDIAN, endian_arch);
         1061  +		      if (eff_dims == GAIA_XY_Z)
         1062  +			{
         1063  +			    gaiaSetPointXYZ (line->Coords, points, x, y, 0.0);
         1064  +			}
         1065  +		      else if (eff_dims == GAIA_XY_M)
         1066  +			{
         1067  +			    gaiaSetPointXYM (line->Coords, points, x, y, 0.0);
         1068  +			}
         1069  +		      else if (eff_dims == GAIA_XY_Z_M)
         1070  +			{
         1071  +			    gaiaSetPointXYZM (line->Coords, points, x, y,
         1072  +					      0.0, 0.0);
         1073  +			}
         1074  +		      else
         1075  +			{
         1076  +			    gaiaSetPoint (line->Coords, points, x, y);
         1077  +			}
         1078  +		      start++;
         1079  +		      points++;
         1080  +		  }
         1081  +		if (!geom)
         1082  +		  {
         1083  +		      if (eff_dims == GAIA_XY_Z)
         1084  +			  geom = gaiaAllocGeomCollXYZ ();
         1085  +		      else if (eff_dims == GAIA_XY_M)
         1086  +			  geom = gaiaAllocGeomCollXYM ();
         1087  +		      else if (eff_dims == GAIA_XY_Z_M)
         1088  +			  geom = gaiaAllocGeomCollXYZM ();
         1089  +		      else
         1090  +			  geom = gaiaAllocGeomColl ();
         1091  +		      if (eff_type == GAIA_LINESTRING)
         1092  +			  geom->DeclaredType = GAIA_LINESTRING;
         1093  +		      else
         1094  +			  geom->DeclaredType = GAIA_MULTILINESTRING;
         1095  +		  }
         1096  +		gaiaInsertLinestringInGeomColl (geom, line);
         1097  +	    }
         1098  +      }
         1099  +    if (shape == GAIA_SHP_POLYLINEZ)
         1100  +      {
         1101  +	  /* shape polyline Z */
         1102  +	  n = gaiaImport32 (bufshp + 36, GAIA_LITTLE_ENDIAN, endian_arch);
         1103  +	  n1 = gaiaImport32 (bufshp + 40, GAIA_LITTLE_ENDIAN, endian_arch);
         1104  +	  hasM = 0;
         1105  +	  max_size = 38 + (2 * n) + (n1 * 16);	/* size [in 16 bits words !!!] ZM */
         1106  +	  min_size = 30 + (2 * n) + (n1 * 12);	/* size [in 16 bits words !!!] Z-only */
         1107  +	  sz = buflen / 2;
         1108  +	  if (sz < min_size)
         1109  +	      goto error;
         1110  +	  if (sz == max_size)
         1111  +	      hasM = 1;
         1112  +	  base = 44 + (n * 4);
         1113  +	  baseZ = base + (n1 * 16) + 16;
         1114  +	  baseM = baseZ + (n1 * 8) + 16;
         1115  +	  start = 0;
         1116  +	  for (ind = 0; ind < n; ind++)
         1117  +	    {
         1118  +		if (ind < (n - 1))
         1119  +		    end =
         1120  +			gaiaImport32 (bufshp + 44 + ((ind + 1) * 4),
         1121  +				      GAIA_LITTLE_ENDIAN, endian_arch);
         1122  +		else
         1123  +		    end = n1;
         1124  +		points = end - start;
         1125  +		if (eff_dims == GAIA_XY_Z)
         1126  +		    line = gaiaAllocLinestringXYZ (points);
         1127  +		else if (eff_dims == GAIA_XY_M)
         1128  +		    line = gaiaAllocLinestringXYM (points);
         1129  +		else if (eff_dims == GAIA_XY_Z_M)
         1130  +		    line = gaiaAllocLinestringXYZM (points);
         1131  +		else
         1132  +		    line = gaiaAllocLinestring (points);
         1133  +		points = 0;
         1134  +		for (iv = start; iv < end; iv++)
         1135  +		  {
         1136  +		      x = gaiaImport64 (bufshp + base + (iv * 16),
         1137  +					GAIA_LITTLE_ENDIAN, endian_arch);
         1138  +		      y = gaiaImport64 (bufshp + base + (iv * 16) +
         1139  +					8, GAIA_LITTLE_ENDIAN, endian_arch);
         1140  +		      z = gaiaImport64 (bufshp + baseZ + (iv * 8),
         1141  +					GAIA_LITTLE_ENDIAN, endian_arch);
         1142  +		      if (hasM)
         1143  +			  m = gaiaImport64 (bufshp + baseM +
         1144  +					    (iv * 8), GAIA_LITTLE_ENDIAN,
         1145  +					    endian_arch);
         1146  +		      else
         1147  +			  m = 0.0;
         1148  +		      if (m < SHAPEFILE_NO_DATA)
         1149  +			  m = 0.0;
         1150  +		      if (eff_dims == GAIA_XY_Z)
         1151  +			{
         1152  +			    gaiaSetPointXYZ (line->Coords, points, x, y, z);
         1153  +			}
         1154  +		      else if (eff_dims == GAIA_XY_M)
         1155  +			{
         1156  +			    gaiaSetPointXYM (line->Coords, points, x, y, m);
         1157  +			}
         1158  +		      else if (eff_dims == GAIA_XY_Z_M)
         1159  +			{
         1160  +			    gaiaSetPointXYZM (line->Coords, points, x, y, z, m);
         1161  +			}
         1162  +		      else
         1163  +			{
         1164  +			    gaiaSetPoint (line->Coords, points, x, y);
         1165  +			}
         1166  +		      start++;
         1167  +		      points++;
         1168  +		  }
         1169  +		if (!geom)
         1170  +		  {
         1171  +		      if (eff_dims == GAIA_XY_Z)
         1172  +			  geom = gaiaAllocGeomCollXYZ ();
         1173  +		      else if (eff_dims == GAIA_XY_M)
         1174  +			  geom = gaiaAllocGeomCollXYM ();
         1175  +		      else if (eff_dims == GAIA_XY_Z_M)
         1176  +			  geom = gaiaAllocGeomCollXYZM ();
         1177  +		      else
         1178  +			  geom = gaiaAllocGeomColl ();
         1179  +		      if (eff_type == GAIA_LINESTRING)
         1180  +			  geom->DeclaredType = GAIA_LINESTRING;
         1181  +		      else
         1182  +			  geom->DeclaredType = GAIA_MULTILINESTRING;
         1183  +		  }
         1184  +		gaiaInsertLinestringInGeomColl (geom, line);
         1185  +	    }
         1186  +      }
         1187  +    if (shape == GAIA_SHP_POLYLINEM)
         1188  +      {
         1189  +	  /* shape polyline M */
         1190  +	  n = gaiaImport32 (bufshp + 36, GAIA_LITTLE_ENDIAN, endian_arch);
         1191  +	  n1 = gaiaImport32 (bufshp + 40, GAIA_LITTLE_ENDIAN, endian_arch);
         1192  +	  hasM = 0;
         1193  +	  max_size = 30 + (2 * n) + (n1 * 12);	/* size [in 16 bits words !!!] M */
         1194  +	  min_size = 22 + (2 * n) + (n1 * 8);	/* size [in 16 bits words !!!] no-M */
         1195  +	  sz = buflen / 2;
         1196  +	  if (sz < min_size)
         1197  +	      goto error;
         1198  +	  if (sz == max_size)
         1199  +	      hasM = 1;
         1200  +	  base = 44 + (n * 4);
         1201  +	  baseM = base + (n1 * 16) + 16;
         1202  +	  start = 0;
         1203  +	  for (ind = 0; ind < n; ind++)
         1204  +	    {
         1205  +		if (ind < (n - 1))
         1206  +		    end =
         1207  +			gaiaImport32 (bufshp + 44 + ((ind + 1) * 4),
         1208  +				      GAIA_LITTLE_ENDIAN, endian_arch);
         1209  +		else
         1210  +		    end = n1;
         1211  +		points = end - start;
         1212  +		if (eff_dims == GAIA_XY_Z)
         1213  +		    line = gaiaAllocLinestringXYZ (points);
         1214  +		else if (eff_dims == GAIA_XY_M)
         1215  +		    line = gaiaAllocLinestringXYM (points);
         1216  +		else if (eff_dims == GAIA_XY_Z_M)
         1217  +		    line = gaiaAllocLinestringXYZM (points);
         1218  +		else
         1219  +		    line = gaiaAllocLinestring (points);
         1220  +		points = 0;
         1221  +		for (iv = start; iv < end; iv++)
         1222  +		  {
         1223  +		      x = gaiaImport64 (bufshp + base + (iv * 16),
         1224  +					GAIA_LITTLE_ENDIAN, endian_arch);
         1225  +		      y = gaiaImport64 (bufshp + base + (iv * 16) +
         1226  +					8, GAIA_LITTLE_ENDIAN, endian_arch);
         1227  +		      if (hasM)
         1228  +			  m = gaiaImport64 (bufshp + baseM +
         1229  +					    (iv * 8), GAIA_LITTLE_ENDIAN,
         1230  +					    endian_arch);
         1231  +		      else
         1232  +			  m = 0.0;
         1233  +		      if (m < SHAPEFILE_NO_DATA)
         1234  +			  m = 0.0;
         1235  +		      if (eff_dims == GAIA_XY_Z)
         1236  +			{
         1237  +			    gaiaSetPointXYZ (line->Coords, points, x, y, 0.0);
         1238  +			}
         1239  +		      else if (eff_dims == GAIA_XY_M)
         1240  +			{
         1241  +			    gaiaSetPointXYM (line->Coords, points, x, y, m);
         1242  +			}
         1243  +		      else if (eff_dims == GAIA_XY_Z_M)
         1244  +			{
         1245  +			    gaiaSetPointXYZM (line->Coords, points, x, y,
         1246  +					      0.0, m);
         1247  +			}
         1248  +		      else
         1249  +			{
         1250  +			    gaiaSetPoint (line->Coords, points, x, y);
         1251  +			}
         1252  +		      start++;
         1253  +		      points++;
         1254  +		  }
         1255  +		if (!geom)
         1256  +		  {
         1257  +		      if (eff_dims == GAIA_XY_Z)
         1258  +			  geom = gaiaAllocGeomCollXYZ ();
         1259  +		      else if (eff_dims == GAIA_XY_M)
         1260  +			  geom = gaiaAllocGeomCollXYM ();
         1261  +		      else if (eff_dims == GAIA_XY_Z_M)
         1262  +			  geom = gaiaAllocGeomCollXYZM ();
         1263  +		      else
         1264  +			  geom = gaiaAllocGeomColl ();
         1265  +		      if (eff_type == GAIA_LINESTRING)
         1266  +			  geom->DeclaredType = GAIA_LINESTRING;
         1267  +		      else
         1268  +			  geom->DeclaredType = GAIA_MULTILINESTRING;
         1269  +		  }
         1270  +		gaiaInsertLinestringInGeomColl (geom, line);
         1271  +	    }
         1272  +      }
         1273  +    if (shape == GAIA_SHP_POLYGON)
         1274  +      {
         1275  +	  /* shape polygon */
         1276  +	  n = gaiaImport32 (bufshp + 36, GAIA_LITTLE_ENDIAN, endian_arch);
         1277  +	  n1 = gaiaImport32 (bufshp + 40, GAIA_LITTLE_ENDIAN, endian_arch);
         1278  +	  base = 44 + (n * 4);
         1279  +	  start = 0;
         1280  +	  for (ind = 0; ind < n; ind++)
         1281  +	    {
         1282  +		if (ind < (n - 1))
         1283  +		    end =
         1284  +			gaiaImport32 (bufshp + 44 + ((ind + 1) * 4),
         1285  +				      GAIA_LITTLE_ENDIAN, endian_arch);
         1286  +		else
         1287  +		    end = n1;
         1288  +		points = end - start;
         1289  +		if (eff_dims == GAIA_XY_Z)
         1290  +		    ring = gaiaAllocRingXYZ (points);
         1291  +		else if (eff_dims == GAIA_XY_M)
         1292  +		    ring = gaiaAllocRingXYM (points);
         1293  +		else if (eff_dims == GAIA_XY_Z_M)
         1294  +		    ring = gaiaAllocRingXYZM (points);
         1295  +		else
         1296  +		    ring = gaiaAllocRing (points);
         1297  +		points = 0;
         1298  +		for (iv = start; iv < end; iv++)
         1299  +		  {
         1300  +		      x = gaiaImport64 (bufshp + base + (iv * 16),
         1301  +					GAIA_LITTLE_ENDIAN, endian_arch);
         1302  +		      y = gaiaImport64 (bufshp + base + (iv * 16) +
         1303  +					8, GAIA_LITTLE_ENDIAN, endian_arch);
         1304  +		      if (eff_dims == GAIA_XY_Z)
         1305  +			{
         1306  +			    gaiaSetPointXYZ (ring->Coords, points, x, y, 0.0);
         1307  +			}
         1308  +		      else if (eff_dims == GAIA_XY_M)
         1309  +			{
         1310  +			    gaiaSetPointXYM (ring->Coords, points, x, y, 0.0);
         1311  +			}
         1312  +		      else if (eff_dims == GAIA_XY_Z_M)
         1313  +			{
         1314  +			    gaiaSetPointXYZM (ring->Coords, points, x, y,
         1315  +					      0.0, 0.0);
         1316  +			}
         1317  +		      else
         1318  +			{
         1319  +			    gaiaSetPoint (ring->Coords, points, x, y);
         1320  +			}
         1321  +		      start++;
         1322  +		      points++;
         1323  +		  }
         1324  +		shp_add_ring (&ringsColl, ring);
         1325  +	    }
         1326  +	  shp_arrange_rings (&ringsColl);
         1327  +	  /* allocating the final geometry */
         1328  +	  if (eff_dims == GAIA_XY_Z)
         1329  +	      geom = gaiaAllocGeomCollXYZ ();
         1330  +	  else if (eff_dims == GAIA_XY_M)
         1331  +	      geom = gaiaAllocGeomCollXYM ();
         1332  +	  else if (eff_dims == GAIA_XY_Z_M)
         1333  +	      geom = gaiaAllocGeomCollXYZM ();
         1334  +	  else
         1335  +	      geom = gaiaAllocGeomColl ();
         1336  +	  if (eff_type == GAIA_POLYGON)
         1337  +	      geom->DeclaredType = GAIA_POLYGON;
         1338  +	  else
         1339  +	      geom->DeclaredType = GAIA_MULTIPOLYGON;
         1340  +	  shp_build_area (&ringsColl, geom);
         1341  +      }
         1342  +    if (shape == GAIA_SHP_POLYGONZ)
         1343  +      {
         1344  +	  /* shape polygon Z */
         1345  +	  n = gaiaImport32 (bufshp + 36, GAIA_LITTLE_ENDIAN, endian_arch);
         1346  +	  n1 = gaiaImport32 (bufshp + 40, GAIA_LITTLE_ENDIAN, endian_arch);
         1347  +	  hasM = 0;
         1348  +	  max_size = 38 + (2 * n) + (n1 * 16);	/* size [in 16 bits words !!!] ZM */
         1349  +	  min_size = 30 + (2 * n) + (n1 * 12);	/* size [in 16 bits words !!!] Z-only */
         1350  +	  sz = buflen / 2;
         1351  +	  if (sz < min_size)
         1352  +	      goto error;
         1353  +	  if (sz == max_size)
         1354  +	      hasM = 1;
         1355  +	  base = 44 + (n * 4);
         1356  +	  baseZ = base + (n1 * 16) + 16;
         1357  +	  baseM = baseZ + (n1 * 8) + 16;
         1358  +	  start = 0;
         1359  +	  for (ind = 0; ind < n; ind++)
         1360  +	    {
         1361  +		if (ind < (n - 1))
         1362  +		    end =
         1363  +			gaiaImport32 (bufshp + 44 + ((ind + 1) * 4),
         1364  +				      GAIA_LITTLE_ENDIAN, endian_arch);
         1365  +		else
         1366  +		    end = n1;
         1367  +		points = end - start;
         1368  +		if (eff_dims == GAIA_XY_Z)
         1369  +		    ring = gaiaAllocRingXYZ (points);
         1370  +		else if (eff_dims == GAIA_XY_M)
         1371  +		    ring = gaiaAllocRingXYM (points);
         1372  +		else if (eff_dims == GAIA_XY_Z_M)
         1373  +		    ring = gaiaAllocRingXYZM (points);
         1374  +		else
         1375  +		    ring = gaiaAllocRing (points);
         1376  +		points = 0;
         1377  +		for (iv = start; iv < end; iv++)
         1378  +		  {
         1379  +		      x = gaiaImport64 (bufshp + base + (iv * 16),
         1380  +					GAIA_LITTLE_ENDIAN, endian_arch);
         1381  +		      y = gaiaImport64 (bufshp + base + (iv * 16) +
         1382  +					8, GAIA_LITTLE_ENDIAN, endian_arch);
         1383  +		      z = gaiaImport64 (bufshp + baseZ + (iv * 8),
         1384  +					GAIA_LITTLE_ENDIAN, endian_arch);
         1385  +		      if (hasM)
         1386  +			  m = gaiaImport64 (bufshp + baseM +
         1387  +					    (iv * 8), GAIA_LITTLE_ENDIAN,
         1388  +					    endian_arch);
         1389  +		      else
         1390  +			  m = 0.0;
         1391  +		      if (m < SHAPEFILE_NO_DATA)
         1392  +			  m = 0.0;
         1393  +		      if (eff_dims == GAIA_XY_Z)
         1394  +			{
         1395  +			    gaiaSetPointXYZ (ring->Coords, points, x, y, z);
         1396  +			}
         1397  +		      else if (eff_dims == GAIA_XY_M)
         1398  +			{
         1399  +			    gaiaSetPointXYM (ring->Coords, points, x, y, m);
         1400  +			}
         1401  +		      else if (eff_dims == GAIA_XY_Z_M)
         1402  +			{
         1403  +			    gaiaSetPointXYZM (ring->Coords, points, x, y, z, m);
         1404  +			}
         1405  +		      else
         1406  +			{
         1407  +			    gaiaSetPoint (ring->Coords, points, x, y);
         1408  +			}
         1409  +		      start++;
         1410  +		      points++;
         1411  +		  }
         1412  +		shp_add_ring (&ringsColl, ring);
         1413  +	    }
         1414  +	  shp_arrange_rings (&ringsColl);
         1415  +	  /* allocating the final geometry */
         1416  +	  if (eff_dims == GAIA_XY_Z)
         1417  +	      geom = gaiaAllocGeomCollXYZ ();
         1418  +	  else if (eff_dims == GAIA_XY_M)
         1419  +	      geom = gaiaAllocGeomCollXYM ();
         1420  +	  else if (eff_dims == GAIA_XY_Z_M)
         1421  +	      geom = gaiaAllocGeomCollXYZM ();
         1422  +	  else
         1423  +	      geom = gaiaAllocGeomColl ();
         1424  +	  if (eff_type == GAIA_POLYGON)
         1425  +	      geom->DeclaredType = GAIA_POLYGON;
         1426  +	  else
         1427  +	      geom->DeclaredType = GAIA_MULTIPOLYGON;
         1428  +	  shp_build_area (&ringsColl, geom);
         1429  +      }
         1430  +    if (shape == GAIA_SHP_POLYGONM)
         1431  +      {
         1432  +	  /* shape polygon M */
         1433  +	  n = gaiaImport32 (bufshp + 36, GAIA_LITTLE_ENDIAN, endian_arch);
         1434  +	  n1 = gaiaImport32 (bufshp + 40, GAIA_LITTLE_ENDIAN, endian_arch);
         1435  +	  hasM = 0;
         1436  +	  max_size = 30 + (2 * n) + (n1 * 12);	/* size [in 16 bits words !!!] M */
         1437  +	  min_size = 22 + (2 * n) + (n1 * 8);	/* size [in 16 bits words !!!] no-M */
         1438  +	  sz = buflen / 2;
         1439  +	  if (sz < min_size)
         1440  +	      goto error;
         1441  +	  if (sz == max_size)
         1442  +	      hasM = 1;
         1443  +	  base = 44 + (n * 4);
         1444  +	  baseM = base + (n1 * 16) + 16;
         1445  +	  start = 0;
         1446  +	  for (ind = 0; ind < n; ind++)
         1447  +	    {
         1448  +		if (ind < (n - 1))
         1449  +		    end =
         1450  +			gaiaImport32 (bufshp + 44 + ((ind + 1) * 4),
         1451  +				      GAIA_LITTLE_ENDIAN, endian_arch);
         1452  +		else
         1453  +		    end = n1;
         1454  +		points = end - start;
         1455  +		if (eff_dims == GAIA_XY_Z)
         1456  +		    ring = gaiaAllocRingXYZ (points);
         1457  +		else if (eff_dims == GAIA_XY_M)
         1458  +		    ring = gaiaAllocRingXYM (points);
         1459  +		else if (eff_dims == GAIA_XY_Z_M)
         1460  +		    ring = gaiaAllocRingXYZM (points);
         1461  +		else
         1462  +		    ring = gaiaAllocRing (points);
         1463  +		points = 0;
         1464  +		for (iv = start; iv < end; iv++)
         1465  +		  {
         1466  +		      x = gaiaImport64 (bufshp + base + (iv * 16),
         1467  +					GAIA_LITTLE_ENDIAN, endian_arch);
         1468  +		      y = gaiaImport64 (bufshp + base + (iv * 16) +
         1469  +					8, GAIA_LITTLE_ENDIAN, endian_arch);
         1470  +		      if (hasM)
         1471  +			  m = gaiaImport64 (bufshp + baseM +
         1472  +					    (iv * 8), GAIA_LITTLE_ENDIAN,
         1473  +					    endian_arch);
         1474  +		      m = 0.0;
         1475  +		      if (m < SHAPEFILE_NO_DATA)
         1476  +			  m = 0.0;
         1477  +		      if (eff_dims == GAIA_XY_Z)
         1478  +			{
         1479  +			    gaiaSetPointXYZ (ring->Coords, points, x, y, 0.0);
         1480  +			}
         1481  +		      else if (eff_dims == GAIA_XY_M)
         1482  +			{
         1483  +			    gaiaSetPointXYM (ring->Coords, points, x, y, m);
         1484  +			}
         1485  +		      else if (eff_dims == GAIA_XY_Z_M)
         1486  +			{
         1487  +			    gaiaSetPointXYZM (ring->Coords, points, x, y,
         1488  +					      0.0, m);
         1489  +			}
         1490  +		      else
         1491  +			{
         1492  +			    gaiaSetPoint (ring->Coords, points, x, y);
         1493  +			}
         1494  +		      start++;
         1495  +		      points++;
         1496  +		  }
         1497  +		shp_add_ring (&ringsColl, ring);
         1498  +	    }
         1499  +	  shp_arrange_rings (&ringsColl);
         1500  +	  /* allocating the final geometry */
         1501  +	  if (eff_dims == GAIA_XY_Z)
         1502  +	      geom = gaiaAllocGeomCollXYZ ();
         1503  +	  else if (eff_dims == GAIA_XY_M)
         1504  +	      geom = gaiaAllocGeomCollXYM ();
         1505  +	  else if (eff_dims == GAIA_XY_Z_M)
         1506  +	      geom = gaiaAllocGeomCollXYZM ();
         1507  +	  else
         1508  +	      geom = gaiaAllocGeomColl ();
         1509  +	  if (eff_type == GAIA_POLYGON)
         1510  +	      geom->DeclaredType = GAIA_POLYGON;
         1511  +	  else
         1512  +	      geom->DeclaredType = GAIA_MULTIPOLYGON;
         1513  +	  shp_build_area (&ringsColl, geom);
         1514  +      }
         1515  +    if (shape == GAIA_SHP_MULTIPOINT)
         1516  +      {
         1517  +	  /* shape multipoint */
         1518  +	  n = gaiaImport32 (bufshp + 36, GAIA_LITTLE_ENDIAN, endian_arch);
         1519  +	  if (eff_dims == GAIA_XY_Z)
         1520  +	      geom = gaiaAllocGeomCollXYZ ();
         1521  +	  else if (eff_dims == GAIA_XY_M)
         1522  +	      geom = gaiaAllocGeomCollXYM ();
         1523  +	  else if (eff_dims == GAIA_XY_Z_M)
         1524  +	      geom = gaiaAllocGeomCollXYZM ();
         1525  +	  else
         1526  +	      geom = gaiaAllocGeomColl ();
         1527  +	  geom->DeclaredType = GAIA_MULTIPOINT;
         1528  +	  for (iv = 0; iv < n; iv++)
         1529  +	    {
         1530  +		x = gaiaImport64 (bufshp + 40 + (iv * 16),
         1531  +				  GAIA_LITTLE_ENDIAN, endian_arch);
         1532  +		y = gaiaImport64 (bufshp + 40 + (iv * 16) + 8,
         1533  +				  GAIA_LITTLE_ENDIAN, endian_arch);
         1534  +		if (eff_dims == GAIA_XY_Z)
         1535  +		    gaiaAddPointToGeomCollXYZ (geom, x, y, 0.0);
         1536  +		else if (eff_dims == GAIA_XY_M)
         1537  +		    gaiaAddPointToGeomCollXYM (geom, x, y, 0.0);
         1538  +		else if (eff_dims == GAIA_XY_Z_M)
         1539  +		    gaiaAddPointToGeomCollXYZM (geom, x, y, 0.0, 0.0);
         1540  +		else
         1541  +		    gaiaAddPointToGeomColl (geom, x, y);
         1542  +	    }
         1543  +      }
         1544  +    if (shape == GAIA_SHP_MULTIPOINTZ)
         1545  +      {
         1546  +	  /* shape multipoint Z */
         1547  +	  n = gaiaImport32 (bufshp + 36, GAIA_LITTLE_ENDIAN, endian_arch);
         1548  +	  hasM = 0;
         1549  +	  max_size = 36 + (n * 16);	/* size [in 16 bits words !!!] ZM */
         1550  +	  min_size = 28 + (n * 12);	/* size [in 16 bits words !!!] Z-only */
         1551  +	  sz = buflen / 2;
         1552  +	  if (sz < min_size)
         1553  +	      goto error;
         1554  +	  if (sz == max_size)
         1555  +	      hasM = 1;
         1556  +	  baseZ = 40 + (n * 16) + 16;
         1557  +	  baseM = baseZ + (n * 8) + 16;
         1558  +	  if (eff_dims == GAIA_XY_Z)
         1559  +	      geom = gaiaAllocGeomCollXYZ ();
         1560  +	  else if (eff_dims == GAIA_XY_M)
         1561  +	      geom = gaiaAllocGeomCollXYM ();
         1562  +	  else if (eff_dims == GAIA_XY_Z_M)
         1563  +	      geom = gaiaAllocGeomCollXYZM ();
         1564  +	  else
         1565  +	      geom = gaiaAllocGeomColl ();
         1566  +	  geom->DeclaredType = GAIA_MULTIPOINT;
         1567  +	  for (iv = 0; iv < n; iv++)
         1568  +	    {
         1569  +		x = gaiaImport64 (bufshp + 40 + (iv * 16),
         1570  +				  GAIA_LITTLE_ENDIAN, endian_arch);
         1571  +		y = gaiaImport64 (bufshp + 40 + (iv * 16) + 8,
         1572  +				  GAIA_LITTLE_ENDIAN, endian_arch);
         1573  +		z = gaiaImport64 (bufshp + baseZ + (iv * 8),
         1574  +				  GAIA_LITTLE_ENDIAN, endian_arch);
         1575  +		if (hasM)
         1576  +		    m = gaiaImport64 (bufshp + baseM + (iv * 8),
         1577  +				      GAIA_LITTLE_ENDIAN, endian_arch);
         1578  +		else
         1579  +		    m = 0.0;
         1580  +		if (m < SHAPEFILE_NO_DATA)
         1581  +		    m = 0.0;
         1582  +		if (eff_dims == GAIA_XY_Z)
         1583  +		    gaiaAddPointToGeomCollXYZ (geom, x, y, z);
         1584  +		else if (eff_dims == GAIA_XY_M)
         1585  +		    gaiaAddPointToGeomCollXYM (geom, x, y, m);
         1586  +		else if (eff_dims == GAIA_XY_Z_M)
         1587  +		    gaiaAddPointToGeomCollXYZM (geom, x, y, z, m);
         1588  +		else
         1589  +		    gaiaAddPointToGeomColl (geom, x, y);
         1590  +	    }
         1591  +      }
         1592  +    if (shape == GAIA_SHP_MULTIPOINTM)
         1593  +      {
         1594  +	  /* shape multipoint M */
         1595  +	  n = gaiaImport32 (bufshp + 36, GAIA_LITTLE_ENDIAN, endian_arch);
         1596  +	  hasM = 0;
         1597  +	  max_size = 28 + (n * 12);	/* size [in 16 bits words !!!] M */
         1598  +	  min_size = 20 + (n * 8);	/* size [in 16 bits words !!!] no-M */
         1599  +	  sz = buflen / 2;
         1600  +	  if (sz < min_size)
         1601  +	      goto error;
         1602  +	  if (sz == max_size)
         1603  +	      hasM = 1;
         1604  +	  baseM = 40 + (n * 16) + 16;
         1605  +	  if (eff_dims == GAIA_XY_Z)
         1606  +	      geom = gaiaAllocGeomCollXYZ ();
         1607  +	  else if (eff_dims == GAIA_XY_M)
         1608  +	      geom = gaiaAllocGeomCollXYM ();
         1609  +	  else if (eff_dims == GAIA_XY_Z_M)
         1610  +	      geom = gaiaAllocGeomCollXYZM ();
         1611  +	  else
         1612  +	      geom = gaiaAllocGeomColl ();
         1613  +	  geom->DeclaredType = GAIA_MULTIPOINT;
         1614  +	  for (iv = 0; iv < n; iv++)
         1615  +	    {
         1616  +		x = gaiaImport64 (bufshp + 40 + (iv * 16),
         1617  +				  GAIA_LITTLE_ENDIAN, endian_arch);
         1618  +		y = gaiaImport64 (bufshp + 40 + (iv * 16) + 8,
         1619  +				  GAIA_LITTLE_ENDIAN, endian_arch);
         1620  +		if (hasM)
         1621  +		    m = gaiaImport64 (bufshp + baseM + (iv * 8),
         1622  +				      GAIA_LITTLE_ENDIAN, endian_arch);
         1623  +		else
         1624  +		    m = 0.0;
         1625  +		if (m < SHAPEFILE_NO_DATA)
         1626  +		    m = 0.0;
         1627  +		if (eff_dims == GAIA_XY_Z)
         1628  +		    gaiaAddPointToGeomCollXYZ (geom, x, y, 0.0);
         1629  +		else if (eff_dims == GAIA_XY_M)
         1630  +		    gaiaAddPointToGeomCollXYM (geom, x, y, m);
         1631  +		else if (eff_dims == GAIA_XY_Z_M)
         1632  +		    gaiaAddPointToGeomCollXYZM (geom, x, y, 0.0, m);
         1633  +		else
         1634  +		    gaiaAddPointToGeomColl (geom, x, y);
         1635  +	    }
         1636  +      }
         1637  +
         1638  +    if (geom != NULL)
         1639  +	gaiaMbrGeometry (geom);
         1640  +    shp_free_rings (&ringsColl);
         1641  +    return geom;
         1642  +
         1643  +  error:
         1644  +    fprintf (stderr, "\tcorrupted shapefile / invalid format");
         1645  +    shp_free_rings (&ringsColl);
         1646  +    return NULL;
         1647  +}
         1648  +
         1649  +static int
         1650  +do_read_shp (const void *cache, const char *shp_path, int validate, int esri,
         1651  +	     int *invalid)
         1652  +{
         1653  +/* reading some Shapefile and testing for validity */
         1654  +    int current_row;
         1655  +    gaiaShapefilePtr shp = NULL;
         1656  +    int ret;
         1657  +    double minx;
         1658  +    double miny;
         1659  +    double maxx;
         1660  +    double maxy;
         1661  +    double MinX = DBL_MAX;
         1662  +    double MinY = DBL_MAX;
         1663  +    double MaxX = 0.0 - DBL_MAX;
         1664  +    double MaxY = 0.0 - DBL_MAX;
         1665  +    double hMinX;
         1666  +    double hMinY;
         1667  +    double hMaxX;
         1668  +    double hMaxY;
         1669  +    int mismatching;
         1670  +
         1671  +    *invalid = 0;
         1672  +    shp = allocShapefile ();
         1673  +    openShpRead (shp, shp_path, &hMinX, &hMinY, &hMaxX, &hMaxY, &mismatching);
         1674  +    if (!(shp->Valid))
         1675  +      {
         1676  +	  char extra[512];
         1677  +	  *extra = '\0';
         1678  +	  if (shp->LastError)
         1679  +	      sprintf (extra, "\n\tcause: %s\n", shp->LastError);
         1680  +	  fprintf (stderr,
         1681  +		   "\terror: cannot open shapefile '%s'%s", shp_path, extra);
         1682  +	  freeShapefile (shp);
         1683  +	  return 0;
         1684  +      }
         1685  +    if (mismatching)
         1686  +	*invalid += 1;
         1687  +
         1688  +    current_row = 0;
         1689  +    while (1)
         1690  +      {
         1691  +	  /* reading rows from shapefile */
         1692  +	  int shplen;
         1693  +	  ret =
         1694  +	      readShpEntity (shp, current_row, &shplen, &minx, &miny, &maxx,
         1695  +			     &maxy);
         1696  +	  if (ret < 0)
         1697  +	    {
         1698  +		/* found a DBF deleted record */
         1699  +		fprintf (stderr, "\t\trow #%d: logical deletion found\n",
         1700  +			 current_row);
         1701  +		current_row++;
         1702  +		*invalid += 1;
         1703  +		continue;
         1704  +	    }
         1705  +	  if (!ret)
         1706  +	    {
         1707  +		if (!(shp->LastError))	/* normal SHP EOF */
         1708  +		    break;
         1709  +		fprintf (stderr, "\tERROR: %s\n", shp->LastError);
         1710  +		goto stop;
         1711  +	    }
         1712  +
         1713  +	  if (validate)
         1714  +	    {
         1715  +		int nullshape;
         1716  +		gaiaGeomCollPtr geom =
         1717  +		    do_parse_geometry (shp->BufShp, shplen, shp->EffectiveDims,
         1718  +				       shp->EffectiveType, &nullshape);
         1719  +		if (nullshape)
         1720  +		    ;
         1721  +		else
         1722  +		  {
         1723  +		      if (geom == NULL)
         1724  +			{
         1725  +			    fprintf (stderr,
         1726  +				     "\t\trow #%d: unable to get a Geometry\n",
         1727  +				     current_row);
         1728  +			    *invalid += 1;
         1729  +			}
         1730  +		      else
         1731  +			{
         1732  +			    if (geom->MinX != minx || geom->MinY != miny
         1733  +				|| geom->MaxX != maxx || geom->MaxY != maxy)
         1734  +			      {
         1735  +				  fprintf (stderr,
         1736  +					   "\t\trow #%d: mismatching BBOX\n",
         1737  +					   current_row);
         1738  +				  *invalid += 1;
         1739  +			      }
         1740  +			    if (esri)
         1741  +			      {
         1742  +				  /* checking invalid geometries in ESRI mode */
         1743  +				  gaiaGeomCollPtr detail;
         1744  +				  detail =
         1745  +				      gaiaIsValidDetailEx_r (cache, geom, 1);
         1746  +				  if (detail == NULL)
         1747  +				    {
         1748  +					/* extra checks */
         1749  +					int extra = 0;
         1750  +					if (gaiaIsToxic_r (cache, geom))
         1751  +					    extra = 1;
         1752  +					if (gaiaIsNotClosedGeomColl_r
         1753  +					    (cache, geom))
         1754  +					    extra = 1;
         1755  +					if (extra)
         1756  +					  {
         1757  +					      char *reason =
         1758  +						  gaiaIsValidReason_r (cache,
         1759  +								       geom);
         1760  +					      if (reason == NULL)
         1761  +						  fprintf (stderr,
         1762  +							   "\t\trow #%d: invalid Geometry (unknown reason)\n",
         1763  +							   current_row);
         1764  +					      else
         1765  +						{
         1766  +						    fprintf (stderr,
         1767  +							     "\t\trow #%d: %s\n",
         1768  +							     current_row,
         1769  +							     reason);
         1770  +						    free (reason);
         1771  +						}
         1772  +					      *invalid += 1;
         1773  +					  }
         1774  +				    }
         1775  +				  else
         1776  +				    {
         1777  +					char *reason =
         1778  +					    gaiaIsValidReason_r (cache, geom);
         1779  +					if (reason == NULL)
         1780  +					    fprintf (stderr,
         1781  +						     "\t\trow #%d: invalid Geometry (unknown reason)\n",
         1782  +						     current_row);
         1783  +					else
         1784  +					  {
         1785  +					      fprintf (stderr,
         1786  +						       "\t\trow #%d: %s\n",
         1787  +						       current_row, reason);
         1788  +					      free (reason);
         1789  +					  }
         1790  +					*invalid += 1;
         1791  +					gaiaFreeGeomColl (detail);
         1792  +				    }
         1793  +			      }
         1794  +			    else
         1795  +			      {
         1796  +				  /* checking invalid geometries in ISO/OGC mode */
         1797  +				  if (gaiaIsValid_r (cache, geom) != 1)
         1798  +				    {
         1799  +					char *reason =
         1800  +					    gaiaIsValidReason_r (cache, geom);
         1801  +					if (reason == NULL)
         1802  +					    fprintf (stderr,
         1803  +						     "\t\trow #%d: invalid Geometry (unknown reason)\n",
         1804  +						     current_row);
         1805  +					else
         1806  +					  {
         1807  +					      fprintf (stderr,
         1808  +						       "\t\trow #%d: %s\n",
         1809  +						       current_row, reason);
         1810  +					      free (reason);
         1811  +					  }
         1812  +					*invalid += 1;
         1813  +				    }
         1814  +			      }
         1815  +			    gaiaFreeGeomColl (geom);
         1816  +			}
         1817  +		  }
         1818  +	    }
         1819  +	  if (minx != DBL_MAX && miny != DBL_MAX && maxx != DBL_MAX
         1820  +	      && maxy != DBL_MAX)
         1821  +	    {
         1822  +		if (minx < MinX)
         1823  +		    MinX = minx;
         1824  +		if (miny < MinY)
         1825  +		    MinY = miny;
         1826  +		if (maxx > MaxX)
         1827  +		    MaxX = maxx;
         1828  +		if (maxy > MaxY)
         1829  +		    MaxY = maxy;
         1830  +	    }
         1831  +	  current_row++;
         1832  +      }
         1833  +    freeShapefile (shp);
         1834  +
         1835  +    if (MinX != hMinX || MinY != hMinY || MaxX != hMaxX || MaxY != hMaxY)
         1836  +      {
         1837  +	  fprintf (stderr, "\t\tHEADERS: found invalid BBOX\n");
         1838  +	  *invalid += 1;
         1839  +      }
         1840  +
         1841  +    return 1;
         1842  +
         1843  +  stop:
         1844  +    freeShapefile (shp);
         1845  +    fprintf (stderr, "\tMalformed shapefile: quitting\n");
         1846  +    return 0;
         1847  +}
         1848  +
         1849  +static void
         1850  +do_clen_files (const char *out_path, const char *name)
         1851  +{
         1852  +/* removing an invalid Shapefile (not properly repaired) */
         1853  +    char path[1024];
         1854  +
         1855  +    sprintf (path, "%s/%s.shx", out_path, name);
         1856  +#ifdef _WIN32
         1857  +    _unlink (path);
         1858  +#else
         1859  +    unlink (path);
         1860  +#endif
         1861  +
         1862  +    sprintf (path, "%s/%s.shp", out_path, name);
         1863  +#ifdef _WIN32
         1864  +    _unlink (path);
         1865  +#else
         1866  +    unlink (path);
         1867  +#endif
         1868  +
         1869  +    sprintf (path, "%s/%s.dbf", out_path, name);
         1870  +#ifdef _WIN32
         1871  +    _unlink (path);
         1872  +#else
         1873  +    unlink (path);
         1874  +#endif
         1875  +}
         1876  +
         1877  +static void
         1878  +openShpWrite (gaiaShapefilePtr shp, const char *path, int shape,
         1879  +	      gaiaDbfListPtr dbf_list)
         1880  +{
         1881  +/* trying to create the shapefile */
         1882  +    FILE *fl_shx = NULL;
         1883  +    FILE *fl_shp = NULL;
         1884  +    FILE *fl_dbf = NULL;
         1885  +    char xpath[1024];
         1886  +    unsigned char *buf_shp = NULL;
         1887  +    int buf_size = 1024;
         1888  +    unsigned char *dbf_buf = NULL;
         1889  +    gaiaDbfFieldPtr fld;
         1890  +    char *sys_err;
         1891  +    char errMsg[1024];
         1892  +    short dbf_reclen = 0;
         1893  +    int shp_size = 0;
         1894  +    int shx_size = 0;
         1895  +    unsigned short dbf_size = 0;
         1896  +    int len;
         1897  +    int endian_arch = gaiaEndianArch ();
         1898  +    char buf[2048];
         1899  +    if (shp->flShp != NULL || shp->flShx != NULL || shp->flDbf != NULL)
         1900  +      {
         1901  +	  sprintf (errMsg,
         1902  +		   "attempting to reopen an already opened Shapefile\n");
         1903  +	  goto unsupported_conversion;
         1904  +      }
         1905  +    buf_shp = malloc (buf_size);
         1906  +/* trying to open shapefile files */
         1907  +    sprintf (xpath, "%s.shx", path);
         1908  +    fl_shx = fopen (xpath, "wb");
         1909  +    if (!fl_shx)
         1910  +      {
         1911  +	  sys_err = strerror (errno);
         1912  +	  sprintf (errMsg, "unable to open '%s' for writing: %s", xpath,
         1913  +		   sys_err);
         1914  +	  goto no_file;
         1915  +      }
         1916  +    sprintf (xpath, "%s.shp", path);
         1917  +    fl_shp = fopen (xpath, "wb");
         1918  +    if (!fl_shp)
         1919  +      {
         1920  +	  sys_err = strerror (errno);
         1921  +	  sprintf (errMsg, "unable to open '%s' for writing: %s", xpath,
         1922  +		   sys_err);
         1923  +	  goto no_file;
         1924  +      }
         1925  +    sprintf (xpath, "%s.dbf", path);
         1926  +    fl_dbf = fopen (xpath, "wb");
         1927  +    if (!fl_dbf)
         1928  +      {
         1929  +	  sys_err = strerror (errno);
         1930  +	  sprintf (errMsg, "unable to open '%s' for writing: %s", xpath,
         1931  +		   sys_err);
         1932  +	  goto no_file;
         1933  +      }
         1934  +/* allocating DBF buffer */
         1935  +    dbf_reclen = 1;		/* an extra byte is needed because in DBF rows first byte is a marker for deletion */
         1936  +    fld = dbf_list->First;
         1937  +    while (fld)
         1938  +      {
         1939  +	  /* computing the DBF record length */
         1940  +	  dbf_reclen += fld->Length;
         1941  +	  fld = fld->Next;
         1942  +      }
         1943  +    dbf_buf = malloc (dbf_reclen);
         1944  +/* writing an empty SHP file header */
         1945  +    memset (buf_shp, 0, 100);
         1946  +    fwrite (buf_shp, 1, 100, fl_shp);
         1947  +    shp_size = 50;		/* note: shapefile [SHP and SHX] counts sizes in WORDS of 16 bits, not in bytes of 8 bits !!!! */
         1948  +/* writing an empty SHX file header */
         1949  +    memset (buf_shp, 0, 100);
         1950  +    fwrite (buf_shp, 1, 100, fl_shx);
         1951  +    shx_size = 50;
         1952  +/* writing the DBF file header */
         1953  +    memset (buf_shp, '\0', 32);
         1954  +    fwrite (buf_shp, 1, 32, fl_dbf);
         1955  +    dbf_size = 32;		/* note: DBF counts sizes in bytes */
         1956  +    fld = dbf_list->First;
         1957  +    while (fld)
         1958  +      {
         1959  +	  /* exporting DBF Fields specifications */
         1960  +	  memset (buf_shp, 0, 32);
         1961  +	  strcpy (buf, fld->Name);
         1962  +	  memcpy (buf_shp, buf, strlen (buf));
         1963  +	  *(buf_shp + 11) = fld->Type;
         1964  +	  *(buf_shp + 16) = fld->Length;
         1965  +	  *(buf_shp + 17) = fld->Decimals;
         1966  +	  fwrite (buf_shp, 1, 32, fl_dbf);
         1967  +	  dbf_size += 32;
         1968  +	  fld = fld->Next;
         1969  +      }
         1970  +    fwrite ("\r", 1, 1, fl_dbf);	/* this one is a special DBF delimiter that closes file header */
         1971  +    dbf_size++;
         1972  +/* setting up the SHP struct */
         1973  +    len = strlen (path);
         1974  +    shp->Path = malloc (len + 1);
         1975  +    strcpy (shp->Path, path);
         1976  +    shp->ReadOnly = 0;
         1977  +    shp->Shape = shape;
         1978  +    shp->flShp = fl_shp;
         1979  +    shp->flShx = fl_shx;
         1980  +    shp->flDbf = fl_dbf;
         1981  +    shp->Dbf = dbf_list;
         1982  +    shp->BufShp = buf_shp;
         1983  +    shp->ShpBfsz = buf_size;
         1984  +    shp->BufDbf = dbf_buf;
         1985  +    shp->DbfHdsz = dbf_size + 1;
         1986  +    shp->DbfReclen = dbf_reclen;
         1987  +    shp->DbfSize = dbf_size;
         1988  +    shp->DbfRecno = 0;
         1989  +    shp->ShpSize = shp_size;
         1990  +    shp->ShxSize = shx_size;
         1991  +    shp->MinX = DBL_MAX;
         1992  +    shp->MinY = DBL_MAX;
         1993  +    shp->MaxX = -DBL_MAX;
         1994  +    shp->MaxY = -DBL_MAX;
         1995  +    shp->Valid = 1;
         1996  +    shp->endian_arch = endian_arch;
         1997  +    return;
         1998  +  unsupported_conversion:
         1999  +/* illegal charset */
         2000  +    if (shp->LastError)
         2001  +	free (shp->LastError);
         2002  +    len = strlen (errMsg);
         2003  +    shp->LastError = malloc (len + 1);
         2004  +    strcpy (shp->LastError, errMsg);
         2005  +    return;
         2006  +  no_file:
         2007  +/* one of shapefile's files can't be created/opened */
         2008  +    if (shp->LastError)
         2009  +	free (shp->LastError);
         2010  +    len = strlen (errMsg);
         2011  +    shp->LastError = malloc (len + 1);
         2012  +    strcpy (shp->LastError, errMsg);
         2013  +    if (buf_shp)
         2014  +	free (buf_shp);
         2015  +    if (fl_shx)
         2016  +	fclose (fl_shx);
         2017  +    if (fl_shp)
         2018  +	fclose (fl_shp);
         2019  +    if (fl_dbf)
         2020  +	fclose (fl_dbf);
         2021  +    return;
         2022  +}
         2023  +
         2024  +static int
         2025  +writeShpEntity (gaiaShapefilePtr shp, const unsigned char *bufshp, int shplen,
         2026  +		const unsigned char *bufdbf, int dbflen)
         2027  +{
         2028  +/* trying to write an entity into shapefile */
         2029  +    unsigned char buf[64];
         2030  +    int endian_arch = shp->endian_arch;
         2031  +    int shape;
         2032  +    double minx;
         2033  +    double maxx;
         2034  +    double miny;
         2035  +    double maxy;
         2036  +
         2037  +/* inserting entity in SHX file */
         2038  +    gaiaExport32 (buf, shp->ShpSize, GAIA_BIG_ENDIAN, endian_arch);	/* exports current SHP file position */
         2039  +    gaiaExport32 (buf + 4, shplen / 2, GAIA_BIG_ENDIAN, endian_arch);	/* exports entitiy size [in 16 bits words !!!] */
         2040  +    fwrite (buf, 1, 8, shp->flShx);
         2041  +    (shp->ShxSize) += 4;	/* updating current SHX file position [in 16 bits words !!!] */
         2042  +
         2043  +/* inserting entity in SHP file */
         2044  +    gaiaExport32 (buf, shp->DbfRecno + 1, GAIA_BIG_ENDIAN, endian_arch);	/* exports entity ID */
         2045  +    gaiaExport32 (buf + 4, shplen / 2, GAIA_BIG_ENDIAN, endian_arch);	/* exports entity size [in 16 bits words !!!] */
         2046  +    fwrite (buf, 1, 8, shp->flShp);
         2047  +    (shp->ShpSize) += 4;
         2048  +    fwrite (bufshp, 1, shplen, shp->flShp);
         2049  +    (shp->ShpSize) += shplen / 2;	/* updating current SHP file position [in 16 bits words !!!] */
         2050  +
         2051  +/* inserting entity in DBF file */
         2052  +    fwrite (bufdbf, 1, dbflen, shp->flDbf);
         2053  +    (shp->DbfRecno)++;
         2054  +
         2055  +/* updating the full extent BBOX */
         2056  +    shape = gaiaImport32 (bufshp + 0, GAIA_LITTLE_ENDIAN, endian_arch);
         2057  +    if (shape == GAIA_SHP_POINT || shape == GAIA_SHP_POINTZ
         2058  +	|| shape == GAIA_SHP_POINTM)
         2059  +      {
         2060  +	  minx = gaiaImport64 (bufshp + 4, GAIA_LITTLE_ENDIAN, endian_arch);
         2061  +	  maxx = minx;
         2062  +	  miny = gaiaImport64 (bufshp + 12, GAIA_LITTLE_ENDIAN, endian_arch);
         2063  +	  maxy = miny;
         2064  +	  if (minx < shp->MinX)
         2065  +	      shp->MinX = minx;
         2066  +	  if (maxx > shp->MaxX)
         2067  +	      shp->MaxX = maxx;
         2068  +	  if (miny < shp->MinY)
         2069  +	      shp->MinY = miny;
         2070  +	  if (maxy > shp->MaxY)
         2071  +	      shp->MaxY = maxy;
         2072  +      }
         2073  +    if (shape == GAIA_SHP_POLYLINE || shape == GAIA_SHP_POLYLINEZ
         2074  +	|| shape == GAIA_SHP_POLYLINEM || shape == GAIA_SHP_POLYGON
         2075  +	|| shape == GAIA_SHP_POLYGONZ || shape == GAIA_SHP_POLYGONM
         2076  +	|| shape == GAIA_SHP_MULTIPOINT || shape == GAIA_SHP_MULTIPOINTZ
         2077  +	|| shape == GAIA_SHP_MULTIPOINTM)
         2078  +      {
         2079  +	  minx = gaiaImport64 (bufshp + 4, GAIA_LITTLE_ENDIAN, endian_arch);
         2080  +	  miny = gaiaImport64 (bufshp + 12, GAIA_LITTLE_ENDIAN, endian_arch);
         2081  +	  maxx = gaiaImport64 (bufshp + 20, GAIA_LITTLE_ENDIAN, endian_arch);
         2082  +	  maxy = gaiaImport64 (bufshp + 28, GAIA_LITTLE_ENDIAN, endian_arch);
         2083  +	  if (minx < shp->MinX)
         2084  +	      shp->MinX = minx;
         2085  +	  if (maxx > shp->MaxX)
         2086  +	      shp->MaxX = maxx;
         2087  +	  if (miny < shp->MinY)
         2088  +	      shp->MinY = miny;
         2089  +	  if (maxy > shp->MaxY)
         2090  +	      shp->MaxY = maxy;
         2091  +      }
         2092  +    return 1;
         2093  +}
         2094  +
         2095  +static int
         2096  +check_geometry (gaiaGeomCollPtr geom, int shape)
         2097  +{
         2098  +/* cheching the geometry type and dims */
         2099  +    int pts = 0;
         2100  +    int lns = 0;
         2101  +    int pgs = 0;
         2102  +    gaiaPointPtr pt;
         2103  +    gaiaLinestringPtr ln;
         2104  +    gaiaPolygonPtr pg;
         2105  +
         2106  +    pt = geom->FirstPoint;
         2107  +    while (pt != NULL)
         2108  +      {
         2109  +	  pts++;
         2110  +	  pt = pt->Next;
         2111  +      }
         2112  +    ln = geom->FirstLinestring;
         2113  +    while (ln != NULL)
         2114  +      {
         2115  +	  lns++;
         2116  +	  ln = ln->Next;
         2117  +      }
         2118  +    pg = geom->FirstPolygon;
         2119  +    while (pg != NULL)
         2120  +      {
         2121  +	  pgs++;
         2122  +	  pg = pg->Next;
         2123  +      }
         2124  +
         2125  +    if (pts == 1 && lns == 0 && pgs == 0)
         2126  +      {
         2127  +	  if (shape == GAIA_SHP_POINT && geom->DimensionModel == GAIA_XY)
         2128  +	      return 1;
         2129  +	  if (shape == GAIA_SHP_POINTZ
         2130  +	      && (geom->DimensionModel == GAIA_XY_Z
         2131  +		  || geom->DimensionModel == GAIA_XY_Z_M))
         2132  +	      return 1;
         2133  +	  if (shape == GAIA_SHP_POINTM && geom->DimensionModel == GAIA_XY_M)
         2134  +	      return 1;
         2135  +	  if (shape == GAIA_SHP_MULTIPOINT && geom->DimensionModel == GAIA_XY)
         2136  +	      return 1;
         2137  +	  if (shape == GAIA_SHP_MULTIPOINTZ
         2138  +	      && (geom->DimensionModel == GAIA_XY_Z
         2139  +		  || geom->DimensionModel == GAIA_XY_Z_M))
         2140  +	      return 1;
         2141  +	  if (shape == GAIA_SHP_MULTIPOINTM
         2142  +	      && geom->DimensionModel == GAIA_XY_M)
         2143  +	      return 1;
         2144  +      }
         2145  +    if (pts > 1 && lns == 0 && pgs == 0)
         2146  +      {
         2147  +	  if (shape == GAIA_SHP_MULTIPOINT && geom->DimensionModel == GAIA_XY)
         2148  +	      return 1;
         2149  +	  if (shape == GAIA_SHP_MULTIPOINTZ
         2150  +	      && (geom->DimensionModel == GAIA_XY_Z
         2151  +		  || geom->DimensionModel == GAIA_XY_Z_M))
         2152  +	      return 1;
         2153  +	  if (shape == GAIA_SHP_MULTIPOINTM
         2154  +	      && geom->DimensionModel == GAIA_XY_M)
         2155  +	      return 1;
         2156  +      }
         2157  +    if (pts == 0 && lns > 0 && pgs == 0)
         2158  +      {
         2159  +	  if (shape == GAIA_SHP_POLYLINE && geom->DimensionModel == GAIA_XY)
         2160  +	      return 1;
         2161  +	  if (shape == GAIA_SHP_POLYLINEZ
         2162  +	      && (geom->DimensionModel == GAIA_XY_Z
         2163  +		  || geom->DimensionModel == GAIA_XY_Z_M))
         2164  +	      return 1;
         2165  +	  if (shape == GAIA_SHP_POLYLINEM && geom->DimensionModel == GAIA_XY_M)
         2166  +	      return 1;
         2167  +      }
         2168  +    if (pts == 0 && lns == 0 && pgs > 0)
         2169  +      {
         2170  +	  if (shape == GAIA_SHP_POLYGON && geom->DimensionModel == GAIA_XY)
         2171  +	      return 1;
         2172  +	  if (shape == GAIA_SHP_POLYGONZ
         2173  +	      && (geom->DimensionModel == GAIA_XY_Z
         2174  +		  || geom->DimensionModel == GAIA_XY_Z_M))
         2175  +	      return 1;
         2176  +	  if (shape == GAIA_SHP_POLYGONM && geom->DimensionModel == GAIA_XY_M)
         2177  +	      return 1;
         2178  +      }
         2179  +
         2180  +    return 0;
         2181  +}
         2182  +
         2183  +static int
         2184  +check_geometry_verbose (gaiaGeomCollPtr geom, int shape, char **expected,
         2185  +			char **actual)
         2186  +{
         2187  +/* cheching the geometry type and dims - verbose */
         2188  +    int pts = 0;
         2189  +    int lns = 0;
         2190  +    int pgs = 0;
         2191  +    gaiaPointPtr pt;
         2192  +    gaiaLinestringPtr ln;
         2193  +    gaiaPolygonPtr pg;
         2194  +    const char *str;
         2195  +    int len;
         2196  +
         2197  +    *expected = NULL;
         2198  +    *actual = NULL;
         2199  +    pt = geom->FirstPoint;
         2200  +    while (pt != NULL)
         2201  +      {
         2202  +	  pts++;
         2203  +	  pt = pt->Next;
         2204  +      }
         2205  +    ln = geom->FirstLinestring;
         2206  +    while (ln != NULL)
         2207  +      {
         2208  +	  lns++;
         2209  +	  ln = ln->Next;
         2210  +      }
         2211  +    pg = geom->FirstPolygon;
         2212  +    while (pg != NULL)
         2213  +      {
         2214  +	  pgs++;
         2215  +	  pg = pg->Next;
         2216  +      }
         2217  +
         2218  +    if (pts == 1 && lns == 0 && pgs == 0)
         2219  +      {
         2220  +	  if (shape == GAIA_SHP_POINT && geom->DimensionModel == GAIA_XY)
         2221  +	      return 1;
         2222  +	  if (shape == GAIA_SHP_POINTZ
         2223  +	      && (geom->DimensionModel == GAIA_XY_Z
         2224  +		  || geom->DimensionModel == GAIA_XY_Z_M))
         2225  +	      return 1;
         2226  +	  if (shape == GAIA_SHP_POINTM && geom->DimensionModel == GAIA_XY_M)
         2227  +	      return 1;
         2228  +	  if (shape == GAIA_SHP_MULTIPOINT && geom->DimensionModel == GAIA_XY)
         2229  +	      return 1;
         2230  +	  if (shape == GAIA_SHP_MULTIPOINTZ
         2231  +	      && (geom->DimensionModel == GAIA_XY_Z
         2232  +		  || geom->DimensionModel == GAIA_XY_Z_M))
         2233  +	      return 1;
         2234  +	  if (shape == GAIA_SHP_MULTIPOINTM
         2235  +	      && geom->DimensionModel == GAIA_XY_M)
         2236  +	      return 1;
         2237  +      }
         2238  +    if (pts > 1 && lns == 0 && pgs == 0)
         2239  +      {
         2240  +	  if (shape == GAIA_SHP_MULTIPOINT && geom->DimensionModel == GAIA_XY)
         2241  +	      return 1;
         2242  +	  if (shape == GAIA_SHP_MULTIPOINTZ
         2243  +	      && (geom->DimensionModel == GAIA_XY_Z
         2244  +		  || geom->DimensionModel == GAIA_XY_Z_M))
         2245  +	      return 1;
         2246  +	  if (shape == GAIA_SHP_MULTIPOINTM
         2247  +	      && geom->DimensionModel == GAIA_XY_M)
         2248  +	      return 1;
         2249  +      }
         2250  +    if (pts == 0 && lns > 0 && pgs == 0)
         2251  +      {
         2252  +	  if (shape == GAIA_SHP_POLYLINE && geom->DimensionModel == GAIA_XY)
         2253  +	      return 1;
         2254  +	  if (shape == GAIA_SHP_POLYLINEZ
         2255  +	      && (geom->DimensionModel == GAIA_XY_Z
         2256  +		  || geom->DimensionModel == GAIA_XY_Z_M))
         2257  +	      return 1;
         2258  +	  if (shape == GAIA_SHP_POLYLINEM && geom->DimensionModel == GAIA_XY_M)
         2259  +	      return 1;
         2260  +      }
         2261  +    if (pts == 0 && lns == 0 && pgs > 0)
         2262  +      {
         2263  +	  if (shape == GAIA_SHP_POLYGON && geom->DimensionModel == GAIA_XY)
         2264  +	      return 1;
         2265  +	  if (shape == GAIA_SHP_POLYGONZ
         2266  +	      && (geom->DimensionModel == GAIA_XY_Z
         2267  +		  || geom->DimensionModel == GAIA_XY_Z_M))
         2268  +	      return 1;
         2269  +	  if (shape == GAIA_SHP_POLYGONM && geom->DimensionModel == GAIA_XY_M)
         2270  +	      return 1;
         2271  +      }
         2272  +
         2273  +    switch (shape)
         2274  +      {
         2275  +      case GAIA_SHP_POINT:
         2276  +	  str = "POINT";
         2277  +	  break;
         2278  +      case GAIA_SHP_POINTZ:
         2279  +	  str = "POINT-M";
         2280  +	  break;
         2281  +      case GAIA_SHP_POINTM:
         2282  +	  str = "POINT-Z";
         2283  +	  break;
         2284  +      case GAIA_SHP_POLYLINE:
         2285  +	  str = "POLYLINE";
         2286  +	  break;
         2287  +      case GAIA_SHP_POLYLINEZ:
         2288  +	  str = "POLYLINE-Z";
         2289  +	  break;
         2290  +      case GAIA_SHP_POLYLINEM:
         2291  +	  str = "POLYLINE-M";
         2292  +	  break;
         2293  +      case GAIA_SHP_POLYGON:
         2294  +	  str = "POLYGON";
         2295  +	  break;
         2296  +      case GAIA_SHP_POLYGONZ:
         2297  +	  str = "POLYGON-Z";
         2298  +	  break;
         2299  +      case GAIA_SHP_POLYGONM:
         2300  +	  str = "POLYGON-M";
         2301  +	  break;
         2302  +      case GAIA_SHP_MULTIPOINT:
         2303  +	  str = "MULTIPOINT";
         2304  +	  break;
         2305  +      case GAIA_SHP_MULTIPOINTZ:
         2306  +	  str = "MULTIPOINT-Z";
         2307  +	  break;
         2308  +      case GAIA_SHP_MULTIPOINTM:
         2309  +	  str = "MULTIPOINT-M";
         2310  +	  break;
         2311  +      default:
         2312  +	  str = "UNKNOWN";
         2313  +	  break;
         2314  +      };
         2315  +    len = strlen (str);
         2316  +    *expected = malloc (len + 1);
         2317  +    strcpy (*expected, str);
         2318  +
         2319  +    str = "UNKNOWN";
         2320  +    if (pts == 1 && lns == 0 && pgs == 0)
         2321  +      {
         2322  +	  if (geom->DimensionModel == GAIA_XY)
         2323  +	      str = "POINT";
         2324  +	  if (geom->DimensionModel == GAIA_XY_Z
         2325  +	      || geom->DimensionModel == GAIA_XY_Z_M)
         2326  +	      str = "POINT-Z";
         2327  +	  if (geom->DimensionModel == GAIA_XY_M)
         2328  +	      str = "POINT-M";
         2329  +      }
         2330  +    if (pts > 1 && lns == 0 && pgs == 0)
         2331  +      {
         2332  +	  if (geom->DimensionModel == GAIA_XY)
         2333  +	      str = "MULTIPOINT";
         2334  +	  if (geom->DimensionModel == GAIA_XY_Z
         2335  +	      || geom->DimensionModel == GAIA_XY_Z_M)
         2336  +	      str = "MULTIPOINT-Z";
         2337  +	  if (geom->DimensionModel == GAIA_XY_M)
         2338  +	      str = "MULTIPOINT-M";
         2339  +      }
         2340  +    if (pts == 0 && lns > 0 && pgs == 0)
         2341  +      {
         2342  +	  if (geom->DimensionModel == GAIA_XY)
         2343  +	      str = "POLYLINE";
         2344  +	  if (geom->DimensionModel == GAIA_XY_Z
         2345  +	      || geom->DimensionModel == GAIA_XY_Z_M)
         2346  +	      str = "POLYLINE-Z";
         2347  +	  if (geom->DimensionModel == GAIA_XY_M)
         2348  +	      str = "POLYLINE-M";
         2349  +      }
         2350  +    if (pts == 0 && lns == 0 && pgs > 0)
         2351  +      {
         2352  +	  if (geom->DimensionModel == GAIA_XY)
         2353  +	      str = "POLYGON";
         2354  +	  if (geom->DimensionModel == GAIA_XY_Z
         2355  +	      || geom->DimensionModel == GAIA_XY_Z_M)
         2356  +	      str = "POLYGON-Z";
         2357  +	  return 1;
         2358  +	  if (geom->DimensionModel == GAIA_XY_M)
         2359  +	      str = "POLYGON-M";
         2360  +	  return 1;
         2361  +      }
         2362  +    len = strlen (str);
         2363  +    *actual = malloc (len + 1);
         2364  +    strcpy (*actual, str);
         2365  +
         2366  +    return 0;
         2367  +}
         2368  +
         2369  +static void
         2370  +gaiaSaneClockwise (gaiaPolygonPtr polyg)
         2371  +{
         2372  +/*
         2373  +/ when exporting POLYGONs to SHAPEFILE, we must guarantee that:
         2374  +/ - all EXTERIOR RING must be clockwise
         2375  +/ - all INTERIOR RING must be anti-clockwise
         2376  +/
         2377  +/ this function checks for the above conditions,
         2378  +/ and if needed inverts the rings
         2379  +*/
         2380  +    int ib;
         2381  +    int iv;
         2382  +    int iv2;
         2383  +    double x;
         2384  +    double y;
         2385  +    double z;
         2386  +    double m;
         2387  +    gaiaRingPtr new_ring;
         2388  +    gaiaRingPtr ring = polyg->Exterior;
         2389  +    gaiaClockwise (ring);
         2390  +    if (!(ring->Clockwise))
         2391  +      {
         2392  +	  /* exterior ring needs inversion */
         2393  +	  if (ring->DimensionModel == GAIA_XY_Z)
         2394  +	      new_ring = gaiaAllocRingXYZ (ring->Points);
         2395  +	  else if (ring->DimensionModel == GAIA_XY_M)
         2396  +	      new_ring = gaiaAllocRingXYM (ring->Points);
         2397  +	  else if (ring->DimensionModel == GAIA_XY_Z_M)
         2398  +	      new_ring = gaiaAllocRingXYZM (ring->Points);
         2399  +	  else
         2400  +	      new_ring = gaiaAllocRing (ring->Points);
         2401  +	  iv2 = 0;
         2402  +	  for (iv = ring->Points - 1; iv >= 0; iv--)
         2403  +	    {
         2404  +		if (ring->DimensionModel == GAIA_XY_Z)
         2405  +		  {
         2406  +		      gaiaGetPointXYZ (ring->Coords, iv, &x, &y, &z);
         2407  +		      gaiaSetPointXYZ (new_ring->Coords, iv2, x, y, z);
         2408  +		  }
         2409  +		else if (ring->DimensionModel == GAIA_XY_M)
         2410  +		  {
         2411  +		      gaiaGetPointXYM (ring->Coords, iv, &x, &y, &m);
         2412  +		      gaiaSetPointXYM (new_ring->Coords, iv2, x, y, m);
         2413  +		  }
         2414  +		else if (ring->DimensionModel == GAIA_XY_Z_M)
         2415  +		  {
         2416  +		      gaiaGetPointXYZM (ring->Coords, iv, &x, &y, &z, &m);
         2417  +		      gaiaSetPointXYZM (new_ring->Coords, iv2, x, y, z, m);
         2418  +		  }
         2419  +		else
         2420  +		  {
         2421  +		      gaiaGetPoint (ring->Coords, iv, &x, &y);
         2422  +		      gaiaSetPoint (new_ring->Coords, iv2, x, y);
         2423  +		  }
         2424  +		iv2++;
         2425  +	    }
         2426  +	  polyg->Exterior = new_ring;
         2427  +	  gaiaFreeRing (ring);
         2428  +      }
         2429  +    for (ib = 0; ib < polyg->NumInteriors; ib++)
         2430  +      {
         2431  +	  ring = polyg->Interiors + ib;
         2432  +	  gaiaClockwise (ring);
         2433  +	  if (ring->Clockwise)
         2434  +	    {
         2435  +		/* interior ring needs inversion */
         2436  +		if (ring->DimensionModel == GAIA_XY_Z)
         2437  +		    new_ring = gaiaAllocRingXYZ (ring->Points);
         2438  +		else if (ring->DimensionModel == GAIA_XY_M)
         2439  +		    new_ring = gaiaAllocRingXYM (ring->Points);
         2440  +		else if (ring->DimensionModel == GAIA_XY_Z_M)
         2441  +		    new_ring = gaiaAllocRingXYZM (ring->Points);
         2442  +		else
         2443  +		    new_ring = gaiaAllocRing (ring->Points);
         2444  +		iv2 = 0;
         2445  +		for (iv = ring->Points - 1; iv >= 0; iv--)
         2446  +		  {
         2447  +		      if (ring->DimensionModel == GAIA_XY_Z)
         2448  +			{
         2449  +			    gaiaGetPointXYZ (ring->Coords, iv, &x, &y, &z);
         2450  +			    gaiaSetPointXYZ (new_ring->Coords, iv2, x, y, z);
         2451  +			}
         2452  +		      else if (ring->DimensionModel == GAIA_XY_M)
         2453  +			{
         2454  +			    gaiaGetPointXYM (ring->Coords, iv, &x, &y, &m);
         2455  +			    gaiaSetPointXYM (new_ring->Coords, iv2, x, y, m);
         2456  +			}
         2457  +		      else if (ring->DimensionModel == GAIA_XY_Z_M)
         2458  +			{
         2459  +			    gaiaGetPointXYZM (ring->Coords, iv, &x, &y, &z, &m);
         2460  +			    gaiaSetPointXYZM (new_ring->Coords, iv2, x, y,
         2461  +					      z, m);
         2462  +			}
         2463  +		      else
         2464  +			{
         2465  +			    gaiaGetPoint (ring->Coords, iv, &x, &y);
         2466  +			    gaiaSetPoint (new_ring->Coords, iv2, x, y);
         2467  +			}
         2468  +		      iv2++;
         2469  +		  }
         2470  +		for (iv = 0; iv < ring->Points; iv++)
         2471  +		  {
         2472  +		      if (ring->DimensionModel == GAIA_XY_Z)
         2473  +			{
         2474  +			    gaiaGetPointXYZ (new_ring->Coords, iv, &x, &y, &z);
         2475  +			    gaiaSetPointXYZ (ring->Coords, iv, x, y, z);
         2476  +			}
         2477  +		      else if (ring->DimensionModel == GAIA_XY_M)
         2478  +			{
         2479  +			    gaiaGetPointXYM (new_ring->Coords, iv, &x, &y, &m);
         2480  +			    gaiaSetPointXYM (ring->Coords, iv, x, y, m);
         2481  +			}
         2482  +		      else if (ring->DimensionModel == GAIA_XY_Z_M)
         2483  +			{
         2484  +			    gaiaGetPointXYZM (new_ring->Coords, iv, &x, &y,
         2485  +					      &z, &m);
         2486  +			    gaiaSetPointXYZM (ring->Coords, iv, x, y, z, m);
         2487  +			}
         2488  +		      else
         2489  +			{
         2490  +			    gaiaGetPoint (new_ring->Coords, iv, &x, &y);
         2491  +			    gaiaSetPoint (ring->Coords, iv, x, y);
         2492  +			}
         2493  +		  }
         2494  +		gaiaFreeRing (new_ring);
         2495  +	    }
         2496  +      }
         2497  +}
         2498  +
         2499  +static int
         2500  +do_export_geometry (gaiaGeomCollPtr geom, unsigned char **bufshp, int *buflen,
         2501  +		    int xshape, int rowno, int eff_dims)
         2502  +{
         2503  +/* attempting to encode a Geometry */
         2504  +    unsigned char *buf;
         2505  +    int iv;
         2506  +    int tot_ln;
         2507  +    int tot_v;
         2508  +    int tot_pts;
         2509  +    int this_size;
         2510  +    int ix;
         2511  +    double x;
         2512  +    double y;
         2513  +    double z;
         2514  +    double m;
         2515  +    int hasM;
         2516  +    double minZ;
         2517  +    double maxZ;
         2518  +    double minM;
         2519  +    double maxM;
         2520  +    int endian_arch = gaiaEndianArch ();
         2521  +
         2522  +    if (geom == NULL)
         2523  +      {
         2524  +	  /* exporting a NULL Shape */
         2525  +	  *buflen = 4;
         2526  +	  buf = malloc (4);
         2527  +	  gaiaExport32 (buf + 0, GAIA_SHP_NULL, GAIA_LITTLE_ENDIAN, endian_arch);	/* exports geometry type = NULL */
         2528  +	  *bufshp = buf;
         2529  +	  return 1;
         2530  +      }
         2531  +
         2532  +    if (!check_geometry (geom, xshape))
         2533  +      {
         2534  +	  /* mismatching Geometry type */
         2535  +	  fprintf (stderr, "\tinput row #%d: mismatching Geometry type\n",
         2536  +		   rowno);
         2537  +	  return 0;
         2538  +      }
         2539  +    gaiaMbrGeometry (geom);
         2540  +
         2541  +    if (xshape == GAIA_SHP_POINT)
         2542  +      {
         2543  +	  /* this one is expected to be a POINT */
         2544  +	  gaiaPointPtr pt = geom->FirstPoint;
         2545  +	  *buflen = 20;
         2546  +	  buf = malloc (20);
         2547  +	  gaiaExport32 (buf + 0, GAIA_SHP_POINT, GAIA_LITTLE_ENDIAN, endian_arch);	/* exports geometry type = POINT */
         2548  +	  gaiaExport64 (buf + 4, pt->X, GAIA_LITTLE_ENDIAN, endian_arch);	/* exports X coordinate */
         2549  +	  gaiaExport64 (buf + 12, pt->Y, GAIA_LITTLE_ENDIAN, endian_arch);	/* exports Y coordinate */
         2550  +	  *bufshp = buf;
         2551  +	  return 1;
         2552  +      }
         2553  +    if (xshape == GAIA_SHP_POINTZ)
         2554  +      {
         2555  +	  /* this one is expected to be a POINT Z */
         2556  +	  gaiaPointPtr pt = geom->FirstPoint;
         2557  +	  *buflen = 36;
         2558  +	  buf = malloc (36);
         2559  +	  gaiaExport32 (buf + 0, GAIA_SHP_POINTZ, GAIA_LITTLE_ENDIAN, endian_arch);	/* exports geometry type = POINT Z */
         2560  +	  gaiaExport64 (buf + 4, pt->X, GAIA_LITTLE_ENDIAN, endian_arch);	/* exports X coordinate */
         2561  +	  gaiaExport64 (buf + 12, pt->Y, GAIA_LITTLE_ENDIAN, endian_arch);	/* exports Y coordinate */
         2562  +	  gaiaExport64 (buf + 20, pt->Z, GAIA_LITTLE_ENDIAN, endian_arch);	/* exports Z coordinate */
         2563  +	  gaiaExport64 (buf + 28, pt->M, GAIA_LITTLE_ENDIAN, endian_arch);	/* exports M coordinate */
         2564  +	  *bufshp = buf;
         2565  +	  return 1;
         2566  +      }
         2567  +    if (xshape == GAIA_SHP_POINTM)
         2568  +      {
         2569  +	  /* this one is expected to be a POINT M */
         2570  +	  gaiaPointPtr pt = geom->FirstPoint;
         2571  +	  *buflen = 28;
         2572  +	  buf = malloc (28);
         2573  +	  gaiaExport32 (buf + 0, GAIA_SHP_POINTM, GAIA_LITTLE_ENDIAN, endian_arch);	/* exports geometry type = POINT M */
         2574  +	  gaiaExport64 (buf + 4, pt->X, GAIA_LITTLE_ENDIAN, endian_arch);	/* exports X coordinate */
         2575  +	  gaiaExport64 (buf + 12, pt->Y, GAIA_LITTLE_ENDIAN, endian_arch);	/* exports Y coordinate */
         2576  +	  gaiaExport64 (buf + 20, pt->Y, GAIA_LITTLE_ENDIAN, endian_arch);	/* exports M coordinate */
         2577  +	  *bufshp = buf;
         2578  +	  return 1;
         2579  +      }
         2580  +    if (xshape == GAIA_SHP_POLYLINE)
         2581  +      {
         2582  +	  /* this one is expected to be a LINESTRING / MULTILINESTRING */
         2583  +	  gaiaLinestringPtr line;
         2584  +	  tot_ln = 0;
         2585  +	  tot_v = 0;
         2586  +	  line = geom->FirstLinestring;
         2587  +	  while (line)
         2588  +	    {
         2589  +		/* computes # lines and total # points */
         2590  +		tot_v += line->Points;
         2591  +		tot_ln++;
         2592  +		line = line->Next;
         2593  +	    }
         2594  +	  this_size = 22 + (2 * tot_ln) + (tot_v * 8);	/* size [in 16 bits words !!!] for this SHP entity */
         2595  +	  *buflen = this_size * 2;
         2596  +	  buf = malloc (this_size * 2);
         2597  +	  gaiaExport32 (buf + 0, GAIA_SHP_POLYLINE, GAIA_LITTLE_ENDIAN, endian_arch);	/* exports geometry type = POLYLINE */
         2598  +	  gaiaExport64 (buf + 4, geom->MinX, GAIA_LITTLE_ENDIAN, endian_arch);	/* exports the MBR for this geometry */
         2599  +	  gaiaExport64 (buf + 12, geom->MinY, GAIA_LITTLE_ENDIAN, endian_arch);
         2600  +	  gaiaExport64 (buf + 20, geom->MaxX, GAIA_LITTLE_ENDIAN, endian_arch);
         2601  +	  gaiaExport64 (buf + 28, geom->MaxY, GAIA_LITTLE_ENDIAN, endian_arch);
         2602  +	  gaiaExport32 (buf + 36, tot_ln, GAIA_LITTLE_ENDIAN, endian_arch);	/* exports # lines in this polyline */
         2603  +	  gaiaExport32 (buf + 40, tot_v, GAIA_LITTLE_ENDIAN, endian_arch);	/* exports total # points */
         2604  +	  tot_v = 0;		/* resets points counter */
         2605  +	  ix = 44;		/* sets current buffer offset */
         2606  +	  line = geom->FirstLinestring;
         2607  +	  while (line)
         2608  +	    {
         2609  +		/* exports start point index for each line */
         2610  +		gaiaExport32 (buf + ix, tot_v, GAIA_LITTLE_ENDIAN, endian_arch);
         2611  +		tot_v += line->Points;
         2612  +		ix += 4;
         2613  +		line = line->Next;
         2614  +	    }
         2615  +	  line = geom->FirstLinestring;
         2616  +	  while (line)
         2617  +	    {
         2618  +		/* exports points for each line */
         2619  +		for (iv = 0; iv < line->Points; iv++)
         2620  +		  {
         2621  +		      /* exports a POINT [x,y] */
         2622  +		      if (line->DimensionModel == GAIA_XY_Z)
         2623  +			{
         2624  +			    gaiaGetPointXYZ (line->Coords, iv, &x, &y, &z);
         2625  +			}
         2626  +		      else if (line->DimensionModel == GAIA_XY_M)
         2627  +			{
         2628  +			    gaiaGetPointXYM (line->Coords, iv, &x, &y, &m);
         2629  +			}
         2630  +		      else if (line->DimensionModel == GAIA_XY_Z_M)
         2631  +			{
         2632  +			    gaiaGetPointXYZM (line->Coords, iv, &x, &y, &z, &m);
         2633  +			}
         2634  +		      else
         2635  +			{
         2636  +			    gaiaGetPoint (line->Coords, iv, &x, &y);
         2637  +			}
         2638  +		      gaiaExport64 (buf + ix, x,
         2639  +				    GAIA_LITTLE_ENDIAN, endian_arch);
         2640  +		      ix += 8;
         2641  +		      gaiaExport64 (buf + ix, y,
         2642  +				    GAIA_LITTLE_ENDIAN, endian_arch);
         2643  +		      ix += 8;
         2644  +		  }
         2645  +		line = line->Next;
         2646  +	    }
         2647  +	  *bufshp = buf;
         2648  +	  return 1;
         2649  +      }
         2650  +    if (xshape == GAIA_SHP_POLYLINEZ)
         2651  +      {
         2652  +	  /* this one is expected to be a LINESTRING / MULTILINESTRING Z */
         2653  +	  gaiaLinestringPtr line;
         2654  +	  gaiaZRangeGeometry (geom, &minZ, &maxZ);
         2655  +	  gaiaMRangeGeometry (geom, &minM, &maxM);
         2656  +	  tot_ln = 0;
         2657  +	  tot_v = 0;
         2658  +	  line = geom->FirstLinestring;
         2659  +	  while (line)
         2660  +	    {
         2661  +		/* computes # lines and total # points */
         2662  +		tot_v += line->Points;
         2663  +		tot_ln++;
         2664  +		line = line->Next;
         2665  +	    }
         2666  +	  hasM = 0;
         2667  +	  if (eff_dims == GAIA_XY_M || eff_dims == GAIA_XY_Z_M)
         2668  +	      hasM = 1;
         2669  +	  if (hasM)
         2670  +	      this_size = 38 + (2 * tot_ln) + (tot_v * 16);	/* size [in 16 bits words !!!] ZM */
         2671  +	  else
         2672  +	      this_size = 30 + (2 * tot_ln) + (tot_v * 12);	/* size [in 16 bits words !!!] Z-only */
         2673  +	  *buflen = this_size * 2;
         2674  +	  buf = malloc (this_size * 2);
         2675  +	  gaiaExport32 (buf + 0, GAIA_SHP_POLYLINEZ, GAIA_LITTLE_ENDIAN, endian_arch);	/* exports geometry type = POLYLINE Z */
         2676  +	  gaiaExport64 (buf + 4, geom->MinX, GAIA_LITTLE_ENDIAN, endian_arch);	/* exports the MBR for this geometry */
         2677  +	  gaiaExport64 (buf + 12, geom->MinY, GAIA_LITTLE_ENDIAN, endian_arch);
         2678  +	  gaiaExport64 (buf + 20, geom->MaxX, GAIA_LITTLE_ENDIAN, endian_arch);
         2679  +	  gaiaExport64 (buf + 28, geom->MaxY, GAIA_LITTLE_ENDIAN, endian_arch);
         2680  +	  gaiaExport32 (buf + 36, tot_ln, GAIA_LITTLE_ENDIAN, endian_arch);	/* exports # lines in this polyline */
         2681  +	  gaiaExport32 (buf + 40, tot_v, GAIA_LITTLE_ENDIAN, endian_arch);	/* exports total # points */
         2682  +	  tot_v = 0;		/* resets points counter */
         2683  +	  ix = 44;		/* sets current buffer offset */
         2684  +	  line = geom->FirstLinestring;
         2685  +	  while (line)
         2686  +	    {
         2687  +		/* exports start point index for each line */
         2688  +		gaiaExport32 (buf + ix, tot_v, GAIA_LITTLE_ENDIAN, endian_arch);
         2689  +		tot_v += line->Points;
         2690  +		ix += 4;
         2691  +		line = line->Next;
         2692  +	    }
         2693  +	  line = geom->FirstLinestring;
         2694  +	  while (line)
         2695  +	    {
         2696  +		/* exports points for each line */
         2697  +		for (iv = 0; iv < line->Points; iv++)
         2698  +		  {
         2699  +		      /* exports a POINT [x,y] */
         2700  +		      if (line->DimensionModel == GAIA_XY_Z)
         2701  +			{
         2702  +			    gaiaGetPointXYZ (line->Coords, iv, &x, &y, &z);
         2703  +			}
         2704  +		      else if (line->DimensionModel == GAIA_XY_M)
         2705  +			{
         2706  +			    gaiaGetPointXYM (line->Coords, iv, &x, &y, &m);
         2707  +			}
         2708  +		      else if (line->DimensionModel == GAIA_XY_Z_M)
         2709  +			{
         2710  +			    gaiaGetPointXYZM (line->Coords, iv, &x, &y, &z, &m);
         2711  +			}
         2712  +		      else
         2713  +			{
         2714  +			    gaiaGetPoint (line->Coords, iv, &x, &y);
         2715  +			}
         2716  +		      gaiaExport64 (buf + ix, x,
         2717  +				    GAIA_LITTLE_ENDIAN, endian_arch);
         2718  +		      ix += 8;
         2719  +		      gaiaExport64 (buf + ix, y,
         2720  +				    GAIA_LITTLE_ENDIAN, endian_arch);
         2721  +		      ix += 8;
         2722  +		  }
         2723  +		line = line->Next;
         2724  +	    }
         2725  +	  /* exporting the Z-range [min/max] */
         2726  +	  gaiaExport64 (buf + ix, minZ, GAIA_LITTLE_ENDIAN, endian_arch);
         2727  +	  ix += 8;
         2728  +	  gaiaExport64 (buf + ix, maxZ, GAIA_LITTLE_ENDIAN, endian_arch);
         2729  +	  ix += 8;
         2730  +	  line = geom->FirstLinestring;
         2731  +	  while (line)
         2732  +	    {
         2733  +		/* exports Z-values for each line */
         2734  +		for (iv = 0; iv < line->Points; iv++)
         2735  +		  {
         2736  +		      /* exports Z-value */
         2737  +		      z = 0.0;
         2738  +		      if (line->DimensionModel == GAIA_XY_Z)
         2739  +			{
         2740  +			    gaiaGetPointXYZ (line->Coords, iv, &x, &y, &z);
         2741  +			}
         2742  +		      else if (line->DimensionModel == GAIA_XY_M)
         2743  +			{
         2744  +			    gaiaGetPointXYM (line->Coords, iv, &x, &y, &m);
         2745  +			}
         2746  +		      else if (line->DimensionModel == GAIA_XY_Z_M)
         2747  +			{
         2748  +			    gaiaGetPointXYZM (line->Coords, iv, &x, &y, &z, &m);
         2749  +			}
         2750  +		      else
         2751  +			{
         2752  +			    gaiaGetPoint (line->Coords, iv, &x, &y);
         2753  +			}
         2754  +		      gaiaExport64 (buf + ix, z,
         2755  +				    GAIA_LITTLE_ENDIAN, endian_arch);
         2756  +		      ix += 8;
         2757  +		  }
         2758  +		line = line->Next;
         2759  +	    }
         2760  +	  if (hasM)
         2761  +	    {
         2762  +		/* exporting the M-range [min/max] */
         2763  +		gaiaExport64 (buf + ix, minM, GAIA_LITTLE_ENDIAN, endian_arch);
         2764  +		ix += 8;
         2765  +		gaiaExport64 (buf + ix, maxM, GAIA_LITTLE_ENDIAN, endian_arch);
         2766  +		ix += 8;
         2767  +		line = geom->FirstLinestring;
         2768  +		while (line)
         2769  +		  {
         2770  +		      /* exports M-values for each line */
         2771  +		      for (iv = 0; iv < line->Points; iv++)
         2772  +			{
         2773  +			    /* exports M-value */
         2774  +			    m = 0.0;
         2775  +			    if (line->DimensionModel == GAIA_XY_Z)
         2776  +			      {
         2777  +				  gaiaGetPointXYZ (line->Coords, iv,
         2778  +						   &x, &y, &z);
         2779  +			      }
         2780  +			    else if (line->DimensionModel == GAIA_XY_M)
         2781  +			      {
         2782  +				  gaiaGetPointXYM (line->Coords, iv,
         2783  +						   &x, &y, &m);
         2784  +			      }
         2785  +			    else if (line->DimensionModel == GAIA_XY_Z_M)
         2786  +			      {
         2787  +				  gaiaGetPointXYZM (line->Coords, iv,
         2788  +						    &x, &y, &z, &m);
         2789  +			      }
         2790  +			    else
         2791  +			      {
         2792  +				  gaiaGetPoint (line->Coords, iv, &x, &y);
         2793  +			      }
         2794  +			    gaiaExport64 (buf + ix, m,
         2795  +					  GAIA_LITTLE_ENDIAN, endian_arch);
         2796  +			    ix += 8;
         2797  +			}
         2798  +		      line = line->Next;
         2799  +		  }
         2800  +	    }
         2801  +	  *bufshp = buf;
         2802  +	  return 1;
         2803  +      }
         2804  +    if (xshape == GAIA_SHP_POLYLINEM)
         2805  +      {
         2806  +	  /* this one is expected to be a LINESTRING / MULTILINESTRING M */
         2807  +	  gaiaLinestringPtr line;
         2808  +	  gaiaMRangeGeometry (geom, &minM, &maxM);
         2809  +	  tot_ln = 0;
         2810  +	  tot_v = 0;
         2811  +	  line = geom->FirstLinestring;
         2812  +	  while (line)
         2813  +	    {
         2814  +		/* computes # lines and total # points */
         2815  +		tot_v += line->Points;
         2816  +		tot_ln++;
         2817  +		line = line->Next;
         2818  +	    }
         2819  +	  this_size = 30 + (2 * tot_ln) + (tot_v * 12);	/* size [in 16 bits words !!!] for this SHP entity */
         2820  +	  *buflen = this_size * 2;
         2821  +	  buf = malloc (this_size * 2);
         2822  +	  gaiaExport32 (buf + 0, GAIA_SHP_POLYLINEM, GAIA_LITTLE_ENDIAN, endian_arch);	/* exports geometry type = POLYLINE M */
         2823  +	  gaiaExport64 (buf + 4, geom->MinX, GAIA_LITTLE_ENDIAN, endian_arch);	/* exports the MBR for this geometry */
         2824  +	  gaiaExport64 (buf + 12, geom->MinY, GAIA_LITTLE_ENDIAN, endian_arch);
         2825  +	  gaiaExport64 (buf + 20, geom->MaxX, GAIA_LITTLE_ENDIAN, endian_arch);
         2826  +	  gaiaExport64 (buf + 28, geom->MaxY, GAIA_LITTLE_ENDIAN, endian_arch);
         2827  +	  gaiaExport32 (buf + 36, tot_ln, GAIA_LITTLE_ENDIAN, endian_arch);	/* exports # lines in this polyline */
         2828  +	  gaiaExport32 (buf + 40, tot_v, GAIA_LITTLE_ENDIAN, endian_arch);	/* exports total # points */
         2829  +	  tot_v = 0;		/* resets points counter */
         2830  +	  ix = 44;		/* sets current buffer offset */
         2831  +	  line = geom->FirstLinestring;
         2832  +	  while (line)
         2833  +	    {
         2834  +		/* exports start point index for each line */
         2835  +		gaiaExport32 (buf + ix, tot_v, GAIA_LITTLE_ENDIAN, endian_arch);
         2836  +		tot_v += line->Points;
         2837  +		ix += 4;
         2838  +		line = line->Next;
         2839  +	    }
         2840  +	  line = geom->FirstLinestring;
         2841  +	  while (line)
         2842  +	    {
         2843  +		/* exports points for each line */
         2844  +		for (iv = 0; iv < line->Points; iv++)
         2845  +		  {
         2846  +		      /* exports a POINT [x,y] */
         2847  +		      if (line->DimensionModel == GAIA_XY_Z)
         2848  +			{
         2849  +			    gaiaGetPointXYZ (line->Coords, iv, &x, &y, &z);
         2850  +			}
         2851  +		      else if (line->DimensionModel == GAIA_XY_M)
         2852  +			{
         2853  +			    gaiaGetPointXYM (line->Coords, iv, &x, &y, &m);
         2854  +			}
         2855  +		      else if (line->DimensionModel == GAIA_XY_Z_M)
         2856  +			{
         2857  +			    gaiaGetPointXYZM (line->Coords, iv, &x, &y, &z, &m);
         2858  +			}
         2859  +		      else
         2860  +			{
         2861  +			    gaiaGetPoint (line->Coords, iv, &x, &y);
         2862  +			}
         2863  +		      gaiaExport64 (buf + ix, x,
         2864  +				    GAIA_LITTLE_ENDIAN, endian_arch);
         2865  +		      ix += 8;
         2866  +		      gaiaExport64 (buf + ix, y,
         2867  +				    GAIA_LITTLE_ENDIAN, endian_arch);
         2868  +		      ix += 8;
         2869  +		  }
         2870  +		line = line->Next;
         2871  +	    }
         2872  +	  /* exporting the M-range [min/max] */
         2873  +	  gaiaExport64 (buf + ix, minM, GAIA_LITTLE_ENDIAN, endian_arch);
         2874  +	  ix += 8;
         2875  +	  gaiaExport64 (buf + ix, maxM, GAIA_LITTLE_ENDIAN, endian_arch);
         2876  +	  ix += 8;
         2877  +	  line = geom->FirstLinestring;
         2878  +	  while (line)
         2879  +	    {
         2880  +		/* exports M-values for each line */
         2881  +		for (iv = 0; iv < line->Points; iv++)
         2882  +		  {
         2883  +		      /* exports M-value */
         2884  +		      m = 0.0;
         2885  +		      if (line->DimensionModel == GAIA_XY_Z)
         2886  +			{
         2887  +			    gaiaGetPointXYZ (line->Coords, iv, &x, &y, &z);
         2888  +			}
         2889  +		      else if (line->DimensionModel == GAIA_XY_M)
         2890  +			{
         2891  +			    gaiaGetPointXYM (line->Coords, iv, &x, &y, &m);
         2892  +			}
         2893  +		      else if (line->DimensionModel == GAIA_XY_Z_M)
         2894  +			{
         2895  +			    gaiaGetPointXYZM (line->Coords, iv, &x, &y, &z, &m);
         2896  +			}
         2897  +		      else
         2898  +			{
         2899  +			    gaiaGetPoint (line->Coords, iv, &x, &y);
         2900  +			}
         2901  +		      gaiaExport64 (buf + ix, m,
         2902  +				    GAIA_LITTLE_ENDIAN, endian_arch);
         2903  +		      ix += 8;
         2904  +		  }
         2905  +		line = line->Next;
         2906  +	    }
         2907  +	  *bufshp = buf;
         2908  +	  return 1;
         2909  +      }
         2910  +    if (xshape == GAIA_SHP_POLYGON)
         2911  +      {
         2912  +	  /* this one is expected to be a POLYGON or a MULTIPOLYGON */
         2913  +	  gaiaPolygonPtr polyg;
         2914  +	  gaiaRingPtr ring;
         2915  +	  int ib;
         2916  +	  tot_ln = 0;
         2917  +	  tot_v = 0;
         2918  +	  polyg = geom->FirstPolygon;
         2919  +	  while (polyg)
         2920  +	    {
         2921  +		/* computes # rings and total # points */
         2922  +		gaiaSaneClockwise (polyg);	/* we must assure that exterior ring is clockwise, and interior rings are anti-clockwise */
         2923  +		ring = polyg->Exterior;	/* this one is the exterior ring */
         2924  +		tot_v += ring->Points;
         2925  +		tot_ln++;
         2926  +		for (ib = 0; ib < polyg->NumInteriors; ib++)
         2927  +		  {
         2928  +		      /* that ones are the interior rings */
         2929  +		      ring = polyg->Interiors + ib;
         2930  +		      tot_v += ring->Points;
         2931  +		      tot_ln++;
         2932  +		  }
         2933  +		polyg = polyg->Next;
         2934  +	    }
         2935  +	  this_size = 22 + (2 * tot_ln) + (tot_v * 8);	/* size [in 16 bits words !!!] for this SHP entity */
         2936  +	  *buflen = this_size * 2;
         2937  +	  buf = malloc (this_size * 2);
         2938  +	  gaiaExport32 (buf + 0, GAIA_SHP_POLYGON, GAIA_LITTLE_ENDIAN, endian_arch);	/* exports geometry type = POLYGON */
         2939  +	  gaiaExport64 (buf + 4, geom->MinX, GAIA_LITTLE_ENDIAN, endian_arch);	/* exports the MBR for this geometry */
         2940  +	  gaiaExport64 (buf + 12, geom->MinY, GAIA_LITTLE_ENDIAN, endian_arch);
         2941  +	  gaiaExport64 (buf + 20, geom->MaxX, GAIA_LITTLE_ENDIAN, endian_arch);
         2942  +	  gaiaExport64 (buf + 28, geom->MaxY, GAIA_LITTLE_ENDIAN, endian_arch);
         2943  +	  gaiaExport32 (buf + 36, tot_ln, GAIA_LITTLE_ENDIAN, endian_arch);	/* exports # rings in this polygon */
         2944  +	  gaiaExport32 (buf + 40, tot_v, GAIA_LITTLE_ENDIAN, endian_arch);	/* exports total # points */
         2945  +	  tot_v = 0;		/* resets points counter */
         2946  +	  ix = 44;		/* sets current buffer offset */
         2947  +	  polyg = geom->FirstPolygon;
         2948  +	  while (polyg)
         2949  +	    {
         2950  +		/* exports start point index for each line */
         2951  +		ring = polyg->Exterior;	/* this one is the exterior ring */
         2952  +		gaiaExport32 (buf + ix, tot_v, GAIA_LITTLE_ENDIAN, endian_arch);
         2953  +		tot_v += ring->Points;
         2954  +		ix += 4;
         2955  +		for (ib = 0; ib < polyg->NumInteriors; ib++)
         2956  +		  {
         2957  +		      /* that ones are the interior rings */
         2958  +		      ring = polyg->Interiors + ib;
         2959  +		      gaiaExport32 (buf + ix, tot_v,
         2960  +				    GAIA_LITTLE_ENDIAN, endian_arch);
         2961  +		      tot_v += ring->Points;
         2962  +		      ix += 4;
         2963  +		  }
         2964  +		polyg = polyg->Next;
         2965  +	    }
         2966  +	  polyg = geom->FirstPolygon;
         2967  +	  while (polyg)
         2968  +	    {
         2969  +		/* exports points for each ring */
         2970  +		ring = polyg->Exterior;	/* this one is the exterior ring */
         2971  +		for (iv = 0; iv < ring->Points; iv++)
         2972  +		  {
         2973  +		      /* exports a POINT [x,y] - exterior ring */
         2974  +		      if (ring->DimensionModel == GAIA_XY_Z)
         2975  +			{
         2976  +			    gaiaGetPointXYZ (ring->Coords, iv, &x, &y, &z);
         2977  +			}
         2978  +		      else if (ring->DimensionModel == GAIA_XY_M)
         2979  +			{
         2980  +			    gaiaGetPointXYM (ring->Coords, iv, &x, &y, &m);
         2981  +			}
         2982  +		      else if (ring->DimensionModel == GAIA_XY_Z_M)
         2983  +			{
         2984  +			    gaiaGetPointXYZM (ring->Coords, iv, &x, &y, &z, &m);
         2985  +			}
         2986  +		      else
         2987  +			{
         2988  +			    gaiaGetPoint (ring->Coords, iv, &x, &y);
         2989  +			}
         2990  +		      gaiaExport64 (buf + ix, x,
         2991  +				    GAIA_LITTLE_ENDIAN, endian_arch);
         2992  +		      ix += 8;
         2993  +		      gaiaExport64 (buf + ix, y,
         2994  +				    GAIA_LITTLE_ENDIAN, endian_arch);
         2995  +		      ix += 8;
         2996  +		  }
         2997  +		for (ib = 0; ib < polyg->NumInteriors; ib++)
         2998  +		  {
         2999  +		      /* that ones are the interior rings */
         3000  +		      ring = polyg->Interiors + ib;
         3001  +		      for (iv = 0; iv < ring->Points; iv++)
         3002  +			{
         3003  +			    /* exports a POINT [x,y] - interior ring */
         3004  +			    if (ring->DimensionModel == GAIA_XY_Z)
         3005  +			      {
         3006  +				  gaiaGetPointXYZ (ring->Coords, iv,
         3007  +						   &x, &y, &z);
         3008  +			      }
         3009  +			    else if (ring->DimensionModel == GAIA_XY_M)
         3010  +			      {
         3011  +				  gaiaGetPointXYM (ring->Coords, iv,
         3012  +						   &x, &y, &m);
         3013  +			      }
         3014  +			    else if (ring->DimensionModel == GAIA_XY_Z_M)
         3015  +			      {
         3016  +				  gaiaGetPointXYZM (ring->Coords, iv,
         3017  +						    &x, &y, &z, &m);
         3018  +			      }
         3019  +			    else
         3020  +			      {
         3021  +				  gaiaGetPoint (ring->Coords, iv, &x, &y);
         3022  +			      }
         3023  +			    gaiaExport64 (buf + ix, x,
         3024  +					  GAIA_LITTLE_ENDIAN, endian_arch);
         3025  +			    ix += 8;
         3026  +			    gaiaExport64 (buf + ix, y,
         3027  +					  GAIA_LITTLE_ENDIAN, endian_arch);
         3028  +			    ix += 8;
         3029  +			}
         3030  +		  }
         3031  +		polyg = polyg->Next;
         3032  +	    }
         3033  +	  *bufshp = buf;
         3034  +	  return 1;
         3035  +      }
         3036  +    if (xshape == GAIA_SHP_POLYGONZ)
         3037  +      {
         3038  +	  /* this one is expected to be a POLYGON or a MULTIPOLYGON Z */
         3039  +	  gaiaPolygonPtr polyg;
         3040  +	  gaiaRingPtr ring;
         3041  +	  int ib;
         3042  +	  gaiaZRangeGeometry (geom, &minZ, &maxZ);
         3043  +	  gaiaMRangeGeometry (geom, &minM, &maxM);
         3044  +	  tot_ln = 0;
         3045  +	  tot_v = 0;
         3046  +	  polyg = geom->FirstPolygon;
         3047  +	  while (polyg)
         3048  +	    {
         3049  +		/* computes # rings and total # points */
         3050  +		gaiaSaneClockwise (polyg);	/* we must assure that exterior ring is clockwise, and interior rings are anti-clockwise */
         3051  +		ring = polyg->Exterior;	/* this one is the exterior ring */
         3052  +		tot_v += ring->Points;
         3053  +		tot_ln++;
         3054  +		for (ib = 0; ib < polyg->NumInteriors; ib++)
         3055  +		  {
         3056  +		      /* that ones are the interior rings */
         3057  +		      ring = polyg->Interiors + ib;
         3058  +		      tot_v += ring->Points;
         3059  +		      tot_ln++;
         3060  +		  }
         3061  +		polyg = polyg->Next;
         3062  +	    }
         3063  +	  hasM = 0;
         3064  +	  if (eff_dims == GAIA_XY_M || eff_dims == GAIA_XY_Z_M)
         3065  +	      hasM = 1;
         3066  +	  if (hasM)
         3067  +	      this_size = 38 + (2 * tot_ln) + (tot_v * 16);	/* size [in 16 bits words !!!] ZM */
         3068  +	  else
         3069  +	      this_size = 30 + (2 * tot_ln) + (tot_v * 12);	/* size [in 16 bits words !!!] Z-only */
         3070  +	  *buflen = this_size * 2;
         3071  +	  buf = malloc (this_size * 2);
         3072  +	  gaiaExport32 (buf + 0, GAIA_SHP_POLYGONZ, GAIA_LITTLE_ENDIAN, endian_arch);	/* exports geometry type = POLYGON Z */
         3073  +	  gaiaExport64 (buf + 4, geom->MinX, GAIA_LITTLE_ENDIAN, endian_arch);	/* exports the MBR for this geometry */
         3074  +	  gaiaExport64 (buf + 12, geom->MinY, GAIA_LITTLE_ENDIAN, endian_arch);
         3075  +	  gaiaExport64 (buf + 20, geom->MaxX, GAIA_LITTLE_ENDIAN, endian_arch);
         3076  +	  gaiaExport64 (buf + 28, geom->MaxY, GAIA_LITTLE_ENDIAN, endian_arch);
         3077  +	  gaiaExport32 (buf + 36, tot_ln, GAIA_LITTLE_ENDIAN, endian_arch);	/* exports # rings in this polygon */
         3078  +	  gaiaExport32 (buf + 40, tot_v, GAIA_LITTLE_ENDIAN, endian_arch);	/* exports total # points */
         3079  +	  tot_v = 0;		/* resets points counter */
         3080  +	  ix = 44;		/* sets current buffer offset */
         3081  +	  polyg = geom->FirstPolygon;
         3082  +	  while (polyg)
         3083  +	    {
         3084  +		/* exports start point index for each line */
         3085  +		ring = polyg->Exterior;	/* this one is the exterior ring */
         3086  +		gaiaExport32 (buf + ix, tot_v, GAIA_LITTLE_ENDIAN, endian_arch);
         3087  +		tot_v += ring->Points;
         3088  +		ix += 4;
         3089  +		for (ib = 0; ib < polyg->NumInteriors; ib++)
         3090  +		  {
         3091  +		      /* that ones are the interior rings */
         3092  +		      ring = polyg->Interiors + ib;
         3093  +		      gaiaExport32 (buf + ix, tot_v,
         3094  +				    GAIA_LITTLE_ENDIAN, endian_arch);
         3095  +		      tot_v += ring->Points;
         3096  +		      ix += 4;
         3097  +		  }
         3098  +		polyg = polyg->Next;
         3099  +	    }
         3100  +	  polyg = geom->FirstPolygon;
         3101  +	  while (polyg)
         3102  +	    {
         3103  +		/* exports points for each ring */
         3104  +		ring = polyg->Exterior;	/* this one is the exterior ring */
         3105  +		for (iv = 0; iv < ring->Points; iv++)
         3106  +		  {
         3107  +		      /* exports a POINT [x,y] - exterior ring */
         3108  +		      if (ring->DimensionModel == GAIA_XY_Z)
         3109  +			{
         3110  +			    gaiaGetPointXYZ (ring->Coords, iv, &x, &y, &z);
         3111  +			}
         3112  +		      else if (ring->DimensionModel == GAIA_XY_M)
         3113  +			{
         3114  +			    gaiaGetPointXYM (ring->Coords, iv, &x, &y, &m);
         3115  +			}
         3116  +		      else if (ring->DimensionModel == GAIA_XY_Z_M)
         3117  +			{
         3118  +			    gaiaGetPointXYZM (ring->Coords, iv, &x, &y, &z, &m);
         3119  +			}
         3120  +		      else
         3121  +			{
         3122  +			    gaiaGetPoint (ring->Coords, iv, &x, &y);
         3123  +			}
         3124  +		      gaiaExport64 (buf + ix, x,
         3125  +				    GAIA_LITTLE_ENDIAN, endian_arch);
         3126  +		      ix += 8;
         3127  +		      gaiaExport64 (buf + ix, y,
         3128  +				    GAIA_LITTLE_ENDIAN, endian_arch);
         3129  +		      ix += 8;
         3130  +		  }
         3131  +		for (ib = 0; ib < polyg->NumInteriors; ib++)
         3132  +		  {
         3133  +		      /* that ones are the interior rings */
         3134  +		      ring = polyg->Interiors + ib;
         3135  +		      for (iv = 0; iv < ring->Points; iv++)
         3136  +			{
         3137  +			    /* exports a POINT [x,y] - interior ring */
         3138  +			    if (ring->DimensionModel == GAIA_XY_Z)
         3139  +			      {
         3140  +				  gaiaGetPointXYZ (ring->Coords, iv,
         3141  +						   &x, &y, &z);
         3142  +			      }
         3143  +			    else if (ring->DimensionModel == GAIA_XY_M)
         3144  +			      {
         3145  +				  gaiaGetPointXYM (ring->Coords, iv,
         3146  +						   &x, &y, &m);
         3147  +			      }
         3148  +			    else if (ring->DimensionModel == GAIA_XY_Z_M)
         3149  +			      {
         3150  +				  gaiaGetPointXYZM (ring->Coords, iv,
         3151  +						    &x, &y, &z, &m);
         3152  +			      }
         3153  +			    else
         3154  +			      {
         3155  +				  gaiaGetPoint (ring->Coords, iv, &x, &y);
         3156  +			      }
         3157  +			    gaiaExport64 (buf + ix, x,
         3158  +					  GAIA_LITTLE_ENDIAN, endian_arch);
         3159  +			    ix += 8;
         3160  +			    gaiaExport64 (buf + ix, y,
         3161  +					  GAIA_LITTLE_ENDIAN, endian_arch);
         3162  +			    ix += 8;
         3163  +			}
         3164  +		  }
         3165  +		polyg = polyg->Next;
         3166  +	    }
         3167  +	  /* exporting the Z-range [min/max] */
         3168  +	  gaiaExport64 (buf + ix, minZ, GAIA_LITTLE_ENDIAN, endian_arch);
         3169  +	  ix += 8;
         3170  +	  gaiaExport64 (buf + ix, maxZ, GAIA_LITTLE_ENDIAN, endian_arch);
         3171  +	  ix += 8;
         3172  +	  polyg = geom->FirstPolygon;
         3173  +	  while (polyg)
         3174  +	    {
         3175  +		/* exports Z-values for each ring */
         3176  +		ring = polyg->Exterior;	/* this one is the exterior ring */
         3177  +		for (iv = 0; iv < ring->Points; iv++)
         3178  +		  {
         3179  +		      /* exports Z-values - exterior ring */
         3180  +		      z = 0.0;
         3181  +		      if (ring->DimensionModel == GAIA_XY_Z)
         3182  +			{
         3183  +			    gaiaGetPointXYZ (ring->Coords, iv, &x, &y, &z);
         3184  +			}
         3185  +		      else if (ring->DimensionModel == GAIA_XY_M)
         3186  +			{
         3187  +			    gaiaGetPointXYM (ring->Coords, iv, &x, &y, &m);
         3188  +			}
         3189  +		      else if (ring->DimensionModel == GAIA_XY_Z_M)
         3190  +			{
         3191  +			    gaiaGetPointXYZM (ring->Coords, iv, &x, &y, &z, &m);
         3192  +			}
         3193  +		      else
         3194  +			{
         3195  +			    gaiaGetPoint (ring->Coords, iv, &x, &y);
         3196  +			}
         3197  +		      gaiaExport64 (buf + ix, z,
         3198  +				    GAIA_LITTLE_ENDIAN, endian_arch);
         3199  +		      ix += 8;
         3200  +		  }
         3201  +		for (ib = 0; ib < polyg->NumInteriors; ib++)
         3202  +		  {
         3203  +		      /* that ones are the interior rings */
         3204  +		      ring = polyg->Interiors + ib;
         3205  +		      for (iv = 0; iv < ring->Points; iv++)
         3206  +			{
         3207  +			    /* exports Z-values - interior ring */
         3208  +			    z = 0.0;
         3209  +			    if (ring->DimensionModel == GAIA_XY_Z)
         3210  +			      {
         3211  +				  gaiaGetPointXYZ (ring->Coords, iv,
         3212  +						   &x, &y, &z);
         3213  +			      }
         3214  +			    else if (ring->DimensionModel == GAIA_XY_M)
         3215  +			      {
         3216  +				  gaiaGetPointXYM (ring->Coords, iv,
         3217  +						   &x, &y, &m);
         3218  +			      }
         3219  +			    else if (ring->DimensionModel == GAIA_XY_Z_M)
         3220  +			      {
         3221  +				  gaiaGetPointXYZM (ring->Coords, iv,
         3222  +						    &x, &y, &z, &m);
         3223  +			      }
         3224  +			    else
         3225  +			      {
         3226  +				  gaiaGetPoint (ring->Coords, iv, &x, &y);
         3227  +			      }
         3228  +			    gaiaExport64 (buf + ix, z,
         3229  +					  GAIA_LITTLE_ENDIAN, endian_arch);
         3230  +			    ix += 8;
         3231  +			}
         3232  +		  }
         3233  +		polyg = polyg->Next;
         3234  +	    }
         3235  +	  if (hasM)
         3236  +	    {
         3237  +		/* exporting the M-range [min/max] */
         3238  +		gaiaExport64 (buf + ix, minM, GAIA_LITTLE_ENDIAN, endian_arch);
         3239  +		ix += 8;
         3240  +		gaiaExport64 (buf + ix, maxM, GAIA_LITTLE_ENDIAN, endian_arch);
         3241  +		ix += 8;
         3242  +		polyg = geom->FirstPolygon;
         3243  +		while (polyg)
         3244  +		  {
         3245  +		      /* exports M-values for each ring */
         3246  +		      ring = polyg->Exterior;	/* this one is the exterior ring */
         3247  +		      for (iv = 0; iv < ring->Points; iv++)
         3248  +			{
         3249  +			    /* exports M-values - exterior ring */
         3250  +			    m = 0.0;
         3251  +			    if (ring->DimensionModel == GAIA_XY_Z)
         3252  +			      {
         3253  +				  gaiaGetPointXYZ (ring->Coords, iv,
         3254  +						   &x, &y, &z);
         3255  +			      }
         3256  +			    else if (ring->DimensionModel == GAIA_XY_M)
         3257  +			      {
         3258  +				  gaiaGetPointXYM (ring->Coords, iv,
         3259  +						   &x, &y, &m);
         3260  +			      }
         3261  +			    else if (ring->DimensionModel == GAIA_XY_Z_M)
         3262  +			      {
         3263  +				  gaiaGetPointXYZM (ring->Coords, iv,
         3264  +						    &x, &y, &z, &m);
         3265  +			      }
         3266  +			    else
         3267  +			      {
         3268  +				  gaiaGetPoint (ring->Coords, iv, &x, &y);
         3269  +			      }
         3270  +			    gaiaExport64 (buf + ix, m,
         3271  +					  GAIA_LITTLE_ENDIAN, endian_arch);
         3272  +			    ix += 8;
         3273  +			}
         3274  +		      for (ib = 0; ib < polyg->NumInteriors; ib++)
         3275  +			{
         3276  +			    /* that ones are the interior rings */
         3277  +			    ring = polyg->Interiors + ib;
         3278  +			    for (iv = 0; iv < ring->Points; iv++)
         3279  +			      {
         3280  +				  /* exports M-values - interior ring */
         3281  +				  m = 0.0;
         3282  +				  if (ring->DimensionModel == GAIA_XY_Z)
         3283  +				    {
         3284  +					gaiaGetPointXYZ (ring->Coords,
         3285  +							 iv, &x, &y, &z);
         3286  +				    }
         3287  +				  else if (ring->DimensionModel == GAIA_XY_M)
         3288  +				    {
         3289  +					gaiaGetPointXYM (ring->Coords,
         3290  +							 iv, &x, &y, &m);
         3291  +				    }
         3292  +				  else if (ring->DimensionModel == GAIA_XY_Z_M)
         3293  +				    {
         3294  +					gaiaGetPointXYZM (ring->Coords,
         3295  +							  iv, &x, &y, &z, &m);
         3296  +				    }
         3297  +				  else
         3298  +				    {
         3299  +					gaiaGetPoint (ring->Coords, iv, &x, &y);
         3300  +				    }
         3301  +				  gaiaExport64 (buf + ix, m,
         3302  +						GAIA_LITTLE_ENDIAN,
         3303  +						endian_arch);
         3304  +				  ix += 8;
         3305  +			      }
         3306  +			}
         3307  +		      polyg = polyg->Next;
         3308  +		  }
         3309  +	    }
         3310  +	  *bufshp = buf;
         3311  +	  return 1;
         3312  +      }
         3313  +    if (xshape == GAIA_SHP_POLYGONM)
         3314  +      {
         3315  +	  /* this one is expected to be a POLYGON or a MULTIPOLYGON M */
         3316  +	  gaiaPolygonPtr polyg;
         3317  +	  gaiaRingPtr ring;
         3318  +	  int ib;
         3319  +	  gaiaMRangeGeometry (geom, &minM, &maxM);
         3320  +	  tot_ln = 0;
         3321  +	  tot_v = 0;
         3322  +	  polyg = geom->FirstPolygon;
         3323  +	  while (polyg)
         3324  +	    {
         3325  +		/* computes # rings and total # points */
         3326  +		gaiaSaneClockwise (polyg);	/* we must assure that exterior ring is clockwise, and interior rings are anti-clockwise */
         3327  +		ring = polyg->Exterior;	/* this one is the exterior ring */
         3328  +		tot_v += ring->Points;
         3329  +		tot_ln++;
         3330  +		for (ib = 0; ib < polyg->NumInteriors; ib++)
         3331  +		  {
         3332  +		      /* that ones are the interior rings */
         3333  +		      ring = polyg->Interiors + ib;
         3334  +		      tot_v += ring->Points;
         3335  +		      tot_ln++;
         3336  +		  }
         3337  +		polyg = polyg->Next;
         3338  +	    }
         3339  +	  this_size = 30 + (2 * tot_ln) + (tot_v * 12);	/* size [in 16 bits words !!!] for this SHP entity */
         3340  +	  *buflen = this_size * 2;
         3341  +	  buf = malloc (this_size * 2);
         3342  +	  gaiaExport32 (buf + 0, GAIA_SHP_POLYGONM, GAIA_LITTLE_ENDIAN, endian_arch);	/* exports geometry type = POLYGON M */
         3343  +	  gaiaExport64 (buf + 4, geom->MinX, GAIA_LITTLE_ENDIAN, endian_arch);	/* exports the MBR for this geometry */
         3344  +	  gaiaExport64 (buf + 12, geom->MinY, GAIA_LITTLE_ENDIAN, endian_arch);
         3345  +	  gaiaExport64 (buf + 20, geom->MaxX, GAIA_LITTLE_ENDIAN, endian_arch);
         3346  +	  gaiaExport64 (buf + 28, geom->MaxY, GAIA_LITTLE_ENDIAN, endian_arch);
         3347  +	  gaiaExport32 (buf + 36, tot_ln, GAIA_LITTLE_ENDIAN, endian_arch);	/* exports # rings in this polygon */
         3348  +	  gaiaExport32 (buf + 40, tot_v, GAIA_LITTLE_ENDIAN, endian_arch);	/* exports total # points */
         3349  +	  tot_v = 0;		/* resets points counter */
         3350  +	  ix = 44;		/* sets current buffer offset */
         3351  +	  polyg = geom->FirstPolygon;
         3352  +	  while (polyg)
         3353  +	    {
         3354  +		/* exports start point index for each line */
         3355  +		ring = polyg->Exterior;	/* this one is the exterior ring */
         3356  +		gaiaExport32 (buf + ix, tot_v, GAIA_LITTLE_ENDIAN, endian_arch);
         3357  +		tot_v += ring->Points;
         3358  +		ix += 4;
         3359  +		for (ib = 0; ib < polyg->NumInteriors; ib++)
         3360  +		  {
         3361  +		      /* that ones are the interior rings */
         3362  +		      ring = polyg->Interiors + ib;
         3363  +		      gaiaExport32 (buf + ix, tot_v,
         3364  +				    GAIA_LITTLE_ENDIAN, endian_arch);
         3365  +		      tot_v += ring->Points;
         3366  +		      ix += 4;
         3367  +		  }
         3368  +		polyg = polyg->Next;
         3369  +	    }
         3370  +	  polyg = geom->FirstPolygon;
         3371  +	  while (polyg)
         3372  +	    {
         3373  +		/* exports points for each ring */
         3374  +		ring = polyg->Exterior;	/* this one is the exterior ring */
         3375  +		for (iv = 0; iv < ring->Points; iv++)
         3376  +		  {
         3377  +		      /* exports a POINT [x,y] - exterior ring */
         3378  +		      if (ring->DimensionModel == GAIA_XY_Z)
         3379  +			{
         3380  +			    gaiaGetPointXYZ (ring->Coords, iv, &x, &y, &z);
         3381  +			}
         3382  +		      else if (ring->DimensionModel == GAIA_XY_M)
         3383  +			{
         3384  +			    gaiaGetPointXYM (ring->Coords, iv, &x, &y, &m);
         3385  +			}
         3386  +		      else if (ring->DimensionModel == GAIA_XY_Z_M)
         3387  +			{
         3388  +			    gaiaGetPointXYZM (ring->Coords, iv, &x, &y, &z, &m);
         3389  +			}
         3390  +		      else
         3391  +			{
         3392  +			    gaiaGetPoint (ring->Coords, iv, &x, &y);
         3393  +			}
         3394  +		      gaiaExport64 (buf + ix, x,
         3395  +				    GAIA_LITTLE_ENDIAN, endian_arch);
         3396  +		      ix += 8;
         3397  +		      gaiaExport64 (buf + ix, y,
         3398  +				    GAIA_LITTLE_ENDIAN, endian_arch);
         3399  +		      ix += 8;
         3400  +		  }
         3401  +		for (ib = 0; ib < polyg->NumInteriors; ib++)
         3402  +		  {
         3403  +		      /* that ones are the interior rings */
         3404  +		      ring = polyg->Interiors + ib;
         3405  +		      for (iv = 0; iv < ring->Points; iv++)
         3406  +			{
         3407  +			    /* exports a POINT [x,y] - interior ring */
         3408  +			    if (ring->DimensionModel == GAIA_XY_Z)
         3409  +			      {
         3410  +				  gaiaGetPointXYZ (ring->Coords, iv,
         3411  +						   &x, &y, &z);
         3412  +			      }
         3413  +			    else if (ring->DimensionModel == GAIA_XY_M)
         3414  +			      {
         3415  +				  gaiaGetPointXYM (ring->Coords, iv,
         3416  +						   &x, &y, &m);
         3417  +			      }
         3418  +			    else if (ring->DimensionModel == GAIA_XY_Z_M)
         3419  +			      {
         3420  +				  gaiaGetPointXYZM (ring->Coords, iv,
         3421  +						    &x, &y, &z, &m);
         3422  +			      }
         3423  +			    else
         3424  +			      {
         3425  +				  gaiaGetPoint (ring->Coords, iv, &x, &y);
         3426  +			      }
         3427  +			    gaiaExport64 (buf + ix, x,
         3428  +					  GAIA_LITTLE_ENDIAN, endian_arch);
         3429  +			    ix += 8;
         3430  +			    gaiaExport64 (buf + ix, y,
         3431  +					  GAIA_LITTLE_ENDIAN, endian_arch);
         3432  +			    ix += 8;
         3433  +			}
         3434  +		  }
         3435  +		polyg = polyg->Next;
         3436  +	    }
         3437  +	  /* exporting the M-range [min/max] */
         3438  +	  gaiaExport64 (buf + ix, minM, GAIA_LITTLE_ENDIAN, endian_arch);
         3439  +	  ix += 8;
         3440  +	  gaiaExport64 (buf + ix, maxM, GAIA_LITTLE_ENDIAN, endian_arch);
         3441  +	  ix += 8;
         3442  +	  polyg = geom->FirstPolygon;
         3443  +	  while (polyg)
         3444  +	    {
         3445  +		/* exports M-values for each ring */
         3446  +		ring = polyg->Exterior;	/* this one is the exterior ring */
         3447  +		for (iv = 0; iv < ring->Points; iv++)
         3448  +		  {
         3449  +		      /* exports M-values - exterior ring */
         3450  +		      m = 0.0;
         3451  +		      if (ring->DimensionModel == GAIA_XY_Z)
         3452  +			{
         3453  +			    gaiaGetPointXYZ (ring->Coords, iv, &x, &y, &z);
         3454  +			}
         3455  +		      else if (ring->DimensionModel == GAIA_XY_M)
         3456  +			{
         3457  +			    gaiaGetPointXYM (ring->Coords, iv, &x, &y, &m);
         3458  +			}
         3459  +		      else if (ring->DimensionModel == GAIA_XY_Z_M)
         3460  +			{
         3461  +			    gaiaGetPointXYZM (ring->Coords, iv, &x, &y, &z, &m);
         3462  +			}
         3463  +		      else
         3464  +			{
         3465  +			    gaiaGetPoint (ring->Coords, iv, &x, &y);
         3466  +			}
         3467  +		      gaiaExport64 (buf + ix, m,
         3468  +				    GAIA_LITTLE_ENDIAN, endian_arch);
         3469  +		      ix += 8;
         3470  +		  }
         3471  +		for (ib = 0; ib < polyg->NumInteriors; ib++)
         3472  +		  {
         3473  +		      /* that ones are the interior rings */
         3474  +		      ring = polyg->Interiors + ib;
         3475  +		      for (iv = 0; iv < ring->Points; iv++)
         3476  +			{
         3477  +			    /* exports M-values - interior ring */
         3478  +			    m = 0.0;
         3479  +			    if (ring->DimensionModel == GAIA_XY_Z)
         3480  +			      {
         3481  +				  gaiaGetPointXYZ (ring->Coords, iv,
         3482  +						   &x, &y, &z);
         3483  +			      }
         3484  +			    else if (ring->DimensionModel == GAIA_XY_M)
         3485  +			      {
         3486  +				  gaiaGetPointXYM (ring->Coords, iv,
         3487  +						   &x, &y, &m);
         3488  +			      }
         3489  +			    else if (ring->DimensionModel == GAIA_XY_Z_M)
         3490  +			      {
         3491  +				  gaiaGetPointXYZM (ring->Coords, iv,
         3492  +						    &x, &y, &z, &m);
         3493  +			      }
         3494  +			    else
         3495  +			      {
         3496  +				  gaiaGetPoint (ring->Coords, iv, &x, &y);
         3497  +			      }
         3498  +			    gaiaExport64 (buf + ix, m,
         3499  +					  GAIA_LITTLE_ENDIAN, endian_arch);
         3500  +			    ix += 8;
         3501  +			}
         3502  +		  }
         3503  +		polyg = polyg->Next;
         3504  +	    }
         3505  +	  *bufshp = buf;
         3506  +	  return 1;
         3507  +      }
         3508  +    if (xshape == GAIA_SHP_MULTIPOINT)
         3509  +      {
         3510  +	  /* this one is expected to be a MULTIPOINT */
         3511  +	  gaiaPointPtr pt;
         3512  +	  tot_pts = 0;
         3513  +	  pt = geom->FirstPoint;
         3514  +	  while (pt)
         3515  +	    {
         3516  +		/* computes # points */
         3517  +		tot_pts++;
         3518  +		pt = pt->Next;
         3519  +	    }
         3520  +	  this_size = 20 + (tot_pts * 8);	/* size [in 16 bits words !!!] for this SHP entity */
         3521  +	  *buflen = this_size * 2;
         3522  +	  buf = malloc (this_size * 2);
         3523  +	  gaiaExport32 (buf + 0, GAIA_SHP_MULTIPOINT, GAIA_LITTLE_ENDIAN, endian_arch);	/* exports geometry type = MULTIPOINT */
         3524  +	  gaiaExport64 (buf + 4, geom->MinX, GAIA_LITTLE_ENDIAN, endian_arch);	/* exports the MBR for this geometry */
         3525  +	  gaiaExport64 (buf + 12, geom->MinY, GAIA_LITTLE_ENDIAN, endian_arch);
         3526  +	  gaiaExport64 (buf + 20, geom->MaxX, GAIA_LITTLE_ENDIAN, endian_arch);
         3527  +	  gaiaExport64 (buf + 28, geom->MaxY, GAIA_LITTLE_ENDIAN, endian_arch);
         3528  +	  gaiaExport32 (buf + 36, tot_pts, GAIA_LITTLE_ENDIAN, endian_arch);	/* exports total # points */
         3529  +	  ix = 40;		/* sets current buffer offset */
         3530  +	  pt = geom->FirstPoint;
         3531  +	  while (pt)
         3532  +	    {
         3533  +		/* exports each point */
         3534  +		gaiaExport64 (buf + ix, pt->X, GAIA_LITTLE_ENDIAN, endian_arch);
         3535  +		ix += 8;
         3536  +		gaiaExport64 (buf + ix, pt->Y, GAIA_LITTLE_ENDIAN, endian_arch);
         3537  +		ix += 8;
         3538  +		pt = pt->Next;
         3539  +	    }
         3540  +	  *bufshp = buf;
         3541  +	  return 1;
         3542  +      }
         3543  +    if (xshape == GAIA_SHP_MULTIPOINTZ)
         3544  +      {
         3545  +	  /* this one is expected to be a MULTIPOINT Z */
         3546  +	  gaiaPointPtr pt;
         3547  +	  gaiaZRangeGeometry (geom, &minZ, &maxZ);
         3548  +	  gaiaMRangeGeometry (geom, &minM, &maxM);
         3549  +	  tot_pts = 0;
         3550  +	  pt = geom->FirstPoint;
         3551  +	  while (pt)
         3552  +	    {
         3553  +		/* computes # points */
         3554  +		tot_pts++;
         3555  +		pt = pt->Next;
         3556  +	    }
         3557  +	  hasM = 0;
         3558  +	  if (eff_dims == GAIA_XY_M || eff_dims == GAIA_XY_Z_M)
         3559  +	      hasM = 1;
         3560  +	  if (hasM)
         3561  +	      this_size = 36 + (tot_pts * 16);	/* size [in 16 bits words !!!] ZM */
         3562  +	  else
         3563  +	      this_size = 28 + (tot_pts * 12);	/* size [in 16 bits words !!!] Z-only */
         3564  +	  *buflen = this_size * 2;
         3565  +	  buf = malloc (this_size * 2);
         3566  +	  gaiaExport32 (buf + 0, GAIA_SHP_MULTIPOINTZ, GAIA_LITTLE_ENDIAN, endian_arch);	/* exports geometry type = MULTIPOINT Z */
         3567  +	  gaiaExport64 (buf + 4, geom->MinX, GAIA_LITTLE_ENDIAN, endian_arch);	/* exports the MBR for this geometry */
         3568  +	  gaiaExport64 (buf + 12, geom->MinY, GAIA_LITTLE_ENDIAN, endian_arch);
         3569  +	  gaiaExport64 (buf + 20, geom->MaxX, GAIA_LITTLE_ENDIAN, endian_arch);
         3570  +	  gaiaExport64 (buf + 28, geom->MaxY, GAIA_LITTLE_ENDIAN, endian_arch);
         3571  +	  gaiaExport32 (buf + 36, tot_pts, GAIA_LITTLE_ENDIAN, endian_arch);	/* exports total # points */
         3572  +	  ix = 40;		/* sets current buffer offset */
         3573  +	  pt = geom->FirstPoint;
         3574  +	  while (pt)
         3575  +	    {
         3576  +		/* exports each point */
         3577  +		gaiaExport64 (buf + ix, pt->X, GAIA_LITTLE_ENDIAN, endian_arch);
         3578  +		ix += 8;
         3579  +		gaiaExport64 (buf + ix, pt->Y, GAIA_LITTLE_ENDIAN, endian_arch);
         3580  +		ix += 8;
         3581  +		pt = pt->Next;
         3582  +	    }
         3583  +	  /* exporting the Z-range [min/max] */
         3584  +	  gaiaExport64 (buf + ix, minZ, GAIA_LITTLE_ENDIAN, endian_arch);
         3585  +	  ix += 8;
         3586  +	  gaiaExport64 (buf + ix, maxZ, GAIA_LITTLE_ENDIAN, endian_arch);
         3587  +	  ix += 8;
         3588  +	  pt = geom->FirstPoint;
         3589  +	  while (pt)
         3590  +	    {
         3591  +		/* exports Z-values */
         3592  +		gaiaExport64 (buf + ix, pt->Z, GAIA_LITTLE_ENDIAN, endian_arch);
         3593  +		ix += 8;
         3594  +		pt = pt->Next;
         3595  +	    }
         3596  +	  if (hasM)
         3597  +	    {
         3598  +		/* exporting the M-range [min/max] */
         3599  +		gaiaExport64 (buf + ix, minM, GAIA_LITTLE_ENDIAN, endian_arch);
         3600  +		ix += 8;
         3601  +		gaiaExport64 (buf + ix, maxM, GAIA_LITTLE_ENDIAN, endian_arch);
         3602  +		ix += 8;
         3603  +		pt = geom->FirstPoint;
         3604  +		while (pt)
         3605  +		  {
         3606  +		      /* exports M-values */
         3607  +		      gaiaExport64 (buf + ix, pt->M,
         3608  +				    GAIA_LITTLE_ENDIAN, endian_arch);
         3609  +		      ix += 8;
         3610  +		      pt = pt->Next;
         3611  +		  }
         3612  +	    }
         3613  +	  *bufshp = buf;
         3614  +	  return 1;
         3615  +      }
         3616  +    if (xshape == GAIA_SHP_MULTIPOINTM)
         3617  +      {
         3618  +	  /* this one is expected to be a MULTIPOINT M */
         3619  +	  gaiaPointPtr pt;
         3620  +	  gaiaMRangeGeometry (geom, &minM, &maxM);
         3621  +	  tot_pts = 0;
         3622  +	  pt = geom->FirstPoint;
         3623  +	  while (pt)
         3624  +	    {
         3625  +		/* computes # points */
         3626  +		tot_pts++;
         3627  +		pt = pt->Next;
         3628  +	    }
         3629  +	  this_size = 28 + (tot_pts * 12);	/* size [in 16 bits words !!!] for this SHP entity */
         3630  +	  *buflen = this_size * 2;
         3631  +	  buf = malloc (this_size * 2);
         3632  +	  gaiaExport32 (buf + 0, GAIA_SHP_MULTIPOINTM, GAIA_LITTLE_ENDIAN, endian_arch);	/* exports geometry type = MULTIPOINT M */
         3633  +	  gaiaExport64 (buf + 4, geom->MinX, GAIA_LITTLE_ENDIAN, endian_arch);	/* exports the MBR for this geometry */
         3634  +	  gaiaExport64 (buf + 12, geom->MinY, GAIA_LITTLE_ENDIAN, endian_arch);
         3635  +	  gaiaExport64 (buf + 20, geom->MaxX, GAIA_LITTLE_ENDIAN, endian_arch);
         3636  +	  gaiaExport64 (buf + 28, geom->MaxY, GAIA_LITTLE_ENDIAN, endian_arch);
         3637  +	  gaiaExport32 (buf + 36, tot_pts, GAIA_LITTLE_ENDIAN, endian_arch);	/* exports total # points */
         3638  +	  ix = 40;		/* sets current buffer offset */
         3639  +	  pt = geom->FirstPoint;
         3640  +	  while (pt)
         3641  +	    {
         3642  +		/* exports each point */
         3643  +		gaiaExport64 (buf + ix, pt->X, GAIA_LITTLE_ENDIAN, endian_arch);
         3644  +		ix += 8;
         3645  +		gaiaExport64 (buf + ix, pt->Y, GAIA_LITTLE_ENDIAN, endian_arch);
         3646  +		ix += 8;
         3647  +		pt = pt->Next;
         3648  +	    }
         3649  +	  /* exporting the M-range [min/max] */
         3650  +	  gaiaExport64 (buf + ix, minM, GAIA_LITTLE_ENDIAN, endian_arch);
         3651  +	  ix += 8;
         3652  +	  gaiaExport64 (buf + ix, maxM, GAIA_LITTLE_ENDIAN, endian_arch);
         3653  +	  ix += 8;
         3654  +	  pt = geom->FirstPoint;
         3655  +	  while (pt)
         3656  +	    {
         3657  +		/* exports M-values */
         3658  +		gaiaExport64 (buf + ix, pt->M, GAIA_LITTLE_ENDIAN, endian_arch);
         3659  +		ix += 8;
         3660  +		pt = pt->Next;
         3661  +	    }
         3662  +	  *bufshp = buf;
         3663  +	  return 1;
         3664  +      }
         3665  +
         3666  +    fprintf (stderr,
         3667  +	     "\tinput row #%d: unable to export a consistent Geometry\n",
         3668  +	     rowno);
         3669  +    return 0;
         3670  +}
         3671  +
         3672  +static int
         3673  +do_repair_shapefile (const void *cache, const char *shp_path,
         3674  +		     const char *out_path, int validate, int esri, int force,
         3675  +		     int *repair_failed)
         3676  +{
         3677  +/* repairing some Shapefile */
         3678  +    int current_row;
         3679  +    gaiaShapefilePtr shp_in = NULL;
         3680  +    gaiaShapefilePtr shp_out = NULL;
         3681  +    int ret;
         3682  +    gaiaDbfListPtr dbf_list = NULL;
         3683  +    gaiaDbfFieldPtr in_fld;
         3684  +    double minx;
         3685  +    double miny;
         3686  +    double maxx;
         3687  +    double maxy;
         3688  +    double hMinX;
         3689  +    double hMinY;
         3690  +    double hMaxX;
         3691  +    double hMaxY;
         3692  +    int mismatching;
         3693  +
         3694  +    *repair_failed = 0;
         3695  +
         3696  +/* opening the INPUT SHP */
         3697  +    shp_in = allocShapefile ();
         3698  +    openShpRead (shp_in, shp_path, &hMinX, &hMinY, &hMaxX, &hMaxY,
         3699  +		 &mismatching);
         3700  +    if (!(shp_in->Valid))
         3701  +      {
         3702  +	  char extra[512];
         3703  +	  *extra = '\0';
         3704  +	  if (shp_in->LastError)
         3705  +	      sprintf (extra, "\n\t\tcause: %s\n", shp_in->LastError);
         3706  +	  fprintf (stderr,
         3707  +		   "\t\terror: cannot open shapefile '%s'%s", shp_path, extra);
         3708  +	  freeShapefile (shp_in);
         3709  +	  return 0;
         3710  +      }
         3711  +
         3712  +/* preparing the DBF fields list - OUTPUT */
         3713  +    dbf_list = gaiaAllocDbfList ();
         3714  +    in_fld = shp_in->Dbf->First;
         3715  +    while (in_fld)
         3716  +      {
         3717  +	  /* adding a DBF field - OUTPUT */
         3718  +	  gaiaAddDbfField (dbf_list, in_fld->Name, in_fld->Type, in_fld->Offset,
         3719  +			   in_fld->Length, in_fld->Decimals);
         3720  +	  in_fld = in_fld->Next;
         3721  +      }
         3722  +
         3723  +/* creating the OUTPUT SHP */
         3724  +    shp_out = allocShapefile ();
         3725  +    openShpWrite (shp_out, out_path, shp_in->Shape, dbf_list);
         3726  +    if (!(shp_out->Valid))
         3727  +      {
         3728  +	  char extra[512];
         3729  +	  *extra = '\0';
         3730  +	  if (shp_out->LastError)
         3731  +	      sprintf (extra, "\n\t\tcause: %s\n", shp_out->LastError);
         3732  +	  fprintf (stderr,
         3733  +		   "\t\terror: cannot open shapefile '%s'%s", out_path, extra);
         3734  +	  freeShapefile (shp_in);
         3735  +	  freeShapefile (shp_out);
         3736  +	  gaiaFreeDbfList (dbf_list);
         3737  +	  return 0;
         3738  +      }
         3739  +
         3740  +    current_row = 0;
         3741  +    while (1)
         3742  +      {
         3743  +	  /* reading rows from shapefile */
         3744  +	  int shplen;
         3745  +	  ret =
         3746  +	      readShpEntity (shp_in, current_row, &shplen, &minx, &miny, &maxx,
         3747  +			     &maxy);
         3748  +	  if (ret < 0)
         3749  +	    {
         3750  +		/* found a DBF deleted record */
         3751  +		current_row++;
         3752  +		continue;
         3753  +	    }
         3754  +	  if (!ret)
         3755  +	    {
         3756  +		if (!(shp_in->LastError))	/* normal SHP EOF */
         3757  +		    break;
         3758  +		fprintf (stderr, "\t\tERROR: %s\n", shp_in->LastError);
         3759  +		goto stop;
         3760  +	    }
         3761  +	  if (validate || force)
         3762  +	    {
         3763  +		/* attempting to rearrange geometries */
         3764  +		unsigned char *bufshp;
         3765  +		int buflen;
         3766  +		int nullshape;
         3767  +		gaiaGeomCollPtr geom =
         3768  +		    do_parse_geometry (shp_in->BufShp, shplen,
         3769  +				       shp_in->EffectiveDims,
         3770  +				       shp_in->EffectiveType, &nullshape);
         3771  +		if (nullshape)
         3772  +		    goto default_null;
         3773  +		if (geom == NULL)
         3774  +		  {
         3775  +		      fprintf (stderr,
         3776  +			       "\t\tinput row #%d: unexpected NULL geometry\n",
         3777  +			       current_row);
         3778  +		      *repair_failed = 1;
         3779  +		      goto default_null;
         3780  +		  }
         3781  +
         3782  +		if (validate)
         3783  +		  {
         3784  +		      /* testing for invalid Geometries */
         3785  +		      int is_invalid = 0;
         3786  +		      if (esri)
         3787  +			{
         3788  +			    /* checking invalid geometries in ESRI mode */
         3789  +			    gaiaGeomCollPtr detail;
         3790  +			    detail = gaiaIsValidDetailEx_r (cache, geom, 1);
         3791  +			    if (detail == NULL)
         3792  +			      {
         3793  +				  /* extra checks */
         3794  +				  int extra = 0;
         3795  +				  if (gaiaIsToxic_r (cache, geom))
         3796  +				      extra = 1;
         3797  +				  if (gaiaIsNotClosedGeomColl_r (cache, geom))
         3798  +				      extra = 1;
         3799  +				  if (extra)
         3800  +				      is_invalid = 1;
         3801  +			      }
         3802  +			    else
         3803  +			      {
         3804  +				  is_invalid = 1;
         3805  +				  gaiaFreeGeomColl (detail);
         3806  +			      }
         3807  +			}
         3808  +		      else
         3809  +			{
         3810  +			    /* checking invalid geometries in ISO/OGC mode */
         3811  +			    if (gaiaIsValid_r (cache, geom) != 1)
         3812  +				is_invalid = 1;
         3813  +			}
         3814  +
         3815  +#ifdef ENABLE_RTTOPO		/* only if RTTOPO is enabled */
         3816  +		      if (is_invalid)
         3817  +			{
         3818  +			    /* attempting to repair an invalid Geometry */
         3819  +			    char *expected;
         3820  +			    char *actual;
         3821  +			    gaiaGeomCollPtr discarded;
         3822  +			    gaiaGeomCollPtr result =
         3823  +				gaiaMakeValid (cache, geom);
         3824  +			    if (result == NULL)
         3825  +			      {
         3826  +				  fprintf (stderr,
         3827  +					   "\t\tinput row #%d: unexpected MakeValid failure\n",
         3828  +					   current_row);
         3829  +				  gaiaFreeGeomColl (geom);
         3830  +				  *repair_failed = 1;
         3831  +				  goto default_null;
         3832  +			      }
         3833  +			    discarded = gaiaMakeValidDiscarded (cache, geom);
         3834  +			    if (discarded != NULL)
         3835  +			      {
         3836  +				  fprintf (stderr,
         3837  +					   "\t\tinput row #%d: MakeValid reports discarded elements\n",
         3838  +					   current_row);
         3839  +				  gaiaFreeGeomColl (result);
         3840  +				  gaiaFreeGeomColl (discarded);
         3841  +				  gaiaFreeGeomColl (geom);
         3842  +				  *repair_failed = 1;
         3843  +				  goto default_null;
         3844  +			      }
         3845  +			    if (!check_geometry_verbose
         3846  +				(result, shp_in->Shape, &expected, &actual))
         3847  +			      {
         3848  +				  fprintf (stderr,
         3849  +					   "\t\tinput row #%d: MakeValid returned an invalid SHAPE (expected %s, got %s)\n",
         3850  +					   current_row, expected, actual);
         3851  +				  free (expected);
         3852  +				  free (actual);
         3853  +				  gaiaFreeGeomColl (result);
         3854  +				  gaiaFreeGeomColl (geom);
         3855  +				  *repair_failed = 1;
         3856  +				  goto default_null;
         3857  +			      }
         3858  +			    gaiaFreeGeomColl (geom);
         3859  +			    geom = result;
         3860  +			}
         3861  +#endif /* end RTTOPO conditional */
         3862  +
         3863  +		      if (!do_export_geometry
         3864  +			  (geom, &bufshp, &buflen, shp_in->Shape,
         3865  +			   current_row, shp_out->EffectiveDims))
         3866  +			{
         3867  +			    gaiaFreeGeomColl (geom);
         3868  +			    goto stop;
         3869  +			}
         3870  +		      gaiaFreeGeomColl (geom);
         3871  +		  }
         3872  +		else
         3873  +		  {
         3874  +		      if (!do_export_geometry
         3875  +			  (geom, &bufshp, &buflen, shp_in->Shape,
         3876  +			   current_row, shp_out->EffectiveDims))
         3877  +			{
         3878  +			    gaiaFreeGeomColl (geom);
         3879  +			    goto stop;
         3880  +			}
         3881  +		      gaiaFreeGeomColl (geom);
         3882  +		  }
         3883  +		goto ok_geom;
         3884  +
         3885  +	      default_null:
         3886  +		/* exporting a NULL shape */
         3887  +		do_export_geometry
         3888  +		    (NULL, &bufshp, &buflen, shp_in->Shape,
         3889  +		     current_row, shp_out->EffectiveDims);
         3890  +
         3891  +	      ok_geom:
         3892  +		ret = writeShpEntity
         3893  +		    (shp_out, bufshp, buflen, shp_in->BufDbf,
         3894  +		     shp_in->DbfReclen);
         3895  +		free (bufshp);
         3896  +		if (!ret)
         3897  +		    goto stop;
         3898  +	    }
         3899  +	  else
         3900  +	    {
         3901  +		/* passing geometries exactly as they were */
         3902  +		if (!writeShpEntity
         3903  +		    (shp_out, shp_in->BufShp, shplen, shp_in->BufDbf,
         3904  +		     shp_in->DbfReclen))
         3905  +		    goto stop;
         3906  +	    }
         3907  +	  current_row++;
         3908  +      }
         3909  +    gaiaFlushShpHeaders (shp_out);
         3910  +    freeShapefile (shp_in);
         3911  +    freeShapefile (shp_out);
         3912  +    return 1;
         3913  +
         3914  +  stop:
         3915  +    freeShapefile (shp_in);
         3916  +    freeShapefile (shp_out);
         3917  +    fprintf (stderr,
         3918  +	     "\t\tMalformed shapefile, impossible to repair: quitting\n");
         3919  +    return 0;
         3920  +}
         3921  +
         3922  +static int
         3923  +do_test_shapefile (const void *cache, const char *shp_path, int validate,
         3924  +		   int esri, int *invalid)
         3925  +{
         3926  +/* testing a Shapefile for validity */
         3927  +    int n_invalid;
         3928  +
         3929  +    fprintf (stderr, "\nVerifying %s.shp\n", shp_path);
         3930  +    *invalid = 0;
         3931  +    if (!do_read_shp (cache, shp_path, validate, esri, &n_invalid))
         3932  +	return 0;
         3933  +    if (n_invalid)
         3934  +      {
         3935  +	  fprintf (stderr, "\tfound %d invalidit%s: cleaning required.\n",
         3936  +		   n_invalid, (n_invalid > 1) ? "ies" : "y");
         3937  +	  *invalid = 1;
         3938  +      }
         3939  +    else
         3940  +	fprintf (stderr, "\tfound to be already valid.\n");
         3941  +    return 1;
         3942  +}
         3943  +
         3944  +static int
         3945  +check_extension (const char *file_name)
         3946  +{
         3947  +/* checks the file extension */
         3948  +    const char *mark = NULL;
         3949  +    int len = strlen (file_name);
         3950  +    const char *p = file_name + len - 1;
         3951  +
         3952  +    while (p >= file_name)
         3953  +      {
         3954  +	  if (*p == '.')
         3955  +	      mark = p;
         3956  +	  p--;
         3957  +      }
         3958  +    if (mark == NULL)
         3959  +	return SUFFIX_DISCARD;
         3960  +    if (strcasecmp (mark, ".shp") == 0)
         3961  +	return SUFFIX_SHP;
         3962  +    if (strcasecmp (mark, ".shx") == 0)
         3963  +	return SUFFIX_SHX;
         3964  +    if (strcasecmp (mark, ".dbf") == 0)
         3965  +	return SUFFIX_DBF;
         3966  +    return SUFFIX_DISCARD;
         3967  +}
         3968  +
         3969  +static int
         3970  +do_scan_dir (const void *cache, const char *in_dir, const char *out_dir,
         3971  +	     int *n_shp, int *r_shp, int *x_shp, int validate, int esri,
         3972  +	     int force)
         3973  +{
         3974  +/* scanning a directory and searching for Shapefiles to be checked */
         3975  +    struct shp_entry *p_shp;
         3976  +    struct shp_list *list = alloc_shp_list ();
         3977  +
         3978  +#if defined(_WIN32) && !defined(__MINGW32__)
         3979  +/* Visual Studio .NET */
         3980  +    struct _finddata_t c_file;
         3981  +    intptr_t hFile;
         3982  +    char *path;
         3983  +    char *name;
         3984  +    int len;
         3985  +    int ret;
         3986  +    if (_chdir (in_dir) < 0)
         3987  +	goto error;
         3988  +    if ((hFile = _findfirst ("*.shp", &c_file)) == -1L)
         3989  +	;
         3990  +    else
         3991  +      {
         3992  +	  while (1)
         3993  +	    {
         3994  +		if ((c_file.attrib & _A_RDONLY) == _A_RDONLY
         3995  +		    || (c_file.attrib & _A_NORMAL) == _A_NORMAL)
         3996  +		  {
         3997  +		      name = sqlite3_mprintf ("%s", c_file.name);
         3998  +		      len = strlen (name);
         3999  +		      name[len - 4] = '\0';
         4000  +		      path = sqlite3_mprintf ("%s/%s", in_dir, name);
         4001  +		      do_add_shapefile (list, path, name, SUFFIX_SHP);
         4002  +		  }
         4003  +		if (_findnext (hFile, &c_file) != 0)
         4004  +		    break;
         4005  +	    }
         4006  +	  _findclose (hFile);
         4007  +	  if ((hFile = _findfirst ("*.shx", &c_file)) == -1L)
         4008  +	      ;
         4009  +	  else
         4010  +	    {
         4011  +		while (1)
         4012  +		  {
         4013  +		      if ((c_file.attrib & _A_RDONLY) == _A_RDONLY
         4014  +			  || (c_file.attrib & _A_NORMAL) == _A_NORMAL)
         4015  +			{
         4016  +			    name = sqlite3_mprintf ("%s", c_file.name);
         4017  +			    len = strlen (name);
         4018  +			    name[len - 4] = '\0';
         4019  +			    path = sqlite3_mprintf ("%s/%s", in_dir, name);
         4020  +			    do_add_shapefile (list, path, name, SUFFIX_SHX);
         4021  +			}
         4022  +		      if (_findnext (hFile, &c_file) != 0)
         4023  +			  break;
         4024  +		  }
         4025  +		_findclose (hFile);
         4026  +		if ((hFile = _findfirst ("*.dbf", &c_file)) == -1L)
         4027  +		    ;
         4028  +		else
         4029  +		  {
         4030  +		      while (1)
         4031  +			{
         4032  +			    if ((c_file.attrib & _A_RDONLY) == _A_RDONLY
         4033  +				|| (c_file.attrib & _A_NORMAL) == _A_NORMAL)
         4034  +			      {
         4035  +				  name = sqlite3_mprintf ("%s", c_file.name);
         4036  +				  len = strlen (name);
         4037  +				  name[len - 4] = '\0';
         4038  +				  path =
         4039  +				      sqlite3_mprintf ("%s/%s", in_dir, name);
         4040  +				  do_add_shapefile (list, path, name,
         4041  +						    SUFFIX_DBF);
         4042  +			      }
         4043  +			    if (_findnext (hFile, &c_file) != 0)
         4044  +				break;
         4045  +			}
         4046  +		      _findclose (hFile);
         4047  +		  }
         4048  +	    }
         4049  +      }
         4050  +#else
         4051  +/* not Visual Studio .NET */
         4052  +    char *path;
         4053  +    char *name;
         4054  +    struct dirent *entry;
         4055  +    int len;
         4056  +    int suffix;
         4057  +    DIR *dir = opendir (in_dir);
         4058  +    if (!dir)
         4059  +	goto error;
         4060  +    while (1)
         4061  +      {
         4062  +	  /* extracting the SHP candidates */
         4063  +	  entry = readdir (dir);
         4064  +	  if (!entry)
         4065  +	      break;
         4066  +	  suffix = check_extension (entry->d_name);
         4067  +	  if (suffix == SUFFIX_DISCARD)
         4068  +	      continue;
         4069  +	  path = sqlite3_mprintf ("%s/%s", in_dir, entry->d_name);
         4070  +	  len = strlen (path);
         4071  +	  path[len - 4] = '\0';
         4072  +	  name = sqlite3_mprintf ("%s", entry->d_name);
         4073  +	  len = strlen (name);
         4074  +	  name[len - 4] = '\0';
         4075  +	  do_add_shapefile (list, path, name, suffix);
         4076  +      }
         4077  +    closedir (dir);
         4078  +#endif
         4079  +
         4080  +    p_shp = list->first;
         4081  +    while (p_shp != NULL)
         4082  +      {
         4083  +	  if (test_valid_shp (p_shp))
         4084  +	    {
         4085  +		int invalid;
         4086  +		if (!do_test_shapefile
         4087  +		    (cache, p_shp->base_name, validate, esri, &invalid))
         4088  +		    goto error;
         4089  +		*n_shp += 1;
         4090  +		if (invalid)
         4091  +		    *x_shp += 1;
         4092  +		if ((invalid || force) && out_dir != NULL)
         4093  +		  {
         4094  +		      /* attempting to repair */
         4095  +		      int repair_failed;
         4096  +		      int ret;
         4097  +		      char *out_path = sqlite3_mprintf ("%s/%s", out_dir,
         4098  +							p_shp->file_name);
         4099  +		      fprintf (stderr, "\tAttempting to repair: %s.shp\n",
         4100  +			       out_path);
         4101  +		      ret =
         4102  +			  do_repair_shapefile (cache, p_shp->base_name,
         4103  +					       out_path, validate, esri, force,
         4104  +					       &repair_failed);
         4105  +		      sqlite3_free (out_path);
         4106  +		      if (!ret)
         4107  +			  goto error;
         4108  +		      if (repair_failed)
         4109  +			{
         4110  +			    do_clen_files (out_dir, p_shp->base_name);
         4111  +			    fprintf (stderr,
         4112  +				     "\tFAILURE: automatic repair is impossible, manual repair required.\n");
         4113  +			}
         4114  +		      else
         4115  +			{
         4116  +			    *r_shp += 1;
         4117  +			    fprintf (stderr, "\tOK, successfully repaired.\n");
         4118  +			}
         4119  +		  }
         4120  +	    }
         4121  +	  p_shp = p_shp->next;
         4122  +      }
         4123  +
         4124  +    free_shp_list (list);
         4125  +    return 1;
         4126  +
         4127  +  error:
         4128  +    free_shp_list (list);
         4129  +    fprintf (stderr, "Unable to access \"%s\"\n", in_dir);
         4130  +    return 0;
         4131  +}
         4132  +
         4133  +static void
         4134  +do_version ()
         4135  +{
         4136  +/* printing version infos */
         4137  +	fprintf( stderr, "\nVersion infos\n");
         4138  +	fprintf( stderr, "===========================================\n");
         4139  +    fprintf (stderr, "shp_sanitize : %s\n", VERSION);
         4140  +	fprintf (stderr, "target CPU ..: %s\n", spatialite_target_cpu ());
         4141  +    fprintf (stderr, "libspatialite: %s\n", spatialite_version ());
         4142  +    fprintf (stderr, "libsqlite3 ..: %s\n", sqlite3_libversion ());
         4143  +    fprintf (stderr, "\n");
         4144  +}
         4145  +
         4146  +static void
         4147  +do_help ()
         4148  +{
         4149  +/* printing the argument list */
         4150  +    fprintf (stderr, "\n\nusage: shp_sanitize ARGLIST\n");
         4151  +    fprintf (stderr,
         4152  +	     "=================================================================\n");
         4153  +    fprintf (stderr,
         4154  +	     "-h or --help                      print this help message\n");
         4155  +    fprintf (stderr, "-v or --version                   print version infos\n");
         4156  +    fprintf (stderr,
         4157  +	     "-idir or --in-dir   dir-path      directory expected to contain\n"
         4158  +	     "                                  all SHP to be checked\n");
         4159  +    fprintf (stderr,
         4160  +	     "-odir or --out-dir  dir-path      <optional> directory where to\n"
         4161  +	     "                                  store all repaired SHPs\n\n");
         4162  +    fprintf (stderr,
         4163  +	     "======================= optional args ===========================\n"
         4164  +	     "-geom or --invalid-geoms          checks for invalid Geometries\n"
         4165  +	     "-esri or --esri-flag              tolerates ESRI-like inner holes\n"
         4166  +	     "-force or --force-repair          unconditionally repair\n\n");
         4167  +}
         4168  +
         4169  +int
         4170  +main (int argc, char *argv[])
         4171  +{
         4172  +/* the MAIN function simply perform arguments checking */
         4173  +    int i;
         4174  +    int error = 0;
         4175  +    int next_arg = ARG_NONE;
         4176  +    char *in_dir = NULL;
         4177  +    char *out_dir = NULL;
         4178  +    int validate = 0;
         4179  +    int esri = 0;
         4180  +    int force = 0;
         4181  +    int n_shp = 0;
         4182  +    int r_shp = 0;
         4183  +    int x_shp = 0;
         4184  +    const void *cache;
         4185  +
         4186  +    for (i = 1; i < argc; i++)
         4187  +      {
         4188  +	  /* parsing the invocation arguments */
         4189  +	  if (next_arg != ARG_NONE)
         4190  +	    {
         4191  +		switch (next_arg)
         4192  +		  {
         4193  +		  case ARG_IN_DIR:
         4194  +		      in_dir = argv[i];
         4195  +		      break;
         4196  +		  case ARG_OUT_DIR:
         4197  +		      out_dir = argv[i];
         4198  +		      break;
         4199  +		  };
         4200  +		next_arg = ARG_NONE;
         4201  +		continue;
         4202  +	    }
         4203  +	  if (strcasecmp (argv[i], "--help") == 0
         4204  +	      || strcmp (argv[i], "-h") == 0)
         4205  +	    {
         4206  +		do_help ();
         4207  +		return -1;
         4208  +	    }
         4209  +	  if (strcasecmp (argv[i], "--version") == 0
         4210  +	      || strcmp (argv[i], "-v") == 0)
         4211  +	    {
         4212  +		do_version ();
         4213  +		return -1;
         4214  +	    }
         4215  +	  if (strcasecmp (argv[i], "-idir") == 0
         4216  +	      || strcasecmp (argv[i], "--in-dir") == 0)
         4217  +	    {
         4218  +		next_arg = ARG_IN_DIR;
         4219  +		continue;
         4220  +	    }
         4221  +	  if (strcasecmp (argv[i], "-odir") == 0
         4222  +	      || strcasecmp (argv[i], "--out-dir") == 0)
         4223  +	    {
         4224  +		next_arg = ARG_OUT_DIR;
         4225  +		continue;
         4226  +	    }
         4227  +	  if (strcasecmp (argv[i], "-geom") == 0
         4228  +	      || strcasecmp (argv[i], "--invalid-geoms") == 0)
         4229  +	    {
         4230  +		validate = 1;
         4231  +		continue;
         4232  +	    }
         4233  +	  if (strcasecmp (argv[i], "-esri") == 0
         4234  +	      || strcasecmp (argv[i], "--esri-flag") == 0)
         4235  +	    {
         4236  +		esri = 1;
         4237  +		continue;
         4238  +	    }
         4239  +	  if (strcasecmp (argv[i], "-force") == 0
         4240  +	      || strcasecmp (argv[i], "--force-repair") == 0)
         4241  +	    {
         4242  +		force = 1;
         4243  +		continue;
         4244  +	    }
         4245  +	  fprintf (stderr, "unknown argument: %s\n", argv[i]);
         4246  +	  error = 1;
         4247  +      }
         4248  +    if (error)
         4249  +      {
         4250  +	  do_help ();
         4251  +	  return -1;
         4252  +      }
         4253  +/* checking the arguments */
         4254  +    if (!in_dir)
         4255  +      {
         4256  +	  fprintf (stderr, "did you forget setting the --in-dir argument ?\n");
         4257  +	  error = 1;
         4258  +      }
         4259  +    if (error)
         4260  +      {
         4261  +	  do_help ();
         4262  +	  return -1;
         4263  +      }
         4264  +
         4265  +#ifndef ENABLE_RTTOPO		/* only if RTTOPO is disabled */
         4266  +    if (validate)
         4267  +      {
         4268  +	  validate = 0;
         4269  +	  fprintf (stderr,
         4270  +		   "the --validate-geoms option will be ignored because\n"
         4271  +		   "this copy of \"shp_sanitize\" was built by disabling RTTOPO support.\n\n");
         4272  +      }
         4273  +#endif /* end RTTOPO conditional */
         4274  +
         4275  +    if (out_dir != NULL)
         4276  +      {
         4277  +#ifdef _WIN32
         4278  +	  if (_mkdir (out_dir) != 0)
         4279  +#else
         4280  +	  if (mkdir (out_dir, 0777) != 0)
         4281  +#endif
         4282  +	    {
         4283  +		fprintf (stderr,
         4284  +			 "ERROR: unable to create the output directory\n%s\n%s\n\n",
         4285  +			 out_dir, strerror (errno));
         4286  +		return -1;
         4287  +	    }
         4288  +      }
         4289  +
         4290  +    cache = spatialite_alloc_connection ();
         4291  +    spatialite_set_silent_mode (cache);
         4292  +    fprintf (stderr, "\nInput dir: %s\n", in_dir);
         4293  +    if (out_dir != NULL)
         4294  +      {
         4295  +	  fprintf (stderr, "Output dir: %s\n", out_dir);
         4296  +	  if (force)
         4297  +	      fprintf (stderr, "Unconditionally repairing all Shapefiles\n");
         4298  +      }
         4299  +    else
         4300  +	fprintf (stderr, "Only a diagnostic report will be reported\n");
         4301  +    if (validate)
         4302  +      {
         4303  +	  fprintf (stderr, "Checking for invalid geometries (%s mode)\n",
         4304  +		   esri ? "ESRI" : "ISO/OGC");
         4305  +      }
         4306  +
         4307  +    if (!do_scan_dir
         4308  +	(cache, in_dir, out_dir, &n_shp, &r_shp, &x_shp, validate, esri, force))
         4309  +      {
         4310  +	  fprintf (stderr,
         4311  +		   "\n... quitting ... some unexpected error occurred\n");
         4312  +	  spatialite_cleanup_ex (cache);
         4313  +	  return -1;
         4314  +      }
         4315  +
         4316  +    fprintf (stderr, "\n===========================================\n");
         4317  +    fprintf (stderr, "%d Shapefil%s ha%s been inspected.\n", n_shp,
         4318  +	     (n_shp > 1) ? "es" : "e", (n_shp > 1) ? "ve" : "s");
         4319  +    fprintf (stderr, "%d malformed Shapefil%s ha%s been identified.\n", x_shp,
         4320  +	     (x_shp > 1) ? "es" : "e", (x_shp > 1) ? "ve" : "s");
         4321  +    fprintf (stderr, "%d Shapefil%s ha%s been repaired.\n\n", r_shp,
         4322  +	     (r_shp > 1) ? "es" : "e", (r_shp > 1) ? "ve" : "s");
         4323  +
         4324  +    spatialite_cleanup_ex (cache);
         4325  +    return 0;
         4326  +}

Changes to spatialite_convert.c.

    29     29   #include <sys/types.h>
    30     30   #endif
    31     31   
    32     32   #include <stdlib.h>
    33     33   #include <stdio.h>
    34     34   #include <string.h>
    35     35   
           36  +#if defined(_WIN32) && !defined(__MINGW32__)
           37  +#include "config-msvc.h"
           38  +#else
    36     39   #include "config.h"
           40  +#endif
    37     41   
    38     42   #ifdef SPATIALITE_AMALGAMATION
    39     43   #include <spatialite/sqlite3.h>
    40     44   #else
    41     45   #include <sqlite3.h>
    42     46   #endif
    43     47   
................................................................................
  6870   6874   	  sqlite3_close (db_handle);
  6871   6875   	  return;
  6872   6876         }
  6873   6877       spatialite_init_ex (db_handle, cache, 0);
  6874   6878       *handle = db_handle;
  6875   6879       return;
  6876   6880   }
         6881  +
         6882  +static void
         6883  +do_version ()
         6884  +{
         6885  +/* printing version infos */
         6886  +	fprintf( stderr, "\nVersion infos\n");
         6887  +	fprintf( stderr, "===========================================\n");
         6888  +    fprintf (stderr, "spatialite_convert: %s\n", VERSION);
         6889  +	fprintf (stderr, "target CPU .......: %s\n", spatialite_target_cpu ());
         6890  +    fprintf (stderr, "libspatialite ....: %s\n", spatialite_version ());
         6891  +    fprintf (stderr, "libsqlite3 .......: %s\n", sqlite3_libversion ());
         6892  +    fprintf (stderr, "\n");
         6893  +}
  6877   6894   
  6878   6895   static void
  6879   6896   do_help ()
  6880   6897   {
  6881   6898   /* printing the argument list */
  6882   6899       fprintf (stderr, "\n\nusage: spatialite_convert ARGLIST\n");
  6883   6900       fprintf (stderr,
  6884   6901   	     "==============================================================\n");
  6885   6902       fprintf (stderr,
  6886   6903   	     "-h or --help                    print this help message\n");
         6904  +    fprintf (stderr, "-v or --version                 print version infos\n");
  6887   6905       fprintf (stderr,
  6888   6906   	     "-d or --db-path  pathname       the SpatiaLite DB path\n\n");
  6889   6907       fprintf (stderr,
  6890         -	     "-v or --version    num          target Version (2, 3, 4)\n");
         6908  +	     "-tv or --target-version  num    target Version (2, 3, 4)\n");
  6891   6909   }
  6892   6910   
  6893   6911   int
  6894   6912   main (int argc, char *argv[])
  6895   6913   {
  6896   6914   /* the MAIN function simply perform arguments checking */
  6897   6915       sqlite3 *handle;
................................................................................
  6924   6942   		continue;
  6925   6943   	    }
  6926   6944   	  if (strcasecmp (argv[i], "--help") == 0
  6927   6945   	      || strcmp (argv[i], "-h") == 0)
  6928   6946   	    {
  6929   6947   		do_help ();
  6930   6948   		return -1;
         6949  +	    }
         6950  +	  if (strcasecmp (argv[i], "--version") == 0
         6951  +	      || strcmp (argv[i], "-v") == 0)
         6952  +	    {
         6953  +		do_version ();
         6954  +		return -1;
  6931   6955   	    }
  6932   6956   	  if (strcmp (argv[i], "-d") == 0)
  6933   6957   	    {
  6934   6958   		next_arg = ARG_DB_PATH;
  6935   6959   		continue;
  6936   6960   	    }
  6937   6961   	  if (strcasecmp (argv[i], "--db-path") == 0)
  6938   6962   	    {
  6939   6963   		next_arg = ARG_DB_PATH;
  6940   6964   		continue;
  6941   6965   	    }
  6942         -	  if (strcasecmp (argv[i], "--version") == 0
  6943         -	      || strcmp (argv[i], "-v") == 0)
         6966  +	  if (strcasecmp (argv[i], "--target-version") == 0
         6967  +	      || strcmp (argv[i], "-tv") == 0)
  6944   6968   	    {
  6945   6969   		next_arg = ARG_VERSION;
  6946   6970   		continue;
  6947   6971   	    }
  6948   6972   	  fprintf (stderr, "unknown argument: %s\n", argv[i]);
  6949   6973   	  error = 1;
  6950   6974         }

Added spatialite_dem.c.

            1  +/*
            2  +/ spatialite_dem
            3  +/
            4  +/ a tool for setting Z coordinates from XYZ files
            5  +/
            6  +/ version 1.0, 2017-09-14
            7  +/
            8  +/ Author: Mark Johnson, Berlin Germany mj10777@googlemail.com
            9  +/
           10  +/ Copyright (C) 2017  Alessandro Furieri
           11  +/
           12  +/    This program is free software: you can redistribute it and/or modify
           13  +/    it under the terms of the GNU General Public License as published by
           14  +/    the Free Software Foundation, either version 3 of the License, or
           15  +/    (at your option) any later version.
           16  +/
           17  +/    This program is distributed in the hope that it will be useful,
           18  +/    but WITHOUT ANY WARRANTY; without even the implied warranty of
           19  +/    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
           20  +/    GNU General Public License for more details.
           21  +/
           22  +/    You should have received a copy of the GNU General Public License
           23  +/    along with this program.  If not, see <http://www.gnu.source_geom/licenses/>.
           24  +/
           25  +*/
           26  +// -- -- ---------------------------------- --
           27  +// astyle spatialite_dem.c
           28  +// valgrind --track-origins=yes --leak-check=full --show-leak-kinds=all --log-file=valgrind.spatialite_dem.utm_fetchz.txt ./spatialite_dem  -fetchz_xy  24747.115253 20725.147344
           29  +// -- -- ---------------------------------- --
           30  +#if defined(_WIN32) && !defined(__MINGW32__)
           31  +/* MSVC strictly requires this include [off_t] */
           32  +#include <sys/types.h>
           33  +#endif
           34  +
           35  +#include <unistd.h>
           36  +#include <stdlib.h>
           37  +#include <stdio.h>
           38  +#include <string.h>
           39  +#include <sys/time.h>
           40  +#include <time.h>
           41  +
           42  +#if defined(_WIN32) && !defined(__MINGW32__)
           43  +#include "config-msvc.h"
           44  +#include <io.h>
           45  +#include <direct.h>
           46  +#else
           47  +#include "config.h"
           48  +#include <dirent.h>
           49  +#endif
           50  +
           51  +#ifdef SPATIALITE_AMALGAMATION
           52  +#include <spatialite/sqlite3.h>
           53  +#else
           54  +#include <sqlite3.h>
           55  +#endif
           56  +
           57  +#include <spatialite/gaiaaux.h>
           58  +#include <spatialite/gaiageo.h>
           59  +#include <spatialite.h>
           60  +
           61  +#ifdef _WIN32
           62  +#define strcasecmp	_stricmp
           63  +#endif /* not WIN32 */
           64  +// -- -- ---------------------------------- --
           65  +#define ARG_NONE		0
           66  +#define ARG_DB_PATH		1
           67  +#define ARG_TABLE		2
           68  +#define ARG_COL		3
           69  +#define ARG_DEM_PATH		4
           70  +#define ARG_TABLE_DEM		5
           71  +#define ARG_COL_DEM		6
           72  +#define ARG_RESOLUTION_DEM		7
           73  +#define ARG_COPY_M		8
           74  +#define ARG_COMMAND_TYPE		9
           75  +#define ARG_FETCHZ_X		10
           76  +#define ARG_FETCHZ_Y		11
           77  +#define ARG_FETCHZ_XY		12
           78  +#define ARG_DEFAULT_SRID		13
           79  +// -- -- ---------------------------------- --
           80  +#define CMD_DEM_SNIFF		100
           81  +#define CMD_DEM_FETCHZ		101
           82  +#define CMD_DEM_CREATE		102
           83  +#define CMD_DEM_IMPORT_XYZ		103
           84  +#define CMD_DEM_UPDATEZ		104
           85  +// -- -- ---------------------------------- --
           86  +#define CONF_TYPE_DEM		1
           87  +#define CONF_TYPE_SOURCE	2
           88  +// -- -- ---------------------------------- --
           89  +// Definitions used for dem-conf
           90  +// -- -- ---------------------------------- --
           91  +#define MAXBUF 1024
           92  +#define DELIM "="
           93  +#ifdef _WIN32
           94  +#define LENGTHNL 2
           95  +#else
           96  +#define LENGTHNL 1
           97  +#endif /* not WIN32 */
           98  +// -- -- ---------------------------------- --
           99  +// Output of time elapse
          100  +// min      = (int)(time_diff.tv_sec/60);
          101  +// secs    = (int)(time_diff.tv_sec-(min*60));
          102  +// msecs = (int)(time_diff.tv_usec/1000);
          103  +// printf("%d mins %02d.%03d secs",min,sec,msecs);
          104  +// -- -- ---------------------------------- --
          105  +int timeval_subtract (struct timeval *time_diff, struct timeval *time_end, struct timeval *time_start, char **time_message)
          106  +{
          107  + int diff=0;
          108  + int days=0;
          109  + int hours=0;
          110  + int mins=0;
          111  + int secs=0;
          112  + int msecs=0;
          113  +// Perform the carry for the later subtraction by updating time_start.
          114  + if (time_end->tv_usec < time_start->tv_usec)
          115  + {
          116  +  int nsec = (time_start->tv_usec - time_end->tv_usec) / 1000000 + 1;
          117  +  time_start->tv_usec -= 1000000 * nsec;
          118  +  time_start->tv_sec += nsec;
          119  + }
          120  + if (time_end->tv_usec - time_start->tv_usec > 1000000)
          121  + {
          122  +  int nsec = (time_end->tv_usec - time_start->tv_usec) / 1000000;
          123  +  time_start->tv_usec += 1000000 * nsec;
          124  +  time_start->tv_sec -= nsec;
          125  + }
          126  +// Compute the time remaining to wait. tv_usec is certainly positive.
          127  + time_diff->tv_sec = time_end->tv_sec - time_start->tv_sec;
          128  + time_diff->tv_usec = time_end->tv_usec - time_start->tv_usec;
          129  +// -- -- ---------------------------------- --
          130  + diff = (int)time_diff->tv_sec;
          131  + if (diff > 86400 )
          132  + {// sec per day
          133  +  days = diff / 86400;
          134  +  diff = diff-(days*86400);
          135  + }
          136  + if (diff > 3660 )
          137  + {// sec per hour
          138  +  hours = diff / 3660;
          139  +  diff = diff -(hours*3660);
          140  + }
          141  + if (diff > 60 )
          142  + {
          143  +  mins = diff / 60;
          144  + }
          145  + secs = diff - (mins * 60);
          146  + msecs = (int)(time_diff->tv_usec/1000);
          147  +// -- -- ---------------------------------- --
          148  + if (*time_message)
          149  + {
          150  +  sqlite3_free(*time_message);
          151  +  *time_message = NULL;
          152  + }
          153  + if ( days > 0)
          154  + {
          155  +  *time_message = sqlite3_mprintf(">> time needed: %2 days %02d hours %02d mins %02d secs %02d milli-secs", days, hours, mins, secs,msecs);
          156  + } else if ( hours > 0)
          157  + {
          158  +  *time_message = sqlite3_mprintf(">> time needed: %02d hours %02d mins %02d secs %02d milli-secs", hours, mins, secs,msecs);
          159  + } else if ( mins > 0)
          160  + {
          161  +  *time_message = sqlite3_mprintf(">> time needed: %02d mins %02d secs %02d milli-secs", mins, secs,msecs);
          162  + }
          163  + else if (secs > 0 )
          164  + {
          165  +  *time_message = sqlite3_mprintf(">> time needed: %02d secs %02d milli-secs", secs,msecs);
          166  + }
          167  + else
          168  + {
          169  +  *time_message = sqlite3_mprintf(">> time needed: %02d milli-secs",msecs);
          170  + }
          171  +// -- -- ---------------------------------- --
          172  +// Return 1 if time_diff is negative.
          173  + return time_end->tv_sec < time_start->tv_sec;
          174  +// -- -- ---------------------------------- --
          175  +}
          176  +// -- -- ---------------------------------- --
          177  +// dem-conf structure
          178  +// -- -- ---------------------------------- --
          179  +struct config_dem
          180  +{
          181  + char dem_path[MAXBUF];
          182  + char dem_table[MAXBUF];
          183  + char dem_geometry[MAXBUF];
          184  + double dem_extent_minx;
          185  + double dem_extent_miny;
          186  + double dem_extent_maxx;
          187  + double dem_extent_maxy;
          188  + double dem_resolution;
          189  + int dem_srid;
          190  + unsigned int dem_rows_count;
          191  + int default_srid;
          192  +// Not to be used for conf_file [internal use only]
          193  + char *schema;
          194  + double fetchz_x;
          195  + double fetchz_y;
          196  + double dem_z;
          197  + double dem_m;
          198  + int has_z;
          199  + int has_m;
          200  + int has_spatial_index;
          201  + int is_spatial_table;
          202  + int config_type; // dem=0 ; source=1;
          203  + unsigned int id_rowid; // For debugging
          204  + unsigned int count_points; // For debugging
          205  + unsigned int count_points_nr; // For debugging
          206  +};
          207  +// -- -- ---------------------------------- --
          208  +// Reading dem-conf
          209  +// Environment var 'SPATIALITE_DEM'
          210  +// - with path to dem-conf
          211  +// ->  must be created by
          212  +//  (or using same syntax as)  write_demconfig
          213  +// -- -- ---------------------------------- --
          214  +// if not found, the tool will look for a
          215  +// - 'spatialite_dem.conf' file in the active directory
          216  +// if not found, default values will be used
          217  +// -- -- ---------------------------------- --
          218  +// - any line not starting
          219  +// -> with a '#' [comment]
          220  +// -> not containing a '=' will be ignored
          221  +// - any other line will look for specific
          222  +//   keywords before the '='
          223  +// -> unknown keywords will be ignored
          224  +// -- -- ---------------------------------- --
          225  +struct config_dem get_demconfig(char *conf_filename, int verbose)
          226  +{
          227  + struct config_dem config_struct;
          228  +// -- -- ---------------------------------- --
          229  +// Setting default values
          230  +// -- -- ---------------------------------- --
          231  + strcpy(config_struct.dem_path,"");
          232  + strcpy(config_struct.dem_table,"");
          233  + strcpy(config_struct.dem_geometry,"");
          234  + config_struct.dem_extent_minx=0.0;
          235  + config_struct.dem_extent_miny=0.0;
          236  + config_struct.dem_extent_maxx=0.0;
          237  + config_struct.dem_extent_maxy=0.0;
          238  + config_struct.dem_resolution=0.0;
          239  + config_struct.dem_srid=-2; // invalid
          240  + config_struct.default_srid=-2; // invalid
          241  + config_struct.dem_rows_count=0;
          242  +// -- -- ---------------------------------- --
          243  +// Not to be used for conf_file [internal use only]
          244  +// -- -- ---------------------------------- --
          245  + config_struct.fetchz_x=0.0;
          246  + config_struct.fetchz_y=0.0;
          247  + config_struct.dem_z=0.0;
          248  + config_struct.dem_m=0.0;
          249  + config_struct.has_z=0;
          250  + config_struct.has_m=0;
          251  + config_struct.has_spatial_index=0;
          252  + config_struct.is_spatial_table=0;
          253  + config_struct.schema=NULL;
          254  + config_struct.config_type=-1;
          255  + config_struct.id_rowid=0; // For debugging
          256  + config_struct.count_points=0; // For debugging
          257  + config_struct.count_points_nr=0; // For debugging
          258  +// -- -- ---------------------------------- --
          259  + if ((conf_filename) && (strlen(conf_filename) > 0) )
          260  + {
          261  +  FILE *conf_file = fopen(conf_filename, "r");
          262  +  if (conf_file != NULL)
          263  +  {
          264  +   char line[MAXBUF];
          265  +   while(fgets(line, sizeof(line), conf_file) != NULL)
          266  +   {
          267  +    char *conf_parm=NULL;
          268  +    char *conf_value=NULL;
          269  +    conf_parm=(char *)line;
          270  +    conf_value = strstr((char *)line,DELIM);
          271  +    // Skip any comments (#) lines that may also contain a '='
          272  +    if ( (conf_parm[0] != '#') && (conf_value) )
          273  +    {
          274  +     conf_parm[(int)(conf_value-conf_parm)]=0;
          275  +     conf_value = conf_value + strlen(DELIM);
          276  +     conf_value[strcspn(conf_value, "\r\n")] = 0;
          277  +     // printf("parm[%s] value[%s]\n",conf_parm,conf_value);
          278  +     if (strcmp(conf_parm,"dem_path") == 0)
          279  +     {
          280  +      strcpy(config_struct.dem_path,conf_value);
          281  +      // printf("%s[%s]\n",conf_parm,config_struct.dem_path);
          282  +     } else if (strcmp(conf_parm,"dem_table") == 0)
          283  +     {
          284  +      strcpy(config_struct.dem_table,conf_value);
          285  +      // printf("%s[%s]\n",conf_parm,config_struct.dem_table);
          286  +     } else if (strcmp(conf_parm,"dem_geometry") == 0)
          287  +     {
          288  +      strcpy(config_struct.dem_geometry,conf_value);
          289  +      // printf("%s[%s]\n",conf_parm,config_struct.dem_geometry);
          290  +     } else if (strcmp(conf_parm,"dem_extent_minx") == 0)
          291  +     {
          292  +      config_struct.dem_extent_minx=atof(conf_value);
          293  +      //printf("%s[%2.7f]\n",conf_parm,config_struct.dem_extent_minx);
          294  +     } else if (strcmp(conf_parm,"dem_extent_miny") == 0)
          295  +     {
          296  +      config_struct.dem_extent_miny=atof(conf_value);
          297  +      //printf("%s[%2.7f]\n",conf_parm,config_struct.dem_extent_miny);
          298  +     } else if (strcmp(conf_parm,"dem_extent_maxx") == 0)
          299  +     {
          300  +      config_struct.dem_extent_maxx=atof(conf_value);
          301  +      //printf("%s[%2.7f]\n",conf_parm,config_struct.dem_extent_maxx);
          302  +     } else if (strcmp(conf_parm,"dem_extent_maxy") == 0)
          303  +     {
          304  +      config_struct.dem_extent_maxy=atof(conf_value);
          305  +      //printf("%s[%2.7f]\n",conf_parm,config_struct.dem_extent_maxy);
          306  +     } else if (strcmp(conf_parm,"dem_resolution") == 0)
          307  +     {
          308  +      config_struct.dem_resolution=atof(conf_value);
          309  +      //printf("%s[%2.7f]\n",conf_parm,config_struct.dem_resolution);
          310  +     } else if (strcmp(conf_parm,"dem_srid") == 0)
          311  +     {
          312  +      config_struct.dem_rows_count=atol(conf_value);
          313  +      // printf("%s[%d]\n",conf_parm,config_struct.dem_rows_count);
          314  +     } else if (strcmp(conf_parm,"dem_srid") == 0)
          315  +     {
          316  +      config_struct.dem_srid=atoi(conf_value);
          317  +      // printf("%s[%d]\n",conf_parm,config_struct.dem_srid);
          318  +     } else if (strcmp(conf_parm,"default_srid") == 0)
          319  +     {
          320  +      config_struct.default_srid=atoi(conf_value);
          321  +      // printf("%s[%d]\n",conf_parm,config_struct.default_srid);
          322  +     }
          323  +    }
          324  +   } // End while
          325  +   fclose(conf_file);
          326  +  } // End if file
          327  +  else
          328  +  {
          329  +   if (strcmp(conf_filename,"spatialite_dem.conf") != 0)
          330  +   {
          331  +    if (verbose)
          332  +    {
          333  +     fprintf(stderr, "-E-> spatialite_dem: not found: conf_filename[%s]\n",conf_filename);
          334  +    }
          335  +   }
          336  +  }
          337  + }
          338  + return config_struct;
          339  +}
          340  +// -- -- ---------------------------------- --
          341  +// writing dem-conf
          342  +// - any line not starting
          343  +// -> with a '#' [comment]
          344  +// -> not containing a '=' will be ignored
          345  +// - any other line will look for specific
          346  +//   keywords before the '='
          347  +// -> unknown keywords will be ignored
          348  +// -- -- ---------------------------------- --
          349  +// Saving dem-conf '-save_conf'
          350  +//  - will save to files set in 'SPATIALITE_DEM'
          351  +// - if empty to the default 'spatialite_dem.conf'
          352  +// -- -- ---------------------------------- --
          353  +int write_demconfig(char *conf_filename, struct config_dem config_struct)
          354  +{
          355  + int rc=0;
          356  + FILE *conf_file = fopen(conf_filename, "w");
          357  + if (conf_file != NULL)
          358  + {
          359  +  fprintf(conf_file, "# -- -- ---------------------------------- --\n");
          360  +  fprintf(conf_file, "# For use with spatialite_dem\n");
          361  +  fprintf(conf_file, "# -- -- ---------------------------------- --\n");
          362  +  fprintf(conf_file, "# export SPATIALITE_DEM=%s\n",conf_filename);
          363  +  fprintf(conf_file, "# -- -- ---------------------------------- --\n");
          364  +  fprintf(conf_file, "# Full path to Spatialite-Database containing a Dem-POINTZ (or POINTZM) Geometry\n");
          365  +  fprintf(conf_file, "dem_path=%s\n", config_struct.dem_path);
          366  +  fprintf(conf_file, "# Table-Name containing a Dem-POINTZ (or POINTZM) Geometry\n");
          367  +  fprintf(conf_file, "dem_table=%s\n", config_struct.dem_table);
          368  +  fprintf(conf_file, "# Geometry-Column containing a Dem-POINTZ (or POINTZM) Geometry\n");
          369  +  fprintf(conf_file, "dem_geometry=%s\n", config_struct.dem_geometry);
          370  +  fprintf(conf_file, "# Srid of the Dem-Geometry\n");
          371  +  fprintf(conf_file, "dem_srid=%d\n", config_struct.dem_srid);
          372  +  fprintf(conf_file, "# -- -- ---------------------------------- --\n");
          373  +  fprintf(conf_file, "# Area around given point to Query Dem-Geometry in units of Dem-Srid\n");
          374  +  fprintf(conf_file, "# -> Rule: a Dem with 1m resolution: min=0.50\n");
          375  +  fprintf(conf_file, "dem_resolution=%2.7f\n", config_struct.dem_resolution);
          376  +  fprintf(conf_file, "# -- -- ---------------------------------- --\n");
          377  +  fprintf(conf_file, "# Default Srid to use for queries against Dem-Geometry [-fetchz_xy, -updatez]\n");
          378  +  fprintf(conf_file, "default_srid=%d\n", config_struct.default_srid);
          379  +  fprintf(conf_file, "# -- -- ---------------------------------- --\n");
          380  +  fprintf(conf_file, "# Count of rows in Dem-Geometry\n");
          381  +  fprintf(conf_file, "dem_rows_count=%u\n", config_struct.dem_rows_count);
          382  +  fprintf(conf_file, "# Min X of Dem-Geometry\n");
          383  +  fprintf(conf_file, "dem_extent_minx=%2.7f\n", config_struct.dem_extent_minx);
          384  +  fprintf(conf_file, "# Max X of Dem-Geometry\n");
          385  +  fprintf(conf_file, "dem_extent_maxx=%2.7f\n", config_struct.dem_extent_maxx);
          386  +  fprintf(conf_file, "# Min Y of Dem-Geometry\n");
          387  +  fprintf(conf_file, "dem_extent_miny=%2.7f\n", config_struct.dem_extent_miny);
          388  +  fprintf(conf_file, "# Max Y of Dem-Geometry\n");
          389  +  fprintf(conf_file, "dem_extent_maxy=%2.7f\n", config_struct.dem_extent_maxy);
          390  +  fprintf(conf_file, "# Width of Dem-Area in Srid-Units\n");
          391  +  fprintf(conf_file, "dem_extent_width=%2.7f\n", (config_struct.dem_extent_maxx-config_struct.dem_extent_minx));
          392  +  fprintf(conf_file, "# Height of Dem-Area in Srid-Units\n");
          393  +  fprintf(conf_file, "dem_extent_height=%2.7f\n", (config_struct.dem_extent_maxy-config_struct.dem_extent_miny));
          394  +  fprintf(conf_file, "# -- -- ---------------------------------- --\n");
          395  +  fclose(conf_file);
          396  +  rc=1;
          397  + }
          398  + return rc;
          399  +}
          400  +// -- -- ---------------------------------- --
          401  +// From a given point, build area around it by 'resolution_dem'
          402  +// - utm 0.999 meters, Solder Berlin 1.0375644 meters
          403  +// (resolution_dem/2) could also be done
          404  +// - but to insure that at least 1 point is returned, left as is
          405  +// The nearest point will always be retrieved, or none at all.
          406  +// -- -- ---------------------------------- --
          407  +static int
          408  +insert_dem_points(sqlite3 *db_handle, struct config_dem *dem_config, double *xx_source, double *yy_source, double *zz_source, int verbose)
          409  +{
          410  + /* checking for 3D geometries - version 4 */
          411  + int ret=0;
          412  + int ret_insert=SQLITE_OK;
          413  + int i=0;
          414  + char *sql_statement = NULL;
          415  + sqlite3_stmt *stmt = NULL;
          416  + char *sql_err = NULL;
          417  + if (zz_source)
          418  + {
          419  +  sql_statement = sqlite3_mprintf("INSERT INTO \"%s\" (point_x,point_y, point_z,\"%s\") "
          420  +                                  "VALUES(?,?,?,MakePointZ(?,?,?,%d)) ",dem_config->dem_table,dem_config->dem_geometry,dem_config->dem_srid);
          421  +  ret = sqlite3_prepare_v2( db_handle, sql_statement, -1, &stmt, NULL );
          422  +  if ( ret == SQLITE_OK )
          423  +  {
          424  +   sqlite3_free(sql_statement);
          425  +   if (sqlite3_exec(db_handle, "BEGIN", NULL, NULL, &sql_err) == SQLITE_OK)
          426  +   {
          427  +    for (i=0; i<(int)(dem_config->count_points); i++)
          428  +    {
          429  +     if (ret_insert != SQLITE_ABORT )
          430  +     {
          431  +      // Note: sqlite3_bind_* index is 1-based, os apposed to sqlite3_column_* that is 0-based.
          432  +      sqlite3_bind_double(stmt, 1, xx_source[i]);
          433  +      sqlite3_bind_double(stmt, 2, yy_source[i]);
          434  +      sqlite3_bind_double(stmt, 3, zz_source[i]);
          435  +      sqlite3_bind_double(stmt, 4, xx_source[i]);
          436  +      sqlite3_bind_double(stmt, 5, yy_source[i]);
          437  +      sqlite3_bind_double(stmt, 6, zz_source[i]);
          438  +      dem_config->count_points_nr=i;
          439  +      ret_insert = sqlite3_step( stmt );
          440  +      if ( ret_insert == SQLITE_DONE || ret_insert == SQLITE_ROW )
          441  +      {
          442  +       ret_insert=SQLITE_OK;
          443  +      }
          444  +      else
          445  +      {
          446  +       ret_insert=SQLITE_ABORT;
          447  +      }
          448  +     }
          449  +     sqlite3_reset(stmt);
          450  +     sqlite3_clear_bindings(stmt);
          451  +     xx_source[i]=0.0;
          452  +     yy_source[i]=0.0;
          453  +     zz_source[i]=0.0;
          454  +    }
          455  +    ret=0;
          456  +    if (ret_insert == SQLITE_ABORT )
          457  +    {
          458  +     if (sqlite3_exec(db_handle, "ROLLBACK", NULL, NULL, &sql_err) == SQLITE_OK)
          459  +     {
          460  +      ret=0;
          461  +     }
          462  +    }
          463  +    else
          464  +    {
          465  +     if (sqlite3_exec(db_handle, "COMMIT", NULL, NULL, &sql_err) == SQLITE_OK)
          466  +     {
          467  +      ret = 1;
          468  +      dem_config->dem_rows_count+=dem_config->count_points;
          469  +      dem_config->count_points=0;
          470  +      dem_config->count_points_nr=0;
          471  +     }
          472  +    }
          473  +   }
          474  +   sqlite3_finalize( stmt );
          475  +   if (sql_err)
          476  +   {
          477  +    sqlite3_free(sql_err);
          478  +   }
          479  +  }
          480  +  else
          481  +  {
          482  +   if (verbose)
          483  +   {
          484  +    fprintf(stderr, "-W-> insert_dem_points: rc=%d sql[%s]\n",ret,sql_statement);
          485  +   }
          486  +   sqlite3_free(sql_statement);
          487  +  }
          488  + }
          489  + return ret;
          490  +}
          491  +// -- -- ---------------------------------- --
          492  +// From a given point, build area around it by 'resolution_dem'
          493  +// - utm 0.999 meters, Solder Berlin 1.0375644 meters
          494  +// (resolution_dem/2) could also be done
          495  +// - but to insure that at least 1 point is returned, left as is
          496  +// The nearest point will always be retrieved, or none at all.
          497  +// -- -- ---------------------------------- --
          498  +static int
          499  +retrieve_dem_points(sqlite3 *db_handle, struct config_dem *dem_config, int count_points, double *xx_source, double *yy_source, double *zz, double *mm, int *count_z, int *count_m, int verbose)
          500  +{
          501  + /* checking for 3D geometries - version 4 */
          502  + int ret=0;
          503  + int i=0;
          504  + char *sql_statement = NULL;
          505  + sqlite3_stmt *stmt = NULL;
          506  + int has_m = 0;
          507  + double x_source=0.0;
          508  + double y_source=0.0;
          509  + double z_source=0.0;
          510  + double m_source=0.0;
          511  + *count_z=0;
          512  + *count_m=0;
          513  + if (mm)
          514  + {
          515  +  has_m = 1;
          516  + }
          517  + if (zz)
          518  + {
          519  +  for (i=0; i<count_points; i++)
          520  +  {
          521  +   dem_config->count_points_nr=i;
          522  +   x_source=xx_source[i];
          523  +   y_source=yy_source[i];
          524  +   /* checking the GEOMETRY_COLUMNS table */
          525  +   if (has_m)
          526  +   {
          527  +    sql_statement = sqlite3_mprintf("SELECT ST_Z(\"%s\"), ST_M(\"%s\") "
          528  +                                    "FROM '%s'.'%s' WHERE (ROWID IN ( "
          529  +                                    "SELECT ROWID FROM SpatialIndex WHERE ( "
          530  +                                    "(f_table_name = 'DB=%s.%s') AND "
          531  +                                    "(f_geometry_column = '%s') AND "
          532  +                                    "(search_frame = ST_Buffer(MakePoint(%2.7f,%2.7f,%d),%2.7f)))) AND "
          533  +                                    "(ST_ClosestPoint(%s, MakePoint(%2.7f,%2.7f,%d)) IS NOT Null) ) "
          534  +                                    "ORDER BY ST_Distance(%s,MakePoint(%2.7f,%2.7f,%d)) ASC LIMIT 1"
          535  +                                    ,dem_config->dem_geometry,dem_config->dem_geometry,dem_config->schema,dem_config->dem_table,dem_config->schema,dem_config->dem_table
          536  +                                    ,dem_config->dem_geometry,x_source,y_source,dem_config->dem_srid,dem_config->dem_resolution
          537  +                                    ,dem_config->dem_geometry,x_source,y_source,dem_config->dem_srid,dem_config->dem_geometry,x_source,y_source,dem_config->dem_srid);
          538  +   }
          539  +   else
          540  +   {
          541  +    sql_statement = sqlite3_mprintf("SELECT ST_Z(\"%s\") "
          542  +                                    "FROM '%s'.'%s' WHERE (ROWID IN ( "
          543  +                                    "SELECT ROWID FROM SpatialIndex WHERE ("
          544  +                                    "(f_table_name = 'DB=%s.%s') AND "
          545  +                                    "(f_geometry_column = '%s') AND "
          546  +                                    "(search_frame = ST_Buffer(MakePoint(%2.7f,%2.7f,%d),%2.7f)))) AND "
          547  +                                    "(ST_ClosestPoint(%s, MakePoint(%2.7f,%2.7f,%d)) IS NOT Null) ) "
          548  +                                    "ORDER BY ST_Distance(%s,MakePoint(%2.7f,%2.7f,%d)) ASC LIMIT 1"
          549  +                                    ,dem_config->dem_geometry,dem_config->schema,dem_config->dem_table,dem_config->schema,dem_config->dem_table
          550  +                                    ,dem_config->dem_geometry,x_source,y_source,dem_config->dem_srid,dem_config->dem_resolution
          551  +                                    ,dem_config->dem_geometry,x_source,y_source,dem_config->dem_srid,dem_config->dem_geometry,x_source,y_source,dem_config->dem_srid);
          552  +   }
          553  +   ret = sqlite3_prepare_v2( db_handle, sql_statement, -1, &stmt, NULL );
          554  +#if 0
          555  +   if ((dem_config->id_rowid == 354) && (dem_config->count_points == 207))
          556  +   {
          557  +    fprintf(stderr, "-III-> [EXTERIOR RING] -1a- cnt[%d,%d,%d] sql[%s] id_rowid[%d]\n",dem_config->count_points,dem_config->count_points_nr,ret,sql_statement,dem_config->id_rowid);
          558  +   }
          559  +#endif
          560  +   if ( ret == SQLITE_OK )
          561  +   {
          562  +    sqlite3_free(sql_statement);
          563  +    while ( sqlite3_step( stmt ) == SQLITE_ROW )
          564  +    {
          565  +     if ( sqlite3_column_type( stmt, 0 ) != SQLITE_NULL )
          566  +     {
          567  +      z_source = sqlite3_column_double (stmt, 0);
          568  +      if ( (z_source != 0.0 ) && (zz[i] != z_source ) )
          569  +      {// Do not force an update if everything is 0 or has not otherwise changed
          570  +       zz[i] = z_source;
          571  +       *count_z += 1;
          572  +      }
          573  +     }
          574  +     if ( sqlite3_column_type( stmt, 1 ) != SQLITE_NULL )
          575  +     {
          576  +      m_source = sqlite3_column_double (stmt, 1);
          577  +      if ( (m_source != 0.0 ) && (mm[i] != m_source ) )
          578  +      {// Do not force an update if everything is 0 or has not otherwise changed
          579  +       mm[i] = m_source;
          580  +       *count_m += 1;
          581  +      }
          582  +      mm[i] = sqlite3_column_double (stmt, 1);
          583  +     }
          584  +    }
          585  +    sqlite3_finalize( stmt );
          586  +   }
          587  +   else
          588  +   {
          589  +    if (verbose)
          590  +    {
          591  +     fprintf(stderr, "-W-> retrieve_dem_points: rc=%d sql[%s]\n",ret,sql_statement);
          592  +    }
          593  +    sqlite3_free(sql_statement);
          594  +   }
          595  +  }
          596  + }
          597  +// printf("-I-> retrieve_dem_points: total[%d] not 0.0: z[%d] m[%d]\n",count_points,*count_z,*count_m);
          598  + if (*count_z > 0)
          599  +  return 1;
          600  + return 0;
          601  +}
          602  +// -- -- ---------------------------------- --
          603  +//
          604  +// -- -- ---------------------------------- --
          605  +static int
          606  +callFetchZ(sqlite3 *db_handle, struct config_dem *dem_config, int verbose)
          607  +{
          608  + int ret=0;
          609  + char *sql_statement = NULL;
          610  + sqlite3_stmt *stmt = NULL;
          611  + int i_count_z=0;
          612  + int i_count_m=0;
          613  + double *xx_use = NULL;
          614  + double *yy_use = NULL;
          615  + double *mm_use = NULL;
          616  + double *zz = NULL;
          617  +// -- -- ---------------------------------- --
          618  + dem_config->dem_z=0;;
          619  + dem_config->dem_m=0;
          620  +// -- -- ---------------------------------- --
          621  + if (dem_config->dem_srid != dem_config->default_srid )
          622  + {
          623  +  sql_statement = sqlite3_mprintf("SELECT ST_X(ST_Transform(MakePoint(%2.7f,%2.7f,%d),%d)),  "
          624  +                                  "ST_Y(ST_Transform(MakePoint(%2.7f,%2.7f,%d),%d))"
          625  +                                  ,dem_config->fetchz_x, dem_config->fetchz_y, dem_config->default_srid,dem_config->dem_srid
          626  +                                  ,dem_config->fetchz_x, dem_config->fetchz_y, dem_config->default_srid,dem_config->dem_srid);
          627  +  ret = sqlite3_prepare_v2( db_handle, sql_statement, -1, &stmt, NULL );
          628  +  if ( ret == SQLITE_OK )
          629  +  {
          630  +   sqlite3_free(sql_statement);
          631  +   while ( sqlite3_step( stmt ) == SQLITE_ROW )
          632  +   {
          633  +    if (( sqlite3_column_type( stmt, 0 ) != SQLITE_NULL ) &&
          634  +        ( sqlite3_column_type( stmt, 1 ) != SQLITE_NULL ) )
          635  +    {
          636  +     dem_config->fetchz_x = sqlite3_column_double(stmt, 0);
          637  +     dem_config->fetchz_y = sqlite3_column_double(stmt, 1);
          638  +    }
          639  +   }
          640  +   sqlite3_finalize( stmt );
          641  +  }
          642  +  else
          643  +  {
          644  +   if (verbose)
          645  +   {
          646  +    fprintf(stderr, "-W-> callFetchZ : rc=%d sql[%s]\n",ret,sql_statement);
          647  +   }
          648  +   sqlite3_free(sql_statement);
          649  +  }
          650  + }
          651  +// -- -- ---------------------------------- --
          652  + ret=0;
          653  + if ((dem_config->fetchz_x >= dem_config->dem_extent_minx) && (dem_config->fetchz_x <= dem_config->dem_extent_maxx) &&
          654  +     (dem_config->fetchz_y >= dem_config->dem_extent_miny) && (dem_config->fetchz_y <= dem_config->dem_extent_maxy ) )
          655  + {
          656  +  xx_use = malloc(sizeof (double) * 1);
          657  +  yy_use = malloc(sizeof (double) * 1);
          658  +  zz = malloc(sizeof (double) * 1);
          659  +  mm_use = malloc(sizeof (double) * 1);
          660  +  xx_use[0] = dem_config->fetchz_x;
          661  +  yy_use[0] = dem_config->fetchz_y;
          662  +  zz[0] = dem_config->dem_z;
          663  +  mm_use[0] = dem_config->dem_m;
          664  +  dem_config->count_points=1;
          665  +  if (retrieve_dem_points(db_handle, dem_config, 1, xx_use, yy_use,zz,mm_use,&i_count_z, &i_count_m,verbose))
          666  +  {
          667  +   ret=1;
          668  +   dem_config->dem_z=zz[0];
          669  +   dem_config->dem_m=mm_use[0];
          670  +  }
          671  +  free(xx_use);
          672  +  free(yy_use);
          673  +  free(zz);
          674  +  free(mm_use);
          675  +  xx_use = NULL;
          676  +  yy_use = NULL;
          677  +  mm_use = NULL;
          678  +  zz = NULL;
          679  + }
          680  +// -- -- ---------------------------------- --
          681  + return ret;
          682  +}
          683  +// -- -- ---------------------------------- --
          684  +// GNU libc (Linux, and FreeBSD)
          685  +// - sys/param.h
          686  +// -- -- ---------------------------------- --
          687  +#define MIN(a,b) (((a)<(b))?(a):(b))
          688  +#define MAX(a,b) (((a)>(b))?(a):(b))
          689  +// -- -- ---------------------------------- --
          690  +// Based on gg_transform.c gaiaTransformCommon
          691  +// if the source geometry is out of range of the dem area, NULL is returned
          692  +// if the if the z or m values have not changed, NULL is returned
          693  +// - in both cases no update should be done and is not an error
          694  +// if the Dem-Database Geometry-Column uses a different Srid
          695  +// - a second Geometry will be sent with the transfored values
          696  +// --> those x,y values will be sent to retrieve_dem_points
          697  +//       to retrieve the nearst point
          698  +// The retrieved z,m values will be copied WITHOUT any changes
          699  +// -- -- ---------------------------------- --
          700  +static gaiaGeomCollPtr
          701  +getDemCollect(sqlite3 *db_handle, gaiaGeomCollPtr source_geom, gaiaGeomCollPtr dem_geom, struct config_dem *dem_config,
          702  +              int *count_points_total, int *count_z_total, int *count_m_total, int verbose)
          703  +{
          704  +// creates a new GEOMETRY replacing found z-points from the original one
          705  + int ib=0;
          706  + int cnt=0;
          707  + int i=0;
          708  + double *xx = NULL;
          709  + double *yy = NULL;
          710  + double *xx_dem = NULL;
          711  + double *yy_dem = NULL;
          712  + double *zz = NULL;
          713  + double *mm = NULL;
          714  + double *xx_use = NULL;
          715  + double *yy_use = NULL;
          716  + double *mm_use = NULL;
          717  + int count_z=0;
          718  + int count_m=0;
          719  + int i_count_z=0;
          720  + int i_count_m=0;
          721  + double x = 0.0;
          722  + double y = 0.0;
          723  + double z = 0.0;
          724  + double m = 0.0;
          725  + double extent_minx=0.0;
          726  + double extent_miny=0.0;
          727  + double extent_maxx=0.0;
          728  + double extent_maxy=0.0;
          729  + int error = 0;
          730  + int isExtentWithin=0;
          731  + gaiaPointPtr pt = NULL;
          732  + gaiaPointPtr pt_dem = NULL;
          733  + gaiaLinestringPtr ln = NULL;
          734  + gaiaLinestringPtr ln_dem = NULL;
          735  + gaiaLinestringPtr dst_ln = NULL;
          736  + gaiaPolygonPtr pg = NULL;
          737  + gaiaPolygonPtr pg_dem = NULL;
          738  + gaiaPolygonPtr dst_pg = NULL;
          739  + gaiaRingPtr rng = NULL;
          740  + gaiaRingPtr rng_dem = NULL;
          741  + gaiaRingPtr dst_rng = NULL;
          742  + gaiaGeomCollPtr dst = NULL;
          743  + if (source_geom->DimensionModel == GAIA_XY_Z)
          744  +  dst = gaiaAllocGeomCollXYZ();
          745  + else if (source_geom->DimensionModel == GAIA_XY_M)
          746  +  dst = gaiaAllocGeomCollXYM();
          747  + else if (source_geom->DimensionModel == GAIA_XY_Z_M)
          748  +  dst = gaiaAllocGeomCollXYZM();
          749  + else
          750  +  dst = gaiaAllocGeomColl ();
          751  + cnt = 0;
          752  + dst->Srid = source_geom->Srid;
          753  + pt = source_geom->FirstPoint;
          754  + extent_minx=source_geom->MinX;
          755  + extent_miny=source_geom->MinY;
          756  + extent_maxx=source_geom->MaxX;
          757  + extent_maxy=source_geom->MaxY;
          758  + if (dem_geom)
          759  + {
          760  +  extent_minx=dem_geom->MinX;
          761  +  extent_miny=dem_geom->MinY;
          762  +  extent_maxx=dem_geom->MaxX;
          763  +  extent_maxy=dem_geom->MaxY;
          764  + }
          765  +// -- -- ---------------------------------- --
          766  +// Touches (partially within)
          767  +// -- -- ---------------------------------- --
          768  + int left_x = MAX(extent_minx, dem_config->dem_extent_minx);
          769  + int right_x = MIN(extent_maxx, dem_config->dem_extent_maxx);
          770  + int bottom_y = MAX(extent_miny, dem_config->dem_extent_miny);
          771  + int top_y = MIN(extent_maxy, dem_config->dem_extent_maxy);
          772  + if ((right_x > left_x) && (top_y > bottom_y))
          773  + {
          774  +  isExtentWithin=1;
          775  + }
          776  +// -- -- ---------------------------------- --
          777  +#if 0
          778  + if ((extent_minx >= dem_config->dem_extent_minx) && (extent_maxx <= dem_config->dem_extent_maxx) &&
          779  +     (extent_miny >= dem_config->dem_extent_miny) && (extent_maxy <= dem_config->dem_extent_maxy ) )
          780  + {
          781  +  isExtentWithin=1;
          782  + }
          783  +#endif
          784  + if (!isExtentWithin)
          785  + {
          786  +  error=1;
          787  +  goto stop;
          788  + }
          789  +// -- -- ---------------------------------- --
          790  +// Call only if geometry is partially within the Dem extent
          791  +// -- -- ---------------------------------- --
          792  +// Points
          793  +// -- -- ---------------------------------- --
          794  + while (pt)
          795  + {
          796  +  // counting POINTs
          797  +  cnt++;
          798  +  pt = pt->Next;
          799  + }
          800  + if (cnt)
          801  + {
          802  +  // reprojecting POINTs
          803  +  xx = malloc(sizeof (double) * cnt);
          804  +  yy = malloc(sizeof (double) * cnt);
          805  +  if (dem_geom)
          806  +  {
          807  +   xx_dem = malloc(sizeof (double) * cnt);
          808  +   yy_dem = malloc(sizeof (double) * cnt);
          809  +   xx_use = xx_dem;
          810  +   yy_use = yy_dem;
          811  +  }
          812  +  else
          813  +  {
          814  +   xx_use = xx;
          815  +   yy_use = yy;
          816  +  }
          817  +  zz = malloc(sizeof (double) * cnt);
          818  +  if (source_geom->DimensionModel == GAIA_XY_M || source_geom->DimensionModel == GAIA_XY_Z_M)
          819  +   mm = malloc(sizeof (double) * cnt);
          820  +  i = 0;
          821  +  pt = source_geom->FirstPoint;
          822  +  if (dem_geom)
          823  +  {
          824  +   pt_dem = dem_geom->FirstPoint;
          825  +  }
          826  +  while (pt)
          827  +  {
          828  +   // inserting points to be converted in temporary arrays
          829  +   xx[i] = pt->X;
          830  +   yy[i] = pt->Y;
          831  +   if (source_geom->DimensionModel == GAIA_XY_Z || source_geom->DimensionModel == GAIA_XY_Z_M)
          832  +    zz[i] = pt->Z;
          833  +   else
          834  +    zz[i] = 0.0;
          835  +   if (source_geom->DimensionModel == GAIA_XY_M || source_geom->DimensionModel == GAIA_XY_Z_M)
          836  +    mm[i] = pt->M;
          837  +   if (pt_dem)
          838  +   {
          839  +    xx_dem[i] = pt_dem->X;
          840  +    yy_dem[i] = pt_dem->Y;
          841  +   }
          842  +   i++;
          843  +   // -- -- ---------------------------------- --
          844  +   // MultiPoints, next
          845  +   // -- -- ---------------------------------- --
          846  +   pt = pt->Next;
          847  +   if (dem_geom)
          848  +   {
          849  +    pt_dem =pt_dem->Next;
          850  +   }
          851  +  }
          852  +  if ((dem_config->has_m) && (mm) )
          853  +  {
          854  +   mm_use = mm;
          855  +  }
          856  +  // searching for nearest point
          857  +  *count_points_total+=cnt;
          858  +  i_count_z=0;
          859  +  i_count_m=0;
          860  +  dem_config->count_points=cnt;
          861  +  if (retrieve_dem_points(db_handle, dem_config, cnt, xx_use, yy_use,zz,mm_use,&i_count_z, &i_count_m,verbose))
          862  +  {
          863  +   *count_z_total+=i_count_z;
          864  +   *count_m_total+=i_count_m;
          865  +   count_z+=i_count_z;
          866  +   count_m+=i_count_m;
          867  +  }
          868  +  xx_use = NULL;
          869  +  yy_use = NULL;
          870  +  mm_use = NULL;
          871  +  // inserting the reprojected POINTs in the new GEOMETRY
          872  +  for (i = 0; i < cnt; i++)
          873  +  {
          874  +   x = xx[i];
          875  +   y = yy[i];
          876  +   if (source_geom->DimensionModel == GAIA_XY_Z || source_geom->DimensionModel == GAIA_XY_Z_M)
          877  +    z = zz[i];
          878  +   else
          879  +    z = 0.0;
          880  +   if (source_geom->DimensionModel == GAIA_XY_M || source_geom->DimensionModel == GAIA_XY_Z_M)
          881  +    m = mm[i];
          882  +   else
          883  +    m = 0.0;
          884  +   if (dst->DimensionModel == GAIA_XY_Z)
          885  +    gaiaAddPointToGeomCollXYZ(dst, x, y, z);
          886  +   else if (dst->DimensionModel == GAIA_XY_M)
          887  +    gaiaAddPointToGeomCollXYM(dst, x, y, m);
          888  +   else if (dst->DimensionModel == GAIA_XY_Z_M)
          889  +    gaiaAddPointToGeomCollXYZM(dst, x, y, z, m);
          890  +   else
          891  +    gaiaAddPointToGeomColl(dst, x, y);
          892  +  }
          893  +  free(xx);
          894  +  free(yy);
          895  +  free(zz);
          896  +  xx = NULL;
          897  +  yy = NULL;
          898  +  zz = NULL;
          899  +  if (xx_dem)
          900  +  {
          901  +   free(xx_dem);
          902  +   xx_dem = NULL;
          903  +   free(yy_dem);
          904  +   yy_dem = NULL;
          905  +  }
          906  +  if (source_geom->DimensionModel == GAIA_XY_M || source_geom->DimensionModel == GAIA_XY_Z_M)
          907  +  {
          908  +   free(mm);
          909  +   mm = NULL;
          910  +  }
          911  + }
          912  + if (error)
          913  +  goto stop;
          914  +// -- -- ---------------------------------- --
          915  +// Linestrings
          916  +// -- -- ---------------------------------- --
          917  + ln = source_geom->FirstLinestring;
          918  + if (dem_geom)
          919  + {
          920  +  ln_dem = dem_geom->FirstLinestring;
          921  + }
          922  +// Call only if geometry is inside the Dem extent
          923  + while (ln)
          924  + {
          925  +  // reprojecting LINESTRINGs
          926  +  cnt = ln->Points;
          927  +  xx = malloc(sizeof (double) * cnt);
          928  +  yy = malloc(sizeof (double) * cnt);
          929  +  if (dem_geom)
          930  +  {
          931  +   xx_dem = malloc(sizeof (double) * cnt);
          932  +   yy_dem = malloc(sizeof (double) * cnt);
          933  +   xx_use = xx_dem;
          934  +   yy_use = yy_dem;
          935  +  }
          936  +  else
          937  +  {
          938  +   xx_use = xx;
          939  +   yy_use = yy;
          940  +  }
          941  +  zz = malloc(sizeof (double) * cnt);
          942  +  if (ln->DimensionModel == GAIA_XY_M || ln->DimensionModel == GAIA_XY_Z_M)
          943  +   mm = malloc(sizeof (double) * cnt);
          944  +  for (i = 0; i < cnt; i++)
          945  +  {
          946  +   // inserting points to be converted in temporary arrays
          947  +   if (ln->DimensionModel == GAIA_XY_Z)
          948  +   {
          949  +    gaiaGetPointXYZ(ln->Coords, i, &x, &y, &z);
          950  +   }
          951  +   else if (ln->DimensionModel == GAIA_XY_M)
          952  +   {
          953  +    gaiaGetPointXYM(ln->Coords, i, &x, &y, &m);
          954  +   }
          955  +   else if (ln->DimensionModel == GAIA_XY_Z_M)
          956  +   {
          957  +    gaiaGetPointXYZM(ln->Coords, i, &x, &y, &z, &m);
          958  +   }
          959  +   else
          960  +   {
          961  +    gaiaGetPoint(ln->Coords, i, &x, &y);
          962  +   }
          963  +   xx[i] = x;
          964  +   yy[i] = y;
          965  +   if (ln_dem)
          966  +   {
          967  +    if (ln_dem->DimensionModel == GAIA_XY_Z)
          968  +    {
          969  +     gaiaGetPointXYZ(ln_dem->Coords, i, &x, &y, &z);
          970  +    }
          971  +    else if (ln_dem->DimensionModel == GAIA_XY_M)
          972  +    {
          973  +     gaiaGetPointXYM(ln->Coords, i, &x, &y, &m);
          974  +    }
          975  +    else if (ln_dem->DimensionModel == GAIA_XY_Z_M)
          976  +    {
          977  +     gaiaGetPointXYZM(ln_dem->Coords, i, &x, &y, &z, &m);
          978  +    }
          979  +    else
          980  +    {
          981  +     gaiaGetPoint(ln_dem->Coords, i, &x, &y);
          982  +    }
          983  +    xx_dem[i] = x;
          984  +    yy_dem[i] = y;
          985  +   }
          986  +   if (ln->DimensionModel == GAIA_XY_Z || ln->DimensionModel == GAIA_XY_Z_M)
          987  +    zz[i] = z;
          988  +   else
          989  +    zz[i] = 0.0;
          990  +   if (ln->DimensionModel == GAIA_XY_M || ln->DimensionModel == GAIA_XY_Z_M)
          991  +    mm[i] = m;
          992  +  }
          993  +  if ((dem_config->has_m) && (mm) )
          994  +  {
          995  +   mm_use = mm;
          996  +  }
          997  +  // searching for nearest point
          998  +  *count_points_total+=cnt;
          999  +  i_count_z=0;
         1000  +  i_count_m=0;
         1001  +  dem_config->count_points=cnt;
         1002  +  if (retrieve_dem_points(db_handle, dem_config, cnt, xx_use, yy_use,zz,mm_use,&i_count_z, &i_count_m,verbose))
         1003  +  {
         1004  +   *count_z_total+=i_count_z;
         1005  +   *count_m_total+=i_count_m;
         1006  +   count_z+=i_count_z;
         1007  +   count_m+=i_count_m;
         1008  +  }
         1009  +  xx_use = NULL;
         1010  +  yy_use = NULL;
         1011  +  mm_use = NULL;
         1012  +  // inserting the reprojected LINESTRING in the new GEOMETRY
         1013  +  dst_ln = gaiaAddLinestringToGeomColl (dst, cnt);
         1014  +  for (i = 0; i < cnt; i++)
         1015  +  {
         1016  +   // setting LINESTRING points
         1017  +   x = xx[i];
         1018  +   y = yy[i];
         1019  +   if (ln->DimensionModel == GAIA_XY_Z || ln->DimensionModel == GAIA_XY_Z_M)
         1020  +    z = zz[i];
         1021  +   else
         1022  +    z = 0.0;
         1023  +   if (ln->DimensionModel == GAIA_XY_M || ln->DimensionModel == GAIA_XY_Z_M)
         1024  +    m = mm[i];
         1025  +   else
         1026  +    m = 0.0;
         1027  +   if (dst_ln->DimensionModel == GAIA_XY_Z)
         1028  +   {
         1029  +    gaiaSetPointXYZ (dst_ln->Coords, i, x, y, z);
         1030  +   }
         1031  +   else if (dst_ln->DimensionModel == GAIA_XY_M)
         1032  +   {
         1033  +    gaiaSetPointXYM(dst_ln->Coords, i, x, y, m);
         1034  +   }
         1035  +   else if (dst_ln->DimensionModel == GAIA_XY_Z_M)
         1036  +   {
         1037  +    gaiaSetPointXYZM(dst_ln->Coords, i, x, y, z, m);
         1038  +   }
         1039  +   else
         1040  +   {
         1041  +    gaiaSetPoint(dst_ln->Coords, i, x, y);
         1042  +   }
         1043  +  }
         1044  +  free(xx);
         1045  +  free(yy);
         1046  +  xx = NULL;
         1047  +  yy = NULL;
         1048  +  if (xx_dem)
         1049  +  {
         1050  +   free(xx_dem);
         1051  +   xx_dem = NULL;
         1052  +   free(yy_dem);
         1053  +   yy_dem = NULL;
         1054  +  }
         1055  +  free(zz);
         1056  +  zz = NULL;
         1057  +  if (ln->DimensionModel == GAIA_XY_M || ln->DimensionModel == GAIA_XY_Z_M)
         1058  +  {
         1059  +   free(mm);
         1060  +   mm = NULL;
         1061  +  }
         1062  +  if (error)
         1063  +   goto stop;
         1064  +// -- -- ---------------------------------- --
         1065  +// MultiLinestrings, next
         1066  +// -- -- ---------------------------------- --
         1067  +  ln = ln->Next;
         1068  +  if (dem_geom)
         1069  +  {
         1070  +   ln_dem = ln_dem->Next;
         1071  +  }
         1072  + }
         1073  +// -- -- ---------------------------------- --
         1074  +// Polygons
         1075  +// -- -- ---------------------------------- --
         1076  + pg = source_geom->FirstPolygon;
         1077  + if (dem_geom)
         1078  + {
         1079  +  pg_dem = dem_geom->FirstPolygon;
         1080  + }
         1081  + while (pg)
         1082  + {
         1083  +  // -- -- ---------------------------------- --
         1084  +  // Polygons-ExteriorRing
         1085  +  // -- -- ---------------------------------- --
         1086  +  rng = pg->Exterior;
         1087  +  cnt = rng->Points;
         1088  +  dst_pg = gaiaAddPolygonToGeomColl(dst, cnt, pg->NumInteriors);
         1089  +  xx = malloc(sizeof (double) * cnt);
         1090  +  yy = malloc(sizeof (double) * cnt);
         1091  +  if (dem_geom)
         1092  +  {
         1093  +   xx_dem = malloc(sizeof (double) * cnt);
         1094  +   yy_dem = malloc(sizeof (double) * cnt);
         1095  +   rng_dem = pg_dem->Exterior;
         1096  +   xx_use = xx_dem;
         1097  +   yy_use = yy_dem;
         1098  +  }
         1099  +  else
         1100  +  {
         1101  +   xx_use = xx;
         1102  +   yy_use = yy;
         1103  +  }
         1104  +  zz = malloc(sizeof (double) * cnt);
         1105  +  if (rng->DimensionModel == GAIA_XY_M || rng->DimensionModel == GAIA_XY_Z_M)
         1106  +   mm = malloc(sizeof (double) * cnt);
         1107  +  for (i = 0; i < cnt; i++)
         1108  +  {
         1109  +   // inserting points to be converted in temporary arrays [EXTERIOR RING]
         1110  +   if (rng->DimensionModel == GAIA_XY_Z)
         1111  +   {
         1112  +    gaiaGetPointXYZ(rng->Coords, i, &x, &y, &z);
         1113  +   }
         1114  +   else if (rng->DimensionModel == GAIA_XY_M)
         1115  +   {
         1116  +    gaiaGetPointXYM(rng->Coords, i, &x, &y, &m);
         1117  +   }
         1118  +   else if (rng->DimensionModel == GAIA_XY_Z_M)
         1119  +   {
         1120  +    gaiaGetPointXYZM(rng->Coords, i, &x, &y, &z, &m);
         1121  +   }
         1122  +   else
         1123  +   {
         1124  +    gaiaGetPoint(rng->Coords, i, &x, &y);
         1125  +   }
         1126  +   xx[i] = x;
         1127  +   yy[i] = y;
         1128  +   if (rng_dem)
         1129  +   {
         1130  +    if (rng_dem->DimensionModel == GAIA_XY_Z)
         1131  +    {
         1132  +     gaiaGetPointXYZ(rng_dem->Coords, i, &x, &y, &z);
         1133  +    }
         1134  +    else if (rng_dem->DimensionModel == GAIA_XY_M)
         1135  +    {
         1136  +     gaiaGetPointXYM(rng_dem->Coords, i, &x, &y, &m);
         1137  +    }
         1138  +    else if (rng_dem->DimensionModel == GAIA_XY_Z_M)
         1139  +    {
         1140  +     gaiaGetPointXYZM(rng_dem->Coords, i, &x, &y, &z, &m);
         1141  +    }
         1142  +    else
         1143  +    {
         1144  +     gaiaGetPoint(rng_dem->Coords, i, &x, &y);
         1145  +    }
         1146  +    xx_dem[i] = x;
         1147  +    yy_dem[i] = y;
         1148  +   }
         1149  +   if (rng->DimensionModel == GAIA_XY_Z  || rng->DimensionModel == GAIA_XY_Z_M)
         1150  +    zz[i] = z;
         1151  +   else
         1152  +    zz[i] = 0.0;
         1153  +   if (rng->DimensionModel == GAIA_XY_M || rng->DimensionModel == GAIA_XY_Z_M)
         1154  +    mm[i] = m;
         1155  +  }
         1156  +  if ((dem_config->has_m) && (mm) )
         1157  +  {
         1158  +   mm_use = mm;
         1159  +  }
         1160  +  // searching for nearest point
         1161  +  *count_points_total+=cnt;
         1162  +  i_count_z=0;
         1163  +  i_count_m=0;
         1164  +  dem_config->count_points=cnt;
         1165  +  if (retrieve_dem_points(db_handle, dem_config, cnt, xx_use, yy_use,zz,mm_use,&i_count_z, &i_count_m,verbose))
         1166  +  {
         1167  +   *count_z_total+=i_count_z;
         1168  +   *count_m_total+=i_count_m;
         1169  +   count_z+=i_count_z;
         1170  +   count_m+=i_count_m;
         1171  +  }
         1172  +  xx_use = NULL;
         1173  +  yy_use = NULL;
         1174  +  mm_use = NULL;
         1175  +  // inserting the reprojected POLYGON in the new GEOMETRY
         1176  +  dst_rng = dst_pg->Exterior;
         1177  +  for (i = 0; i < cnt; i++)
         1178  +  {
         1179  +   // setting EXTERIOR RING points
         1180  +   x = xx[i];
         1181  +   y = yy[i];
         1182  +   if (rng->DimensionModel == GAIA_XY_Z || rng->DimensionModel == GAIA_XY_Z_M)
         1183  +    z = zz[i];
         1184  +   else
         1185  +    z = 0.0;
         1186  +   if (rng->DimensionModel == GAIA_XY_M  || rng->DimensionModel == GAIA_XY_Z_M)
         1187  +    m = mm[i];
         1188  +   else
         1189  +    m = 0.0;
         1190  +   if (dst_rng->DimensionModel == GAIA_XY_Z)
         1191  +   {
         1192  +    gaiaSetPointXYZ (dst_rng->Coords, i, x, y, z);
         1193  +   }
         1194  +   else if (dst_rng->DimensionModel == GAIA_XY_M)
         1195  +   {
         1196  +    gaiaSetPointXYM(dst_rng->Coords, i, x, y, m);
         1197  +   }
         1198  +   else if (dst_rng->DimensionModel == GAIA_XY_Z_M)
         1199  +   {
         1200  +    gaiaSetPointXYZM(dst_rng->Coords, i, x, y, z, m);
         1201  +   }
         1202  +   else
         1203  +   {
         1204  +    gaiaSetPoint(dst_rng->Coords, i, x, y);
         1205  +   }
         1206  +  }
         1207  +  free(xx);
         1208  +  free(yy);
         1209  +  xx = NULL;
         1210  +  yy = NULL;
         1211  +  if (xx_dem)
         1212  +  {
         1213  +   free(xx_dem);
         1214  +   xx_dem = NULL;
         1215  +   free(yy_dem);
         1216  +   yy_dem = NULL;
         1217  +  }
         1218  +  free(zz);
         1219  +  zz = NULL;
         1220  +  if (rng->DimensionModel == GAIA_XY_M || rng->DimensionModel == GAIA_XY_Z_M)
         1221  +  {
         1222  +   free(mm);
         1223  +   mm = NULL;
         1224  +  }
         1225  +  if (error)
         1226  +   goto stop;
         1227  +  // -- -- ---------------------------------- --
         1228  +  // Polygons-InteriorRings
         1229  +  // -- -- ---------------------------------- --
         1230  +  for (ib = 0; ib < pg->NumInteriors; ib++)
         1231  +  {
         1232  +   // processing INTERIOR RINGS
         1233  +   rng = pg->Interiors + ib;
         1234  +   cnt = rng->Points;
         1235  +   xx = malloc(sizeof (double) * cnt);
         1236  +   yy = malloc(sizeof (double) * cnt);
         1237  +   if (dem_geom)
         1238  +   {
         1239  +    xx_dem = malloc(sizeof (double) * cnt);
         1240  +    yy_dem = malloc(sizeof (double) * cnt);
         1241  +    rng_dem = pg_dem->Interiors + ib;
         1242  +    xx_use = xx_dem;
         1243  +    yy_use = yy_dem;
         1244  +   }
         1245  +   else
         1246  +   {
         1247  +    xx_use = xx;
         1248  +    yy_use = yy;
         1249  +   }
         1250  +   zz = malloc(sizeof (double) * cnt);
         1251  +   if (rng->DimensionModel == GAIA_XY_M || rng->DimensionModel == GAIA_XY_Z_M)
         1252  +    mm = malloc(sizeof (double) * cnt);
         1253  +   for (i = 0; i < cnt; i++)
         1254  +   {
         1255  +    // inserting points to be converted in temporary arrays [INTERIOR RING]
         1256  +    if (rng->DimensionModel == GAIA_XY_Z)
         1257  +    {
         1258  +     gaiaGetPointXYZ(rng->Coords, i, &x, &y, &z);
         1259  +    }
         1260  +    else if (rng->DimensionModel == GAIA_XY_M)
         1261  +    {
         1262  +     gaiaGetPointXYM(rng->Coords, i, &x, &y, &m);
         1263  +    }
         1264  +    else if (rng->DimensionModel == GAIA_XY_Z_M)
         1265  +    {
         1266  +     gaiaGetPointXYZM(rng->Coords, i, &x, &y, &z, &m);
         1267  +    }
         1268  +    else
         1269  +    {
         1270  +     gaiaGetPoint(rng->Coords, i, &x, &y);
         1271  +    }
         1272  +    xx[i] = x;
         1273  +    yy[i] = y;
         1274  +    if (rng_dem)
         1275  +    {
         1276  +     if (rng_dem->DimensionModel == GAIA_XY_Z)
         1277  +     {
         1278  +      gaiaGetPointXYZ(rng_dem->Coords, i, &x, &y, &z);
         1279  +     }
         1280  +     else if (rng_dem->DimensionModel == GAIA_XY_M)
         1281  +     {
         1282  +      gaiaGetPointXYM(rng_dem->Coords, i, &x, &y, &m);
         1283  +     }
         1284  +     else if (rng_dem->DimensionModel == GAIA_XY_Z_M)
         1285  +     {
         1286  +      gaiaGetPointXYZM(rng_dem->Coords, i, &x, &y, &z, &m);
         1287  +     }
         1288  +     else
         1289  +     {
         1290  +      gaiaGetPoint(rng_dem->Coords, i, &x, &y);
         1291  +     }
         1292  +     xx_dem[i] = x;
         1293  +     yy_dem[i] = y;
         1294  +    }
         1295  +    if (rng->DimensionModel == GAIA_XY_Z  || rng->DimensionModel == GAIA_XY_Z_M)
         1296  +     zz[i] = z;
         1297  +    else
         1298  +     zz[i] = 0.0;
         1299  +    if (rng->DimensionModel == GAIA_XY_M  || rng->DimensionModel == GAIA_XY_Z_M)
         1300  +     mm[i] = m;
         1301  +   }
         1302  +   if ((dem_config->has_m) && (mm) )
         1303  +   {
         1304  +    mm_use = mm;
         1305  +   }
         1306  +   // searching for nearest point
         1307  +   *count_points_total+=cnt;
         1308  +   i_count_z=0;
         1309  +   i_count_m=0;
         1310  +   dem_config->count_points=cnt;
         1311  +   if (retrieve_dem_points(db_handle, dem_config, cnt, xx_use, yy_use,zz,mm_use,&i_count_z, &i_count_m,verbose))
         1312  +   {
         1313  +    *count_z_total+=i_count_z;
         1314  +    *count_m_total+=i_count_m;
         1315  +    count_z+=i_count_z;
         1316  +    count_m+=i_count_m;
         1317  +   }
         1318  +   xx_use = NULL;
         1319  +   yy_use = NULL;
         1320  +   mm_use = NULL;
         1321  +   // inserting the reprojected POLYGON in the new GEOMETRY
         1322  +   dst_rng = gaiaAddInteriorRing(dst_pg, ib, cnt);
         1323  +   for (i = 0; i < cnt; i++)
         1324  +   {
         1325  +    // setting INTERIOR RING points
         1326  +    x = xx[i];
         1327  +    y = yy[i];
         1328  +    if (rng->DimensionModel == GAIA_XY_Z || rng->DimensionModel == GAIA_XY_Z_M)
         1329  +     z = zz[i];
         1330  +    else
         1331  +     z = 0.0;
         1332  +    if (rng->DimensionModel == GAIA_XY_M || rng->DimensionModel == GAIA_XY_Z_M)
         1333  +     m = mm[i];
         1334  +    else
         1335  +     m = 0.0;
         1336  +    if (dst_rng->DimensionModel == GAIA_XY_Z)
         1337  +    {
         1338  +     gaiaSetPointXYZ(dst_rng->Coords, i, x, y, z);
         1339  +    }
         1340  +    else if (dst_rng->DimensionModel == GAIA_XY_M)
         1341  +    {
         1342  +     gaiaSetPointXYM(dst_rng->Coords, i, x, y, m);
         1343  +    }
         1344  +    else if (dst_rng->DimensionModel == GAIA_XY_Z_M)
         1345  +    {
         1346  +     gaiaSetPointXYZM(dst_rng->Coords, i, x, y, z, m);
         1347  +    }
         1348  +    else
         1349  +    {
         1350  +     gaiaSetPoint(dst_rng->Coords, i, x, y);
         1351  +    }
         1352  +   }
         1353  +   free(xx);
         1354  +   free(yy);
         1355  +   xx = NULL;
         1356  +   yy = NULL;
         1357  +   if (xx_dem)
         1358  +   {
         1359  +    free(xx_dem);
         1360  +    xx_dem = NULL;
         1361  +    free(yy_dem);
         1362  +    yy_dem = NULL;
         1363  +   }
         1364  +   free(zz);
         1365  +   zz = NULL;
         1366  +   if (rng->DimensionModel == GAIA_XY_M || rng->DimensionModel == GAIA_XY_Z_M)
         1367  +   {
         1368  +    free(mm);
         1369  +    mm = NULL;
         1370  +   }
         1371  +   if (error)
         1372  +    goto stop;
         1373  +  }
         1374  +// -- -- ---------------------------------- --
         1375  +// MultiPolygons, next
         1376  +// -- -- ---------------------------------- --
         1377  +  pg = pg->Next;
         1378  +  if (dem_geom)
         1379  +  {
         1380  +   pg_dem = pg_dem->Next;
         1381  +  }
         1382  + }
         1383  +// -- -- ---------------------------------- --
         1384  +// -end- Geometry types
         1385  +// -- -- ---------------------------------- --
         1386  +stop:
         1387  + if ((count_z+count_m) == 0)
         1388  + {// Do not force an update if everything is 0 or has not otherwise changed
         1389  +  error=1;
         1390  + }
         1391  + if (error)
         1392  + {
         1393  +  // some error occurred, or no changes needed
         1394  +  gaiaPointPtr pP;
         1395  +  gaiaPointPtr pPn;
         1396  +  gaiaLinestringPtr pL;
         1397  +  gaiaLinestringPtr pLn;
         1398  +  gaiaPolygonPtr pA;
         1399  +  gaiaPolygonPtr pAn;
         1400  +  pP = dst->FirstPoint;
         1401  +  while (pP != NULL)
         1402  +  {
         1403  +   pPn = pP->Next;
         1404  +   gaiaFreePoint(pP);
         1405  +   pP = pPn;
         1406  +  }
         1407  +  pL = dst->FirstLinestring;
         1408  +  while (pL != NULL)
         1409  +  {
         1410  +   pLn = pL->Next;
         1411  +   gaiaFreeLinestring(pL);
         1412  +   pL = pLn;
         1413  +  }
         1414  +  pA = dst->FirstPolygon;
         1415  +  while (pA != NULL)
         1416  +  {
         1417  +   pAn = pA->Next;
         1418  +   gaiaFreePolygon(pA);
         1419  +   pA = pAn;
         1420  +  }
         1421  +  dst->FirstPoint = NULL;
         1422  +  dst->LastPoint = NULL;
         1423  +  dst->FirstLinestring = NULL;
         1424  +  dst->LastLinestring = NULL;
         1425  +  dst->FirstPolygon = NULL;
         1426  +  dst->LastPolygon = NULL;
         1427  +  gaiaFreeGeomColl(dst);
         1428  +  dst = NULL;
         1429  +  // -- -- ---------------------------------- --
         1430  +  // if the source geometry is out of range of the dem area, NULL is returned
         1431  +  // -- -- ---------------------------------- --
         1432  +  return NULL;
         1433  + }
         1434  + if (dst)
         1435  + {
         1436  +  gaiaMbrGeometry(dst);
         1437  +  dst->DeclaredType = source_geom->DeclaredType;
         1438  + }
         1439  + return dst;
         1440  +}
         1441  +// -- -- ---------------------------------- --
         1442  +// if the source geometry is out of range of the dem area, NULL is returned
         1443  +// - no update should be done and is not an error
         1444  +// if the source geometry cannot be updated, when changed
         1445  +// - this is an error and the loop should stop
         1446  +// The source must be a SpatialTable,
         1447  +// - since ROWID is used for a (possibly) needed update
         1448  +// -- -- ---------------------------------- --
         1449  +static int
         1450  +retrieve_geometries(sqlite3 *db_handle, struct config_dem *source_config, struct config_dem *dem_config, int *count_total_geometries, int *count_changed_geometries,
         1451  +                    int *count_points_total, int *count_z_total, int *count_m_total, int verbose)
         1452  +{
         1453  + char *sql_statement = NULL;
         1454  + sqlite3_stmt *stmt = NULL;
         1455  + sqlite3_stmt *stmt_update = NULL;
         1456  + char *sql_err = NULL;
         1457  + unsigned char *blob_value = NULL;
         1458  + int blob_bytes=0;
         1459  + unsigned char *blob_update = NULL;
         1460  + int blob_bytes_update=0;
         1461  + int id_rowid=0;
         1462  + int ret=0;
         1463  + int ret_update=SQLITE_ABORT;
         1464  + unsigned int i_sleep=1; // 1 second
         1465  + int count_geometries_remainder=100;
         1466  + int transaction_update_changed_last=0;
         1467  + int transaction_count_loops=0;
         1468  + double remainder_calc=0.10;
         1469  + gaiaGeomCollPtr source_geom = NULL;
         1470  + gaiaGeomCollPtr geom_dem = NULL;
         1471  + gaiaGeomCollPtr geom_result = NULL;
         1472  + *count_total_geometries=0;
         1473  + *count_changed_geometries=0;
         1474  + *count_points_total=0;
         1475  + *count_z_total=0;
         1476  + *count_m_total=0;
         1477  +// -- -- ---------------------------------- --
         1478  + count_geometries_remainder=source_config->dem_rows_count/100;
         1479  + if (count_geometries_remainder > 1000)
         1480  + {// Display results every 1.25% of total geometries, when verbose
         1481  +  remainder_calc=remainder_calc/8;
         1482  + } else if (source_config->dem_rows_count > 500)
         1483  + {// Display results every 2.5% of total geometries, when verbose
         1484  +  remainder_calc=remainder_calc/4;
         1485  + } else if (source_config->dem_rows_count > 100)
         1486  + {// Display results every 5% of total geometries, when verbose
         1487  +  remainder_calc=remainder_calc/2;
         1488  + } // else: Display results every 10% of total geometries, when verbose
         1489  + count_geometries_remainder=(int)(source_config->dem_rows_count*remainder_calc);
         1490  +// -- -- ---------------------------------- --
         1491  + if (verbose)
         1492  + {
         1493  +  fprintf(stderr, "-I-> retrieve_geometries: results will be shown after each group of %d geometries, total[%u] \n",count_geometries_remainder,source_config->dem_rows_count);
         1494  + }
         1495  + if (dem_config->default_srid == dem_config->dem_srid)
         1496  + {
         1497  +  sql_statement = sqlite3_mprintf("SELECT ROWID, \"%s\" FROM '%s'.'%s' WHERE \"%s\" IS NOT NULL",
         1498  +                                  source_config->dem_geometry, source_config->schema,source_config->dem_table, source_config->dem_geometry);
         1499  + }
         1500  + else
         1501  + {
         1502  +  sql_statement = sqlite3_mprintf("SELECT ROWID, \"%s\", ST_Transform(\"%s\",%d) FROM '%s'.'%s' WHERE \"%s\"  IS NOT NULL",
         1503  +                                  source_config->dem_geometry,source_config->dem_geometry, dem_config->dem_srid, source_config->schema,source_config->dem_table,source_config->dem_geometry);
         1504  + }
         1505  + ret = sqlite3_prepare_v2(db_handle, sql_statement, -1, &stmt, NULL );
         1506  + if ( ret == SQLITE_OK )
         1507  + {
         1508  +  sqlite3_free(sql_statement);
         1509  +  while ( sqlite3_step( stmt ) == SQLITE_ROW )
         1510  +  {
         1511  +   if (( sqlite3_column_type( stmt, 0 ) != SQLITE_NULL ) &&
         1512  +       ( sqlite3_column_type( stmt, 1 ) != SQLITE_NULL ) )
         1513  +   {
         1514  +    id_rowid = sqlite3_column_int (stmt, 0);
         1515  +    dem_config->id_rowid=id_rowid; // for debugging
         1516  +    blob_value = (unsigned char *)sqlite3_column_blob(stmt, 1);
         1517  +    blob_bytes = sqlite3_column_bytes(stmt,1);
         1518  +    source_geom = gaiaFromSpatiaLiteBlobWkb(blob_value, blob_bytes);
         1519  +    *count_total_geometries+=1;
         1520  +   }
         1521  +   if ( sqlite3_column_type( stmt, 2 ) != SQLITE_NULL )
         1522  +   {
         1523  +    blob_value = (unsigned char *)sqlite3_column_blob(stmt, 2);
         1524  +    blob_bytes = sqlite3_column_bytes(stmt,2);
         1525  +    geom_dem = gaiaFromSpatiaLiteBlobWkb(blob_value, blob_bytes);
         1526  +   }
         1527  +   if (source_geom)
         1528  +   {
         1529  +    // if the source geometry is out of range of the dem area, NULL is returned: this is not an error, but no update
         1530  +    geom_result=getDemCollect(db_handle, source_geom, geom_dem, dem_config, count_points_total,count_z_total,count_m_total,verbose);
         1531  +    gaiaFreeGeomColl(source_geom);
         1532  +    source_geom = NULL;
         1533  +    if (geom_dem)
         1534  +    {
         1535  +     gaiaFreeGeomColl(geom_dem);
         1536  +     geom_dem = NULL;
         1537  +    }
         1538  +    ret_update=SQLITE_OK;
         1539  +    if (geom_result)
         1540  +    {
         1541  +     sql_statement = sqlite3_mprintf("UPDATE '%s'.'%s' SET '%s'=? WHERE ROWID=%d",
         1542  +                                     source_config->schema,source_config->dem_table,source_config->dem_geometry,id_rowid);
         1543  +     ret=sqlite3_prepare_v2(db_handle, sql_statement, -1, &stmt_update, NULL);
         1544  +     if ( ret == SQLITE_OK)
         1545  +     {
         1546  +      sqlite3_free(sql_statement);
         1547  +      gaiaToSpatiaLiteBlobWkb(geom_result, &blob_update, &blob_bytes_update);
         1548  +      // Note: sqlite3_bind_* index is 1-based, os apposed to sqlite3_column_* that is 0-based.
         1549  +      sqlite3_bind_blob(stmt_update, 1, blob_update, blob_bytes_update, free);
         1550  +      ret_update = sqlite3_step( stmt_update );
         1551  +      if ( ret_update == SQLITE_DONE || ret_update == SQLITE_ROW )
         1552  +      {
         1553  +       ret_update=SQLITE_OK;
         1554  +       *count_changed_geometries += 1;
         1555  +      }
         1556  +      else
         1557  +      {
         1558  +       ret_update=SQLITE_ABORT;
         1559  +      }
         1560  +      sqlite3_finalize( stmt_update );
         1561  +     }
         1562  +     else
         1563  +     {
         1564  +      if (verbose)
         1565  +      {
         1566  +       fprintf(stderr, "-W-> retrieve_geometries [UPDATE]: rc=%d sql[%s]\n",ret,sql_statement);
         1567  +      }
         1568  +      sqlite3_free(sql_statement);
         1569  +     }
         1570  +    }
         1571  +    gaiaFreeGeomColl(geom_result);
         1572  +    geom_result = NULL;
         1573  +    if (((*count_total_geometries % count_geometries_remainder) == 0))
         1574  +    {
         1575  +     if (*count_changed_geometries > transaction_update_changed_last)
         1576  +     {// Store results only if something has changed
         1577  +      // Note: while testing, this process stopped, with no further updates being reported.
         1578  +      // The assumption was that there was a logical error else where, which was not the case.
         1579  +      // This saving was build in to get to this point and analyse. [cause: missing Next for Linestrings/Polygon for dem_geom]
         1580  +      // Since the logic exists, that UPDATEs are only done after changes have been made
         1581  +      // This sporadic COMMIT/BEGIN has been retained. What is done is done.
         1582  +      if (sqlite3_exec(db_handle, "COMMIT", NULL, NULL, &sql_err) == SQLITE_OK)
         1583  +      {
         1584  +       sleep(i_sleep);
         1585  +       if (sqlite3_exec(db_handle, "BEGIN", NULL, NULL, &sql_err) == SQLITE_OK)
         1586  +       {
         1587  +       }
         1588  +      }
         1589  +      if (sql_err)
         1590  +      {
         1591  +       sqlite3_free(sql_err);
         1592  +      }
         1593  +     }
         1594  +     if (verbose)
         1595  +     {
         1596  +      double procent_diff=(double)(*count_total_geometries)/source_config->dem_rows_count;
         1597  +      remainder_calc=procent_diff*100;
         1598  +      if (transaction_count_loops == 0)
         1599  +      {// Show only once
         1600  +       fprintf(stderr,"-I-> converted geometries commited to Database: \n");
         1601  +      }
         1602  +      transaction_count_loops++;
         1603  +      if (dem_config->has_m)
         1604  +      {// overwrite the previous message [\r]
         1605  +       fprintf(stderr, "\r %02.2f%% total read[%d] changed[%d] ; points total[%d] changed z[%d] changed m[%d] ",remainder_calc,*count_total_geometries,*count_changed_geometries,*count_points_total,*count_z_total,*count_m_total);
         1606  +      }
         1607  +      else
         1608  +      {// overwrite the previous message [\r]
         1609  +       fprintf(stderr, "\r %02.2f%% total read[%d] changed[%d] ; points total[%d] changed z[%d] ",remainder_calc,*count_total_geometries,*count_changed_geometries,*count_points_total,*count_z_total);
         1610  +      }
         1611  +     }
         1612  +     transaction_update_changed_last=*count_changed_geometries;
         1613  +    }
         1614  +   }
         1615  +   if (ret_update == SQLITE_ABORT )
         1616  +   {
         1617  +    break;
         1618  +   }
         1619  +  }
         1620  +  sqlite3_finalize( stmt );
         1621  +  if (verbose)
         1622  +  {// new line after last message [\n]
         1623  +   fprintf(stderr, "\n");
         1624  +  }
         1625  + }
         1626  + else
         1627  + {
         1628  +  if (verbose)
         1629  +  {
         1630  +   fprintf(stderr, "-W-> retrieve_geometries [SELECT]: rc=%d sql[%s]\n",ret,sql_statement);
         1631  +  }
         1632  +  sqlite3_free(sql_statement);
         1633  + }
         1634  + if (ret_update == SQLITE_ABORT )
         1635  + {
         1636  +  return 0;
         1637  + }
         1638  + return 1;
         1639  +}
         1640  +// -- -- ---------------------------------- --
         1641  +// Retrieve information about given
         1642  +// - table and geometry-column
         1643  +// -> for Source and Dem geometries
         1644  +// Dem
         1645  +// - must be a POINTZ or POINTZM
         1646  +// - SpatialIndex must exist
         1647  +// -  Extent and row_count
         1648  +// -> to calculate resolution
         1649  +// Source
         1650  +// - must have a Z or ZM Dimension
         1651  +// Both
         1652  +// -  Srid of geometries
         1653  +// -- -- ---------------------------------- --
         1654  +static int
         1655  +check_geometry_dimension(sqlite3 *db_handle, struct config_dem *use_config, int *geometry_type, int verbose)
         1656  +{
         1657  + /* checking the table, geometry exists and if the geometry supports z-values */
         1658  + int ret=0;
         1659  + char *sql_statement = NULL;
         1660  + sqlite3_stmt *stmt = NULL;
         1661  + int *srid_default = NULL;
         1662  + use_config->has_z = 0;
         1663  + use_config->has_m = 0;
         1664  + use_config->dem_extent_minx=0.0;
         1665  + use_config->dem_extent_miny=0.0;
         1666  + use_config->dem_extent_maxx=0.0;
         1667  + use_config->dem_extent_maxy=0.0;
         1668  + use_config->has_spatial_index=0;
         1669  + use_config->is_spatial_table=0;
         1670  + if (use_config->config_type == CONF_TYPE_DEM )
         1671  + {
         1672  +  srid_default = &use_config->dem_srid;
         1673  + }
         1674  + else
         1675  + {
         1676  +  srid_default = &use_config->default_srid;
         1677  + }
         1678  + *geometry_type = 0;
         1679  + *srid_default = 0;
         1680  +// 390718.000000	5818887.000000	392757.000000	5820847.000000
         1681  +// 392757-390718=2039
         1682  +// 5820847-5818887=1960
         1683  +// 1960*2039=3996440/4000440=0.99900011 resolution
         1684  + sql_statement = sqlite3_mprintf("SELECT a.geometry_type, a.srid, a.spatial_index_enabled, a.layer_type, "
         1685  +                                 "b.extent_min_x, b.extent_min_y, b.extent_max_x, b.extent_max_y, b.row_count "
         1686  +                                 "FROM '%s'.vector_layers AS a LEFT JOIN '%s'.vector_layers_statistics AS b "
         1687  +                                 "ON a.table_name=b.table_name  AND a.geometry_column=b.geometry_column "
         1688  +                                 "WHERE a.table_name='%s' AND a.geometry_column='%s'", use_config->schema, use_config->schema,
         1689  +                                 use_config->dem_table, use_config->dem_geometry);
         1690  + ret = sqlite3_prepare_v2(db_handle, sql_statement, -1, &stmt, NULL );
         1691  + if ( ret == SQLITE_OK )
         1692  + {
         1693  +  sqlite3_free(sql_statement);
         1694  +  while ( sqlite3_step( stmt ) == SQLITE_ROW )
         1695  +  {
         1696  +   if (( sqlite3_column_type( stmt, 0 ) != SQLITE_NULL ) &&
         1697  +       ( sqlite3_column_type( stmt, 1 ) != SQLITE_NULL ) &&
         1698  +       ( sqlite3_column_type( stmt, 2 ) != SQLITE_NULL ) &&
         1699  +       ( sqlite3_column_type( stmt, 3 ) != SQLITE_NULL ))
         1700  +   {
         1701  +    *geometry_type = sqlite3_column_int( stmt, 0 );
         1702  +    *srid_default = sqlite3_column_int( stmt, 1 );
         1703  +    use_config->has_spatial_index = sqlite3_column_int( stmt, 2 );
         1704  +    if (strcmp((const char *)sqlite3_column_text( stmt, 3 ),"SpatialTable") == 0)
         1705  +    {
         1706  +     // The source Database must be in a SpatialTable to be updated [no checking for writable SpatialView's]
         1707  +     // will be using ROWID to UPDATE
         1708  +     use_config->is_spatial_table = 1;
         1709  +    }
         1710  +    // printf("-I-> check_geometry_dimension: coord_dimension=%d GAIA_XY_*l[%d,%d,%d]\n",coord_dimension,GAIA_XY_Z,GAIA_XY_Z_M,GAIA_XY_M);
         1711  +    switch (*geometry_type)
         1712  +    {
         1713  +     case GAIA_POINTZ:
         1714  +     case GAIA_LINESTRINGZ:
         1715  +     case GAIA_POLYGONZ:
         1716  +     case GAIA_MULTIPOINTZ:
         1717  +     case GAIA_MULTILINESTRINGZ:
         1718  +     case GAIA_MULTIPOLYGONZ:
         1719  +     case GAIA_GEOMETRYCOLLECTIONZ:
         1720  +      use_config->has_z = 1;
         1721  +      break;
         1722  +    }
         1723  +    switch (*geometry_type)
         1724  +    {
         1725  +     case GAIA_POINTZM:
         1726  +     case GAIA_LINESTRINGZM:
         1727  +     case GAIA_POLYGONZM:
         1728  +     case GAIA_MULTIPOINTZM:
         1729  +     case GAIA_MULTILINESTRINGZM:
         1730  +     case GAIA_MULTIPOLYGONZM:
         1731  +     case GAIA_GEOMETRYCOLLECTIONZM:
         1732  +      use_config->has_z = 1;
         1733  +      use_config->has_m = 1;
         1734  +      break;
         1735  +    }
         1736  +    switch (*geometry_type)
         1737  +    {
         1738  +     case GAIA_POINTM:
         1739  +     case GAIA_LINESTRINGM:
         1740  +     case GAIA_POLYGONM:
         1741  +     case GAIA_MULTIPOINTM:
         1742  +     case GAIA_MULTILINESTRINGM:
         1743  +     case GAIA_MULTIPOLYGONM:
         1744  +     case GAIA_GEOMETRYCOLLECTIONM:
         1745  +      use_config->has_m = 1;
         1746  +      break;
         1747  +    }
         1748  +   }
         1749  +   if (( sqlite3_column_type( stmt, 4 ) != SQLITE_NULL ) &&
         1750  +       ( sqlite3_column_type( stmt, 5 ) != SQLITE_NULL ) &&
         1751  +       ( sqlite3_column_type( stmt, 6 ) != SQLITE_NULL ) &&
         1752  +       ( sqlite3_column_type( stmt, 7 ) != SQLITE_NULL ) &&
         1753  +       ( sqlite3_column_type( stmt, 8 ) != SQLITE_NULL ))
         1754  +   {
         1755  +    use_config->dem_extent_minx = sqlite3_column_double( stmt, 4 );
         1756  +    use_config->dem_extent_miny = sqlite3_column_double( stmt, 5 );
         1757  +    use_config->dem_extent_maxx = sqlite3_column_double( stmt, 6 );
         1758  +    use_config->dem_extent_maxy = sqlite3_column_double( stmt, 7 );
         1759  +    use_config->dem_rows_count = sqlite3_column_int64( stmt, 8 );
         1760  +   }
         1761  +  }
         1762  +  sqlite3_finalize( stmt );
         1763  +  if ((use_config->is_spatial_table == 1) && (use_config->has_z) && (use_config->dem_rows_count > 0))
         1764  +  {
         1765  +   ret=1; // Valid for usage
         1766  +  }
         1767  + }
         1768  + else
         1769  + {
         1770  +  if (verbose)
         1771  +  {
         1772  +   fprintf(stderr, "-W-> check_geometry_dimension: rc=%d sql[%s]\n",ret,sql_statement);
         1773  +  }
         1774  +  sqlite3_free(sql_statement);
         1775  + }
         1776  + return ret;
         1777  +}
         1778  +static void
         1779  +spatialite_autocreate(sqlite3 *db_handle)
         1780  +{
         1781  + /* attempting to perform self-initialization for a newly created DB */
         1782  + int ret;
         1783  + char sql[1024];
         1784  + char *err_msg = NULL;
         1785  + int count;
         1786  + int i;
         1787  + char **results;
         1788  + int rows;
         1789  + int columns;
         1790  +
         1791  + /* checking if this DB is really empty */
         1792  + strcpy(sql, "SELECT Count(*) from sqlite_master");
         1793  + ret = sqlite3_get_table(db_handle, sql, &results, &rows, &columns, NULL);
         1794  + if (ret != SQLITE_OK)
         1795  +  return;
         1796  + if (rows < 1)
         1797  +  ;
         1798  + else
         1799  + {
         1800  +  for (i = 1; i <= rows; i++)
         1801  +   count = atoi (results[(i * columns) + 0]);
         1802  + }
         1803  + sqlite3_free_table(results);
         1804  +
         1805  + if (count > 0)
         1806  +  return;
         1807  +
         1808  + /* all right, it's empty: proceding to initialize */
         1809  + strcpy(sql, "SELECT InitSpatialMetadataFull(1)");
         1810  + ret = sqlite3_exec(db_handle, sql, NULL, NULL, &err_msg);
         1811  + if (ret != SQLITE_OK)
         1812  + {
         1813  +  fprintf(stderr, "InitSpatialMetadataFull() error: %s\n", err_msg);
         1814  +  sqlite3_free(err_msg);
         1815  +  return;
         1816  + }
         1817  +}
         1818  +// -- -- ---------------------------------- --
         1819  +// Collecting a list of Dem-xyz file
         1820  +// - with checks on the first record
         1821  +// Case 1: a single xyz.file is given
         1822  +// -> the file will be checked and added to the list
         1823  +// Case 2: a directory is given
         1824  +// -> each file will be checked and added to the list
         1825  +// Case 3: a single list.file is given
         1826  +// - contains a list of single xyz.files to be read
         1827  +// -> expected to be inside the given directory
         1828  +// -> each file will be checked and added to the list
         1829  +// -- -- ---------------------------------- --
         1830  +// The list is the TABLE db_memory.xyz_files
         1831  +// Goal is to read the files in a specific order:
         1832  +// --> y='South to North' and x='West to East'
         1833  +// -- -- ---------------------------------- --
         1834  +static int
         1835  +collect_xyz_files(sqlite3 *db_handle,const char *xyz_filename, int *count_xyz_files, int verbose)
         1836  +{
         1837  + int ret=0;
         1838  + int i_count_fields=0;
         1839  + int i_count_fields_check=3;
         1840  + int ret_insert=SQLITE_OK;
         1841  + if (*count_xyz_files < 0)
         1842  + {
         1843  +  *count_xyz_files=0;
         1844  + }
         1845  + double point_x=0.0;
         1846  + double point_y=0.0;
         1847  + double point_z=0.0;
         1848  + char *sql_statement = NULL;
         1849  + int result_file_type=0;
         1850  + char *directory_from_filename = NULL;
         1851  +// -- -- ---------------------------------- --
         1852  + FILE *xyz_file = fopen(xyz_filename, "rt");
         1853  + if (xyz_file != NULL)
         1854  + {
         1855  +  if (verbose)
         1856  +  {
         1857  +   fprintf(stderr,"-I-> collect_xyz_files:reading xyz_filename[%s] \n", xyz_filename);
         1858  +  }
         1859  +  char line[MAXBUF];
         1860  +  while(fgets(line, sizeof(line), xyz_file) != NULL)
         1861  +  {
         1862  +   if (strcmp(line, "SQLite format 3") != 0)
         1863  +   {
         1864  +    line[strcspn(line, "\r\n")] = 0;
         1865  +    char *token;
         1866  +    char *ptr_strtod;
         1867  +    char *saveptr;
         1868  +    i_count_fields=0;
         1869  +    token = strtok_r(line, " ",&saveptr);
         1870  +    point_x=strtod(token, &ptr_strtod);
         1871  +    // atof will cause a signal 11 (SIGSEGV), if token does not contain a double
         1872  +    if ((int)strlen(ptr_strtod) == 0)
         1873  +    {
         1874  +     i_count_fields++;
         1875  +     while(token != NULL)
         1876  +     {
         1877  +      token = strtok_r(NULL," ",&saveptr);
         1878  +      switch (i_count_fields)
         1879  +      {
         1880  +       case 1:
         1881  +        point_y=strtod(token, &ptr_strtod);
         1882  +        if ((int)strlen(ptr_strtod) == 0)
         1883  +        {
         1884  +         i_count_fields++;
         1885  +        }
         1886  +        break;
         1887  +       case 2:
         1888  +        point_z=strtod(token, &ptr_strtod);
         1889  +        if ((int)strlen(ptr_strtod) == 0)
         1890  +        {
         1891  +         i_count_fields++;
         1892  +        }
         1893  +        break;
         1894  +      }
         1895  +     }
         1896  +    }
         1897  +    if (i_count_fields == 0)
         1898  +    {
         1899  +     // This may be a list of xyz.file-names,
         1900  +     // - contained in the same directory
         1901  +     // - that should be read [possibly not all of the xyz.files should be read]
         1902  +     // - order is not important, will be sorted by point_y ASC, point_x ASC of the first record
         1903  +     if (!directory_from_filename)
         1904  +     {
         1905  +      const char *slash = strrchr(xyz_filename,'/');
         1906  +      directory_from_filename=malloc(sizeof(char)*((slash-xyz_filename)+1));
         1907  +      strncpy(directory_from_filename,xyz_filename,slash-xyz_filename);
         1908  +      directory_from_filename[(slash-xyz_filename)]=0;
         1909  +     }
         1910  +     sql_statement = sqlite3_mprintf("%s/%s", directory_from_filename,token);
         1911  +     // the first record will be read. If 3 doubles, seperated by a space, can be created
         1912  +     // 1 : will be returned, after adding the path/file-name, point_x and point_y to db_memory.xyz_files
         1913  +     result_file_type=collect_xyz_files(db_handle,sql_statement, count_xyz_files, 0);
         1914  +     if (result_file_type == 1)
         1915  +     {//file_name has been added to db_memory.xyz_files
         1916  +      ret=1; // xyz-format
         1917  +     }
         1918  +     sqlite3_free(sql_statement);
         1919  +    }
         1920  +    if (i_count_fields == i_count_fields_check)
         1921  +    {
         1922  +     sql_statement = sqlite3_mprintf("INSERT INTO db_memory.xyz_files (point_x,point_y,file_name) "
         1923  +                                     "VALUES(%2.7f,%2.7f,'%s') ",point_x,point_y,xyz_filename);
         1924  +     if (db_handle)
         1925  +     {
         1926  +      if (sqlite3_exec(db_handle, sql_statement, NULL, NULL, NULL) == SQLITE_OK)
         1927  +      {
         1928  +       *count_xyz_files+=1; // xyz-format
         1929  +       result_file_type=1;
         1930  +      }
         1931  +     }
         1932  +     sqlite3_free(sql_statement);
         1933  +     ret_insert = SQLITE_ABORT;
         1934  +    }
         1935  +    if (verbose)
         1936  +    {
         1937  +     fprintf(stderr,"-I->  collect_xyz_files: i_count_fields[%d] check[%d] count_files[%d]\n", i_count_fields,i_count_fields_check,*count_xyz_files);
         1938  +    }
         1939  +   }
         1940  +   else
         1941  +   {
         1942  +    result_file_type=2; // Sqlite3-format
         1943  +   }
         1944  +   if (ret_insert == SQLITE_ABORT )
         1945  +   {
         1946  +    break;
         1947  +   }
         1948  +   if (ret_insert != SQLITE_ABORT )
         1949  +   {
         1950  +    // if this is a list of .xyz files that are being added,
         1951  +    // result_file_type will be 1, but not SQLITE_ABORT
         1952  +    // - since all entries must be read
         1953  +    if (result_file_type != 1)
         1954  +    {
         1955  +     break; // unknown format
         1956  +    }
         1957  +   }
         1958  +  } // End while
         1959  +  fclose(xyz_file);
         1960  +  if (directory_from_filename)
         1961  +  {
         1962  +   free(directory_from_filename);
         1963  +   directory_from_filename=NULL;
         1964  +  }
         1965  + } // Checking for a file
         1966  + else
         1967  + {
         1968  +#if defined(_WIN32) && !defined(__MINGW32__)
         1969  +  /* Visual Studio .NET */
         1970  +  struct _finddata_t c_file;
         1971  +  intptr_t hFile;
         1972  +  char *name;
         1973  +  int len;
         1974  +  int ret;
         1975  +  if (_chdir (in_dir) < 0)
         1976  +   return ret;
         1977  +  if ((hFile = _findfirst ("*.xyz", &c_file)) == -1L)
         1978  +   ;
         1979  +  else
         1980  +  {
         1981  +   while (1)
         1982  +   {// A directory with .xyz files
         1983  +    if ((c_file.attrib & _A_RDONLY) == _A_RDONLY  || (c_file.attrib & _A_NORMAL) == _A_NORMAL)
         1984  +    {
         1985  +     sql_statement = sqlite3_mprintf("%s/%s", xyz_filename,c_file.name);
         1986  +     if (collect_xyz_files(db_handle,sql_statement, count_xyz_files, 0) == 1)
         1987  +     {//file_name has been added to db_memory.xyz_files
         1988  +     }
         1989  +     sqlite3_free(sql_statement);
         1990  +    }
         1991  +    if (_findnext (hFile, &c_file) != 0)
         1992  +     break;
         1993  +   }
         1994  +   _findclose (hFile);
         1995  +  }
         1996  +#else
         1997  +  DIR *xyz_dir = opendir(xyz_filename);
         1998  +  struct dirent *dir;
         1999  +  if (xyz_dir)
         2000  +  {
         2001  +   while ((dir = readdir(xyz_dir)) != NULL)
         2002  +   {
         2003  +    if (dir->d_type == DT_REG)
         2004  +    {
         2005  +     const char *ext = strrchr(dir->d_name,'.');
         2006  +     if ((ext) || (ext != dir->d_name))
         2007  +     {
         2008  +      if (strcmp(ext, ".xyz") == 0)
         2009  +      {// A directory with .xyz files
         2010  +       // - order is not important, will be sorted by point_y ASC, point_x ASC of the first record
         2011  +       sql_statement = sqlite3_mprintf("%s/%s", xyz_filename,dir->d_name);
         2012  +       // the first record will be read. If 3 doubles, seperated by a space, can be created
         2013  +       // 1 : will be returned, after adding the path/file-name, point_x and point_y to db_memory.xyz_files
         2014  +       result_file_type=collect_xyz_files(db_handle,sql_statement, count_xyz_files, 0);
         2015  +       if (result_file_type == 1)
         2016  +       {//file_name has been added to db_memory.xyz_files
         2017  +       }
         2018  +       sqlite3_free(sql_statement);
         2019  +      }
         2020  +     }
         2021  +    }
         2022  +   }
         2023  +   closedir(xyz_dir);
         2024  +  } // Checking for a directory
         2025  +#endif
         2026  + }
         2027  +// -- -- ---------------------------------- --
         2028  + if (*count_xyz_files > 0)
         2029  + {
         2030  +  ret=1; // xyz-format
         2031  + }
         2032  + else
         2033  + {
         2034  +  ret=0; // not supported
         2035  +  if (verbose)
         2036  +  {
         2037  +   fprintf(stderr,"-E-> collect_xyz_files: import.xyz file format not found [%s]\n", xyz_filename);
         2038  +  }
         2039  + }
         2040  +// -- -- ---------------------------------- -
         2041  + return ret;
         2042  +}
         2043  +// -- -- ---------------------------------- --
         2044  +// Read list of Dem-xyz files
         2045  +// - from db_memory.xyz_files
         2046  +// Goal is to INSERT the points in a specific order:
         2047  +// --> y='South to North' and x='West to East'
         2048  +// -- -- ---------------------------------- --
         2049  +static int
         2050  +import_xyz(sqlite3 *db_handle, struct config_dem *dem_config, int count_xyz_files, int verbose)
         2051  +{
         2052  + int ret=0;
         2053  + int ret_select=0;
         2054  + sqlite3_stmt *stmt = NULL;
         2055  + char *sql_statement = NULL;
         2056  + int i_count_loop=100000;
         2057  + int i_count_fields=0;
         2058  + int i_count_fields_check=3;
         2059  + int i_count_in_loop=0;
         2060  + int i_file_count=0;
         2061  + const char *xyz_path_filename;
         2062  +// 18.446.744.073.709.551.615
         2063  + unsigned int i_sleep=1; // 1 second
         2064  + double point_x=0.0;
         2065  + double point_y=0.0;
         2066  + double point_z=0.0;
         2067  + double *xx = NULL;
         2068  + double *yy = NULL;
         2069  + double *zz = NULL;
         2070  + int ret_insert=SQLITE_OK;
         2071  + if (count_xyz_files > 0)
         2072  + {// input-files should be sorted from y='South to North' and x='West to East':  sort -n -k2 -k1 input_file.xyz -o output_file.sort.xyz
         2073  +  // Select files sorted by y='South to North' and x='West to East'
         2074  +  sql_statement = sqlite3_mprintf("SELECT file_name FROM db_memory.xyz_files ORDER BY point_y ASC, point_x ASC");
         2075  +  ret_select = sqlite3_prepare_v2(db_handle, sql_statement, -1, &stmt, NULL );
         2076  +  sqlite3_free(sql_statement);
         2077  +  if ( ret_select == SQLITE_OK )
         2078  +  {
         2079  +   while ( sqlite3_step( stmt ) == SQLITE_ROW )
         2080  +   {
         2081  +    if ( sqlite3_column_type( stmt, 0 ) != SQLITE_NULL )
         2082  +    {
         2083  +     xyz_path_filename=(const char *) sqlite3_column_text (stmt, 0);
         2084  +     // -- -- ---------------------------------- --
         2085  +     FILE *xyz_file = fopen(xyz_path_filename, "rt");
         2086  +     if (xyz_file != NULL)
         2087  +     {
         2088  +      char line[MAXBUF];
         2089  +      i_file_count++;
         2090  +      i_count_in_loop=0;
         2091  +      if (verbose)
         2092  +      {
         2093  +       // CPU: 4-11% ; memory 9.3 Ḿib ; normal working with mouse and applications
         2094  +       fprintf(stderr,"import_xyz: reading  xyz_filename[%s]\n (file %d of %d) in steps of [%u].\n",xyz_path_filename,i_file_count,count_xyz_files, i_count_loop);
         2095  +      }
         2096  +      xx = malloc(sizeof (double) * i_count_loop);
         2097  +      yy = malloc(sizeof (double) * i_count_loop);
         2098  +      zz = malloc(sizeof (double) * i_count_loop);
         2099  +      while(fgets(line, sizeof(line), xyz_file) != NULL)
         2100  +      {
         2101  +       line[strcspn(line, "\r\n")] = 0;
         2102  +       char *token;
         2103  +       char *ptr_strtod;
         2104  +       char *saveptr;
         2105  +       i_count_fields=0;
         2106  +       token = strtok_r(line, " ",&saveptr);
         2107  +       point_x=strtod(token, &ptr_strtod);
         2108  +       // atof will cause a signal 11 (SIGSEGV), if token does not contain a double
         2109  +       if ((int)strlen(ptr_strtod) == 0)
         2110  +       {
         2111  +        i_count_fields++;
         2112  +        while(token != NULL)
         2113  +        {
         2114  +         token = strtok_r(NULL," ",&saveptr);
         2115  +         switch (i_count_fields)
         2116  +         {
         2117  +          case 1:
         2118  +           point_y=strtod(token, &ptr_strtod);
         2119  +           if ((int)strlen(ptr_strtod) == 0)
         2120  +           {
         2121  +            i_count_fields++;
         2122  +           }
         2123  +           break;
         2124  +          case 2:
         2125  +           point_z=strtod(token, &ptr_strtod);
         2126  +           if ((int)strlen(ptr_strtod) == 0)
         2127  +           {
         2128  +            i_count_fields++;
         2129  +           }
         2130  +           break;
         2131  +         }
         2132  +        }
         2133  +       }
         2134  +       if (i_count_fields == i_count_fields_check)
         2135  +       {
         2136  +        if (i_count_in_loop < i_count_loop)
         2137  +        {
         2138  +         xx[i_count_in_loop]=point_x;
         2139  +         yy[i_count_in_loop]=point_y;
         2140  +         zz[i_count_in_loop]=point_z;
         2141  +         i_count_in_loop++;
         2142  +        }
         2143  +        if (i_count_in_loop == i_count_loop)
         2144  +        {
         2145  +         dem_config->count_points=i_count_in_loop;
         2146  +         if (!insert_dem_points(db_handle, dem_config, xx, yy, zz, verbose))
         2147  +         {
         2148  +          // Inserting failed, abort
         2149  +          ret_insert = SQLITE_ABORT;
         2150  +         }
         2151  +         else
         2152  +         {
         2153  +          if (verbose)
         2154  +          {
         2155  +           fprintf(stderr,"\r inserted [%u] ... ", dem_config->dem_rows_count);
         2156  +          }
         2157  +         }
         2158  +         // xx,yy,zz values are reset to 0.0 in insert_dem_points
         2159  +         i_count_in_loop=0;
         2160  +         sleep(i_sleep);
         2161  +        }
         2162  +       }
         2163  +       else
         2164  +       {
         2165  +        ret_insert = SQLITE_ABORT;
         2166  +       }
         2167  +       if (ret_insert == SQLITE_ABORT )
         2168  +       {
         2169  +        break;
         2170  +       }
         2171  +      } // End while
         2172  +      fclose(xyz_file);
         2173  +      // -- -- ---------------------------------- --
         2174  +      // Complete what is left over, when no abort
         2175  +      // -- -- ---------------------------------- --
         2176  +      if (ret_insert != SQLITE_ABORT )
         2177  +      {
         2178  +       ret=1;
         2179  +       if ( i_count_in_loop < i_count_loop)
         2180  +       {
         2181  +        ret=0;
         2182  +        dem_config->count_points=i_count_in_loop;
         2183  +        fprintf(stderr,"import_xyz: calling insert_dem_points: i_count_in_loop[%d].\n",dem_config->count_points);
         2184  +        if (insert_dem_points(db_handle, dem_config, xx, yy, zz, verbose))
         2185  +        {
         2186  +         ret=1;
         2187  +         if (verbose)
         2188  +         {
         2189  +          fprintf(stderr,"\r file%d: inserting compleated [%u]\n",i_file_count, dem_config->dem_rows_count);
         2190  +         }
         2191  +        }
         2192  +       }
         2193  +      }
         2194  +      // -- -- ---------------------------------- --
         2195  +      // clean up
         2196  +      // -- -- ---------------------------------- --
         2197  +      if (xx)
         2198  +      {
         2199  +       free(xx);
         2200  +       xx=NULL;
         2201  +      }
         2202  +      if (yy)
         2203  +      {
         2204  +       free(yy);
         2205  +       yy=NULL;
         2206  +      }
         2207  +      if (zz)
         2208  +      {
         2209  +       free(zz);
         2210  +       zz=NULL;
         2211  +      }
         2212  +     }
         2213  +     else
         2214  +     {
         2215  +      if (verbose)
         2216  +      {
         2217  +       fprintf(stderr,"-E-> import_xyz: import.xyz file not found [%s]\n", xyz_path_filename);
         2218  +      }
         2219  +     }
         2220  +    }
         2221  +   }
         2222  +   sqlite3_finalize( stmt );
         2223  +  }
         2224  + }
         2225  +// -- -- ---------------------------------- --
         2226  + return ret;
         2227  +}
         2228  +// -- -- ---------------------------------- --
         2229  +// Recover Dem-Geometry with SpatialIndex
         2230  +// - recovering a full Geometry Column
         2231  +// -- -- ---------------------------------- --
         2232  +static int
         2233  +recover_geometry_dem(sqlite3 *db_handle, struct config_dem *dem_config, int verbose)
         2234  +{
         2235  + /* recovering a full Geometry Column */
         2236  + int ret;
         2237  + char *err_msg;
         2238  + char *sql_statement = NULL;
         2239  + if (verbose)
         2240  + {
         2241  +  fprintf(stderr,"Recovering Geometry:    %s(%s) as POINTZ with srid=%d\n", dem_config->dem_table,dem_config->dem_geometry, dem_config->dem_srid);
         2242  + }
         2243  + sql_statement = sqlite3_mprintf("SELECT RecoverGeometryColumn(%Q, %Q, %d, %Q, %Q)",
         2244  +                                 dem_config->dem_table,dem_config->dem_geometry, dem_config->dem_srid, "POINT", "XYZ");
         2245  + ret = sqlite3_exec(db_handle, sql_statement, NULL, NULL, &err_msg);
         2246  + sqlite3_free(sql_statement);
         2247  + if (ret != SQLITE_OK)
         2248  + {
         2249  +  if (verbose)
         2250  +  {
         2251  +   fprintf(stderr, "RecoverGeometryColumn error: %s\n", err_msg);
         2252  +  }
         2253  +  sqlite3_free(err_msg);
         2254  +  return 0;
         2255  + }
         2256  + if (verbose)
         2257  + {
         2258  +  fprintf(stderr, "Creating Spatial Index: %s(%s)\n", dem_config->dem_table,dem_config->dem_geometry);
         2259  + }
         2260  + sql_statement = sqlite3_mprintf("SELECT CreateSpatialIndex(%Q, %Q)", dem_config->dem_table,dem_config->dem_geometry);
         2261  + ret = sqlite3_exec(db_handle, sql_statement, NULL, NULL, &err_msg);
         2262  + sqlite3_free(sql_statement);
         2263  + if (ret != SQLITE_OK)
         2264  + {
         2265  +  fprintf(stderr, "CreateSpatialIndex error: %s\n", err_msg);
         2266  +  sqlite3_free(err_msg);
         2267  +  return 0;
         2268  + }
         2269  + if (verbose)
         2270  + {
         2271  +  fprintf(stderr,"UpdateLayerStatistics:  %s(%s)\n", dem_config->dem_table,dem_config->dem_geometry);
         2272  + }
         2273  + sql_statement = sqlite3_mprintf("SELECT UpdateLayerStatistics(%Q, %Q)", dem_config->dem_table,dem_config->dem_geometry);
         2274  + ret = sqlite3_exec(db_handle, sql_statement, NULL, NULL, &err_msg);
         2275  + sqlite3_free(sql_statement);
         2276  + if (ret != SQLITE_OK)
         2277  + {
         2278  +  fprintf(stderr, "UpdateLayerStatistics error: %s\n", err_msg);
         2279  +  sqlite3_free(err_msg);
         2280  +  return 0;
         2281  + }
         2282  + return 1;
         2283  +}
         2284  +// -- -- ---------------------------------- --
         2285  +// Create the Database for Dem
         2286  +// - CREATE TABLE for minimal Dem-Data
         2287  +// -> db_memory.xyz_files
         2288  +// -- -- ---------------------------------- --
         2289  +static int
         2290  +create_dem_db(const char *path_dem, sqlite3 ** handle, void *cache, const char *table_dem, const char *column_dem, int verbose)
         2291  +{
         2292  + /* opening the DB */
         2293  + sqlite3 *db_handle = NULL;
         2294  + int ret=0;
         2295  + char *sql_statement = NULL;
         2296  + *handle = NULL;
         2297  + if ( verbose )
         2298  + {
         2299  +  fprintf(stderr,"SQLite version: %s\n", sqlite3_libversion());
         2300  +  fprintf(stderr,"SpatiaLite version: %s\n\n", spatialite_version());
         2301  + }
         2302  + FILE *db_file = fopen(path_dem, "r");
         2303  + if (db_file != NULL)
         2304  + {
         2305  +  fclose(db_file);
         2306  +  return ret;
         2307  + }
         2308  + ret = sqlite3_open_v2(path_dem, &db_handle, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL);
         2309  + if (ret != SQLITE_OK)
         2310  + {
         2311  +  fprintf(stderr, "cannot open '%s': %s\n", path_dem, sqlite3_errmsg (db_handle));
         2312  +  sqlite3_close(db_handle);
         2313  +  return ret;
         2314  + }
         2315  + spatialite_init_ex(db_handle, cache, 0);
         2316  + spatialite_autocreate(db_handle);
         2317  + if ( (table_dem) && ( column_dem ) )
         2318  + {
         2319  +  sql_statement = sqlite3_mprintf("CREATE TABLE \"%s\" ("
         2320  +                                  "id_dem INTEGER PRIMARY KEY AUTOINCREMENT, "
         2321  +                                  "point_x DOUBLE DEFAULT 0, "
         2322  +                                  "point_y DOUBLE DEFAULT 0, "
         2323  +                                  "point_z DOUBLE DEFAULT 0, "
         2324  +                                  "%s BLOB DEFAULT NULL)"
         2325  +                                  ,table_dem, column_dem);
         2326  +  ret = sqlite3_exec(db_handle, sql_statement, NULL, NULL, NULL);
         2327  +  if (ret != SQLITE_OK)
         2328  +  {
         2329  +   fprintf(stderr, "cannot CREATE Table: '%s' sql[%s]\n\t: %s\n", table_dem, sql_statement, sqlite3_errmsg (db_handle));
         2330  +   sqlite3_free(sql_statement);
         2331  +   sqlite3_close(db_handle);
         2332  +   return ret;
         2333  +  }
         2334  +  sqlite3_free(sql_statement);
         2335  +  if (verbose)
         2336  +  {
         2337  +   fprintf(stderr,"Created table(geometry):  %s(%s)\n", table_dem, column_dem);
         2338  +  }
         2339  +  sql_statement = sqlite3_mprintf("ATTACH DATABASE ':memory:' AS db_memory");
         2340  +  ret = sqlite3_exec(db_handle, sql_statement, NULL, NULL, NULL);
         2341  +  sqlite3_free(sql_statement);
         2342  +  if (ret == SQLITE_OK)
         2343  +  {
         2344  +   sql_statement = sqlite3_mprintf("CREATE TABLE db_memory.xyz_files ("
         2345  +                                   "file_name TEXT DEFAULT '', "
         2346  +                                   "point_x DOUBLE DEFAULT 0, "
         2347  +                                   "point_y DOUBLE DEFAULT 0)");
         2348  +   ret = sqlite3_exec(db_handle, sql_statement, NULL, NULL, NULL);
         2349  +   sqlite3_free(sql_statement);
         2350  +   if (ret != SQLITE_OK)
         2351  +   {
         2352  +   }
         2353  +  }
         2354  + }
         2355  + *handle = db_handle;
         2356  + ret=1;
         2357  + return ret;
         2358  +}
         2359  +// -- -- ---------------------------------- --
         2360  +// Close the Database
         2361  +// - DETACH a connected Database if needed
         2362  +// -> db_memory
         2363  +// -- -- ---------------------------------- --
         2364  +static void
         2365  +close_db(sqlite3 *db_handle, void *cache, const char *schema_dem)
         2366  +{
         2367  + char *sql_statement = NULL;
         2368  + int ret=0;
         2369  + if (schema_dem)
         2370  + {
         2371  +  if (strcmp(schema_dem, "main") != 0)
         2372  +  {
         2373  +   sql_statement = sqlite3_mprintf("DETACH  DATABASE  %s", schema_dem);
         2374  +   ret = sqlite3_exec(db_handle, sql_statement, NULL, NULL, NULL);
         2375  +   sqlite3_free(sql_statement);
         2376  +  }
         2377  + }
         2378  + sql_statement = sqlite3_mprintf("DETACH  DATABASE  db_memory");
         2379  + ret = sqlite3_exec(db_handle, sql_statement, NULL, NULL, NULL);
         2380  + sqlite3_free(sql_statement);
         2381  + sqlite3_close(db_handle);
         2382  + if (cache)
         2383  + {
         2384  +  spatialite_cleanup_ex(cache);
         2385  + }
         2386  + spatialite_shutdown();
         2387  + return;
         2388  +}
         2389  +// -- -- ---------------------------------- --
         2390  +// Open the Database
         2391  +// - ATTACH a connected Database if needed
         2392  +// While 'sniffing' a second source may not be needed
         2393  +// - CREATE TABLE for minimal Dem-Data
         2394  +// -> db_memory.xyz_files
         2395  +// -- -- ---------------------------------- --
         2396  +static int
         2397  +open_db(sqlite3 **handle, void *cache, struct config_dem *source_config, struct config_dem *dem_config, int verbose)
         2398  +{
         2399  + /* opening the DB */
         2400  + sqlite3 *db_handle = NULL;
         2401  + int ret=0;
         2402  + char *sql_statement = NULL;
         2403  + const char *path_db=NULL;
         2404  + const char *path_attach=NULL;
         2405  + const char *schema_db=NULL;
         2406  + const char *schema_attach=NULL;
         2407  + *handle = NULL;
         2408  + if ( verbose )
         2409  + {
         2410  +  fprintf(stderr,"SQLite version: %s\n", sqlite3_libversion());
         2411  +  fprintf(stderr,"SpatiaLite version: %s\n\n", spatialite_version());
         2412  + }
         2413  + if ((strlen(dem_config->dem_path) > 0) && ( (source_config) && (strlen(source_config->dem_path) == 0)))
         2414  + {
         2415  +  // Open the Dem-Database as source [sniff without source or fetchz]
         2416  +  path_db=dem_config->dem_path;
         2417  +  dem_config->schema="main";
         2418  +  schema_attach=dem_config->schema;
         2419  + }
         2420  + else
         2421  + {
         2422  +  path_db=source_config->dem_path;
         2423  +  schema_db=source_config->schema;
         2424  +  path_attach=dem_config->dem_path;
         2425  +  schema_attach=dem_config->schema;
         2426  + }
         2427  + ret = sqlite3_open_v2(path_db, &db_handle, SQLITE_OPEN_READWRITE, NULL);
         2428  + if (ret != SQLITE_OK)
         2429  + {
         2430  +  fprintf(stderr, "cannot open '%s': %s\n", path_db, sqlite3_errmsg (db_handle));
         2431  +  close_db(db_handle, cache, NULL);
         2432  +  return 0;
         2433  + }
         2434  + if (path_attach)
         2435  + {
         2436  +  sql_statement = sqlite3_mprintf("ATTACH DATABASE \"%s\" AS %s",path_attach, schema_attach);
         2437  +  ret = sqlite3_exec(db_handle, sql_statement, NULL, NULL, NULL);
         2438  +  if (ret != SQLITE_OK)
         2439  +  {
         2440  +   fprintf(stderr, "cannot ATTACH Database: '%s' sql[%s]\n\t: %s\n", path_attach, sql_statement, sqlite3_errmsg (db_handle));
         2441  +   sqlite3_free(sql_statement);
         2442  +   close_db(db_handle, cache, NULL);
         2443  +   return 0;
         2444  +  }
         2445  +  sqlite3_free(sql_statement);
         2446  + }
         2447  + sql_statement = sqlite3_mprintf("ATTACH DATABASE ':memory:' AS db_memory");
         2448  + ret = sqlite3_exec(db_handle, sql_statement, NULL, NULL, NULL);
         2449  + sqlite3_free(sql_statement);
         2450  + if (ret == SQLITE_OK)
         2451  + {
         2452  +  sql_statement = sqlite3_mprintf("CREATE TABLE db_memory.xyz_files ("
         2453  +                                  "file_name TEXT DEFAULT '', "
         2454  +                                  "point_x DOUBLE DEFAULT 0, "
         2455  +                                  "point_y DOUBLE DEFAULT 0)");
         2456  +  ret = sqlite3_exec(db_handle, sql_statement, NULL, NULL, NULL);
         2457  +  sqlite3_free(sql_statement);
         2458  +  if (ret != SQLITE_OK)
         2459  +  {
         2460  +  }
         2461  + }
         2462  + spatialite_init_ex(db_handle, cache, 0);
         2463  + *handle = db_handle;
         2464  + return 1;
         2465  +}
         2466  +// -- -- ---------------------------------- --
         2467  +// Help Messages
         2468  +// -- -- ---------------------------------- --
         2469  +static void
         2470  +do_help()
         2471  +{
         2472  + /* printing the argument list */
         2473  + fprintf(stderr, "\n\nusage: spatialite_dem ARGLIST\n");
         2474  + fprintf(stderr,  "==============================================================\n");
         2475  + fprintf(stderr,  "-h or --help                    print this help message\n");
         2476  + fprintf(stderr, "========================== Parameters ========================\n");
         2477  + fprintf(stderr, "  -- -- ---------------- Dem-Data Database ---------------- --\n");
         2478  + fprintf(stderr, "-ddem or --dem-path  pathname to the SpatiaLite Dem DB \n");
         2479  + fprintf(stderr, "-tdem or --table-dem table_name [SpatialTable or SpatialView]\n");
         2480  + fprintf(stderr, "-gdem or --geometry-dem-column col_name the Geometry column\n");
         2481  + fprintf(stderr, "\t must be a POINT Z or a POINT ZM type\n");
         2482  + fprintf(stderr, "-rdem or --dem-resolution of the dem points while searching\n");
         2483  + fprintf(stderr, "\t the automatic resolution calculation is based on the row_count\n");
         2484  + fprintf(stderr, "\t within the extent, which may not be correct!\n");
         2485  + fprintf(stderr, "\t Use '-rdem' to set a realistic value\n");
         2486  + fprintf(stderr, "\n  -- -- ----------------- Source Database ----------------- --\n");
         2487  + fprintf(stderr, "-d or --db-path pathname to the SpatiaLite DB\n");
         2488  + fprintf(stderr, "-t or --table table_name,  must be a SpatialTable\n");
         2489  + fprintf(stderr, "-g or --geometry-column the Geometry column to update\n");
         2490  + fprintf(stderr, "\t must  be a Z or a ZM Dimension type\n\t use CastToXYZ(geom) or CastToXYZM(geom) to convert \n");
         2491  + fprintf(stderr, "  -- -- --------------- General Parameters ---------------- --\n");
         2492  + fprintf(stderr, "-mdem or --copy-m [0=no, 1= yes [default] if exists]\n");
         2493  + fprintf(stderr, "-default_srid or --srid for use with -fetchz\n");
         2494  + fprintf(stderr, "-fetchz_xy x- and y-value for use with -fetchz\n");
         2495  + fprintf(stderr, "-v or  --verbose messages during -updatez and -fetchz\n");
         2496  + fprintf(stderr, "-save_conf based on active -ddem , -tdem, -gdem and -srid when valid\n");
         2497  + fprintf(stderr, "\n  -- -- -------------------- Notes:  ---------------------- --\n");
         2498  + fprintf(stderr, "-I-> the Z value will be copied from the nearest point found\n");
         2499  + fprintf(stderr, "-I-> the Srid of the source Geometry and the Dem-POINT can be different\n");
         2500  + fprintf(stderr, "-I-> when -fetchz_xy is used in a bash script, -v should not be used\n");
         2501  + fprintf(stderr, "\t the z-value will then be retured as the result\n");
         2502  + fprintf(stderr, "\n  -- -- -------------------- Conf file:  ------------------- --\n");
         2503  + fprintf(stderr, "-I-> if 'SPATIALITE_DEM' is set with the path to a file\n");
         2504  + fprintf(stderr, "-I--> 'export SPATIALITE_DEM=/long/path/to/file/berlin_dhh92.conf'\n");
         2505  + fprintf(stderr, "-I-> then '-save_conf' save the config to that file\n");
         2506  + fprintf(stderr, "-I-> this file will be read on each application start, setting those values\n");
         2507  + fprintf(stderr, "-I--> the parameters for :\n");
         2508  + fprintf(stderr, "\t  which Dem-Database and Geometry and the default_srid to use for queries\n");
         2509  + fprintf(stderr, "\t  -> would then not be needed\n");
         2510  + fprintf(stderr, "\n  -- -- ---------------- Importing .xyz files:  ------------------- --\n");
         2511  + fprintf(stderr, "-I-> a single xyz.file or a directory containing .xyz files can be given\n");
         2512  + fprintf(stderr, "\t for directories: only files with the extension .xyz will be searched for\n");
         2513  + fprintf(stderr, "-I-> a single list.file inside a directory containing .xyz files can be given\n");
         2514  + fprintf(stderr, "\t each line containing the file-name that must exist in that directory\n");
         2515  + fprintf(stderr, "-I-> validty checks are done before importing xyz-files\n");
         2516  + fprintf(stderr, "\t the first line may contain only 3 double values (point_x/y/z)\n");
         2517  + fprintf(stderr, "\t if valid, the file-name and the point_x/y points are stored\n");
         2518  + fprintf(stderr, "\t when importing, the list will be read based of the y/x points\n");
         2519  + fprintf(stderr, "\n  -- -- ---------------- Sorting .xyz files:  ---------------------- --\n");
         2520  + fprintf(stderr, "-I->  xyz.files should be sorted:\n");
         2521  + fprintf(stderr, "\t y='South to North' and x='West to East': \n");
         2522  + fprintf(stderr, "\t sort -n -k2 -k1 input_file.xyz -o output_file.sort.xyz");
         2523  + fprintf(stderr, "\n=========================== Commands ===========================\n");
         2524  + fprintf(stderr, "-sniff   [default] analyse settings without UPDATE of z-values \n");
         2525  + fprintf(stderr, "-updatez Perform UPDATE of z-values \n");
         2526  + fprintf(stderr, "-fetchz Perform Query of z-values using  -fetchz_x_y and default_srid\n");
         2527  + fprintf(stderr, "\t will be assumed when using  -fetchz_x_y\n");
         2528  + fprintf(stderr, "-create_dem create Dem-Database using -ddem,-tdem, -gdem and -srid for the Database \n");
         2529  + fprintf(stderr, "\t -d as a dem.xyz file \n");
         2530  + fprintf(stderr, "-import_xyz import another .xyz file into a Dem-Database created with -create_dem \n");
         2531  + fprintf(stderr, "\t these points will not be sorted, but added to the end ");
         2532  + fprintf(stderr, "\n=========================== Sample ===========================\n");
         2533  + fprintf(stderr, "--> with 'SPATIALITE_DEM' set: \n");
         2534  + fprintf(stderr, "spatialite_dem -fetchz_xy  24700.55278283251 20674.74537357586\n");
         2535  + fprintf(stderr, "33.5600000 \n");
         2536  + fprintf(stderr,  "==============================================================\n");
         2537  +}
         2538  +// -- -- ---------------------------------- --
         2539  +// Checking the status of the Dem-Database
         2540  +// - used by differenct command types
         2541  +// -- -- ---------------------------------- --
         2542  +static int
         2543  +command_check_source_db(sqlite3 *db_handle, struct config_dem*source_config, struct config_dem*dem_config, int verbose)
         2544  +{
         2545  + int ret=0;
         2546  + int geometry_type=0;
         2547  + if (strlen(source_config->dem_path) > 0)
         2548  +// -- -- ---------------------------------- --
         2549  +  if ((strlen(source_config->dem_path) > 0) && (strlen(source_config->dem_table) > 0) && (strlen(source_config->dem_geometry) > 0))
         2550  +  {
         2551  +   if (check_geometry_dimension(db_handle,source_config, &geometry_type,verbose))
         2552  +   {
         2553  +    if (verbose)
         2554  +    {
         2555  +     fprintf(stderr,"Source: srid %d\n", source_config->default_srid);
         2556  +     fprintf(stderr,"Source: extent min x/y(%2.7f,%2.7f)\n\t       max x/y(%2.7f,%2.7f)\n",
         2557  +             source_config->dem_extent_minx,source_config->dem_extent_miny,
         2558  +             source_config->dem_extent_maxx,source_config->dem_extent_maxy);
         2559  +     fprintf(stderr,"Source: rows_count(%s) %d\n",source_config->dem_geometry, source_config->dem_rows_count);
         2560  +     fprintf(stderr,"Source: geometry_type(%d) has_z[%d]\n",geometry_type,source_config->has_z);
         2561  +     fprintf(stderr,"Source: spatial_index_enabled[%d]\n",source_config->has_spatial_index);
         2562  +    }
         2563  +    if (source_config->is_spatial_table == 1)
         2564  +    {
         2565  +     if (source_config->has_z)
         2566  +     {// The source Database Table and geometry-columns exists and contains a z-value dimension.
         2567  +      ret = 0;
         2568  +      if (verbose)
         2569  +      {
         2570  +       fprintf(stderr,"Source '%s'\n", source_config->dem_path);
         2571  +       fprintf(stderr," will set %s(%s) Z-Values\n\tfrom nearest POINT found in\n",source_config->dem_table, source_config->dem_geometry);
         2572  +      }
         2573  +     }
         2574  +     else
         2575  +     {
         2576  +      ret = -1;
         2577  +      if (verbose)
         2578  +      {
         2579  +       fprintf(stderr, "DB '%s'\n", source_config->dem_path);
         2580  +       fprintf(stderr, "TABLE[%s] or GEOMETRY-Column[%s] does not contained in a SpatialTable [will not update]\n",source_config->dem_table, source_config->dem_geometry);
         2581  +       fprintf(stderr, "\t command_check_source_db failed: sorry, cowardly quitting\n\n");
         2582  +      }
         2583  +     }
         2584  +    }
         2585  +    else
         2586  +    {
         2587  +     ret = -1;
         2588  +     if (verbose)
         2589  +     {
         2590  +      fprintf(stderr, "DB '%s'\n", source_config->dem_path);
         2591  +      fprintf(stderr, "TABLE[%s] or GEOMETRY-Column[%s] does not contain a Z-Dimension\n",source_config->dem_table, source_config->dem_geometry);
         2592  +      fprintf(stderr, "\t command_check_source_db failed: sorry, cowardly quitting\n\n");
         2593  +     }
         2594  +    }
         2595  +   }
         2596  +   else
         2597  +   {// The source Database Table or geometry-columns does not exist.
         2598  +    ret = -1;
         2599  +    if (verbose)
         2600  +    {
         2601  +     fprintf(stderr, "DB '%s'\n", source_config->dem_path);
         2602  +     fprintf(stderr, "TABLE[%s] or GEOMETRY-Column[%s] not found\n",source_config->dem_table, source_config->dem_geometry);
         2603  +     fprintf(stderr, "\t check_geometry_dimension failed: sorry, cowardly quitting\n\n");
         2604  +    }
         2605  +   }
         2606  +   if (ret == 0)
         2607  +   {
         2608  +    if (verbose)
         2609  +    {
         2610  +     fprintf(stderr, "Source Database: has passed all checks.\n\n");
         2611  +    }
         2612  +   }
         2613  +  }
         2614  +  else
         2615  +  {
         2616  +   if ((strlen(source_config->dem_path) > 0) && (strcmp(source_config->dem_path,".xyz") != 1))
         2617  +   {
         2618  +    if (verbose)
         2619  +    {
         2620  +     fprintf(stderr,"-E-> command_check_source_db: preconditions failed for check_source_db [%s(%s)]\n\t source[%s] \n",source_config->dem_table, source_config->dem_geometry,source_config->dem_path);
         2621  +    }
         2622  +   }
         2623  +  }
         2624  +// -- -- ---------------------------------- --
         2625  + return ret;
         2626  +}
         2627  +// -- -- ---------------------------------- --
         2628  +// Checking the status of the Dem-Database
         2629  +// - used by differenct command types
         2630  +// -- -- ---------------------------------- --
         2631  +static int
         2632  +command_check_dem_db(sqlite3 *db_handle, struct config_dem*dem_config, struct config_dem*source_config, int verbose)
         2633  +{
         2634  + int ret=0;
         2635  + double resolution_calc=0.0;
         2636  + double resolution_dem=dem_config->dem_resolution;
         2637  + int geometry_type=0;
         2638  +// -- -- ---------------------------------- --
         2639  + if ((strlen(dem_config->dem_path) > 0) && (strlen(dem_config->dem_table) > 0) && (strlen(dem_config->dem_geometry) > 0))
         2640  + {
         2641  +  if (check_geometry_dimension(db_handle,dem_config, &geometry_type, verbose))
         2642  +  {
         2643  +   if (dem_config->dem_rows_count)
         2644  +   {
         2645  +    resolution_calc=(dem_config->dem_extent_maxx-dem_config->dem_extent_minx)*(dem_config->dem_extent_maxy-dem_config->dem_extent_miny)/(double)dem_config->dem_rows_count;
         2646  +   }
         2647  +   if (verbose)
         2648  +   {
         2649  +    fprintf(stderr,"Dem: srid %d\n", dem_config->dem_srid);
         2650  +    fprintf(stderr,"Dem: extent min x/y(%2.7f,%2.7f)\n\t    max x/y(%2.7f,%2.7f)\n",
         2651  +            dem_config->dem_extent_minx,dem_config->dem_extent_miny,
         2652  +            dem_config->dem_extent_maxx,dem_config->dem_extent_maxy);
         2653  +    fprintf(stderr,"Dem: extent width(%2.7f)\n\t   height(%2.7f)\n",
         2654  +            (dem_config->dem_extent_maxx-dem_config->dem_extent_minx),
         2655  +            (dem_config->dem_extent_maxy-dem_config->dem_extent_miny));
         2656  +    fprintf(stderr,"Dem: rows_count(%s) %u\n",dem_config->dem_geometry, dem_config->dem_rows_count);
         2657  +    fprintf(stderr,"Dem: resolution(%s) %2.7f\n",dem_config->dem_geometry, resolution_calc);
         2658  +    fprintf(stderr,"Dem: geometry_type(%d) has_z[%d] has_m[%d]\n",geometry_type,dem_config->has_z, dem_config->has_m);
         2659  +    fprintf(stderr,"Dem: spatial_index_enabled[%d]\n",dem_config->has_spatial_index);
         2660  +   }
         2661  +   if (dem_config->has_z)
         2662  +   {// The dem Database Table and geometry-columns exist and contains a z-value dimension.
         2663  +    switch (geometry_type)
         2664  +    {
         2665  +     case GAIA_POINTZ:
         2666  +     case GAIA_POINTZM:
         2667  +      {
         2668  +       if (dem_config->has_spatial_index == 1)
         2669  +       {
         2670  +        if ( (source_config) && (strlen(source_config->dem_path) > 0) && (strlen(source_config->dem_table) > 0))
         2671  +        {// No printing when .xyz file
         2672  +         if (verbose)
         2673  +         {
         2674  +          fprintf(stderr,"Source '%s'\n", source_config->dem_path);
         2675  +          fprintf(stderr," will set %s(%s) Z-Values\n\tfrom nearest POINT found in\n",source_config->dem_table, source_config->dem_geometry);
         2676  +         }
         2677  +        }
         2678  +        if (verbose)
         2679  +        {
         2680  +         fprintf(stderr,"Dem '%s'\n", dem_config->dem_path);
         2681  +         fprintf(stderr," TABLE[%s] with GEOMETRY-Column[%s]\n",dem_config->dem_table, dem_config->dem_geometry);
         2682  +        }
         2683  +        ret = 0;
         2684  +       }
         2685  +       else
         2686  +       {
         2687  +        if (verbose)
         2688  +        {
         2689  +         fprintf(stderr, "Dem '%s'\n", dem_config->dem_path);
         2690  +         fprintf(stderr, "TABLE[%s] or GEOMETRY-Column[%s] must be a POINT with a Z-Dimension with a SpatialIndex\n",dem_config->dem_table, dem_config->dem_geometry);
         2691  +         fprintf(stderr, "\t command_check_dem_db failed: sorry, cowardly quitting\n\n");
         2692  +        }
         2693  +        ret = -1;
         2694  +       }
         2695  +      }
         2696  +      break;
         2697  +     default:
         2698  +      if (verbose)
         2699  +      {
         2700  +       fprintf(stderr, "Dem '%s'\n", dem_config->dem_path);
         2701  +       fprintf(stderr, "TABLE[%s] or GEOMETRY-Column[%s] must be a POINT with a Z-Dimension\n",dem_config->dem_table, dem_config->dem_geometry);
         2702  +       fprintf(stderr, "\t command_check_dem_db failed: sorry, cowardly quitting\n\n");
         2703  +      }
         2704  +      ret = -1;
         2705  +      break;
         2706  +    }
         2707  +   }
         2708  +   else
         2709  +   {
         2710  +    if (verbose)
         2711  +    {
         2712  +     fprintf(stderr, "Dem '%s'\n", dem_config->dem_path);
         2713  +     fprintf(stderr,  "TABLE[%s] or GEOMETRY-Column[%s] does not contain a Z-Dimension\n",dem_config->dem_table, dem_config->dem_geometry);
         2714  +     fprintf(stderr, "\t command_check_dem_db failed: sorry, cowardly quitting\n\n");
         2715  +    }
         2716  +    ret = -1;
         2717  +   }
         2718  +  }
         2719  +  else
         2720  +  {// The dem Database Table or geometry-columns does not exist.
         2721  +   if (verbose)
         2722  +   {
         2723  +    fprintf(stderr, "Dem '%s'\n", dem_config->dem_path);
         2724  +    fprintf(stderr, "TABLE[%s] or GEOMETRY-Column[%s] not found\n",dem_config->dem_table, dem_config->dem_geometry);
         2725  +    fprintf(stderr, "\t check_geometry_dimension failed: sorry, cowardly quitting\n\n");
         2726  +   }
         2727  +   ret = -1;
         2728  +  }
         2729  +  if (ret == 0)
         2730  +  {
         2731  +   if (resolution_dem <= 0.0)
         2732  +   {
         2733  +    if (verbose)
         2734  +    {
         2735  +     fprintf(stderr, "-W-> -rdem was not set. Using: resolution(%s) %2.7f\n",dem_config->dem_geometry, resolution_calc);
         2736  +    }
         2737  +    resolution_dem=resolution_calc;
         2738  +   }
         2739  +   else
         2740  +   {
         2741  +    if (verbose)
         2742  +    {
         2743  +     fprintf(stderr, "-W-> -rdem was set. Using: resolution(%2.7f), overriding the calculated value: %2.7f\n",resolution_dem, resolution_calc);
         2744  +    }
         2745  +   }
         2746  +   dem_config->dem_resolution=resolution_dem;
         2747  +   if ((source_config) && (source_config->has_z))
         2748  +   {
         2749  +    dem_config->default_srid=source_config->default_srid;
         2750  +    if (verbose)
         2751  +    {
         2752  +     if (dem_config->dem_srid == source_config->default_srid)
         2753  +     {
         2754  +      fprintf(stderr, "Dem srid[%d]: is the same as the Source srid[%d].\n", dem_config->dem_srid,dem_config->default_srid);
         2755  +      if ( ( source_config->dem_extent_minx >= dem_config->dem_extent_minx ) && (source_config->dem_extent_maxx <= dem_config->dem_extent_maxx ) &&
         2756  +           ( source_config->dem_extent_miny >= dem_config->dem_extent_miny ) && (source_config->dem_extent_maxy <= dem_config->dem_extent_maxy ) )
         2757  +      {
         2758  +       fprintf(stderr, "The Source[%s]: is totally within the Dem[%s] area.\n", source_config->dem_geometry,dem_config->dem_geometry);
         2759  +      }
         2760  +      else if ( ( source_config->dem_extent_minx < dem_config->dem_extent_minx ) && (source_config->dem_extent_maxx > dem_config->dem_extent_maxx ) &&
         2761  +                ( source_config->dem_extent_miny < dem_config->dem_extent_miny ) && (source_config->dem_extent_maxy > dem_config->dem_extent_maxy ) )
         2762  +      {
         2763  +       fprintf(stderr, "The Source[%s]: is totally covers the Dem[%s] area.\n", source_config->dem_geometry,dem_config->dem_geometry);
         2764  +       fprintf(stderr, "\t only geometries totally within the Dem area will be updated.\n");
         2765  +      }
         2766  +      else if ( ( ( source_config->dem_extent_minx < dem_config->dem_extent_minx ) || ( source_config->dem_extent_minx > dem_config->dem_extent_maxx ) ) &&
         2767  +                ( ( source_config->dem_extent_maxx > dem_config->dem_extent_maxx ) || ( source_config->dem_extent_maxx < dem_config->dem_extent_minx ) ) &&
         2768  +                ( ( source_config->dem_extent_miny < dem_config->dem_extent_miny ) || (source_config->dem_extent_miny > dem_config->dem_extent_maxy) ) &&
         2769  +                ( ( source_config->dem_extent_maxy > dem_config->dem_extent_maxy ) || ( source_config->dem_extent_maxy < dem_config->dem_extent_miny ) ) )
         2770  +      {
         2771  +       // ?? correct ??
         2772  +       fprintf(stderr, "The Dem[%s]: is totally outside of the Source[%s] area.\n", dem_config->dem_geometry,source_config->dem_geometry);
         2773  +      }
         2774  +      else
         2775  +      {
         2776  +       fprintf(stderr, "The Source[%s]: is partially inside of the Dem[%s] area.\n", source_config->dem_geometry,dem_config->dem_geometry);
         2777  +      }
         2778  +     }
         2779  +     else
         2780  +     {
         2781  +      fprintf(stderr, "Dem default_srid[%d]: is different from the Source default_srid[%d].\n", dem_config->dem_srid,dem_config->default_srid);
         2782  +      fprintf(stderr, "\t When searching for the nearest point, the Source points will be transformed to srid[%d].\n", dem_config->dem_srid);
         2783  +     }
         2784  +     fprintf(stderr, "Dem Database: has passed all checks.\n");
         2785  +    }
         2786  +   }
         2787  +  }
         2788  + }
         2789  + else
         2790  + {
         2791  +  if (strlen(dem_config->dem_path) > 0)
         2792  +  {
         2793  +   if (verbose)
         2794  +   {
         2795  +    fprintf(stderr,"-E-> command_check_dem_db: preconditions failed [%s(%s)] \n",dem_config->dem_table, dem_config->dem_geometry);
         2796  +   }
         2797  +  }
         2798  + }
         2799  +// -- -- ---------------------------------- --
         2800  + return ret;
         2801  +}
         2802  +// -- -- ---------------------------------- --
         2803  +// Implementation of command: updatez
         2804  +// - from a Table, geometry of Dem
         2805  +// --> update each z value with z value of
         2806  +// --> nearest Point of Dem
         2807  +// -- -- ---------------------------------- --
         2808  +static int
         2809  +command_updatez_db(sqlite3 *db_handle, struct config_dem*source_config, struct config_dem*dem_config,  int verbose)
         2810  +{
         2811  + int ret=0;
         2812  + char *time_message = NULL;
         2813  + struct timeval time_start;
         2814  + struct timeval time_end;
         2815  + struct timeval time_diff;
         2816  + char *sql_err = NULL;
         2817  + int count_total_geometries=0;
         2818  + int count_changed_geometries=0;
         2819  + int count_points_total=0;
         2820  + int count_z_total=0;
         2821  + int count_m_total=0;
         2822  +
         2823  + if ((strlen(dem_config->dem_path) > 0) && (strlen(dem_config->dem_table) > 0) && (strlen(dem_config->dem_geometry) > 0) &&
         2824  +     (dem_config->dem_srid > 0) && (dem_config->has_z) &&
         2825  +     (strlen(source_config->dem_path) > 0) && (strlen(source_config->dem_table) > 0) && (strlen(source_config->dem_geometry) > 0) &&
         2826  +     (source_config->default_srid > 0) && (source_config->has_z))
         2827  + {// The dem Database Table and geometry-columns exist and contains a z-value dimension.
         2828  +  // -- -- ---------------------------------- --
         2829  +  if (verbose)
         2830  +  {
         2831  +   fprintf(stderr,"-I-> starting update of [%s(%s)] where Z-Values are different.\n",source_config->dem_table, source_config->dem_geometry);
         2832  +  }
         2833  +  /* ok, going to convert */
         2834  +  /* the complete operation is handled as an unique SQL Transaction */
         2835  +  gettimeofday(&time_start, 0);
         2836  +  if (sqlite3_exec(db_handle, "BEGIN", NULL, NULL, &sql_err) == SQLITE_OK)
         2837  +  {
         2838  +   if (retrieve_geometries(db_handle, source_config, dem_config, &count_total_geometries,&count_changed_geometries,&count_points_total,&count_z_total,&count_m_total, verbose) )
         2839  +   {
         2840  +    /* committing the pending SQL Transaction */
         2841  +    if (sqlite3_exec(db_handle, "COMMIT", NULL, NULL, &sql_err) == SQLITE_OK)
         2842  +    {
         2843  +     ret = 0;
         2844  +    }
         2845  +    else
         2846  +    {
         2847  +     if (verbose)
         2848  +     {
         2849  +      fprintf(stderr, "COMMIT TRANSACTION error: %s\n", sql_err);
         2850  +     }
         2851  +     sqlite3_free(sql_err);
         2852  +     if (sql_err)
         2853  +     {
         2854  +      sqlite3_free(sql_err);
         2855  +     }
         2856  +     ret = -1;
         2857  +    }
         2858  +   }
         2859  +   else
         2860  +   {
         2861  +    ret = -1;
         2862  +    if (sqlite3_exec(db_handle, "ROLLBACK", NULL, NULL, &sql_err) == SQLITE_OK)
         2863  +    {
         2864  +    }
         2865  +    if (sql_err)
         2866  +    {
         2867  +     sqlite3_free(sql_err);
         2868  +    }
         2869  +    if (verbose)
         2870  +    {
         2871  +     fprintf(stderr, "DB '%s'\n", source_config->dem_path);
         2872  +     fprintf(stderr, "TABLE[%s] or GEOMETRY-Column[%s] error durring UPDATE\n",source_config->dem_table, source_config->dem_geometry);
         2873  +     fprintf(stderr, "*** ERROR: conversion failed\n\n");
         2874  +    }
         2875  +   }
         2876  +   gettimeofday(&time_end, 0);
         2877  +   timeval_subtract(&time_diff,&time_end,&time_start,&time_message);
         2878  +   if (ret == 0)
         2879  +   {
         2880  +    if (verbose)
         2881  +    {
         2882  +     fprintf(stderr,"-I-> geometries total[%d] changed[%d] ; points total[%d] changed z[%d] changed m[%d]\n",count_total_geometries,count_changed_geometries,count_points_total,count_z_total,count_m_total);
         2883  +     fprintf(stderr,"\tDatabase-file successfully updated found, changed, Z-Values !!!\n");
         2884  +     fprintf(stderr,"%s\n\n", time_message);
         2885  +    }
         2886  +   }
         2887  +  }
         2888  +  else
         2889  +  {
         2890  +   if (verbose)
         2891  +   {
         2892  +    fprintf(stderr, "BEGIN TRANSACTION error: %s\n", sql_err);
         2893  +   }
         2894  +   sqlite3_free(sql_err);
         2895  +   if (sql_err)
         2896  +   {
         2897  +    sqlite3_free(sql_err);
         2898  +   }
         2899  +   ret = -1;
         2900  +  }
         2901  + }
         2902  + else
         2903  + {// preconditions not fulfilled
         2904  +  if (verbose)
         2905  +  {
         2906  +   fprintf(stderr,"-E-> command_updatez_db: preconditions failed [%s(%s)] \n",source_config->dem_table, source_config->dem_geometry);
         2907  +  }
         2908  + }
         2909  +// -- -- ---------------------------------- --
         2910  + if (time_message)
         2911  + {
         2912  +  sqlite3_free(time_message);
         2913  +  time_message = NULL;
         2914  + }
         2915  +// -- -- ---------------------------------- --
         2916  + return ret;
         2917  +}
         2918  +// -- -- ---------------------------------- --
         2919  +// Implementation of command: fetchz
         2920  +// - from a given srid, point_x,point_y
         2921  +// --> return point_z value
         2922  +// -- -- ---------------------------------- --
         2923  +static int
         2924  +command_fetchz(sqlite3 *db_handle, struct config_dem *dem_config, int verbose)
         2925  +{
         2926  + int ret=0;
         2927  + char *time_message = NULL;
         2928  + struct timeval time_start;
         2929  + struct timeval time_end;
         2930  + struct timeval time_diff;
         2931  +// -- -- ---------------------------------- --
         2932  + if ( (dem_config->fetchz_x != 0.0) && (dem_config->fetchz_x != dem_config->fetchz_y) && (dem_config->default_srid > 0)  && (dem_config->dem_srid > 0))
         2933  + {
         2934  +  if (verbose)
         2935  +  {
         2936  +   fprintf(stderr, "FetchZ modus: with default_srid[%d]  x[%2.7f] y[%2.7f] has_m[%d]\n",dem_config->default_srid,dem_config->fetchz_x,dem_config->fetchz_y,dem_config->has_m);
         2937  +  }
         2938  +  gettimeofday(&time_start, 0);
         2939  +  if (callFetchZ(db_handle,dem_config,verbose) )
         2940  +  {
         2941  +   ret=1;
         2942  +   gettimeofday(&time_end, 0);
         2943  +   timeval_subtract(&time_diff,&time_end,&time_start,&time_message);
         2944  +   if (verbose)
         2945  +   {
         2946  +    if (dem_config->has_m)
         2947  +    {
         2948  +     fprintf(stderr, "FetchZ modus: with     dem_srid[%d] x[%2.7f] y[%2.7f] z[%2.7f] m[%2.7f]\n",dem_config->dem_srid,dem_config->fetchz_x,dem_config->fetchz_y,dem_config->dem_z,dem_config->dem_m);
         2949  +     fprintf(stderr,"%s\n", time_message);
         2950  +    }
         2951  +    else
         2952  +    {
         2953  +     fprintf(stderr, "FetchZ modus: with     dem_srid[%d] x[%2.7f] y[%2.7f] z[%2.7f]\n",dem_config->dem_srid,dem_config->fetchz_x,dem_config->fetchz_y,dem_config->dem_z);
         2954  +     fprintf(stderr,"%s\n", time_message);
         2955  +    }
         2956  +   }
         2957  +   else
         2958  +   {// Output for bash
         2959  +    if (dem_config->has_m)
         2960  +    {
         2961  +     printf("%2.7f %2.7f\n", dem_config->dem_z,dem_config->dem_m);
         2962  +    }
         2963  +    else
         2964  +    {
         2965  +     printf("%2.7f\n", dem_config->dem_z);
         2966  +    }
         2967  +   }
         2968  +  }
         2969  +  else
         2970  +  {
         2971  +   // callFetchZ failed
         2972  +  }
         2973  + }
         2974  + else
         2975  + {
         2976  +  // preconditions failed
         2977  +  if (verbose)
         2978  +  {
         2979  +   if ( dem_config->fetchz_x == 0.0)
         2980  +   {
         2981  +    fprintf(stderr, "did you forget setting the -fetchz_x argument ?\n");
         2982  +   }
         2983  +   if ( dem_config->fetchz_y == 0.0)
         2984  +   {
         2985  +    fprintf(stderr, "did you forget setting the -fetchz_y argument ?\n");
         2986  +   }
         2987  +   if ( dem_config->default_srid <= 0)
         2988  +   {
         2989  +    fprintf(stderr, "did you forget setting the -default_srid argument ?\n");
         2990  +   }
         2991  +   if ( dem_config->dem_srid <= 0)
         2992  +   {
         2993  +    fprintf(stderr, "The dem-srid is invalid\n");
         2994  +   }
         2995  +   fprintf(stderr, "-E command_fetchz: sorry, cowardly quitting\n\n");
         2996  +  }
         2997  + }
         2998  +// -- -- ---------------------------------- --
         2999  + if (time_message)
         3000  + {
         3001  +  sqlite3_free(time_message);
         3002  +  time_message = NULL;
         3003  + }
         3004  +// -- -- ---------------------------------- --
         3005  + return ret;
         3006  +}
         3007  +// -- -- ---------------------------------- --
         3008  +// Implementation of command: fetchz
         3009  +// - from a given srid, point_x,point_y
         3010  +// --> return point_z value
         3011  +// -- -- ---------------------------------- --
         3012  +static int
         3013  +command_dem_create(sqlite3 **db_handle, void *cache, struct config_dem *source_config, struct config_dem *dem_config, int verbose)
         3014  +{
         3015  + int ret=0;
         3016  + char *time_message = NULL;
         3017  + struct timeval time_start;
         3018  + struct timeval time_end;
         3019  + struct timeval time_diff;
         3020  + int count_xyz_files=0;
         3021  +// -- -- ---------------------------------- --
         3022  + if (cache)
         3023  + {
         3024  +  if ( dem_config->dem_srid <= 0)
         3025  +  {
         3026  +   dem_config->dem_srid=dem_config->default_srid;
         3027  +  }
         3028  +  if ((strlen(dem_config->dem_path) > 0) && (strlen(dem_config->dem_table) > 0) && (strlen(dem_config->dem_geometry) > 0) && (dem_config->dem_srid > 0))
         3029  +  {
         3030  +   gettimeofday(&time_start, 0);
         3031  +   if (create_dem_db(dem_config->dem_path, db_handle, cache, dem_config->dem_table, dem_config->dem_geometry,verbose))
         3032  +   {
         3033  +    if (verbose)
         3034  +    {
         3035  +     fprintf(stderr,"-I-> command_dem_createt: created [%s] \n", dem_config->dem_path);
         3036  +    }
         3037  +    if (collect_xyz_files(*db_handle,source_config->dem_path, &count_xyz_files, 0) == 1)
         3038  +    {
         3039  +     dem_config->dem_rows_count=0;
         3040  +     if (import_xyz(*db_handle, dem_config,count_xyz_files,verbose))
         3041  +     {// Import completed correctly
         3042  +      gettimeofday(&time_end, 0);
         3043  +      timeval_subtract(&time_diff,&time_end,&time_start,&time_message);
         3044  +      if (verbose)
         3045  +      {
         3046  +       fprintf(stderr,"%s\n", time_message);
         3047  +      }
         3048  +      gettimeofday(&time_start, 0);
         3049  +      if (recover_geometry_dem(*db_handle, dem_config,verbose))
         3050  +      {// Task completed correctly
         3051  +      }
         3052  +      else
         3053  +      {// Task failed
         3054  +       if (verbose)
         3055  +       {
         3056  +        fprintf(stderr,"-W-> command_dem_created: recover_geometry_dem failed [%s(%s)]  srid[%d]  \n", dem_config->dem_table, dem_config->dem_geometry, dem_config->dem_srid);
         3057  +       }
         3058  +      }
         3059  +      // Sniff the results, set schema_dem to 'main'
         3060  +      dem_config->schema=source_config->schema;
         3061  +      source_config->schema=NULL;
         3062  +      gettimeofday(&time_end, 0);
         3063  +      timeval_subtract(&time_diff,&time_end,&time_start,&time_message);
         3064  +      if (verbose)
         3065  +      {
         3066  +       fprintf(stderr,"%s\n", time_message);
         3067  +      }
         3068  +     }
         3069  +     else
         3070  +     {// Import failed
         3071  +      if (verbose)
         3072  +      {
         3073  +       fprintf(stderr,"-W-> command_dem_created: import_xyz failed [%d] [%s] \n", count_xyz_files,source_config->dem_path);
         3074  +      }
         3075  +     }
         3076  +    }
         3077  +   }
         3078  +   else
         3079  +   {
         3080  +    // Database exits or cannot be created
         3081  +    if (verbose)
         3082  +    {
         3083  +     fprintf(stderr, "Dem '%s'\n", dem_config->dem_path);
         3084  +     fprintf(stderr, "Database exists and will not be overwritten, use -import_xyz to add new data\n");
         3085  +     fprintf(stderr, "-E-> command_dem_create: sorry, cowardly quitting\n\n");
         3086  +    }
         3087  +   }
         3088  +  }
         3089  +  else
         3090  +  {
         3091  +   // preconditions failed
         3092  +   if (verbose)
         3093  +   {
         3094  +    if (strlen(dem_config->dem_path) <= 0)
         3095  +    {
         3096  +     fprintf(stderr, "did you forget setting the -ddem  argument ?\n");
         3097  +    }
         3098  +    if (strlen(dem_config->dem_table) <= 0)
         3099  +    {
         3100  +     fprintf(stderr, "did you forget setting the -tdem  argument ?\n");
         3101  +    }
         3102  +    if (strlen(dem_config->dem_geometry) <= 0)
         3103  +    {
         3104  +     fprintf(stderr, "did you forget setting the -gdem  argument ?\n");
         3105  +    }
         3106  +    if ( dem_config->default_srid <= 0)
         3107  +    {
         3108  +     fprintf(stderr, "did you forget setting the -default_srid argument ?\n");
         3109  +    }
         3110  +    if ( dem_config->dem_srid <= 0)
         3111  +    {
         3112  +     fprintf(stderr, "The dem-srid is invalid\n");
         3113  +    }
         3114  +    fprintf(stderr, "-E command_fetchz: sorry, cowardly quitting\n\n");
         3115  +   }
         3116  +  }
         3117  + }
         3118  +// -- -- ---------------------------------- --
         3119  + if (time_message)
         3120  + {
         3121  +  sqlite3_free(time_message);
         3122  +  time_message = NULL;
         3123  + }
         3124  +// -- -- ---------------------------------- --
         3125  + return ret;
         3126  +}
         3127  +// -- -- ---------------------------------- --
         3128  +// Implementation of command: -import_xyz
         3129  +// - from a given srid, point_x,point_y
         3130  +// --> return point_z value
         3131  +// -- -- ---------------------------------- --
         3132  +static int
         3133  +command_import_xyz(sqlite3 *db_handle, struct config_dem *source_config, struct config_dem *dem_config, int verbose)
         3134  +{
         3135  + int ret=0;
         3136  + char *time_message = NULL;
         3137  + char *sql_statement = NULL;
         3138  + char *err_msg = NULL;;
         3139  + struct timeval time_start;
         3140  + struct timeval time_end;
         3141  + struct timeval time_diff;
         3142  + int count_xyz_files=0;
         3143  +// -- -- ---------------------------------- --
         3144  + if ((strlen(source_config->dem_path) > 0) && (strlen(dem_config->dem_path) > 0) && (strlen(dem_config->dem_table) > 0) && (strlen(dem_config->dem_geometry) > 0))
         3145  + {
         3146  +  if ((dem_config->has_z) && (dem_config->dem_srid > 0))
         3147  +  {
         3148  +   if (db_handle)
         3149  +   {
         3150  +    gettimeofday(&time_start, 0);
         3151  +    if (verbose)
         3152  +    {
         3153  +     fprintf(stderr, "-import_xyz: with srid[%d] .xyz[%s] \n",source_config->default_srid,source_config->dem_path);
         3154  +    }
         3155  +    if (collect_xyz_files(db_handle,source_config->dem_path, &count_xyz_files, 0) == 1)
         3156  +    {
         3157  +     dem_config->dem_rows_count=0; // Set to 0, just in case
         3158  +     if (import_xyz(db_handle, dem_config,count_xyz_files,verbose))
         3159  +     {// Import completed correctly
         3160  +      gettimeofday(&time_end, 0);
         3161  +      timeval_subtract(&time_diff,&time_end,&time_start,&time_message);
         3162  +      if (verbose)
         3163  +      {
         3164  +       fprintf(stderr,"%s\n", time_message);
         3165  +      }
         3166  +      gettimeofday(&time_start, 0);
         3167  +      if (verbose)
         3168  +      {
         3169  +       fprintf(stderr,"UpdateLayerStatistics:  %s(%s)\n", dem_config->dem_table,dem_config->dem_geometry);
         3170  +      }
         3171  +      sql_statement = sqlite3_mprintf("SELECT UpdateLayerStatistics(%Q, %Q)", dem_config->dem_table,dem_config->dem_geometry);
         3172  +      int ret_update = sqlite3_exec(db_handle, sql_statement, NULL, NULL, &err_msg);
         3173  +      sqlite3_free(sql_statement);
         3174  +      if (ret_update != SQLITE_OK)
         3175  +      {
         3176  +       fprintf(stderr, "UpdateLayerStatistics error: %s\n", err_msg);
         3177  +       sqlite3_free(err_msg);
         3178  +      }
         3179  +      else
         3180  +      {
         3181  +       ret=1;
         3182  +      }
         3183  +      gettimeofday(&time_end, 0);
         3184  +      timeval_subtract(&time_diff,&time_end,&time_start,&time_message);
         3185  +      if (verbose)
         3186  +      {
         3187  +       fprintf(stderr,"%s\n", time_message);
         3188  +      }
         3189  +     }
         3190  +    }
         3191  +   }
         3192  +  }
         3193  + }
         3194  +// -- -- ---------------------------------- --
         3195  + if (time_message)
         3196  + {
         3197  +  sqlite3_free(time_message);
         3198  +  time_message = NULL;
         3199  + }
         3200  +// -- -- ---------------------------------- --
         3201  + return ret;
         3202  +}
         3203  +// -- -- ---------------------------------- --
         3204  +// Main
         3205  +// Commands
         3206  +// - sniff
         3207  +// -> allows the user to prepair the 'update' command
         3208  +// -> Source and Dem can be done separately or together
         3209  +// - update
         3210  +// -- -- ---------------------------------- --
         3211  +int
         3212  +main(int argc, char *argv[])
         3213  +{
         3214  + /* the MAIN function simply perform arguments checking */
         3215  + sqlite3 *db_handle = NULL;
         3216  + char *schema_db = "main";
         3217  + char *schema_dem = "db_dem";
         3218  + char *dem_geometry_default = "dem_point";
         3219  + void *cache = NULL;
         3220  + int verbose=0;
         3221  + int copy_m = 1;
         3222  + int next_arg = ARG_NONE;
         3223  + int i_command_type=CMD_DEM_SNIFF;
         3224  + struct config_dem dem_config;
         3225  + struct config_dem source_config;
         3226  + int save_conf=0;
         3227  + int exit_code=1; // unix_exit_code: 0=correct, 1=error
         3228  + int i=0;
         3229  + int error = 0;
         3230  +// -- -- ---------------------------------- --
         3231  +// Will look for conf [not an error if nothing found]
         3232  +// - if not found, all arguments must be set
         3233  +// -- -- ---------------------------------- --
         3234  + char *dem_configfile =  "spatialite_dem.conf";
         3235  + char *spatialite_dem = getenv("SPATIALITE_DEM");
         3236  +// -- -- ---------------------------------- --
         3237  +// Reading the configuration, if found
         3238  +// - setting default values
         3239  +// -- -- ---------------------------------- --
         3240  + if (spatialite_dem)
         3241  + {
         3242  +  dem_configfile=spatialite_dem;
         3243  + }
         3244  +// -- -- ---------------------------------- --
         3245  +// Warning, if non default, conf is given but not found
         3246  +// -- -- ---------------------------------- --
         3247  + dem_config = get_demconfig(dem_configfile,1);
         3248  + dem_config.config_type = CONF_TYPE_DEM; // dem
         3249  + dem_config.schema = schema_dem;  // dem
         3250  +// -- -- ---------------------------------- --
         3251  +// No external source config
         3252  +// - returns default values only
         3253  +// -- -- ---------------------------------- --
         3254  + source_config = get_demconfig(NULL,0);
         3255  + source_config.config_type = CONF_TYPE_SOURCE; // source
         3256  + source_config.schema = schema_db; // source
         3257  +// -- -- ---------------------------------- --
         3258  + if (strlen(dem_config.dem_path) > 0)
         3259  + {
         3260  +  if (dem_config.dem_srid > 0)
         3261  +  {
         3262  +   source_config.dem_srid=dem_config.dem_srid;
         3263  +  }
         3264  +  if (dem_config.default_srid > 0)
         3265  +  {
         3266  +   source_config.default_srid=dem_config.default_srid;
         3267  +  }
         3268  + }
         3269  +// -- -- ---------------------------------- --
         3270  +// Reading the arguments
         3271  +// -- -- ---------------------------------- --
         3272  + for (i = 1; i < argc; i++)
         3273  + {
         3274  +  // parsing the invocation arguments
         3275  +  if (next_arg != ARG_NONE)
         3276  +  {
         3277  +   switch (next_arg)
         3278  +   {
         3279  +    case ARG_DB_PATH:
         3280  +     strcpy(source_config.dem_path,argv[i]);
         3281  +     break;
         3282  +    case ARG_TABLE:
         3283  +     strcpy(source_config.dem_table,argv[i]);
         3284  +     break;
         3285  +    case ARG_COL:
         3286  +     strcpy(source_config.dem_geometry,argv[i]);
         3287  +     break;
         3288  +    case ARG_DEM_PATH:
         3289  +     strcpy(dem_config.dem_path,argv[i]);
         3290  +     break;
         3291  +    case ARG_TABLE_DEM:
         3292  +     strcpy(dem_config.dem_table,argv[i]);
         3293  +     break;
         3294  +    case ARG_COL_DEM:
         3295  +     strcpy(dem_config.dem_geometry,argv[i]);
         3296  +     break;
         3297  +    case ARG_RESOLUTION_DEM:
         3298  +     // this will override the calculated value (which may not be correct)
         3299  +     // - it also gives the user the choice to change the area around a point to search for.
         3300  +     dem_config.dem_resolution = atof(argv[i]);
         3301  +     break;
         3302  +    case ARG_COPY_M:
         3303  +     copy_m = atoi(argv[i]);
         3304  +     if (copy_m != 1 )
         3305  +      copy_m=0;
         3306  +     break;
         3307  +    case ARG_FETCHZ_X:
         3308  +     dem_config.fetchz_x = atof(argv[i]);
         3309  +     break;
         3310  +    case ARG_FETCHZ_Y:
         3311  +     dem_config.fetchz_y = atof(argv[i]);
         3312  +     break;
         3313  +    case ARG_FETCHZ_XY:
         3314  +     dem_config.fetchz_x = atof(argv[i++]);
         3315  +     dem_config.fetchz_y = atof(argv[i]);
         3316  +     break;
         3317  +    case ARG_DEFAULT_SRID:
         3318  +     source_config.default_srid = atoi(argv[i]);
         3319  +     dem_config.default_srid = atoi(argv[i]);
         3320  +     break;
         3321  +   };
         3322  +   next_arg = ARG_NONE;
         3323  +   continue;
         3324  +  }
         3325  +  if (strcasecmp (argv[i], "--help") == 0 || strcmp(argv[i], "-h") == 0)
         3326  +  {
         3327  +   do_help ();
         3328  +   return exit_code;
         3329  +  }
         3330  +  if (strcmp(argv[i], "-d") == 0)
         3331  +  {
         3332  +   next_arg = ARG_DB_PATH;
         3333  +   continue;
         3334  +  }
         3335  +  if (strcasecmp (argv[i], "--db-path") == 0)
         3336  +  {
         3337  +   next_arg = ARG_DB_PATH;
         3338  +   continue;
         3339  +  }
         3340  +  if (strcasecmp (argv[i], "--table") == 0)
         3341  +  {
         3342  +   next_arg = ARG_TABLE;
         3343  +   continue;
         3344  +  }
         3345  +  if (strcmp(argv[i], "-t") == 0)
         3346  +  {
         3347  +   next_arg = ARG_TABLE;
         3348  +   continue;
         3349  +  }
         3350  +  if (strcasecmp (argv[i], "--geometry-column") == 0)
         3351  +  {
         3352  +   next_arg = ARG_COL;
         3353  +   continue;
         3354  +  }
         3355  +  if (strcmp(argv[i], "-g") == 0)
         3356  +  {
         3357  +   next_arg = ARG_COL;
         3358  +   continue;
         3359  +  }
         3360  +  if (strcasecmp (argv[i], "--dem-path") == 0)
         3361  +  {
         3362  +   next_arg = ARG_DEM_PATH;
         3363  +   continue;
         3364  +  }
         3365  +  if (strcmp(argv[i], "-ddem") == 0)
         3366  +  {
         3367  +   next_arg = ARG_DEM_PATH;
         3368  +   continue;
         3369  +  }
         3370  +  if (strcasecmp (argv[i], "--table-dem") == 0)
         3371  +  {
         3372  +   next_arg = ARG_TABLE_DEM;
         3373  +   continue;
         3374  +  }
         3375  +  if (strcmp(argv[i], "-tdem") == 0)
         3376  +  {
         3377  +   next_arg = ARG_TABLE_DEM;
         3378  +   continue;
         3379  +  }
         3380  +  if (strcasecmp (argv[i], "--geometry-dem-column") == 0)
         3381  +  {
         3382  +   next_arg = ARG_COL_DEM;
         3383  +   continue;
         3384  +  }
         3385  +  if (strcmp(argv[i], "-gdem") == 0)
         3386  +  {
         3387  +   next_arg = ARG_COL_DEM;
         3388  +   continue;
         3389  +  }
         3390  +  if (strcasecmp (argv[i], "--dem-resolution") == 0)
         3391  +  {
         3392  +   next_arg = ARG_RESOLUTION_DEM;
         3393  +   continue;
         3394  +  }
         3395  +  if (strcmp(argv[i], "-rdem") == 0)
         3396  +  {
         3397  +   next_arg = ARG_RESOLUTION_DEM;
         3398  +   continue;
         3399  +  }
         3400  +  if (strcasecmp (argv[i], "--m-copy") == 0)
         3401  +  {
         3402  +   next_arg = ARG_COPY_M;
         3403  +   continue;
         3404  +  }
         3405  +  if (strcmp(argv[i], "-mdem") == 0)
         3406  +  {
         3407  +   next_arg = ARG_COPY_M;
         3408  +   continue;
         3409  +  }
         3410  +  if (strcmp(argv[i], "-sniff") == 0)
         3411  +  {
         3412  +   i_command_type=CMD_DEM_SNIFF;
         3413  +   continue;
         3414  +  }
         3415  +  if (strcmp(argv[i], "-updatez") == 0)
         3416  +  {
         3417  +   i_command_type=CMD_DEM_UPDATEZ;
         3418  +   continue;
         3419  +  }
         3420  +  if (strcmp(argv[i], "-fetchz") == 0)
         3421  +  {
         3422  +   i_command_type=CMD_DEM_FETCHZ;
         3423  +   continue;
         3424  +  }
         3425  +  if (strcmp(argv[i], "-create_dem") == 0)
         3426  +  {
         3427  +   i_command_type=CMD_DEM_CREATE;
         3428  +   continue;
         3429  +  }
         3430  +  if (strcmp(argv[i], "-import_xyz") == 0)
         3431  +  {
         3432  +   i_command_type=CMD_DEM_IMPORT_XYZ;
         3433  +   continue;
         3434  +  }
         3435  +  if (strcmp(argv[i], "-fetchz_x") == 0)
         3436  +  {
         3437  +   next_arg = ARG_FETCHZ_X;
         3438  +   continue;
         3439  +  }
         3440  +  if (strcmp(argv[i], "-fetchz_y") == 0)
         3441  +  {
         3442  +   next_arg = ARG_FETCHZ_Y;
         3443  +   continue;
         3444  +  }
         3445  +  if (strcmp(argv[i], "-fetchz_xy") == 0)
         3446  +  {
         3447  +   next_arg = ARG_FETCHZ_XY;
         3448  +   continue;
         3449  +  }
         3450  +  if ( (strcmp(argv[i], "-default_srid") == 0) ||  (strcmp(argv[i], "--srid") == 0) )
         3451  +  {
         3452  +   next_arg = ARG_DEFAULT_SRID;
         3453  +   continue;
         3454  +  }
         3455  +  if ( (strcmp(argv[i], "-v") == 0) ||  (strcmp(argv[i], "--verbose") == 0) )
         3456  +  {
         3457  +   verbose = 1;
         3458  +   continue;
         3459  +  }
         3460  +  if ( (strcmp(argv[i], "-save_conf") == 0) ||  (strcmp(argv[i], "--dem_conf") == 0) )
         3461  +  {
         3462  +   save_conf=1;
         3463  +   continue;
         3464  +  }
         3465  +  fprintf(stderr, "unknown argument: %s\n", argv[i]);
         3466  +  error = 1;
         3467  + }
         3468  +// -- -- ---------------------------------- --
         3469  +// Setting the default argument of dem_geometry
         3470  +// - dem_point
         3471  +// -- -- ---------------------------------- --
         3472  + if (strlen(dem_config.dem_geometry) == 0)
         3473  + {
         3474  +  strcpy(dem_config.dem_geometry,dem_geometry_default);
         3475  + }
         3476  +// -- -- ---------------------------------- --
         3477  +// checking, resetting the arguments
         3478  +// -- -- ---------------------------------- --
         3479  + if (i_command_type == CMD_DEM_SNIFF)
         3480  + {
         3481  +  if ((strlen(dem_config.dem_path) > 0) && (strlen(dem_config.dem_table) > 0) && (strlen(dem_config.dem_geometry) > 0) &&
         3482  +      (dem_config.fetchz_x != 0.0) && (dem_config.fetchz_x != dem_config.fetchz_y) )
         3483  +  {// -fetchz was intended but forgotten, be tolerant to the lazy user
         3484  +   i_command_type = CMD_DEM_FETCHZ;
         3485  +  }
         3486  +  else
         3487  +  {// for -sniff -v is always active
         3488  +   verbose=1;
         3489  +  }
         3490  + }
         3491  + if (verbose)
         3492  + {
         3493  +  if (strlen(dem_config.dem_path) == 0)
         3494  +  {
         3495  +   if (i_command_type == CMD_DEM_UPDATEZ)
         3496  +   {
         3497  +    fprintf(stderr, "did you forget setting the --dem-path argument ?\n");
         3498  +    error = 1;
         3499  +   }
         3500  +   else
         3501  +   {
         3502  +    fprintf(stderr, "Warning: --dem-path argument has not been set [assuming -sniff only]\n");
         3503  +   }
         3504  +  }
         3505  +  if (strlen(source_config.dem_path) == 0)
         3506  +  {
         3507  +   if (i_command_type == CMD_DEM_UPDATEZ)
         3508  +   {
         3509  +    fprintf(stderr, "did you forget setting the --db-path argument ?\n");
         3510  +    error = 1;
         3511  +   }
         3512  +  }
         3513  + }
         3514  +// -- -- ---------------------------------- --
         3515  +// Bale out on errors
         3516  +// -- -- ---------------------------------- --
         3517  + if (error)
         3518  + {
         3519  +  do_help();
         3520  +  return exit_code;
         3521  + }
         3522  +// -- -- ---------------------------------- --
         3523  +// opening the DB
         3524  +// - method 1: create a new Database
         3525  +// - method 2: input is not a Database, only Dem
         3526  +// - method 3: both input and dem are a Database, when given
         3527  +// -- -- ---------------------------------- --
         3528  + cache = spatialite_alloc_connection();
         3529  + if (i_command_type == CMD_DEM_CREATE)
         3530  + {
         3531  +  if (command_dem_create(&db_handle, cache, &source_config, &dem_config, verbose))
         3532  +  {
         3533  +   // Sniff the results, set schema_dem to 'main'
         3534  +   i_command_type = CMD_DEM_SNIFF;
         3535  +   dem_config.schema=schema_db;
         3536  +  }
         3537  + }
         3538  + else
         3539  + {
         3540  +  if (i_command_type == CMD_DEM_IMPORT_XYZ)
         3541  +  {// Open the Dem-Database as the main source [not attached ; since db_path=import.xyz]
         3542  +   open_db(&db_handle, cache, NULL, &dem_config,verbose);
         3543  +  }
         3544  +  else
         3545  +  {// Open the Dem-Database as the main source if there is no source [otherwise attached, with source as main ]
         3546  +   open_db(&db_handle, cache, &source_config, &dem_config,verbose);
         3547  +  }
         3548  + }
         3549  +// -- -- ---------------------------------- --
         3550  +// Bale out if no connection
         3551  +// -- -- ---------------------------------- --
         3552  + if (!db_handle)
         3553  + {
         3554  +  spatialite_cleanup_ex(cache);
         3555  +  cache=NULL;
         3556  +  return exit_code;
         3557  + }
         3558  +// -- -- ---------------------------------- --
         3559  +// checking the Source-Database
         3560  +// -- -- ---------------------------------- --
         3561  + command_check_source_db(db_handle,&source_config, &dem_config, verbose);
         3562  +// -- -- ---------------------------------- --
         3563  +// checking the Dem-Database
         3564  +// -- -- ---------------------------------- --
         3565  + if (command_check_dem_db(db_handle,&dem_config, &source_config, verbose) )
         3566  + {
         3567  +  if ( save_conf == 1)
         3568  +  {
         3569  +   if (write_demconfig(dem_configfile, dem_config))
         3570  +   {
         3571  +    fprintf(stderr, "Dem-conf: with default_srid[%d] was saved to\n\t[%s].\n",dem_config.default_srid,dem_configfile);
         3572  +   }
         3573  +  }
         3574  + }
         3575  +// -- -- ---------------------------------- --
         3576  +// After checking, the called functions
         3577  +//  will check the result before running
         3578  +// -- -- ---------------------------------- --
         3579  + if ( (i_command_type == CMD_DEM_SNIFF) && (dem_config.has_z) && (source_config.has_z))
         3580  + {
         3581  +  if (verbose)
         3582  +  {
         3583  +   fprintf(stderr, "Sniffing modus: All pre-conditions have been fulfilled.\n");
         3584  +   fprintf(stderr, "\t to start update, use the '-updatez' parameter.\n");
         3585  +   fprintf(stderr, "\t to save dem-conf,  use the '-save_conf' parameter.\n");
         3586  +  }
         3587  +  exit_code = 0; // correct
         3588  + }
         3589  +// -- -- ---------------------------------- --
         3590  +// Start --update
         3591  +// -- -- ---------------------------------- --
         3592  + if (i_command_type == CMD_DEM_UPDATEZ)
         3593  + {
         3594  +  if (!copy_m)
         3595  +  {// The User desires that m values be ignored
         3596  +   dem_config.has_m=0;
         3597  +  }
         3598  +  if (command_updatez_db(db_handle, &source_config,&dem_config, verbose) )
         3599  +  {
         3600  +   exit_code = 0; // correct
         3601  +  }
         3602  + }
         3603  +// -- -- ---------------------------------- --
         3604  +// Start -import_xyz
         3605  +// -- -- ---------------------------------- --
         3606  + if (i_command_type == CMD_DEM_IMPORT_XYZ)
         3607  + {
         3608  +  if (command_import_xyz(db_handle, &source_config, &dem_config, verbose))
         3609  +  {
         3610  +   exit_code = 0; // correct
         3611  +  }
         3612  + }
         3613  +// -- -- ---------------------------------- --
         3614  +// Start -fetchz
         3615  +// -- -- ---------------------------------- --
         3616  + if (i_command_type == CMD_DEM_FETCHZ)
         3617  + {
         3618  +  if (command_fetchz(db_handle, &dem_config, verbose) )
         3619  +  {
         3620  +   exit_code = 0; // correct
         3621  +  }
         3622  + }
         3623  +// -- -- ---------------------------------- --
         3624  +// Close Application
         3625  +// - DETACH when needed
         3626  +// -- -- ---------------------------------- --
         3627  + if (db_handle)
         3628  + {
         3629  +  close_db(db_handle,cache, schema_dem);
         3630  +  cache=NULL;
         3631  + }
         3632  + return exit_code;
         3633  +// -- -- ---------------------------------- --
         3634  +}
         3635  +

Changes to spatialite_dxf.c.

    30     30   #include <sys/types.h>
    31     31   #endif
    32     32   
    33     33   #include <stdlib.h>
    34     34   #include <stdio.h>
    35     35   #include <string.h>
    36     36   
           37  +#if defined(_WIN32) && !defined(__MINGW32__)
           38  +#include "config-msvc.h"
           39  +#else
    37     40   #include "config.h"
           41  +#endif
    38     42   
    39     43   #ifdef SPATIALITE_AMALGAMATION
    40     44   #include <spatialite/sqlite3.h>
    41     45   #else
    42     46   #include <sqlite3.h>
    43     47   #endif
    44     48   
................................................................................
    88     92         }
    89     93       sqlite3_free_table (results);
    90     94   
    91     95       if (count > 0)
    92     96   	return;
    93     97   
    94     98   /* all right, it's empty: proceding to initialize */
    95         -    strcpy (sql, "SELECT InitSpatialMetadata(1)");
           99  +    strcpy (sql, "SELECT InitSpatialMetadataFull(1)");
    96    100       ret = sqlite3_exec (db, sql, NULL, NULL, &err_msg);
    97    101       if (ret != SQLITE_OK)
    98    102         {
    99         -	  fprintf (stderr, "InitSpatialMetadata() error: %s\n", err_msg);
          103  +	  fprintf (stderr, "InitSpatialMetadataFull() error: %s\n", err_msg);
   100    104   	  sqlite3_free (err_msg);
   101    105   	  return;
   102    106         }
   103    107   }
          108  +
          109  +static void
          110  +do_version ()
          111  +{
          112  +/* printing version infos */
          113  +	fprintf( stderr, "\nVersion infos\n");
          114  +	fprintf( stderr, "===========================================\n");
          115  +    fprintf (stderr, "spatialite_dxf: %s\n", VERSION);
          116  +	fprintf (stderr, "target CPU ...: %s\n", spatialite_target_cpu ());
          117  +    fprintf (stderr, "libspatialite : %s\n", spatialite_version ());
          118  +    fprintf (stderr, "libsqlite3 ...: %s\n", sqlite3_libversion ());
          119  +    fprintf (stderr, "\n");
          120  +}
   104    121   
   105    122   static void
   106    123   do_help ()
   107    124   {
   108    125   /* printing the argument list */
   109    126       fprintf (stderr, "\n\nusage: spatialite_dxf ARGLIST\n");
   110    127       fprintf (stderr,
   111    128   	     "==============================================================\n");
   112    129       fprintf (stderr,
   113    130   	     "-h or --help                    print this help message\n");
          131  +    fprintf (stderr, "-v or --version                 print version infos\n");
   114    132       fprintf (stderr,
   115    133   	     "-d or --db-path  pathname       the SpatiaLite DB path\n");
   116    134       fprintf (stderr, "-x or --dxf-path pathname       the input DXF path\n\n");
   117    135       fprintf (stderr, "you can specify the following options as well:\n");
   118    136       fprintf (stderr, "----------------------------------------------\n");
   119    137       fprintf (stderr,
   120    138   	     "-s or --srid       num          an explicit SRID value\n");
................................................................................
   212    230   		continue;
   213    231   	    }
   214    232   	  if (strcasecmp (argv[i], "--help") == 0
   215    233   	      || strcmp (argv[i], "-h") == 0)
   216    234   	    {
   217    235   		do_help ();
   218    236   		return -1;
          237  +	    }
          238  +	  if (strcasecmp (argv[i], "--version") == 0
          239  +	      || strcmp (argv[i], "-v") == 0)
          240  +	    {
          241  +		do_version ();
          242  +		return -1;
   219    243   	    }
   220    244   	  if (strcasecmp (argv[i], "--db-path") == 0)
   221    245   	    {
   222    246   		next_arg = ARG_DB_PATH;
   223    247   		continue;
   224    248   	    }
   225    249   	  if (strcmp (argv[i], "-d") == 0)

Changes to spatialite_gml.c.

   587    587       if (params->is_feature)
   588    588   	check_end1_fid (params, el);
   589    589       if (params->is_fid)
   590    590         {
   591    591   	  *(params->CharData + params->CharDataLen) = '\0';
   592    592   	  column_name (params, el);
   593    593         }
          594  +    *(params->CharData) = '\0';
          595  +    params->CharDataLen = 0;
   594    596   }
   595    597   
   596    598   static void
   597    599   column_value (struct gml_params *params, const char *el)
   598    600   {
   599    601   /* handling a column value */
   600    602       char prefix[1024];
................................................................................
  1255   1257   	  *(params->CharData + params->CharDataLen) = '\0';
  1256   1258   	  column_value (params, el);
  1257   1259         }
  1258   1260       if (strcasecmp (el, "gml:coordinates") == 0)
  1259   1261   	parse_coords_1 (params);
  1260   1262       if (strcasecmp (el, "gml:posList") == 0 || strcasecmp (el, "gml:pos") == 0)
  1261   1263   	parse_coords_2 (params);
         1264  +    *(params->CharData) = '\0';
         1265  +    params->CharDataLen = 0;
  1262   1266   }
  1263   1267   
  1264   1268   static void
  1265   1269   spatialite_autocreate (sqlite3 * db)
  1266   1270   {
  1267   1271   /* attempting to perform self-initialization for a newly created DB */
  1268   1272       int ret;
................................................................................
  1288   1292         }
  1289   1293       sqlite3_free_table (results);
  1290   1294   
  1291   1295       if (count > 0)
  1292   1296   	return;
  1293   1297   
  1294   1298   /* all right, it's empty: proceding to initialize */
  1295         -    strcpy (sql, "SELECT InitSpatialMetadata(1)");
         1299  +    strcpy (sql, "SELECT InitSpatialMetadataFull(1)");
  1296   1300       ret = sqlite3_exec (db, sql, NULL, NULL, &err_msg);
  1297   1301       if (ret != SQLITE_OK)
  1298   1302         {
  1299         -	  fprintf (stderr, "InitSpatialMetadata() error: %s\n", err_msg);
         1303  +	  fprintf (stderr, "InitSpatialMetadataFull() error: %s\n", err_msg);
  1300   1304   	  sqlite3_free (err_msg);
  1301   1305   	  return;
  1302   1306         }
  1303   1307   }
  1304   1308   
  1305   1309   static void
  1306   1310   open_db (const char *path, sqlite3 ** handle, void *cache)
................................................................................
  1572   1576   	      free (col->txt_value);
  1573   1577   	  col = col_n;
  1574   1578         }
  1575   1579       if (params->CharData)
  1576   1580   	free (params->CharData);
  1577   1581       clean_geometry (params);
  1578   1582   }
         1583  +
         1584  +static void
         1585  +do_version ()
         1586  +{
         1587  +/* printing version infos */
         1588  +    XML_Expat_Version expat;
         1589  +	fprintf( stderr, "\nVersion infos\n");
         1590  +	fprintf( stderr, "===========================================\n");
         1591  +    fprintf (stderr, "spatialite_gml: %s\n", VERSION);
         1592  +	fprintf (stderr, "target CPU ...: %s\n", spatialite_target_cpu ());
         1593  +    fprintf (stderr, "libspatialite : %s\n", spatialite_version ());
         1594  +    fprintf (stderr, "libsqlite3 ...: %s\n", sqlite3_libversion ());
         1595  +    expat = XML_ExpatVersionInfo ();
         1596  +    fprintf (stderr, "libexpat .....: %d.%d.%d\n", expat.major, expat.minor,
         1597  +	     expat.micro);
         1598  +    fprintf (stderr, "\n");
         1599  +}
  1579   1600   
  1580   1601   static void
  1581   1602   do_help ()
  1582   1603   {
  1583   1604   /* printing the argument list */
  1584   1605       fprintf (stderr, "\n\nusage: spatialite_gml ARGLIST\n");
  1585   1606       fprintf (stderr,
  1586   1607   	     "==============================================================\n");
  1587   1608       fprintf (stderr,
  1588   1609   	     "-h or --help                    print this help message\n");
         1610  +    fprintf (stderr, "-v or --version                 print version infos\n");
  1589   1611       fprintf (stderr, "-g or --gml-path pathname       the GML-XML file path\n");
  1590   1612       fprintf (stderr,
  1591   1613   	     "-d or --db-path     pathname    the SpatiaLite DB path\n\n");
  1592   1614       fprintf (stderr, "-t or --table-name  name        the DB table name\n\n");
  1593   1615       fprintf (stderr, "you can specify the following options as well\n");
  1594   1616       fprintf (stderr,
  1595   1617   	     "-m or --in-memory               using IN-MEMORY database\n");
................................................................................
  1636   1658       params.geometry = NULL;
  1637   1659       params.polygon.exterior = NULL;
  1638   1660       params.polygon.first = NULL;
  1639   1661       params.polygon.last = NULL;
  1640   1662       params.CharDataStep = 65536;
  1641   1663       params.CharDataMax = params.CharDataStep;
  1642   1664       params.CharData = malloc (params.CharDataStep);
         1665  +    params.CharDataLen = 0;
  1643   1666   
  1644   1667       for (i = 1; i < argc; i++)
  1645   1668         {
  1646   1669   	  /* parsing the invocation arguments */
  1647   1670   	  if (next_arg != ARG_NONE)
  1648   1671   	    {
  1649   1672   		switch (next_arg)
................................................................................
  1662   1685   		continue;
  1663   1686   	    }
  1664   1687   	  if (strcasecmp (argv[i], "--help") == 0
  1665   1688   	      || strcmp (argv[i], "-h") == 0)
  1666   1689   	    {
  1667   1690   		do_help ();
  1668   1691   		return -1;
         1692  +	    }
         1693  +	  if (strcasecmp (argv[i], "--version") == 0
         1694  +	      || strcmp (argv[i], "-v") == 0)
         1695  +	    {
         1696  +		do_version ();
         1697  +		return -1;
  1669   1698   	    }
  1670   1699   	  if (strcmp (argv[i], "-g") == 0)
  1671   1700   	    {
  1672   1701   		next_arg = ARG_GML_PATH;
  1673   1702   		continue;
  1674   1703   	    }
  1675   1704   	  if (strcasecmp (argv[i], "--gml-path") == 0)

Changes to spatialite_network.c.

  1106   1106         }
  1107   1107       sqlite3_free_table (results);
  1108   1108   
  1109   1109       if (count > 0)
  1110   1110   	return;
  1111   1111   
  1112   1112   /* all right, it's empty: proceding to initialize */
  1113         -    strcpy (sql, "SELECT InitSpatialMetadata(1)");
         1113  +    strcpy (sql, "SELECT InitSpatialMetadataFull(1)");
  1114   1114       ret = sqlite3_exec (db, sql, NULL, NULL, &err_msg);
  1115   1115       if (ret != SQLITE_OK)
  1116   1116         {
  1117         -	  fprintf (stderr, "InitSpatialMetadata() error: %s\n", err_msg);
         1117  +	  fprintf (stderr, "InitSpatialMetadataFull() error: %s\n", err_msg);
  1118   1118   	  sqlite3_free (err_msg);
  1119   1119   	  return;
  1120   1120         }
  1121   1121   }
  1122   1122   
  1123   1123   static void
  1124   1124   validate (const char *path, const char *table, const char *from_column,
................................................................................
  2546   2546       ret = sqlite3_close (handle);
  2547   2547       if (ret != SQLITE_OK)
  2548   2548   	fprintf (stderr, "sqlite3_close() error: %s\n",
  2549   2549   		 sqlite3_errmsg (handle));
  2550   2550       spatialite_cleanup_ex (cache);
  2551   2551       graph_free (p_graph);
  2552   2552   }
         2553  +
         2554  +static void
         2555  +do_version ()
         2556  +{
         2557  +/* printing version infos */
         2558  +	fprintf( stderr, "\nVersion infos\n");
         2559  +	fprintf( stderr, "===========================================\n");
         2560  +    fprintf (stderr, "spatialite_network: %s\n", VERSION);
         2561  +	fprintf (stderr, "target CPU .......: %s\n", spatialite_target_cpu ());
         2562  +    fprintf (stderr, "libspatialite ....: %s\n", spatialite_version ());
         2563  +    fprintf (stderr, "libsqlite3 .......: %s\n", sqlite3_libversion ());
         2564  +    fprintf (stderr, "\n");
         2565  +}
  2553   2566   
  2554   2567   static void
  2555   2568   do_help ()
  2556   2569   {
  2557   2570   /* printing the argument list */
  2558   2571       fprintf (stderr, "\n\nusage: spatialite_network ARGLIST\n");
  2559   2572       fprintf (stderr,
  2560   2573   	     "==============================================================\n");
  2561   2574       fprintf (stderr,
  2562   2575   	     "-h or --help                      print this help message\n");
         2576  +    fprintf (stderr, "-v or --version                   print version infos\n");
  2563   2577       fprintf (stderr,
  2564   2578   	     "-d or --db-path pathname          the SpatiaLite db path\n");
  2565   2579       fprintf (stderr,
  2566   2580   	     "-T or --table table_name          the db table to be validated\n");
  2567   2581       fprintf (stderr,
  2568   2582   	     "-f or --from-column col_name      the column for FromNode\n");
  2569   2583       fprintf (stderr,
................................................................................
  2594   2608   	     "both columns are expected to contain BOOLEAN values [1-0];\n");
  2595   2609       fprintf (stderr,
  2596   2610   	     "1 means that the arc connection in the given direction is\n");
  2597   2611       fprintf (stderr, "valid, otherwise 0 means a forbidden connection\n\n");
  2598   2612       fprintf (stderr, "in order to create a permanent NETWORK-DATA table\n");
  2599   2613       fprintf (stderr, "you can select the following options:\n");
  2600   2614       fprintf (stderr, "-o or --output-table table_name\n");
  2601         -    fprintf (stderr, "-v or --virtual-table table_name\n");
         2615  +    fprintf (stderr, "-vt or --virtual-table table_name\n");
  2602   2616       fprintf (stderr, "--overwrite-output\n\n");
  2603   2617   }
  2604   2618   
  2605   2619   int
  2606   2620   main (int argc, char *argv[])
  2607   2621   {
  2608   2622   /* the MAIN function simply perform arguments checking */
................................................................................
  2668   2682   		continue;
  2669   2683   	    }
  2670   2684   	  if (strcasecmp (argv[i], "--help") == 0
  2671   2685   	      || strcmp (argv[i], "-h") == 0)
  2672   2686   	    {
  2673   2687   		do_help ();
  2674   2688   		return -1;
         2689  +	    }
         2690  +	  if (strcasecmp (argv[i], "--version") == 0
         2691  +	      || strcmp (argv[i], "-v") == 0)
         2692  +	    {
         2693  +		do_version ();
         2694  +		return -1;
  2675   2695   	    }
  2676   2696   	  if (strcasecmp (argv[i], "--db-path") == 0)
  2677   2697   	    {
  2678   2698   		next_arg = ARG_DB_PATH;
  2679   2699   		continue;
  2680   2700   	    }
  2681   2701   	  if (strcmp (argv[i], "-d") == 0)
................................................................................
  2704   2724   		continue;
  2705   2725   	    }
  2706   2726   	  if (strcasecmp (argv[i], "--virtual-table") == 0)
  2707   2727   	    {
  2708   2728   		next_arg = ARG_VIRT_TABLE;
  2709   2729   		continue;
  2710   2730   	    }
  2711         -	  if (strcmp (argv[i], "-v") == 0)
         2731  +	  if (strcmp (argv[i], "-vt") == 0)
  2712   2732   	    {
  2713   2733   		next_arg = ARG_VIRT_TABLE;
  2714   2734   		continue;
  2715   2735   	    }
  2716   2736   	  if (strcasecmp (argv[i], "--from-column") == 0)
  2717   2737   	    {
  2718   2738   		next_arg = ARG_FROM_COLUMN;

Changes to spatialite_osm_filter.c.

   250    250   			    if (sqlite3_column_type (query, 9) != SQLITE_NULL)
   251    251   				v = clean_xml ((const char *)
   252    252   					       sqlite3_column_text (query, 9));
   253    253   
   254    254   			    if (first)
   255    255   			      {
   256    256   				  /* first NODE row */
   257         -				  char *timestamp = clean_xml (p_timestamp);
   258         -				  char *changeset = clean_xml (p_changeset);
   259         -				  char *user = NULL;
   260         -				  if (p_user)
   261         -				      user = clean_xml (p_user);
          257  +				  char *timestamp =
          258  +				      p_timestamp ? clean_xml (p_timestamp) :
          259  +				      NULL;
          260  +				  char *changeset =
          261  +				      p_changeset ? clean_xml (p_changeset) :
          262  +				      NULL;
          263  +				  char *user =
          264  +				      p_user ? clean_xml (p_user) : NULL;
   262    265   				  first = 0;
   263    266   #if defined(_WIN32) || defined(__MINGW32__)
   264    267   /* CAVEAT - M$ runtime doesn't supports %lld for 64 bits */
   265    268   				  fprintf (out, "\t<node id=\"%I64d\"", id);
   266    269   #else
   267    270   				  fprintf (out, "\t<node id=\"%lld\"", id);
   268    271   #endif
   269         -				  if (!user)
   270         -				      fprintf (out,
   271         -					       " lat=\"%1.7f\" lon=\"%1.7f\" version=\"%d\" changeset=\"%s\" uid=\"%d\" timestamp=\"%s\"",
   272         -					       y, x, version, changeset, uid,
   273         -					       timestamp);
   274         -				  else
   275         -				      fprintf (out,
   276         -					       " lat=\"%1.7f\" lon=\"%1.7f\" version=\"%d\" changeset=\"%s\" user=\"%s\" uid=\"%d\" timestamp=\"%s\"",
   277         -					       y, x, version, changeset, user,
   278         -					       uid, timestamp);
   279         -				  free (changeset);
   280    272   				  if (user)
   281         -				      free (user);
   282         -				  free (timestamp);
          273  +				    {
          274  +					fprintf (out, " user=\"%s\"", user);
          275  +					free (user);
          276  +				    }
          277  +				  if (changeset)
          278  +				    {
          279  +					fprintf (out, " changeset=\"%s\"",
          280  +						 changeset);
          281  +					free (changeset);
          282  +				    }
          283  +				  if (timestamp)
          284  +				    {
          285  +					fprintf (out, " timestamp=\"%s\"",
          286  +						 timestamp);
          287  +					free (timestamp);
          288  +				    }
          289  +				  if (!version)
          290  +				      version = 1;
          291  +				  fprintf (out, " version=\"%d\"", version);
          292  +				  fprintf (out,
          293  +					   " lat=\"%1.7f\" lon=\"%1.7f\" uid=\"%d\" ",
          294  +					   y, x, uid);
   283    295   				  if (k == NULL && v == NULL)
   284    296   				      fprintf (out, "/>\n");
   285    297   				  else
   286    298   				      fprintf (out, ">\n");
   287    299   			      }
   288    300   			    if (k != NULL && v != NULL)
   289    301   			      {
................................................................................
   417    429   				(const char *) sqlite3_column_text (query, 5);
   418    430   			    sqlite3_int64 node_id =
   419    431   				sqlite3_column_int64 (query, 6);
   420    432   
   421    433   			    if (first)
   422    434   			      {
   423    435   				  /* first WAY row */
   424         -				  char *timestamp = clean_xml (p_timestamp);
   425         -				  char *changeset = clean_xml (p_changeset);
          436  +				  char *timestamp =
          437  +				      p_timestamp ? clean_xml (p_timestamp) :
          438  +				      NULL;
          439  +				  char *changeset =
          440  +				      p_changeset ? clean_xml (p_changeset) :
          441  +				      NULL;
   426    442   				  char *user = NULL;
   427    443   				  if (p_user)
   428    444   				      user = clean_xml (p_user);
   429    445   				  first = 0;
   430    446   #if defined(_WIN32) || defined(__MINGW32__)
   431    447   /* CAVEAT - M$ runtime doesn't supports %lld for 64 bits */
   432    448   				  fprintf (out, "\t<way id=\"%I64d\"", id);
   433    449   #else
   434    450   				  fprintf (out, "\t<way id=\"%lld\"", id);
   435    451   #endif
   436         -				  if (!user)
   437         -				      fprintf (out,
   438         -					       " version=\"%d\" changeset=\"%s\" uid=\"%d\" timestamp=\"%s\">\n",
   439         -					       version, changeset, uid,
   440         -					       timestamp);
   441         -				  else
   442         -				      fprintf (out,
   443         -					       " version=\"%d\" changeset=\"%s\" user=\"%s\" uid=\"%d\" timestamp=\"%s\">\n",
   444         -					       version, changeset, user, uid,
   445         -					       timestamp);
   446         -				  free (changeset);
   447    452   				  if (user)
   448         -				      free (user);
   449         -				  free (timestamp);
          453  +				    {
          454  +					fprintf (out, " user=\"%s\"", user);
          455  +					free (user);
          456  +				    }
          457  +				  if (changeset)
          458  +				    {
          459  +					fprintf (out, " changeset=\"%s\"",
          460  +						 changeset);
          461  +					free (changeset);
          462  +				    }
          463  +				  if (timestamp)
          464  +				    {
          465  +					fprintf (out, " timestamp=\"%s\"",
          466  +						 timestamp);
          467  +					free (timestamp);
          468  +				    }
          469  +				  if (!version)
          470  +				      version = 1;
          471  +				  fprintf (out, " version=\"%d\"", version);
          472  +				  fprintf (out, " uid=\"%d\" >\n", uid);
   450    473   			      }
   451    474   			    /* NODE REF tag */
   452    475   #if defined(_WIN32) || defined(__MINGW32__)
   453    476   /* CAVEAT - M$ runtime doesn't supports %lld for 64 bits */
   454    477   			    fprintf (out, "\t\t<nd ref=\"%I64d\"/>\n", node_id);
   455    478   #else
   456    479   			    fprintf (out, "\t\t<nd ref=\"%lld\"/>\n", node_id);
................................................................................
   657    680   				clean_xml ((const char *)
   658    681   					   sqlite3_column_text (query_way, 6));
   659    682   			    sqlite3_int64 way_id =
   660    683   				sqlite3_column_int64 (query_way, 7);
   661    684   
   662    685   			    if (first)
   663    686   			      {
   664         -				  /* first WAY row */
   665         -				  char *timestamp = clean_xml (p_timestamp);
   666         -				  char *changeset = clean_xml (p_changeset);
          687  +				  /* first RELATION row */
          688  +				  char *timestamp =
          689  +				      p_timestamp ? clean_xml (p_timestamp) :
          690  +				      NULL;
          691  +				  char *changeset =
          692  +				      p_changeset ? clean_xml (p_changeset) :
          693  +				      NULL;
   667    694   				  char *user = NULL;
   668    695   				  if (p_user)
   669    696   				      user = clean_xml (p_user);
   670    697   				  first = 0;
   671    698   #if defined(_WIN32) || defined(__MINGW32__)
   672    699   /* CAVEAT - M$ runtime doesn't supports %lld for 64 bits */
   673    700   				  fprintf (out, "\t<relation id=\"%I64d\"", id);
   674    701   #else
   675    702   				  fprintf (out, "\t<relation id=\"%lld\"", id);
   676    703   #endif
   677         -				  if (!user)
   678         -				      fprintf (out,
   679         -					       " version=\"%d\" changeset=\"%s\" uid=\"%d\" timestamp=\"%s\">\n",
   680         -					       version, changeset, uid,
   681         -					       timestamp);
   682         -				  else
   683         -				      fprintf (out,
   684         -					       " version=\"%d\" changeset=\"%s\" user=\"%s\" uid=\"%d\" timestamp=\"%s\">\n",
   685         -					       version, changeset, user, uid,
   686         -					       timestamp);
   687         -				  free (changeset);
   688         -				  free (user);
   689         -				  free (timestamp);
          704  +				  if (user)
          705  +				    {
          706  +					fprintf (out, " user=\"%s\"", user);
          707  +					free (user);
          708  +				    }
          709  +				  if (changeset)
          710  +				    {
          711  +					fprintf (out, " changeset=\"%s\"",
          712  +						 changeset);
          713  +					free (changeset);
          714  +				    }
          715  +				  if (timestamp)
          716  +				    {
          717  +					fprintf (out, " timestamp=\"%s\"",
          718  +						 timestamp);
          719  +					free (timestamp);
          720  +				    }
          721  +				  if (!version)
          722  +				      version = 1;
          723  +				  fprintf (out, " version=\"%d\"", version);
          724  +				  fprintf (out, " uid=\"%d\" >\n", uid);
   690    725   			      }
   691    726   			    /* NODE REF tag */
   692    727   #if defined(_WIN32) || defined(__MINGW32__)
   693    728   /* CAVEAT - M$ runtime doesn't supports %lld for 64 bits */
   694    729   			    fprintf (out,
   695    730   				     "\t\t<member type=\"way\" ref=\"%I64d\" role=\"%s\"/>\n",
   696    731   				     way_id, role);
................................................................................
  1558   1593     unknown:
  1559   1594       if (db_handle)
  1560   1595   	sqlite3_close (db_handle);
  1561   1596       fprintf (stderr, "DB '%s'\n", path);
  1562   1597       fprintf (stderr, "doesn't seems to contain valid OSM-RAW data ...\n\n");
  1563   1598       return;
  1564   1599   }
         1600  +
         1601  +static void
         1602  +do_version ()
         1603  +{
         1604  +/* printing version infos */
         1605  +	fprintf( stderr, "\nVersion infos\n");
         1606  +	fprintf( stderr, "===========================================\n");
         1607  +    fprintf (stderr, "spatialite_osm_filter: %s\n", VERSION);
         1608  +	fprintf (stderr, "target CPU ..........: %s\n", spatialite_target_cpu ());
         1609  +    fprintf (stderr, "libspatialite .......: %s\n", spatialite_version ());
         1610  +    fprintf (stderr, "libsqlite3 ..........: %s\n", sqlite3_libversion ());
         1611  +    fprintf (stderr, "\n");
         1612  +}
  1565   1613   
  1566   1614   static void
  1567   1615   do_help ()
  1568   1616   {
  1569   1617   /* printing the argument list */
  1570   1618       fprintf (stderr, "\n\nusage: spatialite_osm_filter ARGLIST\n");
  1571   1619       fprintf (stderr,
  1572   1620   	     "==============================================================\n");
  1573   1621       fprintf (stderr,
  1574   1622   	     "-h or --help                    print this help message\n");
         1623  +    fprintf (stderr, "-v or --version                 print version infos\n");
  1575   1624       fprintf (stderr,
  1576   1625   	     "-o or --osm-path pathname       the OSM-XML [output] file path\n");
  1577   1626       fprintf (stderr,
  1578   1627   	     "-w or --wkt-mask-path pathname  path of text file [WKT mask]\n");
  1579   1628       fprintf (stderr,
  1580   1629   	     "-d or --db-path  pathname       the SpatiaLite DB path\n\n");
  1581   1630       fprintf (stderr, "you can specify the following options as well\n");
................................................................................
  1632   1681   		continue;
  1633   1682   	    }
  1634   1683   	  if (strcasecmp (argv[i], "--help") == 0
  1635   1684   	      || strcmp (argv[i], "-h") == 0)
  1636   1685   	    {
  1637   1686   		do_help ();
  1638   1687   		return -1;
         1688  +	    }
         1689  +	  if (strcasecmp (argv[i], "--version") == 0
         1690  +	      || strcmp (argv[i], "-v") == 0)
         1691  +	    {
         1692  +		do_version ();
         1693  +		return -1;
  1639   1694   	    }
  1640   1695   	  if (strcmp (argv[i], "-o") == 0)
  1641   1696   	    {
  1642   1697   		next_arg = ARG_OSM_PATH;
  1643   1698   		continue;
  1644   1699   	    }
  1645   1700   	  if (strcasecmp (argv[i], "--osm-path") == 0)

Changes to spatialite_osm_map.c.

   363    363   		      gaiaToSpatiaLiteBlobWkb (geom, &blob, &blob_size);
   364    364   		      gaiaFreeGeomColl (geom);
   365    365   		      sqlite3_bind_blob (layer->ins_point_stmt, 4, blob,
   366    366   					 blob_size, free);
   367    367   		      ret = sqlite3_step (layer->ins_point_stmt);
   368    368   		      if (ret == SQLITE_DONE || ret == SQLITE_ROW)
   369    369   			  return 1;
   370         -		      fprintf (stderr, "sqlite3_step() error: INS_POINT %s\n",
   371         -			       layer_name);
   372         -		      sqlite3_finalize (layer->ins_point_stmt);
   373         -		      layer->ins_point_stmt = NULL;
   374         -		      return 0;
          370  +		      fprintf (stderr,
          371  +			       "sqlite3_step() error: INS_POINT %s (%s)\n",
          372  +			       layer_name, sqlite3_errmsg (params->db_handle));
          373  +		      return 1;
   375    374   		  }
   376    375   		return 1;
   377    376   	    }
   378    377         }
   379    378       return 1;
   380    379   }
   381    380   
................................................................................
   402    401   	  gaiaToSpatiaLiteBlobWkb (geom, &blob, &blob_size);
   403    402   	  gaiaFreeGeomColl (geom);
   404    403   	  sqlite3_bind_blob (params->ins_generic_point_stmt, 3, blob,
   405    404   			     blob_size, free);
   406    405   	  ret = sqlite3_step (params->ins_generic_point_stmt);
   407    406   	  if (ret == SQLITE_DONE || ret == SQLITE_ROW)
   408    407   	      return 1;
   409         -	  fprintf (stderr, "sqlite3_step() error: INS_GENERIC_POINT\n");
   410         -	  sqlite3_finalize (params->ins_generic_point_stmt);
   411         -	  params->ins_generic_point_stmt = NULL;
   412         -	  return 0;
          408  +	  fprintf (stderr, "sqlite3_step() error: INS_GENERIC_POINT (%s)\n",
          409  +		   sqlite3_errmsg (params->db_handle));
          410  +	  return 1;
   413    411         }
   414    412       return 1;
   415    413   }
   416    414   
   417    415   static int
   418    416   address_insert (struct aux_params *params, const readosm_node * node,
   419    417   		const char *country, const char *city, const char *postcode,
................................................................................
   464    462   	  gaiaToSpatiaLiteBlobWkb (geom, &blob, &blob_size);
   465    463   	  gaiaFreeGeomColl (geom);
   466    464   	  sqlite3_bind_blob (params->ins_addresses_stmt, 8, blob, blob_size,
   467    465   			     free);
   468    466   	  ret = sqlite3_step (params->ins_addresses_stmt);
   469    467   	  if (ret == SQLITE_DONE || ret == SQLITE_ROW)
   470    468   	      return 1;
   471         -	  fprintf (stderr, "sqlite3_step() error: INS_ADDRESSES\n");
   472         -	  sqlite3_finalize (params->ins_addresses_stmt);
   473         -	  params->ins_addresses_stmt = NULL;
   474         -	  return 0;
          469  +	  fprintf (stderr, "sqlite3_step() error: INS_ADDRESSES (%s)\n",
          470  +		   sqlite3_errmsg (params->db_handle));
          471  +	  return 1;
   475    472         }
   476    473       return 1;
   477    474   }
   478    475   
   479    476   static int
   480    477   tmp_nodes_insert (struct aux_params *params, const readosm_node * node)
   481    478   {
................................................................................
   486    483       sqlite3_clear_bindings (params->ins_tmp_nodes_stmt);
   487    484       sqlite3_bind_int64 (params->ins_tmp_nodes_stmt, 1, node->id);
   488    485       sqlite3_bind_double (params->ins_tmp_nodes_stmt, 2, node->latitude);
   489    486       sqlite3_bind_double (params->ins_tmp_nodes_stmt, 3, node->longitude);
   490    487       ret = sqlite3_step (params->ins_tmp_nodes_stmt);
   491    488       if (ret == SQLITE_DONE || ret == SQLITE_ROW)
   492    489   	return 1;
   493         -    fprintf (stderr, "sqlite3_step() error: INS_TMP_NODES\n");
   494         -    sqlite3_finalize (params->ins_tmp_nodes_stmt);
   495         -    params->ins_tmp_nodes_stmt = NULL;
   496         -    return 0;
          490  +    fprintf (stderr, "sqlite3_step() error: INS_TMP_NODES (%s)\n",
          491  +	     sqlite3_errmsg (params->db_handle));
          492  +    return 1;
   497    493   }
   498    494   
   499    495   static int
   500    496   consume_node (const void *user_data, const readosm_node * node)
   501    497   {
   502    498   /* processing an OSM Node (ReadOSM callback function) */
   503    499       struct aux_params *params = (struct aux_params *) user_data;
................................................................................
   804    800   					     SQLITE_STATIC);
   805    801   		      sqlite3_bind_blob (layer->ins_linestring_stmt, 4, blob,
   806    802   					 blob_size, SQLITE_STATIC);
   807    803   		      ret = sqlite3_step (layer->ins_linestring_stmt);
   808    804   		      if (ret == SQLITE_DONE || ret == SQLITE_ROW)
   809    805   			  return 1;
   810    806   		      fprintf (stderr,
   811         -			       "sqlite3_step() error: INS_LINESTRING %s\n",
   812         -			       layer_name);
   813         -		      sqlite3_finalize (layer->ins_linestring_stmt);
   814         -		      layer->ins_linestring_stmt = NULL;
   815         -		      return 0;
          807  +			       "sqlite3_step() error: INS_LINESTRING %s (%s)\n",
          808  +			       layer_name, sqlite3_errmsg (params->db_handle));
          809  +		      return 1;
   816    810   		  }
   817    811   		return 1;
   818    812   	    }
   819    813         }
   820    814       return 1;
   821    815   }
   822    816   
................................................................................
   858    852   					     strlen (name), SQLITE_STATIC);
   859    853   		      sqlite3_bind_blob (layer->ins_polygon_stmt, 4, blob,
   860    854   					 blob_size, SQLITE_STATIC);
   861    855   		      ret = sqlite3_step (layer->ins_polygon_stmt);
   862    856   		      if (ret == SQLITE_DONE || ret == SQLITE_ROW)
   863    857   			  return 1;
   864    858   		      fprintf (stderr,
   865         -			       "sqlite3_step() error: INS_POLYGON %s\n",
   866         -			       layer_name);
   867         -		      sqlite3_finalize (layer->ins_polygon_stmt);
   868         -		      layer->ins_polygon_stmt = NULL;
   869         -		      return 0;
          859  +			       "sqlite3_step() error: INS_POLYGON %s (%s)\n",
          860  +			       layer_name, sqlite3_errmsg (params->db_handle));
          861  +		      return 1;
   870    862   		  }
   871    863   		return 1;
   872    864   	    }
   873    865         }
   874    866       return 1;
   875    867   }
   876    868   
................................................................................
   890    882   	      sqlite3_bind_text (params->ins_generic_linestring_stmt, 2, name,
   891    883   				 strlen (name), SQLITE_STATIC);
   892    884   	  sqlite3_bind_blob (params->ins_generic_linestring_stmt, 3, blob,
   893    885   			     blob_size, SQLITE_STATIC);
   894    886   	  ret = sqlite3_step (params->ins_generic_linestring_stmt);
   895    887   	  if (ret == SQLITE_DONE || ret == SQLITE_ROW)
   896    888   	      return 1;
   897         -	  fprintf (stderr, "sqlite3_step() error: INS_GENERIC_LINESTRING\n");
   898         -	  sqlite3_finalize (params->ins_generic_linestring_stmt);
   899         -	  params->ins_generic_linestring_stmt = NULL;
   900         -	  return 0;
          889  +	  fprintf (stderr,
          890  +		   "sqlite3_step() error: INS_GENERIC_LINESTRING (%s)\n",
          891  +		   sqlite3_errmsg (params->db_handle));
          892  +	  return 1;
   901    893         }
   902    894       return 1;
   903    895   }
   904    896   
   905    897   static int
   906    898   polygon_generic_insert (struct aux_params *params, sqlite3_int64 id,
   907    899   			unsigned char *blob, int blob_size, const char *name)
................................................................................
   918    910   	      sqlite3_bind_text (params->ins_generic_polygon_stmt, 2, name,
   919    911   				 strlen (name), SQLITE_STATIC);
   920    912   	  sqlite3_bind_blob (params->ins_generic_polygon_stmt, 3, blob,
   921    913   			     blob_size, SQLITE_STATIC);
   922    914   	  ret = sqlite3_step (params->ins_generic_polygon_stmt);
   923    915   	  if (ret == SQLITE_DONE || ret == SQLITE_ROW)
   924    916   	      return 1;
   925         -	  fprintf (stderr, "sqlite3_step() error: INS_GENERIC_POLYGON\n");
   926         -	  sqlite3_finalize (params->ins_generic_polygon_stmt);
   927         -	  params->ins_generic_polygon_stmt = NULL;
   928         -	  return 0;
          917  +	  fprintf (stderr, "sqlite3_step() error: INS_GENERIC_POLYGON (%s)\n",
          918  +		   sqlite3_errmsg (params->db_handle));
          919  +	  return 1;
   929    920         }
   930    921       return 1;
   931    922   }
   932    923   
   933    924   static int
   934    925   tmp_ways_insert (struct aux_params *params, sqlite3_int64 id, int area,
   935    926   		 unsigned char *blob, int blob_size)
................................................................................
   943    934       sqlite3_bind_int (params->ins_tmp_ways_stmt, 2, area);
   944    935       sqlite3_bind_blob (params->ins_tmp_ways_stmt, 3, blob, blob_size,
   945    936   		       SQLITE_STATIC);
   946    937       ret = sqlite3_step (params->ins_tmp_ways_stmt);
   947    938   
   948    939       if (ret == SQLITE_DONE || ret == SQLITE_ROW)
   949    940   	return 1;
   950         -    fprintf (stderr, "sqlite3_step() error: INS_TMP_WAYS\n");
   951         -    sqlite3_finalize (params->ins_tmp_ways_stmt);
   952         -    params->ins_tmp_ways_stmt = NULL;
   953         -    return 0;
          941  +    fprintf (stderr, "sqlite3_step() error: INS_TMP_WAYS (%s)\n",
          942  +	     sqlite3_errmsg (params->db_handle));
          943  +    return 1;
   954    944   }
   955    945   
   956    946   static int
   957    947   eval_way (struct aux_params *params, const readosm_way * way, int area,
   958    948   	  unsigned char *blob, int blob_size)
   959    949   {
   960    950       int i_tag;
................................................................................
  1418   1408   					     SQLITE_STATIC);
  1419   1409   		      sqlite3_bind_blob (layer->ins_linestring_stmt, 4, blob,
  1420   1410   					 blob_size, free);
  1421   1411   		      ret = sqlite3_step (layer->ins_linestring_stmt);
  1422   1412   		      if (ret == SQLITE_DONE || ret == SQLITE_ROW)
  1423   1413   			  return 1;
  1424   1414   		      fprintf (stderr,
  1425         -			       "sqlite3_step() error: INS_MULTILINESTRING %s\n",
  1426         -			       layer_name);
  1427         -		      sqlite3_finalize (layer->ins_linestring_stmt);
  1428         -		      layer->ins_linestring_stmt = NULL;
  1429         -		      return 0;
         1415  +			       "sqlite3_step() error: INS_MULTILINESTRING %s (%s)\n",
         1416  +			       layer_name, sqlite3_errmsg (params->db_handle));
         1417  +		      return 1;
  1430   1418   		  }
  1431   1419   		return 1;
  1432   1420   	    }
  1433   1421         }
  1434   1422       return 1;
  1435   1423   }
  1436   1424   
................................................................................
  1817   1805   					     strlen (name), SQLITE_STATIC);
  1818   1806   		      sqlite3_bind_blob (layer->ins_polygon_stmt, 4, blob,
  1819   1807   					 blob_size, free);
  1820   1808   		      ret = sqlite3_step (layer->ins_polygon_stmt);
  1821   1809   		      if (ret == SQLITE_DONE || ret == SQLITE_ROW)
  1822   1810   			  return 1;
  1823   1811   		      fprintf (stderr,
  1824         -			       "sqlite3_step() error: INS_MULTIPOLYGON %s\n",
  1825         -			       layer_name);
  1826         -		      sqlite3_finalize (layer->ins_polygon_stmt);
  1827         -		      layer->ins_polygon_stmt = NULL;
  1828         -		      return 0;
         1812  +			       "sqlite3_step() error: INS_MULTIPOLYGON %s (%s)\n",
         1813  +			       layer_name, sqlite3_errmsg (params->db_handle));
         1814  +		      return 1;
  1829   1815   		  }
  1830   1816   		return 1;
  1831   1817   	    }
  1832   1818         }
  1833   1819       return 1;
  1834   1820   }
  1835   1821   
................................................................................
  1860   1846   				 strlen (name), SQLITE_STATIC);
  1861   1847   	  sqlite3_bind_blob (params->ins_generic_linestring_stmt, 3, blob,
  1862   1848   			     blob_size, free);
  1863   1849   	  ret = sqlite3_step (params->ins_generic_linestring_stmt);
  1864   1850   	  if (ret == SQLITE_DONE || ret == SQLITE_ROW)
  1865   1851   	      return 1;
  1866   1852   	  fprintf (stderr,
  1867         -		   "sqlite3_step() error: INS_GENERIC_MULTILINESTRING\n");
  1868         -	  sqlite3_finalize (params->ins_generic_linestring_stmt);
  1869         -	  params->ins_generic_linestring_stmt = NULL;
  1870         -	  return 0;
         1853  +		   "sqlite3_step() error: INS_GENERIC_MULTILINESTRING (%s)\n",
         1854  +		   sqlite3_errmsg (params->db_handle));
         1855  +	  return 1;
  1871   1856         }
  1872   1857       return 1;
  1873   1858   }
  1874   1859   
  1875   1860   static int
  1876   1861   multipolygon_generic_insert (struct aux_params *params,
  1877   1862   			     const readosm_relation * relation,
................................................................................
  1899   1884   	      sqlite3_bind_text (params->ins_generic_polygon_stmt, 2, name,
  1900   1885   				 strlen (name), SQLITE_STATIC);
  1901   1886   	  sqlite3_bind_blob (params->ins_generic_polygon_stmt, 3, blob,
  1902   1887   			     blob_size, free);
  1903   1888   	  ret = sqlite3_step (params->ins_generic_polygon_stmt);
  1904   1889   	  if (ret == SQLITE_DONE || ret == SQLITE_ROW)
  1905   1890   	      return 1;
  1906         -	  fprintf (stderr, "sqlite3_step() error: INS_GENERIC_MULTIPOLYGON\n");
  1907         -	  sqlite3_finalize (params->ins_generic_polygon_stmt);
  1908         -	  params->ins_generic_polygon_stmt = NULL;
  1909         -	  return 0;
         1891  +	  fprintf (stderr,
         1892  +		   "sqlite3_step() error: INS_GENERIC_MULTIPOLYGON (%s)\n",
         1893  +		   sqlite3_errmsg (params->db_handle));
         1894  +	  return 1;
  1910   1895         }
  1911   1896       return 1;
  1912   1897   }
  1913   1898   
  1914   1899   static int
  1915   1900   consume_relation (const void *user_data, const readosm_relation * relation)
  1916   1901   {
................................................................................
  2020   2005         }
  2021   2006       sqlite3_free_table (results);
  2022   2007   
  2023   2008       if (count > 0)
  2024   2009   	return;
  2025   2010   
  2026   2011   /* all right, it's empty: proceding to initialize */
  2027         -    strcpy (sql, "SELECT InitSpatialMetadata(1)");
         2012  +    strcpy (sql, "SELECT InitSpatialMetadataFull(1)");
  2028   2013       ret = sqlite3_exec (db, sql, NULL, NULL, &err_msg);
  2029   2014       if (ret != SQLITE_OK)
  2030   2015         {
  2031         -	  fprintf (stderr, "InitSpatialMetadata() error: %s\n", err_msg);
         2016  +	  fprintf (stderr, "InitSpatialMetadataFull() error: %s\n", err_msg);
  2032   2017   	  sqlite3_free (err_msg);
  2033   2018   	  return;
  2034   2019         }
  2035   2020   }
  2036   2021   
  2037   2022   static void
  2038   2023   open_db (const char *path, sqlite3 ** handle, int cache_size, void *cache)
................................................................................
  2540   2525   		table = results[(i * columns) + 0];
  2541   2526   		geom = results[(i * columns) + 1];
  2542   2527   		do_spatial_index (db_handle, table, geom);
  2543   2528   	    }
  2544   2529         }
  2545   2530       sqlite3_free_table (results);
  2546   2531   }
         2532  +
         2533  +static void
         2534  +do_version ()
         2535  +{
         2536  +/* printing version infos */
         2537  +	fprintf( stderr, "\nVersion infos\n");
         2538  +	fprintf( stderr, "===========================================\n");
         2539  +    fprintf (stderr, "spatialite_osm_map: %s\n", VERSION);
         2540  +	fprintf (stderr, "target CPU .......: %s\n", spatialite_target_cpu ());
         2541  +    fprintf (stderr, "libspatialite ....: %s\n", spatialite_version ());
         2542  +    fprintf (stderr, "libsqlite3 .......: %s\n", sqlite3_libversion ());
         2543  +    fprintf (stderr, "libreadosm .......: %s\n", readosm_version ());
         2544  +    fprintf (stderr, "libexpat .........: %s\n", readosm_expat_version ());
         2545  +    fprintf (stderr, "zlib .............: %s\n", readosm_zlib_version ());
         2546  +    fprintf (stderr, "\n");
         2547  +}
  2547   2548   
  2548   2549   static void
  2549   2550   do_help ()
  2550   2551   {
  2551   2552   /* printing the argument list */
  2552   2553       fprintf (stderr, "\n\nusage: spatialite_osm_map ARGLIST\n");
  2553   2554       fprintf (stderr,
  2554   2555   	     "==============================================================\n");
  2555   2556       fprintf (stderr,
  2556   2557   	     "-h or --help                    print this help message\n");
         2558  +    fprintf (stderr, "-v or --version                 print version infos\n");
  2557   2559       fprintf (stderr, "-o or --osm-path pathname       the OSM-XML file path\n");
  2558   2560       fprintf (stderr,
  2559   2561   	     "                 both OSM-XML (*.osm) and OSM-ProtoBuf\n");
  2560   2562       fprintf (stderr,
  2561   2563   	     "                 (*.osm.pbf) are indifferently supported.\n\n");
  2562   2564       fprintf (stderr,
  2563   2565   	     "-d or --db-path  pathname       the SpatiaLite DB path\n\n");
................................................................................
  2621   2623   		continue;
  2622   2624   	    }
  2623   2625   	  if (strcasecmp (argv[i], "--help") == 0
  2624   2626   	      || strcmp (argv[i], "-h") == 0)
  2625   2627   	    {
  2626   2628   		do_help ();
  2627   2629   		return -1;
         2630  +	    }
         2631  +	  if (strcasecmp (argv[i], "--version") == 0
         2632  +	      || strcmp (argv[i], "-v") == 0)
         2633  +	    {
         2634  +		do_version ();
         2635  +		return -1;
  2628   2636   	    }
  2629   2637   	  if (strcmp (argv[i], "-o") == 0)
  2630   2638   	    {
  2631   2639   		next_arg = ARG_OSM_PATH;
  2632   2640   		continue;
  2633   2641   	    }
  2634   2642   	  if (strcasecmp (argv[i], "--osm-path") == 0)

Changes to spatialite_osm_net.c.

  1500   1500   	  for (i = 1; i <= rows; i++)
  1501   1501   	      count = atoi (results[(i * columns) + 0]);
  1502   1502         }
  1503   1503       sqlite3_free_table (results);
  1504   1504       if (count > 0)
  1505   1505   	return;
  1506   1506   /* all right, it's empty: proceding to initialize */
  1507         -    strcpy (sql, "SELECT InitSpatialMetadata(1)");
         1507  +    strcpy (sql, "SELECT InitSpatialMetadataFull(1)");
  1508   1508       ret = sqlite3_exec (db, sql, NULL, NULL, &err_msg);
  1509   1509       if (ret != SQLITE_OK)
  1510   1510         {
  1511         -	  fprintf (stderr, "InitSpatialMetadata() error: %s\n", err_msg);
         1511  +	  fprintf (stderr, "InitSpatialMetadataFull() error: %s\n", err_msg);
  1512   1512   	  sqlite3_free (err_msg);
  1513   1513   	  return;
  1514   1514         }
  1515   1515   }
  1516   1516   
  1517   1517   static sqlite3 *
  1518   1518   open_db (const char *path, const char *table, int double_arcs, int cache_size,
................................................................................
  2237   2237   	  fprintf (out, "# SpeedClass:yet_anotherclass_2:2.0\n");
  2238   2238   	  fprintf (out, "# SpeedClass:yet_anotherclass_3:3.0\n\n\n");
  2239   2239         }
  2240   2240   
  2241   2241       fclose (out);
  2242   2242       return 1;
  2243   2243   }
         2244  +
         2245  +static void
         2246  +do_version ()
         2247  +{
         2248  +/* printing version infos */
         2249  +	fprintf( stderr, "\nVersion infos\n");
         2250  +	fprintf( stderr, "===========================================\n");
         2251  +    fprintf (stderr, "spatialite_osm_net: %s\n", VERSION);
         2252  +	fprintf (stderr, "target CPU .......: %s\n", spatialite_target_cpu ());
         2253  +    fprintf (stderr, "libspatialite ....: %s\n", spatialite_version ());
         2254  +    fprintf (stderr, "libsqlite3 .......: %s\n", sqlite3_libversion ());
         2255  +    fprintf (stderr, "libreadosm .......: %s\n", readosm_version ());
         2256  +    fprintf (stderr, "libexpat .........: %s\n", readosm_expat_version ());
         2257  +    fprintf (stderr, "zlib .............: %s\n", readosm_zlib_version ());
         2258  +    fprintf (stderr, "\n");
         2259  +}
  2244   2260   
  2245   2261   static void
  2246   2262   do_help ()
  2247   2263   {
  2248   2264   /* printing the argument list */
  2249   2265       fprintf (stderr, "\n\nusage: spatialite_osm_net ARGLIST\n");
  2250   2266       fprintf (stderr,
  2251   2267   	     "==============================================================\n");
  2252   2268       fprintf (stderr,
  2253   2269   	     "-h or --help                    print this help message\n");
         2270  +    fprintf (stderr, "-v or --version                 print version infos\n");
  2254   2271       fprintf (stderr, "-o or --osm-path pathname       the OSM-XML file path\n");
  2255   2272       fprintf (stderr,
  2256   2273   	     "                 both OSM-XML (*.osm) and OSM-ProtoBuf\n");
  2257   2274       fprintf (stderr,
  2258   2275   	     "                 (*.osm.pbf) are indifferently supported.\n\n");
  2259   2276       fprintf (stderr,
  2260   2277   	     "-d or --db-path  pathname       the SpatiaLite DB path\n");
................................................................................
  2345   2362   		continue;
  2346   2363   	    }
  2347   2364   	  if (strcasecmp (argv[i], "--help") == 0
  2348   2365   	      || strcmp (argv[i], "-h") == 0)
  2349   2366   	    {
  2350   2367   		do_help ();
  2351   2368   		return -1;
         2369  +	    }
         2370  +	  if (strcasecmp (argv[i], "--version") == 0
         2371  +	      || strcmp (argv[i], "-v") == 0)
         2372  +	    {
         2373  +		do_version ();
         2374  +		return -1;
  2352   2375   	    }
  2353   2376   	  if (strcmp (argv[i], "-o") == 0)
  2354   2377   	    {
  2355   2378   		next_arg = ARG_OSM_PATH;
  2356   2379   		continue;
  2357   2380   	    }
  2358   2381   	  if (strcasecmp (argv[i], "--osm-path") == 0)

Changes to spatialite_osm_overpass.c.

    25     25   */
    26     26   
    27     27   #include <stdlib.h>
    28     28   #include <stdio.h>
    29     29   #include <string.h>
    30     30   #include <float.h>
    31     31   
           32  +#if defined(_WIN32) && !defined(__MINGW32__)
           33  +#include "config-msvc.h"
           34  +#else
           35  +#include "config.h"
           36  +#endif
           37  +
           38  +#ifdef ENABLE_LIBXML2		/* only if LIBXML2 is enabled */
           39  +
    32     40   #include <libxml/parser.h>
    33     41   #include <libxml/nanohttp.h>
    34     42   
    35     43   #include <sqlite3.h>
    36     44   #include <spatialite/gaiageo.h>
    37     45   #include <spatialite.h>
    38     46   
................................................................................
  1195   1203         }
  1196   1204       sqlite3_free_table (results);
  1197   1205   
  1198   1206       if (count > 0)
  1199   1207   	return;
  1200   1208   
  1201   1209   /* all right, it's empty: proceding to initialize */
  1202         -    strcpy (sql, "SELECT InitSpatialMetadata(1)");
         1210  +    strcpy (sql, "SELECT InitSpatialMetadataFull(1)");
  1203   1211       ret = sqlite3_exec (db, sql, NULL, NULL, &err_msg);
  1204   1212       if (ret != SQLITE_OK)
  1205   1213         {
  1206         -	  fprintf (stderr, "InitSpatialMetadata() error: %s\n", err_msg);
         1214  +	  fprintf (stderr, "InitSpatialMetadataFull() error: %s\n", err_msg);
  1207   1215   	  sqlite3_free (err_msg);
  1208   1216   	  return;
  1209   1217         }
  1210   1218   }
  1211   1219   
  1212   1220   static int
  1213   1221   create_road_tables (struct aux_params *params)
................................................................................
  3993   4001   	  save = *miny;
  3994   4002   	  *miny = *maxy;
  3995   4003   	  *maxy = save;
  3996   4004   	  ret = 0;
  3997   4005         }
  3998   4006       return ret;
  3999   4007   }
         4008  +
         4009  +static void
         4010  +do_version ()
         4011  +{
         4012  +/* printing version infos */
         4013  +	fprintf( stderr, "\nVersion infos\n");
         4014  +	fprintf( stderr, "===========================================\n");
         4015  +    fprintf (stderr, "spatialite_osm_overpass: %s\n", VERSION);
         4016  +	fprintf (stderr, "target CPU ............: %s\n", spatialite_target_cpu ());
         4017  +    fprintf (stderr, "libspatialite .........: %s\n", spatialite_version ());
         4018  +    fprintf (stderr, "libsqlite3 ............: %s\n", sqlite3_libversion ());
         4019  +    fprintf (stderr, "libxml2 ...............: %s\n", LIBXML_DOTTED_VERSION);
         4020  +    fprintf (stderr, "\n");
         4021  +}
  4000   4022   
  4001   4023   static void
  4002   4024   do_help ()
  4003   4025   {
  4004   4026   /* printing the argument list */
  4005   4027       fprintf (stderr, "\n\nusage: spatialite_osm_overpass ARGLIST\n");
  4006   4028       fprintf (stderr,
  4007   4029   	     "==============================================================\n");
  4008   4030       fprintf (stderr,
  4009   4031   	     "-h or --help                    print this help message\n");
         4032  +    fprintf (stderr, "-v or --version                 print version infos\n");
  4010   4033       fprintf (stderr,
  4011   4034   	     "-d or --db-path     pathname    the SpatiaLite DB path\n");
  4012   4035       fprintf (stderr,
  4013   4036   	     "-minx or --bbox-minx  coord     BoundingBox - west longitude\n");
  4014   4037       fprintf (stderr,
  4015   4038   	     "-maxx or --bbox-maxx  coord     BoundingBox - east longitude\n");
  4016   4039       fprintf (stderr,
................................................................................
  4034   4057   	     "-m or --in-memory               using IN-MEMORY database\n");
  4035   4058       fprintf (stderr,
  4036   4059   	     "-jo or --journal-off            unsafe [but faster] mode\n");
  4037   4060       fprintf (stderr,
  4038   4061   	     "-p or --preserve                skipping final cleanup (preserving OSM tables)\n");
  4039   4062   }
  4040   4063   
         4064  +#endif /* end LIBXML2 conditional */
         4065  +
  4041   4066   int
  4042   4067   main (int argc, char *argv[])
  4043   4068   {
  4044   4069   /* the MAIN function simply perform arguments checking */
         4070  +
         4071  +#ifndef ENABLE_LIBXML2		/* only if LIBXML2 is disabled */
         4072  +    fprintf (stderr, "\nthis copy of \"spatialite_osm_overpass\"\n"
         4073  +	     "was built by disabling LIBXML2 support.\n"
         4074  +	     "Sorry, cowardly quitting ...\n");
         4075  +    return 0;
         4076  +#else
  4045   4077       sqlite3 *handle;
  4046   4078       int i;
  4047   4079       int next_arg = ARG_NONE;
  4048   4080       const char *osm_url = "http://overpass-api.de/api";
  4049   4081       const char *db_path = NULL;
  4050   4082       int in_memory = 0;
  4051   4083       int cache_size = 0;
................................................................................
  4148   4180   		continue;
  4149   4181   	    }
  4150   4182   	  if (strcasecmp (argv[i], "--help") == 0
  4151   4183   	      || strcmp (argv[i], "-h") == 0)
  4152   4184   	    {
  4153   4185   		do_help ();
  4154   4186   		return -1;
         4187  +	    }
         4188  +	  if (strcasecmp (argv[i], "--version") == 0
         4189  +	      || strcmp (argv[i], "-v") == 0)
         4190  +	    {
         4191  +		do_version ();
         4192  +		return -1;
  4155   4193   	    }
  4156   4194   	  if (strcmp (argv[i], "-d") == 0)
  4157   4195   	    {
  4158   4196   		next_arg = ARG_DB_PATH;
  4159   4197   		continue;
  4160   4198   	    }
  4161   4199   	  if (strcasecmp (argv[i], "--db-path") == 0)
................................................................................
  4584   4622   
  4585   4623   /* closing the DB connection */
  4586   4624       sqlite3_close (handle);
  4587   4625       spatialite_cleanup_ex (cache);
  4588   4626       spatialite_shutdown ();
  4589   4627       downloader_cleanup (&downloader);
  4590   4628       return 0;
         4629  +#endif /* end LIBXML2 conditional */
  4591   4630   }

Changes to spatialite_osm_raw.c.

   616    616         }
   617    617       sqlite3_free_table (results);
   618    618   
   619    619       if (count > 0)
   620    620   	return;
   621    621   
   622    622   /* all right, it's empty: proceding to initialize */
   623         -    strcpy (sql, "SELECT InitSpatialMetadata(1)");
          623  +    strcpy (sql, "SELECT InitSpatialMetadataFull(1)");
   624    624       ret = sqlite3_exec (db, sql, NULL, NULL, &err_msg);
   625    625       if (ret != SQLITE_OK)
   626    626         {
   627         -	  fprintf (stderr, "InitSpatialMetadata() error: %s\n", err_msg);
          627  +	  fprintf (stderr, "InitSpatialMetadataFull() error: %s\n", err_msg);
   628    628   	  sqlite3_free (err_msg);
   629    629   	  return;
   630    630         }
   631    631   }
   632    632   
   633    633   static void
   634    634   open_db (const char *path, sqlite3 ** handle, int cache_size, void *cache)
................................................................................
   929    929       if (db_handle)
   930    930   	sqlite3_close (db_handle);
   931    931       fprintf (stderr, "DB '%s'\n", path);
   932    932       fprintf (stderr, "doesn't seems to contain valid Spatial Metadata ...\n\n");
   933    933       fprintf (stderr, "Please, initialize Spatial Metadata\n\n");
   934    934       return;
   935    935   }
          936  +
          937  +static void
          938  +do_version ()
          939  +{
          940  +/* printing version infos */
          941  +	fprintf( stderr, "\nVersion infos\n");
          942  +	fprintf( stderr, "===========================================\n");
          943  +    fprintf (stderr, "spatialite_osm_raw: %s\n", VERSION);
          944  +	fprintf (stderr, "target CPU .......: %s\n", spatialite_target_cpu ());
          945  +    fprintf (stderr, "libspatialite ....: %s\n", spatialite_version ());
          946  +    fprintf (stderr, "libsqlite3 .......: %s\n", sqlite3_libversion ());
          947  +    fprintf (stderr, "libreadosm .......: %s\n", readosm_version ());
          948  +    fprintf (stderr, "libexpat .........: %s\n", readosm_expat_version ());
          949  +    fprintf (stderr, "zlib .............: %s\n", readosm_zlib_version ());
          950  +    fprintf (stderr, "\n");
          951  +}
   936    952   
   937    953   static void
   938    954   do_help ()
   939    955   {
   940    956   /* printing the argument list */
   941    957       fprintf (stderr, "\n\nusage: spatialite_osm_raw ARGLIST\n");
   942    958       fprintf (stderr,
   943    959   	     "==============================================================\n");
   944    960       fprintf (stderr,
   945    961   	     "-h or --help                    print this help message\n");
          962  +    fprintf (stderr, "-v or --version                 print version infos\n");
   946    963       fprintf (stderr, "-o or --osm-path pathname       the OSM-file path\n");
   947    964       fprintf (stderr,
   948    965   	     "                 both OSM-XML (*.osm) and OSM-ProtoBuf\n");
   949    966       fprintf (stderr,
   950    967   	     "                 (*.osm.pbf) are indifferently supported.\n\n");
   951    968       fprintf (stderr,
   952    969   	     "-d or --db-path  pathname       the SpatiaLite DB path\n\n");
................................................................................
  1016   1033   		continue;
  1017   1034   	    }
  1018   1035   	  if (strcasecmp (argv[i], "--help") == 0
  1019   1036   	      || strcmp (argv[i], "-h") == 0)
  1020   1037   	    {
  1021   1038   		do_help ();
  1022   1039   		return -1;
         1040  +	    }
         1041  +	  if (strcasecmp (argv[i], "--version") == 0
         1042  +	      || strcmp (argv[i], "-v") == 0)
         1043  +	    {
         1044  +		do_version ();
         1045  +		return -1;
  1023   1046   	    }
  1024   1047   	  if (strcmp (argv[i], "-o") == 0)
  1025   1048   	    {
  1026   1049   		next_arg = ARG_OSM_PATH;
  1027   1050   		continue;
  1028   1051   	    }
  1029   1052   	  if (strcasecmp (argv[i], "--osm-path") == 0)

Changes to spatialite_tool.c.

    93     93         }
    94     94       sqlite3_free_table (results);
    95     95   
    96     96       if (count > 0)
    97     97   	return;
    98     98   
    99     99   /* all right, it's empty: proceding to initialize */
   100         -    strcpy (sql, "SELECT InitSpatialMetadata(1)");
          100  +    strcpy (sql, "SELECT InitSpatialMetadataFull(1)");
   101    101       ret = sqlite3_exec (db, sql, NULL, NULL, &err_msg);
   102    102       if (ret != SQLITE_OK)
   103    103         {
   104         -	  fprintf (stderr, "InitSpatialMetadata() error: %s\n", err_msg);
          104  +	  fprintf (stderr, "InitSpatialMetadataFull() error: %s\n", err_msg);
   105    105   	  sqlite3_free (err_msg);
   106    106   	  return;
   107    107         }
   108    108   }
   109    109   
   110    110   static void
   111    111   do_import_dbf (char *db_path, char *dbf_path, char *table, char *charset)
................................................................................
   224    224   /* disconnecting the SpatiaLite DB */
   225    225       ret = sqlite3_close (handle);
   226    226       if (ret != SQLITE_OK)
   227    227   	fprintf (stderr, "sqlite3_close() error: %s\n",
   228    228   		 sqlite3_errmsg (handle));
   229    229       spatialite_cleanup_ex (cache);
   230    230   }
          231  +
          232  +static void
          233  +do_version ()
          234  +{
          235  +/* printing version infos */
          236  +	fprintf( stderr, "\nVersion infos\n");
          237  +	fprintf( stderr, "===========================================\n");
          238  +    fprintf (stderr, "exif_loader .: %s\n", VERSION);
          239  +	fprintf (stderr, "target CPU ..: %s\n", spatialite_target_cpu ());
          240  +    fprintf (stderr, "libspatialite: %s\n", spatialite_version ());
          241  +    fprintf (stderr, "libsqlite3 ..: %s\n", sqlite3_libversion ());
          242  +    fprintf (stderr, "\n");
          243  +}
   231    244   
   232    245   static void
   233    246   do_help ()
   234    247   {
   235    248   /* printing the argument list */
   236    249       fprintf (stderr, "\n\nusage: spatitalite_tool CMD ARGLIST\n");
   237    250       fprintf (stderr,
   238    251   	     "==============================================================\n");
   239    252       fprintf (stderr, "CMD has to be one of the followings:\n");
   240    253       fprintf (stderr, "------------------------------------\n");
   241    254       fprintf (stderr,
   242    255   	     "-h or --help                      print this help message\n");
          256  +    fprintf (stderr, "-v or --version                   print version infos\n");
   243    257       fprintf (stderr,
   244    258   	     "-i or --import                    import [CSV/TXT, DBF or SHP]\n");
   245    259       fprintf (stderr,
   246    260   	     "-e or --export-shp                exporting some shapefile\n");
   247    261       fprintf (stderr, "\nsupported ARGs are:\n");
   248    262       fprintf (stderr, "-------------------\n");
   249    263       fprintf (stderr, "-dbf or --dbf-path pathname       the full DBF path\n");
................................................................................
   332    346   		continue;
   333    347   	    }
   334    348   	  if (strcasecmp (argv[i], "--help") == 0
   335    349   	      || strcmp (argv[i], "-h") == 0)
   336    350   	    {
   337    351   		do_help ();
   338    352   		return -1;
          353  +	    }
          354  +	  if (strcasecmp (argv[i], "--version") == 0
          355  +	      || strcmp (argv[i], "-v") == 0)
          356  +	    {
          357  +		do_version ();
          358  +		return -1;
   339    359   	    }
   340    360   	  if (strcasecmp (argv[i], "--shapefile") == 0)
   341    361   	    {
   342    362   		next_arg = ARG_SHP;
   343    363   		in_shp = 1;
   344    364   		continue;
   345    365   	    }

Added spatialite_xml2utf8.c.

            1  +/* 
            2  +/ spatialite_xml2utf8
            3  +/
            4  +/ a tool converting the charset encoding for any XML as UTF-8
            5  +/
            6  +/ version 1.0, 2017 August 25
            7  +/
            8  +/ Author: Sandro Furieri a.furieri@lqt.it
            9  +/
           10  +/ Copyright (C) 2017  Alessandro Furieri
           11  +/
           12  +/    This program is free software: you can redistribute it and/or modify
           13  +/    it under the terms of the GNU General Public License as published by
           14  +/    the Free Software Foundation, either version 3 of the License, or
           15  +/    (at your option) any later version.
           16  +/
           17  +/    This program is distributed in the hope that it will be useful,
           18  +/    but WITHOUT ANY WARRANTY; without even the implied warranty of
           19  +/    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
           20  +/    GNU General Public License for more details.
           21  +/
           22  +/    You should have received a copy of the GNU General Public License
           23  +/    along with this program.  If not, see <http://www.gnu.org/licenses/>.
           24  +/
           25  +*/
           26  +
           27  +#include <stdlib.h>
           28  +#include <stdio.h>
           29  +
           30  +#if defined(_WIN32) && !defined(__MINGW32__)
           31  +#include "config-msvc.h"
           32  +#else
           33  +#include "config.h"
           34  +#endif
           35  +
           36  +#if defined(__MINGW32__) || defined(_WIN32)
           37  +#define LIBICONV_STATIC
           38  +#include <iconv.h>
           39  +#define LIBCHARSET_STATIC
           40  +#ifdef _MSC_VER
           41  +/* <localcharset.h> isn't supported on OSGeo4W */
           42  +/* applying a tricky workaround to fix this issue */
           43  +extern const char *locale_charset (void);
           44  +#else /* sane Windows - not OSGeo4W */
           45  +#include <localcharset.h>
           46  +#endif /* end localcharset */
           47  +#else /* not MINGW32 - WIN32 */
           48  +#if defined(__APPLE__) || defined(__ANDROID__)
           49  +#include <iconv.h>
           50  +#include <localcharset.h>
           51  +#else /* neither Mac OsX nor Android */
           52  +#include <iconv.h>
           53  +#include <langinfo.h>
           54  +#endif
           55  +#endif
           56  +
           57  +static void
           58  +do_convert (iconv_t cvt, char *in, char *out, size_t i_len)
           59  +{
           60  +    size_t i;
           61  +    size_t max_len = i_len * 4;
           62  +    size_t o_len = max_len;
           63  +    char *p_in = in;
           64  +    char *p_out = out;
           65  +    if (iconv (cvt, &p_in, &i_len, &p_out, &o_len) == (size_t) (-1))
           66  +      {
           67  +	  fprintf (stderr, "invalid character sequence !!!\n");
           68  +	  return;
           69  +      }
           70  +    for (i = 0; i < max_len - o_len; i++)
           71  +	putchar (out[i]);
           72  +    putchar ('\n');
           73  +}
           74  +
           75  +int
           76  +main (int argc, const char *argv[])
           77  +{
           78  +    int lineno = 0;
           79  +    size_t count;
           80  +    char *out = malloc (1024 * 1024);
           81  +    char *in = malloc (1024 * 1924);
           82  +    char *p_in;
           83  +    iconv_t cvt;
           84  +    const char *charset = NULL;
           85  +    if (argc != 2)
           86  +      {
           87  +	  fprintf (stderr,
           88  +		   "usage: spatialite_utf8 input-charset <input >output\n");
           89  +	  return -1;
           90  +      }
           91  +    charset = argv[1];
           92  +
           93  +    cvt = iconv_open ("UTF-8", charset);
           94  +    if (cvt == (iconv_t) (-1))
           95  +      {
           96  +	  fprintf (stderr, "Unknown charset: %s\n", charset);
           97  +	  goto stop;
           98  +      }
           99  +
          100  +    count = 0;
          101  +    p_in = in;
          102  +    while (1)
          103  +      {
          104  +	  int c = getchar ();
          105  +	  if (c == EOF || c == '\n')
          106  +	    {
          107  +		if (lineno > 0)
          108  +		    do_convert (cvt, in, out, count);
          109  +		else
          110  +		    printf ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
          111  +		if (c == EOF)
          112  +		    break;
          113  +		lineno++;
          114  +		count = 0;
          115  +		p_in = in;
          116  +		continue;
          117  +	    }
          118  +	  *p_in++ = c;
          119  +	  count++;
          120  +      }
          121  +
          122  +    iconv_close (cvt);
          123  +
          124  +  stop:
          125  +    return 0;
          126  +}

Changes to spatialite_xml_collapse.c.

    41     41   
    42     42   #include <stdlib.h>
    43     43   #include <stdio.h>
    44     44   #include <string.h>
    45     45   
    46     46   #include <sqlite3.h>
    47     47   #include <spatialite.h>
           48  +
           49  +#if defined(_WIN32) && !defined(__MINGW32__)
           50  +#include "config-msvc.h"
           51  +#else
           52  +#include "config.h"
           53  +#endif
    48     54   
    49     55   #define ARG_NONE	0
    50     56   #define ARG_DB_PATH	1
    51     57   #define ARG_CACHE_SIZE 2
    52     58   #define ARG_NAME_LEVEL 3
    53     59   
    54     60   struct resultset_values
................................................................................
  1861   1867         }
  1862   1868       sqlite3_free_table (results);
  1863   1869   
  1864   1870       if (count > 0)
  1865   1871   	return;
  1866   1872   
  1867   1873   /* all right, it's empty: proceding to initialize */
  1868         -    strcpy (sql, "SELECT InitSpatialMetadata(1)");
         1874  +    strcpy (sql, "SELECT InitSpatialMetadataFull(1)");
  1869   1875       ret = sqlite3_exec (db, sql, NULL, NULL, &err_msg);
  1870   1876       if (ret != SQLITE_OK)
  1871   1877         {
  1872         -	  fprintf (stderr, "InitSpatialMetadata() error: %s\n", err_msg);
         1878  +	  fprintf (stderr, "InitSpatialMetadataFull() error: %s\n", err_msg);
  1873   1879   	  sqlite3_free (err_msg);
  1874   1880   	  return;
  1875   1881         }
  1876   1882   }
  1877   1883   
  1878   1884   static int
  1879   1885   check_xml_metacatalog (sqlite3 * db_handle)
................................................................................
  2032   2038         }
  2033   2039   
  2034   2040   /* enabling PK/FK constraints */
  2035   2041       sqlite3_exec (db_handle, "PRAGMA foreign_keys = 1", NULL, NULL, NULL);
  2036   2042       *handle = db_handle;
  2037   2043       return;
  2038   2044   }
         2045  +
         2046  +static void
         2047  +do_version ()
         2048  +{
         2049  +/* printing version infos */
         2050  +	fprintf( stderr, "\nVersion infos\n");
         2051  +	fprintf( stderr, "===========================================\n");
         2052  +    fprintf (stderr, "spatialite_osm_overpass: %s\n", VERSION);
         2053  +	fprintf (stderr, "target CPU ............: %s\n", spatialite_target_cpu ());
         2054  +    fprintf (stderr, "libspatialite .........: %s\n", spatialite_version ());
         2055  +    fprintf (stderr, "libsqlite3 ............: %s\n", sqlite3_libversion ());
         2056  +    fprintf (stderr, "\n");
         2057  +}
  2039   2058   
  2040   2059   static void
  2041   2060   do_help ()
  2042   2061   {
  2043   2062   /* printing the argument list */
  2044   2063       fprintf (stderr, "\n\nusage: spatialite_xml_collapse ARGLIST\n");
  2045   2064       fprintf (stderr,
  2046   2065   	     "==============================================================\n");
  2047   2066       fprintf (stderr,
  2048   2067   	     "-h or --help                    print this help message\n");
         2068  +    fprintf (stderr, "-v or --version                 print version infos\n");
  2049   2069       fprintf (stderr,
  2050   2070   	     "-d or --db-path     pathname    the SpatiaLite DB path\n\n");
  2051   2071       fprintf (stderr, "you can specify the following options as well\n");
  2052   2072       fprintf (stderr,
  2053   2073   	     "-dd or --delete-duplicates      remove all duplicate rows except one\n");
  2054   2074       fprintf (stderr,
  2055   2075   	     "-nl or --nl-level      num      tree-level for table-names (dft: 0)\n\n");
................................................................................
  2107   2127   		continue;
  2108   2128   	    }
  2109   2129   	  if (strcasecmp (argv[i], "--help") == 0
  2110   2130   	      || strcmp (argv[i], "-h") == 0)
  2111   2131   	    {
  2112   2132   		do_help ();
  2113   2133   		return -1;
         2134  +	    }
         2135  +	  if (strcasecmp (argv[i], "--version") == 0
         2136  +	      || strcmp (argv[i], "-v") == 0)
         2137  +	    {
         2138  +		do_version ();
         2139  +		return -1;
  2114   2140   	    }
  2115   2141   	  if (strcmp (argv[i], "-d") == 0)
  2116   2142   	    {
  2117   2143   		next_arg = ARG_DB_PATH;
  2118   2144   		continue;
  2119   2145   	    }
  2120   2146   	  if (strcasecmp (argv[i], "--db-path") == 0)

Changes to spatialite_xml_load.c.

    43     43   #include <stdlib.h>
    44     44   #include <stdio.h>
    45     45   #include <string.h>
    46     46   #include <libgen.h>
    47     47   
    48     48   #include <expat.h>
    49     49   
           50  +#if defined(_WIN32) && !defined(__MINGW32__)
           51  +#include "config-msvc.h"
           52  +#else
    50     53   #include "config.h"
           54  +#endif
    51     55   
    52     56   #ifdef SPATIALITE_AMALGAMATION
    53     57   #include <spatialite/sqlite3.h>
    54     58   #else
    55     59   #include <sqlite3.h>
    56     60   #endif
    57     61   #include <spatialite.h>
................................................................................
  2209   2213         }
  2210   2214       sqlite3_free_table (results);
  2211   2215   
  2212   2216       if (count > 0)
  2213   2217   	return;
  2214   2218   
  2215   2219   /* all right, it's empty: proceding to initialize */
  2216         -    strcpy (sql, "SELECT InitSpatialMetadata(1)");
         2220  +    strcpy (sql, "SELECT InitSpatialMetadataFull(1)");
  2217   2221       ret = sqlite3_exec (db, sql, NULL, NULL, &err_msg);
  2218   2222       if (ret != SQLITE_OK)
  2219   2223         {
  2220         -	  fprintf (stderr, "InitSpatialMetadata() error: %s\n", err_msg);
         2224  +	  fprintf (stderr, "InitSpatialMetadataFull() error: %s\n", err_msg);
  2221   2225   	  sqlite3_free (err_msg);
  2222   2226   	  return;
  2223   2227         }
  2224   2228   }
  2225   2229   
  2226   2230   static void
  2227   2231   open_db (const char *path, sqlite3 ** handle, int cache_size, void *cache)

Changes to spatialite_xml_print.c.

    40     40   #include <sys/types.h>
    41     41   #endif
    42     42   
    43     43   #include <stdlib.h>
    44     44   #include <stdio.h>
    45     45   #include <string.h>
    46     46   
           47  +#if defined(_WIN32) && !defined(__MINGW32__)
           48  +#include "config-msvc.h"
           49  +#else
    47     50   #include "config.h"
           51  +#endif
    48     52   
    49     53   #ifdef SPATIALITE_AMALGAMATION
    50     54   #include <spatialite/sqlite3.h>
    51     55   #else
    52     56   #include <sqlite3.h>
    53     57   #endif
    54     58   #include <spatialite.h>
................................................................................
   918    922         }
   919    923   
   920    924   /* enabling PK/FK constraints */
   921    925       sqlite3_exec (db_handle, "PRAGMA foreign_keys = 1", NULL, NULL, NULL);
   922    926       *handle = db_handle;
   923    927       return;
   924    928   }
          929  +
          930  +static void
          931  +do_version ()
          932  +{
          933  +/* printing version infos */
          934  +	fprintf( stderr, "\nVersion infos\n");
          935  +	fprintf( stderr, "===========================================\n");
          936  +    fprintf (stderr, "spatialite_xml_print: %s\n", VERSION);
          937  +	fprintf (stderr, "target CPU .........: %s\n", spatialite_target_cpu ());
          938  +    fprintf (stderr, "libspatialite ......: %s\n", spatialite_version ());
          939  +    fprintf (stderr, "libsqlite3 .........: %s\n", sqlite3_libversion ());
          940  +    fprintf (stderr, "\n");
          941  +}
   925    942   
   926    943   static void
   927    944   do_help ()
   928    945   {
   929    946   /* printing the argument list */
   930    947       fprintf (stderr, "\n\nusage: spatialite_xml_printf ARGLIST\n");
   931    948       fprintf (stderr,
   932    949   	     "==============================================================\n");
   933    950       fprintf (stderr,
   934    951   	     "-h or --help                    print this help message\n");
          952  +    fprintf (stderr, "-v or --version                 print version infos\n");
   935    953       fprintf (stderr,
   936    954   	     "-d or --db-path     pathname    the SpatiaLite DB [INPUT] path\n\n");
   937    955       fprintf (stderr,
   938    956   	     "-x or --xml-path    pathname    the XML file [OUTPUT] path\n");
   939    957       fprintf (stderr,
   940    958   	     "-cs or --cache-size    num      DB cache size (how many pages)\n");
   941    959       fprintf (stderr,
................................................................................
   978    996   		continue;
   979    997   	    }
   980    998   	  if (strcasecmp (argv[i], "--help") == 0
   981    999   	      || strcmp (argv[i], "-h") == 0)
   982   1000   	    {
   983   1001   		do_help ();
   984   1002   		return -1;
         1003  +	    }
         1004  +	  if (strcasecmp (argv[i], "--version") == 0
         1005  +	      || strcmp (argv[i], "-v") == 0)
         1006  +	    {
         1007  +		do_version ();
         1008  +		return -1;
   985   1009   	    }
   986   1010   	  if (strcmp (argv[i], "-x") == 0)
   987   1011   	    {
   988   1012   		next_arg = ARG_XML_PATH;
   989   1013   		continue;
   990   1014   	    }
   991   1015   	  if (strcasecmp (argv[i], "--xml-path") == 0)

Changes to spatialite_xml_validator.c.

    24     24   /
    25     25   */
    26     26   
    27     27   #include <stdlib.h>
    28     28   #include <stdio.h>
    29     29   #include <string.h>
    30     30   
           31  +#if defined(_WIN32) && !defined(__MINGW32__)
           32  +#include "config-msvc.h"
           33  +#else
    31     34   #include "config.h"
           35  +#endif
           36  +
           37  +#ifdef ENABLE_LIBXML2		/* only if LIBXML2 is enabled */
    32     38   
    33     39   #include <libxml/parser.h>
    34     40   #include <libxml/xmlschemas.h>
    35     41   #include <libxml/xpath.h>
    36     42   #include <libxml/xpathInternals.h>
    37     43   
    38     44   struct list_item
................................................................................
   632    638   	xmlFreeDoc (xml_doc);
   633    639       if (schemaURI != NULL)
   634    640   	free (schemaURI);
   635    641       fprintf (stderr, "ERROR - invalid XML: %s\n\n", path);
   636    642       return 0;
   637    643   }
   638    644   
          645  +#endif /* end LIBXML2 conditional */
          646  +
   639    647   int
   640    648   main (int argc, char *argv[])
   641    649   {
   642    650   /* the MAIN function mainly perform arguments checking */
          651  +
          652  +#ifndef ENABLE_LIBXML2		/* only if LIBXML2 is disabled */
          653  +    fprintf (stderr, "\nthis copy of \"spatialite_xml_validator\"\n"
          654  +	     "was built by disabling LIBXML2 support.\n"
          655  +	     "Sorry, cowardly quitting ...\n");
          656  +    return 0;
          657  +#else
   643    658       const char *xml_path = NULL;
   644    659       const char *list_path = NULL;
   645    660       int single = 0;
   646    661       int list = 0;
   647    662       int err = 1;
   648    663       int valids = 0;
   649    664       int invalids = 0;
................................................................................
   711    726       cache_cleanup (&cache);
   712    727       xmlCleanupParser ();
   713    728       return 0;
   714    729     error:
   715    730       cache_cleanup (&cache);
   716    731       xmlCleanupParser ();
   717    732       return -1;
          733  +#endif /* end LIBXML2 conditional */
   718    734   }