Check-in Differences
Not logged in

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

Difference From 360acb727dbc921e To 80a1ab14a287da4c

2011-11-10
17:01
switching to version 1.2.1 check-in: 740a9a5992 user: sandro tags: trunk
16:52
switching to version 2.3.0 check-in: 80a1ab14a2 user: sandro tags: trunk
16:37
switching to version 1.1 check-in: 360acb727d user: sandro tags: trunk
16:29
initial repository set up check-in: 1cd01d9029 user: sandro tags: trunk

Changes to BlobExplorer.cpp.

1
2
3
4
5
6
7
8
9
10
11
12
..
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50

51
52
53
54

55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78


79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162

163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247

248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283

284
285
286
287
288






289
290






291
292






293
294




295
296




297
298


299
300


301
302
303
304
305
306
307
308
309
310
311


312
313
314
315
316
317
318
319
320
321
322
323
324
325


326
327
328
329


330
331
332
333
334
335
336
337
338


339
340
341
342
343
344
345
346
347
348
349
350
351
352


353
354
355
356


357
358
359
360
361
362
363
364
365


366
367
368
369
370
371
372
373
374
375
376
377
378
379
380

381
382
383
384
385


386
387
388
389
390
391


392
393
394
395
396
397
398

399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426



427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462


463
464
465

466
467
468



















469
470
471

472
473
474


475
476
477

478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661


662

663
664
665
666
667
668

669

670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685

686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749

750
751
752
753



754
755
756
757
758
759
760
761
762


763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779

780

781
782
783
784
785
786
787
788
/*
/ BlobExplorer.cpp
/ a dialog to explore a BLOB value
/
/ version 1.1, 2008 September 13
/
/ Author: Sandro Furieri a-furieri@lqt.it
/
/ Copyright (C) 2008  Alessandro Furieri
/
/    This program is free software: you can redistribute it and/or modify
/    it under the terms of the GNU General Public License as published by
................................................................................
*/

#include "Classdef.h"

#include "wx/mstream.h"
#include "wx/clipbrd.h"

BlobExplorerDialog::BlobExplorerDialog (MyFrame * parent, int blob_size,
					unsigned char *blob)
{
//
// constructor; just calls Create()
//
    Create (parent, blob_size, blob);
}

bool
BlobExplorerDialog::Create (MyFrame * parent, int blob_size,
			    unsigned char *blob)
{
//
// creating the dialog
//
    MainFrame = parent;
    BlobSize = blob_size;
    Blob = blob;
    BlobType = MainFrame->GuessBlobType (BlobSize, Blob);

    Geometry = NULL;
    Image = NULL;
    if (BlobType == MyFrame::BLOB_GEOMETRY)
	Geometry = gaiaFromSpatiaLiteBlobWkb (Blob, BlobSize);

    if (BlobType == MyFrame::BLOB_JPEG || BlobType == MyFrame::BLOB_PNG
	|| BlobType == MyFrame::BLOB_GIF)
      {
	  ::wxInitAllImageHandlers ();
	  wxMemoryInputStream reader (Blob, BlobSize);
	  Image = new wxImage (reader);
      }
    if (wxPropertySheetDialog::Create
	(parent, wxID_ANY, wxT ("BLOB explorer"), wxDefaultPosition,
	 wxDefaultSize,
	 wxDEFAULT_DIALOG_STYLE | (int) wxPlatform::IfNot (wxOS_WINDOWS_CE,
							   wxRESIZE_BORDER))
	== false)
	return false;
    wxBookCtrlBase *book = GetBookCtrl ();
// creates individual panels
    wxPanel *hexadecimal = CreateHexadecimalPage (book);
    book->AddPage (hexadecimal, wxT ("Hexadecimal dump"), true);
    if (BlobType == MyFrame::BLOB_GEOMETRY)
      {
	  wxPanel *geometry = CreateGeometryPage (book);
	  book->AddPage (geometry, wxT ("Geometry explorer"), false);
      }
    if (BlobType == MyFrame::BLOB_JPEG || BlobType == MyFrame::BLOB_PNG


	|| BlobType == MyFrame::BLOB_GIF)
      {
	  wxPanel *image = CreateImagePage (book);
	  book->AddPage (image, wxT ("Image"), false);
      }
    CreateButtons (wxOK);
    LayoutDialog ();
// appends event handler for TAB/PAGE changing
    Connect (wxID_ANY, wxEVT_COMMAND_NOTEBOOK_PAGE_CHANGED,
	     (wxObjectEventFunction) & BlobExplorerDialog::OnPageChanged);
// appends event handler for OK button
    Connect (wxID_OK, wxEVT_COMMAND_BUTTON_CLICKED,
	     (wxObjectEventFunction) & BlobExplorerDialog::OnOk);
// centers the dialog window
    Centre ();
    UpdateHexadecimalPage ();
    return true;
}

wxPanel *
BlobExplorerDialog::CreateHexadecimalPage (wxWindow * parent)
{
//
// creating the HEXADECIMAL page
//
    wxPanel *panel = new wxPanel (parent, ID_PANE_HEXADECIMAL);
    wxBoxSizer *topSizer = new wxBoxSizer (wxVERTICAL);
    panel->SetSizer (topSizer);
    wxBoxSizer *boxSizer = new wxBoxSizer (wxVERTICAL);
    topSizer->Add (boxSizer, 0, wxALIGN_CENTER | wxALL, 5);
// creating a control to show the hexadecimal dump
    wxBoxSizer *hexSizer = new wxBoxSizer (wxHORIZONTAL);
    boxSizer->Add (hexSizer, 0, wxALIGN_LEFT | wxALL, 0);
    MyHexList *hexCtrl = new MyHexList (this, Blob, BlobSize, panel,
					ID_HEX, wxDefaultPosition,
					wxSize (560,
						320),
					wxLC_REPORT | wxLC_VIRTUAL);
    wxFont font (9, wxFONTFAMILY_MODERN, wxFONTSTYLE_NORMAL,
		 wxFONTWEIGHT_NORMAL);
    hexCtrl->SetFont (font);
    wxListItem column0;
    hexCtrl->InsertColumn (0, wxT ("Address"));
    hexCtrl->SetColumnWidth (0, 90);
    hexCtrl->InsertColumn (1, wxT ("Hexadecimal"));
    hexCtrl->SetColumnWidth (1, 340);
    hexCtrl->InsertColumn (2, wxT ("ASCII"));
    hexCtrl->SetColumnWidth (2, 90);
    hexSizer->Add (hexCtrl, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
    panel->SetSizer (topSizer);
    topSizer->Fit (panel);
    return panel;
}

wxPanel *
BlobExplorerDialog::CreateGeometryPage (wxWindow * parent)
{
//
// creating the GEOMETRY page
//
    wxPanel *panel = new wxPanel (parent, ID_PANE_HEXADECIMAL);
    wxBoxSizer *topSizer = new wxBoxSizer (wxVERTICAL);
    panel->SetSizer (topSizer);
    wxBoxSizer *boxSizer = new wxBoxSizer (wxVERTICAL);
    topSizer->Add (boxSizer, 0, wxALIGN_CENTER | wxALL, 5);
// creating a control to show the geometry as a text table
    wxBoxSizer *geomSizer = new wxBoxSizer (wxHORIZONTAL);
    boxSizer->Add (geomSizer, 0, wxALIGN_LEFT | wxALL, 0);
    wxTextCtrl *geomCtrl = new wxTextCtrl (panel, ID_GEOM_TABLE, wxT (""),
					   wxDefaultPosition, wxSize (270,
								      320),
					   wxTE_MULTILINE | wxTE_RICH |
					   wxTE_READONLY | wxHSCROLL);
    geomSizer->Add (geomCtrl, 0, wxALIGN_LEFT | wxALL, 5);
// creating a control to show the geometry in a graphical fashion
    wxStaticBox *exBox = new wxStaticBox (panel, wxID_STATIC,
					  wxT ("Geometry preview"),
					  wxDefaultPosition, wxDefaultSize);
    wxBoxSizer *exampleSizer = new wxStaticBoxSizer (exBox, wxHORIZONTAL);
    geomSizer->Add (exampleSizer, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
    DrawGeometry (270, 270);
    GraphicsGeometry *geomGraph =
	new GraphicsGeometry (this, panel, ID_GEOM_GRAPH,
			      GeomPreview, wxSize (270, 270));

    exampleSizer->Add (geomGraph, 0, wxALIGN_CENTER_VERTICAL | wxALL, 0);
    panel->SetSizer (topSizer);
    topSizer->Fit (panel);
    return panel;
}

wxPanel *
BlobExplorerDialog::CreateImagePage (wxWindow * parent)
{
//
// creating the IMAGE page
//
    wxPanel *panel = new wxPanel (parent, ID_PANE_IMAGE);
    wxBoxSizer *topSizer = new wxBoxSizer (wxVERTICAL);
    panel->SetSizer (topSizer);
    wxBoxSizer *boxSizer = new wxBoxSizer (wxVERTICAL);
    topSizer->Add (boxSizer, 0, wxALIGN_CENTER | wxALL, 5);
// creating a control to show the image title
    wxBoxSizer *imgSizer = new wxBoxSizer (wxVERTICAL);
    boxSizer->Add (imgSizer, 0, wxALIGN_TOP | wxALL, 0);
    wxStaticText *imageTitle = new wxStaticText (panel, ID_IMAGE_TITLE,
						 wxT ("Image"),
						 wxDefaultPosition,
						 wxSize (560,
							 10));
    imgSizer->Add (imageTitle, 0, wxALIGN_LEFT | wxALL, 5);
// creating a control to show the image
    wxStaticBox *exBox = new wxStaticBox (panel, ID_IMG_BOX,
					  wxT ("Image preview"),
					  wxDefaultPosition, wxDefaultSize);
    wxBoxSizer *exampleSizer = new wxStaticBoxSizer (exBox, wxHORIZONTAL);
    imgSizer->Add (exampleSizer, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
    ImageShow *imgShow = new ImageShow (this, panel, ID_IMAGE,
					wxBitmap (), wxSize (560, 300));
    exampleSizer->Add (imgShow, 0, wxALIGN_CENTER_VERTICAL | wxALL, 0);
    panel->SetSizer (topSizer);
    topSizer->Fit (panel);
    return panel;
}

void
BlobExplorerDialog::OnPageChanged (wxNotebookEvent & event)
{
//
// TAB/PAGE selection changed
//
    switch (event.GetSelection ())
      {
      case 0:
	  UpdateHexadecimalPage ();
	  break;
      case 1:
	  if (BlobType == MyFrame::BLOB_GEOMETRY)
	      UpdateGeometryPage ();
	  else
	      UpdateImagePage ();
	  break;
      };
}

void
BlobExplorerDialog::UpdateHexadecimalPage ()
{
//
// updating the HEXADECIMAL page
//
    MyHexList *hexCtrl = (MyHexList *) FindWindow (ID_HEX);
    hexCtrl->EnsureVisible (0);
}

void
BlobExplorerDialog::UpdateGeometryPage ()
{
//
// updating the GEOMETRY page
//
    gaiaPointPtr pt;
    gaiaLinestringPtr ln;
    gaiaPolygonPtr pg;
    gaiaRingPtr rng;
    int points = 0;
    int linestrings = 0;
    int polygons = 0;
    int ib;
    wxString strValue;

    wxTextAttr attrBold (wxColour (0, 0, 0), wxColour (255, 255, 255),
			 wxFont (9, wxFONTFAMILY_MODERN, wxFONTSTYLE_NORMAL,
				 wxFONTWEIGHT_BOLD));
    wxTextAttr attrNorm (wxColour (0, 0, 0), wxColour (255, 255, 255),
			 wxFont (9, wxFONTFAMILY_MODERN, wxFONTSTYLE_NORMAL,
				 wxFONTWEIGHT_NORMAL));
    wxTextCtrl *geomCtrl = (wxTextCtrl *) FindWindow (ID_GEOM_TABLE);
    if (geomCtrl->GetValue ().Len () < 1)
      {
	  ::wxBeginBusyCursor ();
	  pt = Geometry->FirstPoint;
	  while (pt)
	    {
		// counting how many points are into this Geometry
		points++;
		pt = pt->Next;
	    }
	  ln = Geometry->FirstLinestring;
	  while (ln)
	    {
		// counting how many linestrings are into this Geometry
		linestrings++;
		ln = ln->Next;
	    }
	  pg = Geometry->FirstPolygon;
	  while (pg)
	    {
		// counting how many polygons are into this Geometry
		polygons++;
		pg = pg->Next;
	    }
	  // determining the Geometry type
	  geomCtrl->SetDefaultStyle (attrNorm);
	  geomCtrl->AppendText (wxT ("SRID: "));
	  geomCtrl->SetDefaultStyle (attrBold);
	  strValue.Printf (wxT ("%d"), Geometry->Srid);

	  geomCtrl->AppendText (strValue);
	  geomCtrl->SetDefaultStyle (attrNorm);
	  geomCtrl->AppendText (wxT ("\n\n"));
	  strValue = wxT ("UNKNOWN GEOMETRY TYPE");
	  if (points == 1 && linestrings == 0 && polygons == 0)






	      strValue = wxT ("POINT");
	  else if (points == 0 && linestrings == 1 && polygons == 0)






	      strValue = wxT ("LINESTRING");
	  else if (points == 0 && linestrings == 0 && polygons == 1)






	      strValue = wxT ("POLYGON");
	  else if (points > 1 && linestrings == 0 && polygons == 0)




	      strValue = wxT ("MULTIPOINT");
	  else if (points == 0 && linestrings > 1 && polygons == 0)




	      strValue = wxT ("MULTILINESTRING");
	  else if (points == 0 && linestrings == 0 && polygons > 1)


	      strValue = wxT ("MULTIPOLYGON");
	  else


	      strValue = wxT ("GEOMETRYCOLLECTION");
	  geomCtrl->SetDefaultStyle (attrNorm);
	  geomCtrl->AppendText (wxT ("Geometry type: "));
	  geomCtrl->SetDefaultStyle (attrBold);
	  geomCtrl->AppendText (strValue);
	  geomCtrl->SetDefaultStyle (attrNorm);
	  geomCtrl->AppendText (wxT ("\n\n"));
	  if (points)
	    {
		// printing the Points list
		strValue.Printf (wxT ("#%d POINT"), points);


		if (points > 1)
		    strValue += wxT ("s:");
		else
		    strValue += wxT (":");
		geomCtrl->SetDefaultStyle (attrBold);
		geomCtrl->AppendText (strValue);
		geomCtrl->SetDefaultStyle (attrNorm);
		pt = Geometry->FirstPoint;
		points = 0;
		while (pt)
		  {
		      // printing each Point
		      points++;
		      strValue.Printf (wxT ("\n  %d) "), points);


		      geomCtrl->SetDefaultStyle (attrBold);
		      geomCtrl->AppendText (strValue);
		      geomCtrl->SetDefaultStyle (attrNorm);
		      strValue.Printf (wxT ("%1.4lf  %1.4lf"), pt->X, pt->Y);


		      geomCtrl->AppendText (strValue);
		      pt = pt->Next;
		  }
		geomCtrl->AppendText (wxT ("\n\n\n"));
	    }
	  if (linestrings)
	    {
		// printing the Linestrings list
		strValue.Printf (wxT ("#%d LINESTRING"), linestrings);


		if (linestrings > 1)
		    strValue += wxT ("s:");
		else
		    strValue += wxT (":");
		geomCtrl->SetDefaultStyle (attrBold);
		geomCtrl->AppendText (strValue);
		geomCtrl->SetDefaultStyle (attrNorm);
		ln = Geometry->FirstLinestring;
		linestrings = 0;
		while (ln)
		  {
		      // printing each Linestring
		      linestrings++;
		      strValue.Printf (wxT ("\n  %d) "), linestrings);


		      geomCtrl->SetDefaultStyle (attrBold);
		      geomCtrl->AppendText (strValue);
		      geomCtrl->SetDefaultStyle (attrNorm);
		      strValue.Printf (wxT ("%d vertices"), ln->Points);


		      geomCtrl->AppendText (strValue);
		      ln = ln->Next;
		  }
		geomCtrl->AppendText (wxT ("\n\n\n"));
	    }
	  if (polygons)
	    {
		// printing the Polygons list
		strValue.Printf (wxT ("#%d POLYGON"), polygons);


		if (polygons > 1)
		    strValue += wxT ("s:");
		else
		    strValue += wxT (":");
		geomCtrl->SetDefaultStyle (attrBold);
		geomCtrl->AppendText (strValue);
		geomCtrl->SetDefaultStyle (attrNorm);
		pg = Geometry->FirstPolygon;
		polygons = 0;
		while (pg)
		  {
		      // printing each Polygon
		      polygons++;
		      strValue.Printf (wxT ("\n  %d)    exterior ring"),
				       polygons);

		      geomCtrl->SetDefaultStyle (attrBold);
		      geomCtrl->AppendText (strValue);
		      geomCtrl->SetDefaultStyle (attrNorm);
		      rng = pg->Exterior;
		      strValue.Printf (wxT (": %d vertices"), rng->Points);


		      geomCtrl->AppendText (strValue);
		      for (ib = 0; ib < pg->NumInteriors; ib++)
			{
			    // printing each interior ring
			    strValue.Printf (wxT ("\n  %d.%d) "), polygons,
					     ib + 1);


			    geomCtrl->SetDefaultStyle (attrBold);
			    geomCtrl->AppendText (strValue);
			    geomCtrl->SetDefaultStyle (attrNorm);
			    rng = pg->Interiors + ib;
			    strValue.Printf (wxT
					     (" interior ring: %d vertices"),
					     rng->Points);

			    geomCtrl->AppendText (strValue);
			}
		      pg = pg->Next;
		  }
		geomCtrl->AppendText (wxT ("\n\n\n"));
	    }
	  ::wxEndBusyCursor ();
      }
    GraphicsGeometry *geomGraph =
	(GraphicsGeometry *) FindWindow (ID_GEOM_GRAPH);
    geomGraph->SetBitmap (GeomPreview);
}

void
BlobExplorerDialog::UpdateImagePage ()
{
//
// updating the IMAGE page
//
    double horz;
    double vert;
    wxImage scaledImg;
    wxSize sz;
    wxSize box;
    int boxX;
    int boxY;
    int posX;
    int posY;



    wxString title = wxT ("Invalid Image");
    wxStaticBox *imgBox = (wxStaticBox *) FindWindow (ID_IMG_BOX);
    ImageShow *imgShow = (ImageShow *) FindWindow (ID_IMAGE);
    wxStaticText *imageTitle = (wxStaticText *) FindWindow (ID_IMAGE_TITLE);
    if (Image)
      {
	  ::wxBeginBusyCursor ();
	  if (Image->IsOk () == true)
	    {
		horz = Image->GetWidth ();
		vert = Image->GetHeight ();
		sz = imgShow->GetSize ();
		box = imgBox->GetSize ();
		while (horz > sz.GetWidth () || vert > sz.GetHeight ())
		  {
		      horz *= 0.9;
		      vert *= 0.9;
		  }
		if (horz == Image->GetWidth () && vert == Image->GetHeight ())
		    scaledImg = Image->Copy ();
		else
		    scaledImg =
			Image->Scale ((int) horz, (int) vert,
				      wxIMAGE_QUALITY_HIGH);
		wxBitmap bmp (scaledImg);
		imgBox->GetPosition (&boxX, &boxY);
		posX = (box.GetWidth () - (int) horz) / 2;
		posY = (box.GetHeight () - (int) vert) / 2;
		imgShow->SetSize (boxX + posX, boxY + posY, (int) horz,
				  (int) vert);
		imgShow->SetBitmap (bmp);
		imgShow->Show (true);
		switch (BlobType)
		  {
		  case MyFrame::BLOB_JPEG:
		      title.Printf (wxT


				    ("JPEG image     resolution: %d x %d          %d bytes"),
				    Image->GetWidth (), Image->GetHeight (),
				    BlobSize);

		      break;
		  case MyFrame::BLOB_PNG:
		      title.Printf (wxT



















				    ("PNG image     resolution: %d x %d          %d bytes"),
				    Image->GetWidth (), Image->GetHeight (),
				    BlobSize);

		      break;
		  case MyFrame::BLOB_GIF:
		      title.Printf (wxT


				    ("GIF image     resolution: %d x %d          %d bytes"),
				    Image->GetWidth (), Image->GetHeight (),
				    BlobSize);

		      break;
		  }
	    }
	  ::wxEndBusyCursor ();
      }
    imageTitle->SetLabel (title);
}

void
BlobExplorerDialog::OnOk (wxCommandEvent & event)
{
//
// all done: exiting
//
    wxDialog::EndModal (wxID_OK);
}

void
BlobExplorerDialog::DrawGeometry (int horz, int vert)
{
//
// drawing graphic representation for current Geometry
//
    gaiaPointPtr pt;
    gaiaLinestringPtr ln;
    gaiaPolygonPtr pg;
    gaiaRingPtr rng;
    double minx;
    double miny;
    double maxx;
    double maxy;
    double ext_x;
    double ext_y;
    double cx;
    double cy;
    double pixelRatioX;
    double pixelRatioY;
    double pixelRatio;
    double span_x;
    double span_y;
    double baseX;
    double baseY;
    double x;
    double y;
    double xx;
    double yy;
    int iv;
    int ib;
    int pts;
    int *borders;
    wxPoint *points;
    GeomPreview.Create (horz, vert);
    wxMemoryDC dc (GeomPreview);
//
// background filling
//
    dc.SetBrush (wxBrush (wxColour (255, 255, 255)));
    dc.DrawRectangle (0, 0, horz, vert);
//
// prepearing the drawing pen and brush
//
    dc.SetBrush (wxBrush (wxColour (240, 240, 192)));
    dc.SetPen (wxPen (wxColour (64, 64, 192), 1));
//
// computing the pixel ratio, center position and so on
//
    minx = Geometry->MinX;
    miny = Geometry->MinY;
    maxx = Geometry->MaxX;
    maxy = Geometry->MaxY;
    ext_x = maxx - minx;
    ext_y = maxy - miny;
    if (ext_x < 1.0)
	ext_x = 1.0;
    if (ext_y < 1.0)
	ext_y = 1.0;
    minx = Geometry->MinX - (ext_x / 20.0);
    miny = Geometry->MinY - (ext_y / 20.0);
    maxx = Geometry->MaxX + (ext_x / 20.0);
    maxy = Geometry->MaxY + (ext_y / 20.0);
    ext_x = maxx - minx;
    ext_y = maxy - miny;
    cx = minx + (ext_x / 2.0);
    cy = miny + (ext_y / 2.0);
    pixelRatioX = ext_x / horz;
    pixelRatioY = ext_y / vert;
    if (pixelRatioX > pixelRatioY)
	pixelRatio = pixelRatioX;
    else
	pixelRatio = pixelRatioY;
//
// centering the Y axis
//
    span_y = vert * pixelRatio;
    baseY = cy - (span_y / 2.0);
//
// centering the X axis
//
    span_x = horz * pixelRatio;
    baseX = cx - (span_x / 2.0);
    pg = Geometry->FirstPolygon;
    while (pg)
      {
	  //
	  // drawing polygons
	  //
	  pts = pg->Exterior->Points;
	  for (ib = 0; ib < pg->NumInteriors; ib++)
	    {
		rng = pg->Interiors + ib;
		pts += rng->Points;
	    }
	  borders = new int[pg->NumInteriors + 1];
	  points = new wxPoint[pts];
	  pts = 0;
	  rng = pg->Exterior;
	  borders[0] = rng->Points;
	  for (iv = 0; iv < rng->Points; iv++)
	    {
		gaiaGetPoint (rng->Coords, iv, &x, &y);
		xx = (x - baseX) / pixelRatio;
		yy = (y - baseY) / pixelRatio;
		yy = vert - yy;
		points[pts].x = (int) xx;
		points[pts].y = (int) yy;
		pts++;
	    }
	  for (ib = 0; ib < pg->NumInteriors; ib++)
	    {
		rng = pg->Interiors + ib;
		borders[1 + ib] = rng->Points;
		for (iv = 0; iv < rng->Points; iv++)
		  {
		      gaiaGetPoint (rng->Coords, iv, &x, &y);
		      xx = (x - baseX) / pixelRatio;
		      yy = (y - baseY) / pixelRatio;
		      yy = vert - yy;
		      points[pts].x = (int) xx;
		      points[pts].y = (int) yy;
		      pts++;
		  }
	    }
	  dc.DrawPolyPolygon (pg->NumInteriors + 1, borders, points);
	  delete[]points;
	  delete[]borders;
	  pg = pg->Next;
      }
    ln = Geometry->FirstLinestring;
    while (ln)
      {
	  //
	  // drawing linestrings
	  //
	  points = new wxPoint[ln->Points];
	  for (iv = 0; iv < ln->Points; iv++)
	    {
		gaiaGetPoint (ln->Coords, iv, &x, &y);
		xx = (x - baseX) / pixelRatio;
		yy = (y - baseY) / pixelRatio;
		yy = vert - yy;
		points[iv].x = (int) xx;
		points[iv].y = (int) yy;
	    }
	  dc.DrawLines (ln->Points, points);
	  delete[]points;
	  ln = ln->Next;
      }
    pt = Geometry->FirstPoint;
    while (pt)
      {
	  //
	  // drawing points
	  //
	  xx = (pt->X - baseX) / pixelRatio;
	  yy = (pt->Y - baseY) / pixelRatio;
	  yy = vert - yy;
	  dc.DrawCircle ((int) xx, (int) yy, 2);
	  pt = pt->Next;
      }
}

GraphicsGeometry::GraphicsGeometry (BlobExplorerDialog * parent,
				    wxWindow * panel, wxWindowID id,
				    const wxBitmap & bmp, const wxSize & size):


wxStaticBitmap (panel, id, bmp, wxDefaultPosition, size)

{
    Parent = parent;
}

ImageShow::ImageShow (BlobExplorerDialog * parent, wxWindow * panel,
		      wxWindowID id, const wxBitmap & bmp, const wxSize & size):

wxStaticBitmap (panel, id, bmp, wxDefaultPosition, size)

{
    Parent = parent;
// appends event handler 
    Connect (ID_IMAGE, wxEVT_RIGHT_DOWN,
	     (wxObjectEventFunction) & ImageShow::OnRightClick);
    Connect (Image_Copy, wxEVT_COMMAND_MENU_SELECTED,
	     (wxObjectEventFunction) & ImageShow::OnCmdCopy);
}

void
ImageShow::OnRightClick (wxMouseEvent & event)
{
//
// right click on the Image
//
    wxMenu menu;

    wxMenuItem *menuItem;
    wxImage *Image = Parent->GetImage ();
    if (Image)
      {
	  if (Image->IsOk () == true)
	    {
		wxPoint pt = event.GetPosition ();
		menuItem = new wxMenuItem (&menu, Image_Copy, wxT ("&Copy"));
		menu.Append (menuItem);
		PopupMenu (&menu, pt);
	    }
      }
}

void
ImageShow::OnCmdCopy (wxCommandEvent & event)
{
//
// copying the Image into the clipboard
//
    wxImage *Image = Parent->GetImage ();
    if (wxTheClipboard->Open ())
      {
	  wxTheClipboard->SetData (new wxBitmapDataObject (*Image));
	  wxTheClipboard->Close ();
      }
}

MyHexList::MyHexList (BlobExplorerDialog * parent, unsigned char *blob,
		      int blob_size, wxWindow * panel, wxWindowID id,
		      const wxPoint & pos, const wxSize & size, long style):
wxListCtrl (panel, id, pos, size, style)
{
// constructor - the blob hexadecimal dump
    int i = 0;
    int rows = 0;
    Parent = parent;
    Blob = blob;
    BlobSize = blob_size;
    while (i < BlobSize)
      {
	  // counting how many rows are there
	  rows++;
	  i += 16;
      }
    SetItemCount (rows);
}

MyHexList::~MyHexList ()
{
// does nothing
}

wxString MyHexList::OnGetItemText (long item, long column) const 
{
// return a column value
    int
	i;
    int
	c;
    int
	base = item * 16;
    wxString
	value;

    wxString
	hex;
    if (column == 0)
	value.Printf (wxT ("%08xd"), base);



    else if (column == 1)
      {
	  // prepearing the hex-dump
	  c = 0;
	  for (i = base; i < BlobSize; i++)
	    {
		if (c >= 16)
		    break;
		hex.Printf (wxT ("%02x"), *(Blob + i));


		if (c == 8)
		    value += wxT ("   ");
		else
		    value += wxT (" ");
		value += hex;
		c++;
	    }
      }
    else
      {
	  // prepearing the ascii dump
	  c = 0;
	  for (i = base; i < BlobSize; i++)
	    {
		if (c >= 16)
		    break;
		if (isprint (*(Blob + i)))

		    hex.Printf (wxT ("%c"), *(Blob + i));

		else
		    hex = wxT (".");
		value += hex;
		c++;
	    }
      }
    return value;
}




|







 







|
|




|


<
|
|




|
|
|
<
>
|
|
|
|
>
|
|
|
|
|
|
|
|
<
<
<
<
|
|
|

|
|
|
|
|
|
|
<
>
>
|
|
|
|
|
|
|

|
|

|
|

|
|
|


<
|




|
|
|
|
|

|
|
|
|
<
|
|
|
<
|
|
|
|
|
|
|
|
|
|
|
|


<
|




|
|
|
|
|

|
|
|
|
|
|
|
|

|
|
|
|
|
|
|
<
|
>
|
|
|
|


<
|




|
|
|
|
|

|
|
|
|
|
|
|
|

|
|
|
|
|
|
|
|
|
|
|


<
|




|
|

|
|

|
|
|
|
|
|


<
|




|
|


<
|




|
|
|
|
|
|
|
|
|
>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
>
|
|
|
|
|
>
>
>
>
>
>
|
|
>
>
>
>
>
>
|
|
>
>
>
>
>
>
|
|
>
>
>
>
|
|
>
>
>
>
|
|
>
>
|
|
>
>
|
|
|
|
|
|
|
|
|
|
<
>
>
|
|
|
|
|
|
|
|
|
|
|
|
|
<
>
>
|
|
|
<
>
>
|
|
|
|
|
|
|
|
<
>
>
|
|
|
|
|
|
|
|
|
|
|
|
|
<
>
>
|
|
|
<
>
>
|
|
|
|
|
|
|
|
<
>
>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<
>
|
|
|
|
<
>
>
|
|
|
|
<
<
>
>
|
|
|
|
<
|
<
>
|
|
|
|
|
|
|
|
|
<
|


<
|




|
|
|
|
|
|
|
|
|
>
>
>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<
|
|
|
|
|
|
<
|
|
|
|
<
<
>
>
|
|
<
>
|
<
<
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
|
<
>
|
<
<
>
>
|
|
<
>
|
|
|
|
|
|


<
|




|


<
|




|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|



|
|



|
|



|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|



|
|



|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|


|
|
|
>
>
|
>

|


|
|
>
|
>

|

|
|
|
|


<
|




<
>
|
|
|
|
|
|
|
|
|
|
|
|


<
|




|
|
|
|
|
|


|
|
|
|


|
|
|
|
|
|
|
|
|
|
|
|


|




|


|
<
|
<
<
|
|
<
>
|
<
|
<
>
>
>
|
|
|
|
|
|
|
|
<
>
>
|
|
|
|
|
|
|
<
|
|
|
|
|
|
|
|
|
>
|
>
|
|
|
|
|
|
|

1
2
3
4
5
6
7
8
9
10
11
12
..
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39

40
41
42
43
44
45
46
47
48

49
50
51
52
53
54
55
56
57
58
59
60
61
62




63
64
65
66
67
68
69
70
71
72
73

74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94

95
96
97
98
99
100
101
102
103
104
105
106
107
108
109

110
111
112

113
114
115
116
117
118
119
120
121
122
123
124
125
126

127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153

154
155
156
157
158
159
160
161

162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194

195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213

214
215
216
217
218
219
220
221
222

223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331

332
333
334
335
336
337
338
339
340
341
342
343
344
345
346

347
348
349
350
351

352
353
354
355
356
357
358
359
360
361

362
363
364
365
366
367
368
369
370
371
372
373
374
375
376

377
378
379
380
381

382
383
384
385
386
387
388
389
390
391

392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407

408
409
410
411
412

413
414
415
416
417
418


419
420
421
422
423
424

425

426
427
428
429
430
431
432
433
434
435

436
437
438

439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477

478
479
480
481
482
483

484
485
486
487


488
489
490
491

492
493


494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514

515
516


517
518
519
520

521
522
523
524
525
526
527
528
529

530
531
532
533
534
535
536
537

538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725

726
727
728
729
730

731
732
733
734
735
736
737
738
739
740
741
742
743
744
745

746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787

788


789
790

791
792

793

794
795
796
797
798
799
800
801
802
803
804

805
806
807
808
809
810
811
812
813

814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
/*
/ BlobExplorer.cpp
/ a dialog to explore a BLOB value
/
/ version 1.2, 2008 October 9
/
/ Author: Sandro Furieri a-furieri@lqt.it
/
/ Copyright (C) 2008  Alessandro Furieri
/
/    This program is free software: you can redistribute it and/or modify
/    it under the terms of the GNU General Public License as published by
................................................................................
*/

#include "Classdef.h"

#include "wx/mstream.h"
#include "wx/clipbrd.h"

BlobExplorerDialog::BlobExplorerDialog(MyFrame * parent, int blob_size,
                                       unsigned char *blob)
{
//
// constructor; just calls Create()
//
  Create(parent, blob_size, blob);
}


bool BlobExplorerDialog::Create(MyFrame * parent, int blob_size,
                                unsigned char *blob)
{
//
// creating the dialog
//
  MainFrame = parent;
  BlobSize = blob_size;
  Blob = blob;

  BlobType = gaiaGuessBlobType(Blob, BlobSize);
  Geometry = NULL;
  Image = NULL;
  if (BlobType == GAIA_GEOMETRY_BLOB)
    Geometry = gaiaFromSpatiaLiteBlobWkb(Blob, BlobSize);
  if (BlobType == GAIA_JPEG_BLOB || BlobType == GAIA_EXIF_BLOB
      || BlobType == GAIA_EXIF_GPS_BLOB || BlobType == GAIA_PNG_BLOB
      || BlobType == GAIA_GIF_BLOB)
    {
      ::wxInitAllImageHandlers();
      wxMemoryInputStream reader(Blob, BlobSize);
      Image = new wxImage(reader);
    }
  if (wxPropertySheetDialog::Create(parent, wxID_ANY, wxT("BLOB explorer")) ==




      false)
    return false;
  wxBookCtrlBase *book = GetBookCtrl();
// creates individual panels
  wxPanel *hexadecimal = CreateHexadecimalPage(book);
  book->AddPage(hexadecimal, wxT("Hexadecimal dump"), true);
  if (BlobType == GAIA_GEOMETRY_BLOB)
    {
      wxPanel *geometry = CreateGeometryPage(book);
      book->AddPage(geometry, wxT("Geometry explorer"), false);
    }

  if (BlobType == GAIA_JPEG_BLOB || BlobType == GAIA_EXIF_BLOB
      || BlobType == GAIA_EXIF_GPS_BLOB || BlobType == GAIA_PNG_BLOB
      || BlobType == GAIA_GIF_BLOB)
    {
      wxPanel *image = CreateImagePage(book);
      book->AddPage(image, wxT("Image"), false);
    }
  CreateButtons(wxOK);
  LayoutDialog();
// appends event handler for TAB/PAGE changing
  Connect(wxID_ANY, wxEVT_COMMAND_NOTEBOOK_PAGE_CHANGED,
          (wxObjectEventFunction) & BlobExplorerDialog::OnPageChanged);
// appends event handler for OK button
  Connect(wxID_OK, wxEVT_COMMAND_BUTTON_CLICKED,
          (wxObjectEventFunction) & BlobExplorerDialog::OnOk);
// centers the dialog window
  Centre();
  UpdateHexadecimalPage();
  return true;
}


wxPanel *BlobExplorerDialog::CreateHexadecimalPage(wxWindow * parent)
{
//
// creating the HEXADECIMAL page
//
  wxPanel *panel = new wxPanel(parent, ID_PANE_HEXADECIMAL);
  wxBoxSizer *topSizer = new wxBoxSizer(wxVERTICAL);
  panel->SetSizer(topSizer);
  wxBoxSizer *boxSizer = new wxBoxSizer(wxVERTICAL);
  topSizer->Add(boxSizer, 0, wxALIGN_CENTER | wxALL, 5);
// creating a control to show the hexadecimal dump
  wxBoxSizer *hexSizer = new wxBoxSizer(wxHORIZONTAL);
  boxSizer->Add(hexSizer, 0, wxALIGN_LEFT | wxALL, 0);
  MyHexList *hexCtrl = new MyHexList(this, Blob, BlobSize, panel,
                                     ID_HEX, wxDefaultPosition,

                                     wxSize(620, 320),
                                     wxLC_REPORT | wxLC_VIRTUAL);
  wxFont font(9, wxFONTFAMILY_MODERN, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL);

  hexCtrl->SetFont(font);
  wxListItem column0;
  hexCtrl->InsertColumn(0, wxT("Address"));
  hexCtrl->SetColumnWidth(0, 90);
  hexCtrl->InsertColumn(1, wxT("Hexadecimal"));
  hexCtrl->SetColumnWidth(1, 370);
  hexCtrl->InsertColumn(2, wxT("ASCII"));
  hexCtrl->SetColumnWidth(2, 130);
  hexSizer->Add(hexCtrl, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
  panel->SetSizer(topSizer);
  topSizer->Fit(panel);
  return panel;
}


wxPanel *BlobExplorerDialog::CreateGeometryPage(wxWindow * parent)
{
//
// creating the GEOMETRY page
//
  wxPanel *panel = new wxPanel(parent, ID_PANE_HEXADECIMAL);
  wxBoxSizer *topSizer = new wxBoxSizer(wxVERTICAL);
  panel->SetSizer(topSizer);
  wxBoxSizer *boxSizer = new wxBoxSizer(wxVERTICAL);
  topSizer->Add(boxSizer, 0, wxALIGN_CENTER | wxALL, 5);
// creating a control to show the geometry as a text table
  wxBoxSizer *geomSizer = new wxBoxSizer(wxHORIZONTAL);
  boxSizer->Add(geomSizer, 0, wxALIGN_LEFT | wxALL, 0);
  wxTextCtrl *geomCtrl = new wxTextCtrl(panel, ID_GEOM_TABLE, wxT(""),
                                        wxDefaultPosition, wxSize(270,
                                                                  320),
                                        wxTE_MULTILINE | wxTE_RICH |
                                        wxTE_READONLY | wxHSCROLL);
  geomSizer->Add(geomCtrl, 0, wxALIGN_LEFT | wxALL, 5);
// creating a control to show the geometry in a graphical fashion
  wxStaticBox *exBox = new wxStaticBox(panel, wxID_STATIC,
                                       wxT("Geometry preview"),
                                       wxDefaultPosition, wxDefaultSize);
  wxBoxSizer *exampleSizer = new wxStaticBoxSizer(exBox, wxHORIZONTAL);
  geomSizer->Add(exampleSizer, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
  DrawGeometry(300, 300);
  GraphicsGeometry *geomGraph = new GraphicsGeometry(this, panel, ID_GEOM_GRAPH,

                                                     GeomPreview, wxSize(300,
                                                                         300));
  exampleSizer->Add(geomGraph, 0, wxALIGN_CENTER_VERTICAL | wxALL, 0);
  panel->SetSizer(topSizer);
  topSizer->Fit(panel);
  return panel;
}


wxPanel *BlobExplorerDialog::CreateImagePage(wxWindow * parent)
{
//
// creating the IMAGE page
//
  wxPanel *panel = new wxPanel(parent, ID_PANE_IMAGE);
  wxBoxSizer *topSizer = new wxBoxSizer(wxVERTICAL);
  panel->SetSizer(topSizer);
  wxBoxSizer *boxSizer = new wxBoxSizer(wxVERTICAL);
  topSizer->Add(boxSizer, 0, wxALIGN_CENTER | wxALL, 5);
// creating a control to show the image title
  wxBoxSizer *imgSizer = new wxBoxSizer(wxVERTICAL);
  boxSizer->Add(imgSizer, 0, wxALIGN_TOP | wxALL, 0);
  wxStaticText *imageTitle = new wxStaticText(panel, ID_IMAGE_TITLE,
                                              wxT("Image"),
                                              wxDefaultPosition,
                                              wxSize(560,
                                                     10));
  imgSizer->Add(imageTitle, 0, wxALIGN_LEFT | wxALL, 5);
// creating a control to show the image
  wxStaticBox *exBox = new wxStaticBox(panel, ID_IMG_BOX,
                                       wxT("Image preview"),
                                       wxDefaultPosition, wxDefaultSize);
  wxBoxSizer *exampleSizer = new wxStaticBoxSizer(exBox, wxHORIZONTAL);
  imgSizer->Add(exampleSizer, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
  ImageShow *imgShow = new ImageShow(this, panel, ID_IMAGE,
                                     wxBitmap(), wxSize(560, 300));
  exampleSizer->Add(imgShow, 0, wxALIGN_CENTER_VERTICAL | wxALL, 0);
  panel->SetSizer(topSizer);
  topSizer->Fit(panel);
  return panel;
}


void BlobExplorerDialog::OnPageChanged(wxNotebookEvent & event)
{
//
// TAB/PAGE selection changed
//
  switch (event.GetSelection())
    {
      case 0:
        UpdateHexadecimalPage();
        break;
      case 1:
        if (BlobType == GAIA_GEOMETRY_BLOB)
          UpdateGeometryPage();
        else
          UpdateImagePage();
        break;
    };
}


void BlobExplorerDialog::UpdateHexadecimalPage()
{
//
// updating the HEXADECIMAL page
//
  MyHexList *hexCtrl = (MyHexList *) FindWindow(ID_HEX);
  hexCtrl->EnsureVisible(0);
}


void BlobExplorerDialog::UpdateGeometryPage()
{
//
// updating the GEOMETRY page
//
  gaiaPointPtr pt;
  gaiaLinestringPtr ln;
  gaiaPolygonPtr pg;
  gaiaRingPtr rng;
  int points = 0;
  int linestrings = 0;
  int polygons = 0;
  int ib;
  wxString strValue;
  char dummy[1024];
  wxTextAttr attrBold(wxColour(0, 0, 0), wxColour(255, 255, 255),
                      wxFont(9, wxFONTFAMILY_MODERN, wxFONTSTYLE_NORMAL,
                             wxFONTWEIGHT_BOLD));
  wxTextAttr attrNorm(wxColour(0, 0, 0), wxColour(255, 255, 255),
                      wxFont(9, wxFONTFAMILY_MODERN, wxFONTSTYLE_NORMAL,
                             wxFONTWEIGHT_NORMAL));
  wxTextCtrl *geomCtrl = (wxTextCtrl *) FindWindow(ID_GEOM_TABLE);
  if (geomCtrl->GetValue().Len() < 1)
    {
      ::wxBeginBusyCursor();
      pt = Geometry->FirstPoint;
      while (pt)
        {
          // counting how many points are into this Geometry
          points++;
          pt = pt->Next;
        }
      ln = Geometry->FirstLinestring;
      while (ln)
        {
          // counting how many linestrings are into this Geometry
          linestrings++;
          ln = ln->Next;
        }
      pg = Geometry->FirstPolygon;
      while (pg)
        {
          // counting how many polygons are into this Geometry
          polygons++;
          pg = pg->Next;
        }
      // determining the Geometry type
      geomCtrl->SetDefaultStyle(attrNorm);
      geomCtrl->AppendText(wxT("SRID: "));
      geomCtrl->SetDefaultStyle(attrBold);
      sprintf(dummy, "%d", Geometry->Srid);
      strValue = wxString::FromUTF8(dummy);
      geomCtrl->AppendText(strValue);
      geomCtrl->SetDefaultStyle(attrNorm);
      geomCtrl->AppendText(wxT("\n\n"));
      strValue = wxT("UNKNOWN GEOMETRY TYPE");
      if (points == 1 && linestrings == 0 && polygons == 0)
        {
          if (Geometry->DeclaredType == GAIA_MULTIPOINT)
            strValue = wxT("MULTIPOINT");
          else if (Geometry->DeclaredType == GAIA_GEOMETRYCOLLECTION)
            strValue = wxT("GEOMETRYCOLLECTION");
          else
            strValue = wxT("POINT");
      } else if (points == 0 && linestrings == 1 && polygons == 0)
        {
          if (Geometry->DeclaredType == GAIA_MULTILINESTRING)
            strValue = wxT("MULTILINESTRING");
          else if (Geometry->DeclaredType == GAIA_GEOMETRYCOLLECTION)
            strValue = wxT("GEOMETRYCOLLECTION");
          else
            strValue = wxT("LINESTRING");
      } else if (points == 0 && linestrings == 0 && polygons == 1)
        {
          if (Geometry->DeclaredType == GAIA_MULTIPOLYGON)
            strValue = wxT("MULTIPOLYGON");
          else if (Geometry->DeclaredType == GAIA_GEOMETRYCOLLECTION)
            strValue = wxT("GEOMETRYCOLLECTION");
          else
            strValue = wxT("POLYGON");
      } else if (points > 1 && linestrings == 0 && polygons == 0)
        {
          if (Geometry->DeclaredType == GAIA_GEOMETRYCOLLECTION)
            strValue = wxT("GEOMETRYCOLLECTION");
          else
            strValue = wxT("MULTIPOINT");
      } else if (points == 0 && linestrings > 1 && polygons == 0)
        {
          if (Geometry->DeclaredType == GAIA_GEOMETRYCOLLECTION)
            strValue = wxT("GEOMETRYCOLLECTION");
          else
            strValue = wxT("MULTILINESTRING");
      } else if (points == 0 && linestrings == 0 && polygons > 1)
        {
          if (Geometry->DeclaredType == GAIA_GEOMETRYCOLLECTION)
            strValue = wxT("GEOMETRYCOLLECTION");
          else
            strValue = wxT("MULTIPOLYGON");
      } else
        strValue = wxT("GEOMETRYCOLLECTION");
      geomCtrl->SetDefaultStyle(attrNorm);
      geomCtrl->AppendText(wxT("Geometry type: "));
      geomCtrl->SetDefaultStyle(attrBold);
      geomCtrl->AppendText(strValue);
      geomCtrl->SetDefaultStyle(attrNorm);
      geomCtrl->AppendText(wxT("\n\n"));
      if (points)
        {
          // printing the Points list

          sprintf(dummy, "#%d POINT", points);
          strValue = wxString::FromUTF8(dummy);
          if (points > 1)
            strValue += wxT("s:");
          else
            strValue += wxT(":");
          geomCtrl->SetDefaultStyle(attrBold);
          geomCtrl->AppendText(strValue);
          geomCtrl->SetDefaultStyle(attrNorm);
          pt = Geometry->FirstPoint;
          points = 0;
          while (pt)
            {
              // printing each Point
              points++;

              sprintf(dummy, "\n  %d) ", points);
              strValue = wxString::FromUTF8(dummy);
              geomCtrl->SetDefaultStyle(attrBold);
              geomCtrl->AppendText(strValue);
              geomCtrl->SetDefaultStyle(attrNorm);

              sprintf(dummy, "%1.4lf  %1.4lf", pt->X, pt->Y);
              strValue = wxString::FromUTF8(dummy);
              geomCtrl->AppendText(strValue);
              pt = pt->Next;
            }
          geomCtrl->AppendText(wxT("\n\n\n"));
        }
      if (linestrings)
        {
          // printing the Linestrings list

          sprintf(dummy, "#%d LINESTRING", linestrings);
          strValue = wxString::FromUTF8(dummy);
          if (linestrings > 1)
            strValue += wxT("s:");
          else
            strValue += wxT(":");
          geomCtrl->SetDefaultStyle(attrBold);
          geomCtrl->AppendText(strValue);
          geomCtrl->SetDefaultStyle(attrNorm);
          ln = Geometry->FirstLinestring;
          linestrings = 0;
          while (ln)
            {
              // printing each Linestring
              linestrings++;

              sprintf(dummy, "\n  %d) ", linestrings);
              strValue = wxString::FromUTF8(dummy);
              geomCtrl->SetDefaultStyle(attrBold);
              geomCtrl->AppendText(strValue);
              geomCtrl->SetDefaultStyle(attrNorm);

              sprintf(dummy, "%d vertices", ln->Points);
              strValue = wxString::FromUTF8(dummy);
              geomCtrl->AppendText(strValue);
              ln = ln->Next;
            }
          geomCtrl->AppendText(wxT("\n\n\n"));
        }
      if (polygons)
        {
          // printing the Polygons list

          sprintf(dummy, "#%d POLYGON", polygons);
          strValue = wxString::FromUTF8(dummy);
          if (polygons > 1)
            strValue += wxT("s:");
          else
            strValue += wxT(":");
          geomCtrl->SetDefaultStyle(attrBold);
          geomCtrl->AppendText(strValue);
          geomCtrl->SetDefaultStyle(attrNorm);
          pg = Geometry->FirstPolygon;
          polygons = 0;
          while (pg)
            {
              // printing each Polygon
              polygons++;
              sprintf(dummy, "\n  %d)    exterior ring", polygons);

              strValue = wxString::FromUTF8(dummy);
              geomCtrl->SetDefaultStyle(attrBold);
              geomCtrl->AppendText(strValue);
              geomCtrl->SetDefaultStyle(attrNorm);
              rng = pg->Exterior;

              sprintf(dummy, ": %d vertices", rng->Points);
              strValue = wxString::FromUTF8(dummy);
              geomCtrl->AppendText(strValue);
              for (ib = 0; ib < pg->NumInteriors; ib++)
                {
                  // printing each interior ring


                  sprintf(dummy, "\n  %d.%d) ", polygons, ib + 1);
                  strValue = wxString::FromUTF8(dummy);
                  geomCtrl->SetDefaultStyle(attrBold);
                  geomCtrl->AppendText(strValue);
                  geomCtrl->SetDefaultStyle(attrNorm);
                  rng = pg->Interiors + ib;

                  sprintf(dummy, " interior ring: %d vertices", rng->Points);

                  strValue = wxString::FromUTF8(dummy);
                  geomCtrl->AppendText(strValue);
                }
              pg = pg->Next;
            }
          geomCtrl->AppendText(wxT("\n\n\n"));
        }
      ::wxEndBusyCursor();
    }
  GraphicsGeometry *geomGraph = (GraphicsGeometry *) FindWindow(ID_GEOM_GRAPH);

  geomGraph->SetBitmap(GeomPreview);
}


void BlobExplorerDialog::UpdateImagePage()
{
//
// updating the IMAGE page
//
  double horz;
  double vert;
  wxImage scaledImg;
  wxSize sz;
  wxSize box;
  int boxX;
  int boxY;
  int posX;
  int posY;
  char latlong[1024];
  char dummy[1024];
  wxString ll;
  wxString title = wxT("Invalid Image");
  wxStaticBox *imgBox = (wxStaticBox *) FindWindow(ID_IMG_BOX);
  ImageShow *imgShow = (ImageShow *) FindWindow(ID_IMAGE);
  wxStaticText *imageTitle = (wxStaticText *) FindWindow(ID_IMAGE_TITLE);
  if (Image)
    {
      ::wxBeginBusyCursor();
      if (Image->IsOk() == true)
        {
          horz = Image->GetWidth();
          vert = Image->GetHeight();
          sz = imgShow->GetSize();
          box = imgBox->GetSize();
          while (horz > sz.GetWidth() || vert > sz.GetHeight())
            {
              horz *= 0.9;
              vert *= 0.9;
            }
          if (horz == Image->GetWidth() && vert == Image->GetHeight())
            scaledImg = Image->Copy();
          else
            scaledImg =

              Image->Scale((int) horz, (int) vert, wxIMAGE_QUALITY_HIGH);
          wxBitmap bmp(scaledImg);
          imgBox->GetPosition(&boxX, &boxY);
          posX = (box.GetWidth() - (int) horz) / 2;
          posY = (box.GetHeight() - (int) vert) / 2;
          imgShow->SetSize(boxX + posX, boxY + posY, (int) horz, (int) vert);

          imgShow->SetBitmap(bmp);
          imgShow->Show(true);
          switch (BlobType)
            {


              case GAIA_JPEG_BLOB:
                sprintf(dummy,
                        "JPEG image     resolution: %d x %d          %d bytes",
                        Image->GetWidth(), Image->GetHeight(), BlobSize);

                title = wxString::FromUTF8(dummy);
                break;


              case GAIA_EXIF_BLOB:
                sprintf(dummy,
                        "EXIF image     resolution: %d x %d          %d bytes",
                        Image->GetWidth(), Image->GetHeight(), BlobSize);
                title = wxString::FromUTF8(dummy);
                break;
              case GAIA_EXIF_GPS_BLOB:
                if (gaiaGetGpsLatLong(Blob, BlobSize, latlong, 1024))
                  ll = wxString::FromUTF8(latlong);
                else
                  ll = wxT("NOT AVAILABLE");
                sprintf(dummy,
                        "EXIF-GPS image     resolution: %d x %d          %d bytes    GPS: ",
                        Image->GetWidth(), Image->GetHeight(), BlobSize);
                title = wxString::FromUTF8(dummy);
                title += ll;
                break;
              case GAIA_PNG_BLOB:
                sprintf(dummy,
                        "PNG image     resolution: %d x %d          %d bytes",
                        Image->GetWidth(), Image->GetHeight(), BlobSize);

                title = wxString::FromUTF8(dummy);
                break;


              case GAIA_GIF_BLOB:
                sprintf(dummy,
                        "GIF image     resolution: %d x %d          %d bytes",
                        Image->GetWidth(), Image->GetHeight(), BlobSize);

                title = wxString::FromUTF8(dummy);
                break;
            }
        }
      ::wxEndBusyCursor();
    }
  imageTitle->SetLabel(title);
}


void BlobExplorerDialog::OnOk(wxCommandEvent & event)
{
//
// all done: exiting
//
  wxDialog::EndModal(wxID_OK);
}


void BlobExplorerDialog::DrawGeometry(int horz, int vert)
{
//
// drawing graphic representation for current Geometry
//
  gaiaPointPtr pt;
  gaiaLinestringPtr ln;
  gaiaPolygonPtr pg;
  gaiaRingPtr rng;
  double minx;
  double miny;
  double maxx;
  double maxy;
  double ext_x;
  double ext_y;
  double cx;
  double cy;
  double pixelRatioX;
  double pixelRatioY;
  double pixelRatio;
  double span_x;
  double span_y;
  double baseX;
  double baseY;
  double x;
  double y;
  double xx;
  double yy;
  int iv;
  int ib;
  int pts;
  int *borders;
  wxPoint *points;
  GeomPreview.Create(horz, vert);
  wxMemoryDC dc(GeomPreview);
//
// background filling
//
  dc.SetBrush(wxBrush(wxColour(255, 255, 255)));
  dc.DrawRectangle(0, 0, horz, vert);
//
// prepearing the drawing pen and brush
//
  dc.SetBrush(wxBrush(wxColour(240, 240, 192)));
  dc.SetPen(wxPen(wxColour(64, 64, 192), 1));
//
// computing the pixel ratio, center position and so on
//
  minx = Geometry->MinX;
  miny = Geometry->MinY;
  maxx = Geometry->MaxX;
  maxy = Geometry->MaxY;
  ext_x = maxx - minx;
  ext_y = maxy - miny;
  if (ext_x < 1.0)
    ext_x = 1.0;
  if (ext_y < 1.0)
    ext_y = 1.0;
  minx = Geometry->MinX - (ext_x / 20.0);
  miny = Geometry->MinY - (ext_y / 20.0);
  maxx = Geometry->MaxX + (ext_x / 20.0);
  maxy = Geometry->MaxY + (ext_y / 20.0);
  ext_x = maxx - minx;
  ext_y = maxy - miny;
  cx = minx + (ext_x / 2.0);
  cy = miny + (ext_y / 2.0);
  pixelRatioX = ext_x / horz;
  pixelRatioY = ext_y / vert;
  if (pixelRatioX > pixelRatioY)
    pixelRatio = pixelRatioX;
  else
    pixelRatio = pixelRatioY;
//
// centering the Y axis
//
  span_y = vert * pixelRatio;
  baseY = cy - (span_y / 2.0);
//
// centering the X axis
//
  span_x = horz * pixelRatio;
  baseX = cx - (span_x / 2.0);
  pg = Geometry->FirstPolygon;
  while (pg)
    {
      //
      // drawing polygons
      //
      pts = pg->Exterior->Points;
      for (ib = 0; ib < pg->NumInteriors; ib++)
        {
          rng = pg->Interiors + ib;
          pts += rng->Points;
        }
      borders = new int[pg->NumInteriors + 1];
      points = new wxPoint[pts];
      pts = 0;
      rng = pg->Exterior;
      borders[0] = rng->Points;
      for (iv = 0; iv < rng->Points; iv++)
        {
          gaiaGetPoint(rng->Coords, iv, &x, &y);
          xx = (x - baseX) / pixelRatio;
          yy = (y - baseY) / pixelRatio;
          yy = vert - yy;
          points[pts].x = (int) xx;
          points[pts].y = (int) yy;
          pts++;
        }
      for (ib = 0; ib < pg->NumInteriors; ib++)
        {
          rng = pg->Interiors + ib;
          borders[1 + ib] = rng->Points;
          for (iv = 0; iv < rng->Points; iv++)
            {
              gaiaGetPoint(rng->Coords, iv, &x, &y);
              xx = (x - baseX) / pixelRatio;
              yy = (y - baseY) / pixelRatio;
              yy = vert - yy;
              points[pts].x = (int) xx;
              points[pts].y = (int) yy;
              pts++;
            }
        }
      dc.DrawPolyPolygon(pg->NumInteriors + 1, borders, points);
      delete[]points;
      delete[]borders;
      pg = pg->Next;
    }
  ln = Geometry->FirstLinestring;
  while (ln)
    {
      //
      // drawing linestrings
      //
      points = new wxPoint[ln->Points];
      for (iv = 0; iv < ln->Points; iv++)
        {
          gaiaGetPoint(ln->Coords, iv, &x, &y);
          xx = (x - baseX) / pixelRatio;
          yy = (y - baseY) / pixelRatio;
          yy = vert - yy;
          points[iv].x = (int) xx;
          points[iv].y = (int) yy;
        }
      dc.DrawLines(ln->Points, points);
      delete[]points;
      ln = ln->Next;
    }
  pt = Geometry->FirstPoint;
  while (pt)
    {
      //
      // drawing points
      //
      xx = (pt->X - baseX) / pixelRatio;
      yy = (pt->Y - baseY) / pixelRatio;
      yy = vert - yy;
      dc.DrawCircle((int) xx, (int) yy, 2);
      pt = pt->Next;
    }
}

GraphicsGeometry::GraphicsGeometry(BlobExplorerDialog * parent,
                                   wxWindow * panel, wxWindowID id,
                                   const wxBitmap & bmp,
                                   const wxSize & size):wxStaticBitmap(panel,
                                                                       id, bmp,
                                                                       wxDefaultPosition,
                                                                       size)
{
  Parent = parent;
}

ImageShow::ImageShow(BlobExplorerDialog * parent, wxWindow * panel,
                     wxWindowID id, const wxBitmap & bmp,
                     const wxSize & size):wxStaticBitmap(panel, id, bmp,
                                                         wxDefaultPosition,
                                                         size)
{
  Parent = parent;
// appends event handler 
  Connect(ID_IMAGE, wxEVT_RIGHT_DOWN,
          (wxObjectEventFunction) & ImageShow::OnRightClick);
  Connect(Image_Copy, wxEVT_COMMAND_MENU_SELECTED,
          (wxObjectEventFunction) & ImageShow::OnCmdCopy);
}


void ImageShow::OnRightClick(wxMouseEvent & event)
{
//
// right click on the Image
//

  wxMenu *menu = new wxMenu();
  wxMenuItem *menuItem;
  wxImage *Image = Parent->GetImage();
  if (Image)
    {
      if (Image->IsOk() == true)
        {
          wxPoint pt = event.GetPosition();
          menuItem = new wxMenuItem(menu, Image_Copy, wxT("&Copy"));
          menu->Append(menuItem);
          PopupMenu(menu, pt);
        }
    }
}


void ImageShow::OnCmdCopy(wxCommandEvent & event)
{
//
// copying the Image into the clipboard
//
  wxImage *Image = Parent->GetImage();
  if (wxTheClipboard->Open())
    {
      wxTheClipboard->SetData(new wxBitmapDataObject(*Image));
      wxTheClipboard->Close();
    }
}

MyHexList::MyHexList(BlobExplorerDialog * parent, unsigned char *blob,
                     int blob_size, wxWindow * panel, wxWindowID id,
                     const wxPoint & pos, const wxSize & size,
                     long style):wxListCtrl(panel, id, pos, size, style)
{
// constructor - the blob hexadecimal dump
  int i = 0;
  int rows = 0;
  Parent = parent;
  Blob = blob;
  BlobSize = blob_size;
  while (i < BlobSize)
    {
      // counting how many rows are there
      rows++;
      i += 16;
    }
  SetItemCount(rows);
}

MyHexList::~MyHexList()
{
// does nothing
}

wxString MyHexList::OnGetItemText(long item, long column) const
{
// return a column value
  int i;

  int c;


  int base = item * 16;
  wxString value;

  char dummy[64];
  wxString hex;

  if (column == 0)

    {
      sprintf(dummy, "%08xd", base);
      value = wxString::FromUTF8(dummy);
  } else if (column == 1)
    {
      // prepearing the hex-dump
      c = 0;
      for (i = base; i < BlobSize; i++)
        {
          if (c >= 16)
            break;

          sprintf(dummy, "%02x", *(Blob + i));
          hex = wxString::FromUTF8(dummy);
          if (c == 8)
            value += wxT("   ");
          else
            value += wxT(" ");
          value += hex;
          c++;
        }

  } else
    {
      // prepearing the ascii dump
      c = 0;
      for (i = base; i < BlobSize; i++)
        {
          if (c >= 16)
            break;
          if (isprint(*(Blob + i)))
            {
              sprintf(dummy, "%c", *(Blob + i));
              hex = wxString::FromUTF8(dummy);
          } else
            hex = wxT(".");
          value += hex;
          c++;
        }
    }
  return value;
}

Added COPYING.





































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
                    GNU GENERAL PUBLIC LICENSE
                       Version 3, 29 June 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The GNU General Public License is a free, copyleft license for
software and other kinds of works.

  The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.  We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors.  You can apply it to
your programs, too.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.

  To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights.  Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.

  For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received.  You must make sure that they, too, receive
or can get the source code.  And you must show them these terms so they
know their rights.

  Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.

  For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software.  For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.

  Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so.  This is fundamentally incompatible with the aim of
protecting users' freedom to change the software.  The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable.  Therefore, we
have designed this version of the GPL to prohibit the practice for those
products.  If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.

  Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary.  To prevent this, the GPL assures that
patents cannot be used to render the program non-free.

  The precise terms and conditions for copying, distribution and
modification follow.

                       TERMS AND CONDITIONS

  0. Definitions.

  "This License" refers to version 3 of the GNU General Public License.

  "Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.

  "The Program" refers to any copyrightable work licensed under this
License.  Each licensee is addressed as "you".  "Licensees" and
"recipients" may be individuals or organizations.

  To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy.  The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.

  A "covered work" means either the unmodified Program or a work based
on the Program.

  To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy.  Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.

  To "convey" a work means any kind of propagation that enables other
parties to make or receive copies.  Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.

  An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License.  If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.

  1. Source Code.

  The "source code" for a work means the preferred form of the work
for making modifications to it.  "Object code" means any non-source
form of a work.

  A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.

  The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form.  A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.

  The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities.  However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work.  For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.

  The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.

  The Corresponding Source for a work in source code form is that
same work.

  2. Basic Permissions.

  All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met.  This License explicitly affirms your unlimited
permission to run the unmodified Program.  The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work.  This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.

  You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force.  You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright.  Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.

  Conveying under any other circumstances is permitted solely under
the conditions stated below.  Sublicensing is not allowed; section 10
makes it unnecessary.

  3. Protecting Users' Legal Rights From Anti-Circumvention Law.

  No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.

  When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.

  4. Conveying Verbatim Copies.

  You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.

  You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.

  5. Conveying Modified Source Versions.

  You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:

    a) The work must carry prominent notices stating that you modified
    it, and giving a relevant date.

    b) The work must carry prominent notices stating that it is
    released under this License and any conditions added under section
    7.  This requirement modifies the requirement in section 4 to
    "keep intact all notices".

    c) You must license the entire work, as a whole, under this
    License to anyone who comes into possession of a copy.  This
    License will therefore apply, along with any applicable section 7
    additional terms, to the whole of the work, and all its parts,
    regardless of how they are packaged.  This License gives no
    permission to license the work in any other way, but it does not
    invalidate such permission if you have separately received it.

    d) If the work has interactive user interfaces, each must display
    Appropriate Legal Notices; however, if the Program has interactive
    interfaces that do not display Appropriate Legal Notices, your
    work need not make them do so.

  A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit.  Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.

  6. Conveying Non-Source Forms.

  You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:

    a) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by the
    Corresponding Source fixed on a durable physical medium
    customarily used for software interchange.

    b) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by a
    written offer, valid for at least three years and valid for as
    long as you offer spare parts or customer support for that product
    model, to give anyone who possesses the object code either (1) a
    copy of the Corresponding Source for all the software in the
    product that is covered by this License, on a durable physical
    medium customarily used for software interchange, for a price no
    more than your reasonable cost of physically performing this
    conveying of source, or (2) access to copy the
    Corresponding Source from a network server at no charge.

    c) Convey individual copies of the object code with a copy of the
    written offer to provide the Corresponding Source.  This
    alternative is allowed only occasionally and noncommercially, and
    only if you received the object code with such an offer, in accord
    with subsection 6b.

    d) Convey the object code by offering access from a designated
    place (gratis or for a charge), and offer equivalent access to the
    Corresponding Source in the same way through the same place at no
    further charge.  You need not require recipients to copy the
    Corresponding Source along with the object code.  If the place to
    copy the object code is a network server, the Corresponding Source
    may be on a different server (operated by you or a third party)
    that supports equivalent copying facilities, provided you maintain
    clear directions next to the object code saying where to find the
    Corresponding Source.  Regardless of what server hosts the
    Corresponding Source, you remain obligated to ensure that it is
    available for as long as needed to satisfy these requirements.

    e) Convey the object code using peer-to-peer transmission, provided
    you inform other peers where the object code and Corresponding
    Source of the work are being offered to the general public at no
    charge under subsection 6d.

  A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.

  A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling.  In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage.  For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product.  A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.

  "Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source.  The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.

  If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information.  But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).

  The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed.  Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.

  Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.

  7. Additional Terms.

  "Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law.  If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.

  When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it.  (Additional permissions may be written to require their own
removal in certain cases when you modify the work.)  You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.

  Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:

    a) Disclaiming warranty or limiting liability differently from the
    terms of sections 15 and 16 of this License; or

    b) Requiring preservation of specified reasonable legal notices or
    author attributions in that material or in the Appropriate Legal
    Notices displayed by works containing it; or

    c) Prohibiting misrepresentation of the origin of that material, or
    requiring that modified versions of such material be marked in
    reasonable ways as different from the original version; or

    d) Limiting the use for publicity purposes of names of licensors or
    authors of the material; or

    e) Declining to grant rights under trademark law for use of some
    trade names, trademarks, or service marks; or

    f) Requiring indemnification of licensors and authors of that
    material by anyone who conveys the material (or modified versions of
    it) with contractual assumptions of liability to the recipient, for
    any liability that these contractual assumptions directly impose on
    those licensors and authors.

  All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10.  If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term.  If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.

  If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.

  Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.

  8. Termination.

  You may not propagate or modify a covered work except as expressly
provided under this License.  Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).

  However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.

  Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.

  Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License.  If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.

  9. Acceptance Not Required for Having Copies.

  You are not required to accept this License in order to receive or
run a copy of the Program.  Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance.  However,
nothing other than this License grants you permission to propagate or
modify any covered work.  These actions infringe copyright if you do
not accept this License.  Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.

  10. Automatic Licensing of Downstream Recipients.

  Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License.  You are not responsible
for enforcing compliance by third parties with this License.

  An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations.  If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.

  You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License.  For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.

  11. Patents.

  A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based.  The
work thus licensed is called the contributor's "contributor version".

  A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version.  For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.

  Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.

  In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement).  To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.

  If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients.  "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.

  If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.

  A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License.  You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.

  Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.

  12. No Surrender of Others' Freedom.

  If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all.  For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.

  13. Use with the GNU Affero General Public License.

  Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work.  The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.

  14. Revised Versions of this License.

  The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time.  Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

  Each version is given a distinguishing version number.  If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation.  If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.

  If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.

  Later license versions may give you additional or different
permissions.  However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.

  15. Disclaimer of Warranty.

  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

  16. Limitation of Liability.

  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.

  17. Interpretation of Sections 15 and 16.

  If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.

                     END OF TERMS AND CONDITIONS

            How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

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

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

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

Also add information on how to contact you by electronic and paper mail.

  If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:

    <program>  Copyright (C) <year>  <name of author>
    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
    This is free software, and you are welcome to redistribute it
    under certain conditions; type `show c' for details.

The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License.  Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".

  You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.

  The GNU General Public License does not permit incorporating your program
into proprietary programs.  If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library.  If this is what you want to do, use the GNU Lesser General
Public License instead of this License.  But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

Changes to Classdef.h.

24
25
26
27
28
29
30

31
32

33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365














































































































































































































366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413



414

415


416



417



418



419



420



421
422
423
424
425
426
427
428
429
430
431
432


433

434

435
436
437



438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039



































































































































































































































































































































































































































































































1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052


1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073


































































































































































































































































































































*/

#include "wx/wx.h"
#include "wx/aui/aui.h"
#include "wx/treectrl.h"
#include "wx/grid.h"
#include "wx/listctrl.h"

#include "wx/propdlg.h"
#include "wx/generic/propdlg.h"


#include <spatialite/sqlite3.h>

#define OMIT_GEOS    0
#define OMIT_PROJ    0
#include <spatialite/gaiageo.h>

enum
{
// control IDs for main window and tree list control
    ID_Connect = 1,
    ID_CreateNew,
    ID_Disconnect,
    ID_Vacuum,
    ID_SqlScript,
    ID_LoadShp,
	ID_LoadTxt,
    ID_VirtualShp,
	ID_VirtualTxt,
    ID_Srids,
    ID_Charset,
    ID_Help,
    Tree_NewTable,
    Tree_NewView,
    Tree_NewIndex,
    Tree_NewTrigger,
    Tree_NewColumn,
    Tree_Show,
    Tree_Drop,
    Tree_Rename,
    Tree_Select,
    Tree_Refresh,
    Tree_SpatialIndex,
	Tree_MbrCache,
    Tree_ShowSql,
    Tree_Recover,
    Tree_CheckGeometry,
    Tree_SetSrid,
    Tree_DumpShp,
    Tree_DumpTxtTab,
    Tree_DumpCsv,
    Tree_DumpHtml,
    Tree_Edit,
    Grid_Clear,
    Grid_All,
    Grid_Column,
    Grid_Row,
    Grid_Copy,
    Grid_Blob,
    Grid_Delete,
    Grid_Insert,
    Grid_Abort,
    Grid_BlobIn,
    Grid_BlobOut,
    Grid_BlobNull,
    Image_Copy,
};

enum
{
// control IDs for dialogs
    ID_SQL = 10000,
    ID_SQL_GO,
    ID_HISTORY_BACK,
    ID_HISTORY_FORWARD,
    ID_RS_FIRST,
    ID_RS_LAST,
    ID_RS_NEXT,
    ID_RS_PREVIOUS,
    ID_REFRESH,
    ID_RS_BLOCK,
    ID_PANE_HEXADECIMAL,
    ID_PANE_GEOMETRY,
    ID_PANE_IMAGE,
    ID_HEX,
    ID_GEOM_TABLE,
    ID_GEOM_GRAPH,
    ID_GEOM_BOX,
    ID_IMAGE_TITLE,
    ID_IMG_BOX,
    ID_IMAGE,
	ID_VIRTSHP_TABLE,
    ID_VIRTSHP_SRID,
    ID_VIRTSHP_CHARSET,
	ID_VIRTTXT_TABLE,
	ID_VIRTTXT_CHARSET,
	ID_VIRTTXT_TITLES,
	ID_VIRTTXT_SEPARATOR,
	ID_VIRTTXT_CHARSEPARATOR,
	ID_VIRTTXT_QUOTE,
	ID_VIRTTXT_POINT,
    ID_LDSHP_TABLE,
    ID_LDSHP_COLUMN,
    ID_LDSHP_SRID,
    ID_LDSHP_CHARSET,
	ID_LDTXT_TABLE,
	ID_LDTXT_CHARSET,
	ID_LDTXT_TITLES,
	ID_LDTXT_SEPARATOR,
	ID_LDTXT_CHARSEPARATOR,
	ID_LDTXT_QUOTE,
	ID_LDTXT_POINT,
    ID_DMPSHP_CHARSET,
    ID_DMPTXT_CHARSET,
    ID_DFLT_CHARSET,
    ID_DFLT_ASK,
    ID_SCRIPT_CHARSET,
    ID_RCVR_SRID,
    ID_RCVR_TYPE,
    ID_SRID_OLD,
    ID_SRID_SRID,
    ID_SEARCH,
};

enum
{
// tree item data types
    MY_TABLE = 0,
    MY_VTABLE,
    MY_VIEW,
    MY_COLUMN,
    MY_GEOMETRY,
    MY_GEOMETRY_INDEX,
	MY_GEOMETRY_CACHED,
    MY_INDEX,
    MY_TRIGGER,
    MY_INT_VARIANT,
    MY_DBL_VARIANT,
    MY_TXT_VARIANT,
    MY_BLOB_VARIANT,
    MY_NULL_VARIANT,
};

class MyObject:public wxTreeItemData
{
//
// a class to store TreeItemData
//
  private:
    int Type;			// the object type
    wxString Name;		// the object name
    wxString Column;		// the column name [optional]
  public:
      MyObject (int type, wxString & name);
      MyObject (int type, wxString & name, wxString & column);
      virtual ~ MyObject () { ; }
    int GetType () { return Type; }
    wxString & GetName () {	return Name; }
    wxString & GetColumn () { return Column; }
};

class MyColumnInfo
{
//
// a class to store a DB column
//
  private:
    wxString Name;		// the column name
    bool PrimaryKey;		// Primary Key column
    bool Geometry;		// Geometry column
    bool GeometryIndex;		// Geometry column + SpatialIndex
	bool MbrCache;		// Geometry column + MbrCache
    MyColumnInfo *Next;		// pointer to next element into the linked list
  public:
      MyColumnInfo (wxString & name, bool pkey);
     ~MyColumnInfo () { ; }
    wxString & GetName () { return Name; }
    bool IsPrimaryKey () { return PrimaryKey; }
    void SetGeometry () { Geometry = true; }
    bool IsGeometry () { return Geometry; }
    void SetGeometryIndex () { GeometryIndex = true; }
    bool IsGeometryIndex () { return GeometryIndex; }
	void SetMbrCache () { MbrCache = true; }
    bool IsMbrCache () { return MbrCache; }
    void SetNext (MyColumnInfo * next) { Next = next; }
    MyColumnInfo *GetNext () { return Next; }
};

class MyIndexInfo
{
//
// a class to store a DB index
//
  private:
    wxString Name;		// the index name
    MyIndexInfo *Next;		// pointer to next element into the linked list
  public:
      MyIndexInfo (wxString & name);
     ~MyIndexInfo () { ; }
    wxString & GetName () { return Name; }
    void SetNext (MyIndexInfo * next) { Next = next; }
    MyIndexInfo *GetNext () { return Next; }
};

class MyTriggerInfo
{
//
// a class to store a DB trigger
//
  private:
    wxString Name;		// the trigger name
    MyTriggerInfo *Next;	// pointer to next element into the linked list
  public:
      MyTriggerInfo (wxString & name);
     ~MyTriggerInfo () { ; }
    wxString & GetName () { return Name; }
    void SetNext (MyTriggerInfo * next) { Next = next; }
    MyTriggerInfo *GetNext () { return Next; }
};

class MyTableInfo
{
//
// a class to store DB table columns
//
  private:
    MyColumnInfo * FirstColumn;	// first element into the columns linked list
    MyColumnInfo *LastColumn;	// last element into the columns linked list
    MyIndexInfo *FirstIndex;	// first element into the indices linked list
    MyIndexInfo *LastIndex;	// last element into the indices linked list
    MyTriggerInfo *FirstTrigger;	// first element into the triggers linked list
    MyTriggerInfo *LastTrigger;	// last element into the triggers linked list
  public:
      MyTableInfo () { FirstColumn = NULL; LastColumn = NULL;
		FirstIndex = NULL; LastIndex = NULL; FirstTrigger = NULL;
		LastTrigger = NULL; }
     ~MyTableInfo ();
    void AddColumn (wxString & name, bool pkey);
    void SetGeometry (wxString & name, bool index, bool cached);
    void AddIndex (wxString & name);
    void AddTrigger (wxString & name);
    MyColumnInfo *GetFirstColumn () { return FirstColumn; }
    MyIndexInfo *GetFirstIndex () { return FirstIndex; }
    MyTriggerInfo *GetFirstTrigger () { return FirstTrigger; }
};

class MyViewInfo
{
//
// a class to store DB view columns
//
  private:
    MyColumnInfo * First;	// first element into the columns linked list
    MyColumnInfo *Last;		// last element into the columns linked list
  public:
      MyViewInfo () { First = NULL; Last = NULL; }
     ~MyViewInfo ();
    void AddColumn (wxString & name);
    MyColumnInfo *GetFirst () { return First; }
};

class MyVariant
{
//
// a class to store Variant-Type values
//
  private:
    int Type;			// the Variant-Type
    int IntValue;		// the Integer value
    double DblValue;		// the Double value
    wxString TxtValue;		// the Text value
    unsigned char *Blob;	// the BLOB value
    int BlobSize;		// the BLOB size
  public:
      MyVariant () { Type = MY_NULL_VARIANT; Blob = NULL; }
     ~MyVariant () { if (Blob) delete Blob; }
    void Clear () { if (Blob) delete Blob; Blob = NULL;
		Type = MY_NULL_VARIANT; }
    void Set (int value) { Type = MY_INT_VARIANT;
		IntValue = value; }
    void Set (double value) { Type = MY_DBL_VARIANT;
		DblValue = value; }
    void Set (const unsigned char *text);
    void Set (wxString & string) { Type = MY_TXT_VARIANT;
		TxtValue = string; }
    void Set (const void *blob, int size);
    void Copy (MyVariant * other);
    int GetType () { return Type; }
    int GetIntValue () { return IntValue; }
    double GetDblValue () { return DblValue; }
    wxString & GetTxtValue () { return TxtValue; }
    int GetBlobSize () { return BlobSize; }
    unsigned char *GetBlob () { return Blob; }
};

class MyRowVariant
{
//
// a class to store a row composed of Variant-Type values
//
  private:
    int NumCols;		// number of columns
    MyVariant *ColumnArray;	// the column as an array
    bool Deleted;		// switch to mark row deletion
    MyRowVariant *Next;		// pointer to next element into the linked list
  public:
      MyRowVariant () { NumCols = 0; ColumnArray = NULL;
		Deleted = false; Next = NULL; }
    MyRowVariant (int cols) { NumCols = cols;
		ColumnArray = new MyVariant[cols]; Next = NULL; }
    ~MyRowVariant () { if (ColumnArray) delete[]ColumnArray; }
    void Create (int cols);
    int GetNumCols () { return NumCols; }
    void Set (int col, int value);
    void Set (int col, double value);
    void Set (int col, const unsigned char *text);
    void Set (int col, const void *blob, int size);
    MyVariant *GetColumn (int col);
    void SetDeleted () { Deleted = true; }
    bool IsDeleted () { return Deleted; }
    void SetNext (MyRowVariant * next) { Next = next; }
    MyRowVariant *GetNext () { return Next; }
};

class MyVariantList
{
//
// a class to store a whole result set
//
  private:
    int NumCols;		// number of columns
    wxString *ColumnName;	// the column names
    MyRowVariant *First;	// first element into the linked list
    MyRowVariant *Last;		// last element into the linked list
  public:
      MyVariantList ();
     ~MyVariantList ();
    MyRowVariant *Add (int columns);
    void SetColumnName (int col, const char *colName);
    MyRowVariant *GetFirst () { return First; }
    int GetRows (); 
    int GetColumns () { return NumCols; }
    wxString & GetColumnName (int col);














































































































































































































};

class MyBlobs
{
//
// a class to store BLOBs
//
  private:
    int NumRows;		// the number of rows
    int NumCols;		// the number of columns
    MyRowVariant *Rows;		// pointer to an array of rows
  public:
      MyBlobs (int rows, int cols);
     ~MyBlobs ();
    void SetBlob (int row, int col, MyVariant * blobVar);
    MyVariant *GetBlob (int row, int col);
};

class MyValues
{
//
// a class to store column values for editing
//
  private:
    int NumRows;		// the number of rows
    int NumCols;		// the number of columns
    MyRowVariant *Rows;		// pointer to an array of rows
  public:
      MyValues (int rows, int cols);
     ~MyValues ();
    void SetValue (int row, int col, int value);
    void SetValue (int row, int col, double value);
    void SetValue (int row, int col, wxString & string);
    MyRowVariant *GetRow (int row);
    MyVariant *GetValue (int row, int col);
};

class MySqlQuery
{
//
// a class to store an SQL query - history
//
  private:
    wxString Sql;
    MySqlQuery *Prev;
    MySqlQuery *Next;
  public:
      MySqlQuery (wxString & sql) { Sql = sql; Prev = NULL; 



		Next = NULL; }

     ~MySqlQuery () { ; }


    wxString & GetSql () { return Sql; }



    void SetPrev (MySqlQuery * prev) { Prev = prev; }



    MySqlQuery *GetPrev () { return Prev; }



    void SetNext (MySqlQuery * next) { Next = next; }



    MySqlQuery *GetNext () { return Next; }



};

class MySqlHistory
{
//
// a class supporting SQL queries history
//
  private:
    MySqlQuery * First;
    MySqlQuery *Last;
    MySqlQuery *Current;
  public:


      MySqlHistory () { First = NULL; Last = NULL;

		Current = NULL; }

     ~MySqlHistory ();
    void Add (wxString & sql);
    MySqlQuery *GetCurrent () { return Current; }



    MySqlQuery *GetNext ();
    MySqlQuery *GetPrev ();
    bool TestNext ();
    bool TestPrev ();
};

class MyApp:public wxApp
{
//
// the main APP
//
    virtual bool OnInit ();
};

class MyTableTree:public wxTreeCtrl
{
//
// a tree-control used for SQLite DB tables
//
  private:
    class MyFrame * MainFrame;
    wxTreeItemId Root;		// the root node
    wxImageList *Images;	// the images list
    wxTreeItemId CurrentItem;	// the tree item holding the current context menu
  public:
      MyTableTree () { ; }
    MyTableTree (MyFrame * parent, wxWindowID id = wxID_ANY);
    virtual ~ MyTableTree () { ; }
    void SetPath (wxString & path) { SetItemText (Root, path); }
    void FlushAll () { DeleteChildren (Root); }
    void AddTable (wxString & tableName, bool virtualTable);
    void AddView (wxString & viewName);
    void ExpandRoot () { Expand (Root); }
    void ShowMenu (wxTreeItemId & item, wxPoint & pt);
    void OnSelChanged (wxTreeEvent & event);
    void OnRightClick (wxTreeEvent & event);
    void OnCmdNewTable (wxCommandEvent & event);
    void OnCmdNewView (wxCommandEvent & event);
    void OnCmdNewIndex (wxCommandEvent & event);
    void OnCmdNewTrigger (wxCommandEvent & event);
    void OnCmdNewColumn (wxCommandEvent & event);
    void OnCmdShow (wxCommandEvent & event);
    void OnCmdDrop (wxCommandEvent & event);
    void OnCmdRename (wxCommandEvent & event);
    void OnCmdSelect (wxCommandEvent & event);
    void OnCmdRefresh (wxCommandEvent & event);
    void OnCmdRecover (wxCommandEvent & event);
    void OnCmdShowSql (wxCommandEvent & event);
    void OnCmdSpatialIndex (wxCommandEvent & event);
	void OnCmdMbrCache (wxCommandEvent & event);
    void OnCmdCheckGeometry (wxCommandEvent & event);
    void OnCmdSetSrid (wxCommandEvent & event);
    void OnCmdDumpShp (wxCommandEvent & event);
    void OnCmdDumpTxtTab (wxCommandEvent & event);
    void OnCmdDumpCsv (wxCommandEvent & event);
    void OnCmdDumpHtml (wxCommandEvent & event);
    void OnCmdEdit (wxCommandEvent & event);
};

class MyQueryView:public wxPanel
{
//
// a panel to be used for SQL Queries
//
  private:
    class MyFrame * MainFrame;
    MySqlHistory History;
    wxTextCtrl *SqlCtrl;
    wxBitmapButton *BtnSqlGo;
    wxBitmapButton *BtnHistoryBack;
    wxBitmapButton *BtnHistoryForward;
    wxBitmapButton *BtnRsFirst;
    wxBitmapButton *BtnRsLast;
    wxBitmapButton *BtnRsNext;
    wxBitmapButton *BtnRsPrevious;
    wxBitmapButton *BtnRefresh;
    wxStaticText *RsCurrentBlock;
    int RsBlock;
    int RsBeginRow;
    int RsEndRow;
    int RsMaxRow;
    int CurrentEvtRow;
    int CurrentEvtColumn;
    MyVariant *CurrentBlob;
    wxString SqlErrorMsg;
    wxGrid *TableView;
    MyBlobs *TableBlobs;
    MyValues *TableValues;
    bool ReadOnly;
    int *RowIds;
    int PrimaryKeys[1024];
    int BlobColumns[1024];
    wxString TableName;
    bool InsertPending;
    MyRowVariant *InsertRow;
  public:
      MyQueryView () { ; }
    MyQueryView (MyFrame * parent, wxWindowID id = wxID_ANY);
    virtual ~ MyQueryView () { if (RowIds) delete[]RowIds;
		if (InsertRow) delete InsertRow; }
    void HideControls ();
    void HideRsControls ();
    void ShowSqlControls ();
    void ShowRsControls ();
    bool IsPrimaryKey (int column);
    bool IsBlobColumn (int column);
    void EditTable (wxString & sql, int *primaryKeys, int *blobCols,
		    wxString & tableName);
    void SetSql (wxString & sql, bool execute);
    bool ExecuteSql (wxString & sql, int from);
    void CreateGrid (int rows, int cols);
    void ResizeTableView ();
    void SetHistoryStates ();
    void DoInsert (bool confirmed);
    void HexBlobValue (unsigned char *blob, int size, wxString & hex);
    void OnSize (wxSizeEvent & event);
    void OnSqlGo (wxCommandEvent & event);
    void OnHistoryBack (wxCommandEvent & event);
    void OnHistoryForward (wxCommandEvent & event);
    void OnRsFirst (wxCommandEvent & event);
    void OnRsLast (wxCommandEvent & event);
    void OnRsNext (wxCommandEvent & event);
    void OnRsPrevious (wxCommandEvent & event);
    void OnRefresh (wxCommandEvent & event);
    void OnCellSelected (wxGridEvent & event);
    void OnRightClick (wxGridEvent & event);
    void OnCellChanged (wxGridEvent & event);
    void OnCmdDelete (wxCommandEvent & event);
    void OnCmdInsert (wxCommandEvent & event);
    void OnCmdAbort (wxCommandEvent & event);
    void OnCmdClearSelection (wxCommandEvent & event);
    void OnCmdSelectAll (wxCommandEvent & event);
    void OnCmdSelectRow (wxCommandEvent & event);
    void OnCmdSelectColumn (wxCommandEvent & event);
    void OnCmdCopy (wxCommandEvent & event);
    void OnCmdBlob (wxCommandEvent & event);
    void OnCmdBlobIn (wxCommandEvent & event);
    void OnCmdBlobOut (wxCommandEvent & event);
    void OnCmdBlobNull (wxCommandEvent & event);
};

class MyFrame:public wxFrame
{
//
// the main GUI frame
//
  private:
    unsigned char Jpeg1Signature[2];
    unsigned char Jpeg2Signature[2];
    unsigned char Jpeg3Signature[4];
    unsigned char JfifSignature[4];
    unsigned char ExifSignature[4];
    unsigned char PngSignature[8];
    unsigned char ZipSignature[4];
    wxAuiManager Manager;	// the GUI manager
    MyTableTree *TableTree;	// the tables tree list
    MyQueryView *QueryView;	// the QueryResult panel
    bool HelpPane;		// is the HELP pane already opened ?
    sqlite3 *SqliteHandle;	// handle for SQLite DB
    wxString SqlitePath;	// path of SQLite DB
    wxString LastDirectory;	// path of directory used  
    int CharsetsLen;		// # charsets defined
    wxString *Charsets;		// table of charsets [code only]
    wxString *CharsetsNames;	// table of charsets [whith description]
    wxString LocaleCharset;	// locale charset
    wxString DefaultCharset;	// default charset
    bool AskCharset;		// switch to set default charset for every output
    wxBitmap *BtnCreateNew;	// button icon for DB CREATE&CONNECT
    wxBitmap *BtnConnect;	// button icon for DB CONNECT
    wxBitmap *BtnDisconnect;	// button icon for DB DISCONNECT
    wxBitmap *BtnVacuum;	// button icon for DB VACUUM
    wxBitmap *BtnSqlScript;	// button icon for Execute SQL SCRIPT
    wxBitmap *BtnCharset;	// button icon for Default CHARSET
    wxBitmap *BtnLoadShp;	// button icon for LOAD SHP
	wxBitmap *BtnLoadTxt;	// button icon for LOAD TXT/CSV
    wxBitmap *BtnVirtualShp;	// button icon for VIRTUAL SHP
	wxBitmap *BtnVirtualTxt;	// button icon for VIRTUAL TXT/CSV
    wxBitmap *BtnSrids;		// button icon for SEARCH SRIDs
    wxBitmap *BtnHelp;		// button icon for HELP
    wxBitmap *BtnAbout;		// button icon for ABOUT
    wxBitmap *BtnExit;		// button icon for EXIT
  public:
    enum
    {
	BLOB_NULL = 0,
	BLOB_HEX,
	BLOB_GEOMETRY,
	BLOB_JPEG,
	BLOB_JFIF,
	BLOB_EXIF,
	BLOB_PNG,
	BLOB_GIF,
	BLOB_PDF,
	BLOB_ZIP,
    };
      MyFrame (const wxString & title, const wxPoint & pos, const wxSize & size,
	       wxString & path);
      virtual ~ MyFrame ();

    void UpdateStatusBar ();
    bool IsConnected () { if (SqliteHandle) return true;
		else return false;
    }
    static void CleanSql (char *str);
    void CleanTxtTab (char *str);
    void CleanCsv (char *str);
    void CleanHtml (char *str);
    sqlite3 *GetSqlite () { return SqliteHandle; }
    void CloseHelpPane () { HelpPane = false; }
    void OpenHelpPane () { HelpPane = true; }

    bool OpenDB ();
    bool CreateDB ();
    void CloseDB ();
    void InitTableTree ();
    void ClearTableTree ();
    void GetTableColumns (wxString & tableName, MyTableInfo * list);
    void GetTableIndices (wxString & tableName, MyTableInfo * list);
    void GetTableTriggers (wxString & tableName, MyTableInfo * list);
    void GetViewColumns (wxString & viewName, MyViewInfo * list);
    void EditTable (wxString & sql, int *primaryKeys, int *blobCols,
		    wxString & table) 
			{ QueryView->EditTable (sql, primaryKeys, blobCols, table); }
    void SetSql (wxString & sql, bool execute)
		{ QueryView->SetSql (sql, execute); }
    int GuessBlobType (int blob_size, unsigned char *blob);
    bool ExecuteSql (const char *sql, int rowNo);
    void Rollback ();
    bool TableAlreadyExists (wxString & name);
    bool SridNotExists (int srid);
    bool CheckMetadata ();
    void CleanSqlString (char *sql);
    wxString *GetCharsets () { return Charsets; }
    wxString *GetCharsetsNames () { return CharsetsNames; }
    int GetCharsetsLen () { return CharsetsLen; }
    gaiaDbfFieldPtr GetDbfField (gaiaDbfListPtr list, char *name);
	void LoadShapefile (wxString & path, wxString & table, int srid,
			wxString & column, wxString & charset);
    void DumpShapefile (wxString & path, wxString & table, wxString & column,
			wxString & charset);
	void LoadText (wxString & path, wxString & table, wxString & charset, bool first_titles, char decimal_separator, 
	char separator, char text_separator);
	void DumpTxtTab (wxString & path, wxString & table, wxString & charset);
    void DumpCsv (wxString & path, wxString & table, wxString & charset);
    void DumpHtml (wxString & path, wxString & table, wxString & charset);
    void GetHelp (wxString & html);
    wxString *GetColumnNames (wxString & table, int *columns);
    void SetLastDirectory (wxString & path) { LastDirectory = path; }
    wxString & GetLastDirectory () { return LastDirectory; }
    wxString & GetLocaleCharset () { return LocaleCharset; }
    wxString & GetDefaultCharset () { return DefaultCharset; }
    wxString & GetCharsetName (wxString & charset);
    int GetCharsetIndex (wxString & charset);
    bool IsSetAskCharset () { return AskCharset; }
	char * ReadSqlLine(FILE *fl, int *len, int *eof);
	
    void OnQuit (wxCommandEvent & event);
    void OnAbout (wxCommandEvent & event);
    void OnConnect (wxCommandEvent & event);
    void OnCreateNew (wxCommandEvent & event);
    void OnDisconnect (wxCommandEvent & event);
    void OnVacuum (wxCommandEvent & event);
    void OnSqlScript (wxCommandEvent & event);
    void OnCharset (wxCommandEvent & event);
    void OnLoadShp (wxCommandEvent & event);
	void OnLoadTxt (wxCommandEvent & event);
    void OnVirtualShp (wxCommandEvent & event);
	void OnVirtualTxt (wxCommandEvent & event);
    void OnSrids (wxCommandEvent & event);
    void OnHelp (wxCommandEvent & event);
    void OnMouseMove (wxMouseEvent & event);
};

class HelpDialog:public wxDialog
{
//
// the help dialog
//
  private:
    MyFrame * MainFrame;
  public:
    HelpDialog () { MainFrame = NULL; }
    HelpDialog (MyFrame * parent) { Create (parent); }
    bool Create (MyFrame * parent);
    virtual ~ HelpDialog () { ; }
    void CreateControls ();
    void OnClose (wxCloseEvent & event);
};

class SearchSridDialog:public wxDialog
{
//
// a dialog preparing a Search SRID by name
//
  private:
    MyFrame * MainFrame;
    wxString String;		// required search string
  public:
      SearchSridDialog () { ; }
    SearchSridDialog (MyFrame * parent);
    bool Create (MyFrame * parent);
    virtual ~ SearchSridDialog () { ; }
    void CreateControls ();
    wxString & GetString () { return String; }
    void OnOk (wxCommandEvent & event);
};

class SetSridDialog:public wxDialog
{
//
// a dialog preparing a SET SRID
//
  private:
    MyFrame * MainFrame;
    wxString Table;		// the table's name 
    wxString Column;		// the column's name to be recovered
    int OldSrid;		// SRID to substitute
    int Srid;			// required SRID
  public:
      SetSridDialog () { ; }
    SetSridDialog (MyFrame * parent, wxString & table, wxString & column);
    bool Create (MyFrame * parent, wxString & table, wxString & column);
    virtual ~ SetSridDialog () { ; }
    void CreateControls ();
    int GetOldSrid () { return OldSrid; }
    int GetSrid () { return Srid; }
    void OnOk (wxCommandEvent & event);
};

class RecoverDialog:public wxDialog
{
//
// a dialog preparing a RECOVER GEOMETRY
//
  private:
    MyFrame * MainFrame;
    wxString Table;		// the table's name 
    wxString Column;		// the column's name to be recovered
    int Srid;			// required SRID
    wxString Type;		// required Geometry Type
  public:
      RecoverDialog () { ; }
    RecoverDialog (MyFrame * parent, wxString & table, wxString & column);
    bool Create (MyFrame * parent, wxString & table, wxString & column);
    virtual ~ RecoverDialog () { ; }
    void CreateControls ();
    wxString & GetType () { return Type; }
    int GetSrid () { return Srid; }
    void OnOk (wxCommandEvent & event);
};

class VirtualShpDialog:public wxDialog
{
//
// a dialog preparing a CREATE VIRTUAL SHAPE
//
  private:
    MyFrame * MainFrame;
    wxString Path;		// the SHP base path
	wxString Table;		// the table name
    wxString Default;		// the default charset
    wxString Charset;		// the SHP charset
    int Srid;			// the SRID
  public:
      VirtualShpDialog () { ; }
    VirtualShpDialog (MyFrame * parent, wxString & path, wxString & table, wxString & defCs);
    bool Create (MyFrame * parent, wxString & path, wxString & table, wxString & defCs);
    virtual ~ VirtualShpDialog () { ; }
    void CreateControls ();
	wxString & GetTable() { return Table; }
    wxString & GetCharset () { 	return Charset; }
    int GetSrid () { return Srid; }
    void OnOk (wxCommandEvent & event);
};

class VirtualTxtDialog:public wxDialog
{
//
// a dialog preparing a CREATE VIRTUAL TEXT
//
  private:
    MyFrame * MainFrame;
    wxString Path;		// the CSV/TXT base path
	wxString Table;		// the table name
    wxString Default;		// the default charset
    wxString Charset;		// the CSV/TXT charset
	bool FirstLineTitles;	// TRUE if first line stores column titles
	char Separator;			// the character to be used as field separator
	char TextSeparator;		// the character to be used as text separator
	bool DecimalPointIsComma;		// TRUE if decimal separator is COMMA
  public:
      VirtualTxtDialog () { ; }
    VirtualTxtDialog (MyFrame * parent, wxString & path, wxString & table, wxString & defCs);
    bool Create (MyFrame * parent, wxString & path, wxString & table, wxString & defCs);
    virtual ~ VirtualTxtDialog () { ; }
    void CreateControls ();
	wxString & GetTable() { return Table; }
    wxString & GetCharset () { 	return Charset; }
	bool IsFirstLineTitles() { return FirstLineTitles; }
	char GetSeparator() { return Separator; }
	char GetTextSeparator() { return TextSeparator; }
	bool IsDecimalPointComma() { return DecimalPointIsComma; }
	void OnSeparator (wxCommandEvent & event);
	void OnDecimalSeparator (wxCommandEvent & event);
	void OnQuote (wxCommandEvent & event);
    void OnOk (wxCommandEvent & event);
};

class LoadShpDialog:public wxDialog
{
//
// a dialog preparing a LOAD SHAPE
//
  private:
    MyFrame * MainFrame;
    wxString Path;		// the SHP base path
    wxString Table;		// the table's name to be created
    wxString Column;		// the column's name for Geometry
    wxString Default;		// the default charset
    wxString Charset;		// the SHP charset
    int Srid;			// the SRID
  public:
      LoadShpDialog () { ; }
    LoadShpDialog (MyFrame * parent, wxString & path, wxString & table,
		   int srid, wxString & column, wxString & defCs);
    bool Create (MyFrame * parent, wxString & path, wxString & table, int srid,
		 wxString & column, wxString & defCs);
    virtual ~ LoadShpDialog () { ; }
    void CreateControls ();
    wxString & GetTable () { return Table; }
    wxString & GetColumn () { return Column; }
    wxString & GetCharset () { return Charset; }
    int GetSrid () { return Srid; }
    void OnOk (wxCommandEvent & event);
};

class DumpShpDialog:public wxDialog
{
//
// a dialog preparing a DUMP SHAPE
//
  private:
    MyFrame * MainFrame;
    wxString Path;		// the SHP base path
    wxString Table;		// the table's name to be created
    wxString Column;		// the column's name for Geometry
    wxString Default;		// the default charset
    wxString Charset;		// the SHP charset
  public:
      DumpShpDialog () { ; }
    DumpShpDialog (MyFrame * parent, wxString & path, wxString & table,
		   wxString & column, wxString & defCs);
    bool Create (MyFrame * parent, wxString & path, wxString & table,
		 wxString & column, wxString & defCs);
    virtual ~ DumpShpDialog () { ; }
    void CreateControls ();
    wxString & GetCharset () { return Charset; }
    void OnOk (wxCommandEvent & event);
};

class LoadTxtDialog:public wxDialog
{
//
// a dialog preparing a LOAD TXT/CSV
//
  private:
    MyFrame * MainFrame;
    wxString Path;		// the CSV/TXT base path
	wxString Table;		// the table name
    wxString Default;		// the default charset
    wxString Charset;		// the CSV/TXT charset
	bool FirstLineTitles;	// TRUE if first line stores column titles
	char Separator;			// the character to be used as field separator
	char TextSeparator;		// the character to be used as text separator
	bool DecimalPointIsComma;		// TRUE if decimal separator is COMMA
  public:
      LoadTxtDialog () { ; }
    LoadTxtDialog (MyFrame * parent, wxString & path, wxString & table, wxString & defCs);
    bool Create (MyFrame * parent, wxString & path, wxString & table, wxString & defCs);
    virtual ~ LoadTxtDialog () { ; }
    void CreateControls ();
	wxString & GetTable() { return Table; }
    wxString & GetCharset () { 	return Charset; }
	bool IsFirstLineTitles() { return FirstLineTitles; }
	char GetSeparator() { return Separator; }
	char GetTextSeparator() { return TextSeparator; }
	bool IsDecimalPointComma() { return DecimalPointIsComma; }
	void OnSeparator (wxCommandEvent & event);
	void OnDecimalSeparator (wxCommandEvent & event);
	void OnQuote (wxCommandEvent & event);
    void OnOk (wxCommandEvent & event);
};

class DumpTxtDialog:public wxDialog
{
//
// a dialog preparing a DUMP generic text
//
  private:
    MyFrame * MainFrame;
    wxString Path;		// the SHP base path
    wxString Default;		// the default charset
    wxString Charset;		// the target charset
  public:
      DumpTxtDialog () { ; }
    DumpTxtDialog (MyFrame * parent, wxString & path, wxString & target,
		   wxString & defCs);
    bool Create (MyFrame * parent, wxString & path, wxString & target,
		 wxString & defCs);
    virtual ~ DumpTxtDialog () { ; }
    void CreateControls ();
    wxString & GetCharset () { return Charset; }
    void OnOk (wxCommandEvent & event);
};

class SqlScriptDialog:public wxDialog
{
//
// a dialog preparing an SQL SCRIPT execute
//
  private:
    MyFrame * MainFrame;
    wxString Path;		// the SHP base path
    wxString Default;		// the default charset
    wxString Charset;		// the target charset
  public:
      SqlScriptDialog () { ; }
    SqlScriptDialog (MyFrame * parent, wxString & path, wxString & defCs);
    bool Create (MyFrame * parent, wxString & path, wxString & defCs);
    virtual ~ SqlScriptDialog () { ; }
    void CreateControls ();
    wxString & GetCharset () { return Charset; }
    void OnOk (wxCommandEvent & event);
};

class DefaultCharsetDialog:public wxDialog
{
//
// a dialog for selecting DEFAULT CHARSET
//
  private:
    MyFrame * MainFrame;
    wxString Charset;		// the default charset
    bool AskCharset;		// true / false
  public:
      DefaultCharsetDialog () { ; }
    DefaultCharsetDialog (MyFrame * parent, wxString & charset, bool ask);
    bool Create (MyFrame * parent, wxString & charset, bool ask);
    virtual ~ DefaultCharsetDialog () { ; }
    void CreateControls ();
    wxString & GetCharset () { return Charset; }
    bool IsSetAskCharset () { return AskCharset; }
    void OnOk (wxCommandEvent & event);
};


class BlobExplorerDialog:public wxPropertySheetDialog
{
//
// a dialog to explore a BLOB value
//
  private:
    MyFrame * MainFrame;
    int BlobSize;		// the BLOB size
    unsigned char *Blob;	// the BLOB value
    int BlobType;		// the BLOB type
    gaiaGeomCollPtr Geometry;	// the geometry [optional]
    wxImage *Image;		// the image [optional]
    wxBitmap GeomPreview;	// the geometry preview
  public:
      BlobExplorerDialog ()
    {;
    }
    BlobExplorerDialog (MyFrame * parent, int blob_size, unsigned char *blob);
    bool Create (MyFrame * parent, int blob_size, unsigned char *blob);
    virtual ~ BlobExplorerDialog () { if (Geometry) gaiaFreeGeomColl (Geometry);
		if (Image) delete Image; }
    void DrawGeometry (int horz, int vert);
    wxPanel *CreateHexadecimalPage (wxWindow * book);
    wxPanel *CreateGeometryPage (wxWindow * book);
    wxPanel *CreateImagePage (wxWindow * book);
    void UpdateHexadecimalPage ();
    void UpdateGeometryPage ();
    void UpdateImagePage ();
    gaiaGeomCollPtr GetGeometry () { return Geometry; }
    wxImage *GetImage () { return Image; }
    int GetBlobType () { return BlobType; }
    void OnOk (wxCommandEvent & event);
    void OnPageChanged (wxNotebookEvent & event);
};

class GraphicsGeometry:public wxStaticBitmap
{
//
// a window to show some Geometry in a graphical fashion
//
  private:
    BlobExplorerDialog * Parent;
  public:
    GraphicsGeometry (BlobExplorerDialog * parent, wxWindow * panel,
		      wxWindowID id, const wxBitmap & bmp, wxSize const &size);
      virtual ~ GraphicsGeometry () { ; }



































































































































































































































































































































































































































































































};

class ImageShow:public wxStaticBitmap
{
//
// a window to show some Image [Jpeg-Png-Gif]
//
  private:
    BlobExplorerDialog * Parent;
  public:
    ImageShow (BlobExplorerDialog * parent, wxWindow * panel, wxWindowID id,
	       const wxBitmap & bmp, const wxSize & size);
      virtual ~ ImageShow () { ; }


    void OnRightClick (wxMouseEvent & event);
    void OnCmdCopy (wxCommandEvent & event);
};

class MyHexList:public wxListCtrl
{
//
// a class for Hexdecimal dumps
//
  private:
    BlobExplorerDialog * Parent;
    int BlobSize;		// the BLOB size
    unsigned char *Blob;	// the BLOB value
  public:
      MyHexList (BlobExplorerDialog * parent, unsigned char *blob,
		 int blob_size, wxWindow * panel, wxWindowID id,
		 const wxPoint & pos = wxDefaultPosition, const wxSize & size =
		 wxDefaultSize, long style = 0);
      virtual ~ MyHexList ();
    virtual wxString OnGetItemText (long item, long column) const;
};









































































































































































































































































































































>


>





|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







|
|
|
|
|
|
|
|
|







|
|
|
|
|
|
|
|
|
|
|
|







|
|
|
|
|
|
>
>
>
|
>
|
>
>
|
>
>
>
|
>
>
>
|
>
>
>
|
>
>
>
|
>
>
>







|
|
|
|
|
>
>
|
>
|
>
|
|
|
>
>
>
|
|
|
|







|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







|
|
|
|
|
|
>
>
|
|







|
|
|
|
|
|
|
|
|
|
|

>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
*/

#include "wx/wx.h"
#include "wx/aui/aui.h"
#include "wx/treectrl.h"
#include "wx/grid.h"
#include "wx/listctrl.h"
#include "wx/textctrl.h"
#include "wx/propdlg.h"
#include "wx/generic/propdlg.h"
#include "wx/timer.h"

#include <spatialite/sqlite3.h>

#define OMIT_GEOS    0
#define OMIT_PROJ    0
#include <spatialite/gaiaaux.h>
#include <spatialite/gaiaexif.h>
#include <spatialite/gaiageo.h>
#include <spatialite.h>

//
// functions for QSORT / BSEARCH
//
int cmp_prenodes_code(const void *p1, const void *p2);
int cmp_prenodes_id(const void *p1, const void *p2);
int cmp_nodes2_code(const void *p1, const void *p2);
int cmp_nodes2_id(const void *p1, const void *p2);
int cmp_nodes1_code(const void *p1, const void *p2);
int cmp_nodes1_id(const void *p1, const void *p2);

enum
{
// control IDs for main window and tree list control
  ID_Connect = 1,
  ID_CreateNew,
  ID_Disconnect,
  ID_MemoryDbLoad,
  ID_MemoryDbNew,
  ID_MemoryDbClock,
  ID_MemoryDbSave,
  ID_Vacuum,
  ID_SqlScript,
  ID_LoadShp,
  ID_LoadTxt,
  ID_VirtualShp,
  ID_VirtualTxt,
  ID_Network,
  ID_Exif,
  ID_Srids,
  ID_Charset,
  ID_Help,
  Tree_NewTable,
  Tree_NewView,
  Tree_NewIndex,
  Tree_NewTrigger,
  Tree_NewColumn,
  Tree_Show,
  Tree_Drop,
  Tree_Rename,
  Tree_Select,
  Tree_Refresh,
  Tree_SpatialIndex,
  Tree_MbrCache,
  Tree_RebuildTriggers,
  Tree_ShowSql,
  Tree_Recover,
  Tree_CheckGeometry,
  Tree_SetSrid,
  Tree_DumpShp,
  Tree_DumpTxtTab,
  Tree_DumpCsv,
  Tree_DumpHtml,
  Tree_Edit,
  Grid_Clear,
  Grid_All,
  Grid_Column,
  Grid_Row,
  Grid_Copy,
  Grid_Blob,
  Grid_Delete,
  Grid_Insert,
  Grid_Abort,
  Grid_BlobIn,
  Grid_BlobOut,
  Grid_BlobNull,
  Image_Copy,
};

enum
{
// control IDs for dialogs
  ID_SQL = 10000,
  ID_SQL_GO,
  ID_HISTORY_BACK,
  ID_HISTORY_FORWARD,
  ID_RS_FIRST,
  ID_RS_LAST,
  ID_RS_NEXT,
  ID_RS_PREVIOUS,
  ID_REFRESH,
  ID_RS_BLOCK,
  ID_PANE_HEXADECIMAL,
  ID_PANE_GEOMETRY,
  ID_PANE_IMAGE,
  ID_HEX,
  ID_GEOM_TABLE,
  ID_GEOM_GRAPH,
  ID_GEOM_BOX,
  ID_IMAGE_TITLE,
  ID_IMG_BOX,
  ID_IMAGE,
  ID_VIRTSHP_TABLE,
  ID_VIRTSHP_SRID,
  ID_VIRTSHP_CHARSET,
  ID_VIRTTXT_TABLE,
  ID_VIRTTXT_CHARSET,
  ID_VIRTTXT_TITLES,
  ID_VIRTTXT_SEPARATOR,
  ID_VIRTTXT_CHARSEPARATOR,
  ID_VIRTTXT_QUOTE,
  ID_VIRTTXT_POINT,
  ID_LDSHP_TABLE,
  ID_LDSHP_COLUMN,
  ID_LDSHP_SRID,
  ID_LDSHP_CHARSET,
  ID_LDTXT_TABLE,
  ID_LDTXT_CHARSET,
  ID_LDTXT_TITLES,
  ID_LDTXT_SEPARATOR,
  ID_LDTXT_CHARSEPARATOR,
  ID_LDTXT_QUOTE,
  ID_LDTXT_POINT,
  ID_DMPSHP_CHARSET,
  ID_DMPTXT_CHARSET,
  ID_NET_TABLE,
  ID_NET_FROM,
  ID_NET_TO,
  ID_NET_GEOM,
  ID_NET_LENGTH,
  ID_NET_COST,
  ID_NET_BIDIR,
  ID_NET_ONEWAY,
  ID_NET_FROM_TO,
  ID_NET_TO_FROM,
  ID_EXIF_PATH,
  ID_EXIF_FOLDER,
  ID_EXIF_SINGLE,
  ID_EXIF_METADATA,
  ID_EXIF_GPS_ONLY,
  ID_DFLT_CHARSET,
  ID_DFLT_ASK,
  ID_SCRIPT_CHARSET,
  ID_RCVR_SRID,
  ID_RCVR_TYPE,
  ID_SRID_OLD,
  ID_SRID_SRID,
  ID_SEARCH,
  ID_HELP_HTML,
  ID_AUTO_SAVE_PATH,
  ID_AUTO_SAVE_INTERVAL,
  ID_AUTO_SAVE_CHANGE_PATH,
};

enum
{
// tree item data types
  MY_TABLE = 0,
  MY_VTABLE,
  MY_VIEW,
  MY_COLUMN,
  MY_GEOMETRY,
  MY_GEOMETRY_INDEX,
  MY_GEOMETRY_CACHED,
  MY_INDEX,
  MY_TRIGGER,
  MY_INT_VARIANT,
  MY_DBL_VARIANT,
  MY_TXT_VARIANT,
  MY_BLOB_VARIANT,
  MY_NULL_VARIANT,
};

enum
{
// control IDs for timers
  ID_AUTO_SAVE_TIMER = 20000,
};

class MyObject:public wxTreeItemData
{
//
// a class to store TreeItemData
//
private:
  int Type;                     // the object type
  wxString Name;                // the object name
  wxString Column;              // the column name [optional]
public:
    MyObject(int type, wxString & name);
    MyObject(int type, wxString & name, wxString & column);
    virtual ~ MyObject()
  {;
  }
  int GetType()
  {
    return Type;
  }
  wxString & GetName()
  {
    return Name;
  }
  wxString & GetColumn()
  {
    return Column;
  }
};

class MyColumnInfo
{
//
// a class to store a DB column
//
private:
  wxString Name;                // the column name
  bool PrimaryKey;              // Primary Key column
  bool Geometry;                // Geometry column
  bool GeometryIndex;           // Geometry column + SpatialIndex
  bool MbrCache;                // Geometry column + MbrCache
  MyColumnInfo *Next;           // pointer to next element into the linked list
public:
    MyColumnInfo(wxString & name, bool pkey);
   ~MyColumnInfo()
  {;
  }
  wxString & GetName()
  {
    return Name;
  }
  bool IsPrimaryKey()
  {
    return PrimaryKey;
  }
  void SetGeometry()
  {
    Geometry = true;
  }
  bool IsGeometry()
  {
    return Geometry;
  }
  void SetGeometryIndex()
  {
    GeometryIndex = true;
  }
  bool IsGeometryIndex()
  {
    return GeometryIndex;
  }
  void SetMbrCache()
  {
    MbrCache = true;
  }
  bool IsMbrCache()
  {
    return MbrCache;
  }
  void SetNext(MyColumnInfo * next)
  {
    Next = next;
  }
  MyColumnInfo *GetNext()
  {
    return Next;
  }
};

class MyIndexInfo
{
//
// a class to store a DB index
//
private:
  wxString Name;                // the index name
  MyIndexInfo *Next;            // pointer to next element into the linked list
public:
    MyIndexInfo(wxString & name);
    MyIndexInfo()
  {;
  }
  wxString & GetName()
  {
    return Name;
  }
  void SetNext(MyIndexInfo * next)
  {
    Next = next;
  }
  MyIndexInfo *GetNext()
  {
    return Next;
  }
};

class MyTriggerInfo
{
//
// a class to store a DB trigger
//
private:
  wxString Name;                // the trigger name
  MyTriggerInfo *Next;          // pointer to next element into the linked list
public:
    MyTriggerInfo(wxString & name);
   ~MyTriggerInfo()
  {;
  }
  wxString & GetName()
  {
    return Name;
  }
  void SetNext(MyTriggerInfo * next)
  {
    Next = next;
  }
  MyTriggerInfo *GetNext()
  {
    return Next;
  }
};

class MyTableInfo
{
//
// a class to store DB table columns
//
private:
  MyColumnInfo * FirstColumn;   // first element into the columns linked list
  MyColumnInfo *LastColumn;     // last element into the columns linked list
  MyIndexInfo *FirstIndex;      // first element into the indices linked list
  MyIndexInfo *LastIndex;       // last element into the indices linked list
  MyTriggerInfo *FirstTrigger;  // first element into the triggers linked list
  MyTriggerInfo *LastTrigger;   // last element into the triggers linked list
public:
    MyTableInfo()
  {
    FirstColumn = NULL;
    LastColumn = NULL;
    FirstIndex = NULL;
    LastIndex = NULL;
    FirstTrigger = NULL;
    LastTrigger = NULL;
  }
   ~MyTableInfo();
  void AddColumn(wxString & name, bool pkey);
  void SetGeometry(wxString & name, bool index, bool cached);
  void AddIndex(wxString & name);
  void AddTrigger(wxString & name);
  MyColumnInfo *GetFirstColumn()
  {
    return FirstColumn;
  }
  MyIndexInfo *GetFirstIndex()
  {
    return FirstIndex;
  }
  MyTriggerInfo *GetFirstTrigger()
  {
    return FirstTrigger;
  }
};

class MyViewInfo
{
//
// a class to store DB view columns
//
private:
  MyColumnInfo * First;         // first element into the columns linked list
  MyColumnInfo *Last;           // last element into the columns linked list
public:
    MyViewInfo()
  {
    First = NULL;
    Last = NULL;
  }
   ~MyViewInfo();
  void AddColumn(wxString & name);
  MyColumnInfo *GetFirst()
  {
    return First;
  }
};

class MyVariant
{
//
// a class to store Variant-Type values
//
private:
  int Type;                     // the Variant-Type
  sqlite3_int64 IntValue;       // the Integer value
  double DblValue;              // the Double value
  wxString TxtValue;            // the Text value
  unsigned char *Blob;          // the BLOB value
  int BlobSize;                 // the BLOB size
public:
    MyVariant()
  {
    Type = MY_NULL_VARIANT;
    Blob = NULL;
  }
   ~MyVariant()
  {
    if (Blob)
      delete Blob;
  }
  void Clear()
  {
    if (Blob)
      delete Blob;
    Blob = NULL;
    Type = MY_NULL_VARIANT;
  }
  void Set(sqlite3_int64 value)
  {
    Type = MY_INT_VARIANT;
    IntValue = value;
  }
  void Set(double value)
  {
    Type = MY_DBL_VARIANT;
    DblValue = value;
  }
  void Set(const unsigned char *text);
  void Set(wxString & string)
  {
    Type = MY_TXT_VARIANT;
    TxtValue = string;
  }
  void Set(const void *blob, int size);
  void Copy(MyVariant * other);
  int GetType()
  {
    return Type;
  }
  sqlite3_int64 GetIntValue()
  {
    return IntValue;
  }
  double GetDblValue()
  {
    return DblValue;
  }
  wxString & GetTxtValue()
  {
    return TxtValue;
  }
  int GetBlobSize()
  {
    return BlobSize;
  }
  unsigned char *GetBlob()
  {
    return Blob;
  }
};

class MyRowVariant
{
//
// a class to store a row composed of Variant-Type values
//
private:
  int NumCols;                  // number of columns
  MyVariant *ColumnArray;       // the column as an array
  bool Deleted;                 // switch to mark row deletion
  MyRowVariant *Next;           // pointer to next element into the linked list
public:
    MyRowVariant()
  {
    NumCols = 0;
    ColumnArray = NULL;
    Deleted = false;
    Next = NULL;
  }
  MyRowVariant(int cols)
  {
    NumCols = cols;
    ColumnArray = new MyVariant[cols];
    Next = NULL;
  }
  ~MyRowVariant()
  {
    if (ColumnArray)
      delete[]ColumnArray;
  }
  void Create(int cols);
  int GetNumCols()
  {
    return NumCols;
  }
  void Set(int col, sqlite3_int64 value);
  void Set(int col, double value);
  void Set(int col, const unsigned char *text);
  void Set(int col, const void *blob, int size);
  MyVariant *GetColumn(int col);
  void SetDeleted()
  {
    Deleted = true;
  }
  bool IsDeleted()
  {
    return Deleted;
  }
  void SetNext(MyRowVariant * next)
  {
    Next = next;
  }
  MyRowVariant *GetNext()
  {
    return Next;
  }
};

class MyVariantList
{
//
// a class to store a whole result set
//
private:
  int NumCols;                  // number of columns
  wxString *ColumnName;         // the column names
  MyRowVariant *First;          // first element into the linked list
  MyRowVariant *Last;           // last element into the linked list
public:
    MyVariantList();
   ~MyVariantList();
  MyRowVariant *Add(int columns);
  void SetColumnName(int col, const char *colName);
  MyRowVariant *GetFirst()
  {
    return First;
  }
  int GetRows();
  int GetColumns()
  {
    return NumCols;
  }
  wxString & GetColumnName(int col);
};

class MyBlobs
{
//
// a class to store BLOBs
//
private:
  int NumRows;                  // the number of rows
  int NumCols;                  // the number of columns
  MyRowVariant *Rows;           // pointer to an array of rows
public:
    MyBlobs(int rows, int cols);
   ~MyBlobs();
  void SetBlob(int row, int col, MyVariant * blobVar);
  MyVariant *GetBlob(int row, int col);
};

class MyValues
{
//
// a class to store column values for editing
//
private:
  int NumRows;                  // the number of rows
  int NumCols;                  // the number of columns
  MyRowVariant *Rows;           // pointer to an array of rows
public:
    MyValues(int rows, int cols);
   ~MyValues();
  void SetValue(int row, int col, sqlite3_int64 value);
  void SetValue(int row, int col, double value);
  void SetValue(int row, int col, wxString & string);
  MyRowVariant *GetRow(int row);
  MyVariant *GetValue(int row, int col);
};

class MySqlQuery
{
//
// a class to store an SQL query - history
//
private:
  wxString Sql;
  MySqlQuery *Prev;
  MySqlQuery *Next;
public:
    MySqlQuery(wxString & sql)
  {
    Sql = sql;
    Prev = NULL;
    Next = NULL;
  }
   ~MySqlQuery()
  {;
  }
  wxString & GetSql()
  {
    return Sql;
  }
  void SetPrev(MySqlQuery * prev)
  {
    Prev = prev;
  }
  MySqlQuery *GetPrev()
  {
    return Prev;
  }
  void SetNext(MySqlQuery * next)
  {
    Next = next;
  }
  MySqlQuery *GetNext()
  {
    return Next;
  }
};

class MySqlHistory
{
//
// a class supporting SQL queries history
//
private:
  MySqlQuery * First;
  MySqlQuery *Last;
  MySqlQuery *Current;
public:
    MySqlHistory()
  {
    First = NULL;
    Last = NULL;
    Current = NULL;
  }
   ~MySqlHistory();
  void Add(wxString & sql);
  MySqlQuery *GetCurrent()
  {
    return Current;
  }
  MySqlQuery *GetNext();
  MySqlQuery *GetPrev();
  bool TestNext();
  bool TestPrev();
};

class MyApp:public wxApp
{
//
// the main APP
//
  virtual bool OnInit();
};

class MyTableTree:public wxTreeCtrl
{
//
// a tree-control used for SQLite DB tables
//
private:
  class MyFrame * MainFrame;
  wxTreeItemId Root;            // the root node
  wxImageList *Images;          // the images list
  wxTreeItemId CurrentItem;     // the tree item holding the current context menu
public:
    MyTableTree()
  {;
  }
  MyTableTree(class MyFrame * parent, wxWindowID id = wxID_ANY);
  virtual ~ MyTableTree()
  {;
  }
  void SetPath(wxString & path)
  {
    SetItemText(Root, path);
  }
  void FlushAll()
  {
    DeleteChildren(Root);
  }
  void AddTable(wxString & tableName, bool virtualTable);
  void AddView(wxString & viewName);
  void ExpandRoot()
  {
    Expand(Root);
  }
  void ShowMenu(wxTreeItemId & item, wxPoint & pt);
  void OnSelChanged(wxTreeEvent & event);
  void OnRightClick(wxTreeEvent & event);
  void OnCmdNewTable(wxCommandEvent & event);
  void OnCmdNewView(wxCommandEvent & event);
  void OnCmdNewIndex(wxCommandEvent & event);
  void OnCmdNewTrigger(wxCommandEvent & event);
  void OnCmdNewColumn(wxCommandEvent & event);
  void OnCmdShow(wxCommandEvent & event);
  void OnCmdDrop(wxCommandEvent & event);
  void OnCmdRename(wxCommandEvent & event);
  void OnCmdSelect(wxCommandEvent & event);
  void OnCmdRefresh(wxCommandEvent & event);
  void OnCmdRecover(wxCommandEvent & event);
  void OnCmdShowSql(wxCommandEvent & event);
  void OnCmdSpatialIndex(wxCommandEvent & event);
  void OnCmdMbrCache(wxCommandEvent & event);
  void OnCmdRebuildTriggers(wxCommandEvent & event);
  void OnCmdCheckGeometry(wxCommandEvent & event);
  void OnCmdSetSrid(wxCommandEvent & event);
  void OnCmdDumpShp(wxCommandEvent & event);
  void OnCmdDumpTxtTab(wxCommandEvent & event);
  void OnCmdDumpCsv(wxCommandEvent & event);
  void OnCmdDumpHtml(wxCommandEvent & event);
  void OnCmdEdit(wxCommandEvent & event);
};

class MyResultSetView:public wxPanel
{
//
// a panel to be used for SQL Queries
//
private:
  class MyFrame * MainFrame;
  wxBitmapButton *BtnRsFirst;
  wxBitmapButton *BtnRsLast;
  wxBitmapButton *BtnRsNext;
  wxBitmapButton *BtnRsPrevious;
  wxBitmapButton *BtnRefresh;
  wxStaticText *RsCurrentBlock;
  int RsBlock;
  int RsBeginRow;
  int RsEndRow;
  int RsMaxRow;
  int CurrentEvtRow;
  int CurrentEvtColumn;
  MyVariant *CurrentBlob;
  wxGrid *TableView;
  MyBlobs *TableBlobs;
  MyValues *TableValues;
  bool ReadOnly;
  sqlite3_int64 *RowIds;
  int PrimaryKeys[1024];
  int BlobColumns[1024];
  wxString TableName;
  bool InsertPending;
  MyRowVariant *InsertRow;
  wxString SqlErrorMsg;
public:
    MyResultSetView()
  {;
  }
  MyResultSetView(MyFrame * parent, wxWindowID id = wxID_ANY);
  virtual ~ MyResultSetView();
  void HideControls();
  void ShowControls();
  wxString & GetSqlErrorMsg()
  {
    return SqlErrorMsg;
  }
  bool IsPrimaryKey(int column);
  bool IsBlobColumn(int column);
  void EditTable(wxString & sql, int *primaryKeys, int *blobCols,
                 wxString & tableName);
  void CreateGrid(int rows, int cols);
  bool ExecuteSql(wxString & sql, int from, bool read_only);
  void ResizeView();
  void DoInsert(bool confirmed);
  void HexBlobValue(unsigned char *blob, int size, wxString & hex);
  void OnSize(wxSizeEvent & event);
  void OnRsFirst(wxCommandEvent & event);
  void OnRsLast(wxCommandEvent & event);
  void OnRsNext(wxCommandEvent & event);
  void OnRsPrevious(wxCommandEvent & event);
  void OnRefresh(wxCommandEvent & event);
  void OnCellSelected(wxGridEvent & event);
  void OnRightClick(wxGridEvent & event);
  void OnCellChanged(wxGridEvent & event);
  void OnCmdDelete(wxCommandEvent & event);
  void OnCmdInsert(wxCommandEvent & event);
  void OnCmdAbort(wxCommandEvent & event);
  void OnCmdClearSelection(wxCommandEvent & event);
  void OnCmdSelectAll(wxCommandEvent & event);
  void OnCmdSelectRow(wxCommandEvent & event);
  void OnCmdSelectColumn(wxCommandEvent & event);
  void OnCmdCopy(wxCommandEvent & event);
  void OnCmdBlob(wxCommandEvent & event);
  void OnCmdBlobIn(wxCommandEvent & event);
  void OnCmdBlobOut(wxCommandEvent & event);
  void OnCmdBlobNull(wxCommandEvent & event);
};

class MySqlControl:public wxTextCtrl
{
//
// the SQL text control
//
private:
  class MyQueryView * Parent;
public:
  MySqlControl(MyQueryView * parent, wxWindowID id, const wxString & value,
               const wxPoint & pos, const wxSize & size, long style);
    virtual ~ MySqlControl()
  {;
  }
  void OnSqlMousePosition(wxMouseEvent & event);
  void OnSqlArrowPosition(wxKeyEvent & event);
};

class SqlTokenizer
{
//
// a class used for tokenizing SQL statements
//
private:
  wxString ** TokenList;
  int Block;
  int Max;
  int Index;
  void Expand();
  void Insert(wxString * token);
  wxString CurrentToken;
public:
    SqlTokenizer(wxString & sql);
   ~SqlTokenizer();
  bool HasMoreTokens();
    wxString & GetNextToken();
};

class MyQueryView:public wxPanel
{
//
// a panel to be used for SQL Queries
//
private:
  class MyFrame * MainFrame;
  MySqlHistory History;
  MySqlControl *SqlCtrl;
  wxBitmapButton *BtnSqlGo;
  wxBitmapButton *BtnHistoryBack;
  wxBitmapButton *BtnHistoryForward;
  int BracketStart;
  int BracketEnd;
  bool IgnoreEvent;
public:
    MyQueryView()
  {;
  }
  MyQueryView(MyFrame * parent, wxWindowID id = wxID_ANY);
  virtual ~ MyQueryView()
  {;
  }
  void HideControls();
  void ShowControls();
  bool IsSqliteExtra(wxString & str);
  bool IsSqlString(wxString & str);
  bool IsSqlNumber(wxString & str);
  bool IsSqlFunction(wxString & str, char next_c);
  bool IsSqlGeoFunction(wxString & str, char next_c);
  bool IsIgnoreEvent()
  {
    return IgnoreEvent;
  }
  void EventBrackets();
  bool CheckBrackets(int pos, bool reverse_direction, int *on, int *off);
  void EvidBrackets(int on, int off);
  void DoSqlSyntaxColor();
  wxTextCtrl *GetSqlCtrl()
  {
    return SqlCtrl;
  }
  void SetSql(wxString & sql, bool execute);
  void SetHistoryStates();
  void OnSize(wxSizeEvent & event);
  void OnSqlGo(wxCommandEvent & event);
  void OnHistoryBack(wxCommandEvent & event);
  void OnHistoryForward(wxCommandEvent & event);
  void OnSqlSyntaxColor(wxCommandEvent & event);
  void AddToHistory(wxString & sql);
};

class MyFrame:public wxFrame
{
//
// the main GUI frame
//
private:
  wxString AutoFDOmsg;
  bool SpatiaLiteMetadata;
  wxAuiManager Manager;         // the GUI manager
  wxString ConfigLayout;        // PERSISTENCY - the layout configuration
  int ConfigPaneX;              // PERSISTENCY - the main pane screen origin X
  int ConfigPaneY;              // PERSISTENCY - the main pane screen origin Y
  int ConfigPaneWidth;          // PERSISTENCY - the main pane screen width
  int ConfigPaneHeight;         // PERSISTENCY - the main pane screen height
  wxString ConfigDbPath;        // PERSISTENCY - the last opend DB path
  wxString ConfigDir;           //PERSISTENCY -  the last used directory
  MyTableTree *TableTree;       // the tables tree list
  MyQueryView *QueryView;       // the QueryResult panel
  MyResultSetView *RsView;      // the QueryResult panel
  bool HelpPane;                // is the HELP pane already opened ?
  sqlite3 *SqliteHandle;        // handle for SQLite DB
  wxString SqlitePath;          // path of SQLite DB
  wxString ExternalSqlitePath;  // path of external SQLite DB [LOAD/SAVE MEMORY database]
  bool MemoryDatabase;          // TRUE if we are currently working on the MEMORY database
  wxString LastDirectory;       // path of directory used  
  int CharsetsLen;              // # charsets defined
  wxString *Charsets;           // table of charsets [code only]
  wxString *CharsetsNames;      // table of charsets [with description]
  wxString LocaleCharset;       // locale charset
  wxString DefaultCharset;      // default charset
  bool AskCharset;              // switch to set default charset for every output
  int TablesLen;                // # tables defined
  wxString *TableNames;         // array of tables
  wxBitmap *BtnCreateNew;       // button icon for DB CREATE&CONNECT
  wxBitmap *BtnConnect;         // button icon for DB CONNECT
  wxBitmap *BtnDisconnect;      // button icon for DB DISCONNECT
  wxBitmap *BtnMemDbLoad;       // button icon for MEMORY DB LOAD
  wxBitmap *BtnMemDbNew;        // button icon for MEMORY DB NEW
  wxBitmap *BtnMemDbClock;      // button icon for MEMORY DB CLOCK
  wxBitmap *BtnMemDbSave;       // button icon for MEMORY DB SAVE
  wxBitmap *BtnVacuum;          // button icon for DB VACUUM
  wxBitmap *BtnSqlScript;       // button icon for Execute SQL SCRIPT
  wxBitmap *BtnCharset;         // button icon for Default CHARSET
  wxBitmap *BtnLoadShp;         // button icon for LOAD SHP
  wxBitmap *BtnLoadTxt;         // button icon for LOAD TXT/CSV
  wxBitmap *BtnVirtualShp;      // button icon for VIRTUAL SHP
  wxBitmap *BtnVirtualTxt;      // button icon for VIRTUAL TXT/CSV
  wxBitmap *BtnNetwork;         // button icon for BUILD NETWORK
  wxBitmap *BtnExif;            // button icon for EXIF LOAD
  wxBitmap *BtnSrids;           // button icon for SEARCH SRIDs
  wxBitmap *BtnHelp;            // button icon for HELP
  wxBitmap *BtnAbout;           // button icon for ABOUT
  wxBitmap *BtnExit;            // button icon for EXIT
// AutoSave timer
  int AutoSaveInterval;
  int LastTotalChanges;
  wxTimer *TimerAutoSave;
public:
    MyFrame(const wxString & title, const wxPoint & pos, const wxSize & size,
            wxString & path);
    virtual ~ MyFrame();

  void UpdateStatusBar();
  bool IsConnected()
  {
    if (SqliteHandle)
      return true;
    else
      return false;
  }
  static void CleanSql(char *str);
  void CleanTxtTab(char *str);
  void CleanCsv(char *str);
  void CleanHtml(char *str);
  wxString & GetExternalSqlitePath()
  {
    return ExternalSqlitePath;
  }
  void SetExternalSqlitePath(wxString & path)
  {
    ExternalSqlitePath = path;
  }
  sqlite3 *GetSqlite()
  {
    return SqliteHandle;
  }
  void CloseHelpPane()
  {
    HelpPane = false;
  }
  void OpenHelpPane()
  {
    HelpPane = true;
  }

  bool OpenDB();
  bool CreateDB();
  void CloseDB();
  bool CreateSpatialMetaData();
  void AutoFDOStart();
  void AutoFDOStop();
  void InitTableTree();
  void ClearTableTree();
  void GetTableColumns(wxString & tableName, MyTableInfo * list);
  void GetTableIndices(wxString & tableName, MyTableInfo * list);
  void GetTableTriggers(wxString & tableName, MyTableInfo * list);
  void GetViewColumns(wxString & viewName, MyViewInfo * list);
  void EditTable(wxString & sql, int *primaryKeys, int *blobCols,
                 wxString & table)
  {
    RsView->EditTable(sql, primaryKeys, blobCols, table);
  }
  void SetSql(wxString & sql, bool execute)
  {
    QueryView->SetSql(sql, execute);
  }
  bool ExecuteSql(const char *sql, int rowNo);
  void Rollback();
  bool TableAlreadyExists(wxString & name);
  bool SridNotExists(int srid);
  bool CheckMetadata();
  void CleanSqlString(char *sql);
  void SaveConfig();
  void LoadConfig();
  wxString *GetCharsets()
  {
    return Charsets;
  }
  wxString *GetCharsetsNames()
  {
    return CharsetsNames;
  }
  int GetCharsetsLen()
  {
    return CharsetsLen;
  }
  gaiaDbfFieldPtr GetDbfField(gaiaDbfListPtr list, char *name);
  void LoadShapefile(wxString & path, wxString & table, int srid,
                     wxString & column, wxString & charset);
  void DumpShapefile(wxString & path, wxString & table, wxString & column,
                     wxString & charset);
  void LoadText(wxString & path, wxString & table, wxString & charset,
                bool first_titles, char decimal_separator, char separator,
                char text_separator);
  void DumpTxtTab(wxString & path, wxString & table, wxString & charset);
  void DumpCsv(wxString & path, wxString & table, wxString & charset);
  void DumpHtml(wxString & path, wxString & table, wxString & charset);
  void GetHelp(wxString & html);
  wxString *GetColumnNames(wxString & table, int *columns);
  void SetLastDirectory(wxString & path)
  {
    LastDirectory = path;
  }
  wxString & GetLastDirectory()
  {
    return LastDirectory;
  }
  wxString & GetLocaleCharset()
  {
    return LocaleCharset;
  }
  wxString & GetDefaultCharset()
  {
    return DefaultCharset;
  }
  wxString & GetCharsetName(wxString & charset);
  int GetCharsetIndex(wxString & charset);
  bool IsSetAskCharset()
  {
    return AskCharset;
  }
  char *ReadSqlLine(FILE * fl, int *len, int *eof);
  MyQueryView *GetQueryView()
  {
    return QueryView;
  }
  MyResultSetView *GetRsView()
  {
    return RsView;
  }
  wxString *GetTables(int *cnt);
  void BuildNetwork(wxString & table, wxString & from, wxString & to,
                    wxString & geometry, bool cost_length, wxString & cost,
                    bool bidirectional, bool one_way,
                    wxString & one_way_from_to, wxString & one_way_to_from);
  bool CreateNetwork(class Network * net, wxString & table, wxString & from,
                     wxString & to, wxString & geometry);
  void ImportExifPhotos(wxString & path, bool folder, bool metadata,
                        bool gps_only);
  void OutputNetNode(unsigned char *auxbuf, int *size, int ind, bool node_code,
                     int max_node_length, class NetNode * pN, int endian_arch);
  bool CheckExifTables();
  int ExifLoadDir(wxString & path, bool gps_only, bool metadata);
  int ExifLoadFile(wxString & path, bool gps_only, bool metadata);
  bool UpdateExifTables(unsigned char *blob, int sz,
                        gaiaExifTagListPtr tag_list, bool metadata,
                        wxString & path);
  bool IsExifGps(gaiaExifTagListPtr tag_list);
  void GetMake(gaiaExifTagListPtr tag_list, wxString & str, bool * ok);
  void GetModel(gaiaExifTagListPtr tag_list, wxString & str, bool * ok);
  void GetGpsTimestamp(gaiaExifTagListPtr tag_list, wxString & str, bool * ok);
  void GetDate(gaiaExifTagListPtr tag_list, wxString & str, bool * ok);
  double GetGpsDirection(gaiaExifTagListPtr tag_list, bool * ok);
  void GetGpsSatellites(gaiaExifTagListPtr tag_list, wxString & str, bool * ok);
  void GetGpsCoords(gaiaExifTagListPtr tag_list, double *longitude,
                    double *latitude, bool * ok);
  sqlite3_int64 GetPixelX(gaiaExifTagListPtr tag_list, bool * ok);
  sqlite3_int64 GetPixelY(gaiaExifTagListPtr tag_list, bool * ok);

  bool MemoryDbSave();
  void LastDitchMemoryDbSave();

  void OnQuit(wxCommandEvent & event);
  void OnAbout(wxCommandEvent & event);
  void OnConnect(wxCommandEvent & event);
  void OnCreateNew(wxCommandEvent & event);
  void OnDisconnect(wxCommandEvent & event);
  void OnMemoryDbLoad(wxCommandEvent & event);
  void OnMemoryDbNew(wxCommandEvent & event);
  void OnMemoryDbClock(wxCommandEvent & event);
  void OnMemoryDbSave(wxCommandEvent & event);
  void OnVacuum(wxCommandEvent & event);
  void OnSqlScript(wxCommandEvent & event);
  void OnCharset(wxCommandEvent & event);
  void OnLoadShp(wxCommandEvent & event);
  void OnLoadTxt(wxCommandEvent & event);
  void OnVirtualShp(wxCommandEvent & event);
  void OnVirtualTxt(wxCommandEvent & event);
  void OnNetwork(wxCommandEvent & event);
  void OnImportExifPhotos(wxCommandEvent & event);
  void OnSrids(wxCommandEvent & event);
  void OnHelp(wxCommandEvent & event);
  void OnMouseMove(wxMouseEvent & event);
  void OnTimerAutoSave(wxTimerEvent & event);
};

class HelpDialog:public wxDialog
{
//
// the help dialog
//
private:
  MyFrame * MainFrame;
public:
  HelpDialog()
  {
    MainFrame = NULL;
  }
  HelpDialog(MyFrame * parent)
  {
    Create(parent);
  }
  bool Create(MyFrame * parent);
  virtual ~ HelpDialog()
  {;
  }
  void CreateControls();
  void OnClose(wxCloseEvent & event);
  void OnSize(wxSizeEvent & event);
};

class SearchSridDialog:public wxDialog
{
//
// a dialog preparing a Search SRID by name
//
private:
  MyFrame * MainFrame;
  wxString String;              // required search string
public:
    SearchSridDialog()
  {;
  }
  SearchSridDialog(MyFrame * parent);
  bool Create(MyFrame * parent);
  virtual ~ SearchSridDialog()
  {;
  }
  void CreateControls();
  wxString & GetString()
  {
    return String;
  }
  void OnOk(wxCommandEvent & event);
};

class SetSridDialog:public wxDialog
{
//
// a dialog preparing a SET SRID
//
private:
  MyFrame * MainFrame;
  wxString Table;               // the table's name 
  wxString Column;              // the column's name to be recovered
  int OldSrid;                  // SRID to substitute
  int Srid;                     // required SRID
public:
    SetSridDialog()
  {;
  }
  SetSridDialog(MyFrame * parent, wxString & table, wxString & column);
  bool Create(MyFrame * parent, wxString & table, wxString & column);
  virtual ~ SetSridDialog()
  {;
  }
  void CreateControls();
  int GetOldSrid()
  {
    return OldSrid;
  }
  int GetSrid()
  {
    return Srid;
  }
  void OnOk(wxCommandEvent & event);
};

class RecoverDialog:public wxDialog
{
//
// a dialog preparing a RECOVER GEOMETRY
//
private:
  MyFrame * MainFrame;
  wxString Table;               // the table's name 
  wxString Column;              // the column's name to be recovered
  int Srid;                     // required SRID
  wxString Type;                // required Geometry Type
public:
    RecoverDialog()
  {;
  }
  RecoverDialog(MyFrame * parent, wxString & table, wxString & column);
  bool Create(MyFrame * parent, wxString & table, wxString & column);
  virtual ~ RecoverDialog()
  {;
  }
  void CreateControls();
  wxString & GetType()
  {
    return Type;
  }
  int GetSrid()
  {
    return Srid;
  }
  void OnOk(wxCommandEvent & event);
};

class VirtualShpDialog:public wxDialog
{
//
// a dialog preparing a CREATE VIRTUAL SHAPE
//
private:
  MyFrame * MainFrame;
  wxString Path;                // the SHP base path
  wxString Table;               // the table name
  wxString Default;             // the default charset
  wxString Charset;             // the SHP charset
  int Srid;                     // the SRID
public:
    VirtualShpDialog()
  {;
  }
  VirtualShpDialog(MyFrame * parent, wxString & path, wxString & table,
                   wxString & defCs);
  bool Create(MyFrame * parent, wxString & path, wxString & table,
              wxString & defCs);
  virtual ~ VirtualShpDialog()
  {;
  }
  void CreateControls();
  wxString & GetTable()
  {
    return Table;
  }
  wxString & GetCharset()
  {
    return Charset;
  }
  int GetSrid()
  {
    return Srid;
  }
  void OnOk(wxCommandEvent & event);
};

class VirtualTxtDialog:public wxDialog
{
//
// a dialog preparing a CREATE VIRTUAL TEXT
//
private:
  MyFrame * MainFrame;
  wxString Path;                // the CSV/TXT base path
  wxString Table;               // the table name
  wxString Default;             // the default charset
  wxString Charset;             // the CSV/TXT charset
  bool FirstLineTitles;         // TRUE if first line stores column titles
  char Separator;               // the character to be used as field separator
  char TextSeparator;           // the character to be used as text separator
  bool DecimalPointIsComma;     // TRUE if decimal separator is COMMA
public:
    VirtualTxtDialog()
  {;
  }
  VirtualTxtDialog(MyFrame * parent, wxString & path, wxString & table,
                   wxString & defCs);
  bool Create(MyFrame * parent, wxString & path, wxString & table,
              wxString & defCs);
  virtual ~ VirtualTxtDialog()
  {;
  }
  void CreateControls();
  wxString & GetTable()
  {
    return Table;
  }
  wxString & GetCharset()
  {
    return Charset;
  }
  bool IsFirstLineTitles()
  {
    return FirstLineTitles;
  }
  char GetSeparator()
  {
    return Separator;
  }
  char GetTextSeparator()
  {
    return TextSeparator;
  }
  bool IsDecimalPointComma()
  {
    return DecimalPointIsComma;
  }
  void OnSeparator(wxCommandEvent & event);
  void OnDecimalSeparator(wxCommandEvent & event);
  void OnQuote(wxCommandEvent & event);
  void OnOk(wxCommandEvent & event);
};

class LoadShpDialog:public wxDialog
{
//
// a dialog preparing a LOAD SHAPE
//
private:
  MyFrame * MainFrame;
  wxString Path;                // the SHP base path
  wxString Table;               // the table's name to be created
  wxString Column;              // the column's name for Geometry
  wxString Default;             // the default charset
  wxString Charset;             // the SHP charset
  int Srid;                     // the SRID
public:
    LoadShpDialog()
  {;
  }
  LoadShpDialog(MyFrame * parent, wxString & path, wxString & table, int srid,
                wxString & column, wxString & defCs);
  bool Create(MyFrame * parent, wxString & path, wxString & table, int srid,
              wxString & column, wxString & defCs);
  virtual ~ LoadShpDialog()
  {;
  }
  void CreateControls();
  wxString & GetTable()
  {
    return Table;
  }
  wxString & GetColumn()
  {
    return Column;
  }
  wxString & GetCharset()
  {
    return Charset;
  }
  int GetSrid()
  {
    return Srid;
  }
  void OnOk(wxCommandEvent & event);
};

class DumpShpDialog:public wxDialog
{
//
// a dialog preparing a DUMP SHAPE
//
private:
  MyFrame * MainFrame;
  wxString Path;                // the SHP base path
  wxString Table;               // the table's name to be created
  wxString Column;              // the column's name for Geometry
  wxString Default;             // the default charset
  wxString Charset;             // the SHP charset
public:
    DumpShpDialog()
  {;
  }
  DumpShpDialog(MyFrame * parent, wxString & path, wxString & table,
                wxString & column, wxString & defCs);
  bool Create(MyFrame * parent, wxString & path, wxString & table,
              wxString & column, wxString & defCs);
  virtual ~ DumpShpDialog()
  {;
  }
  void CreateControls();
  wxString & GetCharset()
  {
    return Charset;
  }
  void OnOk(wxCommandEvent & event);
};

class LoadTxtDialog:public wxDialog
{
//
// a dialog preparing a LOAD TXT/CSV
//
private:
  MyFrame * MainFrame;
  wxString Path;                // the CSV/TXT base path
  wxString Table;               // the table name
  wxString Default;             // the default charset
  wxString Charset;             // the CSV/TXT charset
  bool FirstLineTitles;         // TRUE if first line stores column titles
  char Separator;               // the character to be used as field separator
  char TextSeparator;           // the character to be used as text separator
  bool DecimalPointIsComma;     // TRUE if decimal separator is COMMA
public:
    LoadTxtDialog()
  {;
  }
  LoadTxtDialog(MyFrame * parent, wxString & path, wxString & table,
                wxString & defCs);
  bool Create(MyFrame * parent, wxString & path, wxString & table,
              wxString & defCs);
  virtual ~ LoadTxtDialog()
  {;
  }
  void CreateControls();
  wxString & GetTable()
  {
    return Table;
  }
  wxString & GetCharset()
  {
    return Charset;
  }
  bool IsFirstLineTitles()
  {
    return FirstLineTitles;
  }
  char GetSeparator()
  {
    return Separator;
  }
  char GetTextSeparator()
  {
    return TextSeparator;
  }
  bool IsDecimalPointComma()
  {
    return DecimalPointIsComma;
  }
  void OnSeparator(wxCommandEvent & event);
  void OnDecimalSeparator(wxCommandEvent & event);
  void OnQuote(wxCommandEvent & event);
  void OnOk(wxCommandEvent & event);
};

class DumpTxtDialog:public wxDialog
{
//
// a dialog preparing a DUMP generic text
//
private:
  MyFrame * MainFrame;
  wxString Path;                // the SHP base path
  wxString Default;             // the default charset
  wxString Charset;             // the target charset
public:
    DumpTxtDialog()
  {;
  }
  DumpTxtDialog(MyFrame * parent, wxString & path, wxString & target,
                wxString & defCs);
  bool Create(MyFrame * parent, wxString & path, wxString & target,
              wxString & defCs);
  virtual ~ DumpTxtDialog()
  {;
  }
  void CreateControls();
  wxString & GetCharset()
  {
    return Charset;
  }
  void OnOk(wxCommandEvent & event);
};

class NetworkDialog:public wxDialog
{
//
// a dialog preparing a BUILD NETWORK
//
private:
  MyFrame * MainFrame;
  wxString TableName;           // the table name
  wxString FromColumn;          // the NodeFrom column name
  wxString ToColumn;            // the NodeTo column name
  wxString GeomColumn;          // the Geometry column name
  bool GeomLength;              // Cost is Geometry Length
  wxString CostColumn;          // the Cost column name
  bool Bidirectional;           // Bidirectional arcs
  bool OneWays;                 // OneWays columns supported
  wxString OneWayToFrom;        // the OneWay To-From column
  wxString OneWayFromTo;        // the OneWay From-To column
public:
    NetworkDialog()
  {;
  }
  NetworkDialog(MyFrame * parent);
  bool Create(MyFrame * parent);
  virtual ~ NetworkDialog()
  {;
  }
  void CreateControls();
  wxString & GetTableName()
  {
    return TableName;
  }
  wxString & GetFromColumn()
  {
    return FromColumn;
  }
  wxString & GetToColumn()
  {
    return ToColumn;
  }
  wxString & GetGeomColumn()
  {
    return GeomColumn;
  }
  bool IsGeomLength()
  {
    return GeomLength;
  }
  wxString & GetCostColumn()
  {
    return CostColumn;
  }
  bool IsBidirectional()
  {
    return Bidirectional;
  }
  bool IsOneWays()
  {
    return OneWays;
  }
  wxString & GetOneWayFromTo()
  {
    return OneWayFromTo;
  }
  wxString & GetOneWayToFrom()
  {
    return OneWayToFrom;
  }
  void OnTable(wxCommandEvent & event);
  void OnDirection(wxCommandEvent & event);
  void OnCost(wxCommandEvent & event);
  void OnOneWay(wxCommandEvent & event);
  void OnOk(wxCommandEvent & event);
};

class ExifDialog:public wxDialog
{
//
// a dialog preparing an IMPORT EXIF PHOTOS
//
private:
  MyFrame * MainFrame;
  wxString ImgPath;             // the file name
  wxString DirPath;             // the folder path
  bool Folder;                  // import a whole folder
  bool Metadata;                // feed Metadata tables
  bool GpsOnly;                 // import only if GpsExif present
public:
    ExifDialog()
  {;
  }
  ExifDialog(MyFrame * parent, wxString & dir_path, wxString & img_path);
  bool Create(MyFrame * parent, wxString & dir_path, wxString & img_path);
  virtual ~ ExifDialog()
  {;
  }
  void CreateControls();
  wxString & GetImgPath()
  {
    return ImgPath;
  }
  wxString & GetDirPath()
  {
    return DirPath;
  }
  bool IsFolder()
  {
    return Folder;
  }
  bool IsMetadata()
  {
    return Metadata;
  }
  bool IsGpsOnly()
  {
    return GpsOnly;
  }
  void OnFolder(wxCommandEvent & event);
  void OnMetadata(wxCommandEvent & event);
  void OnGpsOnly(wxCommandEvent & event);
  void OnOk(wxCommandEvent & event);
};

class SqlScriptDialog:public wxDialog
{
//
// a dialog preparing an SQL SCRIPT execute
//
private:
  MyFrame * MainFrame;
  wxString Path;                // the SHP base path
  wxString Default;             // the default charset
  wxString Charset;             // the target charset
public:
    SqlScriptDialog()
  {;
  }
  SqlScriptDialog(MyFrame * parent, wxString & path, wxString & defCs);
  bool Create(MyFrame * parent, wxString & path, wxString & defCs);
  virtual ~ SqlScriptDialog()
  {;
  }
  void CreateControls();
  wxString & GetCharset()
  {
    return Charset;
  }
  void OnOk(wxCommandEvent & event);
};

class DefaultCharsetDialog:public wxDialog
{
//
// a dialog for selecting DEFAULT CHARSET
//
private:
  MyFrame * MainFrame;
  wxString Charset;             // the default charset
  bool AskCharset;              // true / false
public:
    DefaultCharsetDialog()
  {;
  }
  DefaultCharsetDialog(MyFrame * parent, wxString & charset, bool ask);
  bool Create(MyFrame * parent, wxString & charset, bool ask);
  virtual ~ DefaultCharsetDialog()
  {;
  }
  void CreateControls();
  wxString & GetCharset()
  {
    return Charset;
  }
  bool IsSetAskCharset()
  {
    return AskCharset;
  }
  void OnOk(wxCommandEvent & event);
};

class BlobExplorerDialog:public wxPropertySheetDialog
{
//
// a dialog to explore a BLOB value
//
private:
  MyFrame * MainFrame;
  int BlobSize;                 // the BLOB size
  unsigned char *Blob;          // the BLOB value
  int BlobType;                 // the BLOB type
  gaiaGeomCollPtr Geometry;     // the geometry [optional]
  wxImage *Image;               // the image [optional]
  wxBitmap GeomPreview;         // the geometry preview
public:
    BlobExplorerDialog()
  {;
  }
  BlobExplorerDialog(MyFrame * parent, int blob_size, unsigned char *blob);
  bool Create(MyFrame * parent, int blob_size, unsigned char *blob);
  virtual ~ BlobExplorerDialog()
  {
    if (Geometry)
      gaiaFreeGeomColl(Geometry);
    if (Image)
      delete Image;
  }
  void DrawGeometry(int horz, int vert);
  wxPanel *CreateHexadecimalPage(wxWindow * book);
  wxPanel *CreateGeometryPage(wxWindow * book);
  wxPanel *CreateImagePage(wxWindow * book);
  void UpdateHexadecimalPage();
  void UpdateGeometryPage();
  void UpdateImagePage();
  gaiaGeomCollPtr GetGeometry()
  {
    return Geometry;
  }
  wxImage *GetImage()
  {
    return Image;
  }
  int GetBlobType()
  {
    return BlobType;
  }
  void OnOk(wxCommandEvent & event);
  void OnPageChanged(wxNotebookEvent & event);
};

class GraphicsGeometry:public wxStaticBitmap
{
//
// a window to show some Geometry in a graphical fashion
//
private:
  BlobExplorerDialog * Parent;
public:
  GraphicsGeometry(BlobExplorerDialog * parent, wxWindow * panel, wxWindowID id,
                   const wxBitmap & bmp, wxSize const &size);
    virtual ~ GraphicsGeometry()
  {;
  }
};

class ImageShow:public wxStaticBitmap
{
//
// a window to show some Image [Jpeg-Png-Gif]
//
private:
  BlobExplorerDialog * Parent;
public:
  ImageShow(BlobExplorerDialog * parent, wxWindow * panel, wxWindowID id,
            const wxBitmap & bmp, const wxSize & size);
    virtual ~ ImageShow()
  {;
  }
  void OnRightClick(wxMouseEvent & event);
  void OnCmdCopy(wxCommandEvent & event);
};

class MyHexList:public wxListCtrl
{
//
// a class for Hexdecimal dumps
//
private:
  BlobExplorerDialog * Parent;
  int BlobSize;                 // the BLOB size
  unsigned char *Blob;          // the BLOB value
public:
    MyHexList(BlobExplorerDialog * parent, unsigned char *blob,
              int blob_size, wxWindow * panel, wxWindowID id,
              const wxPoint & pos = wxDefaultPosition, const wxSize & size =
              wxDefaultSize, long style = 0);
    virtual ~ MyHexList();
  virtual wxString OnGetItemText(long item, long column) const;
};

class NetNodePre
{
//
// a class to store a temporary node for Network
//
private:
  int Id;
  wxString Code;
  NetNodePre *Next;
public:
    NetNodePre(int id);
    NetNodePre(const char *code);
   ~NetNodePre()
  {;
  }
  int GetId()
  {
    return Id;
  }
  wxString & GetCode()
  {
    return Code;
  }
  void SetNext(NetNodePre * next)
  {
    Next = next;
  }
  NetNodePre *GetNext()
  {
    return Next;
  }
};

class NetNode
{
//
// a class to store a final node for Network
//
private:
  int InternalIndex;
  int Id;
  wxString Code;
  double X;
  double Y;
  class NetArcRef *First;
  class NetArcRef *Last;
  NetNode *Next;
public:
    NetNode(int id);
    NetNode(wxString & code);
   ~NetNode();
  int GetInternalIndex()
  {
    return InternalIndex;
  }
  void SetInternalIndex(int idx)
  {
    InternalIndex = idx;
  }
  int GetId()
  {
    return Id;
  }
  wxString & GetCode()
  {
    return Code;
  }
  double GetX()
  {
    return X;
  }
  void SetX(double x)
  {
    X = x;
  }
  double GetY()
  {
    return Y;
  }
  void SetY(double y)
  {
    Y = y;
  }
  void AddOutcoming(class NetArc * pA);
  NetArcRef *GetFirst()
  {
    return First;
  }
  NetArc **PrepareOutcomings(int *count);
  void SetNext(NetNode * next)
  {
    Next = next;
  }
  NetNode *GetNext()
  {
    return Next;
  }
};

class NetArc
{
//
// a class to store an arc for Network
//
private:
  int RowId;
  NetNode *From;
  NetNode *To;
  double Cost;
  NetArc *Next;
public:
    NetArc(int rowid, NetNode * from, NetNode * to, double cost);
   ~NetArc()
  {;
  }
  int GetRowId()
  {
    return RowId;
  }
  NetNode *GetFrom()
  {
    return From;
  }
  NetNode *GetTo()
  {
    return To;
  }
  double GetCost()
  {
    return Cost;
  }
  void SetNext(NetArc * next)
  {
    Next = next;
  }
  NetArc *GetNext()
  {
    return Next;
  }
};

class NetArcRef
{
//
// a class to store a reference to an arc for Network
//
private:
  NetArc * Reference;
  NetArcRef *Next;
public:
    NetArcRef(NetArc * arc)
  {
    Reference = arc;
    Next = NULL;
  }
   ~NetArcRef()
  {;
  }
  NetArc *GetReference()
  {
    return Reference;
  }
  void SetNext(NetArcRef * next)
  {
    Next = next;
  }
  NetArcRef *GetNext()
  {
    return Next;
  }
};

class Network
{
//
// a class representing a Network
//
private:
  NetNodePre * FirstPre;
  NetNodePre *LastPre;
  int NumPreNodes;
  NetNodePre **SortedPreNodes;
  NetArc *FirstArc;
  NetArc *LastArc;
  NetNode *FirstNode;
  NetNode *LastNode;
  int NumNodes;
  NetNode **SortedNodes;
  bool Error;
  bool NodeCode;
  int MaxCodeLength;
public:
    Network();
   ~Network();
  void CleanPreNodes();
  void InsertNode(int id);
  void InsertNode(const char *code);
  void AddNode(int id);
  void AddNode(wxString & code);
  NetNode *ProcessNode(int id, double x, double y, NetNode ** pOther);
  NetNode *ProcessNode(wxString & code, double x, double y, NetNode ** pOther);
  void Sort();
  NetNode *Find(int id);
  NetNode *Find(wxString & code);
  NetNode *GetSortedNode(int x);
  void AddArc(int rowid, int id_from, int id_to, double node_from_x,
              double node_from_y, double node_to_x, double node_to_y,
              double cost);
  void AddArc(int rowid, const char *code_from, const char *code_to,
              double node_from_x, double node_from_y, double node_to_x,
              double node_to_y, double cost);
  void InitNodes();
  void SetError()
  {
    Error = true;
  }
  bool IsError()
  {
    return Error;
  }
  void SetNodeCode(bool mode)
  {
    NodeCode = mode;
  }
  bool IsNodeCode()
  {
    return NodeCode;
  }
  int GetNumNodes()
  {
    return NumNodes;
  }
  int GetMaxCodeLength()
  {
    return MaxCodeLength;
  }
};

class AutoFDOTable
{
private:
  char *Name;
  AutoFDOTable *Next;
public:
    AutoFDOTable(const char *name, const int len)
  {
    Name = new char[len];
      strcpy(Name, name);
      Next = NULL;
  }
   ~AutoFDOTable()
  {
    if (Name)
      delete[]Name;
  }
  char *GetName()
  {
    return Name;
  }
  void SetNext(AutoFDOTable * next)
  {
    Next = next;
  }
  AutoFDOTable *GetNext()
  {
    return Next;
  }
};

class AutoFDOTables
{
private:
  AutoFDOTable * First;
  AutoFDOTable *Last;
public:
    AutoFDOTables()
  {
    First = NULL;
    Last = NULL;
  }
   ~AutoFDOTables();
  void Add(const char *name, const int len);
  AutoFDOTable *GetFirst()
  {
    return First;
  }
};

class AutoSaveDialog:public wxDialog
{
//
// a dialog to manage AutoSave
//
private:
  MyFrame * MainFrame;
  wxString Path;                // the path to save
  int Seconds;                  // interval 
  wxRadioBox *IntervalCtrl;
  wxTextCtrl *PathCtrl;
public:
    AutoSaveDialog()
  {;
  }
  AutoSaveDialog(MyFrame * parent, wxString & path, int secs);
  bool Create(MyFrame * parent, wxString & path, int secs);
  virtual ~ AutoSaveDialog()
  {;
  }
  void CreateControls();
  int GetSeconds()
  {
    return Seconds;
  }
  void OnOk(wxCommandEvent & event);
  wxString & GetPath()
  {
    return Path;
  }
  void OnIntervalChanged(wxCommandEvent & event);
  void OnChangePath(wxCommandEvent & event);
};

Changes to Dialogs.cpp.

1
2
3
4
5
6
7
8
9
10
11
12
..
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521

522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656

657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100






































































































































































































































































































































































































































































1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115

1116
1117
1118
1119
1120
1121

1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229

1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246

1247
1248
1249
1250
1251
1252

1253
1254

1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310

1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750































































































































































































































































































































































/*
/ Dialogs.cpp
/ various dialog classes
/
/ version 1.1, 2008 September 13
/
/ Author: Sandro Furieri a-furieri@lqt.it
/
/ Copyright (C) 2008  Alessandro Furieri
/
/    This program is free software: you can redistribute it and/or modify
/    it under the terms of the GNU General Public License as published by
................................................................................

#include "Classdef.h"

#include "wx/spinctrl.h"
#include "wx/listctrl.h"
#include "wx/html/htmlwin.h"

bool
VirtualShpDialog::Create (MyFrame * parent, wxString & path, wxString & table,
			  wxString & defCs)
{
//
// creating the dialog
//
    MainFrame = parent;
    Path = path;
    Table = table;
    Default = defCs;
    if (wxDialog::Create (parent, wxID_ANY, wxT ("Creating Virtual Shapefile"))
	== false)
	return false;
// populates individual controls
    CreateControls ();
// sets dialog sizer
    GetSizer ()->Fit (this);
    GetSizer ()->SetSizeHints (this);
// centers the dialog window
    Centre ();
    return true;
}

void
VirtualShpDialog::CreateControls ()
{
//
// creating individual control and setting initial values
//
    wxBoxSizer *topSizer = new wxBoxSizer (wxVERTICAL);
    this->SetSizer (topSizer);
    wxBoxSizer *boxSizer = new wxBoxSizer (wxVERTICAL);
    topSizer->Add (boxSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
// first row: the Shapefile path
    wxBoxSizer *pathSizer = new wxBoxSizer (wxHORIZONTAL);
    boxSizer->Add (pathSizer, 0, wxALIGN_RIGHT | wxALL, 0);
    wxStaticText *pathLabel =
	new wxStaticText (this, wxID_STATIC, wxT ("&Path:"));
    pathSizer->Add (pathLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
    wxTextCtrl *pathValue = new wxTextCtrl (this, wxID_STATIC,
					    Path, wxDefaultPosition,
					    wxSize (350, 22), wxTE_READONLY);
    pathSizer->Add (pathValue, 0, wxALIGN_RIGHT | wxALL, 5);
// second row: TABLE name
    wxBoxSizer *tableSizer = new wxBoxSizer (wxHORIZONTAL);
    boxSizer->Add (tableSizer, 0, wxALIGN_RIGHT | wxALL, 0);
    wxStaticText *tableLabel =
	new wxStaticText (this, wxID_STATIC, wxT ("&Table name:"));
    tableSizer->Add (tableLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
    wxTextCtrl *tableCtrl = new wxTextCtrl (this, ID_VIRTSHP_TABLE, Table,
					    wxDefaultPosition, wxSize (350,
								       22));
    tableSizer->Add (tableCtrl, 0, wxALIGN_RIGHT | wxALL, 5);
// second row: SRID
    wxBoxSizer *sridSizer = new wxBoxSizer (wxHORIZONTAL);
    boxSizer->Add (sridSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 0);
    wxStaticText *sridLabel =
	new wxStaticText (this, wxID_STATIC, wxT ("&SRID:"));
    sridSizer->Add (sridLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
    wxSpinCtrl *sridCtrl = new wxSpinCtrl (this, ID_VIRTSHP_SRID, wxEmptyString,
					   wxDefaultPosition, wxSize (80, 20),
					   wxSP_ARROW_KEYS,
					   -1, 40000, -1);
    sridSizer->Add (sridCtrl, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
// third row: CHARSET
    wxStaticBox *charsetBox = new wxStaticBox (this, wxID_STATIC,
					       wxT ("Charset Encoding"),
					       wxDefaultPosition,
					       wxDefaultSize);
    wxBoxSizer *charsetSizer = new wxStaticBoxSizer (charsetBox, wxHORIZONTAL);
    sridSizer->Add (charsetSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
    wxListBox *charsetCtrl = new wxListBox (this, ID_VIRTSHP_CHARSET,
					    wxDefaultPosition, wxDefaultSize,
					    MainFrame->GetCharsetsLen (),
					    MainFrame->GetCharsetsNames (),
					    wxLB_SINGLE);
    charsetCtrl->SetFont (wxFont
			  (8, wxFONTFAMILY_MODERN, wxFONTSTYLE_NORMAL,
			   wxFONTWEIGHT_NORMAL));
    int idSel = MainFrame->GetCharsetIndex (Default);
    if (idSel != wxNOT_FOUND)
	charsetCtrl->SetSelection (idSel);
    charsetSizer->Add (charsetCtrl, 0, wxALIGN_CENTER_VERTICAL | wxALL, 0);
// OK - CANCEL buttons
    wxBoxSizer *okCancelBox = new wxBoxSizer (wxHORIZONTAL);
    boxSizer->Add (okCancelBox, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 0);
    wxButton *ok = new wxButton (this, wxID_OK, wxT ("&OK"));
    okCancelBox->Add (ok, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
    wxButton *cancel = new wxButton (this, wxID_CANCEL, wxT ("&Cancel"));
    okCancelBox->Add (cancel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
// appends event handler for OK button
    Connect (wxID_OK, wxEVT_COMMAND_BUTTON_CLICKED,
	     (wxObjectEventFunction) & VirtualShpDialog::OnOk);
}

void
VirtualShpDialog::OnOk (wxCommandEvent & event)
{
//
// all done: 
//
    wxTextCtrl *tableCtrl = (wxTextCtrl *) FindWindow (ID_VIRTSHP_TABLE);
    Table = tableCtrl->GetValue ();
    if (Table.Len () < 1)
      {
	  wxMessageBox (wxT ("You must specify the TABLE NAME !!!"),
			wxT ("spatialite-gui"), wxOK | wxICON_WARNING, this);
	  return;
      }
    if (MainFrame->TableAlreadyExists (Table) == true)
      {
	  wxMessageBox (wxT ("a table name '") + Table +
			wxT ("' already exists"), wxT ("spatialite-gui"),
			wxOK | wxICON_WARNING, this);
	  return;
      }
    if (gaiaIllegalSqlName (Table.ToUTF8 ()) == 1
	|| gaiaIsReservedSqlName (Table.ToUTF8 ()) == 1
	|| gaiaIsReservedSqliteName (Table.ToUTF8 ()) == 1)
      {
	  wxMessageBox (wxT ("'") + Table +
			wxT
			("' is an invalid TABLE NAME\n\nillegal name or reserved keyword"),
			wxT ("spatialite-gui"), wxOK | wxICON_WARNING, this);
	  return;
      }
    wxSpinCtrl *sridCtrl = (wxSpinCtrl *) FindWindow (ID_VIRTSHP_SRID);
    Srid = sridCtrl->GetValue ();
    if (Srid == -1)
	;
    else if (MainFrame->SridNotExists (Srid) == true)
      {
	  wxMessageBox (wxT ("invalid SRID value"),
			wxT ("spatialite-gui"), wxOK | wxICON_WARNING, this);
	  return;
      }
    wxListBox *charsetCtrl = (wxListBox *) FindWindow (ID_VIRTSHP_CHARSET);
    int idSel = charsetCtrl->GetSelection ();
    if (idSel == wxNOT_FOUND)
      {
	  wxMessageBox (wxT
			("you must select some Charset Encoding from the list"),
			wxT ("spatialite-gui"), wxOK | wxICON_WARNING, this);
	  return;
      }
    wxString *charsets = MainFrame->GetCharsets ();
    Charset = *(charsets + idSel);
    wxDialog::EndModal (wxID_OK);
}

bool
VirtualTxtDialog::Create (MyFrame * parent, wxString & path, wxString & table,
			  wxString & defCs)
{
//
// creating the dialog
//
    MainFrame = parent;
    Path = path;
    Table = table;
    Default = defCs;
    if (wxDialog::Create (parent, wxID_ANY, wxT ("Creating Virtual CSV/TXT"))
	== false)
	return false;
// populates individual controls
    CreateControls ();
// sets dialog sizer
    GetSizer ()->Fit (this);
    GetSizer ()->SetSizeHints (this);
// centers the dialog window
    Centre ();
    return true;
}

void
VirtualTxtDialog::CreateControls ()
{
//
// creating individual control and setting initial values
//
    FirstLineTitles = true;
    Separator = '\t';
    TextSeparator = '"';
    DecimalPointIsComma = false;
    wxBoxSizer *topSizer = new wxBoxSizer (wxVERTICAL);
    this->SetSizer (topSizer);
    wxBoxSizer *boxSizer = new wxBoxSizer (wxVERTICAL);
    topSizer->Add (boxSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
// first row: the CSV/TXT path
    wxBoxSizer *pathSizer = new wxBoxSizer (wxHORIZONTAL);
    boxSizer->Add (pathSizer, 0, wxALIGN_RIGHT | wxALL, 0);
    wxStaticText *pathLabel =
	new wxStaticText (this, wxID_STATIC, wxT ("&Path:"));
    pathSizer->Add (pathLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
    wxTextCtrl *pathValue = new wxTextCtrl (this, wxID_STATIC,
					    Path, wxDefaultPosition,
					    wxSize (350, 22), wxTE_READONLY);
    pathSizer->Add (pathValue, 0, wxALIGN_RIGHT | wxALL, 5);
// second row: TABLE name
    wxBoxSizer *tableSizer = new wxBoxSizer (wxHORIZONTAL);
    boxSizer->Add (tableSizer, 0, wxALIGN_RIGHT | wxALL, 0);
    wxStaticText *tableLabel =
	new wxStaticText (this, wxID_STATIC, wxT ("&Table name:"));
    tableSizer->Add (tableLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
    wxTextCtrl *tableCtrl = new wxTextCtrl (this, ID_VIRTTXT_TABLE, Table,
					    wxDefaultPosition, wxSize (350,
								       22));
    tableSizer->Add (tableCtrl, 0, wxALIGN_RIGHT | wxALL, 5);
// second row: OPTIONS
    wxBoxSizer *optSizer = new wxBoxSizer (wxHORIZONTAL);
    boxSizer->Add (optSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 0);
    wxBoxSizer *modeSizer = new wxBoxSizer (wxVERTICAL);
    optSizer->Add (modeSizer, 0, wxALIGN_CENTER_VERTICAL | wxALL, 0);
    wxBoxSizer *mode1Sizer = new wxBoxSizer (wxHORIZONTAL);
    modeSizer->Add (mode1Sizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 0);
    wxCheckBox *titleCtrl = new wxCheckBox (this, ID_VIRTTXT_TITLES,
					    wxT
					    ("First line contains column names"),
					    wxDefaultPosition, wxDefaultSize);
    titleCtrl->SetValue (true);
    mode1Sizer->Add (titleCtrl, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
    wxStaticBox *sepBox = new wxStaticBox (this, wxID_STATIC,
					   wxT ("Separators"),
					   wxDefaultPosition, wxDefaultSize);
    wxBoxSizer *sepSizer = new wxStaticBoxSizer (sepBox, wxVERTICAL);
    modeSizer->Add (sepSizer, 0, wxALIGN_LEFT | wxALL, 0);
    wxBoxSizer *mode2Sizer = new wxBoxSizer (wxHORIZONTAL);
    sepSizer->Add (mode2Sizer, 0, wxALIGN_LEFT | wxALL, 0);
    wxString quotes[2];
    quotes[0] = wxT ("&Double \"");
    quotes[1] = wxT ("&Single '");
    wxRadioBox *textSeparatorBox = new wxRadioBox (this, ID_VIRTTXT_QUOTE,
						   wxT
						   ("&Text separator: quotes"),
						   wxDefaultPosition,
						   wxDefaultSize, 2,
						   quotes, 2,
						   wxRA_SPECIFY_COLS);
    mode2Sizer->Add (textSeparatorBox, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
    wxBoxSizer *mode3Sizer = new wxBoxSizer (wxHORIZONTAL);
    sepSizer->Add (mode3Sizer, 0, wxALIGN_LEFT | wxALL, 0);
    wxString separators[6];
    separators[0] = wxT ("&Tab");
    separators[1] = wxT ("&Space");
    separators[2] = wxT ("Co&mma ,");
    separators[3] = wxT ("&Colon :");
    separators[4] = wxT ("S&emicolon ;");
    separators[5] = wxT ("&Other");
    wxRadioBox *separatorBox = new wxRadioBox (this, ID_VIRTTXT_SEPARATOR,
					       wxT ("&Column separator"),
					       wxDefaultPosition, wxDefaultSize,
					       6,
					       separators, 2,
					       wxRA_SPECIFY_COLS);
    mode3Sizer->Add (separatorBox, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
    wxBoxSizer *mode4Sizer = new wxBoxSizer (wxHORIZONTAL);
    sepSizer->Add (mode4Sizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 0);
    wxStaticText *charSeparatorLabel = new wxStaticText (this, wxID_STATIC,
							 wxT
							 ("&Custom separator:"),
							 wxDefaultPosition,
							 wxDefaultSize, 0);
    mode4Sizer->Add (charSeparatorLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
    wxTextCtrl *dummy =
	new wxTextCtrl (this, ID_VIRTTXT_CHARSEPARATOR, wxT ("Dummy Text pq"),
			wxDefaultPosition,
			wxDefaultSize, 0);
    wxSize sz = dummy->GetSize ();
    delete dummy;
    sz.SetWidth (40);
    wxTextCtrl *charSeparatorCtrl =
	new wxTextCtrl (this, ID_VIRTTXT_CHARSEPARATOR, wxT ("TAB"),
			wxDefaultPosition, sz, 0);
    charSeparatorCtrl->SetMaxLength (1);
    charSeparatorCtrl->Enable (false);
    mode4Sizer->Add (charSeparatorCtrl, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
    wxBoxSizer *mode5Sizer = new wxBoxSizer (wxHORIZONTAL);
    sepSizer->Add (mode5Sizer, 0, wxALIGN_LEFT | wxALL, 0);
    wxString points[2];
    points[0] = wxT ("&Point .");
    points[1] = wxT ("&Comma ,");
    wxRadioBox *decimalSeparatorBox = new wxRadioBox (this, ID_VIRTTXT_POINT,
						      wxT
						      ("&Decimal separator"),
						      wxDefaultPosition,
						      wxDefaultSize, 2,
						      points, 2,
						      wxRA_SPECIFY_COLS);
    mode5Sizer->Add (decimalSeparatorBox, 0, wxALIGN_CENTER_VERTICAL | wxALL,
		     5);
// third row: CHARSET
    wxStaticBox *charsetBox = new wxStaticBox (this, wxID_STATIC,
					       wxT ("Charset Encoding"),
					       wxDefaultPosition,
					       wxDefaultSize);
    wxBoxSizer *charsetSizer = new wxStaticBoxSizer (charsetBox, wxHORIZONTAL);
    optSizer->Add (charsetSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
    wxListBox *charsetCtrl = new wxListBox (this, ID_VIRTTXT_CHARSET,
					    wxDefaultPosition, wxDefaultSize,
					    MainFrame->GetCharsetsLen (),
					    MainFrame->GetCharsetsNames (),
					    wxLB_SINGLE);
    charsetCtrl->SetFont (wxFont
			  (8, wxFONTFAMILY_MODERN, wxFONTSTYLE_NORMAL,
			   wxFONTWEIGHT_NORMAL));
    int idSel = MainFrame->GetCharsetIndex (Default);
    if (idSel != wxNOT_FOUND)
	charsetCtrl->SetSelection (idSel);
    charsetSizer->Add (charsetCtrl, 0, wxALIGN_CENTER_VERTICAL | wxALL, 0);
// OK - CANCEL buttons
    wxBoxSizer *okCancelBox = new wxBoxSizer (wxHORIZONTAL);
    boxSizer->Add (okCancelBox, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 0);
    wxButton *ok = new wxButton (this, wxID_OK, wxT ("&OK"));
    okCancelBox->Add (ok, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
    wxButton *cancel = new wxButton (this, wxID_CANCEL, wxT ("&Cancel"));
    okCancelBox->Add (cancel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
// appends event handler for OK button
    Connect (wxID_OK, wxEVT_COMMAND_BUTTON_CLICKED,
	     (wxObjectEventFunction) & VirtualTxtDialog::OnOk);
// appends event handler for radioboxes
    Connect (ID_VIRTTXT_QUOTE, wxEVT_COMMAND_RADIOBOX_SELECTED,
	     (wxObjectEventFunction) & VirtualTxtDialog::OnQuote);
    Connect (ID_VIRTTXT_SEPARATOR, wxEVT_COMMAND_RADIOBOX_SELECTED,
	     (wxObjectEventFunction) & VirtualTxtDialog::OnSeparator);
    Connect (ID_VIRTTXT_POINT, wxEVT_COMMAND_RADIOBOX_SELECTED,
	     (wxObjectEventFunction) & VirtualTxtDialog::OnDecimalSeparator);
}

void
VirtualTxtDialog::OnDecimalSeparator (wxCommandEvent & event)
{
//
// POINT selection changed
//
    wxRadioBox *decimalSeparatorCtrl =
	(wxRadioBox *) FindWindow (ID_VIRTTXT_POINT);
    switch (decimalSeparatorCtrl->GetSelection ())
      {
      case 0:
	  DecimalPointIsComma = false;
	  break;
      case 1:
	  DecimalPointIsComma = true;
	  break;
      };
}

void
VirtualTxtDialog::OnQuote (wxCommandEvent & event)
{
//
// QUOTE selection changed
//
    wxRadioBox *separatorCtrl = (wxRadioBox *) FindWindow (ID_VIRTTXT_QUOTE);
    switch (separatorCtrl->GetSelection ())
      {
      case 0:
	  TextSeparator = '"';
	  break;
      case 1:
	  TextSeparator = '\'';
	  break;
      };
}

void
VirtualTxtDialog::OnSeparator (wxCommandEvent & event)
{
//
// SEPARATOR selection changed
//
    wxTextCtrl *charSeparatorCtrl =
	(wxTextCtrl *) FindWindow (ID_VIRTTXT_CHARSEPARATOR);
    wxRadioBox *separatorCtrl =
	(wxRadioBox *) FindWindow (ID_VIRTTXT_SEPARATOR);
    switch (separatorCtrl->GetSelection ())
      {
      case 0:
	  Separator = '\t';
	  charSeparatorCtrl->SetValue (wxT ("TAB"));
	  break;
      case 1:
	  Separator = ' ';
	  charSeparatorCtrl->SetValue (wxT ("SP"));
	  break;
      case 2:
	  Separator = ',';
	  charSeparatorCtrl->SetValue (wxT (","));
	  break;
      case 3:
	  Separator = ':';
	  charSeparatorCtrl->SetValue (wxT (":"));
	  break;
      case 4:
	  Separator = ';';
	  charSeparatorCtrl->SetValue (wxT (";"));
	  break;
      case 5:
	  Separator = '|';
	  charSeparatorCtrl->SetValue (wxT ("|"));
	  break;
      };
    if (separatorCtrl->GetSelection () == 5)
	charSeparatorCtrl->Enable (true);
    else
	charSeparatorCtrl->Enable (false);
}

void
VirtualTxtDialog::OnOk (wxCommandEvent & event)
{
//
// all done: 
//
    wxTextCtrl *tableCtrl = (wxTextCtrl *) FindWindow (ID_VIRTTXT_TABLE);
    Table = tableCtrl->GetValue ();
    if (Table.Len () < 1)
      {
	  wxMessageBox (wxT ("You must specify the TABLE NAME !!!"),
			wxT ("spatialite-gui"), wxOK | wxICON_WARNING, this);
	  return;
      }
    if (MainFrame->TableAlreadyExists (Table) == true)
      {
	  wxMessageBox (wxT ("a table name '") + Table +
			wxT ("' already exists"), wxT ("spatialite-gui"),
			wxOK | wxICON_WARNING, this);
	  return;
      }
    if (gaiaIllegalSqlName (Table.ToUTF8 ()) == 1
	|| gaiaIsReservedSqlName (Table.ToUTF8 ()) == 1
	|| gaiaIsReservedSqliteName (Table.ToUTF8 ()) == 1)
      {
	  wxMessageBox (wxT ("'") + Table +
			wxT
			("' is an invalid TABLE NAME\n\nillegal name or reserved keyword"),
			wxT ("spatialite-gui"), wxOK | wxICON_WARNING, this);
	  return;
      }
    wxListBox *charsetCtrl = (wxListBox *) FindWindow (ID_VIRTTXT_CHARSET);
    int idSel = charsetCtrl->GetSelection ();
    if (idSel == wxNOT_FOUND)
      {
	  wxMessageBox (wxT
			("you must select some Charset Encoding from the list"),
			wxT ("spatialite-gui"), wxOK | wxICON_WARNING, this);
	  return;
      }
    wxString *charsets = MainFrame->GetCharsets ();
    Charset = *(charsets + idSel);
    wxRadioBox *separatorCtrl =
	(wxRadioBox *) FindWindow (ID_VIRTTXT_SEPARATOR);
    if (separatorCtrl->GetSelection () == 5)
      {
	  wxTextCtrl *charSeparatorCtrl =
	      (wxTextCtrl *) FindWindow (ID_VIRTTXT_CHARSEPARATOR);
	  wxString separator = charSeparatorCtrl->GetValue ();
	  if (separator.Len () != 1)
	    {
		wxMessageBox (wxT
			      ("you must specificy a single char as Custom Column Separator"),
			      wxT ("spatialite-gui"), wxOK | wxICON_WARNING,
			      this);
		return;
	    }
	  char dummy[64];
	  strcpy (dummy, separator.ToUTF8 ());
	  Separator = *dummy;
      }
    wxDialog::EndModal (wxID_OK);
}

bool
LoadTxtDialog::Create (MyFrame * parent, wxString & path, wxString & table,
		       wxString & defCs)
{
//
// creating the dialog
//
    MainFrame = parent;
    Path = path;
    Table = table;
    Default = defCs;
    if (wxDialog::Create (parent, wxID_ANY, wxT ("Load CSV/TXT")) == false)
	return false;
// populates individual controls
    CreateControls ();
// sets dialog sizer
    GetSizer ()->Fit (this);

    GetSizer ()->SetSizeHints (this);
// centers the dialog window
    Centre ();
    return true;
}

void
LoadTxtDialog::CreateControls ()
{
//
// creating individual control and setting initial values
//
    FirstLineTitles = true;
    Separator = '\t';
    TextSeparator = '"';
    DecimalPointIsComma = false;
    wxBoxSizer *topSizer = new wxBoxSizer (wxVERTICAL);
    this->SetSizer (topSizer);
    wxBoxSizer *boxSizer = new wxBoxSizer (wxVERTICAL);
    topSizer->Add (boxSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
// first row: the CSV/TXT path
    wxBoxSizer *pathSizer = new wxBoxSizer (wxHORIZONTAL);
    boxSizer->Add (pathSizer, 0, wxALIGN_RIGHT | wxALL, 0);
    wxStaticText *pathLabel =
	new wxStaticText (this, wxID_STATIC, wxT ("&Path:"));
    pathSizer->Add (pathLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
    wxTextCtrl *pathValue = new wxTextCtrl (this, wxID_STATIC,
					    Path, wxDefaultPosition,
					    wxSize (350, 22), wxTE_READONLY);
    pathSizer->Add (pathValue, 0, wxALIGN_RIGHT | wxALL, 5);
// second row: TABLE name
    wxBoxSizer *tableSizer = new wxBoxSizer (wxHORIZONTAL);
    boxSizer->Add (tableSizer, 0, wxALIGN_RIGHT | wxALL, 0);
    wxStaticText *tableLabel =
	new wxStaticText (this, wxID_STATIC, wxT ("&Table name:"));
    tableSizer->Add (tableLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
    wxTextCtrl *tableCtrl = new wxTextCtrl (this, ID_LDTXT_TABLE, Table,
					    wxDefaultPosition, wxSize (350,
								       22));
    tableSizer->Add (tableCtrl, 0, wxALIGN_RIGHT | wxALL, 5);
// second row: OPTIONS
    wxBoxSizer *optSizer = new wxBoxSizer (wxHORIZONTAL);
    boxSizer->Add (optSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 0);
    wxBoxSizer *modeSizer = new wxBoxSizer (wxVERTICAL);
    optSizer->Add (modeSizer, 0, wxALIGN_CENTER_VERTICAL | wxALL, 0);
    wxBoxSizer *mode1Sizer = new wxBoxSizer (wxHORIZONTAL);
    modeSizer->Add (mode1Sizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 0);
    wxCheckBox *titleCtrl = new wxCheckBox (this, ID_LDTXT_TITLES,
					    wxT
					    ("First line contains column names"),
					    wxDefaultPosition, wxDefaultSize);
    titleCtrl->SetValue (true);
    mode1Sizer->Add (titleCtrl, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
    wxStaticBox *sepBox = new wxStaticBox (this, wxID_STATIC,
					   wxT ("Separators"),
					   wxDefaultPosition, wxDefaultSize);
    wxBoxSizer *sepSizer = new wxStaticBoxSizer (sepBox, wxVERTICAL);
    modeSizer->Add (sepSizer, 0, wxALIGN_LEFT | wxALL, 0);
    wxBoxSizer *mode2Sizer = new wxBoxSizer (wxHORIZONTAL);
    sepSizer->Add (mode2Sizer, 0, wxALIGN_LEFT | wxALL, 0);
    wxString quotes[2];
    quotes[0] = wxT ("&Double \"");
    quotes[1] = wxT ("&Single '");
    wxRadioBox *textSeparatorBox = new wxRadioBox (this, ID_LDTXT_QUOTE,
						   wxT
						   ("&Text separator: quotes"),
						   wxDefaultPosition,
						   wxDefaultSize, 2,
						   quotes, 2,
						   wxRA_SPECIFY_COLS);
    mode2Sizer->Add (textSeparatorBox, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
    wxBoxSizer *mode3Sizer = new wxBoxSizer (wxHORIZONTAL);
    sepSizer->Add (mode3Sizer, 0, wxALIGN_LEFT | wxALL, 0);
    wxString separators[6];
    separators[0] = wxT ("&Tab");
    separators[1] = wxT ("&Space");
    separators[2] = wxT ("Co&mma ,");
    separators[3] = wxT ("&Colon :");
    separators[4] = wxT ("S&emicolon ;");
    separators[5] = wxT ("&Other");
    wxRadioBox *separatorBox = new wxRadioBox (this, ID_LDTXT_SEPARATOR,
					       wxT ("&Column separator"),
					       wxDefaultPosition, wxDefaultSize,
					       6,
					       separators, 2,
					       wxRA_SPECIFY_COLS);
    mode3Sizer->Add (separatorBox, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
    wxBoxSizer *mode4Sizer = new wxBoxSizer (wxHORIZONTAL);
    sepSizer->Add (mode4Sizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 0);
    wxStaticText *charSeparatorLabel = new wxStaticText (this, wxID_STATIC,
							 wxT
							 ("&Custom separator:"),
							 wxDefaultPosition,
							 wxDefaultSize, 0);
    mode4Sizer->Add (charSeparatorLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
    wxTextCtrl *dummy =
	new wxTextCtrl (this, ID_LDTXT_CHARSEPARATOR, wxT ("Dummy Text pq"),
			wxDefaultPosition,
			wxDefaultSize, 0);
    wxSize sz = dummy->GetSize ();
    delete dummy;
    sz.SetWidth (40);
    wxTextCtrl *charSeparatorCtrl =
	new wxTextCtrl (this, ID_LDTXT_CHARSEPARATOR, wxT ("TAB"),
			wxDefaultPosition, sz, 0);
    charSeparatorCtrl->SetMaxLength (1);
    charSeparatorCtrl->Enable (false);
    mode4Sizer->Add (charSeparatorCtrl, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
    wxBoxSizer *mode5Sizer = new wxBoxSizer (wxHORIZONTAL);
    sepSizer->Add (mode5Sizer, 0, wxALIGN_LEFT | wxALL, 0);
    wxString points[2];
    points[0] = wxT ("&Point .");
    points[1] = wxT ("&Comma ,");
    wxRadioBox *decimalSeparatorBox = new wxRadioBox (this, ID_LDTXT_POINT,
						      wxT
						      ("&Decimal separator"),
						      wxDefaultPosition,
						      wxDefaultSize, 2,
						      points, 2,
						      wxRA_SPECIFY_COLS);
    mode5Sizer->Add (decimalSeparatorBox, 0, wxALIGN_CENTER_VERTICAL | wxALL,
		     5);
// third row: CHARSET
    wxStaticBox *charsetBox = new wxStaticBox (this, wxID_STATIC,
					       wxT ("Charset Encoding"),
					       wxDefaultPosition,
					       wxDefaultSize);
    wxBoxSizer *charsetSizer = new wxStaticBoxSizer (charsetBox, wxHORIZONTAL);
    optSizer->Add (charsetSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
    wxListBox *charsetCtrl = new wxListBox (this, ID_LDTXT_CHARSET,
					    wxDefaultPosition, wxDefaultSize,
					    MainFrame->GetCharsetsLen (),
					    MainFrame->GetCharsetsNames (),
					    wxLB_SINGLE);
    charsetCtrl->SetFont (wxFont

			  (8, wxFONTFAMILY_MODERN, wxFONTSTYLE_NORMAL,
			   wxFONTWEIGHT_NORMAL));
    int idSel = MainFrame->GetCharsetIndex (Default);
    if (idSel != wxNOT_FOUND)
	charsetCtrl->SetSelection (idSel);
    charsetSizer->Add (charsetCtrl, 0, wxALIGN_CENTER_VERTICAL | wxALL, 0);
// OK - CANCEL buttons
    wxBoxSizer *okCancelBox = new wxBoxSizer (wxHORIZONTAL);
    boxSizer->Add (okCancelBox, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 0);
    wxButton *ok = new wxButton (this, wxID_OK, wxT ("&OK"));
    okCancelBox->Add (ok, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
    wxButton *cancel = new wxButton (this, wxID_CANCEL, wxT ("&Cancel"));
    okCancelBox->Add (cancel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
// appends event handler for OK button
    Connect (wxID_OK, wxEVT_COMMAND_BUTTON_CLICKED,
	     (wxObjectEventFunction) & LoadTxtDialog::OnOk);
// appends event handler for radioboxes
    Connect (ID_LDTXT_QUOTE, wxEVT_COMMAND_RADIOBOX_SELECTED,
	     (wxObjectEventFunction) & LoadTxtDialog::OnQuote);
    Connect (ID_LDTXT_SEPARATOR, wxEVT_COMMAND_RADIOBOX_SELECTED,
	     (wxObjectEventFunction) & LoadTxtDialog::OnSeparator);
    Connect (ID_LDTXT_POINT, wxEVT_COMMAND_RADIOBOX_SELECTED,
	     (wxObjectEventFunction) & LoadTxtDialog::OnDecimalSeparator);
}

void
LoadTxtDialog::OnDecimalSeparator (wxCommandEvent & event)
{
//
// POINT selection changed
//
    wxRadioBox *decimalSeparatorCtrl =
	(wxRadioBox *) FindWindow (ID_LDTXT_POINT);
    switch (decimalSeparatorCtrl->GetSelection ())
      {
      case 0:
	  DecimalPointIsComma = false;
	  break;
      case 1:
	  DecimalPointIsComma = true;
	  break;
      };
}

void
LoadTxtDialog::OnQuote (wxCommandEvent & event)
{
//
// QUOTE selection changed
//
    wxRadioBox *separatorCtrl = (wxRadioBox *) FindWindow (ID_LDTXT_QUOTE);
    switch (separatorCtrl->GetSelection ())
      {
      case 0:
	  TextSeparator = '"';
	  break;
      case 1:
	  TextSeparator = '\'';
	  break;
      };
}

void
LoadTxtDialog::OnSeparator (wxCommandEvent & event)
{
//
// SEPARATOR selection changed
//
    wxTextCtrl *charSeparatorCtrl =
	(wxTextCtrl *) FindWindow (ID_LDTXT_CHARSEPARATOR);
    wxRadioBox *separatorCtrl = (wxRadioBox *) FindWindow (ID_LDTXT_SEPARATOR);
    switch (separatorCtrl->GetSelection ())
      {
      case 0:
	  Separator = '\t';
	  charSeparatorCtrl->SetValue (wxT ("TAB"));
	  break;
      case 1:
	  Separator = ' ';
	  charSeparatorCtrl->SetValue (wxT ("SP"));
	  break;
      case 2:
	  Separator = ',';
	  charSeparatorCtrl->SetValue (wxT (","));
	  break;
      case 3:
	  Separator = ':';
	  charSeparatorCtrl->SetValue (wxT (":"));
	  break;
      case 4:
	  Separator = ';';
	  charSeparatorCtrl->SetValue (wxT (";"));
	  break;
      case 5:
	  Separator = '|';
	  charSeparatorCtrl->SetValue (wxT ("|"));
	  break;
      };
    if (separatorCtrl->GetSelection () == 5)
	charSeparatorCtrl->Enable (true);
    else
	charSeparatorCtrl->Enable (false);
}

void
LoadTxtDialog::OnOk (wxCommandEvent & event)
{
//
// all done: 
//
    wxTextCtrl *tableCtrl = (wxTextCtrl *) FindWindow (ID_LDTXT_TABLE);
    Table = tableCtrl->GetValue ();
    if (Table.Len () < 1)
      {
	  wxMessageBox (wxT ("You must specify the TABLE NAME !!!"),
			wxT ("spatialite-gui"), wxOK | wxICON_WARNING, this);
	  return;
      }
    if (MainFrame->TableAlreadyExists (Table) == true)
      {
	  wxMessageBox (wxT ("a table name '") + Table +
			wxT ("' already exists"), wxT ("spatialite-gui"),
			wxOK | wxICON_WARNING, this);
	  return;
      }
    if (gaiaIllegalSqlName (Table.ToUTF8 ()) == 1
	|| gaiaIsReservedSqlName (Table.ToUTF8 ()) == 1
	|| gaiaIsReservedSqliteName (Table.ToUTF8 ()) == 1)
      {
	  wxMessageBox (wxT ("'") + Table +
			wxT
			("' is an invalid TABLE NAME\n\nillegal name or reserved keyword"),
			wxT ("spatialite-gui"), wxOK | wxICON_WARNING, this);
	  return;
      }
    wxListBox *charsetCtrl = (wxListBox *) FindWindow (ID_LDTXT_CHARSET);
    int idSel = charsetCtrl->GetSelection ();
    if (idSel == wxNOT_FOUND)
      {
	  wxMessageBox (wxT
			("you must select some Charset Encoding from the list"),
			wxT ("spatialite-gui"), wxOK | wxICON_WARNING, this);
	  return;
      }
    wxString *charsets = MainFrame->GetCharsets ();
    Charset = *(charsets + idSel);
    wxRadioBox *separatorCtrl = (wxRadioBox *) FindWindow (ID_LDTXT_SEPARATOR);
    if (separatorCtrl->GetSelection () == 5)
      {
	  wxTextCtrl *charSeparatorCtrl =
	      (wxTextCtrl *) FindWindow (ID_LDTXT_CHARSEPARATOR);
	  wxString separator = charSeparatorCtrl->GetValue ();
	  if (separator.Len () != 1)
	    {
		wxMessageBox (wxT
			      ("you must specificy a single char as Custom Column Separator"),
			      wxT ("spatialite-gui"), wxOK | wxICON_WARNING,
			      this);
		return;
	    }
	  char dummy[64];
	  strcpy (dummy, separator.ToUTF8 ());
	  Separator = *dummy;
      }
    wxDialog::EndModal (wxID_OK);
}

bool
LoadShpDialog::Create (MyFrame * parent, wxString & path, wxString & table,
		       int srid, wxString & column, wxString & defCs)
{
//
// creating the dialog
//
    MainFrame = parent;
    Path = path;
    Table = table;
    Srid = srid;
    Column = column;
    Default = defCs;
    if (wxDialog::Create (parent, wxID_ANY, wxT ("Load Shapefile")) == false)
	return false;
// populates individual controls
    CreateControls ();
// sets dialog sizer
    GetSizer ()->Fit (this);
    GetSizer ()->SetSizeHints (this);
// centers the dialog window
    Centre ();
    return true;
}

void
LoadShpDialog::CreateControls ()
{
//
// creating individual control and setting initial values
//
    wxBoxSizer *topSizer = new wxBoxSizer (wxVERTICAL);
    this->SetSizer (topSizer);
    wxBoxSizer *boxSizer = new wxBoxSizer (wxVERTICAL);
    topSizer->Add (boxSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
// first row: the Shapefile path
    wxBoxSizer *pathSizer = new wxBoxSizer (wxHORIZONTAL);
    boxSizer->Add (pathSizer, 0, wxALIGN_RIGHT | wxALL, 0);
    wxStaticText *pathLabel =
	new wxStaticText (this, wxID_STATIC, wxT ("&Path:"));
    pathSizer->Add (pathLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
    wxTextCtrl *pathValue = new wxTextCtrl (this, wxID_STATIC,
					    Path, wxDefaultPosition,
					    wxSize (350, 22), wxTE_READONLY);
    pathSizer->Add (pathValue, 0, wxALIGN_RIGHT | wxALL, 5);
// second row: TABLE name
    wxBoxSizer *tableSizer = new wxBoxSizer (wxHORIZONTAL);
    boxSizer->Add (tableSizer, 0, wxALIGN_RIGHT | wxALL, 0);
    wxStaticText *tableLabel =
	new wxStaticText (this, wxID_STATIC, wxT ("&Table name:"));
    tableSizer->Add (tableLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
    wxTextCtrl *tableCtrl = new wxTextCtrl (this, ID_LDSHP_TABLE, Table,
					    wxDefaultPosition, wxSize (350,
								       22));
    tableSizer->Add (tableCtrl, 0, wxALIGN_RIGHT | wxALL, 5);
// third row: GEOMETRY COLUMN name
    wxBoxSizer *colSizer = new wxBoxSizer (wxHORIZONTAL);
    boxSizer->Add (colSizer, 0, wxALIGN_RIGHT | wxALL, 0);
    wxStaticText *colLabel =
	new wxStaticText (this, wxID_STATIC, wxT ("&GeomColumn name:"));
    colSizer->Add (colLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
    wxTextCtrl *colCtrl = new wxTextCtrl (this, ID_LDSHP_COLUMN, Column,
					  wxDefaultPosition, wxSize (350, 22));
    colSizer->Add (colCtrl, 0, wxALIGN_RIGHT | wxALL, 5);
// fourth row: SRID
    wxBoxSizer *sridSizer = new wxBoxSizer (wxHORIZONTAL);
    boxSizer->Add (sridSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 0);
    wxStaticText *sridLabel =
	new wxStaticText (this, wxID_STATIC, wxT ("&SRID:"));
    sridSizer->Add (sridLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
    wxSpinCtrl *sridCtrl = new wxSpinCtrl (this, ID_LDSHP_SRID, wxEmptyString,
					   wxDefaultPosition, wxSize (80, 20),
					   wxSP_ARROW_KEYS,
					   -1, 40000, Srid);
    sridSizer->Add (sridCtrl, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
// fifth row: CHARSET
    wxStaticBox *charsetBox = new wxStaticBox (this, wxID_STATIC,
					       wxT ("Charset Encoding"),
					       wxDefaultPosition,
					       wxDefaultSize);
    wxBoxSizer *charsetSizer = new wxStaticBoxSizer (charsetBox, wxHORIZONTAL);
    sridSizer->Add (charsetSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
    wxListBox *charsetCtrl = new wxListBox (this, ID_LDSHP_CHARSET,
					    wxDefaultPosition, wxDefaultSize,
					    MainFrame->GetCharsetsLen (),
					    MainFrame->GetCharsetsNames (),
					    wxLB_SINGLE);
    charsetCtrl->SetFont (wxFont
			  (8, wxFONTFAMILY_MODERN, wxFONTSTYLE_NORMAL,
			   wxFONTWEIGHT_NORMAL));
    int idSel = MainFrame->GetCharsetIndex (Default);
    if (idSel != wxNOT_FOUND)
	charsetCtrl->SetSelection (idSel);
    charsetSizer->Add (charsetCtrl, 0, wxALIGN_CENTER_VERTICAL | wxALL, 0);
// OK - CANCEL buttons
    wxBoxSizer *okCancelBox = new wxBoxSizer (wxHORIZONTAL);
    boxSizer->Add (okCancelBox, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 0);
    wxButton *ok = new wxButton (this, wxID_OK, wxT ("&OK"));
    okCancelBox->Add (ok, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
    wxButton *cancel = new wxButton (this, wxID_CANCEL, wxT ("&Cancel"));
    okCancelBox->Add (cancel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
// appends event handler for OK button
    Connect (wxID_OK, wxEVT_COMMAND_BUTTON_CLICKED,
	     (wxObjectEventFunction) & LoadShpDialog::OnOk);
}

void
LoadShpDialog::OnOk (wxCommandEvent & event)
{
//
// all done: 
//
    wxTextCtrl *tableCtrl = (wxTextCtrl *) FindWindow (ID_LDSHP_TABLE);
    Table = tableCtrl->GetValue ();
    if (Table.Len () < 1)
      {
	  wxMessageBox (wxT ("You must specify the TABLE NAME !!!"),
			wxT ("spatialite-gui"), wxOK | wxICON_WARNING, this);
	  return;
      }
    if (MainFrame->TableAlreadyExists (Table) == true)
      {
	  wxMessageBox (wxT ("a table name '") + Table +
			wxT ("' already exists"), wxT ("spatialite-gui"),
			wxOK | wxICON_WARNING, this);
	  return;
      }
    if (gaiaIllegalSqlName (Table.ToUTF8 ()) == 1
	|| gaiaIsReservedSqlName (Table.ToUTF8 ()) == 1
	|| gaiaIsReservedSqliteName (Table.ToUTF8 ()) == 1)
      {
	  wxMessageBox (wxT ("'") + Table +
			wxT
			("' is an invalid TABLE NAME\n\nillegal name or reserved keyword"),
			wxT ("spatialite-gui"), wxOK | wxICON_WARNING, this);
	  return;
      }
    wxTextCtrl *columnCtrl = (wxTextCtrl *) FindWindow (ID_LDSHP_COLUMN);
    Column = columnCtrl->GetValue ();
    if (Column.Len () < 1)
      {
	  wxMessageBox (wxT ("You must specify the GEOMETRY COLUMN NAME !!!"),
			wxT ("spatialite-gui"), wxOK | wxICON_WARNING, this);
	  return;
      }
    if (gaiaIllegalSqlName (Column.ToUTF8 ()) == 1
	|| gaiaIsReservedSqlName (Column.ToUTF8 ()) == 1
	|| gaiaIsReservedSqliteName (Column.ToUTF8 ()) == 1)
      {
	  wxMessageBox (wxT ("'") + Column +
			wxT
			("' is an invalid COLUMN NAME\n\nsame as SQL reserved keyword"),
			wxT ("spatialite-gui"), wxOK | wxICON_WARNING, this);
	  return;
      }
    wxSpinCtrl *sridCtrl = (wxSpinCtrl *) FindWindow (ID_LDSHP_SRID);
    Srid = sridCtrl->GetValue ();
    if (MainFrame->SridNotExists (Srid) == true)
      {
	  wxMessageBox (wxT ("invalid SRID value"),
			wxT ("spatialite-gui"), wxOK | wxICON_WARNING, this);
	  return;
      }
    wxListBox *charsetCtrl = (wxListBox *) FindWindow (ID_LDSHP_CHARSET);
    int idSel = charsetCtrl->GetSelection ();
    if (idSel == wxNOT_FOUND)
      {
	  wxMessageBox (wxT
			("you must select some Charset Encoding from the list"),
			wxT ("spatialite-gui"), wxOK | wxICON_WARNING, this);
	  return;
      }
    wxString *charsets = MainFrame->GetCharsets ();
    Charset = *(charsets + idSel);
    wxDialog::EndModal (wxID_OK);
}

bool
DumpShpDialog::Create (MyFrame * parent, wxString & path, wxString & table,
		       wxString & column, wxString & defCs)
{
//
// creating the dialog
//
    MainFrame = parent;
    Path = path;
    Table = table;
    Column = column;
    Default = defCs;
    if (wxDialog::Create (parent, wxID_ANY, wxT ("Dump Shapefile")) == false)
	return false;
// populates individual controls
    CreateControls ();
// sets dialog sizer
    GetSizer ()->Fit (this);
    GetSizer ()->SetSizeHints (this);
// centers the dialog window
    Centre ();
    return true;
}

void
DumpShpDialog::CreateControls ()
{
//
// creating individual control and setting initial values
//
    wxBoxSizer *topSizer = new wxBoxSizer (wxVERTICAL);
    this->SetSizer (topSizer);
    wxBoxSizer *boxSizer = new wxBoxSizer (wxVERTICAL);
    topSizer->Add (boxSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
// first row: the Shapefile path
    wxBoxSizer *pathSizer = new wxBoxSizer (wxHORIZONTAL);
    boxSizer->Add (pathSizer, 0, wxALIGN_RIGHT | wxALL, 0);
    wxStaticText *pathLabel =
	new wxStaticText (this, wxID_STATIC, wxT ("&Path:"));
    pathSizer->Add (pathLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
    wxTextCtrl *pathValue = new wxTextCtrl (this, wxID_STATIC,
					    Path, wxDefaultPosition,
					    wxSize (350, 22), wxTE_READONLY);
    pathSizer->Add (pathValue, 0, wxALIGN_RIGHT | wxALL, 5);
// second row: TABLE name
    wxBoxSizer *tableSizer = new wxBoxSizer (wxHORIZONTAL);
    boxSizer->Add (tableSizer, 0, wxALIGN_RIGHT | wxALL, 0);
    wxStaticText *tableLabel =
	new wxStaticText (this, wxID_STATIC, wxT ("&Table name:"));
    tableSizer->Add (tableLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
    wxTextCtrl *tableCtrl = new wxTextCtrl (this, wxID_STATIC, Table,
					    wxDefaultPosition, wxSize (350,
								       22));
    tableCtrl->Enable (false);
    tableSizer->Add (tableCtrl, 0, wxALIGN_RIGHT | wxALL, 5);
// third row: GEOMETRY COLUMN name
    wxBoxSizer *colSizer = new wxBoxSizer (wxHORIZONTAL);
    boxSizer->Add (colSizer, 0, wxALIGN_RIGHT | wxALL, 0);
    wxStaticText *colLabel =
	new wxStaticText (this, wxID_STATIC, wxT ("&GeomColumn name:"));
    colSizer->Add (colLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
    wxTextCtrl *colCtrl = new wxTextCtrl (this, wxID_STATIC, Column,
					  wxDefaultPosition, wxSize (350, 22));
    colCtrl->Enable (false);
    colSizer->Add (colCtrl, 0, wxALIGN_RIGHT | wxALL, 5);
// fourth row: CHARSET
    wxBoxSizer *csSizer = new wxBoxSizer (wxHORIZONTAL);
    boxSizer->Add (csSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 0);
    wxStaticBox *charsetBox = new wxStaticBox (this, wxID_STATIC,
					       wxT ("Charset Encoding"),
					       wxDefaultPosition,
					       wxDefaultSize);
    wxBoxSizer *charsetSizer = new wxStaticBoxSizer (charsetBox, wxHORIZONTAL);
    csSizer->Add (charsetSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
    wxListBox *charsetCtrl = new wxListBox (this, ID_DMPSHP_CHARSET,
					    wxDefaultPosition, wxDefaultSize,
					    MainFrame->GetCharsetsLen (),
					    MainFrame->GetCharsetsNames (),
					    wxLB_SINGLE);
    charsetCtrl->SetFont (wxFont
			  (8, wxFONTFAMILY_MODERN, wxFONTSTYLE_NORMAL,
			   wxFONTWEIGHT_NORMAL));
    int idSel = MainFrame->GetCharsetIndex (Default);
    if (idSel != wxNOT_FOUND)
	charsetCtrl->SetSelection (idSel);
    charsetSizer->Add (charsetCtrl, 0, wxALIGN_CENTER_VERTICAL | wxALL, 0);
// OK - CANCEL buttons
    wxBoxSizer *okCancelBox = new wxBoxSizer (wxHORIZONTAL);
    boxSizer->Add (okCancelBox, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 0);
    wxButton *ok = new wxButton (this, wxID_OK, wxT ("&OK"));
    okCancelBox->Add (ok, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
    wxButton *cancel = new wxButton (this, wxID_CANCEL, wxT ("&Cancel"));
    okCancelBox->Add (cancel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
// appends event handler for OK button
    Connect (wxID_OK, wxEVT_COMMAND_BUTTON_CLICKED,
	     (wxObjectEventFunction) & DumpShpDialog::OnOk);
}

void
DumpShpDialog::OnOk (wxCommandEvent & event)






































































































































































































































































































































































































































































{
//
// all done: 
//
    wxListBox *charsetCtrl = (wxListBox *) FindWindow (ID_DMPSHP_CHARSET);
    int idSel = charsetCtrl->GetSelection ();
    if (idSel == wxNOT_FOUND)
      {
	  wxMessageBox (wxT
			("you must select some Charset Encoding from the list"),
			wxT ("spatialite-gui"), wxOK | wxICON_WARNING, this);
	  return;
      }
    wxString *charsets = MainFrame->GetCharsets ();
    Charset = *(charsets + idSel);

    wxDialog::EndModal (wxID_OK);
}

bool
DumpTxtDialog::Create (MyFrame * parent, wxString & path,
		       wxString & target, wxString & defCs)

{
//
// creating the dialog
//
    MainFrame = parent;
    Path = path;
    Default = defCs;
    if (wxDialog::Create (parent, wxID_ANY, wxT ("Dump ") + target) == false)
	return false;
// populates individual controls
    CreateControls ();
// sets dialog sizer
    GetSizer ()->Fit (this);
    GetSizer ()->SetSizeHints (this);
// centers the dialog window
    Centre ();
    return true;
}

void
DumpTxtDialog::CreateControls ()
{
//
// creating individual control and setting initial values
//
    wxBoxSizer *topSizer = new wxBoxSizer (wxVERTICAL);
    this->SetSizer (topSizer);
    wxBoxSizer *boxSizer = new wxBoxSizer (wxVERTICAL);
    topSizer->Add (boxSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
// first row: the Shapefile path
    wxBoxSizer *pathSizer = new wxBoxSizer (wxHORIZONTAL);
    boxSizer->Add (pathSizer, 0, wxALIGN_RIGHT | wxALL, 0);
    wxStaticText *pathLabel =
	new wxStaticText (this, wxID_STATIC, wxT ("&Path:"));
    pathSizer->Add (pathLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
    wxTextCtrl *pathValue = new wxTextCtrl (this, wxID_STATIC,
					    Path, wxDefaultPosition,
					    wxSize (350, 22), wxTE_READONLY);
    pathSizer->Add (pathValue, 0, wxALIGN_RIGHT | wxALL, 5);
// second row: CHARSET
    wxBoxSizer *csSizer = new wxBoxSizer (wxHORIZONTAL);
    boxSizer->Add (csSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 0);
    wxStaticBox *charsetBox = new wxStaticBox (this, wxID_STATIC,
					       wxT ("Charset Encoding"),
					       wxDefaultPosition,
					       wxDefaultSize);
    wxBoxSizer *charsetSizer = new wxStaticBoxSizer (charsetBox, wxHORIZONTAL);
    csSizer->Add (charsetSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
    wxListBox *charsetCtrl = new wxListBox (this, ID_DMPTXT_CHARSET,
					    wxDefaultPosition, wxDefaultSize,
					    MainFrame->GetCharsetsLen (),
					    MainFrame->GetCharsetsNames (),
					    wxLB_SINGLE);
    charsetCtrl->SetFont (wxFont
			  (8, wxFONTFAMILY_MODERN, wxFONTSTYLE_NORMAL,
			   wxFONTWEIGHT_NORMAL));
    int idSel = MainFrame->GetCharsetIndex (Default);
    if (idSel != wxNOT_FOUND)
	charsetCtrl->SetSelection (idSel);
    charsetSizer->Add (charsetCtrl, 0, wxALIGN_CENTER_VERTICAL | wxALL, 0);
// OK - CANCEL buttons
    wxBoxSizer *okCancelBox = new wxBoxSizer (wxHORIZONTAL);
    boxSizer->Add (okCancelBox, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 0);
    wxButton *ok = new wxButton (this, wxID_OK, wxT ("&OK"));
    okCancelBox->Add (ok, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
    wxButton *cancel = new wxButton (this, wxID_CANCEL, wxT ("&Cancel"));
    okCancelBox->Add (cancel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
// appends event handler for OK button
    Connect (wxID_OK, wxEVT_COMMAND_BUTTON_CLICKED,
	     (wxObjectEventFunction) & DumpTxtDialog::OnOk);
}

void
DumpTxtDialog::OnOk (wxCommandEvent & event)
{
//
// all done: 
//
    wxListBox *charsetCtrl = (wxListBox *) FindWindow (ID_DMPTXT_CHARSET);
    int idSel = charsetCtrl->GetSelection ();
    if (idSel == wxNOT_FOUND)
      {
	  wxMessageBox (wxT
			("you must select some Charset Encoding from the list"),
			wxT ("spatialite-gui"), wxOK | wxICON_WARNING, this);
	  return;
      }
    wxString *charsets = MainFrame->GetCharsets ();
    Charset = *(charsets + idSel);
    wxDialog::EndModal (wxID_OK);
}

bool
SqlScriptDialog::Create (MyFrame * parent, wxString & path, wxString & defCs)
{
//
// creating the dialog
//
    MainFrame = parent;
    Path = path;
    Default = defCs;
    if (wxDialog::Create (parent, wxID_ANY, wxT ("SQL script execute")) ==
	false)
	return false;
// populates individual controls
    CreateControls ();
// sets dialog sizer
    GetSizer ()->Fit (this);

    GetSizer ()->SetSizeHints (this);
// centers the dialog window
    Centre ();
    return true;
}

void
SqlScriptDialog::CreateControls ()
{
//
// creating individual control and setting initial values
//
    wxBoxSizer *topSizer = new wxBoxSizer (wxVERTICAL);
    this->SetSizer (topSizer);
    wxBoxSizer *boxSizer = new wxBoxSizer (wxVERTICAL);
    topSizer->Add (boxSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
// first row: the SQL script path

    wxBoxSizer *pathSizer = new wxBoxSizer (wxHORIZONTAL);
    boxSizer->Add (pathSizer, 0, wxALIGN_RIGHT | wxALL, 0);
    wxStaticText *pathLabel =
	new wxStaticText (this, wxID_STATIC, wxT ("&Path:"));
    pathSizer->Add (pathLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
    wxTextCtrl *pathValue = new wxTextCtrl (this, wxID_STATIC,

					    Path, wxDefaultPosition,
					    wxSize (350, 22), wxTE_READONLY);

    pathSizer->Add (pathValue, 0, wxALIGN_RIGHT | wxALL, 5);
// second row: CHARSET
    wxBoxSizer *csSizer = new wxBoxSizer (wxHORIZONTAL);
    boxSizer->Add (csSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 0);
    wxStaticBox *charsetBox = new wxStaticBox (this, wxID_STATIC,
					       wxT ("Charset Encoding"),
					       wxDefaultPosition,
					       wxDefaultSize);
    wxBoxSizer *charsetSizer = new wxStaticBoxSizer (charsetBox, wxHORIZONTAL);
    csSizer->Add (charsetSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
    wxListBox *charsetCtrl = new wxListBox (this, ID_SCRIPT_CHARSET,
					    wxDefaultPosition, wxDefaultSize,
					    MainFrame->GetCharsetsLen (),
					    MainFrame->GetCharsetsNames (),
					    wxLB_SINGLE);
    charsetCtrl->SetFont (wxFont
			  (8, wxFONTFAMILY_MODERN, wxFONTSTYLE_NORMAL,
			   wxFONTWEIGHT_NORMAL));
    int idSel = MainFrame->GetCharsetIndex (Default);
    if (idSel != wxNOT_FOUND)
	charsetCtrl->SetSelection (idSel);
    charsetSizer->Add (charsetCtrl, 0, wxALIGN_CENTER_VERTICAL | wxALL, 0);
// OK - CANCEL buttons
    wxBoxSizer *okCancelBox = new wxBoxSizer (wxHORIZONTAL);
    boxSizer->Add (okCancelBox, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 0);
    wxButton *ok = new wxButton (this, wxID_OK, wxT ("&OK"));
    okCancelBox->Add (ok, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
    wxButton *cancel = new wxButton (this, wxID_CANCEL, wxT ("&Cancel"));
    okCancelBox->Add (cancel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
// appends event handler for OK button
    Connect (wxID_OK, wxEVT_COMMAND_BUTTON_CLICKED,
	     (wxObjectEventFunction) & SqlScriptDialog::OnOk);
}

void
SqlScriptDialog::OnOk (wxCommandEvent & event)
{
//
// all done: 
//
    wxListBox *charsetCtrl = (wxListBox *) FindWindow (ID_SCRIPT_CHARSET);
    int idSel = charsetCtrl->GetSelection ();
    if (idSel == wxNOT_FOUND)
      {
	  wxMessageBox (wxT
			("you must select some Charset Encoding from the list"),
			wxT ("spatialite-gui"), wxOK | wxICON_WARNING, this);
	  return;
      }
    wxString *charsets = MainFrame->GetCharsets ();
    Charset = *(charsets + idSel);
    wxDialog::EndModal (wxID_OK);
}

bool
DefaultCharsetDialog::Create (MyFrame * parent, wxString & charset, bool ask)

{
//
// creating the dialog
//
    MainFrame = parent;
    Charset = charset;
    AskCharset = ask;
    if (wxDialog::Create (parent, wxID_ANY, wxT ("Charset settings")) == false)
	return false;
// populates individual controls
    CreateControls ();
// sets dialog sizer
    GetSizer ()->Fit (this);
    GetSizer ()->SetSizeHints (this);
// centers the dialog window
    Centre ();
    return true;
}

void
DefaultCharsetDialog::CreateControls ()
{
//
// creating individual control and setting initial values
//
    wxBoxSizer *topSizer = new wxBoxSizer (wxVERTICAL);
    this->SetSizer (topSizer);
    wxBoxSizer *boxSizer = new wxBoxSizer (wxVERTICAL);
    topSizer->Add (boxSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
// first row: the DEFAULT CHARSET
    wxBoxSizer *csSizer = new wxBoxSizer (wxHORIZONTAL);
    boxSizer->Add (csSizer, 0, wxALIGN_RIGHT | wxALL, 0);
    wxStaticBox *charsetBox = new wxStaticBox (this, wxID_STATIC,
					       wxT ("Default Output Charset"),
					       wxDefaultPosition,
					       wxDefaultSize);
    wxBoxSizer *charsetSizer = new wxStaticBoxSizer (charsetBox, wxVERTICAL);
    csSizer->Add (charsetSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
    wxListBox *charsetCtrl = new wxListBox (this, ID_DFLT_CHARSET,
					    wxDefaultPosition, wxDefaultSize,
					    MainFrame->GetCharsetsLen (),
					    MainFrame->GetCharsetsNames (),
					    wxLB_SINGLE);
    charsetCtrl->SetFont (wxFont
			  (8, wxFONTFAMILY_MODERN, wxFONTSTYLE_NORMAL,
			   wxFONTWEIGHT_NORMAL));
    int idSel = MainFrame->GetCharsetIndex (Charset);
    if (idSel != wxNOT_FOUND)
	charsetCtrl->SetSelection (idSel);
    charsetSizer->Add (charsetCtrl, 0, wxALIGN_CENTER_VERTICAL | wxALL, 0);
// second row: the ASK CHARSET
    wxBoxSizer *askSizer = new wxBoxSizer (wxHORIZONTAL);
    charsetSizer->Add (askSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 0);
    wxCheckBox *askCtrl = new wxCheckBox (this, ID_DFLT_ASK,
					  wxT ("Ask output charset every time"),
					  wxDefaultPosition, wxDefaultSize);
    askCtrl->SetValue (AskCharset);
    askSizer->Add (askCtrl, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
// OK - CANCEL buttons
    wxBoxSizer *okCancelBox = new wxBoxSizer (wxHORIZONTAL);
    boxSizer->Add (okCancelBox, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 0);
    wxButton *ok = new wxButton (this, wxID_OK, wxT ("&OK"));
    okCancelBox->Add (ok, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
    wxButton *cancel = new wxButton (this, wxID_CANCEL, wxT ("&Cancel"));
    okCancelBox->Add (cancel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
// appends event handler for OK button
    Connect (wxID_OK, wxEVT_COMMAND_BUTTON_CLICKED,
	     (wxObjectEventFunction) & DefaultCharsetDialog::OnOk);
}

void
DefaultCharsetDialog::OnOk (wxCommandEvent & event)
{
//
// all done: 
//
    wxListBox *charsetCtrl = (wxListBox *) FindWindow (ID_DFLT_CHARSET);
    int idSel = charsetCtrl->GetSelection ();
    if (idSel == wxNOT_FOUND)
      {
	  wxMessageBox (wxT
			("you must select some Default Charset Encoding from the list"),
			wxT ("spatialite-gui"), wxOK | wxICON_WARNING, this);
	  return;
      }
    wxString *charsets = MainFrame->GetCharsets ();
    Charset = *(charsets + idSel);
    wxCheckBox *askCtrl = (wxCheckBox *) FindWindow (ID_DFLT_ASK);
    AskCharset = askCtrl->GetValue ();
    wxDialog::EndModal (wxID_OK);
}

bool
RecoverDialog::Create (MyFrame * parent, wxString & table, wxString & column)
{
//
// creating the dialog
//
    MainFrame = parent;
    Table = table;
    Column = column;
    Srid = -1;
    if (wxDialog::Create (parent, wxID_ANY, wxT ("Recover Geometry Column")) ==
	false)
	return false;
// populates individual controls
    CreateControls ();
// sets dialog sizer
    GetSizer ()->Fit (this);
    GetSizer ()->SetSizeHints (this);
// centers the dialog window
    Centre ();
    return true;
}

void
RecoverDialog::CreateControls ()
{
//
// creating individual control and setting initial values
//
    wxBoxSizer *topSizer = new wxBoxSizer (wxVERTICAL);
    this->SetSizer (topSizer);
    wxBoxSizer *boxSizer = new wxBoxSizer (wxVERTICAL);
    topSizer->Add (boxSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
// First row: TABLE name
    wxBoxSizer *tableSizer = new wxBoxSizer (wxHORIZONTAL);
    boxSizer->Add (tableSizer, 0, wxALIGN_RIGHT | wxALL, 0);
    wxStaticText *tableLabel =
	new wxStaticText (this, wxID_STATIC, wxT ("&Table name:"));
    tableSizer->Add (tableLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
    wxTextCtrl *tableCtrl = new wxTextCtrl (this, wxID_ANY, Table,
					    wxDefaultPosition, wxSize (350, 22),
					    wxTE_READONLY);
    tableCtrl->Enable (false);
    tableSizer->Add (tableCtrl, 0, wxALIGN_RIGHT | wxALL, 5);
// second row: GEOMETRY COLUMN name
    wxBoxSizer *colSizer = new wxBoxSizer (wxHORIZONTAL);
    boxSizer->Add (colSizer, 0, wxALIGN_RIGHT | wxALL, 0);
    wxStaticText *colLabel =
	new wxStaticText (this, wxID_STATIC, wxT ("&Column name:"));
    colSizer->Add (colLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
    wxTextCtrl *colCtrl = new wxTextCtrl (this, wxID_ANY, Column,
					  wxDefaultPosition, wxSize (350, 22),
					  wxTE_READONLY);
    colCtrl->Enable (false);
    colSizer->Add (colCtrl, 0, wxALIGN_RIGHT | wxALL, 5);
// third row: SRID
    wxBoxSizer *sridSizer = new wxBoxSizer (wxHORIZONTAL);
    boxSizer->Add (sridSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 0);
    wxStaticText *sridLabel =
	new wxStaticText (this, wxID_STATIC, wxT ("&SRID:"));
    sridSizer->Add (sridLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
    wxSpinCtrl *sridCtrl = new wxSpinCtrl (this, ID_RCVR_SRID, wxEmptyString,
					   wxDefaultPosition, wxSize (80, 20),
					   wxSP_ARROW_KEYS,
					   -1, 40000, Srid);
    sridSizer->Add (sridCtrl, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
// fourth row: GEOMETRY TYPE
    wxStaticBox *typeBox = new wxStaticBox (this, wxID_STATIC,
					    wxT ("Geometry Type"),
					    wxDefaultPosition, wxDefaultSize);
    wxBoxSizer *typeSizer = new wxStaticBoxSizer (typeBox, wxHORIZONTAL);
    sridSizer->Add (typeSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
    wxString types[7];
    types[0] = wxT ("POINT");
    types[1] = wxT ("MULTIPOINT");
    types[2] = wxT ("LINESTRING");
    types[3] = wxT ("MULTILINESTRING");
    types[4] = wxT ("POLYGON");
    types[5] = wxT ("MULTIPOLYGON");
    types[6] = wxT ("GEOMETRYCOLLECTION");
    wxListBox *geomType = new wxListBox (this, ID_RCVR_TYPE,
					 wxDefaultPosition, wxDefaultSize, 7,
					 types, wxLB_SINGLE);
    typeSizer->Add (geomType, 0, wxALIGN_CENTER_VERTICAL | wxALL, 0);
// OK - CANCEL buttons
    wxBoxSizer *okCancelBox = new wxBoxSizer (wxHORIZONTAL);
    boxSizer->Add (okCancelBox, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 0);
    wxButton *ok = new wxButton (this, wxID_OK, wxT ("&OK"));
    okCancelBox->Add (ok, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
    wxButton *cancel = new wxButton (this, wxID_CANCEL, wxT ("&Cancel"));
    okCancelBox->Add (cancel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
// appends event handler for OK button
    Connect (wxID_OK, wxEVT_COMMAND_BUTTON_CLICKED,
	     (wxObjectEventFunction) & RecoverDialog::OnOk);
}

void
RecoverDialog::OnOk (wxCommandEvent & event)
{
//
// all done: 
//
    wxSpinCtrl *sridCtrl = (wxSpinCtrl *) FindWindow (ID_RCVR_SRID);
    wxListBox *geomType = (wxListBox *) FindWindow (ID_RCVR_TYPE);
    Srid = sridCtrl->GetValue ();
    if (MainFrame->SridNotExists (Srid) == true)
      {
	  wxMessageBox (wxT ("invalid SRID value"),
			wxT ("spatialite-gui"), wxOK | wxICON_WARNING, this);
	  return;
      }
    Type = geomType->GetStringSelection ();
    if (Type.Len () < 1)
      {
	  wxMessageBox (wxT
			("you must select some Geometry Type from the list"),
			wxT ("spatialite-gui"), wxOK | wxICON_WARNING, this);
	  return;
      }
    wxDialog::EndModal (wxID_OK);
}

bool
SetSridDialog::Create (MyFrame * parent, wxString & table, wxString & column)
{
//
// creating the dialog
//
    MainFrame = parent;
    Table = table;
    Column = column;
    OldSrid = -1;
    Srid = -1;
    if (wxDialog::Create (parent, wxID_ANY, wxT ("Changing SRID")) == false)
	return false;
// populates individual controls
    CreateControls ();
// sets dialog sizer
    GetSizer ()->Fit (this);
    GetSizer ()->SetSizeHints (this);
// centers the dialog window
    Centre ();
    return true;
}

void
SetSridDialog::CreateControls ()
{
//
// creating individual control and setting initial values
//
    wxBoxSizer *topSizer = new wxBoxSizer (wxVERTICAL);
    this->SetSizer (topSizer);
    wxBoxSizer *boxSizer = new wxBoxSizer (wxVERTICAL);
    topSizer->Add (boxSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
// First row: TABLE name
    wxBoxSizer *tableSizer = new wxBoxSizer (wxHORIZONTAL);
    boxSizer->Add (tableSizer, 0, wxALIGN_RIGHT | wxALL, 0);
    wxStaticText *tableLabel =
	new wxStaticText (this, wxID_STATIC, wxT ("&Table name:"));
    tableSizer->Add (tableLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
    wxTextCtrl *tableCtrl = new wxTextCtrl (this, wxID_ANY, Table,
					    wxDefaultPosition, wxSize (350, 22),
					    wxTE_READONLY);
    tableCtrl->Enable (false);
    tableSizer->Add (tableCtrl, 0, wxALIGN_RIGHT | wxALL, 5);
// second row: GEOMETRY COLUMN name
    wxBoxSizer *colSizer = new wxBoxSizer (wxHORIZONTAL);
    boxSizer->Add (colSizer, 0, wxALIGN_RIGHT | wxALL, 0);
    wxStaticText *colLabel =
	new wxStaticText (this, wxID_STATIC, wxT ("&Column name:"));
    colSizer->Add (colLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
    wxTextCtrl *colCtrl = new wxTextCtrl (this, wxID_ANY, Column,
					  wxDefaultPosition, wxSize (350, 22),
					  wxTE_READONLY);
    colCtrl->Enable (false);
    colSizer->Add (colCtrl, 0, wxALIGN_RIGHT | wxALL, 5);
// third row: SRID
    wxBoxSizer *mySizer = new wxBoxSizer (wxHORIZONTAL);
    boxSizer->Add (mySizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 0);
    wxBoxSizer *oldSridSizer = new wxBoxSizer (wxHORIZONTAL);
    mySizer->Add (oldSridSizer, 0, wxALIGN_LEFT | wxALL, 0);
    wxStaticText *oldSridLabel =
	new wxStaticText (this, wxID_STATIC, wxT ("&old SRID:"));
    oldSridSizer->Add (oldSridLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
    wxSpinCtrl *oldSridCtrl = new wxSpinCtrl (this, ID_SRID_OLD, wxEmptyString,
					      wxDefaultPosition, wxSize (80,
									 20),
					      wxSP_ARROW_KEYS,
					      -1, 40000, OldSrid);
    oldSridSizer->Add (oldSridCtrl, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
// fourth row: SRID
    wxBoxSizer *sridSizer = new wxBoxSizer (wxHORIZONTAL);
    mySizer->Add (sridSizer, 0, wxALIGN_RIGHT | wxLEFT, 20);
    wxStaticText *sridLabel =
	new wxStaticText (this, wxID_STATIC, wxT ("&new SRID:"));
    sridSizer->Add (sridLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
    wxSpinCtrl *sridCtrl = new wxSpinCtrl (this, ID_SRID_SRID, wxEmptyString,
					   wxDefaultPosition, wxSize (80, 20),
					   wxSP_ARROW_KEYS,
					   -1, 40000, Srid);
    sridSizer->Add (sridCtrl, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
// OK - CANCEL buttons
    wxBoxSizer *okCancelBox = new wxBoxSizer (wxHORIZONTAL);
    boxSizer->Add (okCancelBox, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 0);
    wxButton *ok = new wxButton (this, wxID_OK, wxT ("&OK"));
    okCancelBox->Add (ok, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
    wxButton *cancel = new wxButton (this, wxID_CANCEL, wxT ("&Cancel"));
    okCancelBox->Add (cancel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
// appends event handler for OK button
    Connect (wxID_OK, wxEVT_COMMAND_BUTTON_CLICKED,
	     (wxObjectEventFunction) & SetSridDialog::OnOk);
}

void
SetSridDialog::OnOk (wxCommandEvent & event)
{
//
// all done: 
//
    wxSpinCtrl *oldSridCtrl = (wxSpinCtrl *) FindWindow (ID_SRID_OLD);
    wxSpinCtrl *sridCtrl = (wxSpinCtrl *) FindWindow (ID_SRID_SRID);
    OldSrid = oldSridCtrl->GetValue ();
    Srid = sridCtrl->GetValue ();
    wxDialog::EndModal (wxID_OK);
}

bool
SearchSridDialog::Create (MyFrame * parent)
{
//
// creating the dialog
//
    MainFrame = parent;
    if (wxDialog::Create (parent, wxID_ANY,
			  wxT ("Searching a SRID by its name")) == false)
	return false;
// populates individual controls
    CreateControls ();
// sets dialog sizer
    GetSizer ()->Fit (this);
    GetSizer ()->SetSizeHints (this);
// centers the dialog window
    Centre ();
    return true;
}

void
SearchSridDialog::CreateControls ()
{
//
// creating individual control and setting initial values
//
    wxBoxSizer *topSizer = new wxBoxSizer (wxVERTICAL);
    this->SetSizer (topSizer);
    wxBoxSizer *boxSizer = new wxBoxSizer (wxVERTICAL);
    topSizer->Add (boxSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
// First row: SEARCH string
    wxBoxSizer *searchSizer = new wxBoxSizer (wxHORIZONTAL);
    boxSizer->Add (searchSizer, 0, wxALIGN_RIGHT | wxALL, 0);
    wxStaticText *searchLabel =
	new wxStaticText (this, wxID_STATIC, wxT ("&Search:"));
    searchSizer->Add (searchLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
    wxTextCtrl *searchCtrl = new wxTextCtrl (this, ID_SEARCH, wxT (""),
					     wxDefaultPosition, wxSize (150,
									22));
    searchSizer->Add (searchCtrl, 0, wxALIGN_RIGHT | wxALL, 5);
// OK - CANCEL buttons
    wxBoxSizer *okCancelBox = new wxBoxSizer (wxHORIZONTAL);
    boxSizer->Add (okCancelBox, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 0);
    wxButton *ok = new wxButton (this, wxID_OK, wxT ("&OK"));
    okCancelBox->Add (ok, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
    wxButton *cancel = new wxButton (this, wxID_CANCEL, wxT ("&Cancel"));
    okCancelBox->Add (cancel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
// appends event handler for OK button
    Connect (wxID_OK, wxEVT_COMMAND_BUTTON_CLICKED,
	     (wxObjectEventFunction) & SearchSridDialog::OnOk);
}

void
SearchSridDialog::OnOk (wxCommandEvent & event)
{
//
// all done: 
//
    wxTextCtrl *searchCtrl = (wxTextCtrl *) FindWindow (ID_SEARCH);
    String = searchCtrl->GetValue ();
    if (String.Len () < 1)
      {
	  wxMessageBox (wxT ("You must specify a string to search for !!!"),
			wxT ("spatialite-gui"), wxOK | wxICON_WARNING, this);
	  return;
      }
    wxDialog::EndModal (wxID_OK);
}

bool
HelpDialog::Create (MyFrame * parent)
{
//
// creating the dialog
//
    MainFrame = parent;
    if (wxDialog::Create (parent, wxID_ANY, wxT ("SQLite + SpatiaLite help")) ==
	false)
	return false;
// populates individual controls
    CreateControls ();
// sets dialog sizer
    GetSizer ()->Fit (this);
    GetSizer ()->SetSizeHints (this);
// centers the dialog window
    MainFrame->OpenHelpPane ();
    Centre ();
// setting up an event handler [dialog closing]
    Connect (wxID_ANY, wxEVT_CLOSE_WINDOW,
	     (wxObjectEventFunction) & HelpDialog::OnClose);
    return true;
}

void
HelpDialog::OnClose (wxCloseEvent & event)
{
//
// this window has been closed
//
    MainFrame->CloseHelpPane ();
    Destroy ();
}

void
HelpDialog::CreateControls ()
{
//
// creating individual control and setting initial values
//
    wxBoxSizer *topSizer = new wxBoxSizer (wxVERTICAL);
    this->SetSizer (topSizer);
    wxBoxSizer *boxSizer = new wxBoxSizer (wxVERTICAL);
    topSizer->Add (boxSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
    wxHtmlWindow *helpWin = new wxHtmlWindow (this, wxID_ANY,
					      wxDefaultPosition, wxSize (620,
									 420));
    wxString html;
    MainFrame->GetHelp (html);
    helpWin->SetPage (html);
    topSizer->Add (helpWin, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
}



































































































































































































































































































































































|







 







|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




|
|
|
|

|
|

|
|
|


<
|




|
|
|

|
|

|
|
|


<
|




|
|
|
<
|
|

|
|
|

|
|
|

|
|
|

|
|
|

|
|
|

|
|
|
|
|
|
|
|


<
|




|
|
|
|
|
|
|
|
|
|
|
<
<
<
<
<
<
<
<
<
<
<
|
|
|
|
|
|
|
<
|
|
|
|
|
|
|
<
|
|
|
|
|
|
|
|
|
|
<
|
|
|
|
|
|
|


<
|
|




|
|
|
|
|
|

|

<
>
|

|
|


<
|




|
|
|
|
|
|
|
|

|
|
|
<
|
|
|
|
|

|
|
|
|
|
|
|
|
|

|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<
|
|
|
|
|
|
<

|
|
|
|
|
|
|
|
|
|
|
|
>
|
<
|
|
|
|

|
|
|
|
|
|

|
|

|
|
|
|
|
|


<
|




|
<
|
|

|
|

|
|
|


<
|




|
|
|

|
|

|
|
|


<
|




|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>




|
|
|
<
<
<
<
<
<
<
<
>
|


<
<
<
>




|
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
|

|

<
>
|

|
|


<
|




|
|
|
|
<
>
|
|
|
|
|
<
>
|
<
>
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<

|
|
|
|
|
|

|
|


<
|




|
|
|
|
|
<
|
|
|
<
<
|


<
<
>




|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
..
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337

























338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354

355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371

372
373
374
375
376
377
378
379

380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412

413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428











429
430
431
432
433
434
435

436
437
438
439
440
441
442

443
444
445
446
447
448
449
450
451
452

453
454
455
456
457
458
459
460
461

462
463
464
465
466
467
468
469
470
471
472
473
474
475
476

477
478
479
480
481
482
483

484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500

501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539

540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564

565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587

588
589
590
591
592
593

594
595
596
597
598
599
600
601
602
603
604
605
606
607
608

609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631

632
633
634
635
636
637

638
639
640
641
642
643
644
645
646
647
648

649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665

666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507








1508
1509
1510
1511



1512
1513
1514
1515
1516
1517
1518
































































































1519
1520
1521
1522
1523

1524
1525
1526
1527
1528
1529
1530

1531
1532
1533
1534
1535
1536
1537
1538
1539

1540
1541
1542
1543
1544
1545

1546
1547

1548
1549





















1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561

1562
1563
1564
1565
1566
1567
1568
1569
1570
1571

1572
1573
1574


1575
1576
1577


1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
/*
/ Dialogs.cpp
/ various dialog classes
/
/ version 1.2, 2008 October 9
/
/ Author: Sandro Furieri a-furieri@lqt.it
/
/ Copyright (C) 2008  Alessandro Furieri
/
/    This program is free software: you can redistribute it and/or modify
/    it under the terms of the GNU General Public License as published by
................................................................................

#include "Classdef.h"

#include "wx/spinctrl.h"
#include "wx/listctrl.h"
#include "wx/html/htmlwin.h"

bool VirtualShpDialog::Create(MyFrame * parent, wxString & path,
                              wxString & table, wxString & defCs)
{
//
// creating the dialog
//
  MainFrame = parent;
  Path = path;
  Table = table;
  Default = defCs;
  if (wxDialog::Create(parent, wxID_ANY, wxT("Creating Virtual Shapefile")) ==
      false)
    return false;
// populates individual controls
  CreateControls();
// sets dialog sizer
  GetSizer()->Fit(this);
  GetSizer()->SetSizeHints(this);
// centers the dialog window
  Centre();
  return true;
}

void VirtualShpDialog::CreateControls()
{
//
// creating individual control and setting initial values
//
  wxBoxSizer *topSizer = new wxBoxSizer(wxVERTICAL);
  this->SetSizer(topSizer);
  wxBoxSizer *boxSizer = new wxBoxSizer(wxVERTICAL);
  topSizer->Add(boxSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
// first row: the Shapefile path
  wxBoxSizer *pathSizer = new wxBoxSizer(wxHORIZONTAL);
  boxSizer->Add(pathSizer, 0, wxALIGN_RIGHT | wxALL, 0);
  wxStaticText *pathLabel = new wxStaticText(this, wxID_STATIC, wxT("&Path:"));
  pathSizer->Add(pathLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
  wxTextCtrl *pathValue = new wxTextCtrl(this, wxID_STATIC,
                                         Path, wxDefaultPosition,
                                         wxSize(350, 22), wxTE_READONLY);
  pathSizer->Add(pathValue, 0, wxALIGN_RIGHT | wxALL, 5);
// second row: TABLE name
  wxBoxSizer *tableSizer = new wxBoxSizer(wxHORIZONTAL);
  boxSizer->Add(tableSizer, 0, wxALIGN_RIGHT | wxALL, 0);
  wxStaticText *tableLabel =
    new wxStaticText(this, wxID_STATIC, wxT("&Table name:"));
  tableSizer->Add(tableLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
  wxTextCtrl *tableCtrl = new wxTextCtrl(this, ID_VIRTSHP_TABLE, Table,
                                         wxDefaultPosition, wxSize(350,
                                                                   22));
  tableSizer->Add(tableCtrl, 0, wxALIGN_RIGHT | wxALL, 5);
// second row: SRID
  wxBoxSizer *sridSizer = new wxBoxSizer(wxHORIZONTAL);
  boxSizer->Add(sridSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 0);
  wxStaticText *sridLabel = new wxStaticText(this, wxID_STATIC, wxT("&SRID:"));
  sridSizer->Add(sridLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
  wxSpinCtrl *sridCtrl = new wxSpinCtrl(this, ID_VIRTSHP_SRID, wxEmptyString,
                                        wxDefaultPosition, wxSize(80, 20),
                                        wxSP_ARROW_KEYS,
                                        -1, 40000, -1);
  sridSizer->Add(sridCtrl, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
// third row: CHARSET
  wxStaticBox *charsetBox = new wxStaticBox(this, wxID_STATIC,
                                            wxT("Charset Encoding"),
                                            wxDefaultPosition,
                                            wxDefaultSize);
  wxBoxSizer *charsetSizer = new wxStaticBoxSizer(charsetBox, wxHORIZONTAL);
  sridSizer->Add(charsetSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
  wxListBox *charsetCtrl = new wxListBox(this, ID_VIRTSHP_CHARSET,
                                         wxDefaultPosition, wxDefaultSize,
                                         MainFrame->GetCharsetsLen(),
                                         MainFrame->GetCharsetsNames(),
                                         wxLB_SINGLE);
  charsetCtrl->
    SetFont(wxFont
            (8, wxFONTFAMILY_MODERN, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL));
  int idSel = MainFrame->GetCharsetIndex(Default);
  if (idSel != wxNOT_FOUND)
    charsetCtrl->SetSelection(idSel);
  charsetSizer->Add(charsetCtrl, 0, wxALIGN_CENTER_VERTICAL | wxALL, 0);
// OK - CANCEL buttons
  wxBoxSizer *okCancelBox = new wxBoxSizer(wxHORIZONTAL);
  boxSizer->Add(okCancelBox, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 0);
  wxButton *ok = new wxButton(this, wxID_OK, wxT("&OK"));
  okCancelBox->Add(ok, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
  wxButton *cancel = new wxButton(this, wxID_CANCEL, wxT("&Cancel"));
  okCancelBox->Add(cancel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
// appends event handler for OK button
  Connect(wxID_OK, wxEVT_COMMAND_BUTTON_CLICKED,
          (wxObjectEventFunction) & VirtualShpDialog::OnOk);
}

void VirtualShpDialog::OnOk(wxCommandEvent & event)
{
//
// all done: 
//
  wxTextCtrl *tableCtrl = (wxTextCtrl *) FindWindow(ID_VIRTSHP_TABLE);
  Table = tableCtrl->GetValue();
  if (Table.Len() < 1)
    {
      wxMessageBox(wxT("You must specify the TABLE NAME !!!"),
                   wxT("spatialite-gui"), wxOK | wxICON_WARNING, this);
      return;
    }
  if (MainFrame->TableAlreadyExists(Table) == true)
    {
      wxMessageBox(wxT("a table name '") + Table + wxT("' already exists"),
                   wxT("spatialite-gui"), wxOK | wxICON_WARNING, this);
      return;
    }
  wxSpinCtrl *sridCtrl = (wxSpinCtrl *) FindWindow(ID_VIRTSHP_SRID);
  Srid = sridCtrl->GetValue();
  if (Srid == -1)
    ;
  else if (MainFrame->SridNotExists(Srid) == true)
    {
      wxMessageBox(wxT("invalid SRID value"), wxT("spatialite-gui"),
                   wxOK | wxICON_WARNING, this);
      return;
    }
  wxListBox *charsetCtrl = (wxListBox *) FindWindow(ID_VIRTSHP_CHARSET);
  int idSel = charsetCtrl->GetSelection();
  if (idSel == wxNOT_FOUND)
    {
      wxMessageBox(wxT("you must select some Charset Encoding from the list"),
                   wxT("spatialite-gui"), wxOK | wxICON_WARNING, this);
      return;
    }
  wxString *charsets = MainFrame->GetCharsets();
  Charset = *(charsets + idSel);
  wxDialog::EndModal(wxID_OK);
}

bool VirtualTxtDialog::Create(MyFrame * parent, wxString & path,
                              wxString & table, wxString & defCs)
{
//
// creating the dialog
//
  MainFrame = parent;
  Path = path;
  Table = table;
  Default = defCs;
  if (wxDialog::Create(parent, wxID_ANY, wxT("Creating Virtual CSV/TXT")) ==
      false)
    return false;
// populates individual controls
  CreateControls();
// sets dialog sizer
  GetSizer()->Fit(this);
  GetSizer()->SetSizeHints(this);
// centers the dialog window
  Centre();
  return true;
}

void VirtualTxtDialog::CreateControls()
{
//
// creating individual control and setting initial values
//
  FirstLineTitles = true;
  Separator = '\t';
  TextSeparator = '"';
  DecimalPointIsComma = false;
  wxBoxSizer *topSizer = new wxBoxSizer(wxVERTICAL);
  this->SetSizer(topSizer);
  wxBoxSizer *boxSizer = new wxBoxSizer(wxVERTICAL);
  topSizer->Add(boxSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
// first row: the CSV/TXT path
  wxBoxSizer *pathSizer = new wxBoxSizer(wxHORIZONTAL);
  boxSizer->Add(pathSizer, 0, wxALIGN_RIGHT | wxALL, 0);
  wxStaticText *pathLabel = new wxStaticText(this, wxID_STATIC, wxT("&Path:"));
  pathSizer->Add(pathLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
  wxTextCtrl *pathValue = new wxTextCtrl(this, wxID_STATIC,
                                         Path, wxDefaultPosition,
                                         wxSize(350, 22), wxTE_READONLY);
  pathSizer->Add(pathValue, 0, wxALIGN_RIGHT | wxALL, 5);
// second row: TABLE name
  wxBoxSizer *tableSizer = new wxBoxSizer(wxHORIZONTAL);
  boxSizer->Add(tableSizer, 0, wxALIGN_RIGHT | wxALL, 0);
  wxStaticText *tableLabel =
    new wxStaticText(this, wxID_STATIC, wxT("&Table name:"));
  tableSizer->Add(tableLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
  wxTextCtrl *tableCtrl = new wxTextCtrl(this, ID_VIRTTXT_TABLE, Table,
                                         wxDefaultPosition, wxSize(350,
                                                                   22));
  tableSizer->Add(tableCtrl, 0, wxALIGN_RIGHT | wxALL, 5);
// second row: OPTIONS
  wxBoxSizer *optSizer = new wxBoxSizer(wxHORIZONTAL);
  boxSizer->Add(optSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 0);
  wxBoxSizer *modeSizer = new wxBoxSizer(wxVERTICAL);
  optSizer->Add(modeSizer, 0, wxALIGN_CENTER_VERTICAL | wxALL, 0);
  wxBoxSizer *mode1Sizer = new wxBoxSizer(wxHORIZONTAL);
  modeSizer->Add(mode1Sizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 0);
  wxCheckBox *titleCtrl = new wxCheckBox(this, ID_VIRTTXT_TITLES,
                                         wxT
                                         ("First line contains column names"),
                                         wxDefaultPosition, wxDefaultSize);
  titleCtrl->SetValue(true);
  mode1Sizer->Add(titleCtrl, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
  wxStaticBox *sepBox = new wxStaticBox(this, wxID_STATIC,
                                        wxT("Separators"),
                                        wxDefaultPosition, wxDefaultSize);
  wxBoxSizer *sepSizer = new wxStaticBoxSizer(sepBox, wxVERTICAL);
  modeSizer->Add(sepSizer, 0, wxALIGN_LEFT | wxALL, 0);
  wxBoxSizer *mode2Sizer = new wxBoxSizer(wxHORIZONTAL);
  sepSizer->Add(mode2Sizer, 0, wxALIGN_LEFT | wxALL, 0);
  wxString quotes[2];
  quotes[0] = wxT("&Double \"");
  quotes[1] = wxT("&Single '");
  wxRadioBox *textSeparatorBox = new wxRadioBox(this, ID_VIRTTXT_QUOTE,
                                                wxT("&Text separator: quotes"),
                                                wxDefaultPosition,
                                                wxDefaultSize, 2,
                                                quotes, 2,
                                                wxRA_SPECIFY_COLS);
  mode2Sizer->Add(textSeparatorBox, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
  wxBoxSizer *mode3Sizer = new wxBoxSizer(wxHORIZONTAL);
  sepSizer->Add(mode3Sizer, 0, wxALIGN_LEFT | wxALL, 0);
  wxString separators[6];
  separators[0] = wxT("&Tab");
  separators[1] = wxT("&Space");
  separators[2] = wxT("Co&mma ,");
  separators[3] = wxT("&Colon :");
  separators[4] = wxT("S&emicolon ;");
  separators[5] = wxT("&Other");
  wxRadioBox *separatorBox = new wxRadioBox(this, ID_VIRTTXT_SEPARATOR,
                                            wxT("&Column separator"),
                                            wxDefaultPosition, wxDefaultSize,
                                            6,
                                            separators, 2,
                                            wxRA_SPECIFY_COLS);
  mode3Sizer->Add(separatorBox, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
  wxBoxSizer *mode4Sizer = new wxBoxSizer(wxHORIZONTAL);
  sepSizer->Add(mode4Sizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 0);
  wxStaticText *charSeparatorLabel = new wxStaticText(this, wxID_STATIC,
                                                      wxT("&Custom separator:"),
                                                      wxDefaultPosition,
                                                      wxDefaultSize, 0);
  mode4Sizer->Add(charSeparatorLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
  wxTextCtrl *dummy =
    new wxTextCtrl(this, ID_VIRTTXT_CHARSEPARATOR, wxT("Dummy Text pq"),
                   wxDefaultPosition,
                   wxDefaultSize, 0);
  wxSize sz = dummy->GetSize();
  delete dummy;
  sz.SetWidth(40);
  wxTextCtrl *charSeparatorCtrl =
    new wxTextCtrl(this, ID_VIRTTXT_CHARSEPARATOR, wxT("TAB"),
                   wxDefaultPosition, sz, 0);
  charSeparatorCtrl->SetMaxLength(1);
  charSeparatorCtrl->Enable(false);
  mode4Sizer->Add(charSeparatorCtrl, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
  wxBoxSizer *mode5Sizer = new wxBoxSizer(wxHORIZONTAL);
  sepSizer->Add(mode5Sizer, 0, wxALIGN_LEFT | wxALL, 0);
  wxString points[2];
  points[0] = wxT("&Point .");
  points[1] = wxT("&Comma ,");
  wxRadioBox *decimalSeparatorBox = new wxRadioBox(this, ID_VIRTTXT_POINT,
                                                   wxT("&Decimal separator"),
                                                   wxDefaultPosition,
                                                   wxDefaultSize, 2,
                                                   points, 2,
                                                   wxRA_SPECIFY_COLS);
  mode5Sizer->Add(decimalSeparatorBox, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
// third row: CHARSET
  wxStaticBox *charsetBox = new wxStaticBox(this, wxID_STATIC,
                                            wxT("Charset Encoding"),
                                            wxDefaultPosition,
                                            wxDefaultSize);
  wxBoxSizer *charsetSizer = new wxStaticBoxSizer(charsetBox, wxHORIZONTAL);
  optSizer->Add(charsetSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
  wxListBox *charsetCtrl = new wxListBox(this, ID_VIRTTXT_CHARSET,
                                         wxDefaultPosition, wxDefaultSize,
                                         MainFrame->GetCharsetsLen(),
                                         MainFrame->GetCharsetsNames(),
                                         wxLB_SINGLE);
  charsetCtrl->
    SetFont(wxFont
            (8, wxFONTFAMILY_MODERN, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL));
  int idSel = MainFrame->GetCharsetIndex(Default);
  if (idSel != wxNOT_FOUND)
    charsetCtrl->SetSelection(idSel);
  charsetSizer->Add(charsetCtrl, 0, wxALIGN_CENTER_VERTICAL | wxALL, 0);
// OK - CANCEL buttons
  wxBoxSizer *okCancelBox = new wxBoxSizer(wxHORIZONTAL);
  boxSizer->Add(okCancelBox, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 0);
  wxButton *ok = new wxButton(this, wxID_OK, wxT("&OK"));
  okCancelBox->Add(ok, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
  wxButton *cancel = new wxButton(this, wxID_CANCEL, wxT("&Cancel"));
  okCancelBox->Add(cancel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
// appends event handler for OK button
  Connect(wxID_OK, wxEVT_COMMAND_BUTTON_CLICKED,
          (wxObjectEventFunction) & VirtualTxtDialog::OnOk);
// appends event handler for radioboxes
  Connect(ID_VIRTTXT_QUOTE, wxEVT_COMMAND_RADIOBOX_SELECTED,
          (wxObjectEventFunction) & VirtualTxtDialog::OnQuote);
  Connect(ID_VIRTTXT_SEPARATOR, wxEVT_COMMAND_RADIOBOX_SELECTED,
          (wxObjectEventFunction) & VirtualTxtDialog::OnSeparator);
  Connect(ID_VIRTTXT_POINT, wxEVT_COMMAND_RADIOBOX_SELECTED,
          (wxObjectEventFunction) & VirtualTxtDialog::OnDecimalSeparator);
}

void VirtualTxtDialog::OnDecimalSeparator(wxCommandEvent & event)

























{
//
// POINT selection changed
//
  wxRadioBox *decimalSeparatorCtrl =
    (wxRadioBox *) FindWindow(ID_VIRTTXT_POINT);
  switch (decimalSeparatorCtrl->GetSelection())
    {
      case 0:
        DecimalPointIsComma = false;
        break;
      case 1:
        DecimalPointIsComma = true;
        break;
    };
}


void VirtualTxtDialog::OnQuote(wxCommandEvent & event)
{
//
// QUOTE selection changed
//
  wxRadioBox *separatorCtrl = (wxRadioBox *) FindWindow(ID_VIRTTXT_QUOTE);
  switch (separatorCtrl->GetSelection())
    {
      case 0:
        TextSeparator = '"';
        break;
      case 1:
        TextSeparator = '\'';
        break;
    };
}


void VirtualTxtDialog::OnSeparator(wxCommandEvent & event)
{
//
// SEPARATOR selection changed
//
  wxTextCtrl *charSeparatorCtrl =
    (wxTextCtrl *) FindWindow(ID_VIRTTXT_CHARSEPARATOR);
  wxRadioBox *separatorCtrl = (wxRadioBox *) FindWindow(ID_VIRTTXT_SEPARATOR);

  switch (separatorCtrl->GetSelection())
    {
      case 0:
        Separator = '\t';
        charSeparatorCtrl->SetValue(wxT("TAB"));
        break;
      case 1:
        Separator = ' ';
        charSeparatorCtrl->SetValue(wxT("SP"));
        break;
      case 2:
        Separator = ',';
        charSeparatorCtrl->SetValue(wxT(","));
        break;
      case 3:
        Separator = ':';
        charSeparatorCtrl->SetValue(wxT(":"));
        break;
      case 4:
        Separator = ';';
        charSeparatorCtrl->SetValue(wxT(";"));
        break;
      case 5:
        Separator = '|';
        charSeparatorCtrl->SetValue(wxT("|"));
        break;
    };
  if (separatorCtrl->GetSelection() == 5)
    charSeparatorCtrl->Enable(true);
  else
    charSeparatorCtrl->Enable(false);
}


void VirtualTxtDialog::OnOk(wxCommandEvent & event)
{
//
// all done: 
//
  wxTextCtrl *tableCtrl = (wxTextCtrl *) FindWindow(ID_VIRTTXT_TABLE);
  Table = tableCtrl->GetValue();
  if (Table.Len() < 1)
    {
      wxMessageBox(wxT("You must specify the TABLE NAME !!!"),
                   wxT("spatialite-gui"), wxOK | wxICON_WARNING, this);
      return;
    }
  if (MainFrame->TableAlreadyExists(Table) == true)
    {
      wxMessageBox(wxT("a table name '") + Table + wxT("' already exists"),











                   wxT("spatialite-gui"), wxOK | wxICON_WARNING, this);
      return;
    }
  wxListBox *charsetCtrl = (wxListBox *) FindWindow(ID_VIRTTXT_CHARSET);
  int idSel = charsetCtrl->GetSelection();
  if (idSel == wxNOT_FOUND)
    {

      wxMessageBox(wxT("you must select some Charset Encoding from the list"),
                   wxT("spatialite-gui"), wxOK | wxICON_WARNING, this);
      return;
    }
  wxString *charsets = MainFrame->GetCharsets();
  Charset = *(charsets + idSel);
  wxRadioBox *separatorCtrl = (wxRadioBox *) FindWindow(ID_VIRTTXT_SEPARATOR);

  if (separatorCtrl->GetSelection() == 5)
    {
      wxTextCtrl *charSeparatorCtrl =
        (wxTextCtrl *) FindWindow(ID_VIRTTXT_CHARSEPARATOR);
      wxString separator = charSeparatorCtrl->GetValue();
      if (separator.Len() != 1)
        {
          wxMessageBox(wxT
                       ("you must specificy a single char as Custom Column Separator"),
                       wxT("spatialite-gui"), wxOK | wxICON_WARNING, this);

          return;
        }
      char dummy[64];
      strcpy(dummy, separator.ToUTF8());
      Separator = *dummy;
    }
  wxDialog::EndModal(wxID_OK);
}


bool LoadTxtDialog::Create(MyFrame * parent, wxString & path, wxString & table,
                           wxString & defCs)
{
//
// creating the dialog
//
  MainFrame = parent;
  Path = path;
  Table = table;
  Default = defCs;
  if (wxDialog::Create(parent, wxID_ANY, wxT("Load CSV/TXT")) == false)
    return false;
// populates individual controls
  CreateControls();
// sets dialog sizer

  GetSizer()->Fit(this);
  GetSizer()->SetSizeHints(this);
// centers the dialog window
  Centre();
  return true;
}


void LoadTxtDialog::CreateControls()
{
//
// creating individual control and setting initial values
//
  FirstLineTitles = true;
  Separator = '\t';
  TextSeparator = '"';
  DecimalPointIsComma = false;
  wxBoxSizer *topSizer = new wxBoxSizer(wxVERTICAL);
  this->SetSizer(topSizer);
  wxBoxSizer *boxSizer = new wxBoxSizer(wxVERTICAL);
  topSizer->Add(boxSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
// first row: the CSV/TXT path
  wxBoxSizer *pathSizer = new wxBoxSizer(wxHORIZONTAL);
  boxSizer->Add(pathSizer, 0, wxALIGN_RIGHT | wxALL, 0);
  wxStaticText *pathLabel = new wxStaticText(this, wxID_STATIC, wxT("&Path:"));

  pathSizer->Add(pathLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
  wxTextCtrl *pathValue = new wxTextCtrl(this, wxID_STATIC,
                                         Path, wxDefaultPosition,
                                         wxSize(350, 22), wxTE_READONLY);
  pathSizer->Add(pathValue, 0, wxALIGN_RIGHT | wxALL, 5);
// second row: TABLE name
  wxBoxSizer *tableSizer = new wxBoxSizer(wxHORIZONTAL);
  boxSizer->Add(tableSizer, 0, wxALIGN_RIGHT | wxALL, 0);
  wxStaticText *tableLabel =
    new wxStaticText(this, wxID_STATIC, wxT("&Table name:"));
  tableSizer->Add(tableLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
  wxTextCtrl *tableCtrl = new wxTextCtrl(this, ID_LDTXT_TABLE, Table,
                                         wxDefaultPosition, wxSize(350,
                                                                   22));
  tableSizer->Add(tableCtrl, 0, wxALIGN_RIGHT | wxALL, 5);
// second row: OPTIONS
  wxBoxSizer *optSizer = new wxBoxSizer(wxHORIZONTAL);
  boxSizer->Add(optSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 0);
  wxBoxSizer *modeSizer = new wxBoxSizer(wxVERTICAL);
  optSizer->Add(modeSizer, 0, wxALIGN_CENTER_VERTICAL | wxALL, 0);
  wxBoxSizer *mode1Sizer = new wxBoxSizer(wxHORIZONTAL);
  modeSizer->Add(mode1Sizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 0);
  wxCheckBox *titleCtrl = new wxCheckBox(this, ID_LDTXT_TITLES,
                                         wxT
                                         ("First line contains column names"),
                                         wxDefaultPosition, wxDefaultSize);
  titleCtrl->SetValue(true);
  mode1Sizer->Add(titleCtrl, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
  wxStaticBox *sepBox = new wxStaticBox(this, wxID_STATIC,
                                        wxT("Separators"),
                                        wxDefaultPosition, wxDefaultSize);
  wxBoxSizer *sepSizer = new wxStaticBoxSizer(sepBox, wxVERTICAL);
  modeSizer->Add(sepSizer, 0, wxALIGN_LEFT | wxALL, 0);
  wxBoxSizer *mode2Sizer = new wxBoxSizer(wxHORIZONTAL);
  sepSizer->Add(mode2Sizer, 0, wxALIGN_LEFT | wxALL, 0);
  wxString quotes[2];
  quotes[0] = wxT("&Double \"");
  quotes[1] = wxT("&Single '");
  wxRadioBox *textSeparatorBox = new wxRadioBox(this, ID_LDTXT_QUOTE,

                                                wxT("&Text separator: quotes"),
                                                wxDefaultPosition,
                                                wxDefaultSize, 2,
                                                quotes, 2,
                                                wxRA_SPECIFY_COLS);
  mode2Sizer->Add(textSeparatorBox, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
  wxBoxSizer *mode3Sizer = new wxBoxSizer(wxHORIZONTAL);
  sepSizer->Add(mode3Sizer, 0, wxALIGN_LEFT | wxALL, 0);
  wxString separators[6];
  separators[0] = wxT("&Tab");
  separators[1] = wxT("&Space");
  separators[2] = wxT("Co&mma ,");
  separators[3] = wxT("&Colon :");
  separators[4] = wxT("S&emicolon ;");
  separators[5] = wxT("&Other");
  wxRadioBox *separatorBox = new wxRadioBox(this, ID_LDTXT_SEPARATOR,
                                            wxT("&Column separator"),
                                            wxDefaultPosition, wxDefaultSize,
                                            6,
                                            separators, 2,
                                            wxRA_SPECIFY_COLS);
  mode3Sizer->Add(separatorBox, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
  wxBoxSizer *mode4Sizer = new wxBoxSizer(wxHORIZONTAL);
  sepSizer->Add(mode4Sizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 0);
  wxStaticText *charSeparatorLabel = new wxStaticText(this, wxID_STATIC,

                                                      wxT("&Custom separator:"),
                                                      wxDefaultPosition,
                                                      wxDefaultSize, 0);
  mode4Sizer->Add(charSeparatorLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
  wxTextCtrl *dummy =
    new wxTextCtrl(this, ID_LDTXT_CHARSEPARATOR, wxT("Dummy Text pq"),
                   wxDefaultPosition,
                   wxDefaultSize, 0);
  wxSize sz = dummy->GetSize();
  delete dummy;
  sz.SetWidth(40);
  wxTextCtrl *charSeparatorCtrl =
    new wxTextCtrl(this, ID_LDTXT_CHARSEPARATOR, wxT("TAB"),
                   wxDefaultPosition, sz, 0);
  charSeparatorCtrl->SetMaxLength(1);
  charSeparatorCtrl->Enable(false);
  mode4Sizer->Add(charSeparatorCtrl, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
  wxBoxSizer *mode5Sizer = new wxBoxSizer(wxHORIZONTAL);
  sepSizer->Add(mode5Sizer, 0, wxALIGN_LEFT | wxALL, 0);
  wxString points[2];
  points[0] = wxT("&Point .");
  points[1] = wxT("&Comma ,");
  wxRadioBox *decimalSeparatorBox = new wxRadioBox(this, ID_LDTXT_POINT,

                                                   wxT("&Decimal separator"),
                                                   wxDefaultPosition,
                                                   wxDefaultSize, 2,
                                                   points, 2,
                                                   wxRA_SPECIFY_COLS);
  mode5Sizer->Add(decimalSeparatorBox, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);

// third row: CHARSET
  wxStaticBox *charsetBox = new wxStaticBox(this, wxID_STATIC,
                                            wxT("Charset Encoding"),
                                            wxDefaultPosition,
                                            wxDefaultSize);
  wxBoxSizer *charsetSizer = new wxStaticBoxSizer(charsetBox, wxHORIZONTAL);
  optSizer->Add(charsetSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
  wxListBox *charsetCtrl = new wxListBox(this, ID_LDTXT_CHARSET,
                                         wxDefaultPosition, wxDefaultSize,
                                         MainFrame->GetCharsetsLen(),
                                         MainFrame->GetCharsetsNames(),
                                         wxLB_SINGLE);
  charsetCtrl->
    SetFont(wxFont
            (8, wxFONTFAMILY_MODERN, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL));

  int idSel = MainFrame->GetCharsetIndex(Default);
  if (idSel != wxNOT_FOUND)
    charsetCtrl->SetSelection(idSel);
  charsetSizer->Add(charsetCtrl, 0, wxALIGN_CENTER_VERTICAL | wxALL, 0);
// OK - CANCEL buttons
  wxBoxSizer *okCancelBox = new wxBoxSizer(wxHORIZONTAL);
  boxSizer->Add(okCancelBox, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 0);
  wxButton *ok = new wxButton(this, wxID_OK, wxT("&OK"));
  okCancelBox->Add(ok, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
  wxButton *cancel = new wxButton(this, wxID_CANCEL, wxT("&Cancel"));
  okCancelBox->Add(cancel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
// appends event handler for OK button
  Connect(wxID_OK, wxEVT_COMMAND_BUTTON_CLICKED,
          (wxObjectEventFunction) & LoadTxtDialog::OnOk);
// appends event handler for radioboxes
  Connect(ID_LDTXT_QUOTE, wxEVT_COMMAND_RADIOBOX_SELECTED,
          (wxObjectEventFunction) & LoadTxtDialog::OnQuote);
  Connect(ID_LDTXT_SEPARATOR, wxEVT_COMMAND_RADIOBOX_SELECTED,
          (wxObjectEventFunction) & LoadTxtDialog::OnSeparator);
  Connect(ID_LDTXT_POINT, wxEVT_COMMAND_RADIOBOX_SELECTED,
          (wxObjectEventFunction) & LoadTxtDialog::OnDecimalSeparator);
}


void LoadTxtDialog::OnDecimalSeparator(wxCommandEvent & event)
{
//
// POINT selection changed
//
  wxRadioBox *decimalSeparatorCtrl = (wxRadioBox *) FindWindow(ID_LDTXT_POINT);

  switch (decimalSeparatorCtrl->GetSelection())
    {
      case 0:
        DecimalPointIsComma = false;
        break;
      case 1:
        DecimalPointIsComma = true;
        break;
    };
}


void LoadTxtDialog::OnQuote(wxCommandEvent & event)
{
//
// QUOTE selection changed
//
  wxRadioBox *separatorCtrl = (wxRadioBox *) FindWindow(ID_LDTXT_QUOTE);
  switch (separatorCtrl->GetSelection())
    {
      case 0:
        TextSeparator = '"';
        break;
      case 1:
        TextSeparator = '\'';
        break;
    };
}


void LoadTxtDialog::OnSeparator(wxCommandEvent & event)
{
//
// SEPARATOR selection changed
//
  wxTextCtrl *charSeparatorCtrl =
    (wxTextCtrl *) FindWindow(ID_LDTXT_CHARSEPARATOR);
  wxRadioBox *separatorCtrl = (wxRadioBox *) FindWindow(ID_LDTXT_SEPARATOR);
  switch (separatorCtrl->GetSelection())
    {
      case 0:
        Separator = '\t';
        charSeparatorCtrl->SetValue(wxT("TAB"));
        break;
      case 1:
        Separator = ' ';
        charSeparatorCtrl->SetValue(wxT("SP"));
        break;
      case 2:
        Separator = ',';
        charSeparatorCtrl->SetValue(wxT(","));
        break;
      case 3:
        Separator = ':';
        charSeparatorCtrl->SetValue(wxT(":"));
        break;
      case 4:
        Separator = ';';
        charSeparatorCtrl->SetValue(wxT(";"));
        break;
      case 5:
        Separator = '|';
        charSeparatorCtrl->SetValue(wxT("|"));
        break;
    };
  if (separatorCtrl->GetSelection() == 5)
    charSeparatorCtrl->Enable(true);
  else
    charSeparatorCtrl->Enable(false);
}

void LoadTxtDialog::OnOk(wxCommandEvent & event)
{
//
// all done: 
//
  wxTextCtrl *tableCtrl = (wxTextCtrl *) FindWindow(ID_LDTXT_TABLE);
  Table = tableCtrl->GetValue();
  if (Table.Len() < 1)
    {
      wxMessageBox(wxT("You must specify the TABLE NAME !!!"),
                   wxT("spatialite-gui"), wxOK | wxICON_WARNING, this);
      return;
    }
  if (MainFrame->TableAlreadyExists(Table) == true)
    {
      wxMessageBox(wxT("a table name '") + Table + wxT("' already exists"),
                   wxT("spatialite-gui"), wxOK | wxICON_WARNING, this);
      return;
    }
  wxListBox *charsetCtrl = (wxListBox *) FindWindow(ID_LDTXT_CHARSET);
  int idSel = charsetCtrl->GetSelection();
  if (idSel == wxNOT_FOUND)
    {
      wxMessageBox(wxT("you must select some Charset Encoding from the list"),
                   wxT("spatialite-gui"), wxOK | wxICON_WARNING, this);
      return;
    }
  wxString *charsets = MainFrame->GetCharsets();
  Charset = *(charsets + idSel);
  wxRadioBox *separatorCtrl = (wxRadioBox *) FindWindow(ID_LDTXT_SEPARATOR);
  if (separatorCtrl->GetSelection() == 5)
    {
      wxTextCtrl *charSeparatorCtrl =
        (wxTextCtrl *) FindWindow(ID_LDTXT_CHARSEPARATOR);
      wxString separator = charSeparatorCtrl->GetValue();
      if (separator.Len() != 1)
        {
          wxMessageBox(wxT
                       ("you must specificy a single char as Custom Column Separator"),
                       wxT("spatialite-gui"), wxOK | wxICON_WARNING, this);
          return;
        }
      char dummy[64];
      strcpy(dummy, separator.ToUTF8());
      Separator = *dummy;
    }
  wxDialog::EndModal(wxID_OK);
}

bool LoadShpDialog::Create(MyFrame * parent, wxString & path, wxString & table,
                           int srid, wxString & column, wxString & defCs)
{
//
// creating the dialog
//
  MainFrame = parent;
  Path = path;
  Table = table;
  Srid = srid;
  Column = column;
  Default = defCs;
  if (wxDialog::Create(parent, wxID_ANY, wxT("Load Shapefile")) == false)
    return false;
// populates individual controls
  CreateControls();
// sets dialog sizer
  GetSizer()->Fit(this);
  GetSizer()->SetSizeHints(this);
// centers the dialog window
  Centre();
  return true;
}

void LoadShpDialog::CreateControls()
{
//
// creating individual control and setting initial values
//
  wxBoxSizer *topSizer = new wxBoxSizer(wxVERTICAL);
  this->SetSizer(topSizer);
  wxBoxSizer *boxSizer = new wxBoxSizer(wxVERTICAL);
  topSizer->Add(boxSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
// first row: the Shapefile path
  wxBoxSizer *pathSizer = new wxBoxSizer(wxHORIZONTAL);
  boxSizer->Add(pathSizer, 0, wxALIGN_RIGHT | wxALL, 0);
  wxStaticText *pathLabel = new wxStaticText(this, wxID_STATIC, wxT("&Path:"));
  pathSizer->Add(pathLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
  wxTextCtrl *pathValue = new wxTextCtrl(this, wxID_STATIC,
                                         Path, wxDefaultPosition,
                                         wxSize(350, 22), wxTE_READONLY);
  pathSizer->Add(pathValue, 0, wxALIGN_RIGHT | wxALL, 5);
// second row: TABLE name
  wxBoxSizer *tableSizer = new wxBoxSizer(wxHORIZONTAL);
  boxSizer->Add(tableSizer, 0, wxALIGN_RIGHT | wxALL, 0);
  wxStaticText *tableLabel =
    new wxStaticText(this, wxID_STATIC, wxT("&Table name:"));
  tableSizer->Add(tableLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
  wxTextCtrl *tableCtrl = new wxTextCtrl(this, ID_LDSHP_TABLE, Table,
                                         wxDefaultPosition, wxSize(350,
                                                                   22));
  tableSizer->Add(tableCtrl, 0, wxALIGN_RIGHT | wxALL, 5);
// third row: GEOMETRY COLUMN name
  wxBoxSizer *colSizer = new wxBoxSizer(wxHORIZONTAL);
  boxSizer->Add(colSizer, 0, wxALIGN_RIGHT | wxALL, 0);
  wxStaticText *colLabel =
    new wxStaticText(this, wxID_STATIC, wxT("&GeomColumn name:"));
  colSizer->Add(colLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
  wxTextCtrl *colCtrl = new wxTextCtrl(this, ID_LDSHP_COLUMN, Column,
                                       wxDefaultPosition, wxSize(350, 22));
  colSizer->Add(colCtrl, 0, wxALIGN_RIGHT | wxALL, 5);
// fourth row: SRID
  wxBoxSizer *sridSizer = new wxBoxSizer(wxHORIZONTAL);
  boxSizer->Add(sridSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 0);
  wxStaticText *sridLabel = new wxStaticText(this, wxID_STATIC, wxT("&SRID:"));
  sridSizer->Add(sridLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
  wxSpinCtrl *sridCtrl = new wxSpinCtrl(this, ID_LDSHP_SRID, wxEmptyString,
                                        wxDefaultPosition, wxSize(80, 20),
                                        wxSP_ARROW_KEYS,
                                        -1, 40000, Srid);
  sridSizer->Add(sridCtrl, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
// fifth row: CHARSET
  wxStaticBox *charsetBox = new wxStaticBox(this, wxID_STATIC,
                                            wxT("Charset Encoding"),
                                            wxDefaultPosition,
                                            wxDefaultSize);
  wxBoxSizer *charsetSizer = new wxStaticBoxSizer(charsetBox, wxHORIZONTAL);
  sridSizer->Add(charsetSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
  wxListBox *charsetCtrl = new wxListBox(this, ID_LDSHP_CHARSET,
                                         wxDefaultPosition, wxDefaultSize,
                                         MainFrame->GetCharsetsLen(),
                                         MainFrame->GetCharsetsNames(),
                                         wxLB_SINGLE);
  charsetCtrl->
    SetFont(wxFont
            (8, wxFONTFAMILY_MODERN, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL));
  int idSel = MainFrame->GetCharsetIndex(Default);
  if (idSel != wxNOT_FOUND)
    charsetCtrl->SetSelection(idSel);
  charsetSizer->Add(charsetCtrl, 0, wxALIGN_CENTER_VERTICAL | wxALL, 0);
// OK - CANCEL buttons
  wxBoxSizer *okCancelBox = new wxBoxSizer(wxHORIZONTAL);
  boxSizer->Add(okCancelBox, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 0);
  wxButton *ok = new wxButton(this, wxID_OK, wxT("&OK"));
  okCancelBox->Add(ok, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
  wxButton *cancel = new wxButton(this, wxID_CANCEL, wxT("&Cancel"));
  okCancelBox->Add(cancel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
// appends event handler for OK button
  Connect(wxID_OK, wxEVT_COMMAND_BUTTON_CLICKED,
          (wxObjectEventFunction) & LoadShpDialog::OnOk);
}

void LoadShpDialog::OnOk(wxCommandEvent & event)
{
//
// all done: 
//
  wxTextCtrl *tableCtrl = (wxTextCtrl *) FindWindow(ID_LDSHP_TABLE);
  Table = tableCtrl->GetValue();
  if (Table.Len() < 1)
    {
      wxMessageBox(wxT("You must specify the TABLE NAME !!!"),
                   wxT("spatialite-gui"), wxOK | wxICON_WARNING, this);
      return;
    }
  if (MainFrame->TableAlreadyExists(Table) == true)
    {
      wxMessageBox(wxT("a table name '") + Table + wxT("' already exists"),
                   wxT("spatialite-gui"), wxOK | wxICON_WARNING, this);
      return;
    }
  wxTextCtrl *columnCtrl = (wxTextCtrl *) FindWindow(ID_LDSHP_COLUMN);
  Column = columnCtrl->GetValue();
  if (Column.Len() < 1)
    {
      wxMessageBox(wxT("You must specify the GEOMETRY COLUMN NAME !!!"),
                   wxT("spatialite-gui"), wxOK | wxICON_WARNING, this);
      return;
    }
  wxSpinCtrl *sridCtrl = (wxSpinCtrl *) FindWindow(ID_LDSHP_SRID);
  Srid = sridCtrl->GetValue();
  if (MainFrame->SridNotExists(Srid) == true)
    {
      wxMessageBox(wxT("invalid SRID value"), wxT("spatialite-gui"),
                   wxOK | wxICON_WARNING, this);
      return;
    }
  wxListBox *charsetCtrl = (wxListBox *) FindWindow(ID_LDSHP_CHARSET);
  int idSel = charsetCtrl->GetSelection();
  if (idSel == wxNOT_FOUND)
    {
      wxMessageBox(wxT("you must select some Charset Encoding from the list"),
                   wxT("spatialite-gui"), wxOK | wxICON_WARNING, this);
      return;
    }
  wxString *charsets = MainFrame->GetCharsets();
  Charset = *(charsets + idSel);
  wxDialog::EndModal(wxID_OK);
}

bool DumpShpDialog::Create(MyFrame * parent, wxString & path, wxString & table,
                           wxString & column, wxString & defCs)
{
//
// creating the dialog
//
  MainFrame = parent;
  Path = path;
  Table = table;
  Column = column;
  Default = defCs;
  if (wxDialog::Create(parent, wxID_ANY, wxT("Dump Shapefile")) == false)
    return false;
// populates individual controls
  CreateControls();
// sets dialog sizer
  GetSizer()->Fit(this);
  GetSizer()->SetSizeHints(this);
// centers the dialog window
  Centre();
  return true;
}

void DumpShpDialog::CreateControls()
{
//
// creating individual control and setting initial values
//
  wxBoxSizer *topSizer = new wxBoxSizer(wxVERTICAL);
  this->SetSizer(topSizer);
  wxBoxSizer *boxSizer = new wxBoxSizer(wxVERTICAL);
  topSizer->Add(boxSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
// first row: the Shapefile path
  wxBoxSizer *pathSizer = new wxBoxSizer(wxHORIZONTAL);
  boxSizer->Add(pathSizer, 0, wxALIGN_RIGHT | wxALL, 0);
  wxStaticText *pathLabel = new wxStaticText(this, wxID_STATIC, wxT("&Path:"));
  pathSizer->Add(pathLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
  wxTextCtrl *pathValue = new wxTextCtrl(this, wxID_STATIC,
                                         Path, wxDefaultPosition,
                                         wxSize(350, 22), wxTE_READONLY);
  pathSizer->Add(pathValue, 0, wxALIGN_RIGHT | wxALL, 5);
// second row: TABLE name
  wxBoxSizer *tableSizer = new wxBoxSizer(wxHORIZONTAL);
  boxSizer->Add(tableSizer, 0, wxALIGN_RIGHT | wxALL, 0);
  wxStaticText *tableLabel =
    new wxStaticText(this, wxID_STATIC, wxT("&Table name:"));
  tableSizer->Add(tableLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
  wxTextCtrl *tableCtrl = new wxTextCtrl(this, wxID_STATIC, Table,
                                         wxDefaultPosition, wxSize(350,
                                                                   22));
  tableCtrl->Enable(false);
  tableSizer->Add(tableCtrl, 0, wxALIGN_RIGHT | wxALL, 5);
// third row: GEOMETRY COLUMN name
  wxBoxSizer *colSizer = new wxBoxSizer(wxHORIZONTAL);
  boxSizer->Add(colSizer, 0, wxALIGN_RIGHT | wxALL, 0);
  wxStaticText *colLabel =
    new wxStaticText(this, wxID_STATIC, wxT("&GeomColumn name:"));
  colSizer->Add(colLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
  wxTextCtrl *colCtrl = new wxTextCtrl(this, wxID_STATIC, Column,
                                       wxDefaultPosition, wxSize(350, 22));
  colCtrl->Enable(false);
  colSizer->Add(colCtrl, 0, wxALIGN_RIGHT | wxALL, 5);
// fourth row: CHARSET
  wxBoxSizer *csSizer = new wxBoxSizer(wxHORIZONTAL);
  boxSizer->Add(csSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 0);
  wxStaticBox *charsetBox = new wxStaticBox(this, wxID_STATIC,
                                            wxT("Charset Encoding"),
                                            wxDefaultPosition,
                                            wxDefaultSize);
  wxBoxSizer *charsetSizer = new wxStaticBoxSizer(charsetBox, wxHORIZONTAL);
  csSizer->Add(charsetSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
  wxListBox *charsetCtrl = new wxListBox(this, ID_DMPSHP_CHARSET,
                                         wxDefaultPosition, wxDefaultSize,
                                         MainFrame->GetCharsetsLen(),
                                         MainFrame->GetCharsetsNames(),
                                         wxLB_SINGLE);
  charsetCtrl->
    SetFont(wxFont
            (8, wxFONTFAMILY_MODERN, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL));
  int idSel = MainFrame->GetCharsetIndex(Default);
  if (idSel != wxNOT_FOUND)
    charsetCtrl->SetSelection(idSel);
  charsetSizer->Add(charsetCtrl, 0, wxALIGN_CENTER_VERTICAL | wxALL, 0);
// OK - CANCEL buttons
  wxBoxSizer *okCancelBox = new wxBoxSizer(wxHORIZONTAL);
  boxSizer->Add(okCancelBox, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 0);
  wxButton *ok = new wxButton(this, wxID_OK, wxT("&OK"));
  okCancelBox->Add(ok, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
  wxButton *cancel = new wxButton(this, wxID_CANCEL, wxT("&Cancel"));
  okCancelBox->Add(cancel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
// appends event handler for OK button
  Connect(wxID_OK, wxEVT_COMMAND_BUTTON_CLICKED,
          (wxObjectEventFunction) & DumpShpDialog::OnOk);
}

void DumpShpDialog::OnOk(wxCommandEvent & event)
{
//
// all done: 
//
  wxListBox *charsetCtrl = (wxListBox *) FindWindow(ID_DMPSHP_CHARSET);
  int idSel = charsetCtrl->GetSelection();
  if (idSel == wxNOT_FOUND)
    {
      wxMessageBox(wxT("you must select some Charset Encoding from the list"),
                   wxT("spatialite-gui"), wxOK | wxICON_WARNING, this);
      return;
    }
  wxString *charsets = MainFrame->GetCharsets();
  Charset = *(charsets + idSel);
  wxDialog::EndModal(wxID_OK);
}

bool DumpTxtDialog::Create(MyFrame * parent, wxString & path, wxString & target,
                           wxString & defCs)
{
//
// creating the dialog
//
  MainFrame = parent;
  Path = path;
  Default = defCs;
  if (wxDialog::Create(parent, wxID_ANY, wxT("Dump ") + target) == false)
    return false;
// populates individual controls
  CreateControls();
// sets dialog sizer
  GetSizer()->Fit(this);
  GetSizer()->SetSizeHints(this);
// centers the dialog window
  Centre();
  return true;
}

void DumpTxtDialog::CreateControls()
{
//
// creating individual control and setting initial values
//
  wxBoxSizer *topSizer = new wxBoxSizer(wxVERTICAL);
  this->SetSizer(topSizer);
  wxBoxSizer *boxSizer = new wxBoxSizer(wxVERTICAL);
  topSizer->Add(boxSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
// first row: the Shapefile path
  wxBoxSizer *pathSizer = new wxBoxSizer(wxHORIZONTAL);
  boxSizer->Add(pathSizer, 0, wxALIGN_RIGHT | wxALL, 0);
  wxStaticText *pathLabel = new wxStaticText(this, wxID_STATIC, wxT("&Path:"));
  pathSizer->Add(pathLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
  wxTextCtrl *pathValue = new wxTextCtrl(this, wxID_STATIC,
                                         Path, wxDefaultPosition,
                                         wxSize(350, 22), wxTE_READONLY);
  pathSizer->Add(pathValue, 0, wxALIGN_RIGHT | wxALL, 5);
// second row: CHARSET
  wxBoxSizer *csSizer = new wxBoxSizer(wxHORIZONTAL);
  boxSizer->Add(csSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 0);
  wxStaticBox *charsetBox = new wxStaticBox(this, wxID_STATIC,
                                            wxT("Charset Encoding"),
                                            wxDefaultPosition,
                                            wxDefaultSize);
  wxBoxSizer *charsetSizer = new wxStaticBoxSizer(charsetBox, wxHORIZONTAL);
  csSizer->Add(charsetSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
  wxListBox *charsetCtrl = new wxListBox(this, ID_DMPTXT_CHARSET,
                                         wxDefaultPosition, wxDefaultSize,
                                         MainFrame->GetCharsetsLen(),
                                         MainFrame->GetCharsetsNames(),
                                         wxLB_SINGLE);
  charsetCtrl->
    SetFont(wxFont
            (8, wxFONTFAMILY_MODERN, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL));
  int idSel = MainFrame->GetCharsetIndex(Default);
  if (idSel != wxNOT_FOUND)
    charsetCtrl->SetSelection(idSel);
  charsetSizer->Add(charsetCtrl, 0, wxALIGN_CENTER_VERTICAL | wxALL, 0);
// OK - CANCEL buttons
  wxBoxSizer *okCancelBox = new wxBoxSizer(wxHORIZONTAL);
  boxSizer->Add(okCancelBox, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 0);
  wxButton *ok = new wxButton(this, wxID_OK, wxT("&OK"));
  okCancelBox->Add(ok, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
  wxButton *cancel = new wxButton(this, wxID_CANCEL, wxT("&Cancel"));
  okCancelBox->Add(cancel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
// appends event handler for OK button
  Connect(wxID_OK, wxEVT_COMMAND_BUTTON_CLICKED,
          (wxObjectEventFunction) & DumpTxtDialog::OnOk);
}

void DumpTxtDialog::OnOk(wxCommandEvent & event)
{
//
// all done: 
//
  wxListBox *charsetCtrl = (wxListBox *) FindWindow(ID_DMPTXT_CHARSET);
  int idSel = charsetCtrl->GetSelection();
  if (idSel == wxNOT_FOUND)
    {
      wxMessageBox(wxT("you must select some Charset Encoding from the list"),
                   wxT("spatialite-gui"), wxOK | wxICON_WARNING, this);
      return;
    }
  wxString *charsets = MainFrame->GetCharsets();
  Charset = *(charsets + idSel);
  wxDialog::EndModal(wxID_OK);
}

bool SqlScriptDialog::Create(MyFrame * parent, wxString & path,
                             wxString & defCs)
{
//
// creating the dialog
//
  MainFrame = parent;
  Path = path;
  Default = defCs;
  if (wxDialog::Create(parent, wxID_ANY, wxT("SQL script execute")) == false)
    return false;
// populates individual controls
  CreateControls();
// sets dialog sizer
  GetSizer()->Fit(this);
  GetSizer()->SetSizeHints(this);
// centers the dialog window
  Centre();
  return true;
}

void SqlScriptDialog::CreateControls()
{
//
// creating individual control and setting initial values
//
  wxBoxSizer *topSizer = new wxBoxSizer(wxVERTICAL);
  this->SetSizer(topSizer);
  wxBoxSizer *boxSizer = new wxBoxSizer(wxVERTICAL);
  topSizer->Add(boxSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
// first row: the SQL script path
  wxBoxSizer *pathSizer = new wxBoxSizer(wxHORIZONTAL);
  boxSizer->Add(pathSizer, 0, wxALIGN_RIGHT | wxALL, 0);
  wxStaticText *pathLabel = new wxStaticText(this, wxID_STATIC, wxT("&Path:"));
  pathSizer->Add(pathLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
  wxTextCtrl *pathValue = new wxTextCtrl(this, wxID_STATIC,
                                         Path, wxDefaultPosition,
                                         wxSize(350, 22), wxTE_READONLY);
  pathSizer->Add(pathValue, 0, wxALIGN_RIGHT | wxALL, 5);
// second row: CHARSET
  wxBoxSizer *csSizer = new wxBoxSizer(wxHORIZONTAL);
  boxSizer->Add(csSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 0);
  wxStaticBox *charsetBox = new wxStaticBox(this, wxID_STATIC,
                                            wxT("Charset Encoding"),
                                            wxDefaultPosition,
                                            wxDefaultSize);
  wxBoxSizer *charsetSizer = new wxStaticBoxSizer(charsetBox, wxHORIZONTAL);
  csSizer->Add(charsetSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
  wxListBox *charsetCtrl = new wxListBox(this, ID_SCRIPT_CHARSET,
                                         wxDefaultPosition, wxDefaultSize,
                                         MainFrame->GetCharsetsLen(),
                                         MainFrame->GetCharsetsNames(),
                                         wxLB_SINGLE);
  charsetCtrl->
    SetFont(wxFont
            (8, wxFONTFAMILY_MODERN, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL));
  int idSel = MainFrame->GetCharsetIndex(Default);
  if (idSel != wxNOT_FOUND)
    charsetCtrl->SetSelection(idSel);
  charsetSizer->Add(charsetCtrl, 0, wxALIGN_CENTER_VERTICAL | wxALL, 0);
// OK - CANCEL buttons
  wxBoxSizer *okCancelBox = new wxBoxSizer(wxHORIZONTAL);
  boxSizer->Add(okCancelBox, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 0);
  wxButton *ok = new wxButton(this, wxID_OK, wxT("&OK"));
  okCancelBox->Add(ok, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
  wxButton *cancel = new wxButton(this, wxID_CANCEL, wxT("&Cancel"));
  okCancelBox->Add(cancel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
// appends event handler for OK button
  Connect(wxID_OK, wxEVT_COMMAND_BUTTON_CLICKED,
          (wxObjectEventFunction) & SqlScriptDialog::OnOk);
}

void SqlScriptDialog::OnOk(wxCommandEvent & event)
{
//
// all done: 
//
  wxListBox *charsetCtrl = (wxListBox *) FindWindow(ID_SCRIPT_CHARSET);
  int idSel = charsetCtrl->GetSelection();
  if (idSel == wxNOT_FOUND)
    {
      wxMessageBox(wxT("you must select some Charset Encoding from the list"),
                   wxT("spatialite-gui"), wxOK | wxICON_WARNING, this);
      return;
    }
  wxString *charsets = MainFrame->GetCharsets();
  Charset = *(charsets + idSel);
  wxDialog::EndModal(wxID_OK);
}

bool DefaultCharsetDialog::Create(MyFrame * parent, wxString & charset,
                                  bool ask)
{
//
// creating the dialog
//
  MainFrame = parent;
  Charset = charset;
  AskCharset = ask;
  if (wxDialog::Create(parent, wxID_ANY, wxT("Charset settings")) == false)
    return false;
// populates individual controls
  CreateControls();
// sets dialog sizer
  GetSizer()->Fit(this);
  GetSizer()->SetSizeHints(this);
// centers the dialog window
  Centre();
  return true;
}

void DefaultCharsetDialog::CreateControls()
{
//
// creating individual control and setting initial values
//
  wxBoxSizer *topSizer = new wxBoxSizer(wxVERTICAL);
  this->SetSizer(topSizer);
  wxBoxSizer *boxSizer = new wxBoxSizer(wxVERTICAL);
  topSizer->Add(boxSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
// first row: the DEFAULT CHARSET
  wxBoxSizer *csSizer = new wxBoxSizer(wxHORIZONTAL);
  boxSizer->Add(csSizer, 0, wxALIGN_RIGHT | wxALL, 0);
  wxStaticBox *charsetBox = new wxStaticBox(this, wxID_STATIC,
                                            wxT("Default Output Charset"),
                                            wxDefaultPosition,
                                            wxDefaultSize);
  wxBoxSizer *charsetSizer = new wxStaticBoxSizer(charsetBox, wxVERTICAL);
  csSizer->Add(charsetSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
  wxListBox *charsetCtrl = new wxListBox(this, ID_DFLT_CHARSET,
                                         wxDefaultPosition, wxDefaultSize,
                                         MainFrame->GetCharsetsLen(),
                                         MainFrame->GetCharsetsNames(),
                                         wxLB_SINGLE);
  charsetCtrl->
    SetFont(wxFont
            (8, wxFONTFAMILY_MODERN, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL));
  int idSel = MainFrame->GetCharsetIndex(Charset);
  if (idSel != wxNOT_FOUND)
    charsetCtrl->SetSelection(idSel);
  charsetSizer->Add(charsetCtrl, 0, wxALIGN_CENTER_VERTICAL | wxALL, 0);
// second row: the ASK CHARSET
  wxBoxSizer *askSizer = new wxBoxSizer(wxHORIZONTAL);
  charsetSizer->Add(askSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 0);
  wxCheckBox *askCtrl = new wxCheckBox(this, ID_DFLT_ASK,
                                       wxT("Ask output charset every time"),
                                       wxDefaultPosition, wxDefaultSize);
  askCtrl->SetValue(AskCharset);
  askSizer->Add(askCtrl, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
// OK - CANCEL buttons
  wxBoxSizer *okCancelBox = new wxBoxSizer(wxHORIZONTAL);
  boxSizer->Add(okCancelBox, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 0);
  wxButton *ok = new wxButton(this, wxID_OK, wxT("&OK"));
  okCancelBox->Add(ok, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
  wxButton *cancel = new wxButton(this, wxID_CANCEL, wxT("&Cancel"));
  okCancelBox->Add(cancel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
// appends event handler for OK button
  Connect(wxID_OK, wxEVT_COMMAND_BUTTON_CLICKED,
          (wxObjectEventFunction) & DefaultCharsetDialog::OnOk);
}

void DefaultCharsetDialog::OnOk(wxCommandEvent & event)
{
//
// all done: 
//
  wxListBox *charsetCtrl = (wxListBox *) FindWindow(ID_DFLT_CHARSET);
  int idSel = charsetCtrl->GetSelection();
  if (idSel == wxNOT_FOUND)
    {
      wxMessageBox(wxT
                   ("you must select some Default Charset Encoding from the list"),
                   wxT("spatialite-gui"), wxOK | wxICON_WARNING, this);
      return;
    }
  wxString *charsets = MainFrame->GetCharsets();
  Charset = *(charsets + idSel);
  wxCheckBox *askCtrl = (wxCheckBox *) FindWindow(ID_DFLT_ASK);
  AskCharset = askCtrl->GetValue();
  wxDialog::EndModal(wxID_OK);
}

bool RecoverDialog::Create(MyFrame * parent, wxString & table,
                           wxString & column)
{
//
// creating the dialog
//
  MainFrame = parent;
  Table = table;
  Column = column;
  Srid = -1;
  if (wxDialog::Create(parent, wxID_ANY, wxT("Recover Geometry Column")) ==
      false)
    return false;
// populates individual controls
  CreateControls();
// sets dialog sizer
  GetSizer()->Fit(this);
  GetSizer()->SetSizeHints(this);
// centers the dialog window
  Centre();
  return true;
}

void RecoverDialog::CreateControls()
{
//
// creating individual control and setting initial values
//
  wxBoxSizer *topSizer = new wxBoxSizer(wxVERTICAL);
  this->SetSizer(topSizer);
  wxBoxSizer *boxSizer = new wxBoxSizer(wxVERTICAL);
  topSizer->Add(boxSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
// First row: TABLE name
  wxBoxSizer *tableSizer = new wxBoxSizer(wxHORIZONTAL);
  boxSizer->Add(tableSizer, 0, wxALIGN_RIGHT | wxALL, 0);
  wxStaticText *tableLabel =
    new wxStaticText(this, wxID_STATIC, wxT("&Table name:"));
  tableSizer->Add(tableLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
  wxTextCtrl *tableCtrl = new wxTextCtrl(this, wxID_ANY, Table,
                                         wxDefaultPosition, wxSize(350, 22),
                                         wxTE_READONLY);
  tableCtrl->Enable(false);
  tableSizer->Add(tableCtrl, 0, wxALIGN_RIGHT | wxALL, 5);
// second row: GEOMETRY COLUMN name
  wxBoxSizer *colSizer = new wxBoxSizer(wxHORIZONTAL);
  boxSizer->Add(colSizer, 0, wxALIGN_RIGHT | wxALL, 0);
  wxStaticText *colLabel =
    new wxStaticText(this, wxID_STATIC, wxT("&Column name:"));
  colSizer->Add(colLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
  wxTextCtrl *colCtrl = new wxTextCtrl(this, wxID_ANY, Column,
                                       wxDefaultPosition, wxSize(350, 22),
                                       wxTE_READONLY);
  colCtrl->Enable(false);
  colSizer->Add(colCtrl, 0, wxALIGN_RIGHT | wxALL, 5);
// third row: SRID
  wxBoxSizer *sridSizer = new wxBoxSizer(wxHORIZONTAL);
  boxSizer->Add(sridSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 0);
  wxStaticText *sridLabel = new wxStaticText(this, wxID_STATIC, wxT("&SRID:"));
  sridSizer->Add(sridLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
  wxSpinCtrl *sridCtrl = new wxSpinCtrl(this, ID_RCVR_SRID, wxEmptyString,
                                        wxDefaultPosition, wxSize(80, 20),
                                        wxSP_ARROW_KEYS,
                                        -1, 40000, Srid);
  sridSizer->Add(sridCtrl, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
// fourth row: GEOMETRY TYPE
  wxStaticBox *typeBox = new wxStaticBox(this, wxID_STATIC,
                                         wxT("Geometry Type"),
                                         wxDefaultPosition, wxDefaultSize);
  wxBoxSizer *typeSizer = new wxStaticBoxSizer(typeBox, wxHORIZONTAL);
  sridSizer->Add(typeSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
  wxString types[7];
  types[0] = wxT("POINT");
  types[1] = wxT("MULTIPOINT");
  types[2] = wxT("LINESTRING");
  types[3] = wxT("MULTILINESTRING");
  types[4] = wxT("POLYGON");
  types[5] = wxT("MULTIPOLYGON");
  types[6] = wxT("GEOMETRYCOLLECTION");
  wxListBox *geomType = new wxListBox(this, ID_RCVR_TYPE,
                                      wxDefaultPosition, wxDefaultSize, 7,
                                      types, wxLB_SINGLE);
  typeSizer->Add(geomType, 0, wxALIGN_CENTER_VERTICAL | wxALL, 0);
// OK - CANCEL buttons
  wxBoxSizer *okCancelBox = new wxBoxSizer(wxHORIZONTAL);
  boxSizer->Add(okCancelBox, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 0);
  wxButton *ok = new wxButton(this, wxID_OK, wxT("&OK"));
  okCancelBox->Add(ok, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
  wxButton *cancel = new wxButton(this, wxID_CANCEL, wxT("&Cancel"));
  okCancelBox->Add(cancel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
// appends event handler for OK button
  Connect(wxID_OK, wxEVT_COMMAND_BUTTON_CLICKED,
          (wxObjectEventFunction) & RecoverDialog::OnOk);
}

void RecoverDialog::OnOk(wxCommandEvent & event)
{
//
// all done: 
//
  wxSpinCtrl *sridCtrl = (wxSpinCtrl *) FindWindow(ID_RCVR_SRID);
  wxListBox *geomType = (wxListBox *) FindWindow(ID_RCVR_TYPE);
  Srid = sridCtrl->GetValue();
  if (MainFrame->SridNotExists(Srid) == true)
    {
      wxMessageBox(wxT("invalid SRID value"), wxT("spatialite-gui"),
                   wxOK | wxICON_WARNING, this);
      return;
    }
  Type = geomType->GetStringSelection();
  if (Type.Len() < 1)
    {
      wxMessageBox(wxT("you must select some Geometry Type from the list"),
                   wxT("spatialite-gui"), wxOK | wxICON_WARNING, this);
      return;
    }
  wxDialog::EndModal(wxID_OK);
}

bool SetSridDialog::Create(MyFrame * parent, wxString & table,
                           wxString & column)
{
//
// creating the dialog
//
  MainFrame = parent;
  Table = table;
  Column = column;
  OldSrid = -1;
  Srid = -1;
  if (wxDialog::Create(parent, wxID_ANY, wxT("Changing SRID")) == false)
    return false;
// populates individual controls
  CreateControls();
// sets dialog sizer
  GetSizer()->Fit(this);
  GetSizer()->SetSizeHints(this);
// centers the dialog window
  Centre();
  return true;
}

void SetSridDialog::CreateControls()
{
//
// creating individual control and setting initial values
//
  wxBoxSizer *topSizer = new wxBoxSizer(wxVERTICAL);
  this->SetSizer(topSizer);
  wxBoxSizer *boxSizer = new wxBoxSizer(wxVERTICAL);
  topSizer->Add(boxSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
// First row: TABLE name
  wxBoxSizer *tableSizer = new wxBoxSizer(wxHORIZONTAL);
  boxSizer->Add(tableSizer, 0, wxALIGN_RIGHT | wxALL, 0);
  wxStaticText *tableLabel =
    new wxStaticText(this, wxID_STATIC, wxT("&Table name:"));
  tableSizer->Add(tableLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
  wxTextCtrl *tableCtrl = new wxTextCtrl(this, wxID_ANY, Table,
                                         wxDefaultPosition, wxSize(350, 22),
                                         wxTE_READONLY);
  tableCtrl->Enable(false);
  tableSizer->Add(tableCtrl, 0, wxALIGN_RIGHT | wxALL, 5);
// second row: GEOMETRY COLUMN name
  wxBoxSizer *colSizer = new wxBoxSizer(wxHORIZONTAL);
  boxSizer->Add(colSizer, 0, wxALIGN_RIGHT | wxALL, 0);
  wxStaticText *colLabel =
    new wxStaticText(this, wxID_STATIC, wxT("&Column name:"));
  colSizer->Add(colLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
  wxTextCtrl *colCtrl = new wxTextCtrl(this, wxID_ANY, Column,
                                       wxDefaultPosition, wxSize(350, 22),
                                       wxTE_READONLY);
  colCtrl->Enable(false);
  colSizer->Add(colCtrl, 0, wxALIGN_RIGHT | wxALL, 5);
// third row: SRID
  wxBoxSizer *mySizer = new wxBoxSizer(wxHORIZONTAL);
  boxSizer->Add(mySizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 0);
  wxBoxSizer *oldSridSizer = new wxBoxSizer(wxHORIZONTAL);
  mySizer->Add(oldSridSizer, 0, wxALIGN_LEFT | wxALL, 0);
  wxStaticText *oldSridLabel =
    new wxStaticText(this, wxID_STATIC, wxT("&old SRID:"));
  oldSridSizer->Add(oldSridLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
  wxSpinCtrl *oldSridCtrl = new wxSpinCtrl(this, ID_SRID_OLD, wxEmptyString,
                                           wxDefaultPosition, wxSize(80,
                                                                     20),
                                           wxSP_ARROW_KEYS,
                                           -1, 40000, OldSrid);
  oldSridSizer->Add(oldSridCtrl, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
// fourth row: SRID
  wxBoxSizer *sridSizer = new wxBoxSizer(wxHORIZONTAL);
  mySizer->Add(sridSizer, 0, wxALIGN_RIGHT | wxLEFT, 20);
  wxStaticText *sridLabel =
    new wxStaticText(this, wxID_STATIC, wxT("&new SRID:"));
  sridSizer->Add(sridLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
  wxSpinCtrl *sridCtrl = new wxSpinCtrl(this, ID_SRID_SRID, wxEmptyString,
                                        wxDefaultPosition, wxSize(80, 20),
                                        wxSP_ARROW_KEYS,
                                        -1, 40000, Srid);
  sridSizer->Add(sridCtrl, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
// OK - CANCEL buttons
  wxBoxSizer *okCancelBox = new wxBoxSizer(wxHORIZONTAL);
  boxSizer->Add(okCancelBox, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 0);
  wxButton *ok = new wxButton(this, wxID_OK, wxT("&OK"));
  okCancelBox->Add(ok, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
  wxButton *cancel = new wxButton(this, wxID_CANCEL, wxT("&Cancel"));
  okCancelBox->Add(cancel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
// appends event handler for OK button
  Connect(wxID_OK, wxEVT_COMMAND_BUTTON_CLICKED,
          (wxObjectEventFunction) & SetSridDialog::OnOk);
}

void SetSridDialog::OnOk(wxCommandEvent & event)
{
//
// all done: 
//
  wxSpinCtrl *oldSridCtrl = (wxSpinCtrl *) FindWindow(ID_SRID_OLD);
  wxSpinCtrl *sridCtrl = (wxSpinCtrl *) FindWindow(ID_SRID_SRID);
  OldSrid = oldSridCtrl->GetValue();








  Srid = sridCtrl->GetValue();
  wxDialog::EndModal(wxID_OK);
}




bool SearchSridDialog::Create(MyFrame * parent)
{
//
// creating the dialog
//
  MainFrame = parent;
  if (wxDialog::Create(parent, wxID_ANY, wxT("Searching a SRID by its name")) ==
































































































      false)
    return false;
// populates individual controls
  CreateControls();
// sets dialog sizer

  GetSizer()->Fit(this);
  GetSizer()->SetSizeHints(this);
// centers the dialog window
  Centre();
  return true;
}


void SearchSridDialog::CreateControls()
{
//
// creating individual control and setting initial values
//
  wxBoxSizer *topSizer = new wxBoxSizer(wxVERTICAL);
  this->SetSizer(topSizer);
  wxBoxSizer *boxSizer = new wxBoxSizer(wxVERTICAL);
  topSizer->Add(boxSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);

// First row: SEARCH string
  wxBoxSizer *searchSizer = new wxBoxSizer(wxHORIZONTAL);
  boxSizer->Add(searchSizer, 0, wxALIGN_RIGHT | wxALL, 0);
  wxStaticText *searchLabel =
    new wxStaticText(this, wxID_STATIC, wxT("&Search:"));
  searchSizer->Add(searchLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);

  wxTextCtrl *searchCtrl = new wxTextCtrl(this, ID_SEARCH, wxT(""),
                                          wxDefaultPosition, wxSize(150,

                                                                    22));
  searchSizer->Add(searchCtrl, 0, wxALIGN_RIGHT | wxALL, 5);





















// OK - CANCEL buttons
  wxBoxSizer *okCancelBox = new wxBoxSizer(wxHORIZONTAL);
  boxSizer->Add(okCancelBox, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 0);
  wxButton *ok = new wxButton(this, wxID_OK, wxT("&OK"));
  okCancelBox->Add(ok, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
  wxButton *cancel = new wxButton(this, wxID_CANCEL, wxT("&Cancel"));
  okCancelBox->Add(cancel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
// appends event handler for OK button
  Connect(wxID_OK, wxEVT_COMMAND_BUTTON_CLICKED,
          (wxObjectEventFunction) & SearchSridDialog::OnOk);
}


void SearchSridDialog::OnOk(wxCommandEvent & event)
{
//
// all done: 
//
  wxTextCtrl *searchCtrl = (wxTextCtrl *) FindWindow(ID_SEARCH);
  String = searchCtrl->GetValue();
  if (String.Len() < 1)
    {
      wxMessageBox(wxT("You must specify a string to search for !!!"),

                   wxT("spatialite-gui"), wxOK | wxICON_WARNING, this);
      return;
    }


  wxDialog::EndModal(wxID_OK);
}



bool HelpDialog::Create(MyFrame * parent)
{
//
// creating the dialog
//
  MainFrame = parent;
  if (wxDialog::Create(parent, wxID_ANY, wxT("SQLite + SpatiaLite help"),
                       wxDefaultPosition, wxDefaultSize,
                       wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER) == false)
    return false;
// populates individual controls
  CreateControls();
// sets dialog sizer
  GetSizer()->Fit(this);
  GetSizer()->SetSizeHints(this);
// centers the dialog window
  MainFrame->OpenHelpPane();
  Centre();
// setting up an event handler [dialog closing]
  Connect(wxID_ANY, wxEVT_CLOSE_WINDOW,
          (wxObjectEventFunction) & HelpDialog::OnClose);
  return true;
}

void HelpDialog::OnClose(wxCloseEvent & event)
{
//
// this window has been closed
//
  MainFrame->CloseHelpPane();
  Destroy();
}

void HelpDialog::CreateControls()
{
//
// creating individual control and setting initial values
//
  wxBoxSizer *topSizer = new wxBoxSizer(wxVERTICAL);
  this->SetSizer(topSizer);
  wxBoxSizer *boxSizer = new wxBoxSizer(wxVERTICAL);
  topSizer->Add(boxSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
  wxHtmlWindow *helpWin = new wxHtmlWindow(this, ID_HELP_HTML,
                                           wxDefaultPosition, wxSize(400,
                                                                     200));
  wxString html;
  MainFrame->GetHelp(html);
  helpWin->SetPage(html);
  topSizer->Add(helpWin, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
  Connect(wxID_ANY, wxEVT_SIZE, (wxObjectEventFunction) & HelpDialog::OnSize);
}

void HelpDialog::OnSize(wxSizeEvent & event)
{
//
// this window has changed its size
//
  wxSize sz = GetClientSize();
  wxHtmlWindow *helpWin = (wxHtmlWindow *) FindWindow(ID_HELP_HTML);
  helpWin->SetSize(sz.GetWidth() - 6, sz.GetHeight() - 6);
}

bool NetworkDialog::Create(MyFrame * parent)
{
//
// creating the dialog
//
  MainFrame = parent;
  FromColumn = wxT("");
  ToColumn = wxT("");
  GeomColumn = wxT("");
  GeomLength = true;
  CostColumn = wxT("");
  Bidirectional = true;
  OneWays = false;
  OneWayFromTo = wxT("");
  OneWayToFrom = wxT("");
  if (wxDialog::Create(parent, wxID_ANY, wxT("Build Network")) == false)
    return false;
// populates individual controls
  CreateControls();
// sets dialog sizer
  GetSizer()->Fit(this);
  GetSizer()->SetSizeHints(this);
// centers the dialog window
  Centre();
  return true;
}

void NetworkDialog::CreateControls()
{
//
// creating individual control and setting initial values
//
  wxBoxSizer *topSizer = new wxBoxSizer(wxVERTICAL);
  this->SetSizer(topSizer);
  wxBoxSizer *boxSizer = new wxBoxSizer(wxVERTICAL);
  topSizer->Add(boxSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
  wxBoxSizer *row0Sizer = new wxBoxSizer(wxHORIZONTAL);
  boxSizer->Add(row0Sizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
// first row: first column: the Main TABLE
  wxBoxSizer *tableSizer = new wxBoxSizer(wxHORIZONTAL);
  row0Sizer->Add(tableSizer, 0, wxALIGN_CENTRE_VERTICAL | wxALL, 0);
  wxStaticBox *tableBox = new wxStaticBox(this, wxID_STATIC,
                                          wxT("Base Table [graph]"),
                                          wxDefaultPosition,
                                          wxDefaultSize);
  wxBoxSizer *tableNameSizer = new wxStaticBoxSizer(tableBox, wxVERTICAL);
  tableSizer->Add(tableNameSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
  int nTables;
  wxString *tables = MainFrame->GetTables(&nTables);
  wxListBox *tableCtrl = new wxListBox(this, ID_NET_TABLE,
                                       wxDefaultPosition, wxDefaultSize,
                                       nTables, tables, wxLB_SINGLE);
  delete[]tables;
  tableNameSizer->Add(tableCtrl, 0, wxALIGN_CENTER_VERTICAL | wxALL, 0);
  wxSize size = tableCtrl->GetSize();
  size.SetHeight(size.GetHeight() / 2);
// first row: second column: the NodeFrom COLUMN
  wxBoxSizer *netSizer = new wxBoxSizer(wxHORIZONTAL);
  row0Sizer->Add(netSizer, 0, wxALIGN_RIGHT | wxALL, 0);
  wxStaticBox *netBox = new wxStaticBox(this, wxID_STATIC,
                                        wxT("Network configuration"),
                                        wxDefaultPosition,
                                        wxDefaultSize);
  wxBoxSizer *colSizer = new wxStaticBoxSizer(netBox, wxVERTICAL);
  netSizer->Add(colSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
  wxBoxSizer *row1Sizer = new wxBoxSizer(wxHORIZONTAL);
  colSizer->Add(row1Sizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
  wxBoxSizer *fromSizer = new wxBoxSizer(wxHORIZONTAL);
  row1Sizer->Add(fromSizer, 0, wxALIGN_RIGHT | wxALL, 0);
  wxStaticBox *fromBox = new wxStaticBox(this, wxID_STATIC,
                                         wxT("NodeFrom Column"),
                                         wxDefaultPosition,
                                         wxDefaultSize);
  wxBoxSizer *fromColSizer = new wxStaticBoxSizer(fromBox, wxVERTICAL);
  fromSizer->Add(fromColSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
  wxListBox *fromCtrl = new wxListBox(this, ID_NET_FROM,
                                      wxDefaultPosition, size,
                                      0, NULL, wxLB_SINGLE);
  fromCtrl->Enable(false);
  fromColSizer->Add(fromCtrl, 0, wxALIGN_CENTER_VERTICAL | wxALL, 0);
// first row: third column: the NodeTo COLUMN
  wxBoxSizer *toSizer = new wxBoxSizer(wxHORIZONTAL);
  row1Sizer->Add(toSizer, 0, wxALIGN_RIGHT | wxALL, 0);
  wxStaticBox *toBox = new wxStaticBox(this, wxID_STATIC,
                                       wxT("NodeTo Column"),
                                       wxDefaultPosition,
                                       wxDefaultSize);
  wxBoxSizer *toColSizer = new wxStaticBoxSizer(toBox, wxVERTICAL);
  toSizer->Add(toColSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
  wxListBox *toCtrl = new wxListBox(this, ID_NET_TO,
                                    wxDefaultPosition, size,
                                    0, NULL, wxLB_SINGLE);
  toCtrl->Enable(false);
  toColSizer->Add(toCtrl, 0, wxALIGN_CENTER_VERTICAL | wxALL, 0);
// first row: fourth column: the Geometry COLUMN
  wxBoxSizer *geoSizer = new wxBoxSizer(wxHORIZONTAL);
  row1Sizer->Add(geoSizer, 0, wxALIGN_RIGHT | wxALL, 0);
  wxStaticBox *geoBox = new wxStaticBox(this, wxID_STATIC,
                                        wxT("Geometry Column"),
                                        wxDefaultPosition,
                                        wxDefaultSize);
  wxBoxSizer *geoColSizer = new wxStaticBoxSizer(geoBox, wxVERTICAL);
  toSizer->Add(geoColSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
  wxListBox *geoCtrl = new wxListBox(this, ID_NET_GEOM,
                                     wxDefaultPosition, size,
                                     0, NULL, wxLB_SINGLE);
  geoCtrl->Enable(false);
  geoColSizer->Add(geoCtrl, 0, wxALIGN_CENTER_VERTICAL | wxALL, 0);
// second row: first column: UNIDIRECTIONAL / BIDIRECTIONAL
  wxBoxSizer *row2Sizer = new wxBoxSizer(wxHORIZONTAL);
  colSizer->Add(row2Sizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
  wxString dirs[2];
  dirs[0] = wxT("&Uni-Directional");
  dirs[1] = wxT("&Bi-Directional");
  wxRadioBox *dirSel = new wxRadioBox(this, ID_NET_BIDIR,
                                      wxT("&Arc connections"),
                                      wxDefaultPosition,
                                      wxDefaultSize, 2,
                                      dirs, 2,
                                      wxRA_SPECIFY_ROWS);
  dirSel->SetSelection(1);
  dirSel->Enable(false);
  row2Sizer->Add(dirSel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 0);
// second row: second column: the COST is GLenth selection
  wxString costs[2];
  costs[0] = wxT("&Using GLength(Geometry) as Cost");
  costs[1] = wxT("&Using Cost Column");
  wxRadioBox *costSel = new wxRadioBox(this, ID_NET_LENGTH,
                                       wxT("&Cost type"),
                                       wxDefaultPosition,
                                       wxDefaultSize, 2,
                                       costs, 2,
                                       wxRA_SPECIFY_ROWS);
  costSel->SetSelection(0);
  costSel->Enable(false);
  row2Sizer->Add(costSel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
// second row: third column: the COST COLUMN    
  wxBoxSizer *costSizer = new wxBoxSizer(wxHORIZONTAL);
  row2Sizer->Add(costSizer, 0, wxALIGN_RIGHT | wxALL, 0);
  wxStaticBox *costBox = new wxStaticBox(this, wxID_STATIC,
                                         wxT("Cost Column"),
                                         wxDefaultPosition,
                                         wxDefaultSize);
  wxBoxSizer *costColSizer = new wxStaticBoxSizer(costBox, wxVERTICAL);
  costSizer->Add(costColSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
  wxListBox *costCtrl = new wxListBox(this, ID_NET_COST,
                                      wxDefaultPosition, size,
                                      0, NULL, wxLB_SINGLE);
  costCtrl->Enable(false);
  costColSizer->Add(costCtrl, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
// third row: second column: the OneWay Selection
  wxBoxSizer *row3Sizer = new wxBoxSizer(wxHORIZONTAL);
  colSizer->Add(row3Sizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
  wxString oneWays[2];
  oneWays[0] = wxT("&Not using OneWay Columns");
  oneWays[1] = wxT("&Using OneWay Columns");
  wxRadioBox *oneWaySel = new wxRadioBox(this, ID_NET_ONEWAY,
                                         wxT("&OneWays"),
                                         wxDefaultPosition,
                                         wxDefaultSize, 2,
                                         oneWays, 2,
                                         wxRA_SPECIFY_ROWS);
  oneWaySel->SetSelection(0);
  oneWaySel->Enable(false);
  row3Sizer->Add(oneWaySel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
// third row: second column: the OneWay FromTo COLUMN
  wxBoxSizer *fromToSizer = new wxBoxSizer(wxHORIZONTAL);
  row3Sizer->Add(fromToSizer, 0, wxALIGN_RIGHT | wxALL, 0);
  wxStaticBox *fromToBox = new wxStaticBox(this, wxID_STATIC,
                                           wxT("From -> To Column"),
                                           wxDefaultPosition,
                                           wxDefaultSize);
  wxBoxSizer *fromToColSizer = new wxStaticBoxSizer(fromToBox, wxVERTICAL);
  fromToSizer->Add(fromToColSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
  wxListBox *fromToCtrl = new wxListBox(this, ID_NET_FROM_TO,
                                        wxDefaultPosition, size,
                                        0, NULL, wxLB_SINGLE);
  fromToCtrl->Enable(false);
  fromToColSizer->Add(fromToCtrl, 0, wxALIGN_CENTER_VERTICAL | wxALL, 0);
// fourth row: second column: the OneWay To From COLUMN
  wxBoxSizer *toFromSizer = new wxBoxSizer(wxHORIZONTAL);
  row3Sizer->Add(toFromSizer, 0, wxALIGN_RIGHT | wxALL, 0);
  wxStaticBox *toFromBox = new wxStaticBox(this, wxID_STATIC,
                                           wxT("To -> From Column"),
                                           wxDefaultPosition,
                                           wxDefaultSize);
  wxBoxSizer *toFromColSizer = new wxStaticBoxSizer(toFromBox, wxVERTICAL);
  toFromSizer->Add(toFromColSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
  wxListBox *toFromCtrl = new wxListBox(this, ID_NET_TO_FROM,
                                        wxDefaultPosition, size,
                                        0, NULL, wxLB_SINGLE);
  toFromCtrl->Enable(false);
  toFromColSizer->Add(toFromCtrl, 0, wxALIGN_CENTER_VERTICAL | wxALL, 0);
// OK - CANCEL buttons
  wxBoxSizer *okCancelBox = new wxBoxSizer(wxHORIZONTAL);
  boxSizer->Add(okCancelBox, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 0);
  wxButton *ok = new wxButton(this, wxID_OK, wxT("&OK"));
  okCancelBox->Add(ok, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
  wxButton *cancel = new wxButton(this, wxID_CANCEL, wxT("&Cancel"));
  okCancelBox->Add(cancel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
// appends event handler for OK button
  Connect(wxID_OK, wxEVT_COMMAND_BUTTON_CLICKED,
          (wxObjectEventFunction) & NetworkDialog::OnOk);
// appends event handlers for radio buttons etc
  Connect(ID_NET_TABLE, wxEVT_COMMAND_LISTBOX_SELECTED,
          (wxObjectEventFunction) & NetworkDialog::OnTable);
  Connect(ID_NET_BIDIR, wxEVT_COMMAND_RADIOBOX_SELECTED,
          (wxObjectEventFunction) & NetworkDialog::OnDirection);
  Connect(ID_NET_LENGTH, wxEVT_COMMAND_RADIOBOX_SELECTED,
          (wxObjectEventFunction) & NetworkDialog::OnCost);
  Connect(ID_NET_ONEWAY, wxEVT_COMMAND_RADIOBOX_SELECTED,
          (wxObjectEventFunction) & NetworkDialog::OnOneWay);
}

void NetworkDialog::OnTable(wxCommandEvent & event)
{
//
// TABLE selection changed
//
  wxListBox *tableCtrl = (wxListBox *) FindWindow(ID_NET_TABLE);
  TableName = tableCtrl->GetStringSelection();
  int n_cols;
  wxString *columns = MainFrame->GetColumnNames(TableName, &n_cols);
  wxListBox *fromCtrl = (wxListBox *) FindWindow(ID_NET_FROM);
  fromCtrl->Clear();
  fromCtrl->InsertItems(n_cols, columns, 0);
  fromCtrl->Enable(true);
  wxListBox *toCtrl = (wxListBox *) FindWindow(ID_NET_TO);
  toCtrl->Clear();
  toCtrl->InsertItems(n_cols, columns, 0);
  toCtrl->Enable(true);
  wxListBox *geomCtrl = (wxListBox *) FindWindow(ID_NET_GEOM);
  geomCtrl->Clear();
  geomCtrl->InsertItems(n_cols, columns, 0);
  geomCtrl->Enable(true);
  wxListBox *costCtrl = (wxListBox *) FindWindow(ID_NET_COST);
  costCtrl->Clear();
  costCtrl->InsertItems(n_cols, columns, 0);
  costCtrl->Enable(false);
  wxListBox *fromToCtrl = (wxListBox *) FindWindow(ID_NET_FROM_TO);
  fromToCtrl->Clear();
  fromToCtrl->InsertItems(n_cols, columns, 0);
  fromToCtrl->Enable(false);
  wxListBox *toFromCtrl = (wxListBox *) FindWindow(ID_NET_TO_FROM);
  toFromCtrl->Clear();
  toFromCtrl->InsertItems(n_cols, columns, 0);
  toFromCtrl->Enable(false);
  wxRadioBox *dirSel = (wxRadioBox *) FindWindow(ID_NET_BIDIR);
  Bidirectional = true;
  dirSel->SetSelection(1);
  dirSel->Enable(true);
  wxRadioBox *costSel = (wxRadioBox *) FindWindow(ID_NET_LENGTH);
  GeomLength = true;
  costSel->SetSelection(0);
  costSel->Enable(true);
  wxRadioBox *oneWaySel = (wxRadioBox *) FindWindow(ID_NET_ONEWAY);
  OneWays = false;
  oneWaySel->SetSelection(0);
  oneWaySel->Enable(true);
}

void NetworkDialog::OnDirection(wxCommandEvent & event)
{
//
// BIDIRECTIONAL radio box
//
  wxRadioBox *oneWaySel = (wxRadioBox *) FindWindow(ID_NET_ONEWAY);
  wxRadioBox *dirSel = (wxRadioBox *) FindWindow(ID_NET_BIDIR);
  wxListBox *fromToCtrl = (wxListBox *) FindWindow(ID_NET_FROM_TO);
  wxListBox *toFromCtrl = (wxListBox *) FindWindow(ID_NET_TO_FROM);
  if (Bidirectional == true)
    {
      Bidirectional = false;
      dirSel->SetSelection(0);
      OneWays = false;
      oneWaySel->SetSelection(0);
      oneWaySel->Enable(false);
      fromToCtrl->Enable(false);
      toFromCtrl->Enable(false);
  } else
    {
      Bidirectional = true;
      dirSel->SetSelection(1);
      OneWays = false;
      oneWaySel->SetSelection(0);
      oneWaySel->Enable(true);
      fromToCtrl->Enable(false);
      toFromCtrl->Enable(false);
    }
}

void NetworkDialog::OnCost(wxCommandEvent & event)
{
//
// COST radio box
//
  wxRadioBox *costSel = (wxRadioBox *) FindWindow(ID_NET_LENGTH);
  wxListBox *costCtrl = (wxListBox *) FindWindow(ID_NET_COST);
  if (GeomLength == true)
    {
      GeomLength = false;
      costSel->SetSelection(1);
      costCtrl->Enable(true);
  } else
    {
      GeomLength = true;
      costSel->SetSelection(0);
      costCtrl->Enable(false);
    }
}

void NetworkDialog::OnOneWay(wxCommandEvent & event)
{
//
// OneWay radio box
//
  wxRadioBox *oneWaySel = (wxRadioBox *) FindWindow(ID_NET_ONEWAY);
  wxListBox *fromToCtrl = (wxListBox *) FindWindow(ID_NET_FROM_TO);
  wxListBox *toFromCtrl = (wxListBox *) FindWindow(ID_NET_TO_FROM);
  if (OneWays == true)
    {
      OneWays = false;
      oneWaySel->SetSelection(0);
      fromToCtrl->Enable(false);
      toFromCtrl->Enable(false);
  } else
    {
      OneWays = true;
      oneWaySel->SetSelection(1);
      fromToCtrl->Enable(true);
      toFromCtrl->Enable(true);
    }
}

void NetworkDialog::OnOk(wxCommandEvent & event)
{
//
// all done: 
//
  wxListBox *tableCtrl = (wxListBox *) FindWindow(ID_NET_TABLE);
  TableName = tableCtrl->GetStringSelection();
  if (TableName.Len() < 1)
    {
      wxMessageBox(wxT("You must select some TABLE NAME !!!"),
                   wxT("spatialite-gui"), wxOK | wxICON_WARNING, this);
      return;
    }
  wxListBox *fromCtrl = (wxListBox *) FindWindow(ID_NET_FROM);
  FromColumn = fromCtrl->GetStringSelection();
  if (FromColumn.Len() < 1)
    {
      wxMessageBox(wxT("You must select some 'NodeFrom' COLUMN !!!"),
                   wxT("spatialite-gui"), wxOK | wxICON_WARNING, this);
      return;
    }
  wxListBox *toCtrl = (wxListBox *) FindWindow(ID_NET_TO);
  ToColumn = toCtrl->GetStringSelection();
  if (ToColumn.Len() < 1)
    {
      wxMessageBox(wxT("You must select some 'NodeTo' COLUMN !!!"),
                   wxT("spatialite-gui"), wxOK | wxICON_WARNING, this);
      return;
    }
  wxListBox *geomCtrl = (wxListBox *) FindWindow(ID_NET_GEOM);
  GeomColumn = geomCtrl->GetStringSelection();
  if (GeomColumn.Len() < 1)
    {
      wxMessageBox(wxT("You must select some 'Geometry' COLUMN !!!"),
                   wxT("spatialite-gui"), wxOK | wxICON_WARNING, this);
      return;
    }
  if (GeomLength == true)
    CostColumn = wxT("");
  else
    {
      wxListBox *costCtrl = (wxListBox *) FindWindow(ID_NET_COST);
      CostColumn = costCtrl->GetStringSelection();
      if (CostColumn.Len() < 1)
        {
          wxMessageBox(wxT("You must select some 'Cost' COLUMN !!!"),
                       wxT("spatialite-gui"), wxOK | wxICON_WARNING, this);
          return;
        }
    }
  if (Bidirectional == true && OneWays == true)
    {
      wxListBox *fromToCtrl = (wxListBox *) FindWindow(ID_NET_FROM_TO);
      OneWayFromTo = fromToCtrl->GetStringSelection();
      if (OneWayFromTo.Len() < 1)
        {
          wxMessageBox(wxT("You must select some 'OneWay From->To' COLUMN !!!"),
                       wxT("spatialite-gui"), wxOK | wxICON_WARNING, this);
          return;
        }
      wxListBox *toFromCtrl = (wxListBox *) FindWindow(ID_NET_TO_FROM);
      OneWayToFrom = toFromCtrl->GetStringSelection();
      if (OneWayToFrom.Len() < 1)
        {
          wxMessageBox(wxT("You must select some 'OneWay To->From' COLUMN !!!"),
                       wxT("spatialite-gui"), wxOK | wxICON_WARNING, this);
          return;
        }
  } else
    {
      OneWayFromTo = wxT("");
      OneWayToFrom = wxT("");
    }
  wxDialog::EndModal(wxID_OK);
}

bool ExifDialog::Create(MyFrame * parent, wxString & dir_path,
                        wxString & img_path)
{
//
// creating the dialog
//
  MainFrame = parent;
  DirPath = dir_path;
  ImgPath = img_path;
  Folder = false;
  Metadata = true;
  GpsOnly = false;
  if (wxDialog::Create(parent, wxID_ANY, wxT("Import EXIF Photos")) == false)
    return false;
// populates individual controls
  CreateControls();
// sets dialog sizer
  GetSizer()->Fit(this);
  GetSizer()->SetSizeHints(this);
// centers the dialog window
  Centre();
  return true;
}

void ExifDialog::CreateControls()
{
//
// creating individual control and setting initial values
//
  wxBoxSizer *topSizer = new wxBoxSizer(wxVERTICAL);
  this->SetSizer(topSizer);
  wxBoxSizer *boxSizer = new wxBoxSizer(wxVERTICAL);
  topSizer->Add(boxSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
  wxBoxSizer *row0Sizer = new wxBoxSizer(wxVERTICAL);
  boxSizer->Add(row0Sizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
// first row: the path and file/folder selection
  wxBoxSizer *pathSizer = new wxBoxSizer(wxHORIZONTAL);
  row0Sizer->Add(pathSizer, 0, wxALIGN_CENTRE_VERTICAL | wxALL, 0);
  wxStaticBox *pathBox = new wxStaticBox(this, wxID_STATIC,
                                         wxT("Import from source"),
                                         wxDefaultPosition,
                                         wxDefaultSize);
  wxBoxSizer *pthSizer = new wxStaticBoxSizer(pathBox, wxVERTICAL);
  pathSizer->Add(pthSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
  wxStaticText *pathLabel = new wxStaticText(this, ID_EXIF_PATH, ImgPath);
  pthSizer->Add(pathLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 0);
  wxString imgFolder[2];
  imgFolder[0] = wxT("Import &selected image only");
  imgFolder[1] = wxT("Import &any EXIF from selected folder");
  wxRadioBox *imgFolderSel = new wxRadioBox(this, ID_EXIF_FOLDER,
                                            wxT("&Source selection"),
                                            wxDefaultPosition,
                                            wxDefaultSize, 2,
                                            imgFolder, 2,
                                            wxRA_SPECIFY_ROWS);
  imgFolderSel->SetSelection(0);
  pthSizer->Add(imgFolderSel, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
// second row: the metadata and gps-only selection
  wxBoxSizer *modeSizer = new wxBoxSizer(wxHORIZONTAL);
  boxSizer->Add(modeSizer, 0, wxALIGN_CENTRE_HORIZONTAL | wxALL, 0);
  wxString metadata[2];
  metadata[0] = wxT("Feed full EXIF &Metadata");
  metadata[1] = wxT("&Skip EXIF Metadata");
  wxRadioBox *metadataSel = new wxRadioBox(this, ID_EXIF_METADATA,
                                           wxT("&EXIF Metadata tables"),
                                           wxDefaultPosition,
                                           wxDefaultSize, 2,
                                           metadata, 2,
                                           wxRA_SPECIFY_ROWS);
  metadataSel->SetSelection(0);
  modeSizer->Add(metadataSel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
  wxString gpsOnly[2];
  gpsOnly[0] = wxT("Import any EXIF file");
  gpsOnly[1] = wxT("Import EXIF only if containing &GPS tags");
  wxRadioBox *gpsOnlySel = new wxRadioBox(this, ID_EXIF_GPS_ONLY,
                                          wxT("&GPS position"),
                                          wxDefaultPosition,
                                          wxDefaultSize, 2,
                                          gpsOnly, 2,
                                          wxRA_SPECIFY_ROWS);
  gpsOnlySel->SetSelection(0);
  modeSizer->Add(gpsOnlySel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
// OK - CANCEL buttons
  wxBoxSizer *okCancelBox = new wxBoxSizer(wxHORIZONTAL);
  boxSizer->Add(okCancelBox, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 0);
  wxButton *ok = new wxButton(this, wxID_OK, wxT("&OK"));
  okCancelBox->Add(ok, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
  wxButton *cancel = new wxButton(this, wxID_CANCEL, wxT("&Cancel"));
  okCancelBox->Add(cancel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
// appends event handler for OK button
  Connect(wxID_OK, wxEVT_COMMAND_BUTTON_CLICKED,
          (wxObjectEventFunction) & ExifDialog::OnOk);
// appends event handlers for radio buttons etc
  Connect(ID_EXIF_FOLDER, wxEVT_COMMAND_RADIOBOX_SELECTED,
          (wxObjectEventFunction) & ExifDialog::OnFolder);
  Connect(ID_EXIF_METADATA, wxEVT_COMMAND_RADIOBOX_SELECTED,
          (wxObjectEventFunction) & ExifDialog::OnMetadata);
  Connect(ID_EXIF_GPS_ONLY, wxEVT_COMMAND_RADIOBOX_SELECTED,
          (wxObjectEventFunction) & ExifDialog::OnGpsOnly);
}

void ExifDialog::OnFolder(wxCommandEvent & event)
{
//
// File/Folder radio box
//
  wxRadioBox *folderSel = (wxRadioBox *) FindWindow(ID_EXIF_FOLDER);
  wxStaticText *pathLabel = (wxStaticText *) FindWindow(ID_EXIF_PATH);
  if (Folder == true)
    {
      Folder = false;
      folderSel->SetSelection(0);
      pathLabel->SetLabel(ImgPath);
  } else
    {
      Folder = true;
      folderSel->SetSelection(1);
      pathLabel->SetLabel(DirPath);
    }
}

void ExifDialog::OnMetadata(wxCommandEvent & event)
{
//
// Metadata radio box
//
  wxRadioBox *metadataSel = (wxRadioBox *) FindWindow(ID_EXIF_METADATA);
  if (Metadata == true)
    {
      Metadata = false;
      metadataSel->SetSelection(1);
  } else
    {
      Metadata = true;
      metadataSel->SetSelection(0);
    }
}

void ExifDialog::OnGpsOnly(wxCommandEvent & event)
{
//
// GpsOnly radio box
//
  wxRadioBox *gpsOnlySel = (wxRadioBox *) FindWindow(ID_EXIF_GPS_ONLY);
  if (GpsOnly == true)
    {
      GpsOnly = false;
      gpsOnlySel->SetSelection(0);
  } else
    {
      GpsOnly = true;
      gpsOnlySel->SetSelection(1);
    }
}

void ExifDialog::OnOk(wxCommandEvent & event)
{
//
// all done: 
//
  wxDialog::EndModal(wxID_OK);
}

bool AutoSaveDialog::Create(MyFrame * parent, wxString & path, int secs)
{
//
// creating the dialog
//
  MainFrame = parent;
  Path = path;
  Seconds = secs;
  if (wxDialog::Create(parent, wxID_ANY, wxT("MEMORY-DB AutoSave settings")) ==
      false)
    return false;
// populates individual controls
  CreateControls();
// sets dialog sizer
  GetSizer()->Fit(this);
  GetSizer()->SetSizeHints(this);
// centers the dialog window
  Centre();
  return true;
}

void AutoSaveDialog::CreateControls()
{
//
// creating individual controls and setting initial values
//
  wxBoxSizer *topSizer = new wxBoxSizer(wxVERTICAL);
  this->SetSizer(topSizer);
  wxBoxSizer *boxSizer = new wxBoxSizer(wxVERTICAL);
  topSizer->Add(boxSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
// first row: export path
  wxBoxSizer *pathSizer = new wxBoxSizer(wxHORIZONTAL);
  boxSizer->Add(pathSizer, 0, wxALIGN_RIGHT | wxALL, 0);
  wxStaticText *pathLabel =
    new wxStaticText(this, wxID_STATIC, wxT("&Save as:"));
  pathSizer->Add(pathLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
  wxString pth = Path;
  if (pth.Len() == 0)
    pth = wxT("*** not set: AutoSave IS DISABLED ***");
  PathCtrl = new wxTextCtrl(this, ID_AUTO_SAVE_PATH, pth, wxDefaultPosition,
                            wxSize(350, 22), wxTE_READONLY);
  pathSizer->Add(PathCtrl, 0, wxALIGN_RIGHT | wxALL, 5);
// second row: CHANGE PATH button
  wxBoxSizer *changeBox = new wxBoxSizer(wxHORIZONTAL);
  boxSizer->Add(changeBox, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 0);
  wxButton *change =
    new wxButton(this, ID_AUTO_SAVE_CHANGE_PATH, wxT("&Set the export path"));
  changeBox->Add(change, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
// third row: INTERVAL
  wxBoxSizer *modeSizer = new wxBoxSizer(wxHORIZONTAL);
  boxSizer->Add(modeSizer, 0, wxALIGN_LEFT | wxALL, 0);
  wxString modes[6];
  modes[0] = wxT("&Disable AutoSaving");
  modes[1] = wxT("Every &30 seconds");
  modes[2] = wxT("Every &minute");
  modes[3] = wxT("Every &2 minutes");
  modes[4] = wxT("Every &5 minutes");
  modes[5] = wxT("Every &10 minutes");
  IntervalCtrl = new wxRadioBox(this, ID_AUTO_SAVE_INTERVAL,
                                wxT("&AutoSave interval"),
                                wxDefaultPosition, wxDefaultSize, 6, modes, 6,
                                wxRA_SPECIFY_ROWS);
  if (Seconds <= 0)
    IntervalCtrl->SetSelection(0);
  else if (Seconds <= 30)
    IntervalCtrl->SetSelection(1);
  else if (Seconds <= 60)
    IntervalCtrl->SetSelection(2);
  else if (Seconds <= 120)
    IntervalCtrl->SetSelection(3);
  else if (Seconds <= 300)
    IntervalCtrl->SetSelection(4);
  else
    IntervalCtrl->SetSelection(5);
  modeSizer->Add(IntervalCtrl, 0, wxALIGN_RIGHT | wxALL, 5);

// OK - CANCEL buttons
  wxBoxSizer *okCancelBox = new wxBoxSizer(wxHORIZONTAL);
  boxSizer->Add(okCancelBox, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 0);
  wxButton *ok = new wxButton(this, wxID_OK, wxT("&OK"));
  okCancelBox->Add(ok, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
  wxButton *cancel = new wxButton(this, wxID_CANCEL, wxT("&Cancel"));
  okCancelBox->Add(cancel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
// appends event handler for OK button
  Connect(wxID_OK, wxEVT_COMMAND_BUTTON_CLICKED,
          (wxObjectEventFunction) & AutoSaveDialog::OnOk);
  Connect(ID_AUTO_SAVE_CHANGE_PATH, wxEVT_COMMAND_BUTTON_CLICKED,
          (wxObjectEventFunction) & AutoSaveDialog::OnChangePath);
  Connect(ID_AUTO_SAVE_INTERVAL, wxEVT_COMMAND_RADIOBOX_SELECTED,
          (wxObjectEventFunction) & AutoSaveDialog::OnIntervalChanged);
}

void AutoSaveDialog::OnChangePath(wxCommandEvent & WXUNUSED(event))
{
//
//  exporting the MEMORY-DB into an external DB 
//
  int retdlg;
  wxString lastDir;
  wxFileDialog *fileDialog = new wxFileDialog(this, wxT("Saving the MEMORY-DB"),
                                              wxT(""), wxT("db.sqlite"),
                                              wxT
                                              ("SQLite DB (*.sqlite)|*.sqlite|All files (*.*)|*.*"),
                                              wxFD_SAVE | wxFD_OVERWRITE_PROMPT,
                                              wxDefaultPosition,
                                              wxDefaultSize,
                                              wxT("filedlg"));
  lastDir = MainFrame->GetLastDirectory();
  if (lastDir.Len() >= 1)
    fileDialog->SetDirectory(lastDir);
  retdlg = fileDialog->ShowModal();
  if (retdlg == wxID_OK)
    {
      // exporting the external DB
      wxString pth = fileDialog->GetPath();
      wxString extPth = wxT("*** not set: AutoSave IS DISABLED ***");
      MainFrame->SetExternalSqlitePath(pth);
      if (MainFrame->MemoryDbSave() == true)
        {
          wxMessageBox(wxT("Ok, MEMORY-DB was succesfully saved"),
                       wxT("spatialite-gui"), wxOK | wxICON_INFORMATION, this);
          wxFileName file(fileDialog->GetPath());
          lastDir = file.GetPath();
          MainFrame->SetLastDirectory(lastDir);
          extPth = MainFrame->GetExternalSqlitePath();
          PathCtrl->SetValue(extPth);
      } else
        PathCtrl->SetValue(extPth);
    }
}

void AutoSaveDialog::OnIntervalChanged(wxCommandEvent & event)
{
//
// Interval selection changed
//
  if (IntervalCtrl->GetSelection() == 0)
    Seconds = 0;
  else if (IntervalCtrl->GetSelection() == 1)
    Seconds = 30;
  else if (IntervalCtrl->GetSelection() == 2)
    Seconds = 60;
  else if (IntervalCtrl->GetSelection() == 3)
    Seconds = 120;
  else if (IntervalCtrl->GetSelection() == 4)
    Seconds = 300;
  else
    Seconds = 600;
}

void AutoSaveDialog::OnOk(wxCommandEvent & event)
{
//
// all done: 
//
  wxDialog::EndModal(wxID_OK);
}

Added Exif.cpp.





















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
/*
/ Exif.cpp
/ methods related to EXIF import
/
/ version 1.2, 2008 October 9
/
/ Author: Sandro Furieri a-furieri@lqt.it
/
/ Copyright (C) 2008  Alessandro Furieri
/
/    This program is free software: you can redistribute it and/or modify
/    it under the terms of the GNU General Public License as published by
/    the Free Software Foundation, either version 3 of the License, or
/    (at your option) any later version.
/
/    This program is distributed in the hope that it will be useful,
/    but WITHOUT ANY WARRANTY; without even the implied warranty of
/    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
/    GNU General Public License for more details.
/
/    You should have received a copy of the GNU General Public License
/    along with this program.  If not, see <http://www.gnu.org/licenses/>.
/
*/

#include "Classdef.h"

#include <sys/types.h>
#include <dirent.h>
#include <float.h>

void MyFrame::ImportExifPhotos(wxString & path, bool folder, bool metadata,
                               bool gps_only)
{
//
// trying to import EXIF photos
// 
  int cnt;
  char msg[256];
  ::wxBeginBusyCursor();
  if (CheckExifTables() == false)
    {
      ::wxEndBusyCursor();
      wxMessageBox(wxT
                   ("An EXIF table is already defined, but has incompatibles columns"),
                   wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
      return;
    }
  if (folder == true)
    cnt = ExifLoadDir(path, gps_only, metadata);
  else
    cnt = ExifLoadFile(path, gps_only, metadata);
  ::wxEndBusyCursor();
  sprintf(msg, "%d EXIF photo%s succesfully inserted into the DB\n", cnt,
          (cnt > 1) ? "s where" : " was");
  wxMessageBox(wxString::FromUTF8(msg), wxT("spatialite-gui"),
               wxOK | wxICON_INFORMATION, this);
  InitTableTree();
}

bool MyFrame::CheckExifTables()
{
//
// creates the EXIF DB tables / or checks existing ones for validity 
//
  int ret;
  wxString sql;
  char xsql[1024];
  char *errMsg;
  bool ok_photoId;
  bool ok_photo;
  bool ok_pixelX;
  bool ok_pixelY;
  bool ok_cameraMake;
  bool ok_cameraModel;
  bool ok_shotDateTime;
  bool ok_gpsGeometry;
  bool ok_gpsDirection;
  bool ok_gpsSatellites;
  bool ok_gpsTimestamp;
  bool ok_fromPath;
  bool ok_tagId;
  bool ok_tagName;
  bool ok_gpsTag;
  bool ok_valueType;
  bool ok_typeName;
  bool ok_countValues;
  bool ok_valueIndex;
  bool ok_byteValue;
  bool ok_stringValue;
  bool ok_numValue;
  bool ok_numValueBis;
  bool ok_doubleValue;
  bool ok_humanReadable;
  bool err_pk;
  bool ok_photoIdPk;
  bool ok_tagIdPk;
  bool ok_valueIndexPk;
  bool pKey;
  const char *name;
  int i;
  char **results;
  int rows;
  int columns;
// creating the ExifPhoto table 
  sql = wxT("CREATE TABLE IF NOT EXISTS ExifPhoto (\n");
  sql += wxT("PhotoId INTEGER PRIMARY KEY AUTOINCREMENT,\n");
  sql += wxT("Photo BLOB NOT NULL,\n");
  sql += wxT("PixelX INTEGER,\n");
  sql += wxT("PixelY INTEGER,\n");
  sql += wxT("CameraMake TEXT,\n");
  sql += wxT("CameraModel TEXT,\n");
  sql += wxT("ShotDateTime DOUBLE,\n");
  sql += wxT("GpsGeometry BLOB,\n");
  sql += wxT("GpsDirection DOUBLE, ");
  sql += wxT("GpsSatellites TEXT,\n");
  sql += wxT("GpsTimestamp DOUBLE,\n");
  sql += wxT("FromPath TEXT");
  sql += wxT(")");
  strcpy(xsql, sql.ToUTF8());
  ret = sqlite3_exec(SqliteHandle, xsql, NULL, NULL, &errMsg);
  if (ret != SQLITE_OK)
    {
      wxMessageBox(wxT("CREATE TABLE ExifPhoto error: ") +
                   wxString::FromUTF8(errMsg), wxT("spatialite-gui"),
                   wxOK | wxICON_ERROR, this);
      sqlite3_free(errMsg);
      goto abort;
    }
// checking the ExifPhoto table for sanity 
  ok_photoId = false;
  ok_photo = false;
  ok_pixelX = false;
  ok_pixelY = false;
  ok_cameraMake = false;
  ok_cameraModel = false;
  ok_shotDateTime = false;
  ok_gpsGeometry = false;
  ok_gpsDirection = false;
  ok_gpsSatellites = false;
  ok_gpsTimestamp = false;
  ok_fromPath = false;
  ok_photoIdPk = false;
  err_pk = false;
  strcpy(xsql, "PRAGMA table_info(ExifPhoto)");
  ret =
    sqlite3_get_table(SqliteHandle, xsql, &results, &rows, &columns, &errMsg);
  if (ret != SQLITE_OK)
    {
      wxMessageBox(wxT("PRAGMA table_info(ExifPhoto) error: ") +
                   wxString::FromUTF8(errMsg), wxT("spatialite-gui"),
                   wxOK | wxICON_ERROR, this);
      sqlite3_free(errMsg);
      goto abort;
    }
  if (rows < 1)
    ;
  else
    {
      for (i = 1; i <= rows; i++)
        {
          name = results[(i * columns) + 1];
          if (atoi(results[(i * columns) + 5]) == 0)
            pKey = false;
          else
            pKey = true;
          if (strcasecmp(name, "PhotoId") == 0)
            ok_photoId = true;
          if (strcasecmp(name, "Photo") == 0)
            ok_photo = true;
          if (strcasecmp(name, "PixelX") == 0)
            ok_pixelX = true;
          if (strcasecmp(name, "PixelY") == 0)
            ok_pixelY = true;
          if (strcasecmp(name, "CameraMake") == 0)
            ok_cameraMake = true;
          if (strcasecmp(name, "CameraModel") == 0)
            ok_cameraModel = true;
          if (strcasecmp(name, "ShotDateTime") == 0)
            ok_shotDateTime = true;
          if (strcasecmp(name, "GpsGeometry") == 0)
            ok_gpsGeometry = true;
          if (strcasecmp(name, "GpsDirection") == 0)
            ok_gpsDirection = true;
          if (strcasecmp(name, "GpsTimestamp") == 0)
            ok_gpsTimestamp = true;
          if (strcasecmp(name, "FromPath") == 0)
            ok_fromPath = true;
          if (pKey == true)
            {
              if (strcasecmp(name, "PhotoId") == 0)
                ok_photoIdPk = true;
              else
                err_pk = true;
            }
        }
    }
  sqlite3_free_table(results);
  if (ok_photoId == true && ok_photo == true && ok_pixelX == true
      && ok_pixelY == true && ok_cameraMake == true && ok_cameraModel == true
      && ok_shotDateTime == true && ok_gpsGeometry == true
      && ok_gpsDirection == true && ok_gpsTimestamp == true
      && ok_fromPath == true && ok_photoIdPk == true && err_pk == false)
    ;
  else
    {
      wxMessageBox(wxT
                   ("ERROR: table ExifPhoto already exists, but has incompatible columns"),
                   wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
      sqlite3_free(errMsg);
      goto abort;
    }
// creating the ExifTags table 
  sql = wxT("CREATE TABLE IF NOT EXISTS ExifTags (\n");
  sql += wxT("PhotoId INTEGER NOT NULL,\n");
  sql += wxT("TagId INTEGER NOT NULL,\n");
  sql += wxT("TagName TEXT NOT NULL,\n");
  sql += wxT("GpsTag INTEGER NOT NULL CHECK (GpsTag IN (0, 1)),\n");
  sql +=
    wxT
    ("ValueType INTEGER NOT NULL CHECK (ValueType IN (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)),\n");
  sql += wxT("TypeName TEXT NOT NULL,\n");
  sql += wxT("CountValues INTEGER NOT NULL,\n");
  sql += wxT("PRIMARY KEY (PhotoId, TagId)");
  sql += wxT(")");
  strcpy(xsql, sql.ToUTF8());
  ret = sqlite3_exec(SqliteHandle, xsql, NULL, NULL, &errMsg);
  if (ret != SQLITE_OK)
    {
      wxMessageBox(wxT("CREATE TABLE ExifTags error: ") +
                   wxString::FromUTF8(errMsg), wxT("spatialite-gui"),
                   wxOK | wxICON_ERROR, this);
      sqlite3_free(errMsg);
      goto abort;
    }
// checking the ExifTags table for sanity 
  ok_photoId = false;
  ok_tagId = false;
  ok_tagName = false;
  ok_gpsTag = false;
  ok_valueType = false;
  ok_typeName = false;
  ok_countValues = false;
  ok_photoIdPk = false;
  ok_tagIdPk = false;
  err_pk = false;
  strcpy(xsql, "PRAGMA table_info(ExifTags)");
  ret =
    sqlite3_get_table(SqliteHandle, xsql, &results, &rows, &columns, &errMsg);
  if (ret != SQLITE_OK)
    {
      wxMessageBox(wxT("PRAGMA table_info(ExifTags) error: ") +
                   wxString::FromUTF8(errMsg), wxT("spatialite-gui"),
                   wxOK | wxICON_ERROR, this);
      sqlite3_free(errMsg);
      goto abort;
    }
  if (rows < 1)
    ;
  else
    {
      for (i = 1; i <= rows; i++)
        {
          name = results[(i * columns) + 1];
          if (atoi(results[(i * columns) + 5]) == 0)
            pKey = false;
          else
            pKey = true;
          if (strcasecmp(name, "PhotoId") == 0)
            ok_photoId = true;
          if (strcasecmp(name, "TagId") == 0)
            ok_tagId = true;
          if (strcasecmp(name, "TagName") == 0)
            ok_tagName = true;
          if (strcasecmp(name, "GpsTag") == 0)
            ok_gpsTag = true;
          if (strcasecmp(name, "ValueType") == 0)
            ok_valueType = true;
          if (strcasecmp(name, "TypeName") == 0)
            ok_typeName = true;
          if (strcasecmp(name, "CountValues") == 0)
            ok_countValues = true;
          if (pKey == true)
            {
              if (strcasecmp(name, "PhotoId") == 0)
                ok_photoIdPk = true;
              else if (strcasecmp(name, "TagId") == 0)
                ok_tagIdPk = true;
              else
                err_pk = true;
            }
        }
    }
  sqlite3_free_table(results);
  if (ok_photoId == true && ok_tagId == true && ok_tagName == true
      && ok_gpsTag == true && ok_valueType == true && ok_typeName == true
      && ok_countValues == true && ok_photoIdPk == true && ok_tagIdPk == true
      && err_pk == false)
    ;
  else
    {
      wxMessageBox(wxT
                   ("ERROR: table ExifTags already exists, but has incompatible columns"),
                   wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
      sqlite3_free(errMsg);
      goto abort;
    }
// creating the ExifValues table 
  sql = wxT("CREATE TABLE IF NOT EXISTS ExifValues (\n");
  sql += wxT("PhotoId INTEGER NOT NULL,\n");
  sql += wxT("TagId INTEGER NOT NULL,\n");
  sql += wxT("ValueIndex INTEGER NOT NULL,\n");
  sql += wxT("ByteValue BLOB,\n");
  sql += wxT("StringValue TEXT,\n");
  sql += wxT("NumValue INTEGER,\n");
  sql += wxT("NumValueBis INTEGER,\n");
  sql += wxT("DoubleValue DOUBLE,\n");
  sql += wxT("HumanReadable TEXT,\n");
  sql += wxT("PRIMARY KEY (PhotoId, TagId, ValueIndex)");
  sql += wxT(")");
  strcpy(xsql, sql.ToUTF8());
  ret = sqlite3_exec(SqliteHandle, xsql, NULL, NULL, &errMsg);
  if (ret != SQLITE_OK)
    {
      wxMessageBox(wxT("CREATE TABLE ExifValues error: ") +
                   wxString::FromUTF8(errMsg), wxT("spatialite-gui"),
                   wxOK | wxICON_ERROR, this);
      sqlite3_free(errMsg);
      goto abort;
    }
// checking the ExifValues table for sanity 
  ok_photoId = false;
  ok_tagId = false;
  ok_valueIndex = false;
  ok_byteValue = false;
  ok_stringValue = false;
  ok_numValue = false;
  ok_numValueBis = false;
  ok_doubleValue = false;
  ok_humanReadable = false;
  ok_photoIdPk = false;
  ok_tagIdPk = false;
  ok_valueIndexPk = false;
  err_pk = false;
  strcpy(xsql, "PRAGMA table_info(ExifValues)");
  ret =
    sqlite3_get_table(SqliteHandle, xsql, &results, &rows, &columns, &errMsg);
  if (ret != SQLITE_OK)
    {
      wxMessageBox(wxT("PRAGMA table_info(ExifValues) error: ") +
                   wxString::FromUTF8(errMsg), wxT("spatialite-gui"),
                   wxOK | wxICON_ERROR, this);
      sqlite3_free(errMsg);
      goto abort;
    }
  if (rows < 1)
    ;
  else
    {
      for (i = 1; i <= rows; i++)
        {
          name = results[(i * columns) + 1];
          if (atoi(results[(i * columns) + 5]) == 0)
            pKey = false;
          else
            pKey = true;
          if (strcasecmp(name, "PhotoId") == 0)
            ok_photoId = true;
          if (strcasecmp(name, "TagId") == 0)
            ok_tagId = true;
          if (strcasecmp(name, "ValueIndex") == 0)
            ok_valueIndex = true;
          if (strcasecmp(name, "ByteValue") == 0)
            ok_byteValue = true;
          if (strcasecmp(name, "StringValue") == 0)
            ok_stringValue = true;
          if (strcasecmp(name, "NumValue") == 0)
            ok_numValue = true;
          if (strcasecmp(name, "NumValueBis") == 0)
            ok_numValueBis = true;
          if (strcasecmp(name, "DoubleValue") == 0)
            ok_doubleValue = true;
          if (strcasecmp(name, "HumanReadable") == 0)
            ok_humanReadable = true;
          if (pKey == true)
            {
              if (strcasecmp(name, "PhotoId") == 0)
                ok_photoIdPk = true;
              else if (strcasecmp(name, "TagId") == 0)
                ok_tagIdPk = true;
              else if (strcasecmp(name, "ValueIndex") == 0)
                ok_valueIndexPk = true;
              else
                err_pk = true;
            }
        }
    }
  sqlite3_free_table(results);
  if (ok_photoId == true && ok_tagId == true && ok_valueIndex == true
      && ok_byteValue == true && ok_stringValue == true && ok_numValue == true
      && ok_numValueBis == true && ok_doubleValue == true
      && ok_humanReadable == true && ok_photoIdPk == true && ok_tagIdPk == true
      && ok_valueIndexPk == true && err_pk == false)
    ;
  else
    {
      wxMessageBox(wxT
                   ("ERROR: table ExifValues already exists, but has incompatible columns"),
                   wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
      sqlite3_free(errMsg);
      goto abort;
    }
// creating the ExifView view 
  sql = wxT("CREATE VIEW IF NOT EXISTS ExifMetadata AS\n");
  sql += wxT("SELECT p.PhotoId AS PhotoId, ");
  sql += wxT("t.TagId AS TagId, ");
  sql += wxT("t.TagName AS TagName,");
  sql += wxT("t.GpsTag AS GpsTag,\n");
  sql += wxT("t.ValueType AS ValueType,");
  sql += wxT("t.TypeName AS TypeName, ");
  sql += wxT("t.CountValues AS CountValues, ");
  sql += wxT("v.ValueIndex AS ValueIndex,\n");
  sql += wxT("v.ByteValue AS ByteValue, ");
  sql += wxT("v.StringValue AS StringValue, ");
  sql += wxT("v.NumValue AS NumValue, ");
  sql += wxT("v.NumValueBis AS NumValueBis,\n");
  sql += wxT("v.DoubleValue AS DoubleValue, ");
  sql += wxT("v.HumanReadable AS HumanReadable\n");
  sql += wxT("FROM ExifPhoto AS p, ExifTags AS t, ExifValues AS v\n");
  sql +=
    wxT
    ("WHERE t.PhotoId = p.PhotoId AND v.PhotoId = t.PhotoId AND v.TagId = t.TagId");
  strcpy(xsql, sql.ToUTF8());
  ret = sqlite3_exec(SqliteHandle, xsql, NULL, NULL, &errMsg);
  if (ret != SQLITE_OK)
    {
      wxMessageBox(wxT("CREATE VIEW ExifMetadata error: ") +
                   wxString::FromUTF8(errMsg), wxT("spatialite-gui"),
                   wxOK | wxICON_ERROR, this);
      sqlite3_free(errMsg);
      goto abort;
    }
  return true;
abort:
  return false;
}

int MyFrame::ExifLoadDir(wxString & path, bool gps_only, bool metadata)
{
//
// importing EXIF files from a whole DIRECTORY 
//
  int cnt = 0;
  wxString filePath;
  struct dirent *entry;
  DIR *dir = opendir(path.ToUTF8());
  if (!dir)
    return 0;
  while (1)
    {
      // scanning dir-entries
      entry = readdir(dir);
      if (!entry)
        break;
      filePath = path;
      filePath += wxT("/") + wxString::FromUTF8(entry->d_name);
      cnt += ExifLoadFile(filePath, gps_only, metadata);
    }
  closedir(dir);
  return cnt;
}

int MyFrame::ExifLoadFile(wxString & path, bool gps_only, bool metadata)
{
//
// importing a single EXIF file 
//
  FILE *fl;
  int sz = 0;
  int rd;
  int loaded = 0;
  unsigned char *blob = NULL;
  gaiaExifTagListPtr tag_list = NULL;
  fl = fopen(path.ToUTF8(), "rb");
  if (!fl)
    return 0;
  if (fseek(fl, 0, SEEK_END) == 0)
    sz = ftell(fl);
  if (sz > 14)
    {
      blob = (unsigned char *) malloc(sz);
      rewind(fl);
      rd = fread(blob, 1, sz, fl);
      if (rd == sz)
        {
          tag_list = gaiaGetExifTags(blob, sz);
          if (tag_list)
            {
              if (gps_only && IsExifGps(tag_list) == false)
                goto stop;
              if (UpdateExifTables(blob, sz, tag_list, metadata, path) == false)
                goto stop;
              loaded = 1;
            }
        }
    }
stop:
  if (blob)
    free(blob);
  if (tag_list)
    gaiaExifTagsFree(tag_list);
  fclose(fl);
  return loaded;
}

bool MyFrame::IsExifGps(gaiaExifTagListPtr tag_list)
{
//
// checks if this one is a GPS-tagged EXIF 
//
  bool gps_lat = false;
  bool gps_long = false;
  gaiaExifTagPtr pT = tag_list->First;
  while (pT)
    {
      if (pT->Gps && pT->TagId == 0x04)
        gps_long = true;
      if (pT->Gps && pT->TagId == 0x02)
        gps_lat = true;
      if (gps_long == true && gps_lat == true)
        return true;
      pT = pT->Next;
    }
  return false;
}

bool MyFrame::UpdateExifTables(unsigned char *blob, int sz,
                               gaiaExifTagListPtr tag_list, bool metadata,
                               wxString & path)
{
//
// inserting an EXIF photo into the DB 
//
  int i;
  int iv;
  bool ok;
  int xok;
  int ok_human;
  char tag_name[128];
  gaiaExifTagPtr pT;
  int ret;
  char sql[1024];
  char human[1024];
  wxString make;
  wxString model;
  wxString satellites;
  wxString date;
  wxString timestamp;
  char *errMsg = NULL;
  sqlite3_stmt *stmt;
  sqlite3_int64 pk = 0;
  sqlite3_int64 val64;
  double dblval;
  const char *type_desc;
  double longitude;
  double latitude;
  gaiaGeomCollPtr geom;
  unsigned char *geoblob;
  int geosize;
// starts a transaction 
  strcpy(sql, "BEGIN");
  ret = sqlite3_exec(SqliteHandle, sql, NULL, NULL, &errMsg);
  if (ret != SQLITE_OK)
    {
      wxMessageBox(wxT("BEGIN error: ") + wxString::FromUTF8(errMsg),
                   wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
      sqlite3_free(errMsg);
      goto abort;
    }
// feeding the ExifPhoto table; preparing the SQL statement
  strcpy(sql,
         "INSERT INTO ExifPhoto (PhotoId, Photo, PixelX, PixelY, CameraMake, CameraModel, ");
  strcat(sql,
         "ShotDateTime, GpsGeometry, GpsDirection, GpsSatellites, GpsTimestamp, FromPath) ");
  strcat(sql,
         "VALUES (NULL, ?, ?, ?, ?, ?, JulianDay(?), ?, ?, ?, JulianDay(?), ?)");
  ret = sqlite3_prepare_v2(SqliteHandle, sql, strlen(sql), &stmt, NULL);
  if (ret != SQLITE_OK)
    {
      wxMessageBox(wxT("INSERT INTO ExifPhoto error: ") +
                   wxString::FromUTF8(sqlite3_errmsg(SqliteHandle)),
                   wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
      goto abort;
    }
  sqlite3_bind_blob(stmt, 1, blob, sz, SQLITE_STATIC);
  val64 = GetPixelX(tag_list, &ok);
  if (ok == true)
    sqlite3_bind_int64(stmt, 2, val64);
  else
    sqlite3_bind_null(stmt, 2);
  val64 = GetPixelY(tag_list, &ok);
  if (ok == true)
    sqlite3_bind_int64(stmt, 3, val64);
  else
    sqlite3_bind_null(stmt, 3);
  GetMake(tag_list, make, &ok);
  if (ok == true)
    sqlite3_bind_text(stmt, 4, make.ToUTF8(), make.Len(), SQLITE_TRANSIENT);
  else
    sqlite3_bind_null(stmt, 4);
  GetModel(tag_list, model, &ok);
  if (ok == true)
    sqlite3_bind_text(stmt, 5, model.ToUTF8(), model.Len(), SQLITE_TRANSIENT);
  else
    sqlite3_bind_null(stmt, 5);
  GetDate(tag_list, date, &ok);
  if (ok == true)
    sqlite3_bind_text(stmt, 6, date.ToUTF8(), date.Len(), SQLITE_TRANSIENT);
  else
    sqlite3_bind_text(stmt, 6, "0000-00-00 00:00:00", 19, SQLITE_TRANSIENT);
  GetGpsCoords(tag_list, &longitude, &latitude, &ok);
  if (ok == true)
    {
      geom = gaiaAllocGeomColl();
      geom->Srid = 4326;
      gaiaAddPointToGeomColl(geom, longitude, latitude);
      gaiaToSpatiaLiteBlobWkb(geom, &geoblob, &geosize);
      gaiaFreeGeomColl(geom);
      sqlite3_bind_blob(stmt, 7, geoblob, geosize, SQLITE_TRANSIENT);
      free(geoblob);
  } else
    sqlite3_bind_null(stmt, 7);
  dblval = GetGpsDirection(tag_list, &ok);
  if (ok == true)
    sqlite3_bind_double(stmt, 8, dblval);
  else
    sqlite3_bind_null(stmt, 8);
  GetGpsSatellites(tag_list, satellites, &ok);
  if (ok == true)
    sqlite3_bind_text(stmt, 9, satellites.ToUTF8(), satellites.Len(),
                      SQLITE_TRANSIENT);
  else
    sqlite3_bind_null(stmt, 9);
  GetGpsTimestamp(tag_list, timestamp, &ok);
  if (ok == true)
    sqlite3_bind_text(stmt, 10, timestamp.ToUTF8(), timestamp.Len(),
                      SQLITE_TRANSIENT);
  else
    sqlite3_bind_text(stmt, 10, "0000-00-00 00:00:00", 19, SQLITE_TRANSIENT);
  sqlite3_bind_text(stmt, 11, path.ToUTF8(), path.Len(), SQLITE_TRANSIENT);
  ret = sqlite3_step(stmt);
  if (ret == SQLITE_DONE || ret == SQLITE_ROW)
    ;
  else
    {
      wxMessageBox(wxT("sqlite3_step() error: ") +
                   wxString::FromUTF8(sqlite3_errmsg(SqliteHandle)),
                   wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
      sqlite3_finalize(stmt);
      goto abort;
    }
  sqlite3_finalize(stmt);
  pk = sqlite3_last_insert_rowid(SqliteHandle);
  if (metadata)
    {
      // feeding the ExifTags table; preparing the SQL statement 
      strcpy(sql,
             "INSERT OR IGNORE INTO ExifTags (PhotoId, TagId, TagName, GpsTag, ValueType, ");
      strcat(sql, "TypeName, CountValues) VALUES (?, ?, ?, ?, ?, ?, ?)");
      ret = sqlite3_prepare_v2(SqliteHandle, sql, strlen(sql), &stmt, NULL);
      if (ret != SQLITE_OK)
        {
          wxMessageBox(wxT("INSERT INTO ExifTags error: ") +
                       wxString::FromUTF8(sqlite3_errmsg(SqliteHandle)),
                       wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
          goto abort;
        }
      for (i = 0; i < gaiaGetExifTagsCount(tag_list); i++)
        {
          pT = gaiaGetExifTagByPos(tag_list, i);
          if (pT)
            {
              gaiaExifTagGetName(pT, tag_name, 128);
              switch (gaiaExifTagGetValueType(pT))
                {
                  case 1:
                    type_desc = "BYTE";
                    break;
                  case 2:
                    type_desc = "STRING";
                    break;
                  case 3:
                    type_desc = "SHORT";
                    break;
                  case 4:
                    type_desc = "LONG";
                    break;
                  case 5:
                    type_desc = "RATIONAL";
                    break;
                  case 6:
                    type_desc = "SBYTE";
                    break;
                  case 7:
                    type_desc = "UNDEFINED";
                    break;
                  case 8:
                    type_desc = "SSHORT";
                    break;
                  case 9:
                    type_desc = "SLONG";
                    break;
                  case 10:
                    type_desc = "SRATIONAL";
                    break;
                  case 11:
                    type_desc = "FLOAT";
                    break;
                  case 12:
                    type_desc = "DOUBLE";
                    break;
                  default:
                    type_desc = "UNKNOWN";
                    break;
                };
              // INSERTing an Exif Tag 
              sqlite3_reset(stmt);
              sqlite3_clear_bindings(stmt);
              sqlite3_bind_int64(stmt, 1, pk);
              sqlite3_bind_int(stmt, 2, gaiaExifTagGetId(pT));
              sqlite3_bind_text(stmt, 3, tag_name, strlen(tag_name),
                                SQLITE_STATIC);
              sqlite3_bind_int(stmt, 4, gaiaIsExifGpsTag(pT));
              sqlite3_bind_int(stmt, 5, gaiaExifTagGetValueType(pT));
              sqlite3_bind_text(stmt, 6, type_desc, strlen(type_desc),
                                SQLITE_STATIC);
              sqlite3_bind_int(stmt, 7, gaiaExifTagGetNumValues(pT));
              ret = sqlite3_step(stmt);
              if (ret == SQLITE_DONE || ret == SQLITE_ROW)
                ;
              else
                {
                  wxMessageBox(wxT("sqlite3_step() error: ") +
                               wxString::FromUTF8(sqlite3_errmsg(SqliteHandle)),
                               wxT("spatialite-gui"), wxOK | wxICON_ERROR,
                               this);
                  sqlite3_finalize(stmt);
                  goto abort;
                }
            }
        }
      sqlite3_finalize(stmt);
      // feeding the ExifValues table; preparing the SQL statement
      strcpy(sql,
             "INSERT OR IGNORE INTO ExifValues (PhotoId, TagId, ValueIndex, ByteValue, ");
      strcat(sql,
             "StringValue, NumValue, NumValueBis, DoubleValue, HumanReadable) VALUES ");
      strcat(sql, "(?, ?, ?, ?, ?, ?, ?, ?, ?)");
      ret = sqlite3_prepare_v2(SqliteHandle, sql, strlen(sql), &stmt, NULL);
      if (ret != SQLITE_OK)
        {
          wxMessageBox(wxT("NSERT INTO ExifValues error: ") +
                       wxString::FromUTF8(sqlite3_errmsg(SqliteHandle)),
                       wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
          goto abort;
        }
      for (i = 0; i < gaiaGetExifTagsCount(tag_list); i++)
        {
          pT = gaiaGetExifTagByPos(tag_list, i);
          if (pT)
            {
              gaiaExifTagGetHumanReadable(pT, human, 1024, &ok_human);
              for (iv = 0; iv < gaiaExifTagGetNumValues(pT); iv++)
                {
                  // INSERTing an Exif Tag
                  sqlite3_reset(stmt);
                  sqlite3_clear_bindings(stmt);
                  sqlite3_bind_int64(stmt, 1, pk);
                  sqlite3_bind_int(stmt, 2, gaiaExifTagGetId(pT));
                  sqlite3_bind_int(stmt, 3, iv);
                  if (gaiaExifTagGetValueType(pT) == 1
                      || gaiaExifTagGetValueType(pT) == 6
                      || gaiaExifTagGetValueType(pT) == 7)
                    {
                      sqlite3_bind_blob(stmt, 4, pT->ByteValue, pT->Count,
                                        SQLITE_STATIC);
                      sqlite3_bind_null(stmt, 5);
                      sqlite3_bind_null(stmt, 6);
                      sqlite3_bind_null(stmt, 7);
                      sqlite3_bind_null(stmt, 8);
                    }
                  if (gaiaExifTagGetValueType(pT) == 2)
                    {
                      sqlite3_bind_null(stmt, 4);
                      sqlite3_bind_text(stmt, 5, pT->StringValue,
                                        strlen(pT->StringValue), SQLITE_STATIC);
                      sqlite3_bind_null(stmt, 6);
                      sqlite3_bind_null(stmt, 7);
                      sqlite3_bind_null(stmt, 8);
                    }
                  if (gaiaExifTagGetValueType(pT) == 3)
                    {
                      sqlite3_bind_null(stmt, 4);
                      sqlite3_bind_null(stmt, 5);
                      val64 = gaiaExifTagGetShortValue(pT, iv, &xok);
                      if (!ok)
                        sqlite3_bind_null(stmt, 6);
                      else
                        sqlite3_bind_int64(stmt, 6, val64);
                      sqlite3_bind_null(stmt, 7);
                      sqlite3_bind_null(stmt, 8);
                    }
                  if (gaiaExifTagGetValueType(pT) == 4)
                    {
                      sqlite3_bind_null(stmt, 4);
                      sqlite3_bind_null(stmt, 5);
                      val64 = gaiaExifTagGetLongValue(pT, iv, &xok);
                      if (!ok)
                        sqlite3_bind_null(stmt, 6);
                      else
                        sqlite3_bind_int64(stmt, 6, val64);
                      sqlite3_bind_null(stmt, 7);
                      sqlite3_bind_null(stmt, 8);
                    }
                  if (gaiaExifTagGetValueType(pT) == 5)
                    {
                      sqlite3_bind_null(stmt, 4);
                      sqlite3_bind_null(stmt, 5);
                      val64 = gaiaExifTagGetRational1Value(pT, iv, &xok);
                      if (!ok)
                        sqlite3_bind_null(stmt, 6);
                      else
                        sqlite3_bind_int64(stmt, 6, val64);
                      val64 = gaiaExifTagGetRational2Value(pT, iv, &xok);
                      if (!ok)
                        sqlite3_bind_null(stmt, 7);
                      else
                        sqlite3_bind_int64(stmt, 7, val64);
                      dblval = gaiaExifTagGetRationalValue(pT, iv, &xok);
                      if (!ok)
                        sqlite3_bind_null(stmt, 8);
                      else
                        sqlite3_bind_double(stmt, 8, dblval);
                    }
                  if (gaiaExifTagGetValueType(pT) == 9)
                    {
                      sqlite3_bind_null(stmt, 4);
                      sqlite3_bind_null(stmt, 5);
                      val64 = gaiaExifTagGetSignedLongValue(pT, iv, &xok);
                      if (!ok)
                        sqlite3_bind_null(stmt, 6);
                      else
                        sqlite3_bind_int64(stmt, 6, val64);
                      sqlite3_bind_null(stmt, 7);
                      sqlite3_bind_null(stmt, 8);
                    }
                  if (gaiaExifTagGetValueType(pT) == 10)
                    {
                      sqlite3_bind_null(stmt, 4);
                      sqlite3_bind_null(stmt, 5);
                      val64 = gaiaExifTagGetSignedRational1Value(pT, iv, &xok);
                      if (!ok)
                        sqlite3_bind_null(stmt, 6);
                      else
                        sqlite3_bind_int64(stmt, 6, val64);
                      val64 = gaiaExifTagGetSignedRational2Value(pT, iv, &xok);
                      if (!ok)
                        sqlite3_bind_null(stmt, 7);
                      else
                        sqlite3_bind_int64(stmt, 7, val64);
                      dblval = gaiaExifTagGetSignedRationalValue(pT, iv, &xok);
                      if (!ok)
                        sqlite3_bind_null(stmt, 8);
                      else
                        sqlite3_bind_double(stmt, 8, dblval);
                    }
                  if (gaiaExifTagGetValueType(pT) == 11)
                    {
                      sqlite3_bind_null(stmt, 4);
                      sqlite3_bind_null(stmt, 5);
                      sqlite3_bind_null(stmt, 6);
                      sqlite3_bind_null(stmt, 7);
                      dblval = gaiaExifTagGetFloatValue(pT, iv, &xok);
                      if (!ok)
                        sqlite3_bind_null(stmt, 8);
                      else
                        sqlite3_bind_double(stmt, 8, dblval);
                    }
                  if (gaiaExifTagGetValueType(pT) == 12)
                    {
                      sqlite3_bind_null(stmt, 4);
                      sqlite3_bind_null(stmt, 5);
                      sqlite3_bind_null(stmt, 6);
                      sqlite3_bind_null(stmt, 7);
                      dblval = gaiaExifTagGetDoubleValue(pT, iv, &xok);
                      if (!ok)
                        sqlite3_bind_null(stmt, 8);
                      else
                        sqlite3_bind_double(stmt, 8, dblval);
                    }
                  if (!ok_human)
                    sqlite3_bind_null(stmt, 9);
                  else
                    sqlite3_bind_text(stmt, 9, human, strlen(human),
                                      SQLITE_STATIC);
                  ret = sqlite3_step(stmt);
                  if (ret == SQLITE_DONE || ret == SQLITE_ROW)
                    ;
                  else
                    {
                      wxMessageBox(wxT("sqlite3_step() error: ") +
                                   wxString::
                                   FromUTF8(sqlite3_errmsg(SqliteHandle)),
                                   wxT("spatialite-gui"), wxOK | wxICON_ERROR,
                                   this);
                      sqlite3_finalize(stmt);
                      goto abort;
                    }
                  if (gaiaExifTagGetValueType(pT) == 1
                      || gaiaExifTagGetValueType(pT) == 2
                      || gaiaExifTagGetValueType(pT) == 6
                      || gaiaExifTagGetValueType(pT) == 7)
                    break;
                  ok_human = 0;
                }
            }
        }
      sqlite3_finalize(stmt);
    }
// commits the transaction 
  strcpy(sql, "COMMIT");
  ret = sqlite3_exec(SqliteHandle, sql, NULL, NULL, &errMsg);
  if (ret != SQLITE_OK)
    {
      wxMessageBox(wxT("COMMIT error: ") + wxString::FromUTF8(errMsg),
                   wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
      sqlite3_free(errMsg);
    }
  return true;
abort:
// rolling back the transaction
  strcpy(sql, "ROLLBACK");
  ret = sqlite3_exec(SqliteHandle, sql, NULL, NULL, &errMsg);
  if (ret != SQLITE_OK)
    {
      wxMessageBox(wxT("ROLLBACK error: ") + wxString::FromUTF8(errMsg),
                   wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
      sqlite3_free(errMsg);
    }
  return false;
}

sqlite3_int64 MyFrame::GetPixelX(gaiaExifTagListPtr tag_list, bool * ok)
{
//
// trying to retrieve the ExifImageWidth 
//
  *ok = false;
  if (!tag_list)
    return 0;
  gaiaExifTagPtr tag = tag_list->First;
  while (tag)
    {
      if (tag->TagId == 0xA002)
        {
          // ok, this one is the ExifImageWidth tag 
          if (tag->Type == 3 && tag->Count == 1)
            {
              *ok = true;
              return *(tag->ShortValues + 0);
          } else if (tag->Type == 4 && tag->Count == 1)
            {
              *ok = true;
              return *(tag->LongValues + 0);
            }
        }
      tag = tag->Next;
    }
  return false;
}

sqlite3_int64 MyFrame::GetPixelY(gaiaExifTagListPtr tag_list, bool * ok)
{
//
// trying to retrieve the ExifImageLength 
//
  *ok = false;
  if (!tag_list)
    return 0;
  gaiaExifTagPtr tag = tag_list->First;
  while (tag)
    {
      if (tag->TagId == 0xA003)
        {
          // ok, this one is the ExifImageLength tag
          if (tag->Type == 3 && tag->Count == 1)
            {
              *ok = true;
              return *(tag->ShortValues + 0);
          } else if (tag->Type == 4 && tag->Count == 1)
            {
              *ok = true;
              return *(tag->LongValues + 0);
            }
        }
      tag = tag->Next;
    }
  return false;
}

void MyFrame::GetMake(gaiaExifTagListPtr tag_list, wxString & str, bool * ok)
{
//
// trying to retrieve the Make 
//
  *ok = false;
  if (!tag_list)
    return;
  gaiaExifTagPtr tag = tag_list->First;
  while (tag)
    {
      if (tag->TagId == 0x010F)
        {
          // ok, this one is the Make tag 
          if (tag->Type == 2)
            {
              *ok = true;
              str = wxString::FromUTF8(tag->StringValue);
              return;
            }
        }
      tag = tag->Next;
    }
  return;
}

void MyFrame::GetModel(gaiaExifTagListPtr tag_list, wxString & str, bool * ok)
{
//
// trying to retrieve the Model 
//
  *ok = false;
  if (!tag_list)
    return;
  gaiaExifTagPtr tag = tag_list->First;
  while (tag)
    {
      if (tag->TagId == 0x0110)
        {
          // ok, this one is the Model tag
          if (tag->Type == 2)
            {
              *ok = true;
              str = wxString::FromUTF8(tag->StringValue);
              return;
            }
        }
      tag = tag->Next;
    }
  return;
}

void MyFrame::GetDate(gaiaExifTagListPtr tag_list, wxString & str, bool * ok)
{
//
// trying to retrieve the Date 
//
  *ok = false;
  if (!tag_list)
    return;
  gaiaExifTagPtr tag = tag_list->First;
  while (tag)
    {
      if (tag->TagId == 0x9003)
        {
          // ok, this one is the DateTimeOriginal tag 
          if (tag->Type == 2)
            {
              *ok = true;
              str = wxString::FromUTF8(tag->StringValue);
              if (str.Len() >= 19)
                {
                  str.SetChar(4, '-');
                  str.SetChar(7, '-');
                }
              return;
            }
        }
      tag = tag->Next;
    }
  return;
}

void MyFrame::GetGpsCoords(gaiaExifTagListPtr tag_list, double *longitude,
                           double *latitude, bool * ok)
{
//
// trying to retrieve the GPS coordinates 
//
  char lat_ref = '\0';
  char long_ref = '\0';
  double lat_degs = DBL_MIN;
  double lat_mins = DBL_MIN;
  double lat_secs = DBL_MIN;
  double long_degs = DBL_MIN;
  double long_mins = DBL_MIN;
  double long_secs = DBL_MIN;
  double dblval;
  double sign;
  int xok;
  *ok = false;
  if (!tag_list)
    return;
  gaiaExifTagPtr tag = tag_list->First;
  while (tag)
    {
      if (tag->Gps && tag->TagId == 0x01)
        {
          // ok, this one is the GPSLatitudeRef tag
          if (tag->Type == 2)
            lat_ref = *(tag->StringValue);
        }
      if (tag->Gps && tag->TagId == 0x03)
        {
          // ok, this one is the GPSLongitudeRef tag
          if (tag->Type == 2)
            long_ref = *(tag->StringValue);
        }
      if (tag->Gps && tag->TagId == 0x02)
        {
          // ok, this one is the GPSLatitude tag 
          if (tag->Type == 5 && tag->Count == 3)
            {
              dblval = gaiaExifTagGetRationalValue(tag, 0, &xok);
              if (xok)
                lat_degs = dblval;
              dblval = gaiaExifTagGetRationalValue(tag, 1, &xok);
              if (xok)
                lat_mins = dblval;
              dblval = gaiaExifTagGetRationalValue(tag, 2, &xok);
              if (xok)
                lat_secs = dblval;
            }
        }
      if (tag->Gps && tag->TagId == 0x04)
        {
          // ok, this one is the GPSLongitude tag
          if (tag->Type == 5 && tag->Count == 3)
            {
              dblval = gaiaExifTagGetRationalValue(tag, 0, &xok);
              if (xok)
                long_degs = dblval;
              dblval = gaiaExifTagGetRationalValue(tag, 1, &xok);
              if (xok)
                long_mins = dblval;
              dblval = gaiaExifTagGetRationalValue(tag, 2, &xok);
              if (xok)
                long_secs = dblval;
            }
        }
      tag = tag->Next;
    }
  if ((lat_ref == 'N' || lat_ref == 'S' || long_ref == 'E' || long_ref == 'W')
      && lat_degs != DBL_MIN && lat_mins != DBL_MIN && lat_secs != DBL_MIN
      && long_degs != DBL_MIN && long_mins != DBL_MIN && long_secs != DBL_MIN)
    {
      *ok = true;
      if (lat_ref == 'S')
        sign = -1.0;
      else
        sign = 1.0;
      lat_degs = math_round(lat_degs * 1000000.0);
      lat_mins = math_round(lat_mins * 1000000.0);
      lat_secs = math_round(lat_secs * 1000000.0);
      dblval =
        math_round(lat_degs + (lat_mins / 60.0) +
                   (lat_secs / 3600.0)) * (sign / 1000000.0);
      *latitude = dblval;
      if (long_ref == 'W')
        sign = -1.0;
      else
        sign = 1.0;
      long_degs = math_round(long_degs * 1000000.0);
      long_mins = math_round(long_mins * 1000000.0);
      long_secs = math_round(long_secs * 1000000.0);
      dblval =
        math_round(long_degs + (long_mins / 60.0) +
                   (long_secs / 3600.0)) * (sign / 1000000.0);
      *longitude = dblval;
    }
  return;
}

void MyFrame::GetGpsSatellites(gaiaExifTagListPtr tag_list, wxString & str,
                               bool * ok)
{
//
// trying to retrieve the GPSSatellites 
//
  *ok = false;
  if (!tag_list)
    return;
  gaiaExifTagPtr tag = tag_list->First;
  while (tag)
    {
      if (tag->Gps && tag->TagId == 0x08)
        {
          // ok, this one is the GPSSatellites tag
          if (tag->Type == 2)
            {
              *ok = true;
              str = wxString::FromUTF8(tag->StringValue);
              return;
            }
        }
      tag = tag->Next;
    }
  return;
}

double MyFrame::GetGpsDirection(gaiaExifTagListPtr tag_list, bool * ok)
{
//
// trying to retrieve the GPS direction 
//
  char dir_ref = '\0';
  double direction = DBL_MIN;
  double dblval;
  int xok;
  *ok = false;
  if (!tag_list)
    return direction;
  gaiaExifTagPtr tag = tag_list->First;
  while (tag)
    {
      if (tag->Gps && tag->TagId == 0x10)
        {
          // ok, this one is the GPSDirectionRef tag 
          if (tag->Type == 2)
            dir_ref = *(tag->StringValue);
        }
      if (tag->Gps && tag->TagId == 0x11)
        {
          // ok, this one is the GPSDirection tag
          if (tag->Type == 5 && tag->Count == 1)
            {
              dblval = gaiaExifTagGetRationalValue(tag, 0, &xok);
              if (xok)
                direction = dblval;
            }
        }
      tag = tag->Next;
    }
  if ((dir_ref == 'T' || dir_ref == 'M') && direction != DBL_MIN)
    *ok = true;
  return direction;
}

void MyFrame::GetGpsTimestamp(gaiaExifTagListPtr tag_list, wxString & str,
                              bool * ok)
{
//
// trying to retrieve the GPS Timestamp 
//
  char date[16];
  char timestamp[32];
  double hours = DBL_MIN;
  double mins = DBL_MIN;
  double secs = DBL_MIN;
  double dblval;
  int xok;
  int hh;
  int mm;
  int ss;
  int millis;
  *ok = false;
  if (!tag_list)
    return;
  strcpy(date, "0000-00-00");
  gaiaExifTagPtr tag = tag_list->First;
  while (tag)
    {
      if (tag->Gps && tag->TagId == 0x1D)
        {
          // ok, this one is the GPSDateStamp tag 
          if (tag->Type == 2)
            {
              strcpy(date, tag->StringValue);
              date[4] = '-';
              date[7] = '-';
            }
        }
      if (tag->Gps && tag->TagId == 0x07)
        {
          // ok, this one is the GPSTimeStamp tag 
          if (tag->Type == 5 && tag->Count == 3)
            {
              dblval = gaiaExifTagGetRationalValue(tag, 0, &xok);
              if (xok)
                hours = dblval;
              dblval = gaiaExifTagGetRationalValue(tag, 1, &xok);
              if (xok)
                mins = dblval;
              dblval = gaiaExifTagGetRationalValue(tag, 2, &xok);
              if (xok)
                secs = dblval;
            }
        }
      tag = tag->Next;
    }
  if (hours != DBL_MIN && mins != DBL_MIN && secs != DBL_MIN)
    {
      *ok = true;
      hh = (int) floor(hours);
      mm = (int) floor(mins);
      ss = (int) floor(secs);
      millis = (int) ((secs - ss) * 1000);
      sprintf(timestamp, "%s %02d:%02d:%02d.%03d", date, hh, mm, ss, millis);
      str = wxString::FromUTF8(timestamp);
    }
  return;
}

Changes to Main.cpp.

1
2
3
4
5
6
7
8
9
10
11
12
..
24
25
26
27
28
29
30

31
32
33
34
35
36
37
38
39

40
41
42




43
44
45
46
47
48


49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580


































































































































































































581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
















































































































































































































































































































































































































































































































































1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388















1389
1390
1391
1392
1393
1394
1395
1396

1397
1398
1399
1400
1401

1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176





























































































































































































































































































































































































































































































































































































































/*
/ Main.cpp
/ the main core of spatialite-gui  - a SQLite /SpatiaLite GUI tool
/
/ version 1.1, 2008 September 13
/
/ Author: Sandro Furieri a-furieri@lqt.it
/
/ Copyright (C) 2008  Alessandro Furieri
/
/    This program is free software: you can redistribute it and/or modify
/    it under the terms of the GNU General Public License as published by
................................................................................
*/

#include "Classdef.h"

#include "wx/menu.h"
#include "wx/aboutdlg.h"
#include "wx/filename.h"


#include <spatialite.h>
#include <proj_api.h>
#include <geos_c.h>

//
// ICONs in XPM format [universally portable]
//
#include "icons/icon.xpm"

#include "icons/create_new.xpm"
#include "icons/connect.xpm"
#include "icons/disconnect.xpm"




#include "icons/vacuum.xpm"
#include "icons/sql_script.xpm"
#include "icons/loadshp.xpm"
#include "icons/virtshp.xpm"
#include "icons/loadtxt.xpm"
#include "icons/virttxt.xpm"


#include "icons/srids.xpm"
#include "icons/charset.xpm"
#include "icons/help.xpm"
#include "icons/about.xpm"
#include "icons/exit.xpm"

IMPLEMENT_APP (MyApp)
     bool MyApp::OnInit ()
{
//
// main APP implementation
//
    wxString path;
    if (argc > 1)
	path = argv[1];
    MyFrame *frame =
	new
	MyFrame (wxT ("spatialite-gui      [a GUI tool for SQLite/SpatiaLite]"),
		 wxPoint (0, 0), wxSize (640, 480), path);
    frame->Show (true);
    SetTopWindow (frame);
    return true;
}

MyFrame::MyFrame (const wxString & title, const wxPoint & pos, const wxSize & size, wxString & path):
wxFrame ((wxFrame *) NULL, -1, title, pos,
	 size)
{
//
// main GUI frame constructor
//

//
// setting up the BLOB signatures
//
    Jpeg1Signature[0] = 0xff;
    Jpeg1Signature[1] = 0xd8;
    Jpeg2Signature[0] = 0xff;
    Jpeg2Signature[1] = 0xd9;
    Jpeg3Signature[0] = 0xff;
    Jpeg3Signature[1] = 0xd8;
    Jpeg3Signature[2] = 0xff;
    Jpeg3Signature[3] = 0xe0;
    JfifSignature[0] = 0x4a;
    JfifSignature[1] = 0x46;
    JfifSignature[2] = 0x49;
    JfifSignature[3] = 0x46;
    ExifSignature[0] = 0x45;
    ExifSignature[1] = 0x78;
    ExifSignature[2] = 0x69;
    ExifSignature[3] = 0x66;
    PngSignature[0] = 0x89;
    PngSignature[1] = 0x50;
    PngSignature[2] = 0x4e;
    PngSignature[3] = 0x47;
    PngSignature[4] = 0x0d;
    PngSignature[5] = 0x0a;
    PngSignature[6] = 0x1a;
    PngSignature[7] = 0x0a;
    ZipSignature[0] = 0x50;
    ZipSignature[1] = 0x4b;
    ZipSignature[2] = 0x03;
    ZipSignature[3] = 0x04;

//
// initializing CHARSET lists
//
    CharsetsLen = 79;
    Charsets = new wxString[CharsetsLen];
    CharsetsNames = new wxString[CharsetsLen];
    *(CharsetsNames + 0) = wxT ("ARMSCII-8    Armenian");
    *(CharsetsNames + 1) = wxT ("ASCII        US-ASCII");
    *(CharsetsNames + 2) = wxT ("BIG5         Chinese/Traditional");
    *(CharsetsNames + 3) = wxT ("BIG5-HKSCS   Chinese/Hong Kong");
    *(CharsetsNames + 4) = wxT ("BIG5-HKSCS:1999");
    *(CharsetsNames + 5) = wxT ("BIG5-HKSCS:2001");
    *(CharsetsNames + 6) = wxT ("CP850        DOS/OEM Western Europe");
    *(CharsetsNames + 7) = wxT ("CP862        DOS/OEM Hebrew");
    *(CharsetsNames + 8) = wxT ("CP866        DOS/OEM Cyrillic");
    *(CharsetsNames + 9) = wxT ("CP874        DOS/OEM Thai");
    *(CharsetsNames + 10) = wxT ("CP932        DOS/OEM Japanese");
    *(CharsetsNames + 11) = wxT ("CP936        DOS/OEM Chinese");
    *(CharsetsNames + 12) = wxT ("CP949        DOS/OEM Korean");
    *(CharsetsNames + 13) = wxT ("CP950        DOS/OEM Chinese/Big5");
    *(CharsetsNames + 14) = wxT ("CP1133       Laotian");
    *(CharsetsNames + 15) = wxT ("CP1250       Windows Central Europe");
    *(CharsetsNames + 16) = wxT ("CP1251       Windows Cyrillic");
    *(CharsetsNames + 17) = wxT ("CP1252       Windows Latin 1");
    *(CharsetsNames + 18) = wxT ("CP1253       Windows Greek");
    *(CharsetsNames + 19) = wxT ("CP1254       Windows Turkish");
    *(CharsetsNames + 20) = wxT ("CP1255       Windows Hebrew");
    *(CharsetsNames + 21) = wxT ("CP1256       Windows Arabic");
    *(CharsetsNames + 22) = wxT ("CP1257       Windows Baltic");
    *(CharsetsNames + 23) = wxT ("CP1258       Windows Vietnamese");
    *(CharsetsNames + 24) = wxT ("EUC-CN       Chinese");
    *(CharsetsNames + 25) = wxT ("EUC-JP       Japanese");
    *(CharsetsNames + 26) = wxT ("EUC-KR       Korean");
    *(CharsetsNames + 27) = wxT ("EUC-TW       Taiwan");
    *(CharsetsNames + 28) = wxT ("GB18030      Chinese/National Standard");
    *(CharsetsNames + 29) = wxT ("GBK          Chinese/Simplified");
    *(CharsetsNames + 30) = wxT ("Georgian-Academy");
    *(CharsetsNames + 31) = wxT ("Georgian-PS");
    *(CharsetsNames + 32) = wxT ("HZ           Chinese");
    *(CharsetsNames + 33) = wxT ("ISO-2022-CN  Chinese");
    *(CharsetsNames + 34) = wxT ("ISO-2022-CN-EXT");
    *(CharsetsNames + 35) = wxT ("ISO-2022-JP  Japanese");
    *(CharsetsNames + 36) = wxT ("ISO-2022-JP-1");
    *(CharsetsNames + 37) = wxT ("ISO-2022-JP-2");
    *(CharsetsNames + 38) = wxT ("ISO-2022-KR  Korean");
    *(CharsetsNames + 39) = wxT ("ISO-8859-1   Latin-1 Western European");
    *(CharsetsNames + 40) = wxT ("ISO-8859-2   Latin-2 Central European");
    *(CharsetsNames + 41) = wxT ("ISO-8859-3   Latin-3 South European");
    *(CharsetsNames + 42) = wxT ("ISO-8859-4   Latin-4 North European");
    *(CharsetsNames + 43) = wxT ("ISO-8859-5   Latin/Cyrillic");
    *(CharsetsNames + 44) = wxT ("ISO-8859-6   Latin/Arabic");
    *(CharsetsNames + 45) = wxT ("ISO-8859-7   Latin/Greek");
    *(CharsetsNames + 46) = wxT ("ISO-8859-8   Latin/Hebrew");
    *(CharsetsNames + 47) = wxT ("ISO-8859-9   Latin-5 Turkish");
    *(CharsetsNames + 48) = wxT ("ISO-8859-10  Latin-6 Nordic");
    *(CharsetsNames + 49) = wxT ("ISO-8859-11  Latin/Thai");
    *(CharsetsNames + 50) = wxT ("ISO-8859-13  Latin-7 Baltic Rim");
    *(CharsetsNames + 51) = wxT ("ISO-8859-14  Latin-8 Celtic");
    *(CharsetsNames + 52) = wxT ("ISO-8859-15  Latin-9");
    *(CharsetsNames + 53) =
	wxT ("ISO-8859-16  Latin-10 South-Eastern European");
    *(CharsetsNames + 54) = wxT ("JOHAB        Korean");
    *(CharsetsNames + 55) = wxT ("KOI8-R       Russian");
    *(CharsetsNames + 56) = wxT ("KOI8-U       Ukrainian");
    *(CharsetsNames + 57) = wxT ("KOI8-RU      Belarusian");
    *(CharsetsNames + 58) = wxT ("KOI8-T       Tajik");
    *(CharsetsNames + 59) = wxT ("MacArabic    MAC Arabic");
    *(CharsetsNames + 60) = wxT ("MacCentralEurope");
    *(CharsetsNames + 61) = wxT ("MacCroatian  MAC Croatian");
    *(CharsetsNames + 62) = wxT ("MacCyrillic  MAC Cyrillic");
    *(CharsetsNames + 63) = wxT ("MacGreek     MAC Greek");
    *(CharsetsNames + 64) = wxT ("MacHebrew    MAC Hebrew");
    *(CharsetsNames + 65) = wxT ("MacIceland   MAC Iceland");
    *(CharsetsNames + 66) = wxT ("Macintosh");
    *(CharsetsNames + 67) = wxT ("MacRoman     MAC European/Western languages");
    *(CharsetsNames + 68) = wxT ("MacRomania   MAC Romania");
    *(CharsetsNames + 69) = wxT ("MacThai      MAC Thai");
    *(CharsetsNames + 70) = wxT ("MacTurkish   MAC Turkish");
    *(CharsetsNames + 71) = wxT ("MacUkraine   MAC Ukraine");
    *(CharsetsNames + 72) = wxT ("MuleLao-1    Laotian");
    *(CharsetsNames + 73) = wxT ("PT154        Kazakh");
    *(CharsetsNames + 74) = wxT ("RK1048       Kazakh");
    *(CharsetsNames + 75) = wxT ("SHIFT_JIS    Japanese");
    *(CharsetsNames + 76) = wxT ("TCVN         Vietnamese");
    *(CharsetsNames + 77) = wxT ("TIS-620      Thai");
    *(CharsetsNames + 77) = wxT ("UTF-8        UNICODE/Universal");
    *(CharsetsNames + 78) = wxT ("VISCII       Vietnamese");
    *(Charsets + 0) = wxT ("ARMSCII-8");
    *(Charsets + 1) = wxT ("ASCII");
    *(Charsets + 2) = wxT ("BIG5");
    *(Charsets + 3) = wxT ("BIG5-HKSCS");
    *(Charsets + 4) = wxT ("BIG5-HKSCS:1999");
    *(Charsets + 5) = wxT ("BIG5-HKSCS:2001");
    *(Charsets + 6) = wxT ("CP850");
    *(Charsets + 7) = wxT ("CP862");
    *(Charsets + 8) = wxT ("CP866");
    *(Charsets + 9) = wxT ("CP874");
    *(Charsets + 10) = wxT ("CP932");
    *(Charsets + 11) = wxT ("CP936");
    *(Charsets + 12) = wxT ("CP949");
    *(Charsets + 13) = wxT ("CP950");
    *(Charsets + 14) = wxT ("CP1133");
    *(Charsets + 15) = wxT ("CP1250");
    *(Charsets + 16) = wxT ("CP1251");
    *(Charsets + 17) = wxT ("CP1252");
    *(Charsets + 18) = wxT ("CP1253");
    *(Charsets + 19) = wxT ("CP1254");
    *(Charsets + 20) = wxT ("CP1255");
    *(Charsets + 21) = wxT ("CP1256");
    *(Charsets + 22) = wxT ("CP1257");
    *(Charsets + 23) = wxT ("CP1258");
    *(Charsets + 24) = wxT ("EUC-CN");
    *(Charsets + 25) = wxT ("EUC-JP");
    *(Charsets + 26) = wxT ("EUC-KR");
    *(Charsets + 27) = wxT ("EUC-TW");
    *(Charsets + 28) = wxT ("GB18030");
    *(Charsets + 29) = wxT ("GBK");
    *(Charsets + 30) = wxT ("Georgian-Academy");
    *(Charsets + 31) = wxT ("Georgian-PS");
    *(Charsets + 32) = wxT ("HZ");
    *(Charsets + 33) = wxT ("ISO-2022-CN");
    *(Charsets + 34) = wxT ("ISO-2022-CN-EXT");
    *(Charsets + 35) = wxT ("ISO-2022-JP");
    *(Charsets + 36) = wxT ("ISO-2022-JP-1");
    *(Charsets + 37) = wxT ("ISO-2022-JP-2");
    *(Charsets + 38) = wxT ("ISO-2022-KR");
    *(Charsets + 39) = wxT ("ISO-8859-1");
    *(Charsets + 40) = wxT ("ISO-8859-2");
    *(Charsets + 41) = wxT ("ISO-8859-3");
    *(Charsets + 42) = wxT ("ISO-8859-4");
    *(Charsets + 43) = wxT ("ISO-8859-5");
    *(Charsets + 44) = wxT ("ISO-8859-6");
    *(Charsets + 45) = wxT ("ISO-8859-7");
    *(Charsets + 46) = wxT ("ISO-8859-8");
    *(Charsets + 47) = wxT ("ISO-8859-9");
    *(Charsets + 48) = wxT ("ISO-8859-10");
    *(Charsets + 49) = wxT ("ISO-8859-11");
    *(Charsets + 50) = wxT ("ISO-8859-13");
    *(Charsets + 51) = wxT ("ISO-8859-14");
    *(Charsets + 52) = wxT ("ISO-8859-15");
    *(Charsets + 53) = wxT ("ISO-8859-16");
    *(Charsets + 54) = wxT ("JOHAB");
    *(Charsets + 55) = wxT ("KOI8-R");
    *(Charsets + 56) = wxT ("KOI8-U");
    *(Charsets + 57) = wxT ("KOI8-RU");
    *(Charsets + 58) = wxT ("KOI8-T");
    *(Charsets + 59) = wxT ("MacArabic");
    *(Charsets + 60) = wxT ("MacCentralEurope");
    *(Charsets + 61) = wxT ("MacCroatian");
    *(Charsets + 62) = wxT ("MacCyrillic");
    *(Charsets + 63) = wxT ("MacGreek");
    *(Charsets + 64) = wxT ("MacHebrew");
    *(Charsets + 65) = wxT ("MacIceland");
    *(Charsets + 66) = wxT ("Macintosh");
    *(Charsets + 67) = wxT ("MacRoman");
    *(Charsets + 68) = wxT ("MacRomania");
    *(Charsets + 69) = wxT ("MacThai");
    *(Charsets + 70) = wxT ("MacTurkish");
    *(Charsets + 71) = wxT ("MacUkraine");
    *(Charsets + 72) = wxT ("MuleLao-1");
    *(Charsets + 73) = wxT ("PT154");
    *(Charsets + 74) = wxT ("RK1048");
    *(Charsets + 75) = wxT ("SHIFT_JIS");
    *(Charsets + 76) = wxT ("TCVN");
    *(Charsets + 77) = wxT ("TIS-620");
    *(Charsets + 77) = wxT ("UTF-8");
    *(Charsets + 78) = wxT ("VISCII");
    LocaleCharset = wxString::FromUTF8 (gaiaGetLocaleCharset ());
    DefaultCharset = LocaleCharset;
    AskCharset = false;

    spatialite_init (0);	// loading the SpatiaLite extension

    HelpPane = false;
    SqliteHandle = NULL;
    SqlitePath = wxT ("");
    BtnConnect = new wxBitmap (connect_xpm);
    BtnCreateNew = new wxBitmap (create_new_xpm);
    BtnDisconnect = new wxBitmap (disconnect_xpm);
    BtnVacuum = new wxBitmap (vacuum_xpm);
    BtnSqlScript = new wxBitmap (sql_script_xpm);
    BtnLoadShp = new wxBitmap (loadshp_xpm);
    BtnVirtualShp = new wxBitmap (virtshp_xpm);
    BtnLoadTxt = new wxBitmap (loadtxt_xpm);
    BtnVirtualTxt = new wxBitmap (virttxt_xpm);
    BtnSrids = new wxBitmap (srids_xpm);
    BtnCharset = new wxBitmap (charset_xpm);
    BtnHelp = new wxBitmap (help_xpm);
    BtnAbout = new wxBitmap (about_xpm);
    BtnExit = new wxBitmap (exit_xpm);

//
// setting up the application icon
//      
    wxIcon MyIcon (icon_xpm);
    SetIcon (MyIcon);

//
// setting up panes
//
    TableTree = new MyTableTree (this);
    QueryView = new MyQueryView (this);
    Manager.SetManagedWindow (this);
    wxAuiPaneInfo paneView = wxAuiPaneInfo ().CenterPane ();
    paneView.Caption (wxT ("SQL Query"));
    paneView.Floatable (false);
    paneView.CloseButton (false);
    Manager.AddPane (QueryView, paneView);
    wxAuiPaneInfo paneTree = wxAuiPaneInfo ().Left ();
    paneTree.Caption (wxT ("DB Tables"));
    paneTree.Floatable (false);
    paneTree.CloseButton (false);
    paneTree.BestSize (wxSize (200, 480));
    Manager.AddPane (TableTree, paneTree);
    Manager.Update ();
    Centre ();

//
// setting up the status bar
//
    wxStatusBar *statusBar = new wxStatusBar (this);
    SetStatusBar (statusBar);

//
// setting up the menu bar
//
    wxMenu *menuFile = new wxMenu;
    wxMenuItem *menuItem;
    menuItem = new wxMenuItem (menuFile, ID_Connect,
			       wxT ("&Connecting an existing SQLite DB"));
    menuItem->SetBitmap (*BtnConnect);
    menuFile->Append (menuItem);
    menuItem = new wxMenuItem (menuFile, ID_CreateNew,
			       wxT ("Creating a &New (empty) SQLite DB"));
    menuItem->SetBitmap (*BtnCreateNew);
    menuFile->Append (menuItem);
    menuItem = new wxMenuItem (menuFile, ID_Disconnect,
			       wxT ("&Disconnecting current SQLite DB"));
    menuItem->SetBitmap (*BtnDisconnect);
    menuFile->Append (menuItem);
    menuItem = new wxMenuItem (menuFile, ID_Vacuum,
			       wxT ("&Optimizing current SQLite DB [VACUUM]"));
    menuItem->SetBitmap (*BtnVacuum);
    menuFile->Append (menuItem);
    menuFile->AppendSeparator ();
    menuItem = new wxMenuItem (menuFile, ID_SqlScript,
			       wxT ("&Execute SQL script"));
    menuItem->SetBitmap (*BtnSqlScript);
    menuFile->Append (menuItem);
    menuFile->AppendSeparator ();
    menuItem = new wxMenuItem (menuFile, ID_LoadShp, wxT ("&Load Shapefile"));
    menuItem->SetBitmap (*BtnLoadShp);
    menuFile->Append (menuItem);
    menuItem = new wxMenuItem (menuFile, ID_VirtualShp,
			       wxT ("&Virtual Shapefile"));
    menuItem->SetBitmap (*BtnVirtualShp);
    menuFile->Append (menuItem);
    menuFile->AppendSeparator ();
    menuItem = new wxMenuItem (menuFile, ID_LoadTxt, wxT ("Load CSV/&TXT"));
    menuItem->SetBitmap (*BtnLoadTxt);
    menuFile->Append (menuItem);
    menuItem = new wxMenuItem (menuFile, ID_VirtualTxt,
			       wxT ("Virtual &CSV/TXT"));
    menuItem->SetBitmap (*BtnVirtualTxt);
    menuFile->Append (menuItem);
    menuFile->AppendSeparator ();
    menuItem = new wxMenuItem (menuFile, ID_Srids,
			       wxT ("&Search SRID by name"));
    menuItem->SetBitmap (*BtnSrids);
    menuFile->Append (menuItem);
    menuItem = new wxMenuItem (menuFile, ID_Charset,
			       wxT ("&Default Output Charset"));
    menuItem->SetBitmap (*BtnCharset);
    menuFile->Append (menuItem);
    menuFile->AppendSeparator ();
    menuItem = new wxMenuItem (menuFile, ID_Help, wxT ("&Help"));
    menuItem->SetBitmap (*BtnHelp);
    menuItem = new wxMenuItem (menuFile, wxID_ABOUT, wxT ("&About ..."));
    menuItem->SetBitmap (*BtnAbout);
    menuFile->Append (menuItem);
    menuFile->AppendSeparator ();
    menuItem = new wxMenuItem (menuFile, wxID_EXIT, wxT ("&Quit"));
    menuItem->SetBitmap (*BtnExit);
    menuFile->Append (menuItem);
    wxMenuBar *menuBar = new wxMenuBar;
    menuBar->Append (menuFile, wxT ("&Files"));
    SetMenuBar (menuBar);

//
// setting up menu initial state 
//
    menuBar->Enable (ID_Disconnect, false);
    menuBar->Enable (ID_Vacuum, false);
    menuBar->Enable (ID_SqlScript, false);
    menuBar->Enable (ID_LoadShp, false);
    menuBar->Enable (ID_VirtualShp, false);
    menuBar->Enable (ID_LoadTxt, false);
    menuBar->Enable (ID_VirtualTxt, false);
    menuBar->Enable (ID_Srids, false);

//
// setting up the toolbar
//      
    wxToolBar *toolBar = CreateToolBar ();
    toolBar->AddTool (ID_Connect, wxT ("Connecting an existing SQLite DB"),
		      *BtnConnect, wxNullBitmap,
		      wxITEM_NORMAL, wxT ("Connecting an existing SQLite DB"));
    toolBar->AddTool (ID_CreateNew, wxT ("Creating a &New (empty) SQLite DB"),
		      *BtnCreateNew, wxNullBitmap,
		      wxITEM_NORMAL, wxT ("Creating a &New (empty) SQLite DB"));
    toolBar->AddTool (ID_Disconnect, wxT ("Disconnecting current SQLite DB"),
		      *BtnDisconnect, wxNullBitmap,
		      wxITEM_NORMAL, wxT ("Disconnecting current SQLite DB"));
    toolBar->AddTool (ID_Vacuum, wxT ("Optimizing current SQLite DB [VACUUM]"),
		      *BtnVacuum, wxNullBitmap,
		      wxITEM_NORMAL,
		      wxT ("Optimizing current SQLite DB [VACUUM]"));
    toolBar->AddSeparator ();
    toolBar->AddTool (ID_SqlScript, wxT ("Execute SQL script"),
		      *BtnSqlScript, wxNullBitmap,
		      wxITEM_NORMAL, wxT ("Execute SQL script"));
    toolBar->AddSeparator ();
    toolBar->AddTool (ID_LoadShp, wxT ("Load Shapefile"),
		      *BtnLoadShp, wxNullBitmap,
		      wxITEM_NORMAL, wxT ("Load Shapefile"));
    toolBar->AddTool (ID_VirtualShp, wxT ("Virtual Shapefile"),
		      *BtnVirtualShp, wxNullBitmap,
		      wxITEM_NORMAL, wxT ("Virtual Shapefile"));
    toolBar->AddSeparator ();
    toolBar->AddTool (ID_LoadTxt, wxT ("Load CSV/TXT"),
		      *BtnLoadTxt, wxNullBitmap,
		      wxITEM_NORMAL, wxT ("Load CSV/TXT"));
    toolBar->AddTool (ID_VirtualTxt, wxT ("Virtual CSV/TXT"),
		      *BtnVirtualTxt, wxNullBitmap,
		      wxITEM_NORMAL, wxT ("Virtual CSV/TXT"));
    toolBar->AddSeparator ();
    toolBar->AddTool (ID_Srids, wxT ("Search SRID by name"),
		      *BtnSrids, wxNullBitmap,
		      wxITEM_NORMAL, wxT ("Search SRID by name"));
    toolBar->AddSeparator ();
    toolBar->AddTool (ID_Charset, wxT ("Default Output Charset"),
		      *BtnCharset, wxNullBitmap,
		      wxITEM_NORMAL, wxT ("Default Output Charset"));
    toolBar->AddSeparator ();
    toolBar->AddTool (ID_Help, wxT ("Help"), *BtnHelp, wxNullBitmap,
		      wxITEM_NORMAL, wxT ("Help"));
    toolBar->AddTool (wxID_ABOUT, wxT ("About ..."), *BtnAbout, wxNullBitmap,
		      wxITEM_NORMAL, wxT ("About ..."));
    toolBar->AddSeparator ();
    toolBar->AddTool (wxID_EXIT, wxT ("Quit"), *BtnExit, wxNullBitmap,
		      wxITEM_NORMAL, wxT ("Quit"));
    toolBar->Realize ();
    SetToolBar (toolBar);

//
// setting up the toolbar initial state
//
    toolBar->EnableTool (ID_Disconnect, false);
    toolBar->EnableTool (ID_Vacuum, false);
    toolBar->EnableTool (ID_SqlScript, false);
    toolBar->EnableTool (ID_LoadShp, false);
    toolBar->EnableTool (ID_VirtualShp, false);
    toolBar->EnableTool (ID_LoadTxt, false);
    toolBar->EnableTool (ID_VirtualTxt, false);
    toolBar->EnableTool (ID_Srids, false);

// updating the status bar
    UpdateStatusBar ();

//
// setting up event handlers for menu and toolbar
//
    Connect (ID_Connect, wxEVT_COMMAND_MENU_SELECTED,
	     (wxObjectEventFunction) & MyFrame::OnConnect);
    Connect (ID_CreateNew, wxEVT_COMMAND_MENU_SELECTED,
	     (wxObjectEventFunction) & MyFrame::OnCreateNew);
    Connect (ID_Disconnect, wxEVT_COMMAND_MENU_SELECTED,
	     (wxObjectEventFunction) & MyFrame::OnDisconnect);
    Connect (ID_Vacuum, wxEVT_COMMAND_MENU_SELECTED,
	     (wxObjectEventFunction) & MyFrame::OnVacuum);
    Connect (ID_SqlScript, wxEVT_COMMAND_MENU_SELECTED,
	     (wxObjectEventFunction) & MyFrame::OnSqlScript);
    Connect (ID_LoadShp, wxEVT_COMMAND_MENU_SELECTED,
	     (wxObjectEventFunction) & MyFrame::OnLoadShp);
    Connect (ID_VirtualShp, wxEVT_COMMAND_MENU_SELECTED,
	     (wxObjectEventFunction) & MyFrame::OnVirtualShp);
    Connect (ID_LoadTxt, wxEVT_COMMAND_MENU_SELECTED,
	     (wxObjectEventFunction) & MyFrame::OnLoadTxt);
    Connect (ID_VirtualTxt, wxEVT_COMMAND_MENU_SELECTED,
	     (wxObjectEventFunction) & MyFrame::OnVirtualTxt);
    Connect (ID_Srids, wxEVT_COMMAND_MENU_SELECTED,
	     (wxObjectEventFunction) & MyFrame::OnSrids);
    Connect (ID_Charset, wxEVT_COMMAND_MENU_SELECTED,
	     (wxObjectEventFunction) & MyFrame::OnCharset);
    Connect (ID_Help, wxEVT_COMMAND_MENU_SELECTED,
	     (wxObjectEventFunction) & MyFrame::OnHelp);
    Connect (wxID_ABOUT, wxEVT_COMMAND_MENU_SELECTED,
	     (wxObjectEventFunction) & MyFrame::OnAbout);
    Connect (wxID_EXIT, wxEVT_COMMAND_MENU_SELECTED,
	     (wxObjectEventFunction) & MyFrame::OnQuit);
    Connect (wxID_ANY, wxEVT_MOTION,
	     wxMouseEventHandler (MyFrame::OnMouseMove), NULL, this);

//
// setting up event handlers for mouse
//
    TableTree->Connect (wxID_ANY, wxEVT_MOTION,
			wxMouseEventHandler (MyFrame::OnMouseMove), NULL, this);
    GetMenuBar ()->Connect (wxID_ANY, wxEVT_MOTION,
			    wxMouseEventHandler (MyFrame::OnMouseMove), NULL,
			    this);
    GetStatusBar ()->Connect (wxID_ANY, wxEVT_MOTION,
			      wxMouseEventHandler (MyFrame::OnMouseMove), NULL,
			      this);
}

MyFrame::~MyFrame ()
{
//
// main GUI frame destructor
//
    Manager.UnInit ();
    if (SqliteHandle)
	sqlite3_close (SqliteHandle);
    if (BtnConnect != NULL)
	delete BtnConnect;
    if (BtnCreateNew != NULL)
	delete BtnCreateNew;
    if (BtnDisconnect != NULL)
	delete BtnDisconnect;
    if (BtnVacuum != NULL)
	delete BtnVacuum;
    if (BtnSqlScript != NULL)
	delete BtnSqlScript;
    if (BtnLoadShp != NULL)
	delete BtnLoadShp;
    if (BtnVirtualShp != NULL)
	delete BtnVirtualShp;
    if (BtnLoadTxt != NULL)
	delete BtnLoadTxt;
    if (BtnVirtualTxt != NULL)
	delete BtnVirtualTxt;
    if (BtnSrids != NULL)
	delete BtnSrids;
    if (BtnHelp != NULL)
	delete BtnHelp;
    if (BtnAbout != NULL)
	delete BtnAbout;
    if (BtnExit != NULL)
	delete BtnExit;
    if (Charsets)
	delete[]Charsets;
    if (CharsetsNames)
	delete[]CharsetsNames;
}

void
MyFrame::OnQuit (wxCommandEvent & WXUNUSED (event))
{
//
// EXIT - event handler
//
    CloseDB ();
    Close (TRUE);
}

void
MyFrame::OnHelp (wxCommandEvent & WXUNUSED (event))


































































































































































































{
//
// HELP - event handler
//
    if (HelpPane == true)
	return;
    HelpDialog *help = new HelpDialog (this);
    help->Show ();
}

void
MyFrame::OnAbout (wxCommandEvent & WXUNUSED (event))
{
//
// ABOUT dialog - event handler
//
    char ver[128];
    wxAboutDialogInfo dlg;
    dlg.SetName (wxT ("spatialite-gui"));
    dlg.SetVersion (wxT ("v1.1"));
    wxString str = wxT ("a GUI-tool for SQLite / SpatiaLite\n\n");
    strcpy (ver, spatialite_version ());
    str += wxT ("SpatiaLite version ") + wxString::FromUTF8 (ver) + wxT ("\n");
    strcpy (ver, sqlite3_libversion ());
    str += wxT ("SQLite version ") + wxString::FromUTF8 (ver) + wxT ("\n");
    strcpy (ver, GEOSversion ());
    str += wxT ("GEOS version ") + wxString::FromUTF8 (ver) + wxT ("\n");
    strcpy (ver, pj_get_release ());
    str += wxT ("PROJ.4 version ") + wxString::FromUTF8 (ver) + wxT ("\n\n");
    str += wxT ("SQLite's extension 'SpatiaLite' enabled\n");
    str += wxT ("SQLite's extension 'VirtualShape' enabled\n");
    str += wxT ("SQLite's extension 'VirtualText' enabled\n");
    str += wxT ("SQLite's extension 'RTree' enabled\n");
    str += wxT ("SQLite's extension 'MbrCache' enabled\n\n");
    dlg.SetDescription (str);
    dlg.SetCopyright (wxT ("by Alessandro Furieri - 2008"));
    dlg.SetWebSite (wxT ("http://www.gaia-gis.it"));
    wxString license =
	wxT ("This program is free software; you can redistribute it\n");
    license +=
	wxT
	("and/or modify it under the terms of the GNU General Public License\n");
    license += wxT ("(GPL) as published by the Free Software Foundation\n\n");
    license +=
	wxT
	("A copy of the GPL can be found at\nhttp://www.gnu.org/licenses/gpl.txt");
    dlg.SetLicense (license);
    ::wxAboutBox (dlg);
}

void
MyFrame::OnMouseMove (wxMouseEvent & event)
{
//
// MOUSE motion - event handler
//
    UpdateStatusBar ();
}

void
MyFrame::UpdateStatusBar ()
{
//
// updating the status bar
//
    if (GetStatusBar () == NULL)
	return;
    if (SqlitePath.Len () < 1)
	GetStatusBar ()->SetStatusText (wxT ("not connected"), 0);
    else
	GetStatusBar ()->SetStatusText (wxT ("Current SQLite DB: ") +
					SqlitePath, 0);
    if (SqlitePath.Len () < 1)
	QueryView->HideControls ();
    else
	QueryView->ShowSqlControls ();
}

void
MyFrame::OnConnect (wxCommandEvent & WXUNUSED (event))
{
//
// connecting to an existent SQLite DB
//
    int ret;
    wxString lastDir;
    wxFileDialog *fileDialog = new wxFileDialog (this, wxT ("DB connection"),
						 wxT (""), wxT ("db.sqlite"),
						 wxT
						 ("SQLite DB (*.sqlite)|*.sqlite|All files (*.*)|*.*"),
						 wxFD_OPEN |
						 wxFD_FILE_MUST_EXIST,
						 wxDefaultPosition,
						 wxDefaultSize,
						 wxT ("filedlg"));
    lastDir = GetLastDirectory ();
    if (lastDir.Len () >= 1)
	fileDialog->SetDirectory (lastDir);
    ret = fileDialog->ShowModal ();
    if (ret == wxID_OK)
      {
	  SqlitePath = fileDialog->GetPath ();
	  if (OpenDB () == false)
	      SqlitePath = wxT ("");
	  else
	    {
		wxFileName file (fileDialog->GetPath ());
		lastDir = file.GetPath ();
		SetLastDirectory (lastDir);
		bool metadata = CheckMetadata ();
		wxMenuBar *menuBar = GetMenuBar ();
		menuBar->Enable (ID_Connect, false);
		menuBar->Enable (ID_CreateNew, false);
		menuBar->Enable (ID_Disconnect, true);
		menuBar->Enable (ID_Vacuum, true);
		menuBar->Enable (ID_SqlScript, true);
		menuBar->Enable (ID_LoadShp, true);
		menuBar->Enable (ID_VirtualShp, true);
		menuBar->Enable (ID_LoadTxt, true);
		menuBar->Enable (ID_VirtualTxt, true);
		menuBar->Enable (ID_Srids, metadata);
		wxToolBar *toolBar = GetToolBar ();
		toolBar->EnableTool (ID_Connect, false);
		toolBar->EnableTool (ID_CreateNew, false);
		toolBar->EnableTool (ID_Disconnect, true);
		toolBar->EnableTool (ID_Vacuum, true);
		toolBar->EnableTool (ID_SqlScript, true);
		toolBar->EnableTool (ID_LoadShp, true);
		toolBar->EnableTool (ID_VirtualShp, true);
		toolBar->EnableTool (ID_LoadTxt, true);
		toolBar->EnableTool (ID_VirtualTxt, true);
		toolBar->EnableTool (ID_Srids, metadata);
		UpdateStatusBar ();
	    }
      }
}

void
MyFrame::OnDisconnect (wxCommandEvent & WXUNUSED (event))
{
//
// disconnecting current SQLite DB
//
    CloseDB ();
    wxMenuBar *menuBar = GetMenuBar ();
    menuBar->Enable (ID_Connect, true);
    menuBar->Enable (ID_CreateNew, true);
    menuBar->Enable (ID_Disconnect, false);
    menuBar->Enable (ID_Vacuum, false);
    menuBar->Enable (ID_SqlScript, false);
    menuBar->Enable (ID_LoadShp, false);
    menuBar->Enable (ID_VirtualShp, false);
    menuBar->Enable (ID_LoadTxt, false);
    menuBar->Enable (ID_VirtualTxt, false);
    menuBar->Enable (ID_Srids, false);
    wxToolBar *toolBar = GetToolBar ();
    toolBar->EnableTool (ID_Connect, true);
    toolBar->EnableTool (ID_CreateNew, true);
    toolBar->EnableTool (ID_Disconnect, false);
    toolBar->EnableTool (ID_Vacuum, false);
    toolBar->EnableTool (ID_SqlScript, false);
    toolBar->EnableTool (ID_LoadShp, false);
    toolBar->EnableTool (ID_VirtualShp, false);
    toolBar->EnableTool (ID_LoadTxt, false);
    toolBar->EnableTool (ID_VirtualTxt, false);
    toolBar->EnableTool (ID_Srids, false);
    UpdateStatusBar ();
}

void
MyFrame::OnCreateNew (wxCommandEvent & WXUNUSED (event))
{
//
// creating a new, empty SQLite DB
//
    int retdlg;
    int ret;
    wxString lastDir;
    wxFileDialog *fileDialog =
	new wxFileDialog (this, wxT ("Creating a new, empty DB"),
			  wxT (""), wxT ("db.sqlite"),
			  wxT
			  ("SQLite DB (*.sqlite)|*.sqlite|All files (*.*)|*.*"),
			  wxFD_SAVE | wxFD_OVERWRITE_PROMPT, wxDefaultPosition,
			  wxDefaultSize,
			  wxT ("filedlg"));
    lastDir = GetLastDirectory ();
    if (lastDir.Len () >= 1)
	fileDialog->SetDirectory (lastDir);
    retdlg = fileDialog->ShowModal ();
    if (retdlg == wxID_OK)
      {
	  // creating the new DB
	  SqlitePath = fileDialog->GetPath ();
	  ret = CreateDB ();
	  if (ret == false)
	      goto error;
	  wxFileName file (fileDialog->GetPath ());
	  lastDir = file.GetPath ();
	  SetLastDirectory (lastDir);
	  wxMenuBar *menuBar = GetMenuBar ();
	  menuBar->Enable (ID_Connect, false);
	  menuBar->Enable (ID_CreateNew, false);
	  menuBar->Enable (ID_Disconnect, true);
	  menuBar->Enable (ID_Vacuum, true);
	  menuBar->Enable (ID_SqlScript, true);
	  menuBar->Enable (ID_LoadShp, true);
	  menuBar->Enable (ID_VirtualShp, true);
	  menuBar->Enable (ID_LoadTxt, true);
	  menuBar->Enable (ID_VirtualTxt, true);
	  menuBar->Enable (ID_Srids, false);
	  wxToolBar *toolBar = GetToolBar ();
	  toolBar->EnableTool (ID_Connect, false);
	  toolBar->EnableTool (ID_CreateNew, false);
	  toolBar->EnableTool (ID_Disconnect, true);
	  toolBar->EnableTool (ID_Vacuum, true);
	  toolBar->EnableTool (ID_SqlScript, true);
	  toolBar->EnableTool (ID_LoadShp, true);
	  toolBar->EnableTool (ID_VirtualShp, true);
	  toolBar->EnableTool (ID_LoadTxt, true);
	  toolBar->EnableTool (ID_VirtualTxt, true);
	  toolBar->EnableTool (ID_Srids, false);
	  UpdateStatusBar ();
	  return;
      }
    else
	return;
  error:
    unlink (SqlitePath.ToUTF8 ());
    wxString msg = wxT ("An error occurred\nno DB was created");
    wxMessageBox (msg, wxT ("spatialite-gui"), wxOK | wxICON_ERROR, this);
    return;
}

void
MyFrame::OnVacuum (wxCommandEvent & WXUNUSED (event))
{
//
// performing a VACUUM in order to reorganize the current DB
//
    char *errMsg = NULL;
    ::wxBeginBusyCursor ();
    int ret =
	sqlite3_exec (SqliteHandle, "ANALYZE; VACUUM;", NULL, NULL, &errMsg);
    if (ret != SQLITE_OK)
      {
	  wxMessageBox (wxT ("SQLite SQL error: ") +
			wxString::FromUTF8 (errMsg), wxT ("spatialite-gui"),
			wxOK | wxICON_ERROR, this);
	  sqlite3_free (errMsg);
      }
    else
      {
	  wxMessageBox (wxT ("Current DB was succesfully optimized"),
			wxT ("spatialite-gui"), wxOK | wxICON_INFORMATION,
			this);
      }
    ::wxEndBusyCursor ();
}

char *
MyFrame::ReadSqlLine (FILE * in, int *len, int *eof)
{
//
// reading an SQL script line
//
    int c;
    *eof = 0;
    int size = 4096;
    char *line = (char *) malloc (size);
    int off = 0;
    while ((c = getc (in)) != EOF)
      {
	  // consuming input one chat at each time
	  if (off == size)
	    {
		// buffer overflow; reallocating a bigger one
		// presumably this is because there is some BLOB, so we'll grow by 1MB at each time
		size += 1024 * 1024;
		line = (char *) realloc (line, size);
	    }
	  *(line + off) = c;
	  off++;
	  if (c == '\n')
	    {
		// end of line marker
		*(line + off) = '\0';
		*len = off;
		return line;
	    }
	  if (c == ';')
	    {
		// end of SQL statement marker
		*(line + off) = '\0';
		*len = off;
		return line;
	    }
      }
// EOF reached
    *len = off;
    *eof = 1;
    return line;
}

void
MyFrame::OnSqlScript (wxCommandEvent & WXUNUSED (event))
{
//
// executing an SQL Script
//
    int ret;
    wxString lastDir;
    wxString path;
    wxString charset;
    FILE *sql;
    char *line = NULL;
    char *statement = NULL;
    int stmt_len = 0;
    char *prev_stmt;
    int prev_len;
    int eof;
    int rowNo = 1;
    int stmt = 0;
    int len;
    wxString msg;
    void *cvtCS = NULL;
    char *utf8stmt = NULL;
    int cvtErr;
    wxFileDialog *fileDialog = new wxFileDialog (this, wxT ("SQL Script"),
						 wxT (""),
						 wxT ("init_spatialite.sql"),
						 wxT
						 ("SQL script (*.sql)|*.sql|All files (*.*)|*.*"),
						 wxFD_OPEN |
						 wxFD_FILE_MUST_EXIST,
						 wxDefaultPosition,
						 wxDefaultSize,
						 wxT ("filedlg"));
    lastDir = GetLastDirectory ();
    if (lastDir.Len () >= 1)
	fileDialog->SetDirectory (lastDir);
    ret = fileDialog->ShowModal ();
    if (ret == wxID_OK)
      {
	  path = fileDialog->GetPath ();
	  SqlScriptDialog dlg;
	  dlg.Create (this, path, LocaleCharset);
	  ret = dlg.ShowModal ();
	  if (ret == wxID_OK)
	      charset = dlg.GetCharset ();
	  else
	      return;
	  // opening the SQL script
	  sql = fopen (path.ToUTF8 (), "r");
	  if (sql == NULL)
	    {
		wxMessageBox (wxT ("can't open: ") + fileDialog->GetPath (),
			      wxT ("spatialite-gui"), wxOK | wxICON_ERROR,
			      this);
	    }
	  else
	    {
		wxFileName file (fileDialog->GetPath ());
		lastDir = file.GetPath ();
		SetLastDirectory (lastDir);
		cvtCS = gaiaCreateUTF8Converter (charset.ToUTF8 ());
		if (!cvtCS)
		  {
		      msg = charset + wxT (": unsupported CharacterSet");
		      wxMessageBox (msg, wxT ("spatialite-gui"),
				    wxOK | wxICON_WARNING, this);
		      goto stop;
		  }
		::wxBeginBusyCursor ();
		while (1)
		  {
		      // reading the SQL script lines
		      line = ReadSqlLine (sql, &len, &eof);
		      if (len > 0)
			{
			    if (statement == NULL)
			      {
				  statement = line;
				  stmt_len = len;
			      }
			    else
			      {
				  // appending line to SQL statement
				  prev_stmt = statement;
				  prev_len = stmt_len;
				  stmt_len = prev_len + len;
				  statement = (char *) malloc (stmt_len + 1);
				  memcpy (statement, prev_stmt, prev_len);
				  memcpy (statement + prev_len, line, len);
				  *(statement + stmt_len) = '\0';
				  free (prev_stmt);
				  free (line);
				  line = NULL;
			      }
			}
		      else
			{
			    free (line);
			    line = NULL;
			}
		      if (statement)
			{
			    if (sqlite3_complete (statement))
			      {
				  // executing the SQL statement
				  utf8stmt =
				      gaiaConvertToUTF8 (cvtCS, statement,
							 stmt_len, &cvtErr);
				  free (statement);
				  statement = NULL;
				  stmt_len = 0;
				  if (cvtErr || !utf8stmt)
				    {
					Rollback ();
					msg =
					    wxT
					    ("SQL Script abnormal termination\nillegal character sequence");
					msg +=
					    wxT
					    ("\n\nROLLBACK was automatically performed");
					wxMessageBox (msg,
						      wxT ("spatialite-gui"),
						      wxOK | wxICON_WARNING,
						      this);
					goto stop;
				    }
				  if (ExecuteSql (utf8stmt, rowNo) == false)
				    {
					Rollback ();
					msg =
					    wxT
					    ("SQL Script abnormal termination\nan error occurred");
					msg +=
					    wxT
					    ("\n\nROLLBACK was automatically performed");
					wxMessageBox (msg,
						      wxT ("spatialite-gui"),
						      wxOK | wxICON_WARNING,
						      this);
					goto stop;
				    }
				  else
				    {
					stmt++;
					free (utf8stmt);
					utf8stmt = NULL;
				    }
			      }
			}
		      rowNo++;
		      if (eof)
			  break;
		  }
		msg.Printf (wxT
			    ("SQL Script normal termination\n\n%d SQL statements where performed"),
			    stmt);
		wxMessageBox (msg, wxT ("spatialite-gui"),
			      wxOK | wxICON_INFORMATION, this);
	      stop:
		if (cvtCS)
		    gaiaFreeUTF8Converter (cvtCS);
		if (utf8stmt)
		    free (utf8stmt);
		if (statement)
		    free (statement);
		if (line)
		    free (line);
		fclose (sql);
		::wxEndBusyCursor ();
	    }
      }
}

void
MyFrame::OnLoadShp (wxCommandEvent & WXUNUSED (event))
{
//
// loading a shapefile
//
    int ret;
    wxString table;
    wxString column = wxT ("Geometry");
    wxString charset;
    int srid = -1;
    wxString path;
    wxString lastDir;
    wxFileDialog *fileDialog = new wxFileDialog (this, wxT ("Load Shapefile"),
						 wxT (""),
						 wxT ("shapefile.shp"),
						 wxT
						 ("Shapefile (*.shp)|*.shp|All files (*.*)|*.*"),
						 wxFD_OPEN |
						 wxFD_FILE_MUST_EXIST,
						 wxDefaultPosition,
						 wxDefaultSize,
						 wxT ("filedlg"));
    lastDir = GetLastDirectory ();
    if (lastDir.Len () >= 1)
	fileDialog->SetDirectory (lastDir);
    ret = fileDialog->ShowModal ();
    if (ret == wxID_OK)
      {
	  wxFileName file (fileDialog->GetPath ());
	  lastDir = file.GetPath ();
	  table = file.GetName ();
	  path = file.GetPath ();
	  path += file.GetPathSeparator ();
	  path += file.GetName ();
	  LoadShpDialog dlg;
	  dlg.Create (this, path, table, srid, column, LocaleCharset);
	  ret = dlg.ShowModal ();
	  if (ret == wxID_OK)
	    {
		SetLastDirectory (lastDir);
		table = dlg.GetTable ();
		srid = dlg.GetSrid ();
		column = dlg.GetColumn ();
		charset = dlg.GetCharset ();
		LoadShapefile (path, table, srid, column, charset);
	    }
      }
}

void
MyFrame::OnVirtualShp (wxCommandEvent & WXUNUSED (event))
{
//
// creating a VirtualShape
//
    int ret;
    wxString charset;
    int srid;
    wxString xSrid;
    wxString sql;
    wxString path;
    wxString table;
    wxString lastDir;
    char *errMsg = NULL;
    sqlite3 *sqlite = GetSqlite ();
    wxFileDialog *fileDialog = new wxFileDialog (this, wxT ("VirtualShape"),
						 wxT (""),
						 wxT ("shapefile.shp"),
						 wxT
						 ("Shapefile (*.shp)|*.shp|All files (*.*)|*.*"),
						 wxFD_OPEN |
						 wxFD_FILE_MUST_EXIST,
						 wxDefaultPosition,
						 wxDefaultSize,
						 wxT ("filedlg"));
    lastDir = GetLastDirectory ();
    if (lastDir.Len () >= 1)
	fileDialog->SetDirectory (lastDir);
    ret = fileDialog->ShowModal ();
    if (ret == wxID_OK)
      {
	  path = fileDialog->GetPath ();
	  wxFileName file (path);
	  table = file.GetName ();
	  VirtualShpDialog dlg;
	  dlg.Create (this, path, table, LocaleCharset);
	  ret = dlg.ShowModal ();
	  if (ret == wxID_OK)
	    {
		table = dlg.GetTable ();
		srid = dlg.GetSrid ();
		charset = dlg.GetCharset ();
	    }
	  else
	      return;
	  lastDir = file.GetPath ();
	  SetLastDirectory (lastDir);
	  sql = wxT ("CREATE VIRTUAL TABLE ");
	  sql += table;
	  sql += wxT ("\nUSING VirtualShape('");
	  sql += file.GetPath ();
	  sql += file.GetPathSeparator ();
	  sql += file.GetName ();
	  sql += wxT ("',\n'");
	  sql += charset;
	  xSrid.Printf (wxT ("', %d"), srid);
	  sql += xSrid;
	  sql += wxT (")");
	  ret = sqlite3_exec (sqlite, sql.ToUTF8 (), NULL, NULL, &errMsg);
	  if (ret != SQLITE_OK)
	    {
		wxMessageBox (wxT ("SQLite SQL error: ") +
			      wxString::FromUTF8 (errMsg),
			      wxT ("spatialite-gui"), wxOK | wxICON_ERROR,
			      this);
		sqlite3_free (errMsg);
		return;
	    }
	  wxMessageBox (wxT ("Virtual Table '") + table +
			wxT ("' was successfully created"),
			wxT ("spatialite-gui"), wxOK | wxICON_INFORMATION,
			this);
	  ClearTableTree ();
	  InitTableTree ();
      }
}

void
MyFrame::OnLoadTxt (wxCommandEvent & WXUNUSED (event))
{
//
// loading a CSV/TXT
//
    int ret;
    wxString charset;
    wxString sql;
    wxString path;
    wxString table;
    wxString lastDir;
    bool first_titles;
    bool decimal_comma;
    char separator;
    char text_separator;
    wxString filelist = wxT ("TXT and CSV files (*.txt;*.csv)|*.txt;*.csv");
    filelist +=
	wxT
	("|Text file (*.txt)|*.txt|CSV file (*.csv)|*.csv|All files (*.*)|*.*");
    wxFileDialog *fileDialog = new wxFileDialog (this, wxT ("Load CSV/TXT"),
						 wxT (""),
						 wxT ("textfile.txt"),
						 filelist,
						 wxFD_OPEN |
						 wxFD_FILE_MUST_EXIST,
						 wxDefaultPosition,
						 wxDefaultSize,
						 wxT ("filedlg"));
    lastDir = GetLastDirectory ();
    if (lastDir.Len () >= 1)
	fileDialog->SetDirectory (lastDir);
    ret = fileDialog->ShowModal ();
    if (ret == wxID_OK)
      {
	  path = fileDialog->GetPath ();
	  wxFileName file (path);
	  table = file.GetName ();
	  LoadTxtDialog dlg;
	  dlg.Create (this, path, table, LocaleCharset);
	  ret = dlg.ShowModal ();
	  if (ret == wxID_OK)
	    {
		SetLastDirectory (lastDir);
		table = dlg.GetTable ();
		charset = dlg.GetCharset ();
		first_titles = dlg.IsFirstLineTitles ();
		decimal_comma = dlg.IsDecimalPointComma ();
		separator = dlg.GetSeparator ();
		text_separator = dlg.GetTextSeparator ();
		char decimal_separator = '.';
		if (decimal_comma == true)
		    decimal_separator = ',';
		LoadText (path, table, charset, first_titles, decimal_separator,
			  separator, text_separator);
	    }
      }
}

void
MyFrame::OnVirtualTxt (wxCommandEvent & WXUNUSED (event))
{
//
// creating a VirtualText
//
    int ret;
    wxString charset;
    wxString sql;
    wxString path;
    wxString table;
    wxString lastDir;
    bool first_titles;
    bool decimal_comma;
    char separator;
    char text_separator;
    char dummy[16];
    char *errMsg = NULL;
    sqlite3 *sqlite = GetSqlite ();
    wxString filelist = wxT ("TXT and CSV files (*.txt;*.csv)|*.txt;*.csv");
    filelist +=
	wxT
	("|Text file (*.txt)|*.txt|CSV file (*.csv)|*.csv|All files (*.*)|*.*");
    wxFileDialog *fileDialog = new wxFileDialog (this, wxT ("VirtualText"),
						 wxT (""),
						 wxT ("textfile.txt"),
						 filelist,
						 wxFD_OPEN |
						 wxFD_FILE_MUST_EXIST,
						 wxDefaultPosition,
						 wxDefaultSize,
						 wxT ("filedlg"));
    lastDir = GetLastDirectory ();
    if (lastDir.Len () >= 1)
	fileDialog->SetDirectory (lastDir);
    ret = fileDialog->ShowModal ();
    if (ret == wxID_OK)
      {
	  path = fileDialog->GetPath ();
	  wxFileName file (path);
	  table = file.GetName ();
	  VirtualTxtDialog dlg;
	  dlg.Create (this, path, table, LocaleCharset);
	  ret = dlg.ShowModal ();
	  if (ret == wxID_OK)
	    {
		table = dlg.GetTable ();
		charset = dlg.GetCharset ();
		first_titles = dlg.IsFirstLineTitles ();
		decimal_comma = dlg.IsDecimalPointComma ();
		separator = dlg.GetSeparator ();
		text_separator = dlg.GetTextSeparator ();
	    }
	  else
	      return;
	  lastDir = file.GetPath ();
	  SetLastDirectory (lastDir);
	  sql = wxT ("CREATE VIRTUAL TABLE ");
	  sql += table;
	  sql += wxT ("\nUSING VirtualText('");
	  sql += path;
	  sql += wxT ("',\n'");
	  sql += charset;
	  if (first_titles == true)
	      sql += wxT ("', 1");
	  else
	      sql += wxT ("', 0");
	  if (decimal_comma == true)
	      sql += wxT (", COMMA");
	  else
	      sql += wxT (", POINT");
	  if (text_separator == '\'')
	      sql += wxT (", SINGLEQUOTE");
	  else
	      sql += wxT (", DOUBLEQUOTE");
	  if (separator == '\t')
	      sql += wxT (", TAB");
	  else
	    {
		sprintf (dummy, ", '%c'", separator);
		sql += wxString::FromUTF8 (dummy);
	    }
	  sql += wxT (")");
	  ret = sqlite3_exec (sqlite, sql.ToUTF8 (), NULL, NULL, &errMsg);
	  if (ret != SQLITE_OK)
	    {
		wxMessageBox (wxT ("SQLite SQL error: ") +
			      wxString::FromUTF8 (errMsg),
			      wxT ("spatialite-gui"), wxOK | wxICON_ERROR,
			      this);
		sqlite3_free (errMsg);
		return;
	    }
	  wxMessageBox (wxT ("Virtual Table '") + table +
			wxT ("' was successfully created"),
			wxT ("spatialite-gui"), wxOK | wxICON_INFORMATION,
			this);
	  ClearTableTree ();
	  InitTableTree ();
      }
}

void
MyFrame::OnSrids (wxCommandEvent & WXUNUSED (event))
{
//
// searching a SRID by name
//
    SearchSridDialog dlg;
    int ret;
    wxString string;
    wxString sql;
    dlg.Create (this);
    ret = dlg.ShowModal ();
    if (ret == wxID_OK)
      {
	  string = dlg.GetString ();
	  sql = wxT ("SELECT * FROM spatial_ref_sys\n");
	  sql += wxT ("WHERE ref_sys_name LIKE '%");
	  sql += string;
	  sql += wxT ("%'\nORDER BY srid");
	  QueryView->SetSql (sql, true);
      }
}

void
MyFrame::OnCharset (wxCommandEvent & WXUNUSED (event))
















































































































































































































































































































































































































































































































































{
//
// setting the default CHARSET
//
    DefaultCharsetDialog dlg;
    int ret;
    dlg.Create (this, DefaultCharset, AskCharset);
    ret = dlg.ShowModal ();
    if (ret == wxID_OK)
      {
	  DefaultCharset = dlg.GetCharset ();
	  AskCharset = dlg.IsSetAskCharset ();
      }
}

bool















MyFrame::ExecuteSql (const char *sql, int rowNo)
{
//
// executes an SQL statement from the SQL script
//
    int ret;
    char *errMsg = NULL;
    wxString msg;

    ret = sqlite3_exec (SqliteHandle, sql, NULL, NULL, &errMsg);
    if (ret != SQLITE_OK)
      {
	  msg.Printf (wxT ("row %d\n\nSQLite SQL error: "), rowNo);
	  wxMessageBox (msg + wxString::FromUTF8 (errMsg),

			wxT ("spatialite-gui"), wxOK | wxICON_ERROR, this);
	  sqlite3_free (errMsg);
	  return false;
      }
    return true;
}

void
MyFrame::Rollback ()
{
//
// performing a ROLLBACK
//
    sqlite3_exec (SqliteHandle, "ROLLBACK", NULL, NULL, NULL);
}

bool
MyFrame::OpenDB ()
{
//
// establishing a physical connetion to some DB SQLite
//
    int ret;
    ret =
	sqlite3_open_v2 (SqlitePath.ToUTF8 (), &SqliteHandle,
			 SQLITE_OPEN_READWRITE, NULL);
    if (ret)
      {
	  // impossibile aprire il DB SQLite
	  wxString errCause;
	  errCause = wxString::FromUTF8 (sqlite3_errmsg (SqliteHandle));
	  sqlite3_close (SqliteHandle);
	  wxMessageBox (wxT ("Failure while connecting to DB\n\n") + errCause +
			wxT ("\n") + SqlitePath, wxT ("spatialite-gui"),
			wxOK | wxICON_ERROR, this);
	  SqliteHandle = NULL;
	  ClearTableTree ();
	  return false;
      }
    InitTableTree ();
    return true;
}

void
MyFrame::CloseDB ()
{
//
// disconnecting current SQLite DB
//
    if (!SqliteHandle)
	return;
    sqlite3_close (SqliteHandle);
    SqliteHandle = NULL;
    SqlitePath = wxT ("");
    ClearTableTree ();
}

bool
MyFrame::CreateDB ()
{
// creating a new, empty SQLite DB
    unlink (SqlitePath.ToUTF8 ());
    int ret;
    ret = sqlite3_open_v2 (SqlitePath.ToUTF8 (), &SqliteHandle,
			   SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL);
    if (ret)
      {
	  // an error occurred
	  wxString errCause;
	  errCause = wxString::FromUTF8 (sqlite3_errmsg (SqliteHandle));
	  sqlite3_close (SqliteHandle);
	  wxMessageBox (wxT ("An error occurred\n\n") + errCause + wxT ("\n") +
			SqlitePath, wxT ("spatialite-gui"), wxOK | wxICON_ERROR,
			this);
	  SqliteHandle = NULL;
	  ClearTableTree ();
	  return false;
      }
    InitTableTree ();
    return true;
}

void
MyFrame::CleanSql (char *buf)
{
// well-formatting a string to be used as an SQL string
    char tmp[1024];
    char *in = tmp;
    char *out = buf;
    strcpy (tmp, buf);
    while (*in != '\0')
      {
	  if (*in == '\'')
	      *out++ = '\'';
	  *out++ = *in++;
      }
    *out = '\0';
}

void
MyFrame::InitTableTree ()
{
// loads the table TREE list
    int i;
    char **results;
    int rows;
    int columns;
    char *errMsg = NULL;
    char *name;
    char *createSql;
    char *type;
    wxString tblName;
    wxString sql;
    bool virtualTable = false;
    TableTree->SetPath (SqlitePath);
    TableTree->FlushAll ();
    sql =
	wxT
	("SELECT name, sql, type FROM sqlite_master WHERE (type = 'table' OR type = 'view') ORDER BY name");
    int ret = sqlite3_get_table (SqliteHandle, sql.ToUTF8 (), &results,
				 &rows, &columns, &errMsg);
    if (ret != SQLITE_OK)
      {
	  wxMessageBox (wxT ("SQLite SQL error: ") +
			wxString::FromUTF8 (errMsg), wxT ("spatialite-gui"),
			wxOK | wxICON_ERROR, this);
	  sqlite3_free (errMsg);
	  return;
      }
    if (rows < 1)
	;
    else
      {
	  for (i = 1; i <= rows; i++)
	    {
		name = results[(i * columns) + 0];
		createSql = results[(i * columns) + 1];
		type = results[(i * columns) + 2];
		if (strstr (createSql, "VIRTUAL")
		    || strstr (createSql, "virtual"))
		    virtualTable = true;
		else
		    virtualTable = false;
		tblName = wxString::FromUTF8 (name);
		if (strcmp (type, "view") == 0)
		    TableTree->AddView (tblName);
		else
		    TableTree->AddTable (tblName, virtualTable);
	    }
      }
    sqlite3_free_table (results);
    TableTree->ExpandRoot ();
}

void
MyFrame::GetTableColumns (wxString & tableName, MyTableInfo * list)
{
// loads the table's column list
    int i;
    char **results;
    int rows;
    int columns;
    char *errMsg = NULL;
    char *name;
    char *column;
    wxString Name;
    wxString Column;
    bool pKey;
    bool index;
    bool cached;
    wxString sql;
    sql = wxT ("PRAGMA table_info(");
    sql += tableName;
    sql += wxT (")");
    int ret = sqlite3_get_table (SqliteHandle, sql.ToUTF8 (), &results,
				 &rows, &columns, &errMsg);
    if (ret != SQLITE_OK)
      {
	  wxMessageBox (wxT ("SQLite SQL error: ") +
			wxString::FromUTF8 (errMsg), wxT ("spatialite-gui"),
			wxOK | wxICON_ERROR, this);
	  sqlite3_free (errMsg);
	  return;
      }
    if (rows < 1)
	;
    else
      {
	  for (i = 1; i <= rows; i++)
	    {
		name = results[(i * columns) + 1];
		if (atoi (results[(i * columns) + 5]) == 0)
		    pKey = false;
		else
		    pKey = true;
		Name = wxString::FromUTF8 (name);
		list->AddColumn (Name, pKey);
	    }
      }
    sqlite3_free_table (results);
    if (CheckMetadata () == true)
      {
	  // ok, Spatial MetaData exists; retrieving Geometries and Spatial Indices
	  sql =
	      wxT
	      ("SELECT f_geometry_column, spatial_index_enabled FROM geometry_columns ");
	  sql += wxT ("WHERE f_table_name = '");
	  sql += tableName;
	  sql += wxT ("'");
	  ret = sqlite3_get_table (SqliteHandle, sql.ToUTF8 (), &results,
				   &rows, &columns, &errMsg);
	  if (ret != SQLITE_OK)
	    {
		wxMessageBox (wxT ("SQLite SQL error: ") +
			      wxString::FromUTF8 (errMsg),
			      wxT ("spatialite-gui"), wxOK | wxICON_ERROR,
			      this);
		sqlite3_free (errMsg);
		return;
	    }
	  if (rows < 1)
	      ;
	  else
	    {
		for (i = 1; i <= rows; i++)
		  {
		      column = results[(i * columns) + 0];
		      if (atoi (results[(i * columns) + 1]) == 1)
			  index = true;
		      else
			  index = false;
		      if (atoi (results[(i * columns) + 1]) == 2)
			  cached = true;
		      else
			  cached = false;
		      Column = wxString::FromUTF8 (column);
		      list->SetGeometry (Column, index, cached);
		  }
	    }
	  sqlite3_free_table (results);
      }
}

void
MyFrame::GetViewColumns (wxString & tableName, MyViewInfo * list)
{
// loads the view's column list
    int i;
    char **results;
    int rows;
    int columns;
    char *errMsg = NULL;
    char *name;
    wxString Name;
    wxString sql;
    sql = wxT ("PRAGMA table_info(");
    sql += tableName;
    sql += wxT (")");
    int ret = sqlite3_get_table (SqliteHandle, sql.ToUTF8 (), &results,
				 &rows, &columns, &errMsg);
    if (ret != SQLITE_OK)
      {
	  wxMessageBox (wxT ("SQLite SQL error: ") +
			wxString::FromUTF8 (errMsg), wxT ("spatialite-gui"),
			wxOK | wxICON_ERROR, this);
	  sqlite3_free (errMsg);
	  return;
      }
    if (rows < 1)
	;
    else
      {
	  for (i = 1; i <= rows; i++)
	    {
		name = results[(i * columns) + 1];
		Name = wxString::FromUTF8 (name);
		list->AddColumn (Name);
	    }
      }
    sqlite3_free_table (results);
}

void
MyFrame::GetTableIndices (wxString & tableName, MyTableInfo * list)
{
// loads the table's indices list
    int i;
    char **results;
    int rows;
    int columns;
    char *errMsg = NULL;
    char *name;
    wxString Name;
    wxString sql;
    sql = wxT ("PRAGMA index_list(");
    sql += tableName;
    sql += wxT (")");
    int ret = sqlite3_get_table (SqliteHandle, sql.ToUTF8 (), &results,
				 &rows, &columns, &errMsg);
    if (ret != SQLITE_OK)
      {
	  wxMessageBox (wxT ("SQLite SQL error: ") +
			wxString::FromUTF8 (errMsg), wxT ("spatialite-gui"),
			wxOK | wxICON_ERROR, this);
	  sqlite3_free (errMsg);
	  return;
      }
    if (rows < 1)
	;
    else
      {
	  for (i = 1; i <= rows; i++)
	    {
		name = results[(i * columns) + 1];
		Name = wxString::FromUTF8 (name);
		list->AddIndex (Name);
	    }
      }
    sqlite3_free_table (results);
}

void
MyFrame::GetTableTriggers (wxString & tableName, MyTableInfo * list)
{
// loads the table's indices list
    int i;
    char **results;
    int rows;
    int columns;
    char *errMsg = NULL;
    char *name;
    wxString Name;
    wxString sql;
    sql =
	wxT
	("SELECT name FROM sqlite_master WHERE type = 'trigger' AND tbl_name = '");
    sql += tableName;
    sql += wxT ("' ORDER BY name");
    int ret = sqlite3_get_table (SqliteHandle, sql.ToUTF8 (), &results,
				 &rows, &columns, &errMsg);
    if (ret != SQLITE_OK)
      {
	  wxMessageBox (wxT ("SQLite SQL error: ") +
			wxString::FromUTF8 (errMsg), wxT ("spatialite-gui"),
			wxOK | wxICON_ERROR, this);
	  sqlite3_free (errMsg);
	  return;
      }
    if (rows < 1)
	;
    else
      {
	  for (i = 1; i <= rows; i++)
	    {
		name = results[(i * columns) + 0];
		Name = wxString::FromUTF8 (name);
		list->AddTrigger (Name);
	    }
      }
    sqlite3_free_table (results);
    TableTree->ExpandRoot ();
}

wxString *
MyFrame::GetColumnNames (wxString & tableName, int *n_cols)
{
// loads the table's column names list
    wxString *cols = NULL;
    int nCols = 0;
    char **results;
    int rows;
    int columns;
    int i;
    char *errMsg = NULL;
    wxString sql;
    char *column;
    sql = wxT ("PRAGMA table_info(");
    sql += tableName;
    sql += wxT (")");
    int ret = sqlite3_get_table (SqliteHandle, sql.ToUTF8 (), &results,
				 &rows, &columns, &errMsg);
    if (ret != SQLITE_OK)
      {
	  wxMessageBox (wxT ("SQLite SQL error: ") +
			wxString::FromUTF8 (errMsg), wxT ("spatialite-gui"),
			wxOK | wxICON_ERROR, this);
	  sqlite3_free (errMsg);
	  return NULL;
      }
    sql = wxT ("");
    if (rows < 1)
	;
    else
      {
	  nCols = rows;
	  cols = new wxString[rows];
	  for (i = 1; i <= rows; i++)
	    {
		column = results[(i * columns) + 1];
		*(cols + i - 1) += wxString::FromUTF8 (column);
	    }
      }
    sqlite3_free_table (results);
    *n_cols = nCols;
    return cols;
}

int
MyFrame::GetCharsetIndex (wxString & charset)
{
// identifies the INDEX for a given charset
    int i;
    for (i = 0; i < CharsetsLen; i++)
      {
	  if (*(Charsets + i) == charset)
	      return i;
      }
    return wxNOT_FOUND;
}

wxString & MyFrame::GetCharsetName (wxString & charset)
{
// identifies the full name for a given charset code
    int
	i;
    for (i = 0; i < CharsetsLen; i++)
      {
	  if (*(Charsets + i) == charset)
	      return *(CharsetsNames + i);
      }
    return charset;
}

void
MyFrame::ClearTableTree ()
{
// resets the table TREE list to the empty state
    wxString path = wxT ("no current DB");
    TableTree->SetPath (path);
    TableTree->FlushAll ();
}

int
MyFrame::GuessBlobType (int size, unsigned char *blob)
{
//
// trying to check the content-type for a BLOB value [using signatures]
//
    bool geom;
    if (size < 1 || !blob)
	return BLOB_NULL;
    if (size > 5)
      {
	  if (strncmp ((char *) blob, "%PDF-", 5) == 0)
	      return BLOB_PDF;
      }
    if (size > 6)
      {
	  if (strncmp ((char *) blob, "GIF87a", 6) == 0
	      || strncmp ((char *) blob, "GIF89a", 6) == 0)
	      return BLOB_GIF;
      }
    if (size > 4)
      {
	  if (memcmp (blob, ZipSignature, 4) == 0)
	      return BLOB_ZIP;
	  if (memcmp (blob, Jpeg1Signature, 2) == 0
	      && memcmp (blob + size - 2, Jpeg2Signature, 2) == 0)
	      return BLOB_JPEG;	// this one is the standard JPEG signature
	  if (memcmp (blob, Jpeg3Signature, 4) == 0)
	      return BLOB_JPEG;	// another common JPEG signature
      }
    if (size > 8)
      {
	  if (memcmp (blob, PngSignature, 8) == 0)
	      return BLOB_PNG;
      }
    if (size > 10)
      {
	  if (memcmp (blob + 6, JfifSignature, 4) == 0)
	      return BLOB_JFIF;	// standard JFIF signature 
	  if (memcmp (blob + 6, ExifSignature, 4) == 0)
	      return BLOB_EXIF;	// standard EXIF signature
      }
// testing for GEOMETRY
    geom = true;
    if (size < 45)
	geom = false;
    else
      {
	  if (*(blob + 0) != 0x00)
	      geom = false;
	  if (*(blob + (size - 1)) != 0xFE)
	      geom = false;
	  if (*(blob + 38) != 0x7C)
	      geom = false;
	  if (*(blob + 1) == 0 || *(blob + 1) == 1)
	      ;
	  else
	      geom = false;
      }
    if (geom == true)
	return BLOB_GEOMETRY;
    return BLOB_HEX;
}

void
MyFrame::GetHelp (wxString & html)
{
//
// return the HTML Help
//
    html =
	wxT
	("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
    html += wxT ("<html>");
    html += wxT ("<head>");
    html +=
	wxT
	("<meta content=\"text/html; charset=ISO-8859-1\" http-equiv=\"content-type\">");
    html += wxT ("<title>SQLite + SpatiaLite quick Help</title>");
    html += wxT ("</head>");
    html += wxT ("<body bgcolor=\"#e8e8e8\">");
    html +=
	wxT ("<h1><a name=\"index\">SQLite + SpatiaLite quick Help</a></h1>");
    html += wxT ("<table cellspacing=\"2\" cellpadding=\"2\">");
    html +=
	wxT
	("<tr><td align=\"center\" bgcolor=\"#e0ffe0\" colspan=\"2\">Index of contents</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">1.</td><td bgcolor=\"#f0fff0\"><a href=\"#c1\">SQLite SQL syntax</a></td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">2.</td><td bgcolor=\"#f0fff0\"><a href=\"#c2\">SQLite SQL functions</a><ul>");
    html += wxT ("<li><a href=\"#c21\">ordinary functions</a></li>");
    html += wxT ("<li><a href=\"#c22\">aggregate functions</a></li>");
    html += wxT ("</ul></td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">3.</td><td bgcolor=\"#f0fff0\"><a href=\"#c3\">SpatiaLite SQL Spatial functions</a><ul>");
    html +=
	wxT
	("<li><a href=\"#c30\">SQL utility functions [non-standard] for geometric objects</a></li>");
    html +=
	wxT
	("<li><a href=\"#c31\">functions for constructing a geometric object given its Well-known Text Representation</a></li>");
    html +=
	wxT
	("<li><a href=\"#c32\">functions for constructing a geometric object given its Well-known Binary Representation</a></li>");
    html +=
	wxT
	("<li><a href=\"#c33\">functions for obtaining the Well-known Text / Well-known Binary Representation of a geometric object</a></li>");
    html += wxT ("<li><a href=\"#c34\">functions on type Geometry</a></li>");
    html += wxT ("<li><a href=\"#c35\">functions on type Point</a></li>");
    html +=
	wxT
	("<li><a href=\"#c36\">functions on type Surface [Polygon or Ring]</a></li>");
    html += wxT ("<li><a href=\"#c37\">functions on type Polygon</a></li>");
    html +=
	wxT ("<li><a href=\"#c38\">functions on type GeomCollection</a></li>");
    html +=
	wxT
	("<li><a href=\"#c39\">functions testing approximative spatial relationships via MBRs</a></li>");
    html +=
	wxT
	("<li><a href=\"#c40\">functions testing spatial relationships</a></li>");
    html +=
	wxT
	("<li><a href=\"#c41\">functions implementing spatial operators</a></li>");
    html +=
	wxT
	("<li><a href=\"#c42\">functions for coordinate transformations</a></li>");
    html +=
	wxT
	("<li><a href=\"#c43\">functions for Spatial-MetaData and Spatial-Index handling</a></li>");
    html += wxT ("</ul></td></tr>");
    html += wxT ("</table>");
    html += wxT ("<h3><a name=\"c1\">SQLite SQL syntax</a></h3>");
    html += wxT ("<table cellspacing=\"4\" cellpadding=\"2\"width=\"100%\">");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">ALTER TABLE</td><td bgcolor=\"#f0fff0\">sql-statement ::= ALTER TABLE [database-name .] table-name alteration<br>");
    html += wxT ("alteration ::= RENAME TO new-table-name<br>");
    html += wxT ("alteration ::= ADD [COLUMN] column-def<br></td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">ANALYZE</td><td bgcolor=\"#f0fff0\">sql-statement ::= ANALYZE<br>");
    html += wxT ("sql-statement ::= ANALYZE database-name<br>");
    html +=
	wxT
	("sql-statement ::= ANALYZE [database-name .] table-name<br></td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">ATTACH DATABASE</td><td bgcolor=\"#f0fff0\">sql-statement ::= ATTACH [DATABASE] database-filename AS database-name</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">BEGIN TRANSACTION</td><td bgcolor=\"#f0fff0\">sql-statement ::= BEGIN [ DEFERRED | IMMEDIATE | EXCLUSIVE ] [TRANSACTION [name]]<br>");
    html += wxT ("sql-statement ::= END [TRANSACTION [name]]<br>");
    html += wxT ("sql-statement ::= COMMIT [TRANSACTION [name]]<br>");
    html +=
	wxT ("sql-statement ::= ROLLBACK [TRANSACTION [name]]<br></td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">COMMIT TRANSACTION</td><td bgcolor=\"#f0fff0\">sql-statement ::= BEGIN [ DEFERRED | IMMEDIATE | EXCLUSIVE ] [TRANSACTION [name]]<br>");
    html += wxT ("sql-statement ::= END [TRANSACTION [name]]<br>");
    html += wxT ("sql-statement ::= COMMIT [TRANSACTION [name]]<br>");
    html +=
	wxT ("sql-statement ::= ROLLBACK [TRANSACTION [name]]<br></td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">CREATE INDEX</td><td bgcolor=\"#f0fff0\">sql-statement ::= CREATE [UNIQUE] INDEX [IF NOT EXISTS] [database-name .] index-name<br>");
    html += wxT ("ON table-name ( column-name [, column-name]* )<br>");
    html +=
	wxT
	("column-name ::= name [ COLLATE collation-name] [ ASC | DESC ]</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">CREATE TABLE</td><td bgcolor=\"#f0fff0\">sql-command ::= CREATE [TEMP | TEMPORARY] TABLE [IF NOT EXISTS] [database-name .] table-name (<br>");
    html += wxT ("column-def [, column-def]*<br>");
    html += wxT ("[, constraint]*<br>");
    html += wxT (")<br>");
    html +=
	wxT
	("sql-command ::= CREATE [TEMP | TEMPORARY] TABLE [database-name.] table-name AS select-statement<br>");
    html +=
	wxT
	("column-def ::= name [type] [[CONSTRAINT name] column-constraint]*<br>");
    html += wxT ("type ::= typename |<br>");
    html += wxT ("typename ( number ) |<br>");
    html += wxT ("typename ( number , number )<br>");
    html += wxT ("column-constraint ::= NOT NULL [ conflict-clause ] |<br>");
    html +=
	wxT
	("PRIMARY KEY [sort-order] [ conflict-clause ] [AUTOINCREMENT] |<br>");
    html += wxT ("UNIQUE [ conflict-clause ] |<br>");
    html += wxT ("CHECK ( expr ) |<br>");
    html += wxT ("DEFAULT value |<br>");
    html += wxT ("COLLATE collation-name<br>");
    html +=
	wxT
	("constraint ::= PRIMARY KEY ( column-list ) [ conflict-clause ] |<br>");
    html += wxT ("UNIQUE ( column-list ) [ conflict-clause ] |<br>");
    html += wxT ("CHECK ( expr )<br>");
    html +=
	wxT ("conflict-clause ::= ON CONFLICT conflict-algorithm</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">CREATE TRIGGER</td><td bgcolor=\"#f0fff0\">sql-statement ::= CREATE [TEMP | TEMPORARY] TRIGGER [IF NOT EXISTS] trigger-name [ BEFORE | AFTER ]<br>");
    html += wxT ("database-event ON [database-name .] table-name<br>");
    html += wxT ("trigger-action<br>");
    html +=
	wxT
	("sql-statement ::= CREATE [TEMP | TEMPORARY] TRIGGER [IF NOT EXISTS] trigger-name INSTEAD OF<br>");
    html += wxT ("database-event ON [database-name .] view-name<br>");
    html += wxT ("trigger-action<br>");
    html += wxT ("database-event ::= DELETE |<br>");
    html += wxT ("INSERT |<br>");
    html += wxT ("UPDATE |<br>");
    html += wxT ("UPDATE OF column-list<br>");
    html += wxT ("trigger-action ::= [ FOR EACH ROW ] [ WHEN expression ]<br>");
    html += wxT ("BEGIN<br>");
    html += wxT ("trigger-step ; [ trigger-step ; ]*<br>");
    html += wxT ("END<br>");
    html += wxT ("trigger-step ::= update-statement | insert-statement |<br>");
    html += wxT ("delete-statement | select-statement</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">CREATE VIEW</td><td bgcolor=\"#f0fff0\">sql-command ::= CREATE [TEMP | TEMPORARY] VIEW [IF NOT EXISTS] [database-name.] view-name AS select-statement</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">CREATE VIRTUAL TABLE</td><td bgcolor=\"#f0fff0\">sql-command ::= CREATE VIRTUAL TABLE [database-name .] table-name USING module-name [( arguments )]</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">DELETE</td><td bgcolor=\"#f0fff0\">sql-statement ::= DELETE FROM [database-name .] table-name [WHERE expr]</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">DETACH DATABASE</td><td bgcolor=\"#f0fff0\">sql-command ::= DETACH [DATABASE] database-name</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">DROP INDEX</td><td bgcolor=\"#f0fff0\">sql-command ::= DROP INDEX [IF EXISTS] [database-name .] index-name</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">DROP TABLE</td><td bgcolor=\"#f0fff0\">sql-command ::= DROP TABLE [IF EXISTS] [database-name.] table-name</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">DROP TRIGGER</td><td bgcolor=\"#f0fff0\">sql-statement ::= DROP TRIGGER [IF EXISTS] [database-name .] trigger-name</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">DROP VIEW</td><td bgcolor=\"#f0fff0\">sql-command ::= DROP VIEW [IF EXISTS] view-name</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">END TRANSACTION</td><td bgcolor=\"#f0fff0\">sql-statement ::= BEGIN [ DEFERRED | IMMEDIATE | EXCLUSIVE ] [TRANSACTION [name]]<br>");
    html += wxT ("sql-statement ::= END [TRANSACTION [name]]<br>");
    html += wxT ("sql-statement ::= COMMIT [TRANSACTION [name]]<br>");
    html +=
	wxT ("sql-statement ::= ROLLBACK [TRANSACTION [name]]<br></td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">EXPLAIN</td><td bgcolor=\"#f0fff0\">sql-statement ::= EXPLAIN sql-statement</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">INSERT</td><td bgcolor=\"#f0fff0\">sql-statement ::= INSERT [OR conflict-algorithm] INTO [database-name .] table-name [(column-list)] VALUES(value-list) |<br>");
    html +=
	wxT
	("INSERT [OR conflict-algorithm] INTO [database-name .] table-name [(column-list)] select-statement</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">ON CONFLICT clause</td><td bgcolor=\"#f0fff0\">conflict-clause ::= ON CONFLICT conflict-algorithm<br>");
    html +=
	wxT
	("conflict-algorithm ::= ROLLBACK | ABORT | FAIL | IGNORE | REPLACE</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">PRAGMA</td><td bgcolor=\"#f0fff0\">sql-statement ::= PRAGMA name [= value] |<br>");
    html += wxT ("PRAGMA function(arg)<hr>");
    html += wxT ("PRAGMA auto_vacuum;<br>");
    html +=
	wxT ("PRAGMA auto_vacuum = 0 | none | 1 | full | 2 | incremental;<hr>");
    html += wxT ("PRAGMA cache_size;<br>");
    html += wxT ("PRAGMA cache_size = Number-of-pages;<hr>");
    html += wxT ("PRAGMA case_sensitive_like;<br>");
    html += wxT ("PRAGMA case_sensitive_like = 0 | 1;<hr>");
    html += wxT ("PRAGMA count_changes;<br>");
    html += wxT ("PRAGMA count_changes = 0 | 1;<hr>");
    html += wxT ("PRAGMA default_cache_size;<br>");
    html += wxT ("PRAGMA default_cache_size = Number-of-pages;<hr>");
    html += wxT ("PRAGMA empty_result_callbacks;<br>");
    html += wxT ("PRAGMA empty_result_callbacks = 0 | 1;<hr>");
    html += wxT ("PRAGMA encoding;<br>");
    html += wxT ("PRAGMA encoding = \"UTF-8\";<br>");
    html += wxT ("PRAGMA encoding = \"UTF-16\";<br>");
    html += wxT ("PRAGMA encoding = \"UTF-16le\";<br>");
    html += wxT ("PRAGMA encoding = \"UTF-16be\";<hr>");
    html += wxT ("PRAGMA full_column_names;<br>");
    html += wxT ("PRAGMA full_column_names = 0 | 1;<hr>");
    html += wxT ("PRAGMA fullfsync;<br>");
    html += wxT ("PRAGMA fullfsync = 0 | 1;<hr>");
    html += wxT ("PRAGMA journal_mode;<br>");
    html += wxT ("PRAGMA database.journal_mode;<br>");
    html += wxT ("PRAGMA journal_mode = DELETE | PERSIST | OFF<br>");
    html += wxT ("PRAGMA database.journal_mode = DELETE | PERSIST | OFF<hr>");
    html += wxT ("PRAGMA legacy_file_format;<br>");
    html += wxT ("PRAGMA legacy_file_format = ON | OFF<hr>");
    html += wxT ("PRAGMA locking_mode;<br>");
    html += wxT ("PRAGMA locking_mode = NORMAL | EXCLUSIVE<hr>");
    html += wxT ("PRAGMA page_size;<br>");
    html += wxT ("PRAGMA page_size = bytes;<hr>");
    html += wxT ("PRAGMA max_page_count;<br>");
    html += wxT ("PRAGMA max_page_count = N;<hr>");
    html += wxT ("PRAGMA read_uncommitted;<br>");
    html += wxT ("PRAGMA read_uncommitted = 0 | 1;<hr>");
    html += wxT ("PRAGMA short_column_names;<br>");
    html += wxT ("PRAGMA short_column_names = 0 | 1;<hr>");
    html += wxT ("PRAGMA synchronous;<br>");
    html += wxT ("PRAGMA synchronous = FULL; (2)<br>");
    html += wxT ("PRAGMA synchronous = NORMAL; (1)<br>");
    html += wxT ("PRAGMA synchronous = OFF; (0)<hr>");
    html += wxT ("PRAGMA temp_store;<br>");
    html += wxT ("PRAGMA temp_store = DEFAULT; (0)<br>");
    html += wxT ("PRAGMA temp_store = FILE; (1)<br>");
    html += wxT ("PRAGMA temp_store = MEMORY; (2)<hr>");
    html += wxT ("PRAGMA temp_store_directory;<br>");
    html += wxT ("PRAGMA temp_store_directory = 'directory-name';<hr>");
    html += wxT ("PRAGMA database_list;<hr>");
    html += wxT ("PRAGMA foreign_key_list(table-name);<hr>");
    html += wxT ("PRAGMA [database].freelist_count;<hr>");
    html += wxT ("PRAGMA index_info(index-name);<hr>");
    html += wxT ("PRAGMA index_list(table-name);<hr>");
    html += wxT ("PRAGMA table_info(table-name);<hr>");
    html += wxT ("PRAGMA [database.]schema_version;<br>");
    html += wxT ("PRAGMA [database.]schema_version = integer ;<br>");
    html += wxT ("PRAGMA [database.]user_version;<br>");
    html += wxT ("PRAGMA [database.]user_version = integer ;<hr>");
    html += wxT ("PRAGMA integrity_check;<br>");
    html += wxT ("PRAGMA integrity_check(integer)<hr>");
    html += wxT ("PRAGMA parser_trace = ON; (1)<br>");
    html += wxT ("PRAGMA parser_trace = OFF; (0)<hr>");
    html += wxT ("PRAGMA vdbe_trace = ON; (1)<br>");
    html += wxT ("PRAGMA vdbe_trace = OFF; (0)<hr>");
    html += wxT ("PRAGMA vdbe_listing = ON; (1)<br>");
    html += wxT ("PRAGMA vdbe_listing = OFF; (0)</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">REINDEX</td><td bgcolor=\"#f0fff0\">sql-statement ::= REINDEX collation name<br>");
    html +=
	wxT
	("sql-statement ::= REINDEX [database-name .] table/index-name</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">REPLACE</td><td bgcolor=\"#f0fff0\">sql-statement ::= REPLACE INTO [database-name .] table-name [( column-list )] VALUES ( value-list ) |<br>");
    html +=
	wxT
	("REPLACE INTO [database-name .] table-name [( column-list )] select-statement</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">ROLLBACK TRANSACTION</td><td bgcolor=\"#f0fff0\">sql-statement ::= BEGIN [ DEFERRED | IMMEDIATE | EXCLUSIVE ] [TRANSACTION [name]]<br>");
    html += wxT ("sql-statement ::= END [TRANSACTION [name]]<br>");
    html += wxT ("sql-statement ::= COMMIT [TRANSACTION [name]]<br>");
    html +=
	wxT ("sql-statement ::= ROLLBACK [TRANSACTION [name]]<br></td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">SELECT</td><td bgcolor=\"#f0fff0\">sql-statement ::= SELECT [ALL | DISTINCT] result [FROM table-list]<br>");
    html += wxT ("[WHERE expr]<br>");
    html += wxT ("[GROUP BY expr-list]<br>");
    html += wxT ("[HAVING expr]<br>");
    html += wxT ("[compound-op select]*<br>");
    html += wxT ("[ORDER BY sort-expr-list]<br>");
    html += wxT ("[LIMIT integer [( OFFSET | , ) integer]]<br>");
    html += wxT ("result ::= result-column [, result-column]*<br>");
    html +=
	wxT ("result-column ::= * | table-name . * | expr [ [AS] string ]<br>");
    html += wxT ("table-list ::= table [join-op table join-args]*<br>");
    html += wxT ("table ::= table-name [AS alias] |<br>");
    html += wxT ("( select ) [AS alias]<br>");
    html +=
	wxT
	("join-op ::= , | [NATURAL] [LEFT | RIGHT | FULL] [OUTER | INNER | CROSS] JOIN<br>");
    html += wxT ("join-args ::= [ON expr] [USING ( id-list )]<br>");
    html +=
	wxT ("sort-expr-list ::= expr [sort-order] [, expr [sort-order]]*<br>");
    html +=
	wxT ("sort-order ::= [ COLLATE collation-name ] [ ASC | DESC ]<br>");
    html +=
	wxT
	("compound_op ::= UNION | UNION ALL | INTERSECT | EXCEPT</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">UPDATE</td><td bgcolor=\"#f0fff0\">sql-statement ::= UPDATE [ OR conflict-algorithm ] [database-name .] table-name<br>");
    html += wxT ("SET assignment [, assignment]*<br>");
    html += wxT ("[WHERE expr]<br>");
    html += wxT ("assignment ::= column-name = expr</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">VACUUM</td><td bgcolor=\"#f0fff0\">sql-statement ::= VACUUM</td></tr>");
    html += wxT ("</table>");
    html += wxT ("<a href=\"#index\">back to index</a>");
    html +=
	wxT
	("<h3><a align=\"center\" bgcolor=\"#e0ffe0\" name=\"c2\">SQLite SQL functions</a></h3>");
    html += wxT ("<table cellspacing=\"4\" cellpadding=\"2\" width=\"100%\">");
    html +=
	wxT
	("<tr><td align=\"center\" bgcolor=\"#e0ffe0\" colspan=\"2\"><a name=\"c21\">ordinary functions</a><br><a href=\"#index\">back to index</a></td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">abs(X)</td><td bgcolor=\"#f0fff0\">Return the absolute value of the numeric argument X. ");
    html +=
	wxT
	("Return NULL if X is NULL. Return 0.0 if X is not a numeric value.</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">coalesce(X,Y,...)</td><td bgcolor=\"#f0fff0\">Return a copy of the first non-NULL argument. ");
    html +=
	wxT
	("If all arguments are NULL then NULL is returned. There must be at least 2 arguments.</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">glob(X,Y)</td><td bgcolor=\"#f0fff0\">This function is used to implement the \"X GLOB Y\" syntax of SQLite. ");
    html +=
	wxT
	("The sqlite3_create_function() interface can be used to override this function and thereby change the operation of the GLOB operator.</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">ifnull(X,Y)</td><td bgcolor=\"#f0fff0\">Return a copy of the first non-NULL argument. ");
    html +=
	wxT
	("If both arguments are NULL then NULL is returned. This behaves the same as coalesce().</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">hex(X)</td><td bgcolor=\"#f0fff0\">The argument is interpreted as a BLOB. ");
    html +=
	wxT
	("The result is a hexadecimal rendering of the content of that blob.</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">last_insert_rowid()</td><td bgcolor=\"#f0fff0\">Return the ROWID of the last row insert from this connection to the database. ");
    html +=
	wxT
	("This is the same value that would be returned from the sqlite3_last_insert_rowid() API function.</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">length(X)</td><td bgcolor=\"#f0fff0\">Return the string length of X in characters. ");
    html +=
	wxT
	("If SQLite is configured to support UTF-8, then the number of UTF-8 characters is returned, not the number of bytes.</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">like(X,Y)<br>like(X,Y,Z)</td><td bgcolor=\"#f0fff0\">This function is used to implement the \"X LIKE Y [ESCAPE Z]\" syntax of SQL.");
    html +=
	wxT
	("If the optional ESCAPE clause is present, then the user-function is invoked with three arguments. ");
    html += wxT ("Otherwise, it is invoked with two arguments only. ");
    html +=
	wxT
	("The sqlite3_create_function() interface can be used to override this function and thereby change the operation of the LIKE operator. ");
    html +=
	wxT
	("When doing this, it may be important to override both the two and three argument versions of the like() function. ");
    html +=
	wxT
	("Otherwise, different code may be called to implement the LIKE operator depending on whether or not an ESCAPE clause was specified.</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">load_extension(X)</br>load_extension(X,Y)</td><td bgcolor=\"#f0fff0\">Load SQLite extensions ");
    html +=
	wxT
	("out of the shared library file named X using the entry point Y. ");
    html +=
	wxT
	("The result is a NULL. If Y is omitted then the default entry point of sqlite3_extension_init is used. ");
    html +=
	wxT
	("This function raises an exception if the extension fails to load or initialize correctly.</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">lower(X)</td><td bgcolor=\"#f0fff0\">Return a copy of string X will all ASCII characters converted to lower case. ");
    html +=
	wxT
	("The C library tolower() routine is used for the conversion, which means that this function might not work correctly on non-ASCII UTF-8 characters.</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">ltrim(X)<br>ltrim(X,Y)</td><td bgcolor=\"#f0fff0\">Return a string formed by removing any and all characters ");
    html +=
	wxT
	("that appear in Y from the left side of X. If the Y argument is omitted, spaces are removed.</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">max(X,Y,...)</td><td bgcolor=\"#f0fff0\">Return the argument with the maximum value. ");
    html += wxT ("Arguments may be strings in addition to numbers. ");
    html += wxT ("The maximum value is determined by the usual sort order. ");
    html +=
	wxT
	("Note that max() is a simple function when it has 2 or more arguments but converts to an aggregate function if given only a single argument.</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">min(X,Y,...)</td><td bgcolor=\"#f0fff0\">Return the argument with the minimum value. ");
    html += wxT ("Arguments may be strings in addition to numbers. ");
    html += wxT ("The minimum value is determined by the usual sort order. ");
    html +=
	wxT
	("Note that min() is a simple function when it has 2 or more arguments but converts to an aggregate function if given only a single argument.</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">nullif(X,Y)</td><td bgcolor=\"#f0fff0\">Return the first argument if the arguments are different, otherwise return NULL.</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">quote(X)</td><td bgcolor=\"#f0fff0\">This routine return a string which is the value of its argument suitable for inclusion ");
    html +=
	wxT
	("into another SQL statement. Strings are surrounded by single-quotes with escapes on interior quotes as needed. ");
    html +=
	wxT
	("BLOBs are encoded as hexadecimal literals. The implementation of VACUUM uses this function. ");
    html +=
	wxT
	("The function is also useful when writing triggers to implement undo/redo functionality.</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">random()</td><td bgcolor=\"#f0fff0\">Return a pseudo-random integer between -9223372036854775808 and +9223372036854775807.</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">randomblob(N)</td><td bgcolor=\"#f0fff0\">Return an N-byte blob containing pseudo-random bytes. N should be a postive integer.</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">replace(X,Y,Z)</td><td bgcolor=\"#f0fff0\">Return a string formed by substituting string Z for every occurrance of string Y in string X. ");
    html +=
	wxT
	("The BINARY collating sequence is used for comparisons.</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">round(X)<br>round(X,Y)</td><td bgcolor=\"#f0fff0\">Round off the number X to Y digits to the right of the decimal point. ");
    html += wxT ("If the Y argument is omitted, 0 is assumed.</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">rtrim(X)<br>rtrim(X,Y)</td><td bgcolor=\"#f0fff0\">Return a string formed by removing any and all characters ");
    html +=
	wxT
	("that appear in Y from the right side of X. If the Y argument is omitted, spaces are removed.</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">sqlite_version(X)</td><td bgcolor=\"#f0fff0\">Return the version string for the SQLite library that is running. Example: \"3.5.9\"</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">substr(X,Y,Z)<br>substr(X,Y)</td><td bgcolor=\"#f0fff0\">Return a substring of input string X that begins with the Y-th character ");
    html +=
	wxT
	("and which is Z characters long. If Z is omitted then all character through the end of the string are returned. ");
    html += wxT ("The left-most character of X is number 1. ");
    html +=
	wxT
	("If Y is negative the the first character of the substring is found by counting from the right rather than the left. ");
    html +=
	wxT
	("If X is string then characters indices refer to actual UTF-8 characters. If X is a BLOB then the indices refer to bytes.</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">trim(X)<br>trim(X,Y)</td><td bgcolor=\"#f0fff0\">Return a string formed by removing any and all characters that appear in Y from both ends of X. ");
    html += wxT ("If the Y argument is omitted, spaces are removed.</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">typeof(X)</td><td bgcolor=\"#f0fff0\">Return the type of the expression X. ");
    html +=
	wxT
	("The only return values are \"null\", \"integer\", \"real\", \"text\", and \"blob\".</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">upper(X)</td><td bgcolor=\"#f0fff0\">Return a copy of input string X converted to all upper-case letters. ");
    html +=
	wxT
	("The implementation of this function uses the C library routine toupper() which means it may not work correctly on non-ASCII UTF-8 strings.</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">zeroblob(N)</td><td bgcolor=\"#f0fff0\">Return a BLOB consisting of N bytes of 0x00. ");
    html += wxT ("SQLite manages these zeroblobs very efficiently. ");
    html +=
	wxT
	("Zeroblobs can be used to reserve space for a BLOB that is later written using incremental BLOB I/O.</td></tr> ");
    html +=
	wxT
	("<tr><td align=\"center\" bgcolor=\"#e0ffe0\" colspan=\"2\"><a name=\"c22\">aggregate functions</a><br><a href=\"#index\">back to index</a></td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">avg(X)</td><td bgcolor=\"#f0fff0\">Return the average value of all non-NULL X within a group. ");
    html +=
	wxT
	("String and BLOB values that do not look like numbers are interpreted as 0. ");
    html +=
	wxT
	("The result of avg() is always a floating point value even if all inputs are integers.</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">count(X)<br>count(*)</td><td bgcolor=\"#f0fff0\">The first form return a count of the number of times that X is not NULL in a group. ");
    html +=
	wxT
	("The second form (with no argument) return the total number of rows in the group.</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">group_concat(X)<br>group_concat(X,Y)</td><td bgcolor=\"#f0fff0\">The result is a string which is the concatenation of all non-NULL values of X. ");
    html +=
	wxT
	("If parameter Y is the separator between instances of X. A comma (\",\") is used as the separator if Y is omitted.</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">max(X)</td><td bgcolor=\"#f0fff0\">Return the maximum value of all values in the group. ");
    html +=
	wxT
	("The usual sort order is used to determine the maximum.</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">min(X)</td><td bgcolor=\"#f0fff0\">Return the minimum non-NULL value of all values in the group. ");
    html +=
	wxT
	("The usual sort order is used to determine the minimum. NULL is only returned if all values in the group are NULL.</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">sum(X)<br>total(X)</td><td bgcolor=\"#f0fff0\">Return the numeric sum of all non-NULL values in the group. ");
    html +=
	wxT
	("If there are no non-NULL input rows then sum() return NULL but total() return 0.0. ");
    html +=
	wxT
	("NULL is not normally a helpful result for the sum of no rows but the SQL standard requires it and most other SQL ");
    html +=
	wxT
	("database engines implement sum() that way so SQLite does it in the same way in order to be compatible. ");
    html +=
	wxT
	("The non-standard total() function is provided as a convenient way to work around this design problem in the SQL language.<br>");
    html +=
	wxT
	("The result of total() is always a floating point value. The result of sum() is an integer value if all non-NULL inputs are integers. ");
    html +=
	wxT
	("If any input to sum() is neither an integer or a NULL then sum() return a floating point value which might be an approximation to the true sum.<br>");
    html +=
	wxT
	("Sum() will throw an \"integer overflow\" exception if all inputs are integers or NULL and an integer overflow occurs at any point during the computation.");
    html += wxT ("Total() never throws an exception.</td></tr> ");
    html += wxT ("</table>");
    html += wxT ("<a href=\"#index\">back to index</a>");
    html +=
	wxT ("<h3><a name=\"c3\">SpatiaLite SQL Spatial functions</a></h3>");
    html += wxT ("<table cellspacing=\"4\" cellpadding=\"2\" width=\"100%\">");
    html +=
	wxT
	("<tr><td align=\"center\" bgcolor=\"#e0ffe0\" colspan=\"2\"><a name=\"c30\">SQL utility functions [<i>non-standard</i>] for geometric objects</a></a>");
    html += wxT ("<br><a href=\"#index\">back to index</a></td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">MakePoint( x Double precision , y Double precision, [ , SRID Integer] ) : Geometry</td>");
    html +=
	wxT
	("<td bgcolor=\"#f0fff0\">a Geometry will be returned representing the POINT defined by [x y] coordinates</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">BuildMbr( x1 Double precision , y1 Double precision , x2 Double precision , y2 Double precision, [ , SRID Integer] ) : Geometry</td>");
    html +=
	wxT
	("<td bgcolor=\"#f0fff0\">[x1 y1] and [x2 y2] are assumed to be Points identifying a line segment;");
    html +=
	wxT
	("then a Geometry will be returned representing the MBR for this line segment</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">BuildCircleMbr( x Double precision , y Double precision , radius Double precision [ , SRID Integer] ) : Geometry</td>");
    html +=
	wxT
	("<td bgcolor=\"#f0fff0\">[x y] is assumed to be the center of a circle of given radius; then a Geometry will be returned representing the MBR for this circle</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">MbrMinX( geom Geometry) : Double precision</td>");
    html +=
	wxT
	("<td bgcolor=\"#f0fff0\">return the x-coordinate for geom MBR's leftmost side as a double precision number</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">MbrMinY( geom Geometry) : Double precision</td>");
    html +=
	wxT
	("<td bgcolor=\"#f0fff0\">return the y-coordinate for geom MBR's lowermost side as a double precision number</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">MbrMaxX( geom Geometry) : Double precision</td>");
    html +=
	wxT
	("<td bgcolor=\"#f0fff0\">return the x-coordinate for geom MBR's rightmost side as a double precision number</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">MbrMaxY( geom Geometry) : Double precision</td>");
    html +=
	wxT
	("<td bgcolor=\"#f0fff0\">return the y-coordinate for geom MBR's uppermost side as a double precision number</td></tr>");
    html +=
	wxT
	("<tr><td align=\"center\" bgcolor=\"#e0ffe0\" colspan=\"2\"><a name=\"c31\">functions for constructing a geometric object given its Well-known Text Representation</a>");
    html += wxT ("<br><a href=\"#index\">back to index</a></td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">GeomFromText( wkt String [ , SRID Integer] ) : Geometry</td>");
    html +=
	wxT
	("<td bgcolor=\"#f0fff0\">construct a geometric object given its Well-known text Representation</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">PointFromText( wktPoint String [ , SRID Integer] ) : Point</td>");
    html += wxT ("<td bgcolor=\"#f0fff0\">construct a Point</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">LineFromText( wktLineString String [ , SRID Integer] ) : Linestring<hr>");
    html +=
	wxT
	("LineStringFromText( wktLineString String [ , SRID Integer] ) : Linestring</td>");
    html += wxT ("<td bgcolor=\"#f0fff0\">construct a Linestring</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">PolyFromText( wktPolygon String [ , SRID Integer] ) : Polygon<hr>");
    html +=
	wxT
	("PolygonFromText( wktPolygon String [ , SRID Integer] ) : Polygon</td>");
    html += wxT ("<td bgcolor=\"#f0fff0\">construct a Polygon</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">MPointFromText( wktMultiPoint String [ , SRID Integer] ) : MultiPoint<hr>");
    html +=
	wxT
	("MultiPointFromText( wktMultiPoint String [ , SRID Integer] ) : MultiPoint</td>");
    html += wxT ("<td bgcolor=\"#f0fff0\">construct a MultiPoint</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">MLineFromText( wktMultiLineString String [ , SRID Integer] ) : MultiLinestring<hr>");
    html +=
	wxT
	("MultiLineStringFromText( wktMultiLineString String [ , SRID Integer] ) : MultiLinestring</td>");
    html +=
	wxT ("<td bgcolor=\"#f0fff0\">construct a MultiLinestring</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">MPolyFromText( wktMultiPolygon String [ , SRID Integer] ) : MultiPolygon<hr>");
    html +=
	wxT
	("MultiPolygonFromText( wktMultiPolygon String [ , SRID Integer] ) : MultiPolygon</td>");
    html += wxT ("<td bgcolor=\"#f0fff0\">construct a MultiPolygon</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">GeomCollFromText( wktGeometryCollection String [ , SRID Integer] ) : GeometryCollection<hr>");
    html +=
	wxT
	("GeometryCollectionFromText( wktGeometryCollection String [ , SRID Integer] ) : GeometryCollection</td>");
    html +=
	wxT
	("<td bgcolor=\"#f0fff0\">construct a GeometryCollection</td></tr>");
    html +=
	wxT
	("<tr><td align=\"center\" bgcolor=\"#e0ffe0\" colspan=\"2\"><a name=\"c32\">functions for constructing a geometric object given its Well-known Binary Representation</a>");
    html += wxT ("<br><a href=\"#index\">back to index</a></td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">GeomFromWKB( wkbGeometry Binary [ , SRID Integer] ) : Geometry</td>");
    html +=
	wxT
	("<td bgcolor=\"#f0fff0\">construct a geometric object given its Well-known binary Representation</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">PointFromWKB( wkbPoint Binary [ , SRID Integer] ) : Point</td>");
    html += wxT ("<td bgcolor=\"#f0fff0\">construct a Point</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">LineFromWKB( wkbLineString Binary [ , SRID Integer] ) : Linestring<hr>");
    html +=
	wxT
	("LineStringFromText( wkbLineString Binary [ , SRID Integer] ) : Linestring</td>");
    html += wxT ("<td bgcolor=\"#f0fff0\">construct a Linestring</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">PolyFromWKB( wkbPolygon Binary [ , SRID Integer] ) : Polygon<br>");
    html +=
	wxT
	("PolygonFromWKB( wkbPolygon Binary [ , SRID Integer] ) : Polygon</td>");
    html += wxT ("<td bgcolor=\"#f0fff0\">construct a Polygon</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">MPointFromWKB( wkbMultiPoint Binary [ , SRID Integer] ) : MultiPoint<hr>");
    html +=
	wxT
	("MultiPointFromWKB( wkbMultiPoint Binary [ , SRID Integer] ) : MultiPoint</td>");
    html += wxT ("<td bgcolor=\"#f0fff0\">construct a MultiPoint</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">MLineFromWKB( wkbMultiLineString Binary [ , SRID Integer] ) : MultiLinestring<hr>");
    html +=
	wxT
	("MultiLineStringFromWKB( wkbMultiLineString Binary [ , SRID Integer] ) : MultiLinestring</td>");
    html +=
	wxT ("<td bgcolor=\"#f0fff0\">construct a MultiLinestring</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">MPolyFromWKB( wkbMultiPolygon Binary [ , SRID Integer] ) : MultiPolygon<hr>");
    html +=
	wxT
	("MultiPolygonFromWKB( wkbMultiPolygon Binary [ , SRID Integer] ) : MultiPolygon</td>");
    html += wxT ("<td bgcolor=\"#f0fff0\">construct a MultiPolygon</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">GeomCollFromWKB( wkbGeometryCollection Binary [ , SRID Integer] ) : GeometryCollection<hr>");
    html +=
	wxT
	("GeometryCollectionFromWKB( wkbGeometryCollection Binary [ , SRID Integer] ) : GeometryCollection</td>");
    html +=
	wxT
	("<td bgcolor=\"#f0fff0\">construct a GeometryCollection</td></tr>");
    html +=
	wxT
	("<tr><td align=\"center\" bgcolor=\"#e0ffe0\" colspan=\"2\"><a name=\"c33\">functions for obtaining the Well-known Text / Well-known Binary Representation of a geometric object</a>");
    html += wxT ("<br><a href=\"#index\">back to index</a></td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">AsText( geom Geometry ) : String</td><td bgcolor=\"#f0fff0\">return the Well-known Text representation</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">AsBinary( geom Geometry ) : Binary</td><td bgcolor=\"#f0fff0\">return the Well-known Binary representation</td></tr>");
    html +=
	wxT
	("<tr><td align=\"center\" bgcolor=\"#e0ffe0\" colspan=\"2\"><a name=\"c34\">functions on type Geometry</a>");
    html += wxT ("<br><a href=\"#index\">back to index</a></td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">Dimension( geom Geometry ) : Integer</td>");
    html +=
	wxT
	("<td bgcolor=\"#f0fff0\">return the dimension of the geometric object, which is less than or equal to the dimension of the coordinate space</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">GeometryType( geom Geometry ) : String</td>");
    html +=
	wxT
	("<td bgcolor=\"#f0fff0\">return the name of the instantiable subtype of Geometry of which this geometric object is a member, as a string</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">SRID( geom Geometry ) : Integer</td>");
    html +=
	wxT
	("<td bgcolor=\"#f0fff0\">return the Spatial Reference System ID for this geometric object</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">SetSRID( geom Geometry , SRID Integer ) : Integer</td>");
    html +=
	wxT
	("<td bgcolor=\"#f0fff0\">directly sets the Spatial Reference System ID for this geometric object [no reprojection is applied].<br>");
    html +=
	wxT
	("The return type is Integer, with a return value of 1 for TRUE, 0 for FALSE, and -1 for UNKNOWN corresponding to a ");
    html += wxT ("function invocation on NULL arguments</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">IsEmpty( geom Geometry ) : Integer</td>");
    html +=
	wxT
	("<td bgcolor=\"#f0fff0\">The return type is Integer, with a return value of 1 for TRUE, 0 for FALSE, and -1 for UNKNOWN corresponding to a function invocation on NULL arguments.<br>");
    html +=
	wxT
	("TRUE if this geometric object corresponds to the empty set</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">IsSimple( geom Geometry ) : Integer</td>");
    html +=
	wxT
	("<td bgcolor=\"#f0fff0\">The return type is Integer, with a return value of 1 for TRUE, 0 for FALSE, and -1 for UNKNOWN corresponding to a function invocation on NULL arguments.<br>");
    html +=
	wxT
	("TRUE if this geometric object is simple, as defined in the Geometry Model</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">IsValid( geom Geometry ) : Integer</td>");
    html +=
	wxT
	("<td bgcolor=\"#f0fff0\">The return type is Integer, with a return value of 1 for TRUE, 0 for FALSE, and -1 for UNKNOWN corresponding to a function invocation on NULL arguments.<br>");
    html +=
	wxT
	("TRUE if this geometric object does not contains any topological error</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">Boundary( geom Geometry ) : Geometry</td>");
    html +=
	wxT
	("<td bgcolor=\"#f0fff0\">return a geometric object that is the combinatorial boundary of g as defined in the Geometry Model</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">Envelope( geom Geometry ) : Geometry</td>");
    html +=
	wxT
	("<td bgcolor=\"#f0fff0\">return the rectangle bounding g as a Polygon. ");
    html +=
	wxT
	("The Polygon is defined by the corner points of the bounding box [(MINX, MINY),(MAXX, MINY), (MAXX, MAXY), (MINX, MAXY), (MINX, MINY)].</td></tr>");
    html +=
	wxT
	("<tr><td align=\"center\" bgcolor=\"#e0ffe0\" colspan=\"2\"><a name=\"c35\">functions on type Point</a>");
    html += wxT ("<br><a href=\"#index\">back to index</a></td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">X( pt Point ) : Double precision</td><td bgcolor=\"#f0fff0\">return the x-coordinate of Point p as a double precision number</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">Y( pt Point ) : Double precision</td><td bgcolor=\"#f0fff0\">return the y-coordinate of Point p as a double precision number</td></tr>");
    html +=
	wxT
	("<tr><td align=\"center\" bgcolor=\"#e0ffe0\" colspan=\"2\">functions on type Curve [Linestring or Ring]</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">StartPoint( c Curve ) : Point</td><td bgcolor=\"#f0fff0\">return a Point containing the first Point of c</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">EndPoint( c Curve ) : Point</td><td bgcolor=\"#f0fff0\">return a Point containing the last Point of c</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">NumPoints( line LineString ) : Integer</td><td bgcolor=\"#f0fff0\">return the number of Points in the LineString</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">PointN( line LineString , n Integer ) : Point</td><td bgcolor=\"#f0fff0\">return a Point containing Point n of line</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">GLength( c Curve ) : Double precision</td><td bgcolor=\"#f0fff0\">return the length of c</td></tr>");
    html +=
	wxT ("<tr><td bgcolor=\"#fffff0\">IsClosed( c Curve ) : Integer</td>");
    html +=
	wxT
	("<td bgcolor=\"#f0fff0\">The return type is Integer, with a return value of 1 for TRUE, 0 for FALSE, and -1 for UNKNOWN corresponding to a function invocation on NULL arguments<br>");
    html +=
	wxT
	("return TRUE if c is closed, i.e., if StartPoint(c) = EndPoint(c)</td></tr>");
    html +=
	wxT ("<tr><td bgcolor=\"#fffff0\">IsRing( c Curve ) : Integer</td>");
    html +=
	wxT
	("<td bgcolor=\"#f0fff0\">The return type is Integer, with a return value of 1 for TRUE, 0 for FALSE, and -1 for UNKNOWN corresponding to a function invocation on NULL arguments<br>");
    html +=
	wxT
	("return TRUE if c is a ring, i.e., if c is closed and simple. A simple Curve does not pass through the same Point more than once.</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">Simplify( c Curve , tolerance Double precision ) : Curve</td>");
    html +=
	wxT
	("<td bgcolor=\"#f0fff0\">return a geometric object representing a simplified version of c applying the Douglas-Peukert algorithm with given tolerance</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">SimplifyPreserveTopology( c Curve , tolerance Double precision ) : Curve</td>");
    html +=
	wxT
	("<td bgcolor=\"#f0fff0\">return a geometric object representing a simplified version of c ");
    html +=
	wxT
	("applying the Douglas-Peukert algorithm with given tolerance and respecting topology</td></tr>");
    html +=
	wxT
	("<tr><td align=\"center\" bgcolor=\"#e0ffe0\" colspan=\"2\"><a name=\"c36\">functions on type Surface [Polygon or Ring]</a>");
    html += wxT ("<br><a href=\"#index\">back to index</a></td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">Centroid( s Surface ) : Point</td><td bgcolor=\"#f0fff0\">return the centroid of s, which may lie outside s</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">PointOnSurface( s Surface ) : Point</td><td bgcolor=\"#f0fff0\">return a Point guaranteed to lie on the Surface</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">Area( s Surface ) : Double precision</td><td bgcolor=\"#f0fff0\">return the area of s</td></tr>");
    html +=
	wxT
	("<tr><td align=\"center\" bgcolor=\"#e0ffe0\" colspan=\"2\"><a name=\"c37\">functions on type Polygon</a>");
    html += wxT ("<br><a href=\"#index\">back to index</a></td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">ExteriorRing( polyg Polygon ) : LineString</td><td bgcolor=\"#f0fff0\">return the exteriorRing of p</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">NumInteriorRing( polyg Polygon ) : Integer<hr>NumInteriorRings( polyg Polygon ) : Integer</td>");
    html +=
	wxT
	("<td bgcolor=\"#f0fff0\">return the number of interiorRings</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">InteriorRingN( polyg Polygon , n Integer ) : LineString</td>");
    html +=
	wxT
	("<td bgcolor=\"#f0fff0\">return the nth interiorRing. The order of Rings is not geometrically significant.</td></tr>");
    html +=
	wxT
	("<tr><td align=\"center\" bgcolor=\"#e0ffe0\" colspan=\"2\"><a name=\"c38\">functions on type GeomCollection</a>");
    html += wxT ("<br><a href=\"#index\">back to index</a></td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">NumGeometries( geom GeomCollection ) : Integer</td><td bgcolor=\"#f0fff0\">return the number of geometries</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">GeometryN( geom GeomCollection , n Integer ) : Geometry</td>");
    html +=
	wxT
	("<td bgcolor=\"#f0fff0\">return the nth geometric object in the collection. The order of the elements in the collection is not geometrically significant.</td></tr>");
    html +=
	wxT
	("<tr><td align=\"center\" bgcolor=\"#e0ffe0\" colspan=\"2\"><a name=\"c39\">functions testing approximative spatial relationships via MBRs</a>");
    html += wxT ("<br><a href=\"#index\">back to index</a></td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">MbrEqual( geom1 Geometry , geom2 Geometry ) : Integer</td>");
    html +=
	wxT
	("<td bgcolor=\"#f0fff0\">The return type is Integer, with a return value of 1 for TRUE, 0 for FALSE, and -1 for UNKNOWN corresponding to a function invocation on NULL arguments.<br>");
    html += wxT ("TRUE if g1 and g2 have equal MBRs</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">MbrDisjoint( geom1 Geometry , geom2 Geometry ) : Integer</td>");
    html +=
	wxT
	("<td bgcolor=\"#f0fff0\">The return type is Integer, with a return value of 1 for TRUE, 0 for FALSE, and -1 for UNKNOWN corresponding to a function invocation on NULL arguments.<br>");
    html +=
	wxT
	("TRUE if the intersection of g1 and g2 MBRs is the empty set</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">MbrTouches( geom1 Geometry , geom2 Geometry ) : Integer</td>");
    html +=
	wxT
	("<td bgcolor=\"#f0fff0\">The return type is Integer, with a return value of 1 for TRUE, 0 for FALSE, and -1 for UNKNOWN corresponding to a function invocation on NULL arguments.<br>");
    html +=
	wxT
	("TRUE if the only Points in common between g1 and g2 MBRs lie in the union of the boundaries of g1 and g2</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">MbrWithin( geom1 Geometry , geom2 Geometry ) : Integer</td>");
    html +=
	wxT
	("<td bgcolor=\"#f0fff0\">The return type is Integer, with a return value of 1 for TRUE, 0 for FALSE, and -1 for UNKNOWN corresponding to a function invocation on NULL arguments.<br>");
    html += wxT ("TRUE if g1 MBR is completely contained in g2 MBR</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">MbrOverlaps( geom1 Geometry , geom2 Geometry ) : Integer</td>");
    html +=
	wxT
	("<td bgcolor=\"#f0fff0\">The return type is Integer, with a return value of 1 for TRUE, 0 for FALSE, and -1 for UNKNOWN corresponding to a function invocation on NULL arguments.<br>");
    html +=
	wxT
	("TRUE if the intersection of g1 and g2 MBRs results in a value of the same dimension as g1 and g2 that is different from both g1 and g2</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">MbrIntersects( geom1 Geometry , geom2 Geometry ) : Integer</td>");
    html +=
	wxT
	("<td bgcolor=\"#f0fff0\">The return type is Integer, with a return value of 1 for TRUE, 0 for FALSE, and -1 for UNKNOWN corresponding to a function invocation on NULL arguments<br>");
    html +=
	wxT
	("convenience predicate: TRUE if the intersection of g1 and g2 MBRs is not empty</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">MbrContains( geom1 Geometry , geom2 Geometry ) : Integer</td>");
    html +=
	wxT
	("<td bgcolor=\"#f0fff0\">The return type is Integer, with a return value of 1 for TRUE, 0 for FALSE, and -1 for UNKNOWN corresponding to a function invocation on NULL arguments<br>");
    html +=
	wxT
	("convenience predicate: TRUE if g2 MBR is completely contained in g1 MBR</td></tr>");
    html +=
	wxT
	("<tr><td align=\"center\" bgcolor=\"#e0ffe0\" colspan=\"2\"><a name=\"c40\">functions testing spatial relationships</a>");
    html += wxT ("<br><a href=\"#index\">back to index</a></td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">Equals( geom1 Geometry , geom2 Geometry ) : Integer</td>");
    html +=
	wxT
	("<td bgcolor=\"#f0fff0\">The return type is Integer, with a return value of 1 for TRUE, 0 for FALSE, and -1 for UNKNOWN corresponding to a function invocation on NULL arguments.<br>");
    html += wxT ("TRUE if g1 and g2 are equal</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">Disjoint( geom1 Geometry , geom2 Geometry ) : Integer</td>");
    html +=
	wxT
	("<td bgcolor=\"#f0fff0\">The return type is Integer, with a return value of 1 for TRUE, 0 for FALSE, and -1 for UNKNOWN corresponding to a function invocation on NULL arguments.<br>");
    html +=
	wxT
	("TRUE if the intersection of g1 and g2 is the empty set</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">Touches( geom1 Geometry , geom2 Geometry ) : Integer</td>");
    html +=
	wxT
	("<td bgcolor=\"#f0fff0\">The return type is Integer, with a return value of 1 for TRUE, 0 for FALSE, and -1 for UNKNOWN corresponding to a function invocation on NULL arguments.<br>");
    html +=
	wxT
	("TRUE if the only Points in common between g1 and g2 lie in the union of the boundaries of g1 and g2</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">Within( geom1 Geometry , geom2 Geometry ) : Integer</td>");
    html +=
	wxT
	("<td bgcolor=\"#f0fff0\">The return type is Integer, with a return value of 1 for TRUE, 0 for FALSE, and -1 for UNKNOWN corresponding to a function invocation on NULL arguments.<br>");
    html += wxT ("TRUE if g1 is completely contained in g2</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">Overlaps( geom1 Geometry , geom2 Geometry ) : Integer</td>");
    html +=
	wxT
	("<td bgcolor=\"#f0fff0\">The return type is Integer, with a return value of 1 for TRUE, 0 for FALSE, and -1 for UNKNOWN corresponding to a function invocation on NULL arguments.<br>");
    html +=
	wxT
	("TRUE if the intersection of g1 and g2 results in a value of the same dimension as g1 and g2 that is different from both g1 and g2</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">Crosses( geom1 Geometry , geom2 Geometry ) : Integer</td>");
    html +=
	wxT
	("<td bgcolor=\"#f0fff0\">The return type is Integer, with a return value of 1 for TRUE, 0 for FALSE, and -1 for UNKNOWN corresponding to a function invocation on NULL arguments.<br>");
    html +=
	wxT
	("TRUE if the intersection of g1 and g2 results in a value whose dimension is less than the maximum dimension of g1 and g2 ");
    html +=
	wxT
	("and the intersection value includes Points interior to both g1 and g2, and the intersection value is not equal to either g1 or g2</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">Intersects( geom1 Geometry , geom2 Geometry ) : Integer</td>");
    html +=
	wxT
	("<td bgcolor=\"#f0fff0\">The return type is Integer, with a return value of 1 for TRUE, 0 for FALSE, and -1 for UNKNOWN corresponding to a function invocation on NULL arguments<br>");
    html +=
	wxT
	("convenience predicate: TRUE if the intersection of g1 and g2 is not empty</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">Contains( geom1 Geometry , geom2 Geometry ) : Integer</td>");
    html +=
	wxT
	("<td bgcolor=\"#f0fff0\">The return type is Integer, with a return value of 1 for TRUE, 0 for FALSE, and -1 for UNKNOWN corresponding to a function invocation on NULL arguments<br>");
    html +=
	wxT
	("convenience predicate: TRUE if g2 is completely contained in g1</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">Relate( geom1 Geometry , geom2 Geometry , patternMatrix String ) : Integer</td>");
    html +=
	wxT
	("<td bgcolor=\"#f0fff0\">The return type is Integer, with a return value of 1 for TRUE, 0 for FALSE, and -1 for UNKNOWN corresponding to a function invocation on NULL arguments.<br>");
    html +=
	wxT
	("return TRUE if the spatial relationship specified by the patternMatrix holds</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">Distance( geom1 Geometry , geom2 Geometry ) : Double precision</td>");
    html +=
	wxT
	("<td bgcolor=\"#f0fff0\">return the distance between geom1 and geom2</td></tr>");
    html +=
	wxT
	("<tr><td align=\"center\" bgcolor=\"#e0ffe0\" colspan=\"2\"><a name=\"c41\">functions implementing spatial operators</a>");
    html += wxT ("<br><a href=\"#index\">back to index</a></td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">Intersection( geom1 Geometry , geom2 Geometry ) : Geometry</td>");
    html +=
	wxT
	("<td bgcolor=\"#f0fff0\">return a geometric object that is the intersection of geometric objects geom1 and geom2</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">Difference( geom1 Geometry , geom2 Geometry ) : Geometry</td>");
    html +=
	wxT
	("<td bgcolor=\"#f0fff0\">return a geometric object that is the closure of the set difference of geom1 and geom2</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">GUnion( geom1 Geometry , geom2 Geometry ) : Geometry</td>");
    html +=
	wxT
	("<td bgcolor=\"#f0fff0\">return a geometric object that is the set union of geom1 and geom2</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">SymDifference( geom1 Geometry , geom2 Geometry ) : Geometry</td>");
    html +=
	wxT
	("<td bgcolor=\"#f0fff0\">return a geometric object that is the closure of the set symmetric difference of geom1 and geom2 (logical XOR of space)</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">Buffer( geom Geometry , dist Double precision ) : Geometry</td>");
    html +=
	wxT
	("<td bgcolor=\"#f0fff0\">return a geometric object defined by buffering a distance d around geom, ");
    html +=
	wxT
	("where dist is in the distance units for the Spatial Reference of geom</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">ConvexHull( geom Geometry ) : Geometry</td>");
    html +=
	wxT
	("<td bgcolor=\"#f0fff0\">return a geometric object that is the convex hull of geom</td></tr>");
    html +=
	wxT
	("<tr><td align=\"center\" bgcolor=\"#e0ffe0\" colspan=\"2\"><a name=\"c42\">functions for coordinate transformations</a>");
    html += wxT ("<br><a href=\"#index\">back to index</a></td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">Transform( geom Geometry , newSRID Integer ) : Geometry</td>");
    html +=
	wxT
	("<td bgcolor=\"#f0fff0\">return a geometric object obtained by reprojecting coordinates into the Reference System identified by newSRID</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">ShiftCoords( geom Geometry , shiftX Double precision , shiftY Double precision ) : Geometry<hr>");
    html +=
	wxT
	("ShiftCoordinates( geom Geometry , shiftX Double precision , shiftY Double precision ) : Geometry</td>");
    html +=
	wxT
	("<td bgcolor=\"#f0fff0\">return a geometric object obtained by translating coordinates according to shiftX and shiftY values</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">ScaleCoords( geom Geometry , scaleX Double precision [ , scaleY Double precision ] ) : Geometry<hr>");
    html +=
	wxT
	("ScaleCoordinates( geom Geometry , scaleX Double precision [ , scaleY Double precision ] ) : Geometry</td>");
    html +=
	wxT
	("<td bgcolor=\"#f0fff0\">return a geometric object obtained by scaling coordinates according to scaleX and scaleY values<br>");
    html +=
	wxT
	("if only one scale factor is specified, then an isotropic scaling occurs [i.e. the same scale factor is applied to both axis]");
    html +=
	wxT
	("otherwise an anisotropic scaling occurs [i.e. each axis is scaled according to its own scale factor]</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">RotateCoords( geom Geometry , angleInDegrees Double precision ) : Geometry<hr>");
    html +=
	wxT
	("RotateCoordinates( geom Geometry , angleInDegrees Double precision ) : Geometry</td>");
    html +=
	wxT
	("<td bgcolor=\"#f0fff0\">return a geometric object obtained by rotating coordinates according to angleInDegrees value</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">ReflectCoords( geom Geometry , xAxis Integer , yAxis Integer ) : Geometry<hr>");
    html +=
	wxT
	("ReflectCoordinates( geom Geometry , xAxis Integer , yAxis Integer ) : Geometry</td>");
    html +=
	wxT
	("<td bgcolor=\"#f0fff0\">return a geometric object obtained by reflecting coordinates according to xAxis and yAxis switches<br>");
    html +=
	wxT
	("i.e. if xAxis is 0 (FALSE), then x-coordinates remains untouched; otherwise x-coordinates will be reflected</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">SwapCoords( geom Geometry ) : Geometry<hr>SwapCoordinates( geom Geometry ) : Geometry</td>");
    html +=
	wxT
	("<td bgcolor=\"#f0fff0\">return a geometric object obtained by swapping x- and y-coordinates</td></tr>");
    html +=
	wxT
	("<tr><td align=\"center\" bgcolor=\"#e0ffe0\" colspan=\"2\"><a name=\"c43\">functions for Spatial-MetaData and Spatial-Index handling</a>");
    html += wxT ("<br><a href=\"#index\">back to index</a></td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">InitSpatialMetaData( void ) : Integer</td>");
    html +=
	wxT
	("<td bgcolor=\"#f0fff0\">Creates the geometry_columns and spatial_ref_sys metadata tables");
    html +=
	wxT
	("the return type is Integer, with a return value of 1 for TRUE or 0 for FALSE<br>");
    html +=
	wxT
	("direct invocation of these function is discouraged; you have to run the init_spatialite.sql ");
    html +=
	wxT
	("script in order to fully initialize the Spatial MetaData tables</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">AddGeometryColumn( table String , column String , srid Integer , geom_type String , dimension Integer ) : Integer</td>");
    html +=
	wxT
	("<td bgcolor=\"#f0fff0\">Creates a new geometry column updating the Spatial Metadata tables and creating any required trigger in order to enforce constraints<br>");
    html +=
	wxT
	("the return type is Integer, with a return value of 1 for TRUE or 0 for FALSE</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">RecoverGeometryColumn( table String , column String , srid Integer , geom_type String , dimension Integer ) : Integer</td>");
    html +=
	wxT
	("<td bgcolor=\"#f0fff0\">Validates an existing ordinary column in order to possibly transform it in a real geometry column, ");
    html +=
	wxT
	("thus updating the Spatial Metadata tables and creating any required trigger in order to enforce constraints<br>");
    html +=
	wxT
	("the return type is Integer, with a return value of 1 for TRUE or 0 for FALSE</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">DiscardGeometryColumn( table String , column String ) : Integer</td>");
    html +=
	wxT
	("<td bgcolor=\"#f0fff0\">Removes a geometry column from Spatial MetaData tables and drops any related trigger<br>");
    html +=
	wxT
	("the column itself still continues to exist untouched as an ordinary, unconstrained column<br>");
    html +=
	wxT
	("the return type is Integer, with a return value of 1 for TRUE or 0 for FALSE</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">CreateSpatialIndex( table String , column String ) : Integer</td>");
    html +=
	wxT
	("<td bgcolor=\"#f0fff0\">Builds an RTree Spatial Index on a geometry column, ");
    html +=
	wxT
	("creating any required trigger required in order to enforce full data coherency between the main table and Spatial Index<br>");
    html +=
	wxT
	("the return type is Integer, with a return value of 1 for TRUE or 0 for FALSE</td></tr>");
    html +=
	wxT
	("<tr><td bgcolor=\"#fffff0\">DisableSpatialIndex( table String , column String ) : Integer</td>");
    html +=
	wxT
	("<td bgcolor=\"#f0fff0\">Disables an RTree Spatial Index, removing any related trigger<br>");
    html +=
	wxT
	("the return type is Integer, with a return value of 1 for TRUE or 0 for FALSE</td></tr>");
    html += wxT ("</table>");
    html += wxT ("<a href=\"#index\">back to index</a>");
    html += wxT ("</body>");
    html += wxT ("</html>");
}

































































































































































































































































































































































































































































































































































































































|







 







>









>



>
>
>
>






>
>






|
|




|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>




|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>




|
|
|
|
|
|
|
|
|


|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|




|
|
|
>
|
|
|
|
|
>
|
|
|
|
|


<
|




|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
..
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155

2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
/*
/ Main.cpp
/ the main core of spatialite-gui  - a SQLite /SpatiaLite GUI tool
/
/ version 1.2, 2008 October 9
/
/ Author: Sandro Furieri a-furieri@lqt.it
/
/ Copyright (C) 2008  Alessandro Furieri
/
/    This program is free software: you can redistribute it and/or modify
/    it under the terms of the GNU General Public License as published by
................................................................................
*/

#include "Classdef.h"

#include "wx/menu.h"
#include "wx/aboutdlg.h"
#include "wx/filename.h"
#include "wx/config.h"

#include <spatialite.h>
#include <proj_api.h>
#include <geos_c.h>

//
// ICONs in XPM format [universally portable]
//
#include "icons/icon.xpm"
#include "icons/icon_info.xpm"
#include "icons/create_new.xpm"
#include "icons/connect.xpm"
#include "icons/disconnect.xpm"
#include "icons/memdb_load.xpm"
#include "icons/memdb_new.xpm"
#include "icons/memdb_clock.xpm"
#include "icons/memdb_save.xpm"
#include "icons/vacuum.xpm"
#include "icons/sql_script.xpm"
#include "icons/loadshp.xpm"
#include "icons/virtshp.xpm"
#include "icons/loadtxt.xpm"
#include "icons/virttxt.xpm"
#include "icons/network.xpm"
#include "icons/exif.xpm"
#include "icons/srids.xpm"
#include "icons/charset.xpm"
#include "icons/help.xpm"
#include "icons/about.xpm"
#include "icons/exit.xpm"

IMPLEMENT_APP(MyApp)
     bool MyApp::OnInit()
{
//
// main APP implementation
//
  wxString path;
  if (argc > 1)
    path = argv[1];
  MyFrame *frame =
    new MyFrame(wxT("spatialite-gui      [a GUI tool for SQLite/SpatiaLite]"),
                wxPoint(0, 0), wxSize(640, 480), path);
  frame->Show(true);
  SetTopWindow(frame);
  frame->LoadConfig();
  return true;
}

MyFrame::MyFrame(const wxString & title, const wxPoint & pos, const wxSize & size, wxString & path):
wxFrame((wxFrame *) NULL, -1, title, pos, size)
{
//
// main GUI frame constructor
//
  MemoryDatabase = false;
  AutoSaveInterval = 0;
  LastTotalChanges = 0;
  TimerAutoSave = NULL;
//
// initializing CHARSET lists
//
  CharsetsLen = 79;
  Charsets = new wxString[CharsetsLen];
  CharsetsNames = new wxString[CharsetsLen];
  *(CharsetsNames + 0) = wxT("ARMSCII-8    Armenian");
  *(CharsetsNames + 1) = wxT("ASCII        US-ASCII");
  *(CharsetsNames + 2) = wxT("BIG5         Chinese/Traditional");
  *(CharsetsNames + 3) = wxT("BIG5-HKSCS   Chinese/Hong Kong");
  *(CharsetsNames + 4) = wxT("BIG5-HKSCS:1999");
  *(CharsetsNames + 5) = wxT("BIG5-HKSCS:2001");
  *(CharsetsNames + 6) = wxT("CP850        DOS/OEM Western Europe");
  *(CharsetsNames + 7) = wxT("CP862        DOS/OEM Hebrew");
  *(CharsetsNames + 8) = wxT("CP866        DOS/OEM Cyrillic");
  *(CharsetsNames + 9) = wxT("CP874        DOS/OEM Thai");
  *(CharsetsNames + 10) = wxT("CP932        DOS/OEM Japanese");
  *(CharsetsNames + 11) = wxT("CP936        DOS/OEM Chinese");
  *(CharsetsNames + 12) = wxT("CP949        DOS/OEM Korean");
  *(CharsetsNames + 13) = wxT("CP950        DOS/OEM Chinese/Big5");
  *(CharsetsNames + 14) = wxT("CP1133       Laotian");
  *(CharsetsNames + 15) = wxT("CP1250       Windows Central Europe");
  *(CharsetsNames + 16) = wxT("CP1251       Windows Cyrillic");
  *(CharsetsNames + 17) = wxT("CP1252       Windows Latin 1");
  *(CharsetsNames + 18) = wxT("CP1253       Windows Greek");
  *(CharsetsNames + 19) = wxT("CP1254       Windows Turkish");
  *(CharsetsNames + 20) = wxT("CP1255       Windows Hebrew");
  *(CharsetsNames + 21) = wxT("CP1256       Windows Arabic");
  *(CharsetsNames + 22) = wxT("CP1257       Windows Baltic");
  *(CharsetsNames + 23) = wxT("CP1258       Windows Vietnamese");
  *(CharsetsNames + 24) = wxT("EUC-CN       Chinese");
  *(CharsetsNames + 25) = wxT("EUC-JP       Japanese");
  *(CharsetsNames + 26) = wxT("EUC-KR       Korean");
  *(CharsetsNames + 27) = wxT("EUC-TW       Taiwan");
  *(CharsetsNames + 28) = wxT("GB18030      Chinese/National Standard");
  *(CharsetsNames + 29) = wxT("GBK          Chinese/Simplified");
  *(CharsetsNames + 30) = wxT("Georgian-Academy");
  *(CharsetsNames + 31) = wxT("Georgian-PS");
  *(CharsetsNames + 32) = wxT("HZ           Chinese");
  *(CharsetsNames + 33) = wxT("ISO-2022-CN  Chinese");
  *(CharsetsNames + 34) = wxT("ISO-2022-CN-EXT");
  *(CharsetsNames + 35) = wxT("ISO-2022-JP  Japanese");
  *(CharsetsNames + 36) = wxT("ISO-2022-JP-1");
  *(CharsetsNames + 37) = wxT("ISO-2022-JP-2");
  *(CharsetsNames + 38) = wxT("ISO-2022-KR  Korean");
  *(CharsetsNames + 39) = wxT("ISO-8859-1   Latin-1 Western European");
  *(CharsetsNames + 40) = wxT("ISO-8859-2   Latin-2 Central European");
  *(CharsetsNames + 41) = wxT("ISO-8859-3   Latin-3 South European");
  *(CharsetsNames + 42) = wxT("ISO-8859-4   Latin-4 North European");
  *(CharsetsNames + 43) = wxT("ISO-8859-5   Latin/Cyrillic");
  *(CharsetsNames + 44) = wxT("ISO-8859-6   Latin/Arabic");
  *(CharsetsNames + 45) = wxT("ISO-8859-7   Latin/Greek");
  *(CharsetsNames + 46) = wxT("ISO-8859-8   Latin/Hebrew");
  *(CharsetsNames + 47) = wxT("ISO-8859-9   Latin-5 Turkish");
  *(CharsetsNames + 48) = wxT("ISO-8859-10  Latin-6 Nordic");
  *(CharsetsNames + 49) = wxT("ISO-8859-11  Latin/Thai");
  *(CharsetsNames + 50) = wxT("ISO-8859-13  Latin-7 Baltic Rim");
  *(CharsetsNames + 51) = wxT("ISO-8859-14  Latin-8 Celtic");
  *(CharsetsNames + 52) = wxT("ISO-8859-15  Latin-9");
  *(CharsetsNames + 53) = wxT("ISO-8859-16  Latin-10 South-Eastern European");
  *(CharsetsNames + 54) = wxT("JOHAB        Korean");
  *(CharsetsNames + 55) = wxT("KOI8-R       Russian");
  *(CharsetsNames + 56) = wxT("KOI8-U       Ukrainian");
  *(CharsetsNames + 57) = wxT("KOI8-RU      Belarusian");
  *(CharsetsNames + 58) = wxT("KOI8-T       Tajik");
  *(CharsetsNames + 59) = wxT("MacArabic    MAC Arabic");
  *(CharsetsNames + 60) = wxT("MacCentralEurope");
  *(CharsetsNames + 61) = wxT("MacCroatian  MAC Croatian");
  *(CharsetsNames + 62) = wxT("MacCyrillic  MAC Cyrillic");
  *(CharsetsNames + 63) = wxT("MacGreek     MAC Greek");
  *(CharsetsNames + 64) = wxT("MacHebrew    MAC Hebrew");
  *(CharsetsNames + 65) = wxT("MacIceland   MAC Iceland");
  *(CharsetsNames + 66) = wxT("Macintosh");
  *(CharsetsNames + 67) = wxT("MacRoman     MAC European/Western languages");
  *(CharsetsNames + 68) = wxT("MacRomania   MAC Romania");
  *(CharsetsNames + 69) = wxT("MacThai      MAC Thai");
  *(CharsetsNames + 70) = wxT("MacTurkish   MAC Turkish");
  *(CharsetsNames + 71) = wxT("MacUkraine   MAC Ukraine");
  *(CharsetsNames + 72) = wxT("MuleLao-1    Laotian");
  *(CharsetsNames + 73) = wxT("PT154        Kazakh");
  *(CharsetsNames + 74) = wxT("RK1048       Kazakh");
  *(CharsetsNames + 75) = wxT("SHIFT_JIS    Japanese");
  *(CharsetsNames + 76) = wxT("TCVN         Vietnamese");
  *(CharsetsNames + 77) = wxT("TIS-620      Thai");
  *(CharsetsNames + 77) = wxT("UTF-8        UNICODE/Universal");
  *(CharsetsNames + 78) = wxT("VISCII       Vietnamese");
  *(Charsets + 0) = wxT("ARMSCII-8");
  *(Charsets + 1) = wxT("ASCII");
  *(Charsets + 2) = wxT("BIG5");
  *(Charsets + 3) = wxT("BIG5-HKSCS");
  *(Charsets + 4) = wxT("BIG5-HKSCS:1999");
  *(Charsets + 5) = wxT("BIG5-HKSCS:2001");
  *(Charsets + 6) = wxT("CP850");
  *(Charsets + 7) = wxT("CP862");
  *(Charsets + 8) = wxT("CP866");
  *(Charsets + 9) = wxT("CP874");
  *(Charsets + 10) = wxT("CP932");
  *(Charsets + 11) = wxT("CP936");
  *(Charsets + 12) = wxT("CP949");
  *(Charsets + 13) = wxT("CP950");
  *(Charsets + 14) = wxT("CP1133");
  *(Charsets + 15) = wxT("CP1250");
  *(Charsets + 16) = wxT("CP1251");
  *(Charsets + 17) = wxT("CP1252");
  *(Charsets + 18) = wxT("CP1253");
  *(Charsets + 19) = wxT("CP1254");
  *(Charsets + 20) = wxT("CP1255");
  *(Charsets + 21) = wxT("CP1256");
  *(Charsets + 22) = wxT("CP1257");
  *(Charsets + 23) = wxT("CP1258");
  *(Charsets + 24) = wxT("EUC-CN");
  *(Charsets + 25) = wxT("EUC-JP");
  *(Charsets + 26) = wxT("EUC-KR");
  *(Charsets + 27) = wxT("EUC-TW");
  *(Charsets + 28) = wxT("GB18030");
  *(Charsets + 29) = wxT("GBK");
  *(Charsets + 30) = wxT("Georgian-Academy");
  *(Charsets + 31) = wxT("Georgian-PS");
  *(Charsets + 32) = wxT("HZ");
  *(Charsets + 33) = wxT("ISO-2022-CN");
  *(Charsets + 34) = wxT("ISO-2022-CN-EXT");
  *(Charsets + 35) = wxT("ISO-2022-JP");
  *(Charsets + 36) = wxT("ISO-2022-JP-1");
  *(Charsets + 37) = wxT("ISO-2022-JP-2");
  *(Charsets + 38) = wxT("ISO-2022-KR");
  *(Charsets + 39) = wxT("ISO-8859-1");
  *(Charsets + 40) = wxT("ISO-8859-2");
  *(Charsets + 41) = wxT("ISO-8859-3");
  *(Charsets + 42) = wxT("ISO-8859-4");
  *(Charsets + 43) = wxT("ISO-8859-5");
  *(Charsets + 44) = wxT("ISO-8859-6");
  *(Charsets + 45) = wxT("ISO-8859-7");
  *(Charsets + 46) = wxT("ISO-8859-8");
  *(Charsets + 47) = wxT("ISO-8859-9");
  *(Charsets + 48) = wxT("ISO-8859-10");
  *(Charsets + 49) = wxT("ISO-8859-11");
  *(Charsets + 50) = wxT("ISO-8859-13");
  *(Charsets + 51) = wxT("ISO-8859-14");
  *(Charsets + 52) = wxT("ISO-8859-15");
  *(Charsets + 53) = wxT("ISO-8859-16");
  *(Charsets + 54) = wxT("JOHAB");
  *(Charsets + 55) = wxT("KOI8-R");
  *(Charsets + 56) = wxT("KOI8-U");
  *(Charsets + 57) = wxT("KOI8-RU");
  *(Charsets + 58) = wxT("KOI8-T");
  *(Charsets + 59) = wxT("MacArabic");
  *(Charsets + 60) = wxT("MacCentralEurope");
  *(Charsets + 61) = wxT("MacCroatian");
  *(Charsets + 62) = wxT("MacCyrillic");
  *(Charsets + 63) = wxT("MacGreek");
  *(Charsets + 64) = wxT("MacHebrew");
  *(Charsets + 65) = wxT("MacIceland");
  *(Charsets + 66) = wxT("Macintosh");
  *(Charsets + 67) = wxT("MacRoman");
  *(Charsets + 68) = wxT("MacRomania");
  *(Charsets + 69) = wxT("MacThai");
  *(Charsets + 70) = wxT("MacTurkish");
  *(Charsets + 71) = wxT("MacUkraine");
  *(Charsets + 72) = wxT("MuleLao-1");
  *(Charsets + 73) = wxT("PT154");
  *(Charsets + 74) = wxT("RK1048");
  *(Charsets + 75) = wxT("SHIFT_JIS");
  *(Charsets + 76) = wxT("TCVN");
  *(Charsets + 77) = wxT("TIS-620");
  *(Charsets + 77) = wxT("UTF-8");
  *(Charsets + 78) = wxT("VISCII");
  LocaleCharset = wxString::FromUTF8(gaiaGetLocaleCharset());
  DefaultCharset = LocaleCharset;
  AskCharset = false;

  spatialite_init(0);           // loading the SpatiaLite extension

  HelpPane = false;
  SqliteHandle = NULL;
  SqlitePath = wxT("");
  BtnConnect = new wxBitmap(connect_xpm);
  BtnCreateNew = new wxBitmap(create_new_xpm);
  BtnDisconnect = new wxBitmap(disconnect_xpm);
  BtnMemDbLoad = new wxBitmap(memdb_load_xpm);
  BtnMemDbNew = new wxBitmap(memdb_new_xpm);
  BtnMemDbClock = new wxBitmap(memdb_clock_xpm);
  BtnMemDbSave = new wxBitmap(memdb_save_xpm);
  BtnVacuum = new wxBitmap(vacuum_xpm);
  BtnSqlScript = new wxBitmap(sql_script_xpm);
  BtnLoadShp = new wxBitmap(loadshp_xpm);
  BtnVirtualShp = new wxBitmap(virtshp_xpm);
  BtnLoadTxt = new wxBitmap(loadtxt_xpm);
  BtnVirtualTxt = new wxBitmap(virttxt_xpm);
  BtnNetwork = new wxBitmap(network_xpm);
  BtnExif = new wxBitmap(exif_xpm);
  BtnSrids = new wxBitmap(srids_xpm);
  BtnCharset = new wxBitmap(charset_xpm);
  BtnHelp = new wxBitmap(help_xpm);
  BtnAbout = new wxBitmap(about_xpm);
  BtnExit = new wxBitmap(exit_xpm);

//
// setting up the application icon
//      
  wxIcon MyIcon(icon_xpm);
  SetIcon(MyIcon);

//
// setting up panes
//
  TableTree = new MyTableTree(this);
  QueryView = new MyQueryView(this);
  RsView = new MyResultSetView(this);
  Manager.SetManagedWindow(this);
  wxAuiPaneInfo paneSql = wxAuiPaneInfo().Top();
  paneSql.Name(wxT("sql_stmt"));
  paneSql.CaptionVisible(false);
  paneSql.Floatable(true);
  paneSql.Dockable(true);
  paneSql.Movable(true);
  paneSql.Gripper(true);
  paneSql.CloseButton(false);
  paneSql.BestSize(wxSize(200, 120));
  Manager.AddPane(QueryView, paneSql);
  wxAuiPaneInfo paneView = wxAuiPaneInfo().Centre();
  paneView.Name(wxT("result_set"));
  paneView.CaptionVisible(false);
  paneView.Floatable(true);
  paneView.Dockable(true);
  paneView.Movable(true);
  paneView.Gripper(false);
  paneView.CloseButton(false);
  Manager.AddPane(RsView, paneView);
  wxAuiPaneInfo paneTree = wxAuiPaneInfo().Left();
  paneTree.Name(wxT("tree_view"));
  paneTree.CaptionVisible(false);
  paneTree.Floatable(true);
  paneTree.Dockable(true);
  paneTree.Movable(true);
  paneTree.Gripper(true);
  paneTree.CloseButton(false);
  paneTree.BestSize(wxSize(200, 480));
  Manager.AddPane(TableTree, paneTree, wxPoint(0, 10));
  Manager.Update();
  Centre();

//
// setting up the status bar
//
  wxStatusBar *statusBar = new wxStatusBar(this);
  SetStatusBar(statusBar);

//
// setting up the menu bar
//
  wxMenu *menuFile = new wxMenu;
  wxMenuItem *menuItem;
  menuItem =
    new wxMenuItem(menuFile, ID_Connect,
                   wxT("&Connecting an existing SQLite DB"));
  menuItem->SetBitmap(*BtnConnect);
  menuFile->Append(menuItem);
  menuItem =
    new wxMenuItem(menuFile, ID_CreateNew,
                   wxT("Creating a &New (empty) SQLite DB"));
  menuItem->SetBitmap(*BtnCreateNew);
  menuFile->Append(menuItem);
  wxMenu *memoryMenu = new wxMenu();
  menuItem =
    new wxMenuItem(memoryMenu, ID_MemoryDbLoad,
                   wxT("&Loading an existing DB into the MEMORY-DB"));
  menuItem->SetBitmap(*BtnMemDbLoad);
  memoryMenu->Append(menuItem);
  menuItem =
    new wxMenuItem(memoryMenu, ID_MemoryDbNew,
                   wxT("Creating a &New (empty) MEMORY-DB"));
  menuItem->SetBitmap(*BtnMemDbNew);
  memoryMenu->Append(menuItem);
  menuItem =
    new wxMenuItem(memoryMenu, ID_MemoryDbClock,
                   wxT("&AutoSaving the current MEMORY-DB"));
  menuItem->SetBitmap(*BtnMemDbClock);
  memoryMenu->Append(menuItem);
  menuItem =
    new wxMenuItem(memoryMenu, ID_MemoryDbSave,
                   wxT("&Saving the current MEMORY-DB"));
  menuItem->SetBitmap(*BtnMemDbSave);
  memoryMenu->Append(menuItem);
  menuFile->AppendSubMenu(memoryMenu, wxT("&MEMORY-DB"));
  menuItem =
    new wxMenuItem(menuFile, ID_Disconnect,
                   wxT("&Disconnecting current SQLite DB"));
  menuItem->SetBitmap(*BtnDisconnect);
  menuFile->Append(menuItem);
  menuItem =
    new wxMenuItem(menuFile, ID_Disconnect,
                   wxT("&Disconnecting current SQLite DB"));
  menuItem->SetBitmap(*BtnDisconnect);
  menuFile->Append(menuItem);
  menuItem =
    new wxMenuItem(menuFile, ID_Vacuum,
                   wxT("&Optimizing current SQLite DB [VACUUM]"));
  menuItem->SetBitmap(*BtnVacuum);
  menuFile->Append(menuItem);
  menuFile->AppendSeparator();
  menuItem = new wxMenuItem(menuFile, ID_SqlScript, wxT("&Execute SQL script"));
  menuItem->SetBitmap(*BtnSqlScript);
  menuFile->Append(menuItem);
  menuFile->AppendSeparator();
  menuItem = new wxMenuItem(menuFile, ID_LoadShp, wxT("&Load Shapefile"));
  menuItem->SetBitmap(*BtnLoadShp);
  menuFile->Append(menuItem);
  menuItem = new wxMenuItem(menuFile, ID_VirtualShp, wxT("&Virtual Shapefile"));
  menuItem->SetBitmap(*BtnVirtualShp);
  menuFile->Append(menuItem);
  menuFile->AppendSeparator();
  menuItem = new wxMenuItem(menuFile, ID_LoadTxt, wxT("Load CSV/&TXT"));
  menuItem->SetBitmap(*BtnLoadTxt);
  menuFile->Append(menuItem);
  menuItem = new wxMenuItem(menuFile, ID_VirtualTxt, wxT("Virtual &CSV/TXT"));
  menuItem->SetBitmap(*BtnVirtualTxt);
  menuFile->Append(menuItem);
  menuFile->AppendSeparator();
  menuItem = new wxMenuItem(menuFile, ID_Network, wxT("Build &Network"));
  menuItem->SetBitmap(*BtnNetwork);
  menuFile->Append(menuItem);
  menuFile->AppendSeparator();
  menuItem = new wxMenuItem(menuFile, ID_Exif, wxT("Import &EXIF photos"));
  menuItem->SetBitmap(*BtnExif);
  menuFile->Append(menuItem);
  menuFile->AppendSeparator();
  menuItem = new wxMenuItem(menuFile, ID_Srids, wxT("&Search SRID by name"));
  menuItem->SetBitmap(*BtnSrids);
  menuFile->Append(menuItem);
  menuItem =
    new wxMenuItem(menuFile, ID_Charset, wxT("&Default Output Charset"));
  menuItem->SetBitmap(*BtnCharset);
  menuFile->Append(menuItem);
  menuFile->AppendSeparator();
  menuItem = new wxMenuItem(menuFile, ID_Help, wxT("&Help"));
  menuItem->SetBitmap(*BtnHelp);
  menuItem = new wxMenuItem(menuFile, wxID_ABOUT, wxT("&About ..."));
  menuItem->SetBitmap(*BtnAbout);
  menuFile->Append(menuItem);
  menuFile->AppendSeparator();
  menuItem = new wxMenuItem(menuFile, wxID_EXIT, wxT("&Quit"));
  menuItem->SetBitmap(*BtnExit);
  menuFile->Append(menuItem);
  wxMenuBar *menuBar = new wxMenuBar;
  menuBar->Append(menuFile, wxT("&Files"));
  SetMenuBar(menuBar);

//
// setting up menu initial state 
//
  menuBar->Enable(ID_Disconnect, false);
  menuBar->Enable(ID_MemoryDbClock, false);
  menuBar->Enable(ID_MemoryDbSave, false);
  menuBar->Enable(ID_Vacuum, false);
  menuBar->Enable(ID_SqlScript, false);
  menuBar->Enable(ID_LoadShp, false);
  menuBar->Enable(ID_VirtualShp, false);
  menuBar->Enable(ID_LoadTxt, false);
  menuBar->Enable(ID_VirtualTxt, false);
  menuBar->Enable(ID_Network, false);
  menuBar->Enable(ID_Exif, false);
  menuBar->Enable(ID_Srids, false);

//
// setting up the toolbar
//      
  wxToolBar *toolBar = CreateToolBar();
  toolBar->AddTool(ID_Connect, wxT("Connecting an existing SQLite DB"),
                   *BtnConnect, wxNullBitmap, wxITEM_NORMAL,
                   wxT("Connecting an existing SQLite DB"));
  toolBar->AddTool(ID_CreateNew, wxT("Creating a &New (empty) SQLite DB"),
                   *BtnCreateNew, wxNullBitmap, wxITEM_NORMAL,
                   wxT("Creating a &New (empty) SQLite DB"));
  toolBar->AddTool(ID_MemoryDbLoad,
                   wxT("Loading an existing DB into the MEMORY-DB"),
                   *BtnMemDbLoad, wxNullBitmap, wxITEM_NORMAL,
                   wxT("Loading an existing DB into the MEMORY-DB"));
  toolBar->AddTool(ID_MemoryDbNew, wxT("Creating a New (empty) MEMORY-DB"),
                   *BtnMemDbNew, wxNullBitmap, wxITEM_NORMAL,
                   wxT("Creating a New (empty) MEMORY-DB"));
  toolBar->AddTool(ID_MemoryDbClock, wxT("AutoSaving the current MEMORY-DB"),
                   *BtnMemDbClock, wxNullBitmap, wxITEM_NORMAL,
                   wxT("AutoSaving the current MEMORY-DB"));
  toolBar->AddTool(ID_MemoryDbSave, wxT("Saving the current MEMORY-DB"),
                   *BtnMemDbSave, wxNullBitmap, wxITEM_NORMAL,
                   wxT("Saving the current MEMORY-DB"));
  toolBar->AddTool(ID_Disconnect, wxT("Disconnecting current SQLite DB"),
                   *BtnDisconnect, wxNullBitmap, wxITEM_NORMAL,
                   wxT("Disconnecting current SQLite DB"));
  toolBar->AddTool(ID_Vacuum, wxT("Optimizing current SQLite DB [VACUUM]"),
                   *BtnVacuum, wxNullBitmap, wxITEM_NORMAL,
                   wxT("Optimizing current SQLite DB [VACUUM]"));
  toolBar->AddSeparator();
  toolBar->AddTool(ID_SqlScript, wxT("Execute SQL script"), *BtnSqlScript,
                   wxNullBitmap, wxITEM_NORMAL, wxT("Execute SQL script"));
  toolBar->AddSeparator();
  toolBar->AddTool(ID_LoadShp, wxT("Load Shapefile"), *BtnLoadShp, wxNullBitmap,
                   wxITEM_NORMAL, wxT("Load Shapefile"));
  toolBar->AddTool(ID_VirtualShp, wxT("Virtual Shapefile"), *BtnVirtualShp,
                   wxNullBitmap, wxITEM_NORMAL, wxT("Virtual Shapefile"));
  toolBar->AddSeparator();
  toolBar->AddTool(ID_LoadTxt, wxT("Load CSV/TXT"), *BtnLoadTxt, wxNullBitmap,
                   wxITEM_NORMAL, wxT("Load CSV/TXT"));
  toolBar->AddTool(ID_VirtualTxt, wxT("Virtual CSV/TXT"), *BtnVirtualTxt,
                   wxNullBitmap, wxITEM_NORMAL, wxT("Virtual CSV/TXT"));
  toolBar->AddSeparator();
  toolBar->AddTool(ID_Network, wxT("Build Network"), *BtnNetwork, wxNullBitmap,
                   wxITEM_NORMAL, wxT("Build Network"));
  toolBar->AddSeparator();
  toolBar->AddTool(ID_Exif, wxT("Import EXIF photos"), *BtnExif, wxNullBitmap,
                   wxITEM_NORMAL, wxT("Import EXIF photos"));
  toolBar->AddSeparator();
  toolBar->AddTool(ID_Srids, wxT("Search SRID by name"), *BtnSrids,
                   wxNullBitmap, wxITEM_NORMAL, wxT("Search SRID by name"));
  toolBar->AddSeparator();
  toolBar->AddTool(ID_Charset, wxT("Default Output Charset"), *BtnCharset,
                   wxNullBitmap, wxITEM_NORMAL, wxT("Default Output Charset"));
  toolBar->AddSeparator();
  toolBar->AddTool(ID_Help, wxT("Help"), *BtnHelp, wxNullBitmap, wxITEM_NORMAL,
                   wxT("Help"));
  toolBar->AddTool(wxID_ABOUT, wxT("About ..."), *BtnAbout, wxNullBitmap,
                   wxITEM_NORMAL, wxT("About ..."));
  toolBar->AddSeparator();
  toolBar->AddTool(wxID_EXIT, wxT("Quit"), *BtnExit, wxNullBitmap,
                   wxITEM_NORMAL, wxT("Quit"));
  toolBar->Realize();
  SetToolBar(toolBar);

//
// setting up the toolbar initial state
//
  toolBar->EnableTool(ID_Disconnect, false);
  toolBar->EnableTool(ID_MemoryDbClock, false);
  toolBar->EnableTool(ID_MemoryDbSave, false);
  toolBar->EnableTool(ID_Vacuum, false);
  toolBar->EnableTool(ID_SqlScript, false);
  toolBar->EnableTool(ID_LoadShp, false);
  toolBar->EnableTool(ID_VirtualShp, false);
  toolBar->EnableTool(ID_LoadTxt, false);
  toolBar->EnableTool(ID_VirtualTxt, false);
  toolBar->EnableTool(ID_Network, false);
  toolBar->EnableTool(ID_Exif, false);
  toolBar->EnableTool(ID_Srids, false);

// updating the status bar
  UpdateStatusBar();

//
// setting up event handlers for menu and toolbar
//
  Connect(ID_Connect, wxEVT_COMMAND_MENU_SELECTED,
          (wxObjectEventFunction) & MyFrame::OnConnect);
  Connect(ID_CreateNew, wxEVT_COMMAND_MENU_SELECTED,
          (wxObjectEventFunction) & MyFrame::OnCreateNew);
  Connect(ID_Disconnect, wxEVT_COMMAND_MENU_SELECTED,
          (wxObjectEventFunction) & MyFrame::OnDisconnect);
  Connect(ID_MemoryDbLoad, wxEVT_COMMAND_MENU_SELECTED,
          (wxObjectEventFunction) & MyFrame::OnMemoryDbLoad);
  Connect(ID_MemoryDbNew, wxEVT_COMMAND_MENU_SELECTED,
          (wxObjectEventFunction) & MyFrame::OnMemoryDbNew);
  Connect(ID_MemoryDbClock, wxEVT_COMMAND_MENU_SELECTED,
          (wxObjectEventFunction) & MyFrame::OnMemoryDbClock);
  Connect(ID_MemoryDbSave, wxEVT_COMMAND_MENU_SELECTED,
          (wxObjectEventFunction) & MyFrame::OnMemoryDbSave);
  Connect(ID_Vacuum, wxEVT_COMMAND_MENU_SELECTED,
          (wxObjectEventFunction) & MyFrame::OnVacuum);
  Connect(ID_SqlScript, wxEVT_COMMAND_MENU_SELECTED,
          (wxObjectEventFunction) & MyFrame::OnSqlScript);
  Connect(ID_LoadShp, wxEVT_COMMAND_MENU_SELECTED,
          (wxObjectEventFunction) & MyFrame::OnLoadShp);
  Connect(ID_VirtualShp, wxEVT_COMMAND_MENU_SELECTED,
          (wxObjectEventFunction) & MyFrame::OnVirtualShp);
  Connect(ID_LoadTxt, wxEVT_COMMAND_MENU_SELECTED,
          (wxObjectEventFunction) & MyFrame::OnLoadTxt);
  Connect(ID_VirtualTxt, wxEVT_COMMAND_MENU_SELECTED,
          (wxObjectEventFunction) & MyFrame::OnVirtualTxt);
  Connect(ID_Network, wxEVT_COMMAND_MENU_SELECTED,
          (wxObjectEventFunction) & MyFrame::OnNetwork);
  Connect(ID_Exif, wxEVT_COMMAND_MENU_SELECTED,
          (wxObjectEventFunction) & MyFrame::OnImportExifPhotos);
  Connect(ID_Srids, wxEVT_COMMAND_MENU_SELECTED,
          (wxObjectEventFunction) & MyFrame::OnSrids);
  Connect(ID_Charset, wxEVT_COMMAND_MENU_SELECTED,
          (wxObjectEventFunction) & MyFrame::OnCharset);
  Connect(ID_Help, wxEVT_COMMAND_MENU_SELECTED,
          (wxObjectEventFunction) & MyFrame::OnHelp);
  Connect(wxID_ABOUT, wxEVT_COMMAND_MENU_SELECTED,
          (wxObjectEventFunction) & MyFrame::OnAbout);
  Connect(wxID_EXIT, wxEVT_COMMAND_MENU_SELECTED,
          (wxObjectEventFunction) & MyFrame::OnQuit);
  Connect(wxID_ANY, wxEVT_MOTION, wxMouseEventHandler(MyFrame::OnMouseMove),
          NULL, this);

//
// setting up event handlers for mouse
//
  TableTree->Connect(wxID_ANY, wxEVT_MOTION,
                     wxMouseEventHandler(MyFrame::OnMouseMove), NULL, this);
  GetMenuBar()->Connect(wxID_ANY, wxEVT_MOTION,
                        wxMouseEventHandler(MyFrame::OnMouseMove), NULL, this);
  GetStatusBar()->Connect(wxID_ANY, wxEVT_MOTION,
                          wxMouseEventHandler(MyFrame::OnMouseMove), NULL,
                          this);
//
// setting up a Timer event handler for AutoSave
//
  Connect(ID_AUTO_SAVE_TIMER, wxEVT_TIMER,
          wxTimerEventHandler(MyFrame::OnTimerAutoSave), NULL, this);
}

MyFrame::~MyFrame()
{
//
// main GUI frame destructor
//
  if (TimerAutoSave)
    {
      TimerAutoSave->Stop();
      delete TimerAutoSave;
    }
  LastDitchMemoryDbSave();
  ConfigLayout = Manager.SavePerspective();
  GetPosition(&ConfigPaneX, &ConfigPaneY);
  GetSize(&ConfigPaneWidth, &ConfigPaneHeight);
  SaveConfig();
  Manager.UnInit();
  if (SqliteHandle)
    sqlite3_close(SqliteHandle);
  if (BtnConnect != NULL)
    delete BtnConnect;
  if (BtnCreateNew != NULL)
    delete BtnCreateNew;
  if (BtnDisconnect != NULL)
    delete BtnDisconnect;
  if (BtnMemDbLoad != NULL)
    delete BtnMemDbLoad;
  if (BtnMemDbNew != NULL)
    delete BtnMemDbNew;
  if (BtnMemDbClock != NULL)
    delete BtnMemDbClock;
  if (BtnMemDbSave != NULL)
    delete BtnMemDbSave;
  if (BtnVacuum != NULL)
    delete BtnVacuum;
  if (BtnSqlScript != NULL)
    delete BtnSqlScript;
  if (BtnLoadShp != NULL)
    delete BtnLoadShp;
  if (BtnVirtualShp != NULL)
    delete BtnVirtualShp;
  if (BtnLoadTxt != NULL)
    delete BtnLoadTxt;
  if (BtnVirtualTxt != NULL)
    delete BtnVirtualTxt;
  if (BtnNetwork != NULL)
    delete BtnNetwork;
  if (BtnExif != NULL)
    delete BtnExif;
  if (BtnSrids != NULL)
    delete BtnSrids;
  if (BtnHelp != NULL)
    delete BtnHelp;
  if (BtnAbout != NULL)
    delete BtnAbout;
  if (BtnExit != NULL)
    delete BtnExit;
  if (Charsets)
    delete[]Charsets;
  if (CharsetsNames)
    delete[]CharsetsNames;
}

void MyFrame::SaveConfig()
{
//
// saves layout configuration
//

  wxConfig *config = new wxConfig(wxT("SpatialiteGui"));
  config->Write(wxT("Layout"), ConfigLayout);
  config->Write(wxT("PaneX"), ConfigPaneX);
  config->Write(wxT("PaneY"), ConfigPaneY);
  config->Write(wxT("PaneWidth"), ConfigPaneWidth);
  config->Write(wxT("PaneHeight"), ConfigPaneHeight);
  config->Write(wxT("SqlitePath"), SqlitePath);
  config->Write(wxT("LastDirectory"), LastDirectory);
  delete config;
}

void MyFrame::LoadConfig()
{
//
// loads layout configuration
//
  ConfigLayout = wxT("");
  ConfigDbPath = wxT("");
  ConfigDir = wxT("");
  wxConfig *config = new wxConfig(wxT("SpatialiteGui"));
  config->Read(wxT("Layout"), &ConfigLayout);
  config->Read(wxT("PaneX"), &ConfigPaneX, -1);
  config->Read(wxT("PaneY"), &ConfigPaneY, -1);
  config->Read(wxT("PaneWidth"), &ConfigPaneWidth, -1);
  config->Read(wxT("PaneHeight"), &ConfigPaneHeight, -1);
  config->Read(wxT("SqlitePath"), &ConfigDbPath);
  config->Read(wxT("LastDirectory"), &ConfigDir);
  delete config;
  Hide();
  if (ConfigLayout.Len() > 0)
    Manager.LoadPerspective(ConfigLayout, true);
  if (ConfigPaneX >= 0 && ConfigPaneY >= 0 && ConfigPaneWidth > 0
      && ConfigPaneHeight > 0)
    SetSize(ConfigPaneX, ConfigPaneY, ConfigPaneWidth, ConfigPaneHeight);
  if (ConfigDir.Len() > 0)
    LastDirectory = ConfigDir;
  if (ConfigDbPath.Len() > 0)
    {
      SqlitePath = ConfigDbPath;
      if (OpenDB() == false)
        SqlitePath = wxT("");
      else
        {
          bool metadata = CheckMetadata();
          wxMenuBar *menuBar = GetMenuBar();
          menuBar->Enable(ID_Connect, false);
          menuBar->Enable(ID_MemoryDbLoad, false);
          menuBar->Enable(ID_MemoryDbNew, false);
          if (MemoryDatabase == true)
            {
              menuBar->Enable(ID_MemoryDbSave, true);
              menuBar->Enable(ID_MemoryDbClock, true);
          } else
            {
              menuBar->Enable(ID_MemoryDbSave, false);
              menuBar->Enable(ID_MemoryDbClock, false);
            }
          menuBar->Enable(ID_CreateNew, false);
          menuBar->Enable(ID_Disconnect, true);
          menuBar->Enable(ID_Vacuum, true);
          menuBar->Enable(ID_SqlScript, true);
          menuBar->Enable(ID_LoadShp, true);
          menuBar->Enable(ID_VirtualShp, true);
          menuBar->Enable(ID_LoadTxt, true);
          menuBar->Enable(ID_VirtualTxt, true);
          menuBar->Enable(ID_Network, true);
          menuBar->Enable(ID_Exif, true);
          menuBar->Enable(ID_Srids, metadata);
          wxToolBar *toolBar = GetToolBar();
          toolBar->EnableTool(ID_Connect, false);
          toolBar->EnableTool(ID_MemoryDbLoad, false);
          toolBar->EnableTool(ID_MemoryDbNew, false);
          if (MemoryDatabase == true)
            {
              toolBar->EnableTool(ID_MemoryDbSave, true);
              toolBar->EnableTool(ID_MemoryDbClock, true);
          } else
            {
              toolBar->EnableTool(ID_MemoryDbSave, false);
              toolBar->EnableTool(ID_MemoryDbClock, false);
            }
          toolBar->EnableTool(ID_CreateNew, false);
          toolBar->EnableTool(ID_Disconnect, true);
          toolBar->EnableTool(ID_Vacuum, true);
          toolBar->EnableTool(ID_SqlScript, true);
          toolBar->EnableTool(ID_LoadShp, true);
          toolBar->EnableTool(ID_VirtualShp, true);
          toolBar->EnableTool(ID_LoadTxt, true);
          toolBar->EnableTool(ID_VirtualTxt, true);
          toolBar->EnableTool(ID_Network, true);
          toolBar->EnableTool(ID_Exif, true);
          toolBar->EnableTool(ID_Srids, metadata);
          UpdateStatusBar();
        }
    }
  Show();
  if (AutoFDOmsg.Len() > 0)
    {
      wxMessageBox(AutoFDOmsg, wxT("spatialite-gui"), wxOK | wxICON_INFORMATION,
                   this);
      AutoFDOmsg = wxT("");
    }
}

void MyFrame::OnQuit(wxCommandEvent & WXUNUSED(event))
{
//
// EXIT - event handler
//
  CloseDB();
  Close(true);
}

void MyFrame::OnHelp(wxCommandEvent & WXUNUSED(event))
{
//
// HELP - event handler
//
  if (HelpPane == true)
    return;
  HelpDialog *help = new HelpDialog(this);
  help->Show();
}

void MyFrame::OnAbout(wxCommandEvent & WXUNUSED(event))
{
//
// ABOUT dialog - event handler
//
  char ver[128];
  wxAboutDialogInfo dlg;
  dlg.SetIcon(wxIcon(icon_info_xpm));
  dlg.SetName(wxT("spatialite-gui"));
  dlg.SetVersion(wxT("v1.2"));
  wxString str = wxT("a GUI-tool for SQLite / SpatiaLite\n\n");
  sprintf(ver, "%d.%d.%d", wxMAJOR_VERSION, wxMINOR_VERSION, wxRELEASE_NUMBER);
  str += wxT("wxWidgets version ") + wxString::FromUTF8(ver) + wxT("\n");
  strcpy(ver, spatialite_version());
  str += wxT("SpatiaLite version ") + wxString::FromUTF8(ver) + wxT("\n");
  strcpy(ver, sqlite3_libversion());
  str += wxT("SQLite version ") + wxString::FromUTF8(ver) + wxT("\n");
  strcpy(ver, GEOSversion());
  str += wxT("GEOS version ") + wxString::FromUTF8(ver) + wxT("\n");
  strcpy(ver, pj_get_release());
  str += wxT("PROJ.4 version ") + wxString::FromUTF8(ver) + wxT("\n\n");
  str += wxT("SQLite's extension 'SpatiaLite' enabled\n");
  str += wxT("SQLite's extension 'VirtualShape' enabled\n");
  str += wxT("SQLite's extension 'VirtualText' enabled\n");
  str += wxT("SQLite's extension 'VirtualNetwork' enabled\n");
  str += wxT("SQLite's extension 'RTree' enabled\n");
  str += wxT("SQLite's extension 'MbrCache' enabled\n");
  str += wxT("SQLite's extension 'VirtualFDO' enabled\n\n");
  dlg.SetDescription(str);
  dlg.SetCopyright(wxT("by Alessandro Furieri - 2008"));
  dlg.SetWebSite(wxT("http://www.gaia-gis.it"));
  wxString license =
    wxT("This program is free software; you can redistribute it\n");
  license +=
    wxT("and/or modify it under the terms of the GNU General Public License\n");
  license += wxT("(GPL) as published by the Free Software Foundation\n\n");
  license +=
    wxT
    ("A copy of the GPL can be found at\nhttp://www.gnu.org/licenses/gpl.txt");
  dlg.SetLicense(license);
  ::wxAboutBox(dlg);
}

void MyFrame::OnMouseMove(wxMouseEvent & event)
{
//
// MOUSE motion - event handler
//
  UpdateStatusBar();
}

void MyFrame::UpdateStatusBar()
{
//
// updating the status bar
//
  if (GetStatusBar() == NULL)
    return;
  if (MemoryDatabase == true)
    {
      GetStatusBar()->SetStatusText(wxT("Current SQLite DB: MEMORY-DB"), 0);
      QueryView->ShowControls();
  } else
    {
      if (SqlitePath.Len() < 1)
        GetStatusBar()->SetStatusText(wxT("not connected"), 0);
      else
        GetStatusBar()->SetStatusText(wxT("Current SQLite DB: ") + SqlitePath,
                                      0);
      if (SqlitePath.Len() < 1)
        {
          QueryView->HideControls();
          RsView->HideControls();
      } else
        QueryView->ShowControls();
    }
}

void MyFrame::OnConnect(wxCommandEvent & WXUNUSED(event))
{
//
// connecting to an existent SQLite DB
//
  int ret;
  wxString lastDir;
  wxFileDialog *fileDialog = new wxFileDialog(this, wxT("DB connection"),
                                              wxT(""), wxT("db.sqlite"),
                                              wxT
                                              ("SQLite DB (*.sqlite)|*.sqlite|All files (*.*)|*.*"),
                                              wxFD_OPEN | wxFD_FILE_MUST_EXIST,
                                              wxDefaultPosition,
                                              wxDefaultSize,
                                              wxT("filedlg"));
  lastDir = GetLastDirectory();
  if (lastDir.Len() >= 1)
    fileDialog->SetDirectory(lastDir);
  ret = fileDialog->ShowModal();
  if (ret == wxID_OK)
    {
      SqlitePath = fileDialog->GetPath();
      if (OpenDB() == false)
        SqlitePath = wxT("");
      else
        {
          wxFileName file(fileDialog->GetPath());
          lastDir = file.GetPath();
          SetLastDirectory(lastDir);
          bool metadata = CheckMetadata();
          wxMenuBar *menuBar = GetMenuBar();
          menuBar->Enable(ID_Connect, false);
          menuBar->Enable(ID_CreateNew, false);
          menuBar->Enable(ID_Disconnect, true);
          menuBar->Enable(ID_MemoryDbLoad, false);
          menuBar->Enable(ID_MemoryDbNew, false);
          if (MemoryDatabase == true)
            {
              menuBar->Enable(ID_MemoryDbSave, true);
              menuBar->Enable(ID_MemoryDbClock, true);
          } else
            {
              menuBar->Enable(ID_MemoryDbSave, false);
              menuBar->Enable(ID_MemoryDbClock, false);
            }
          menuBar->Enable(ID_Vacuum, true);
          menuBar->Enable(ID_SqlScript, true);
          menuBar->Enable(ID_LoadShp, true);
          menuBar->Enable(ID_VirtualShp, true);
          menuBar->Enable(ID_LoadTxt, true);
          menuBar->Enable(ID_VirtualTxt, true);
          menuBar->Enable(ID_Network, true);
          menuBar->Enable(ID_Exif, true);
          menuBar->Enable(ID_Srids, metadata);
          wxToolBar *toolBar = GetToolBar();
          toolBar->EnableTool(ID_Connect, false);
          toolBar->EnableTool(ID_CreateNew, false);
          toolBar->EnableTool(ID_Disconnect, true);
          toolBar->EnableTool(ID_MemoryDbLoad, false);
          toolBar->EnableTool(ID_MemoryDbNew, false);
          if (MemoryDatabase == true)
            {
              toolBar->EnableTool(ID_MemoryDbSave, true);
              toolBar->EnableTool(ID_MemoryDbClock, true);
          } else
            {
              toolBar->EnableTool(ID_MemoryDbSave, false);
              toolBar->EnableTool(ID_MemoryDbClock, false);
            }
          toolBar->EnableTool(ID_Vacuum, true);
          toolBar->EnableTool(ID_SqlScript, true);
          toolBar->EnableTool(ID_LoadShp, true);
          toolBar->EnableTool(ID_VirtualShp, true);
          toolBar->EnableTool(ID_LoadTxt, true);
          toolBar->EnableTool(ID_VirtualTxt, true);
          toolBar->EnableTool(ID_Network, true);
          toolBar->EnableTool(ID_Exif, true);
          toolBar->EnableTool(ID_Srids, metadata);
          UpdateStatusBar();
        }
    }
  if (AutoFDOmsg.Len() > 0)
    {
      wxMessageBox(AutoFDOmsg, wxT("spatialite-gui"), wxOK | wxICON_INFORMATION,
                   this);
      AutoFDOmsg = wxT("");
    }
}

void MyFrame::OnDisconnect(wxCommandEvent & WXUNUSED(event))
{
//
// disconnecting current SQLite DB
//
  if (TimerAutoSave)
    {
      TimerAutoSave->Stop();
      delete TimerAutoSave;
      TimerAutoSave = NULL;
    }
  CloseDB();
  ExternalSqlitePath = wxT("");
  wxMenuBar *menuBar = GetMenuBar();
  menuBar->Enable(ID_Connect, true);
  menuBar->Enable(ID_CreateNew, true);
  menuBar->Enable(ID_Disconnect, false);
  menuBar->Enable(ID_MemoryDbLoad, true);
  menuBar->Enable(ID_MemoryDbNew, true);
  menuBar->Enable(ID_MemoryDbSave, false);
  menuBar->Enable(ID_MemoryDbClock, false);
  menuBar->Enable(ID_Vacuum, false);
  menuBar->Enable(ID_SqlScript, false);
  menuBar->Enable(ID_LoadShp, false);
  menuBar->Enable(ID_VirtualShp, false);
  menuBar->Enable(ID_LoadTxt, false);
  menuBar->Enable(ID_VirtualTxt, false);
  menuBar->Enable(ID_Network, false);
  menuBar->Enable(ID_Exif, false);
  menuBar->Enable(ID_Srids, false);
  wxToolBar *toolBar = GetToolBar();
  toolBar->EnableTool(ID_Connect, true);
  toolBar->EnableTool(ID_CreateNew, true);
  toolBar->EnableTool(ID_Disconnect, false);
  toolBar->EnableTool(ID_MemoryDbLoad, true);
  toolBar->EnableTool(ID_MemoryDbNew, true);
  toolBar->EnableTool(ID_MemoryDbSave, false);
  toolBar->EnableTool(ID_MemoryDbClock, false);
  toolBar->EnableTool(ID_Vacuum, false);
  toolBar->EnableTool(ID_SqlScript, false);
  toolBar->EnableTool(ID_LoadShp, false);
  toolBar->EnableTool(ID_VirtualShp, false);
  toolBar->EnableTool(ID_LoadTxt, false);
  toolBar->EnableTool(ID_VirtualTxt, false);
  toolBar->EnableTool(ID_Network, false);
  toolBar->EnableTool(ID_Exif, false);
  toolBar->EnableTool(ID_Srids, false);
  UpdateStatusBar();
}

void MyFrame::OnCreateNew(wxCommandEvent & WXUNUSED(event))
{
//
// creating a new, empty SQLite DB
//
  int retdlg;
  int ret;
  wxString lastDir;
  wxFileDialog *fileDialog =
    new wxFileDialog(this, wxT("Creating a new, empty DB"),
                     wxT(""), wxT("db.sqlite"),
                     wxT("SQLite DB (*.sqlite)|*.sqlite|All files (*.*)|*.*"),
                     wxFD_SAVE | wxFD_OVERWRITE_PROMPT, wxDefaultPosition,
                     wxDefaultSize,
                     wxT("filedlg"));
  lastDir = GetLastDirectory();
  if (lastDir.Len() >= 1)
    fileDialog->SetDirectory(lastDir);
  retdlg = fileDialog->ShowModal();
  if (retdlg == wxID_OK)
    {
      // creating the new DB
      SqlitePath = fileDialog->GetPath();
      ret = CreateDB();
      if (ret == false)
        goto error;
      wxFileName file(fileDialog->GetPath());
      lastDir = file.GetPath();
      SetLastDirectory(lastDir);
      wxMenuBar *menuBar = GetMenuBar();
      menuBar->Enable(ID_Connect, false);
      menuBar->Enable(ID_CreateNew, false);
      menuBar->Enable(ID_Disconnect, true);
      menuBar->Enable(ID_MemoryDbLoad, false);
      menuBar->Enable(ID_MemoryDbNew, false);
      menuBar->Enable(ID_MemoryDbSave, false);
      menuBar->Enable(ID_MemoryDbClock, false);
      menuBar->Enable(ID_Vacuum, true);
      menuBar->Enable(ID_SqlScript, true);
      menuBar->Enable(ID_LoadShp, true);
      menuBar->Enable(ID_VirtualShp, true);
      menuBar->Enable(ID_LoadTxt, true);
      menuBar->Enable(ID_VirtualTxt, true);
      menuBar->Enable(ID_Network, true);
      menuBar->Enable(ID_Exif, true);
      menuBar->Enable(ID_Srids, false);
      wxToolBar *toolBar = GetToolBar();
      toolBar->EnableTool(ID_Connect, false);
      toolBar->EnableTool(ID_CreateNew, false);
      toolBar->EnableTool(ID_Disconnect, true);
      toolBar->EnableTool(ID_MemoryDbLoad, false);
      toolBar->EnableTool(ID_MemoryDbNew, false);
      toolBar->EnableTool(ID_MemoryDbSave, false);
      toolBar->EnableTool(ID_MemoryDbClock, false);
      toolBar->EnableTool(ID_Vacuum, true);
      toolBar->EnableTool(ID_SqlScript, true);
      toolBar->EnableTool(ID_LoadShp, true);
      toolBar->EnableTool(ID_VirtualShp, true);
      toolBar->EnableTool(ID_LoadTxt, true);
      toolBar->EnableTool(ID_VirtualTxt, true);
      toolBar->EnableTool(ID_Network, true);
      toolBar->EnableTool(ID_Exif, true);
      toolBar->EnableTool(ID_Srids, false);
      UpdateStatusBar();
      return;
  } else
    return;
error:
  unlink(SqlitePath.ToUTF8());
  wxString msg = wxT("An error occurred\nno DB was created");
  wxMessageBox(msg, wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
  return;
}

void MyFrame::OnMemoryDbLoad(wxCommandEvent & WXUNUSED(event))
{
//
// loading an external DB into the MEMORY-DB
//
  sqlite3 *extSqlite = NULL;
  sqlite3_backup *backup;
  int retdlg;
  int ret;
  wxString lastDir;
  char path[1024];
  wxString error;
  wxFileDialog *fileDialog =
    new wxFileDialog(this, wxT("Loading an existing DB into the MEMORY-DB"),
                     wxT(""), wxT("db.sqlite"),
                     wxT("SQLite DB (*.sqlite)|*.sqlite|All files (*.*)|*.*"),
                     wxFD_OPEN | wxFD_FILE_MUST_EXIST,
                     wxDefaultPosition,
                     wxDefaultSize,
                     wxT("filedlg"));
  lastDir = GetLastDirectory();
  if (lastDir.Len() >= 1)
    fileDialog->SetDirectory(lastDir);
  retdlg = fileDialog->ShowModal();
  if (retdlg == wxID_OK)
    {
      // opening the external DB
      ExternalSqlitePath = fileDialog->GetPath();
      strcpy(path, ExternalSqlitePath.ToUTF8());
      ret = sqlite3_open_v2(path, &extSqlite, SQLITE_OPEN_READWRITE, NULL);
      if (ret)
        {
          // an error occurred
          wxString errCause = wxString::FromUTF8(sqlite3_errmsg(SqliteHandle));
          error = wxT("Failure while connecting to DB\n\n");
          error += errCause;
          error += wxT("\n");
          goto stop;
        }
      ret =
        sqlite3_open_v2(":memory:", &SqliteHandle,
                        SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL);
      if (ret)
        {
          // an error occurred
          wxString errCause = wxString::FromUTF8(sqlite3_errmsg(SqliteHandle));
          error = wxT("MEMORY-DB: an error occurred \n\n");
          error += errCause;
          error += +wxT("\n");
          goto stop;
        }
      wxFileName file(fileDialog->GetPath());
      lastDir = file.GetPath();
      SetLastDirectory(lastDir);
      backup = sqlite3_backup_init(SqliteHandle, "main", extSqlite, "main");
      if (!backup)
        goto stop;
      while (1)
        {
          ret = sqlite3_backup_step(backup, 1024);
          if (ret == SQLITE_DONE)
            break;
        }
      ret = sqlite3_backup_finish(backup);
      sqlite3_close(extSqlite);
      MemoryDatabase = true;
      AutoSaveInterval = 120;
      AutoFDOStart();
      InitTableTree();
      bool metadata = CheckMetadata();
      wxMenuBar *menuBar = GetMenuBar();
      menuBar->Enable(ID_Connect, false);
      menuBar->Enable(ID_CreateNew, false);
      menuBar->Enable(ID_Disconnect, true);
      menuBar->Enable(ID_MemoryDbLoad, false);
      menuBar->Enable(ID_MemoryDbNew, false);
      if (MemoryDatabase == true)
        {
          menuBar->Enable(ID_MemoryDbSave, true);
          menuBar->Enable(ID_MemoryDbClock, true);
      } else
        {
          menuBar->Enable(ID_MemoryDbSave, false);
          menuBar->Enable(ID_MemoryDbClock, false);
        }
      menuBar->Enable(ID_Vacuum, true);
      menuBar->Enable(ID_SqlScript, true);
      menuBar->Enable(ID_LoadShp, true);
      menuBar->Enable(ID_VirtualShp, true);
      menuBar->Enable(ID_LoadTxt, true);
      menuBar->Enable(ID_VirtualTxt, true);
      menuBar->Enable(ID_Network, true);
      menuBar->Enable(ID_Exif, true);
      menuBar->Enable(ID_Srids, metadata);
      wxToolBar *toolBar = GetToolBar();
      toolBar->EnableTool(ID_Connect, false);
      toolBar->EnableTool(ID_CreateNew, false);
      toolBar->EnableTool(ID_Disconnect, true);
      toolBar->EnableTool(ID_MemoryDbLoad, false);
      toolBar->EnableTool(ID_MemoryDbNew, false);
      if (MemoryDatabase == true)
        {
          toolBar->EnableTool(ID_MemoryDbSave, true);
          toolBar->EnableTool(ID_MemoryDbClock, true);
      } else
        {
          toolBar->EnableTool(ID_MemoryDbSave, false);
          toolBar->EnableTool(ID_MemoryDbClock, false);
        }
      toolBar->EnableTool(ID_Vacuum, true);
      toolBar->EnableTool(ID_SqlScript, true);
      toolBar->EnableTool(ID_LoadShp, true);
      toolBar->EnableTool(ID_VirtualShp, true);
      toolBar->EnableTool(ID_LoadTxt, true);
      toolBar->EnableTool(ID_VirtualTxt, true);
      toolBar->EnableTool(ID_Network, true);
      toolBar->EnableTool(ID_Exif, true);
      toolBar->EnableTool(ID_Srids, metadata);
      UpdateStatusBar();
      if (AutoSaveInterval <= 0)
        {
          if (TimerAutoSave)
            {
              TimerAutoSave->Stop();
              delete TimerAutoSave;
              TimerAutoSave = NULL;
            }
      } else
        {
          //
          // starting the AutoSave timer
          //
          if (!TimerAutoSave)
            TimerAutoSave = new wxTimer(this, ID_AUTO_SAVE_TIMER);
          else
            TimerAutoSave->Stop();
          LastTotalChanges = 0;
          TimerAutoSave->Start(AutoSaveInterval * 1000, wxTIMER_ONE_SHOT);
        }
    }
  if (AutoFDOmsg.Len() > 0)
    {
      wxMessageBox(AutoFDOmsg, wxT("spatialite-gui"), wxOK | wxICON_INFORMATION,
                   this);
      AutoFDOmsg = wxT("");
    }
  return;
stop:
  MemoryDatabase = false;
  if (SqliteHandle)
    sqlite3_close(SqliteHandle);
  if (extSqlite)
    sqlite3_close(extSqlite);
  wxString msg = wxT("MEMORY-DB wasn't loaded\n\n");
  msg += error;
  wxMessageBox(msg, wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
  SqliteHandle = NULL;
}

void MyFrame::OnMemoryDbNew(wxCommandEvent & WXUNUSED(event))
{
//
//creating a new MEMORY-DB
//
  int ret;
  wxToolBar *toolBar;
  wxMenuBar *menuBar;
  bool metadata;
  MemoryDatabase = true;
  AutoSaveInterval = 120;
  ExternalSqlitePath = wxT("");
// creating the new MEMORY-DB
  ret = CreateDB();
  if (ret == false)
    goto error;
  metadata = CheckMetadata();
  menuBar = GetMenuBar();
  menuBar->Enable(ID_Connect, false);
  menuBar->Enable(ID_CreateNew, false);
  menuBar->Enable(ID_Disconnect, true);
  menuBar->Enable(ID_MemoryDbLoad, false);
  menuBar->Enable(ID_MemoryDbNew, false);
  menuBar->Enable(ID_MemoryDbSave, true);
  menuBar->Enable(ID_MemoryDbClock, true);
  menuBar->Enable(ID_Vacuum, true);
  menuBar->Enable(ID_SqlScript, true);
  menuBar->Enable(ID_LoadShp, true);
  menuBar->Enable(ID_VirtualShp, true);
  menuBar->Enable(ID_LoadTxt, true);
  menuBar->Enable(ID_VirtualTxt, true);
  menuBar->Enable(ID_Network, true);
  menuBar->Enable(ID_Exif, true);
  menuBar->Enable(ID_Srids, metadata);
  toolBar = GetToolBar();
  toolBar->EnableTool(ID_Connect, false);
  toolBar->EnableTool(ID_CreateNew, false);
  toolBar->EnableTool(ID_Disconnect, true);
  toolBar->EnableTool(ID_MemoryDbLoad, false);
  toolBar->EnableTool(ID_MemoryDbNew, false);
  toolBar->EnableTool(ID_MemoryDbSave, true);
  toolBar->EnableTool(ID_MemoryDbClock, true);
  toolBar->EnableTool(ID_Vacuum, true);
  toolBar->EnableTool(ID_SqlScript, true);
  toolBar->EnableTool(ID_LoadShp, true);
  toolBar->EnableTool(ID_VirtualShp, true);
  toolBar->EnableTool(ID_LoadTxt, true);
  toolBar->EnableTool(ID_VirtualTxt, true);
  toolBar->EnableTool(ID_Network, true);
  toolBar->EnableTool(ID_Exif, true);
  toolBar->EnableTool(ID_Srids, metadata);
  UpdateStatusBar();
  if (AutoSaveInterval <= 0)
    {
      if (TimerAutoSave)
        {
          TimerAutoSave->Stop();
          delete TimerAutoSave;
          TimerAutoSave = NULL;
        }
  } else
    {
      //
      // starting the AutoSave timer
      //
      if (!TimerAutoSave)
        TimerAutoSave = new wxTimer(this, ID_AUTO_SAVE_TIMER);
      else
        TimerAutoSave->Stop();
      LastTotalChanges = 0;
      TimerAutoSave->Start(AutoSaveInterval * 1000, wxTIMER_ONE_SHOT);
    }
  return;
error:
  wxString msg = wxT("An error occurred\nno MEMORY-DB was created");
  wxMessageBox(msg, wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
  return;
}

bool MyFrame::MemoryDbSave()
{
//
// trying to export the MEMORY-DB into an external DB
//
  sqlite3 *extSqlite = NULL;
  sqlite3_backup *backup;
  char path[1024];
  char bak_path[1024];
  int ret;
  wxString error;
  if (ExternalSqlitePath.Len() == 0)
    return false;
  ::wxBeginBusyCursor();
  strcpy(path, ExternalSqlitePath.ToUTF8());
  strcpy(bak_path, path);
  strcat(bak_path, ".bak");
  unlink(bak_path);
  rename(path, bak_path);
  ret =
    sqlite3_open_v2(path, &extSqlite,
                    SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL);
  if (ret)
    {
      // an error occurred
      wxString errCause = wxString::FromUTF8(sqlite3_errmsg(extSqlite));
      error = wxT("An error occurred\n\n");
      error += errCause;
      error += +wxT("\n");
      error += ExternalSqlitePath;
      goto stop;
    }
  backup = sqlite3_backup_init(extSqlite, "main", SqliteHandle, "main");
  if (!backup)
    goto stop;
  while (1)
    {
      ret = sqlite3_backup_step(backup, 1024);
      if (ret == SQLITE_DONE)
        break;
    }
  ret = sqlite3_backup_finish(backup);
  sqlite3_close(extSqlite);
  unlink(bak_path);
  ::wxEndBusyCursor();
  LastTotalChanges = sqlite3_total_changes(SqliteHandle);
  return true;
stop:
  if (extSqlite)
    sqlite3_close(extSqlite);
  wxString msg = wxT("Backup failure: MEMORY-DB wasn't saved\n\n");
  msg += error;
  wxMessageBox(msg, wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
  ExternalSqlitePath = wxT("");
  ::wxEndBusyCursor();
  return false;
}

void MyFrame::OnMemoryDbSave(wxCommandEvent & WXUNUSED(event))
{
//
//  exporting the MEMORY-DB into an external DB 
//
  int retdlg;
  wxString lastDir;
  if (ExternalSqlitePath.Len() > 0)
    {
      if (MemoryDbSave() == true)
        {
          wxMessageBox(wxT("Ok, MEMORY-DB was succesfully saved"),
                       wxT("spatialite-gui"), wxOK | wxICON_INFORMATION, this);
          if (AutoSaveInterval <= 0)
            {
              if (TimerAutoSave)
                {
                  TimerAutoSave->Stop();
                  delete TimerAutoSave;
                  TimerAutoSave = NULL;
                }
          } else
            {
              //
              // restarting the AutoSave timer
              //
              if (!TimerAutoSave)
                TimerAutoSave = new wxTimer(this, ID_AUTO_SAVE_TIMER);
              else
                TimerAutoSave->Stop();
              TimerAutoSave->Start(AutoSaveInterval * 1000, wxTIMER_ONE_SHOT);
            }
          return;
        }
    }
  wxFileDialog *fileDialog = new wxFileDialog(this, wxT("Saving the MEMORY-DB"),
                                              wxT(""), wxT("db.sqlite"),
                                              wxT
                                              ("SQLite DB (*.sqlite)|*.sqlite|All files (*.*)|*.*"),
                                              wxFD_SAVE | wxFD_OVERWRITE_PROMPT,
                                              wxDefaultPosition,
                                              wxDefaultSize,
                                              wxT("filedlg"));
  lastDir = GetLastDirectory();
  if (lastDir.Len() >= 1)
    fileDialog->SetDirectory(lastDir);
  retdlg = fileDialog->ShowModal();
  if (retdlg == wxID_OK)
    {
      // exporting the external DB
      ExternalSqlitePath = fileDialog->GetPath();
      if (MemoryDbSave() == true)
        {
          wxMessageBox(wxT("Ok, MEMORY-DB was succesfully saved"),
                       wxT("spatialite-gui"), wxOK | wxICON_INFORMATION, this);
          wxFileName file(fileDialog->GetPath());
          lastDir = file.GetPath();
          SetLastDirectory(lastDir);
          if (AutoSaveInterval <= 0)
            {
              if (TimerAutoSave)
                {
                  TimerAutoSave->Stop();
                  delete TimerAutoSave;
                  TimerAutoSave = NULL;
                }
          } else
            {
              //
              // restarting the AutoSave timer
              //
              if (!TimerAutoSave)
                TimerAutoSave = new wxTimer(this, ID_AUTO_SAVE_TIMER);
              else
                TimerAutoSave->Stop();
              TimerAutoSave->Start(AutoSaveInterval * 1000, wxTIMER_ONE_SHOT);
            }
        }
    }
}

void MyFrame::OnMemoryDbClock(wxCommandEvent & WXUNUSED(event))
{
//
//  setting up AutoSave for MEMORY-DB 
//
  AutoSaveDialog dlg;
  dlg.Create(this, ExternalSqlitePath, AutoSaveInterval);
  int ret = dlg.ShowModal();
  if (ret == wxID_OK)
    {
      AutoSaveInterval = dlg.GetSeconds();
      if (AutoSaveInterval <= 0)
        {
          //
          // stopping the AutoSave timer
          //
          if (TimerAutoSave)
            {
              TimerAutoSave->Stop();
              delete TimerAutoSave;
              TimerAutoSave = NULL;
            }
      } else
        {
          //
          // restarting the AutoSave timer
          //
          if (!TimerAutoSave)
            TimerAutoSave = new wxTimer(this, ID_AUTO_SAVE_TIMER);
          else
            TimerAutoSave->Stop();
          TimerAutoSave->Start(AutoSaveInterval * 1000, wxTIMER_ONE_SHOT);
        }
    }
}

void MyFrame::OnVacuum(wxCommandEvent & WXUNUSED(event))
{
//
// performing a VACUUM in order to reorganize the current DB
//
  char *errMsg = NULL;
  ::wxBeginBusyCursor();
  int ret = sqlite3_exec(SqliteHandle, "ANALYZE; VACUUM;", NULL, NULL, &errMsg);
  if (ret != SQLITE_OK)
    {
      wxMessageBox(wxT("SQLite SQL error: ") + wxString::FromUTF8(errMsg),
                   wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
      sqlite3_free(errMsg);
  } else
    {
      wxMessageBox(wxT("Current DB was succesfully optimized"),
                   wxT("spatialite-gui"), wxOK | wxICON_INFORMATION, this);
    }
  ::wxEndBusyCursor();
}

char *MyFrame::ReadSqlLine(FILE * in, int *len, int *eof)
{
//
// reading an SQL script line
//
  int c;
  *eof = 0;
  int size = 4096;
  char *line = (char *) malloc(size);
  int off = 0;
  while ((c = getc(in)) != EOF)
    {
      // consuming input one chat at each time
      if (off == size)
        {
          // buffer overflow; reallocating a bigger one
          // presumably this is because there is some BLOB, so we'll grow by 1MB at each time
          size += 1024 * 1024;
          line = (char *) realloc(line, size);
        }
      *(line + off) = c;
      off++;
      if (c == '\n')
        {
          // end of line marker
          *(line + off) = '\0';
          *len = off;
          return line;
        }
      if (c == ';')
        {
          // end of SQL statement marker
          *(line + off) = '\0';
          *len = off;
          return line;
        }
    }
// EOF reached
  *len = off;
  *eof = 1;
  return line;
}

void MyFrame::OnSqlScript(wxCommandEvent & WXUNUSED(event))
{
//
// executing an SQL Script
//
  int ret;
  wxString lastDir;
  wxString path;
  wxString charset;
  FILE *sql;
  char *line = NULL;
  char *statement = NULL;
  int stmt_len = 0;
  char *prev_stmt;
  int prev_len;
  int eof;
  int rowNo = 1;
  int stmt = 0;
  int len;
  wxString msg;
  char dummy[128];
  void *cvtCS = NULL;
  char *utf8stmt = NULL;
  int cvtErr;
  wxFileDialog *fileDialog = new wxFileDialog(this, wxT("SQL Script"),
                                              wxT(""),
                                              wxT("init_spatialite.sql"),
                                              wxT
                                              ("SQL script (*.sql)|*.sql|All files (*.*)|*.*"),
                                              wxFD_OPEN | wxFD_FILE_MUST_EXIST,
                                              wxDefaultPosition,
                                              wxDefaultSize,
                                              wxT("filedlg"));
  lastDir = GetLastDirectory();
  if (lastDir.Len() >= 1)
    fileDialog->SetDirectory(lastDir);
  ret = fileDialog->ShowModal();
  if (ret == wxID_OK)
    {
      path = fileDialog->GetPath();
      SqlScriptDialog dlg;
      dlg.Create(this, path, LocaleCharset);
      ret = dlg.ShowModal();
      if (ret == wxID_OK)
        charset = dlg.GetCharset();
      else
        return;
      // opening the SQL script
      sql = fopen(path.ToUTF8(), "r");
      if (sql == NULL)
        {
          wxMessageBox(wxT("can't open: ") + fileDialog->GetPath(),
                       wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
      } else
        {
          wxFileName file(fileDialog->GetPath());
          lastDir = file.GetPath();
          SetLastDirectory(lastDir);
          cvtCS = gaiaCreateUTF8Converter(charset.ToUTF8());
          if (!cvtCS)
            {
              msg = charset + wxT(": unsupported CharacterSet");
              wxMessageBox(msg, wxT("spatialite-gui"), wxOK | wxICON_WARNING,
                           this);
              goto stop;
            }
          ::wxBeginBusyCursor();
          while (1)
            {
              // reading the SQL script lines
              line = ReadSqlLine(sql, &len, &eof);
              if (len > 0)
                {
                  if (statement == NULL)
                    {
                      statement = line;
                      stmt_len = len;
                  } else
                    {
                      // appending line to SQL statement
                      prev_stmt = statement;
                      prev_len = stmt_len;
                      stmt_len = prev_len + len;
                      statement = (char *) malloc(stmt_len + 1);
                      memcpy(statement, prev_stmt, prev_len);
                      memcpy(statement + prev_len, line, len);
                      *(statement + stmt_len) = '\0';
                      free(prev_stmt);
                      free(line);
                      line = NULL;
                    }
              } else
                {
                  free(line);
                  line = NULL;
                }
              if (statement)
                {
                  if (sqlite3_complete(statement))
                    {
                      // executing the SQL statement
                      utf8stmt =
                        gaiaConvertToUTF8(cvtCS, statement, stmt_len, &cvtErr);
                      free(statement);
                      statement = NULL;
                      stmt_len = 0;
                      if (cvtErr || !utf8stmt)
                        {
                          Rollback();
                          msg =
                            wxT
                            ("SQL Script abnormal termination\nillegal character sequence");
                          msg +=
                            wxT("\n\nROLLBACK was automatically performed");
                          wxMessageBox(msg, wxT("spatialite-gui"),
                                       wxOK | wxICON_WARNING, this);
                          goto stop;
                        }
                      if (ExecuteSql(utf8stmt, rowNo) == false)
                        {
                          Rollback();
                          msg =
                            wxT
                            ("SQL Script abnormal termination\nan error occurred");
                          msg +=
                            wxT("\n\nROLLBACK was automatically performed");
                          wxMessageBox(msg, wxT("spatialite-gui"),
                                       wxOK | wxICON_WARNING, this);
                          goto stop;
                      } else
                        {
                          stmt++;
                          free(utf8stmt);
                          utf8stmt = NULL;
                        }
                    }
                }
              rowNo++;
              if (eof)
                break;
            }
          sprintf(dummy,
                  "SQL Script normal termination\n\n%d SQL statements where performed",
                  stmt);
          msg = wxString::FromUTF8(dummy);
          wxMessageBox(msg, wxT("spatialite-gui"), wxOK | wxICON_INFORMATION,
                       this);
        stop:
          if (cvtCS)
            gaiaFreeUTF8Converter(cvtCS);
          if (utf8stmt)
            free(utf8stmt);
          if (statement)
            free(statement);
          if (line)
            free(line);
          fclose(sql);
          ::wxEndBusyCursor();
        }
    }
}

void MyFrame::OnLoadShp(wxCommandEvent & WXUNUSED(event))
{
//
// loading a shapefile
//
  int ret;
  wxString table;
  wxString column = wxT("Geometry");
  wxString charset;
  int srid = -1;
  wxString path;
  wxString lastDir;
  wxFileDialog *fileDialog = new wxFileDialog(this, wxT("Load Shapefile"),
                                              wxT(""),
                                              wxT("shapefile.shp"),
                                              wxT
                                              ("Shapefile (*.shp)|*.shp|All files (*.*)|*.*"),
                                              wxFD_OPEN | wxFD_FILE_MUST_EXIST,
                                              wxDefaultPosition,
                                              wxDefaultSize,
                                              wxT("filedlg"));
  lastDir = GetLastDirectory();
  if (lastDir.Len() >= 1)
    fileDialog->SetDirectory(lastDir);
  ret = fileDialog->ShowModal();
  if (ret == wxID_OK)
    {
      wxFileName file(fileDialog->GetPath());
      lastDir = file.GetPath();
      table = file.GetName();
      path = file.GetPath();
      path += file.GetPathSeparator();
      path += file.GetName();
      LoadShpDialog dlg;
      dlg.Create(this, path, table, srid, column, LocaleCharset);
      ret = dlg.ShowModal();
      if (ret == wxID_OK)
        {
          SetLastDirectory(lastDir);
          table = dlg.GetTable();
          srid = dlg.GetSrid();
          column = dlg.GetColumn();
          charset = dlg.GetCharset();
          LoadShapefile(path, table, srid, column, charset);
        }
    }
}

void MyFrame::OnVirtualShp(wxCommandEvent & WXUNUSED(event))
{
//
// creating a VirtualShape
//
  int ret;
  wxString charset;
  int srid;
  char dummy[128];
  wxString sql;
  wxString path;
  wxString table;
  wxString lastDir;
  char *errMsg = NULL;
  sqlite3 *sqlite = GetSqlite();
  wxFileDialog *fileDialog = new wxFileDialog(this, wxT("VirtualShape"),
                                              wxT(""),
                                              wxT("shapefile.shp"),
                                              wxT
                                              ("Shapefile (*.shp)|*.shp|All files (*.*)|*.*"),
                                              wxFD_OPEN | wxFD_FILE_MUST_EXIST,
                                              wxDefaultPosition,
                                              wxDefaultSize,
                                              wxT("filedlg"));
  lastDir = GetLastDirectory();
  if (lastDir.Len() >= 1)
    fileDialog->SetDirectory(lastDir);
  ret = fileDialog->ShowModal();
  if (ret == wxID_OK)
    {
      path = fileDialog->GetPath();
      wxFileName file(path);
      table = file.GetName();
      VirtualShpDialog dlg;
      dlg.Create(this, path, table, LocaleCharset);
      ret = dlg.ShowModal();
      if (ret == wxID_OK)
        {
          table = dlg.GetTable();
          srid = dlg.GetSrid();
          charset = dlg.GetCharset();
      } else
        return;
      lastDir = file.GetPath();
      SetLastDirectory(lastDir);
      sql = wxT("CREATE VIRTUAL TABLE \"");
      sql += table;
      sql += wxT("\"\nUSING VirtualShape('");
      sql += file.GetPath();
      sql += file.GetPathSeparator();
      sql += file.GetName();
      sql += wxT("',\n'");
      sql += charset;
      sprintf(dummy, "', %d", srid);
      sql += wxString::FromUTF8(dummy);
      sql += wxT(")");
      ret = sqlite3_exec(sqlite, sql.ToUTF8(), NULL, NULL, &errMsg);
      if (ret != SQLITE_OK)
        {
          wxMessageBox(wxT("SQLite SQL error: ") + wxString::FromUTF8(errMsg),
                       wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
          sqlite3_free(errMsg);
          return;
        }
      wxMessageBox(wxT("Virtual Table \"") + table +
                   wxT("\" was successfully created"), wxT("spatialite-gui"),
                   wxOK | wxICON_INFORMATION, this);
      InitTableTree();
    }
}

void MyFrame::OnLoadTxt(wxCommandEvent & WXUNUSED(event))
{
//
// loading a CSV/TXT
//
  int ret;
  wxString charset;
  wxString sql;
  wxString path;
  wxString table;
  wxString lastDir;
  bool first_titles;
  bool decimal_comma;
  char separator;
  char text_separator;
  wxString filelist = wxT("TXT and CSV files (*.txt;*.csv)|*.txt;*.csv");
  filelist +=
    wxT("|Text file (*.txt)|*.txt|CSV file (*.csv)|*.csv|All files (*.*)|*.*");
  wxFileDialog *fileDialog = new wxFileDialog(this, wxT("Load CSV/TXT"),
                                              wxT(""),
                                              wxT("textfile.txt"),
                                              filelist,
                                              wxFD_OPEN | wxFD_FILE_MUST_EXIST,
                                              wxDefaultPosition,
                                              wxDefaultSize,
                                              wxT("filedlg"));
  lastDir = GetLastDirectory();
  if (lastDir.Len() >= 1)
    fileDialog->SetDirectory(lastDir);
  ret = fileDialog->ShowModal();
  if (ret == wxID_OK)
    {
      path = fileDialog->GetPath();
      wxFileName file(path);
      table = file.GetName();
      LoadTxtDialog dlg;
      dlg.Create(this, path, table, LocaleCharset);
      ret = dlg.ShowModal();
      if (ret == wxID_OK)
        {
          SetLastDirectory(lastDir);
          table = dlg.GetTable();
          charset = dlg.GetCharset();
          first_titles = dlg.IsFirstLineTitles();
          decimal_comma = dlg.IsDecimalPointComma();
          separator = dlg.GetSeparator();
          text_separator = dlg.GetTextSeparator();
          char decimal_separator = '.';
          if (decimal_comma == true)
            decimal_separator = ',';
          LoadText(path, table, charset, first_titles, decimal_separator,
                   separator, text_separator);
        }
    }
}

void MyFrame::OnVirtualTxt(wxCommandEvent & WXUNUSED(event))
{
//
// creating a VirtualText
//
  int ret;
  wxString charset;
  wxString sql;
  wxString path;
  wxString table;
  wxString lastDir;
  bool first_titles;
  bool decimal_comma;
  char separator;
  char text_separator;
  char dummy[16];
  char *errMsg = NULL;
  sqlite3 *sqlite = GetSqlite();
  wxString filelist = wxT("TXT and CSV files (*.txt;*.csv)|*.txt;*.csv");
  filelist +=
    wxT("|Text file (*.txt)|*.txt|CSV file (*.csv)|*.csv|All files (*.*)|*.*");
  wxFileDialog *fileDialog = new wxFileDialog(this, wxT("VirtualText"),
                                              wxT(""),
                                              wxT("textfile.txt"),
                                              filelist,
                                              wxFD_OPEN | wxFD_FILE_MUST_EXIST,
                                              wxDefaultPosition,
                                              wxDefaultSize,
                                              wxT("filedlg"));
  lastDir = GetLastDirectory();
  if (lastDir.Len() >= 1)
    fileDialog->SetDirectory(lastDir);
  ret = fileDialog->ShowModal();
  if (ret == wxID_OK)
    {
      path = fileDialog->GetPath();
      wxFileName file(path);
      table = file.GetName();
      VirtualTxtDialog dlg;
      dlg.Create(this, path, table, LocaleCharset);
      ret = dlg.ShowModal();
      if (ret == wxID_OK)
        {
          table = dlg.GetTable();
          charset = dlg.GetCharset();
          first_titles = dlg.IsFirstLineTitles();
          decimal_comma = dlg.IsDecimalPointComma();
          separator = dlg.GetSeparator();
          text_separator = dlg.GetTextSeparator();
      } else
        return;
      lastDir = file.GetPath();
      SetLastDirectory(lastDir);
      sql = wxT("CREATE VIRTUAL TABLE \"");
      sql += table;
      sql += wxT("\"\nUSING VirtualText('");
      sql += path;
      sql += wxT("',\n'");
      sql += charset;
      if (first_titles == true)
        sql += wxT("', 1");
      else
        sql += wxT("', 0");
      if (decimal_comma == true)
        sql += wxT(", COMMA");
      else
        sql += wxT(", POINT");
      if (text_separator == '\'')
        sql += wxT(", SINGLEQUOTE");
      else
        sql += wxT(", DOUBLEQUOTE");
      if (separator == '\t')
        sql += wxT(", TAB");
      else
        {
          sprintf(dummy, ", '%c'", separator);
          sql += wxString::FromUTF8(dummy);
        }
      sql += wxT(")");
      ret = sqlite3_exec(sqlite, sql.ToUTF8(), NULL, NULL, &errMsg);
      if (ret != SQLITE_OK)
        {
          wxMessageBox(wxT("SQLite SQL error: ") + wxString::FromUTF8(errMsg),
                       wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
          sqlite3_free(errMsg);
          return;
        }
      wxMessageBox(wxT("Virtual Table \"") + table +
                   wxT("\" was successfully created"), wxT("spatialite-gui"),
                   wxOK | wxICON_INFORMATION, this);
      InitTableTree();
    }
}

void MyFrame::OnNetwork(wxCommandEvent & WXUNUSED(event))
{
//
// building a Network
//
  NetworkDialog dlg;
  int ret;
  wxString table;
  wxString from;
  wxString to;
  wxString geom;
  bool isGeomLength;
  wxString cost;
  bool isBidirectional;
  bool isOneWays;
  wxString oneWayToFrom;
  wxString oneWayFromTo;
  dlg.Create(this);
  ret = dlg.ShowModal();
  if (ret == wxID_OK)
    {
      table = dlg.GetTableName();
      from = dlg.GetFromColumn();
      to = dlg.GetToColumn();
      geom = dlg.GetGeomColumn();
      isGeomLength = dlg.IsGeomLength();
      cost = dlg.GetCostColumn();
      isBidirectional = dlg.IsBidirectional();
      isOneWays = dlg.IsOneWays();
      oneWayToFrom = dlg.GetOneWayToFrom();
      oneWayFromTo = dlg.GetOneWayFromTo();
      BuildNetwork(table, from, to, geom, isGeomLength, cost, isBidirectional,
                   isOneWays, oneWayFromTo, oneWayToFrom);
    }
}

void MyFrame::OnImportExifPhotos(wxCommandEvent & WXUNUSED(event))
{
//
// importing EXIF Photos
//
  ExifDialog dlg;
  int ret;
  wxString path;
  bool isFolder;
  bool isMetadata;
  bool isGpsOnly;
  wxString lastDir;
  wxString dir_path;
  wxString img_path;
  wxString filelist = wxT("JPEG files (*.jpg;*.jpeg)|*.jpg;*.jpeg|");
  filelist += wxT("All files (*.*)|*.*");
  wxFileDialog *fileDialog =
    new wxFileDialog(this, wxT("EXIF File/Folder selection"),
                     wxT(""),
                     wxT(""),
                     filelist,
                     wxFD_OPEN | wxFD_FILE_MUST_EXIST,
                     wxDefaultPosition,
                     wxDefaultSize,
                     wxT("filedlg"));
  lastDir = GetLastDirectory();
  if (lastDir.Len() >= 1)
    fileDialog->SetDirectory(lastDir);
  ret = fileDialog->ShowModal();
  if (ret == wxID_OK)
    {
      img_path = fileDialog->GetPath();
      wxFileName file(img_path);
      dir_path = file.GetPath();
  } else
    return;
  dlg.Create(this, dir_path, img_path);
  ret = dlg.ShowModal();
  if (ret == wxID_OK)
    {
      SetLastDirectory(dir_path);
      isFolder = dlg.IsFolder();
      if (isFolder == true)
        path = dlg.GetDirPath();
      else
        path = dlg.GetImgPath();
      isMetadata = dlg.IsMetadata();
      isGpsOnly = dlg.IsGpsOnly();
      ImportExifPhotos(path, isFolder, isMetadata, isGpsOnly);
    }
}

void MyFrame::OnSrids(wxCommandEvent & WXUNUSED(event))
{
//
// searching a SRID by name
//
  SearchSridDialog dlg;
  int ret;
  wxString string;
  wxString sql;
  dlg.Create(this);
  ret = dlg.ShowModal();
  if (ret == wxID_OK)
    {
      string = dlg.GetString();
      sql = wxT("SELECT * FROM spatial_ref_sys\n");
      sql += wxT("WHERE ref_sys_name LIKE '%");
      sql += string;
      sql += wxT("%'\nORDER BY srid");
      QueryView->SetSql(sql, true);
    }
}

void MyFrame::OnCharset(wxCommandEvent & WXUNUSED(event))
{
//
// setting the default CHARSET
//
  DefaultCharsetDialog dlg;
  int ret;
  dlg.Create(this, DefaultCharset, AskCharset);
  ret = dlg.ShowModal();
  if (ret == wxID_OK)
    {
      DefaultCharset = dlg.GetCharset();
      AskCharset = dlg.IsSetAskCharset();
    }
}

void MyFrame::OnTimerAutoSave(wxTimerEvent & event)
{
//
// AutoSave - Timer event handler
// 
  int tc = sqlite3_total_changes(SqliteHandle);
  if (tc != LastTotalChanges)
    MemoryDbSave();
  if (AutoSaveInterval <= 0)
    {
      delete TimerAutoSave;
      TimerAutoSave = NULL;
  } else
    TimerAutoSave->Start(AutoSaveInterval * 1000, wxTIMER_ONE_SHOT);
}

bool MyFrame::ExecuteSql(const char *sql, int rowNo)
{
//
// executes an SQL statement from the SQL script
//
  int ret;
  char *errMsg = NULL;
  wxString msg;
  char dummy[128];
  ret = sqlite3_exec(SqliteHandle, sql, NULL, NULL, &errMsg);
  if (ret != SQLITE_OK)
    {
      sprintf(dummy, "row %d\n\nSQLite SQL error: ", rowNo);
      msg = wxString::FromUTF8(dummy);
      wxMessageBox(msg + wxString::FromUTF8(errMsg), wxT("spatialite-gui"),
                   wxOK | wxICON_ERROR, this);
      sqlite3_free(errMsg);
      return false;
    }
  return true;
}


void MyFrame::Rollback()
{
//
// performing a ROLLBACK
//
  sqlite3_exec(SqliteHandle, "ROLLBACK", NULL, NULL, NULL);
}

bool MyFrame::OpenDB()
{
//
// establishing a physical connetion to some DB SQLite
//
  int ret;
  ret =
    sqlite3_open_v2(SqlitePath.ToUTF8(), &SqliteHandle, SQLITE_OPEN_READWRITE,
                    NULL);
  if (ret)
    {
      // an error occurred
      wxString errCause;
      errCause = wxString::FromUTF8(sqlite3_errmsg(SqliteHandle));
      sqlite3_close(SqliteHandle);
      wxMessageBox(wxT("Failure while connecting to DB\n\n") + errCause +
                   wxT("\n") + SqlitePath, wxT("spatialite-gui"),
                   wxOK | wxICON_ERROR, this);
      SqliteHandle = NULL;
      ClearTableTree();
      MemoryDatabase = false;
      return false;
    }
  AutoFDOStart();
  InitTableTree();
  return true;
}

void MyFrame::LastDitchMemoryDbSave()
{
//
// performing the last desperate attempt to save a MEMORY-DB
//
  int tc;
  int ret;
  wxString lastDir;
  if (MemoryDatabase == false)
    return;
  if (!SqliteHandle)
    return;
  tc = sqlite3_total_changes(SqliteHandle);
  if (tc == LastTotalChanges)
    return;
  while (1)
    {
      // OK, this MEMORY-DB needs to be saved
      if (MemoryDbSave() == true)
        break;
      // we must ask the user
      wxString msg =
        wxT("WARNING: the MEMORY-DB contains uncommitted changes\n\n");
      msg += wxT("The MEMORY_DB is intrinsecally volatile, so these changes\n");
      msg +=
        wxT("will be irremediably lost if you don't export them to some\n");
      msg += wxT("persistent storage [i.e. on the file-system]\n\n");
      msg +=
        wxT
        ("Do you want to export [SAVE] the MEMORY-DB to some external database ?");
      ret =
        wxMessageBox(msg, wxT("spatialite-gui"), wxYES_NO | wxICON_QUESTION,
                     this);
      if (ret != wxYES)
        break;
      // asking a PATHNAME to the user
      wxFileDialog *fileDialog =
        new wxFileDialog(this, wxT("Saving the MEMORY-DB"),
                         wxT(""), wxT("db.sqlite"),
                         wxT
                         ("SQLite DB (*.sqlite)|*.sqlite|All files (*.*)|*.*"),
                         wxFD_SAVE | wxFD_OVERWRITE_PROMPT,
                         wxDefaultPosition,
                         wxDefaultSize,
                         wxT("filedlg"));
      lastDir = GetLastDirectory();
      if (lastDir.Len() >= 1)
        fileDialog->SetDirectory(lastDir);
      ret = fileDialog->ShowModal();
      if (ret == wxID_OK)
        {
          // exporting the external DB
          ExternalSqlitePath = fileDialog->GetPath();
          if (MemoryDbSave() == true)
            {
              wxMessageBox(wxT("Ok, MEMORY-DB was succesfully saved"),
                           wxT("spatialite-gui"), wxOK | wxICON_INFORMATION,
                           this);
              break;
            }
        }
    }
}

void MyFrame::CloseDB()
{
//
// disconnecting current SQLite DB
//
  if (!SqliteHandle)
    return;
  AutoFDOStop();
  if (AutoFDOmsg.Len() > 0)
    wxMessageBox(AutoFDOmsg, wxT("spatialite-gui"), wxOK | wxICON_INFORMATION,
                 this);
  LastDitchMemoryDbSave();
  sqlite3_close(SqliteHandle);
  SqliteHandle = NULL;
  SqlitePath = wxT("");
  MemoryDatabase = false;
  ClearTableTree();
}

bool MyFrame::CreateDB()
{
// creating a new, empty SQLite DB
  int ret;
  char path[1024];
  if (MemoryDatabase == true)
    strcpy(path, ":memory:");
  else
    {
      strcpy(path, SqlitePath.ToUTF8());
      unlink(path);
    }
  ret =
    sqlite3_open_v2(path, &SqliteHandle,
                    SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL);
  if (ret)
    {
      // an error occurred
      wxString errCause;
      errCause = wxString::FromUTF8(sqlite3_errmsg(SqliteHandle));
      sqlite3_close(SqliteHandle);
      wxMessageBox(wxT("An error occurred\n\n") + errCause + wxT("\n") +
                   SqlitePath, wxT("spatialite-gui"), wxOK | wxICON_ERROR,
                   this);
      SqliteHandle = NULL;
      ClearTableTree();
      MemoryDatabase = false;
      return false;
    }
  if (CreateSpatialMetaData() == false)
    wxMessageBox(wxT("Spatial Metadata tables creation error\n") +
                 SqlitePath, wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
  AutoFDOStart();
  InitTableTree();
  return true;
}

void MyFrame::CleanSql(char *buf)
{
// well-formatting a string to be used as an SQL string
  char tmp[1024];
  char *in = tmp;
  char *out = buf;
  strcpy(tmp, buf);
  while (*in != '\0')
    {
      if (*in == '\'')
        *out++ = '\'';
      *out++ = *in++;
    }
  *out = '\0';
}

void MyFrame::InitTableTree()
{
// loads the table TREE list
  int i;
  char **results;
  int rows;
  int columns;
  char *errMsg = NULL;
  char *name;
  char *createSql;
  char *type;
  wxString tblName;
  wxString sql;
  bool virtualTable = false;
  TableTree->Show(false);
  if (MemoryDatabase == true)
    {
      wxString memory = wxT("MEMORY-DB");
      TableTree->SetPath(memory);
  } else
    TableTree->SetPath(SqlitePath);
  TableTree->FlushAll();
  sql =
    wxT
    ("SELECT name, sql, type FROM sqlite_master WHERE (type = 'table' OR type = 'view') ORDER BY name");
  int ret = sqlite3_get_table(SqliteHandle, sql.ToUTF8(), &results,
                              &rows, &columns, &errMsg);
  if (ret != SQLITE_OK)
    {
      wxMessageBox(wxT("SQLite SQL error: ") + wxString::FromUTF8(errMsg),
                   wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
      sqlite3_free(errMsg);
      return;
    }
  if (rows < 1)
    ;
  else
    {
      for (i = 1; i <= rows; i++)
        {
          name = results[(i * columns) + 0];
          createSql = results[(i * columns) + 1];
          type = results[(i * columns) + 2];
          if (strstr(createSql, "VIRTUAL") || strstr(createSql, "virtual"))
            virtualTable = true;
          else
            virtualTable = false;
          tblName = wxString::FromUTF8(name);
          if (strcmp(type, "view") == 0)
            TableTree->AddView(tblName);
          else
            TableTree->AddTable(tblName, virtualTable);
        }
    }
  sqlite3_free_table(results);
  TableTree->ExpandRoot();
  TableTree->Show(true);
}

wxString *MyFrame::GetTables(int *n)
{
// loads the table list
  int i;
  char **results;
  int rows;
  int columns;
  char *errMsg = NULL;
  char *name;
  wxString *tables = NULL;
  wxString sql;
  *n = 0;
  sql =
    wxT("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name");
  int ret = sqlite3_get_table(SqliteHandle, sql.ToUTF8(), &results,
                              &rows, &columns, &errMsg);
  if (ret != SQLITE_OK)
    {
      wxMessageBox(wxT("SQLite SQL error: ") + wxString::FromUTF8(errMsg),
                   wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
      sqlite3_free(errMsg);
      return tables;
    }
  if (rows < 1)
    ;
  else
    {
      tables = new wxString[rows];
      *n = rows;
      for (i = 1; i <= rows; i++)
        {
          name = results[(i * columns) + 0];
          tables[i - 1] = wxString::FromUTF8(name);
        }
    }
  sqlite3_free_table(results);
  return tables;
}

void MyFrame::GetTableColumns(wxString & tableName, MyTableInfo * list)
{
// loads the table's column list
  int i;
  char **results;
  int rows;
  int columns;
  char *errMsg = NULL;
  char *name;
  char *column;
  wxString Name;
  wxString Column;
  bool pKey;
  bool index;
  bool cached;
  wxString sql;
  sql = wxT("PRAGMA table_info(\"");
  sql += tableName;
  sql += wxT("\")");
  int ret = sqlite3_get_table(SqliteHandle, sql.ToUTF8(), &results,
                              &rows, &columns, &errMsg);
  if (ret != SQLITE_OK)
    {
      wxMessageBox(wxT("SQLite SQL error: ") + wxString::FromUTF8(errMsg),
                   wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
      sqlite3_free(errMsg);
      return;
    }
  if (rows < 1)
    ;
  else
    {
      for (i = 1; i <= rows; i++)
        {
          name = results[(i * columns) + 1];
          if (atoi(results[(i * columns) + 5]) == 0)
            pKey = false;
          else
            pKey = true;
          Name = wxString::FromUTF8(name);
          list->AddColumn(Name, pKey);
        }
    }
  sqlite3_free_table(results);
  if (CheckMetadata() == true)
    {
      // ok, Spatial MetaData exists; retrieving Geometries and Spatial Indices
      sql =
        wxT
        ("SELECT f_geometry_column, spatial_index_enabled FROM geometry_columns ");
      sql += wxT("WHERE f_table_name = '");
      sql += tableName;
      sql += wxT("'");
      ret =
        sqlite3_get_table(SqliteHandle, sql.ToUTF8(), &results, &rows, &columns,
                          &errMsg);
      if (ret != SQLITE_OK)
        {
          wxMessageBox(wxT("SQLite SQL error: ") + wxString::FromUTF8(errMsg),
                       wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
          sqlite3_free(errMsg);
          return;
        }
      if (rows < 1)
        ;
      else
        {
          for (i = 1; i <= rows; i++)
            {
              column = results[(i * columns) + 0];
              if (atoi(results[(i * columns) + 1]) == 1)
                index = true;
              else
                index = false;
              if (atoi(results[(i * columns) + 1]) == 2)
                cached = true;
              else
                cached = false;
              Column = wxString::FromUTF8(column);
              list->SetGeometry(Column, index, cached);
            }
        }
      sqlite3_free_table(results);
    }
}

void MyFrame::GetViewColumns(wxString & tableName, MyViewInfo * list)
{
// loads the view's column list
  int i;
  char **results;
  int rows;
  int columns;
  char *errMsg = NULL;
  char *name;
  wxString Name;
  wxString sql;
  sql = wxT("PRAGMA table_info(\"");
  sql += tableName;
  sql += wxT("\")");
  int ret = sqlite3_get_table(SqliteHandle, sql.ToUTF8(), &results,
                              &rows, &columns, &errMsg);
  if (ret != SQLITE_OK)
    {
      wxMessageBox(wxT("SQLite SQL error: ") + wxString::FromUTF8(errMsg),
                   wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
      sqlite3_free(errMsg);
      return;
    }
  if (rows < 1)
    ;
  else
    {
      for (i = 1; i <= rows; i++)
        {
          name = results[(i * columns) + 1];
          Name = wxString::FromUTF8(name);
          list->AddColumn(Name);
        }
    }
  sqlite3_free_table(results);
}

void MyFrame::GetTableIndices(wxString & tableName, MyTableInfo * list)
{
// loads the table's indices list
  int i;
  char **results;
  int rows;
  int columns;
  char *errMsg = NULL;
  char *name;
  wxString Name;
  wxString sql;
  sql = wxT("PRAGMA index_list(\"");
  sql += tableName;
  sql += wxT("\")");
  int ret = sqlite3_get_table(SqliteHandle, sql.ToUTF8(), &results,
                              &rows, &columns, &errMsg);
  if (ret != SQLITE_OK)
    {
      wxMessageBox(wxT("SQLite SQL error: ") + wxString::FromUTF8(errMsg),
                   wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
      sqlite3_free(errMsg);
      return;
    }
  if (rows < 1)
    ;
  else
    {
      for (i = 1; i <= rows; i++)
        {
          name = results[(i * columns) + 1];
          Name = wxString::FromUTF8(name);
          list->AddIndex(Name);
        }
    }
  sqlite3_free_table(results);
}

void MyFrame::GetTableTriggers(wxString & tableName, MyTableInfo * list)
{
// loads the table's indices list
  int i;
  char **results;
  int rows;
  int columns;
  char *errMsg = NULL;
  char *name;
  wxString Name;
  wxString sql;
  sql =
    wxT
    ("SELECT name FROM sqlite_master WHERE type = 'trigger' AND tbl_name = '");
  sql += tableName;
  sql += wxT("' ORDER BY \"name\"");
  int ret = sqlite3_get_table(SqliteHandle, sql.ToUTF8(), &results,
                              &rows, &columns, &errMsg);
  if (ret != SQLITE_OK)
    {
      wxMessageBox(wxT("SQLite SQL error: ") + wxString::FromUTF8(errMsg),
                   wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
      sqlite3_free(errMsg);
      return;
    }
  if (rows < 1)
    ;
  else
    {
      for (i = 1; i <= rows; i++)
        {
          name = results[(i * columns) + 0];
          Name = wxString::FromUTF8(name);
          list->AddTrigger(Name);
        }
    }
  sqlite3_free_table(results);
  TableTree->ExpandRoot();
}

wxString *MyFrame::GetColumnNames(wxString & tableName, int *n_cols)
{
// loads the table's column names list
  wxString *cols = NULL;
  int nCols = 0;
  char **results;
  int rows;
  int columns;
  int i;
  char *errMsg = NULL;
  wxString sql;
  char *column;
  sql = wxT("PRAGMA table_info(\"");
  sql += tableName;
  sql += wxT("\")");
  int ret = sqlite3_get_table(SqliteHandle, sql.ToUTF8(), &results,
                              &rows, &columns, &errMsg);
  if (ret != SQLITE_OK)
    {
      wxMessageBox(wxT("SQLite SQL error: ") + wxString::FromUTF8(errMsg),
                   wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
      sqlite3_free(errMsg);
      return NULL;
    }
  sql = wxT("");
  if (rows < 1)
    ;
  else
    {
      nCols = rows;
      cols = new wxString[rows];
      for (i = 1; i <= rows; i++)
        {
          column = results[(i * columns) + 1];
          *(cols + i - 1) += wxString::FromUTF8(column);
        }
    }
  sqlite3_free_table(results);
  *n_cols = nCols;
  return cols;
}

int MyFrame::GetCharsetIndex(wxString & charset)
{
// identifies the INDEX for a given charset
  int i;
  for (i = 0; i < CharsetsLen; i++)
    {
      if (*(Charsets + i) == charset)
        return i;
    }
  return wxNOT_FOUND;
}

wxString & MyFrame::GetCharsetName(wxString & charset)
{
// identifies the full name for a given charset code
  int i;
  for (i = 0; i < CharsetsLen; i++)
    {
      if (*(Charsets + i) == charset)
        return *(CharsetsNames + i);
    }
  return charset;
}

void MyFrame::ClearTableTree()
{
// resets the table TREE list to the empty state
  wxString path = wxT("no current DB");
  TableTree->SetPath(path);
  TableTree->FlushAll();
}

void MyFrame::AutoFDOStart()
{
//
// trying to start the FDO-OGR auto-wrapper
//
  int ret;
  const char *name;
  int i;
  char **results;
  int rows;
  int columns;
  char sql[1024];
  int count = 0;
  int len;
  int spatial_type = 0;
  AutoFDOTables tables;
  AutoFDOTable *p;
  wxString fdoNames[5];
  SpatiaLiteMetadata = false;
  AutoFDOmsg = wxT("");
  strcpy(sql, "SELECT CheckSpatialMetadata()");
  ret = sqlite3_get_table(SqliteHandle, sql, &results, &rows, &columns, NULL);
  if (ret != SQLITE_OK)
    goto error1;
  if (rows < 1)
    ;
  else
    {
      for (i = 1; i <= rows; i++)
        spatial_type = atoi(results[(i * columns) + 0]);
    }
  sqlite3_free_table(results);
error1:
  if (spatial_type == 1)
    SpatiaLiteMetadata = true;
  if (spatial_type == 2)
    {
      //
      // ok, creating VirtualFDO tables 
      //
      strcpy(sql, "SELECT DISTINCT f_table_name FROM geometry_columns");
      ret =
        sqlite3_get_table(SqliteHandle, sql, &results, &rows, &columns, NULL);
      if (ret != SQLITE_OK)
        goto error;
      if (rows < 1)
        ;
      else
        {
          for (i = 1; i <= rows; i++)
            {
              name = results[(i * columns) + 0];
              if (name)
                {
                  len = strlen(name);
                  tables.Add(name, len);
                }
            }
        }
      sqlite3_free_table(results);
      p = tables.GetFirst();
      while (p)
        {
          //
          // destroying the VirtualFDO table [if existing] 
          //
          sprintf(sql, "DROP TABLE IF EXISTS \"fdo_%s\"", p->GetName());
          ret = sqlite3_exec(SqliteHandle, sql, NULL, 0, NULL);
          if (ret != SQLITE_OK)
            goto error;
          //
          // creating the VirtualFDO table 
          //
          sprintf(sql, "CREATE VIRTUAL TABLE \"fdo_%s\" USING VirtualFDO(%s)",
                  p->GetName(), p->GetName());
          ret = sqlite3_exec(SqliteHandle, sql, NULL, 0, NULL);
          if (ret != SQLITE_OK)
            goto error;
          if (count < 5)
            fdoNames[count] =
              wxT("- VirtualTable: \"fdo_") + wxString::FromUTF8(p->GetName()) +
              wxT("\"");
          else
            fdoNames[4] = wxT("- ... and others ...");
          count++;
          p = p->GetNext();
        }
    error:
      if (count++)
        {
          AutoFDOmsg =
            wxT("FDO-OGR detected; activating FDO-OGR auto-wrapping ...\n\n");
          if (fdoNames[0].Len() > 0)
            AutoFDOmsg += fdoNames[0] + wxT("\n");
          if (fdoNames[1].Len() > 0)
            AutoFDOmsg += fdoNames[1] + wxT("\n");
          if (fdoNames[2].Len() > 0)
            AutoFDOmsg += fdoNames[2] + wxT("\n");
          if (fdoNames[3].Len() > 0)
            AutoFDOmsg += fdoNames[3] + wxT("\n");
          if (fdoNames[4].Len() > 0)
            AutoFDOmsg += fdoNames[4] + wxT("\n");
          AutoFDOmsg +=
            wxT
            ("\nAccessing these fdo_XX tables you can take full advantage of\n");
          AutoFDOmsg += wxT("FDO-OGR auto-wrapping facility\n");
          AutoFDOmsg +=
            wxT
            ("This allows you to access any specific FDO-OGR Geometry as if it\n");
          AutoFDOmsg +=
            wxT
            ("where native SpatiaLite ones in a completely transparent way.\n");
        }
      return;
    }
}

void MyFrame::AutoFDOStop()
{
//
// trying to stop the FDO-OGR auto-wrapper
//
  int ret;
  const char *name;
  int i;
  char **results;
  int rows;
  int columns;
  char sql[1024];
  int count = 0;
  int len;
  int spatial_type = 0;
  AutoFDOTables tables;
  AutoFDOTable *p;
  AutoFDOmsg = wxT("");
  strcpy(sql, "SELECT CheckSpatialMetadata()");
  ret = sqlite3_get_table(SqliteHandle, sql, &results, &rows, &columns, NULL);
  if (ret != SQLITE_OK)
    goto error1;
  if (rows < 1)
    ;
  else
    {
      for (i = 1; i <= rows; i++)
        spatial_type = atoi(results[(i * columns) + 0]);
    }
  sqlite3_free_table(results);
error1:
  if (spatial_type == 2)
    {
      //
      // ok, destroying VirtualFDO tables 
      //
      strcpy(sql, "SELECT DISTINCT f_table_name FROM geometry_columns");
      ret =
        sqlite3_get_table(SqliteHandle, sql, &results, &rows, &columns, NULL);
      if (ret != SQLITE_OK)
        goto error;
      if (rows < 1)
        ;
      else
        {
          for (i = 1; i <= rows; i++)
            {
              name = results[(i * columns) + 0];
              if (name)
                {
                  len = strlen(name);
                  tables.Add(name, len);
                }
            }
        }
      sqlite3_free_table(results);
      p = tables.GetFirst();
      while (p)
        {
          //
          // destroying the VirtualFDO table [if existing] 
          //
          sprintf(sql, "DROP TABLE IF EXISTS \"fdo_%s\"", p->GetName());
          ret = sqlite3_exec(SqliteHandle, sql, NULL, 0, NULL);
          if (ret != SQLITE_OK)
            goto error;
          count++;
          p = p->GetNext();
        }
    error:
      if (count++)
        AutoFDOmsg = wxT("FDO-OGR auto-wrapping shutdown done");
      return;
    }
}

void MyFrame::GetHelp(wxString & html)
{
//
// return the HTML Help
//
  html =
    wxT("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
  html += wxT("<html>");
  html += wxT("<head>");
  html +=
    wxT
    ("<meta content=\"text/html; charset=UTF-8\" http-equiv=\"content-type\">");
  html += wxT("<title>SQLite + SpatiaLite quick Help</title>");
  html += wxT("</head>");
  html += wxT("<body bgcolor=\"#e8e8e8\">");
  html += wxT("<h1><a name=\"index\">SQLite + SpatiaLite quick Help</a></h1>");
  html += wxT("<table cellspacing=\"2\" cellpadding=\"2\">");
  html +=
    wxT
    ("<tr><td align=\"center\" bgcolor=\"#e0ffe0\" colspan=\"2\">Index of contents</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">1.</td><td bgcolor=\"#f0fff0\"><a href=\"#c1\">SQLite SQL syntax</a></td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">2.</td><td bgcolor=\"#f0fff0\"><a href=\"#c2\">SQLite SQL functions</a><ul>");
  html += wxT("<li><a href=\"#c21\">ordinary functions</a></li>");
  html += wxT("<li><a href=\"#c22\">aggregate functions</a></li>");
  html += wxT("</ul></td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">3.</td><td bgcolor=\"#f0fff0\"><a href=\"#c3\">SpatiaLite SQL Spatial functions</a><ul>");
  html += wxT("<li><a href=\"#math\">math functions</a></li>");
  html +=
    wxT("<li><a href=\"#blob\">utility functions for BLOB objects</a></li>");
  html +=
    wxT
    ("<li><a href=\"#c30\">utility functions [non-standard] for geometric objects</a></li>");
  html +=
    wxT
    ("<li><a href=\"#c31\">functions for constructing a geometric object given its Well-known Text Representation</a></li>");
  html +=
    wxT
    ("<li><a href=\"#c32\">functions for constructing a geometric object given its Well-known Binary Representation</a></li>");
  html +=
    wxT
    ("<li><a href=\"#c33\">functions for obtaining the Well-known Text / Well-known Binary Representation of a geometric object</a></li>");
  html +=
    wxT
    ("<li><a href=\"#c33misc\">functions supporting exotic geometric formats</a></li>");
  html += wxT("<li><a href=\"#c34\">functions on type Geometry</a></li>");
  html += wxT("<li><a href=\"#c35\">functions on type Point</a></li>");
  html +=
    wxT
    ("<li><a href=\"#c36\">functions on type Surface [Polygon or Ring]</a></li>");
  html += wxT("<li><a href=\"#c37\">functions on type Polygon</a></li>");
  html += wxT("<li><a href=\"#c38\">functions on type GeomCollection</a></li>");
  html +=
    wxT
    ("<li><a href=\"#c39\">functions testing approximative spatial relationships via MBRs</a></li>");
  html +=
    wxT
    ("<li><a href=\"#c40\">functions testing spatial relationships</a></li>");
  html +=
    wxT
    ("<li><a href=\"#c41\">functions implementing spatial operators</a></li>");
  html +=
    wxT
    ("<li><a href=\"#c42\">functions for coordinate transformations</a></li>");
  html +=
    wxT
    ("<li><a href=\"#c43\">functions for Spatial-MetaData and Spatial-Index handling</a></li>");
  html +=
    wxT
    ("<li><a href=\"#c43fdo\">functions implementing FDO/OGR compatibily</a></li>");
  html +=
    wxT("<li><a href=\"#c44\">functions for MbrCache-based queries</a></li>");
  html += wxT("</ul></td></tr>");
  html += wxT("</table>");
  html += wxT("<h3><a name=\"c1\">SQLite SQL syntax</a></h3>");
  html += wxT("<table cellspacing=\"4\" cellpadding=\"2\"width=\"100%\">");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">ALTER TABLE</td><td bgcolor=\"#f0fff0\">sql-statement ::= ALTER TABLE [database-name .] table-name alteration<br>");
  html += wxT("alteration ::= RENAME TO new-table-name<br>");
  html += wxT("alteration ::= ADD [COLUMN] column-def<br></td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">ANALYZE</td><td bgcolor=\"#f0fff0\">sql-statement ::= ANALYZE<br>");
  html += wxT("sql-statement ::= ANALYZE database-name<br>");
  html +=
    wxT("sql-statement ::= ANALYZE [database-name .] table-name<br></td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">ATTACH DATABASE</td><td bgcolor=\"#f0fff0\">sql-statement ::= ATTACH [DATABASE] database-filename AS database-name</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">BEGIN TRANSACTION</td><td bgcolor=\"#f0fff0\">sql-statement ::= BEGIN [ DEFERRED | IMMEDIATE | EXCLUSIVE ] [TRANSACTION [name]]<br>");
  html += wxT("sql-statement ::= END [TRANSACTION [name]]<br>");
  html += wxT("sql-statement ::= COMMIT [TRANSACTION [name]]<br>");
  html += wxT("sql-statement ::= ROLLBACK [TRANSACTION [name]]<br></td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">COMMIT TRANSACTION</td><td bgcolor=\"#f0fff0\">sql-statement ::= BEGIN [ DEFERRED | IMMEDIATE | EXCLUSIVE ] [TRANSACTION [name]]<br>");
  html += wxT("sql-statement ::= END [TRANSACTION [name]]<br>");
  html += wxT("sql-statement ::= COMMIT [TRANSACTION [name]]<br>");
  html += wxT("sql-statement ::= ROLLBACK [TRANSACTION [name]]<br></td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">CREATE INDEX</td><td bgcolor=\"#f0fff0\">sql-statement ::= CREATE [UNIQUE] INDEX [IF NOT EXISTS] [database-name .] index-name<br>");
  html += wxT("ON table-name ( column-name [, column-name]* )<br>");
  html +=
    wxT
    ("column-name ::= name [ COLLATE collation-name] [ ASC | DESC ]</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">CREATE TABLE</td><td bgcolor=\"#f0fff0\">sql-command ::= CREATE [TEMP | TEMPORARY] TABLE [IF NOT EXISTS] [database-name .] table-name (<br>");
  html += wxT("column-def [, column-def]*<br>");
  html += wxT("[, constraint]*<br>");
  html += wxT(")<br>");
  html +=
    wxT
    ("sql-command ::= CREATE [TEMP | TEMPORARY] TABLE [database-name.] table-name AS select-statement<br>");
  html +=
    wxT
    ("column-def ::= name [type] [[CONSTRAINT name] column-constraint]*<br>");
  html += wxT("type ::= typename |<br>");
  html += wxT("typename ( number ) |<br>");
  html += wxT("typename ( number , number )<br>");
  html += wxT("column-constraint ::= NOT NULL [ conflict-clause ] |<br>");
  html +=
    wxT("PRIMARY KEY [sort-order] [ conflict-clause ] [AUTOINCREMENT] |<br>");
  html += wxT("UNIQUE [ conflict-clause ] |<br>");
  html += wxT("CHECK ( expr ) |<br>");
  html += wxT("DEFAULT value |<br>");
  html += wxT("COLLATE collation-name<br>");
  html +=
    wxT("constraint ::= PRIMARY KEY ( column-list ) [ conflict-clause ] |<br>");
  html += wxT("UNIQUE ( column-list ) [ conflict-clause ] |<br>");
  html += wxT("CHECK ( expr )<br>");
  html += wxT("conflict-clause ::= ON CONFLICT conflict-algorithm</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">CREATE TRIGGER</td><td bgcolor=\"#f0fff0\">sql-statement ::= CREATE [TEMP | TEMPORARY] TRIGGER [IF NOT EXISTS] trigger-name [ BEFORE | AFTER ]<br>");
  html += wxT("database-event ON [database-name .] table-name<br>");
  html += wxT("trigger-action<br>");
  html +=
    wxT
    ("sql-statement ::= CREATE [TEMP | TEMPORARY] TRIGGER [IF NOT EXISTS] trigger-name INSTEAD OF<br>");
  html += wxT("database-event ON [database-name .] view-name<br>");
  html += wxT("trigger-action<br>");
  html += wxT("database-event ::= DELETE |<br>");
  html += wxT("INSERT |<br>");
  html += wxT("UPDATE |<br>");
  html += wxT("UPDATE OF column-list<br>");
  html += wxT("trigger-action ::= [ FOR EACH ROW ] [ WHEN expression ]<br>");
  html += wxT("BEGIN<br>");
  html += wxT("trigger-step ; [ trigger-step ; ]*<br>");
  html += wxT("END<br>");
  html += wxT("trigger-step ::= update-statement | insert-statement |<br>");
  html += wxT("delete-statement | select-statement</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">CREATE VIEW</td><td bgcolor=\"#f0fff0\">sql-command ::= CREATE [TEMP | TEMPORARY] VIEW [IF NOT EXISTS] [database-name.] view-name AS select-statement</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">CREATE VIRTUAL TABLE</td><td bgcolor=\"#f0fff0\">sql-command ::= CREATE VIRTUAL TABLE [database-name .] table-name USING module-name [( arguments )]</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">DELETE</td><td bgcolor=\"#f0fff0\">sql-statement ::= DELETE FROM [database-name .] table-name [WHERE expr]</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">DETACH DATABASE</td><td bgcolor=\"#f0fff0\">sql-command ::= DETACH [DATABASE] database-name</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">DROP INDEX</td><td bgcolor=\"#f0fff0\">sql-command ::= DROP INDEX [IF EXISTS] [database-name .] index-name</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">DROP TABLE</td><td bgcolor=\"#f0fff0\">sql-command ::= DROP TABLE [IF EXISTS] [database-name.] table-name</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">DROP TRIGGER</td><td bgcolor=\"#f0fff0\">sql-statement ::= DROP TRIGGER [IF EXISTS] [database-name .] trigger-name</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">DROP VIEW</td><td bgcolor=\"#f0fff0\">sql-command ::= DROP VIEW [IF EXISTS] view-name</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">END TRANSACTION</td><td bgcolor=\"#f0fff0\">sql-statement ::= BEGIN [ DEFERRED | IMMEDIATE | EXCLUSIVE ] [TRANSACTION [name]]<br>");
  html += wxT("sql-statement ::= END [TRANSACTION [name]]<br>");
  html += wxT("sql-statement ::= COMMIT [TRANSACTION [name]]<br>");
  html += wxT("sql-statement ::= ROLLBACK [TRANSACTION [name]]<br></td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">EXPLAIN</td><td bgcolor=\"#f0fff0\">sql-statement ::= EXPLAIN sql-statement</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">INSERT</td><td bgcolor=\"#f0fff0\">sql-statement ::= INSERT [OR conflict-algorithm] INTO [database-name .] table-name [(column-list)] VALUES(value-list) |<br>");
  html +=
    wxT
    ("INSERT [OR conflict-algorithm] INTO [database-name .] table-name [(column-list)] select-statement</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">ON CONFLICT clause</td><td bgcolor=\"#f0fff0\">conflict-clause ::= ON CONFLICT conflict-algorithm<br>");
  html +=
    wxT
    ("conflict-algorithm ::= ROLLBACK | ABORT | FAIL | IGNORE | REPLACE</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">PRAGMA</td><td bgcolor=\"#f0fff0\">sql-statement ::= PRAGMA name [= value] |<br>");
  html += wxT("PRAGMA function(arg)<hr>");
  html += wxT("PRAGMA auto_vacuum;<br>");
  html +=
    wxT("PRAGMA auto_vacuum = 0 | none | 1 | full | 2 | incremental;<hr>");
  html += wxT("PRAGMA cache_size;<br>");
  html += wxT("PRAGMA cache_size = Number-of-pages;<hr>");
  html += wxT("PRAGMA case_sensitive_like;<br>");
  html += wxT("PRAGMA case_sensitive_like = 0 | 1;<hr>");
  html += wxT("PRAGMA count_changes;<br>");
  html += wxT("PRAGMA count_changes = 0 | 1;<hr>");
  html += wxT("PRAGMA default_cache_size;<br>");
  html += wxT("PRAGMA default_cache_size = Number-of-pages;<hr>");
  html += wxT("PRAGMA empty_result_callbacks;<br>");
  html += wxT("PRAGMA empty_result_callbacks = 0 | 1;<hr>");
  html += wxT("PRAGMA encoding;<br>");
  html += wxT("PRAGMA encoding = \"UTF-8\";<br>");
  html += wxT("PRAGMA encoding = \"UTF-16\";<br>");
  html += wxT("PRAGMA encoding = \"UTF-16le\";<br>");
  html += wxT("PRAGMA encoding = \"UTF-16be\";<hr>");
  html += wxT("PRAGMA full_column_names;<br>");
  html += wxT("PRAGMA full_column_names = 0 | 1;<hr>");
  html += wxT("PRAGMA fullfsync;<br>");
  html += wxT("PRAGMA fullfsync = 0 | 1;<hr>");
  html += wxT("PRAGMA journal_mode;<br>");
  html += wxT("PRAGMA database.journal_mode;<br>");
  html += wxT("PRAGMA journal_mode = DELETE | PERSIST | OFF<br>");
  html += wxT("PRAGMA database.journal_mode = DELETE | PERSIST | OFF<hr>");
  html += wxT("PRAGMA legacy_file_format;<br>");
  html += wxT("PRAGMA legacy_file_format = ON | OFF<hr>");
  html += wxT("PRAGMA locking_mode;<br>");
  html += wxT("PRAGMA locking_mode = NORMAL | EXCLUSIVE<hr>");
  html += wxT("PRAGMA page_size;<br>");
  html += wxT("PRAGMA page_size = bytes;<hr>");
  html += wxT("PRAGMA max_page_count;<br>");
  html += wxT("PRAGMA max_page_count = N;<hr>");
  html += wxT("PRAGMA read_uncommitted;<br>");
  html += wxT("PRAGMA read_uncommitted = 0 | 1;<hr>");
  html += wxT("PRAGMA short_column_names;<br>");
  html += wxT("PRAGMA short_column_names = 0 | 1;<hr>");
  html += wxT("PRAGMA synchronous;<br>");
  html += wxT("PRAGMA synchronous = FULL; (2)<br>");
  html += wxT("PRAGMA synchronous = NORMAL; (1)<br>");
  html += wxT("PRAGMA synchronous = OFF; (0)<hr>");
  html += wxT("PRAGMA temp_store;<br>");
  html += wxT("PRAGMA temp_store = DEFAULT; (0)<br>");
  html += wxT("PRAGMA temp_store = FILE; (1)<br>");
  html += wxT("PRAGMA temp_store = MEMORY; (2)<hr>");
  html += wxT("PRAGMA temp_store_directory;<br>");
  html += wxT("PRAGMA temp_store_directory = 'directory-name';<hr>");
  html += wxT("PRAGMA database_list;<hr>");
  html += wxT("PRAGMA foreign_key_list(table-name);<hr>");
  html += wxT("PRAGMA [database].freelist_count;<hr>");
  html += wxT("PRAGMA index_info(index-name);<hr>");
  html += wxT("PRAGMA index_list(table-name);<hr>");
  html += wxT("PRAGMA table_info(table-name);<hr>");
  html += wxT("PRAGMA [database.]schema_version;<br>");
  html += wxT("PRAGMA [database.]schema_version = integer ;<br>");
  html += wxT("PRAGMA [database.]user_version;<br>");
  html += wxT("PRAGMA [database.]user_version = integer ;<hr>");
  html += wxT("PRAGMA integrity_check;<br>");
  html += wxT("PRAGMA integrity_check(integer)<hr>");
  html += wxT("PRAGMA parser_trace = ON; (1)<br>");
  html += wxT("PRAGMA parser_trace = OFF; (0)<hr>");
  html += wxT("PRAGMA vdbe_trace = ON; (1)<br>");
  html += wxT("PRAGMA vdbe_trace = OFF; (0)<hr>");
  html += wxT("PRAGMA vdbe_listing = ON; (1)<br>");
  html += wxT("PRAGMA vdbe_listing = OFF; (0)</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">REINDEX</td><td bgcolor=\"#f0fff0\">sql-statement ::= REINDEX collation name<br>");
  html +=
    wxT
    ("sql-statement ::= REINDEX [database-name .] table/index-name</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">REPLACE</td><td bgcolor=\"#f0fff0\">sql-statement ::= REPLACE INTO [database-name .] table-name [( column-list )] VALUES ( value-list ) |<br>");
  html +=
    wxT
    ("REPLACE INTO [database-name .] table-name [( column-list )] select-statement</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">ROLLBACK TRANSACTION</td><td bgcolor=\"#f0fff0\">sql-statement ::= BEGIN [ DEFERRED | IMMEDIATE | EXCLUSIVE ] [TRANSACTION [name]]<br>");
  html += wxT("sql-statement ::= END [TRANSACTION [name]]<br>");
  html += wxT("sql-statement ::= COMMIT [TRANSACTION [name]]<br>");
  html += wxT("sql-statement ::= ROLLBACK [TRANSACTION [name]]<br></td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">SELECT</td><td bgcolor=\"#f0fff0\">sql-statement ::= SELECT [ALL | DISTINCT] result [FROM table-list]<br>");
  html += wxT("[WHERE expr]<br>");
  html += wxT("[GROUP BY expr-list]<br>");
  html += wxT("[HAVING expr]<br>");
  html += wxT("[compound-op select]*<br>");
  html += wxT("[ORDER BY sort-expr-list]<br>");
  html += wxT("[LIMIT integer [( OFFSET | , ) integer]]<br>");
  html += wxT("result ::= result-column [, result-column]*<br>");
  html +=
    wxT("result-column ::= * | table-name . * | expr [ [AS] string ]<br>");
  html += wxT("table-list ::= table [join-op table join-args]*<br>");
  html += wxT("table ::= table-name [AS alias] |<br>");
  html += wxT("( select ) [AS alias]<br>");
  html +=
    wxT
    ("join-op ::= , | [NATURAL] [LEFT | RIGHT | FULL] [OUTER | INNER | CROSS] JOIN<br>");
  html += wxT("join-args ::= [ON expr] [USING ( id-list )]<br>");
  html +=
    wxT("sort-expr-list ::= expr [sort-order] [, expr [sort-order]]*<br>");
  html += wxT("sort-order ::= [ COLLATE collation-name ] [ ASC | DESC ]<br>");
  html +=
    wxT("compound_op ::= UNION | UNION ALL | INTERSECT | EXCEPT</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">UPDATE</td><td bgcolor=\"#f0fff0\">sql-statement ::= UPDATE [ OR conflict-algorithm ] [database-name .] table-name<br>");
  html += wxT("SET assignment [, assignment]*<br>");
  html += wxT("[WHERE expr]<br>");
  html += wxT("assignment ::= column-name = expr</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">VACUUM</td><td bgcolor=\"#f0fff0\">sql-statement ::= VACUUM</td></tr>");
  html += wxT("</table>");
  html += wxT("<a href=\"#index\">back to index</a>");
  html +=
    wxT
    ("<h3><a align=\"center\" bgcolor=\"#e0ffe0\" name=\"c2\">SQLite SQL functions</a></h3>");
  html += wxT("<table cellspacing=\"4\" cellpadding=\"2\" width=\"100%\">");
  html +=
    wxT
    ("<tr><td align=\"center\" bgcolor=\"#e0ffe0\" colspan=\"2\"><a name=\"c21\">ordinary functions</a><br><a href=\"#index\">back to index</a></td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">abs(X)</td><td bgcolor=\"#f0fff0\">Return the absolute value of the numeric argument X. ");
  html +=
    wxT
    ("Return NULL if X is NULL. Return 0.0 if X is not a numeric value.</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">coalesce(X,Y,...)</td><td bgcolor=\"#f0fff0\">Return a copy of the first non-NULL argument. ");
  html +=
    wxT
    ("If all arguments are NULL then NULL is returned. There must be at least 2 arguments.</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">glob(X,Y)</td><td bgcolor=\"#f0fff0\">This function is used to implement the \"X GLOB Y\" syntax of SQLite. ");
  html +=
    wxT
    ("The sqlite3_create_function() interface can be used to override this function and thereby change the operation of the GLOB operator.</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">ifnull(X,Y)</td><td bgcolor=\"#f0fff0\">Return a copy of the first non-NULL argument. ");
  html +=
    wxT
    ("If both arguments are NULL then NULL is returned. This behaves the same as coalesce().</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">hex(X)</td><td bgcolor=\"#f0fff0\">The argument is interpreted as a BLOB. ");
  html +=
    wxT
    ("The result is a hexadecimal rendering of the content of that blob.</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">last_insert_rowid()</td><td bgcolor=\"#f0fff0\">Return the ROWID of the last row insert from this connection to the database. ");
  html +=
    wxT
    ("This is the same value that would be returned from the sqlite3_last_insert_rowid() API function.</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">length(X)</td><td bgcolor=\"#f0fff0\">Return the string length of X in characters. ");
  html +=
    wxT
    ("If SQLite is configured to support UTF-8, then the number of UTF-8 characters is returned, not the number of bytes.</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">like(X,Y)<br>like(X,Y,Z)</td><td bgcolor=\"#f0fff0\">This function is used to implement the \"X LIKE Y [ESCAPE Z]\" syntax of SQL.");
  html +=
    wxT
    ("If the optional ESCAPE clause is present, then the user-function is invoked with three arguments. ");
  html += wxT("Otherwise, it is invoked with two arguments only. ");
  html +=
    wxT
    ("The sqlite3_create_function() interface can be used to override this function and thereby change the operation of the LIKE operator. ");
  html +=
    wxT
    ("When doing this, it may be important to override both the two and three argument versions of the like() function. ");
  html +=
    wxT
    ("Otherwise, different code may be called to implement the LIKE operator depending on whether or not an ESCAPE clause was specified.</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">load_extension(X)</br>load_extension(X,Y)</td><td bgcolor=\"#f0fff0\">Load SQLite extensions ");
  html +=
    wxT("out of the shared library file named X using the entry point Y. ");
  html +=
    wxT
    ("The result is a NULL. If Y is omitted then the default entry point of sqlite3_extension_init is used. ");
  html +=
    wxT
    ("This function raises an exception if the extension fails to load or initialize correctly.</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">lower(X)</td><td bgcolor=\"#f0fff0\">Return a copy of string X will all ASCII characters converted to lower case. ");
  html +=
    wxT
    ("The C library tolower() routine is used for the conversion, which means that this function might not work correctly on non-ASCII UTF-8 characters.</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">ltrim(X)<br>ltrim(X,Y)</td><td bgcolor=\"#f0fff0\">Return a string formed by removing any and all characters ");
  html +=
    wxT
    ("that appear in Y from the left side of X. If the Y argument is omitted, spaces are removed.</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">max(X,Y,...)</td><td bgcolor=\"#f0fff0\">Return the argument with the maximum value. ");
  html += wxT("Arguments may be strings in addition to numbers. ");
  html += wxT("The maximum value is determined by the usual sort order. ");
  html +=
    wxT
    ("Note that max() is a simple function when it has 2 or more arguments but converts to an aggregate function if given only a single argument.</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">min(X,Y,...)</td><td bgcolor=\"#f0fff0\">Return the argument with the minimum value. ");
  html += wxT("Arguments may be strings in addition to numbers. ");
  html += wxT("The minimum value is determined by the usual sort order. ");
  html +=
    wxT
    ("Note that min() is a simple function when it has 2 or more arguments but converts to an aggregate function if given only a single argument.</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">nullif(X,Y)</td><td bgcolor=\"#f0fff0\">Return the first argument if the arguments are different, otherwise return NULL.</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">quote(X)</td><td bgcolor=\"#f0fff0\">This routine return a string which is the value of its argument suitable for inclusion ");
  html +=
    wxT
    ("into another SQL statement. Strings are surrounded by single-quotes with escapes on interior quotes as needed. ");
  html +=
    wxT
    ("BLOBs are encoded as hexadecimal literals. The implementation of VACUUM uses this function. ");
  html +=
    wxT
    ("The function is also useful when writing triggers to implement undo/redo functionality.</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">random()</td><td bgcolor=\"#f0fff0\">Return a pseudo-random integer between -9223372036854775808 and +9223372036854775807.</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">randomblob(N)</td><td bgcolor=\"#f0fff0\">Return an N-byte blob containing pseudo-random bytes. N should be a postive integer.</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">replace(X,Y,Z)</td><td bgcolor=\"#f0fff0\">Return a string formed by substituting string Z for every occurrance of string Y in string X. ");
  html +=
    wxT("The BINARY collating sequence is used for comparisons.</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">round(X)<br>round(X,Y)</td><td bgcolor=\"#f0fff0\">Round off the number X to Y digits to the right of the decimal point. ");
  html += wxT("If the Y argument is omitted, 0 is assumed.</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">rtrim(X)<br>rtrim(X,Y)</td><td bgcolor=\"#f0fff0\">Return a string formed by removing any and all characters ");
  html +=
    wxT
    ("that appear in Y from the right side of X. If the Y argument is omitted, spaces are removed.</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">sqlite_version(X)</td><td bgcolor=\"#f0fff0\">Return the version string for the SQLite library that is running. Example: \"3.5.9\"</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">substr(X,Y,Z)<br>substr(X,Y)</td><td bgcolor=\"#f0fff0\">Return a substring of input string X that begins with the Y-th character ");
  html +=
    wxT
    ("and which is Z characters long. If Z is omitted then all character through the end of the string are returned. ");
  html += wxT("The left-most character of X is number 1. ");
  html +=
    wxT
    ("If Y is negative the the first character of the substring is found by counting from the right rather than the left. ");
  html +=
    wxT
    ("If X is string then characters indices refer to actual UTF-8 characters. If X is a BLOB then the indices refer to bytes.</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">trim(X)<br>trim(X,Y)</td><td bgcolor=\"#f0fff0\">Return a string formed by removing any and all characters that appear in Y from both ends of X. ");
  html += wxT("If the Y argument is omitted, spaces are removed.</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">typeof(X)</td><td bgcolor=\"#f0fff0\">Return the type of the expression X. ");
  html +=
    wxT
    ("The only return values are \"null\", \"integer\", \"real\", \"text\", and \"blob\".</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">upper(X)</td><td bgcolor=\"#f0fff0\">Return a copy of input string X converted to all upper-case letters. ");
  html +=
    wxT
    ("The implementation of this function uses the C library routine toupper() which means it may not work correctly on non-ASCII UTF-8 strings.</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">zeroblob(N)</td><td bgcolor=\"#f0fff0\">Return a BLOB consisting of N bytes of 0x00. ");
  html += wxT("SQLite manages these zeroblobs very efficiently. ");
  html +=
    wxT
    ("Zeroblobs can be used to reserve space for a BLOB that is later written using incremental BLOB I/O.</td></tr> ");
  html +=
    wxT
    ("<tr><td align=\"center\" bgcolor=\"#e0ffe0\" colspan=\"2\"><a name=\"c22\">aggregate functions</a><br><a href=\"#index\">back to index</a></td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">avg(X)</td><td bgcolor=\"#f0fff0\">Return the average value of all non-NULL X within a group. ");
  html +=
    wxT
    ("String and BLOB values that do not look like numbers are interpreted as 0. ");
  html +=
    wxT
    ("The result of avg() is always a floating point value even if all inputs are integers.</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">count(X)<br>count(*)</td><td bgcolor=\"#f0fff0\">The first form return a count of the number of times that X is not NULL in a group. ");
  html +=
    wxT
    ("The second form (with no argument) return the total number of rows in the group.</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">group_concat(X)<br>group_concat(X,Y)</td><td bgcolor=\"#f0fff0\">The result is a string which is the concatenation of all non-NULL values of X. ");
  html +=
    wxT
    ("If parameter Y is the separator between instances of X. A comma (\",\") is used as the separator if Y is omitted.</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">max(X)</td><td bgcolor=\"#f0fff0\">Return the maximum value of all values in the group. ");
  html +=
    wxT("The usual sort order is used to determine the maximum.</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">min(X)</td><td bgcolor=\"#f0fff0\">Return the minimum non-NULL value of all values in the group. ");
  html +=
    wxT
    ("The usual sort order is used to determine the minimum. NULL is only returned if all values in the group are NULL.</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">sum(X)<br>total(X)</td><td bgcolor=\"#f0fff0\">Return the numeric sum of all non-NULL values in the group. ");
  html +=
    wxT
    ("If there are no non-NULL input rows then sum() return NULL but total() return 0.0. ");
  html +=
    wxT
    ("NULL is not normally a helpful result for the sum of no rows but the SQL standard requires it and most other SQL ");
  html +=
    wxT
    ("database engines implement sum() that way so SQLite does it in the same way in order to be compatible. ");
  html +=
    wxT
    ("The non-standard total() function is provided as a convenient way to work around this design problem in the SQL language.<br>");
  html +=
    wxT
    ("The result of total() is always a floating point value. The result of sum() is an integer value if all non-NULL inputs are integers. ");
  html +=
    wxT
    ("If any input to sum() is neither an integer or a NULL then sum() return a floating point value which might be an approximation to the true sum.<br>");
  html +=
    wxT
    ("Sum() will throw an \"integer overflow\" exception if all inputs are integers or NULL and an integer overflow occurs at any point during the computation.");
  html += wxT("Total() never throws an exception.</td></tr> ");
  html += wxT("</table>");
  html += wxT("<a href=\"#index\">back to index</a>");
  html += wxT("<h3><a name=\"c3\">SpatiaLite SQL Spatial functions</a></h3>");
  html += wxT("<table cellspacing=\"4\" cellpadding=\"2\" width=\"100%\">");
  html +=
    wxT
    ("<tr><td align=\"center\" bgcolor=\"#e0ffe0\" colspan=\"2\"><a name=\"math\">SQL math functions</a></a>");
  html += wxT("<br><a href=\"#index\">back to index</a></td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">Abs( x Double precision ) : Double precision</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">returns the absolute value of <i>x</i></td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">Acos( x Double precision ) : Double precision</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">returns the arc cosine of <i>x</i>, that is, the value whose cosine is <i>x</i><br>");
  html += wxT("returns NULL if <i>x</i> is not in the range -1 to 1</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">Asin( x Double precision ) : Double precision</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">returns the arc sine of <i>x</i>, that is, the value whose sine is <i>x</i><br>");
  html += wxT("returns NULL if <i>x</i> is not in the range -1 to 1</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">Atan( x Double precision ) : Double precision</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">returns the arc tangent of <i>x</i>, that is, the value whose tangent is <i>x</i></td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">Ceil( x Double precision ) : Double precision<hr>");
  html += wxT("Ceiling( x Double precision ) : Double precision</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">returns the smallest integer value not less than <i>x</i></td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">Cos( x Double precision ) : Double precision</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">returns the cosine of <i>x</i>, where <i>x</i> is given in <u>radians</u></td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">Cot( x Double precision ) : Double precision</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">returns the cotangent of <i>x</i>, where <i>x</i> is given in <u>radians</u></td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">Degrees( x Double precision ) : Double precision</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">returns the argument <i>x</i>, converted from radians to degrees</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">Exp( x Double precision ) : Double precision</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">returns the value of <b><i>e</i></b> (the base of natural logarithms) raised to the power of <i>x</i><hr>");
  html +=
    wxT
    ("the inverse of this function is <i>Log()</i> (using a single argument only) or <i>Ln()</i></td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">Floor( x Double precision ) : Double precision</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">returns the largest integer value not greater than <i>x</i></td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">Ln( x Double precision ) : Double precision<hr>");
  html += wxT("Log( x Double precision ) : Double precision</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">returns the natural logarithm of <i>x</i>; that is, the base-<b><i>e</i></b> logarithm of <i>x</i><br>");
  html +=
    wxT
    ("If <i>x</i> is less than or equal to 0, then NULL is returned</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">Log( b Double precision, x Double precision ) : Double precision</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">returns the logarithm of <i>x</i> to the base <i>b</i><br>");
  html +=
    wxT
    ("If <i>x</i> is less than or equal to 0, or if <i>b</i> is less than or equal to 1, then NULL is returned<hr>");
  html +=
    wxT
    ("<i>Log(b, x)</i>  is equivalent to <i>Log(x)</i> / <i>Log(b)</i></td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">Log2( x Double precision ) : Double precision</td>");
  html +=
    wxT("<td bgcolor=\"#f0fff0\">returns the base-2 logarithm of <i>x</i><hr>");
  html +=
    wxT
    ("<i>Log2(x)</i>  is equivalent to <i>Log(x)</i> / <i>Log(2)</i></td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">Log10( x Double precision ) : Double precision</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">returns the base-10 logarithm of <i>x</i><hr>");
  html +=
    wxT
    ("<i>Log10(x)</i>  is equivalent to <i>Log(x)</i> / <i>Log(10)</i></td></tr>");
  html += wxT("<tr><td bgcolor=\"#fffff0\">PI( void ) : Double precision</td>");
  html +=
    wxT("<td bgcolor=\"#f0fff0\">returns the value of <i>PI</i></td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">Pow( x Double precision, y Double precision ) : Double precision<hr>");
  html +=
    wxT
    ("Power( x Double precision, y Double precision ) : Double precision</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">returns the value of <i>x</i> raised to the power of <i>y</i></td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">Radians( x Double precision ) : Double precision</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">returns the argument <i>x</i>, converted from degrees to radians</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">Round( x Double precision ) : Double precision</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">returns the integer value nearest to <i>x</i></td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">Sign( x Double precision ) : Double precision</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">returns the sign of the argument as -1, 0, or 1, ");
  html +=
    wxT
    ("depending on whether <i>x</i> is negative, zero, or positive.</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">Sin( x Double precision ) : Double precision</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">returns the sine of <i>x</i>, where <i>x</i> is given in <u>radians</u></td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">Sqrt( x Double precision ) : Double precision</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">returns the square root of a non-negative number <i>x</i></td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">Stddev_pop( x Double precision ) : Double precision</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">returns the population standard deviation of the input values<br>");
  html += wxT("<b><u>aggregate function</u></b></u></td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">Stddev_samp( x Double precision ) : Double precision</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">returns the sample standard deviation of the input values<br>");
  html += wxT("<b><u>aggregate function</u></b></u></td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">Tan( x Double precision ) : Double precision</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">returns the tangent of <i>x</i>, where <i>x</i> is given in <u>radians</u></td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">Var_pop( x Double precision ) : Double precision</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">returns the population variance of the input values (<i>square of the population standard deviation</i>)<br>");
  html += wxT("<b><u>aggregate function</u></b></u></td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">Var_samp( x Double precision ) : Double precision</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">returns the sample variance of the input values (<i>square of the sample standard deviation</i>)<br>");
  html += wxT("<b><u>aggregate function</u></b></u></td></tr>");
  html +=
    wxT
    ("<tr><td align=\"center\" bgcolor=\"#e0ffe0\" colspan=\"2\"><a name=\"blob\">SQL utility functions for BLOB objects</a></a>");
  html += wxT("<br><a href=\"#index\">back to index</a></td></tr>");
  html +=
    wxT("<tr><td bgcolor=\"#fffff0\">IsZipBlob( content Blob ) : Integer</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">The return type is Integer, with a return value of 1 for TRUE, 0 for FALSE, and -1 for UNKNOWN corresponding to a function invocation on NULL arguments.<br>");
  html +=
    wxT
    ("TRUE if this BLOB object corresponds to a valid ZIP-compressed file</td></tr>");
  html +=
    wxT("<tr><td bgcolor=\"#fffff0\">IsPdfBlob( content Blob ) : Integer</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">The return type is Integer, with a return value of 1 for TRUE, 0 for FALSE, and -1 for UNKNOWN corresponding to a function invocation on NULL arguments.<br>");
  html +=
    wxT
    ("TRUE if this BLOB object corresponds to a valid PDF document</td></tr>");
  html +=
    wxT("<tr><td bgcolor=\"#fffff0\">IsGifBlob( image Blob ) : Integer</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">The return type is Integer, with a return value of 1 for TRUE, 0 for FALSE, and -1 for UNKNOWN corresponding to a function invocation on NULL arguments.<br>");
  html +=
    wxT("TRUE if this BLOB object corresponds to a valid GIF image</td></tr>");
  html +=
    wxT("<tr><td bgcolor=\"#fffff0\">IsPngBlob( image Blob ) : Integer</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">The return type is Integer, with a return value of 1 for TRUE, 0 for FALSE, and -1 for UNKNOWN corresponding to a function invocation on NULL arguments.<br>");
  html +=
    wxT("TRUE if this BLOB object corresponds to a valid PNG image</td></tr>");
  html +=
    wxT("<tr><td bgcolor=\"#fffff0\">IsJpegBlob( image Blob ) : Integer</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">The return type is Integer, with a return value of 1 for TRUE, 0 for FALSE, and -1 for UNKNOWN corresponding to a function invocation on NULL arguments.<br>");
  html +=
    wxT("TRUE if this BLOB object corresponds to a valid JPEG image</td></tr>");
  html +=
    wxT("<tr><td bgcolor=\"#fffff0\">IsExifBlob( image Blob ) : Integer</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">The return type is Integer, with a return value of 1 for TRUE, 0 for FALSE, and -1 for UNKNOWN corresponding to a function invocation on NULL arguments.<br>");
  html += wxT("TRUE if this BLOB object corresponds to a valid EXIF image<br>");
  html +=
    wxT
    ("<u>Please note:</u> any valid EXIF image is a valid JPEG as well</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">IsExifGpsBlob( image Blob ) : Integer</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">The return type is Integer, with a return value of 1 for TRUE, 0 for FALSE, and -1 for UNKNOWN corresponding to a function invocation on NULL arguments.<br>");
  html +=
    wxT("TRUE if this BLOB object corresponds to a valid EXIF-GPS image<br>");
  html +=
    wxT
    ("<u>Please note:</u> any valid EXIF-GPS image is a valid EXIF and JPEG as well</td></tr>");
  html +=
    wxT
    ("<tr><td align=\"center\" bgcolor=\"#e0ffe0\" colspan=\"2\"><a name=\"c30\">SQL utility functions [<i>non-standard</i>] for geometric objects</a></a>");
  html += wxT("<br><a href=\"#index\">back to index</a></td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">GeomFromExifGpsBlob( image Blob ) : Geometry</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">a POINT Geometry will be returned representing the GPS long/lat contained within EXIF-GPS <i>metadata</i>	for the BLOB image<hr>");
  html +=
    wxT
    ("NULL will be returned if for any reason it's not possible to build such a POINT</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">MakePoint( x Double precision , y Double precision [ , SRID Integer] ) : Geometry</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">a Geometry will be returned representing the POINT defined by [x y] coordinates</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">BuildMbr( x1 Double precision , y1 Double precision , x2 Double precision , y2 Double precision, [ , SRID Integer] ) : Geometry</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">[x1 y1] and [x2 y2] are assumed to be Points identifying a line segment;");
  html +=
    wxT
    ("then a Geometry will be returned representing the MBR for this line segment</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">BuildCircleMbr( x Double precision , y Double precision , radius Double precision [ , SRID Integer] ) : Geometry</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">[x y] is assumed to be the center of a circle of given radius; then a Geometry will be returned representing the MBR for this circle</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">MbrMinX( geom Geometry) : Double precision</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">return the x-coordinate for geom MBR's leftmost side as a double precision number</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">MbrMinY( geom Geometry) : Double precision</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">return the y-coordinate for geom MBR's lowermost side as a double precision number</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">MbrMaxX( geom Geometry) : Double precision</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">return the x-coordinate for geom MBR's rightmost side as a double precision number</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">MbrMaxY( geom Geometry) : Double precision</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">return the y-coordinate for geom MBR's uppermost side as a double precision number</td></tr>");
  html +=
    wxT
    ("<tr><td align=\"center\" bgcolor=\"#e0ffe0\" colspan=\"2\"><a name=\"c31\">functions for constructing a geometric object given its Well-known Text Representation</a>");
  html += wxT("<br><a href=\"#index\">back to index</a></td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">GeomFromText( wkt String [ , SRID Integer] ) : Geometry</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">construct a geometric object given its Well-known text Representation</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">PointFromText( wktPoint String [ , SRID Integer] ) : Point</td>");
  html += wxT("<td bgcolor=\"#f0fff0\">construct a Point</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">LineFromText( wktLineString String [ , SRID Integer] ) : Linestring<hr>");
  html +=
    wxT
    ("LineStringFromText( wktLineString String [ , SRID Integer] ) : Linestring</td>");
  html += wxT("<td bgcolor=\"#f0fff0\">construct a Linestring</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">PolyFromText( wktPolygon String [ , SRID Integer] ) : Polygon<hr>");
  html +=
    wxT
    ("PolygonFromText( wktPolygon String [ , SRID Integer] ) : Polygon</td>");
  html += wxT("<td bgcolor=\"#f0fff0\">construct a Polygon</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">MPointFromText( wktMultiPoint String [ , SRID Integer] ) : MultiPoint<hr>");
  html +=
    wxT
    ("MultiPointFromText( wktMultiPoint String [ , SRID Integer] ) : MultiPoint</td>");
  html += wxT("<td bgcolor=\"#f0fff0\">construct a MultiPoint</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">MLineFromText( wktMultiLineString String [ , SRID Integer] ) : MultiLinestring<hr>");
  html +=
    wxT
    ("MultiLineStringFromText( wktMultiLineString String [ , SRID Integer] ) : MultiLinestring</td>");
  html += wxT("<td bgcolor=\"#f0fff0\">construct a MultiLinestring</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">MPolyFromText( wktMultiPolygon String [ , SRID Integer] ) : MultiPolygon<hr>");
  html +=
    wxT
    ("MultiPolygonFromText( wktMultiPolygon String [ , SRID Integer] ) : MultiPolygon</td>");
  html += wxT("<td bgcolor=\"#f0fff0\">construct a MultiPolygon</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">GeomCollFromText( wktGeometryCollection String [ , SRID Integer] ) : GeometryCollection<hr>");
  html +=
    wxT
    ("GeometryCollectionFromText( wktGeometryCollection String [ , SRID Integer] ) : GeometryCollection</td>");
  html +=
    wxT("<td bgcolor=\"#f0fff0\">construct a GeometryCollection</td></tr>");
  html +=
    wxT
    ("<tr><td align=\"center\" bgcolor=\"#e0ffe0\" colspan=\"2\"><a name=\"c32\">functions for constructing a geometric object given its Well-known Binary Representation</a>");
  html += wxT("<br><a href=\"#index\">back to index</a></td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">GeomFromWKB( wkbGeometry Binary [ , SRID Integer] ) : Geometry</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">construct a geometric object given its Well-known binary Representation</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">PointFromWKB( wkbPoint Binary [ , SRID Integer] ) : Point</td>");
  html += wxT("<td bgcolor=\"#f0fff0\">construct a Point</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">LineFromWKB( wkbLineString Binary [ , SRID Integer] ) : Linestring<hr>");
  html +=
    wxT
    ("LineStringFromText( wkbLineString Binary [ , SRID Integer] ) : Linestring</td>");
  html += wxT("<td bgcolor=\"#f0fff0\">construct a Linestring</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">PolyFromWKB( wkbPolygon Binary [ , SRID Integer] ) : Polygon<br>");
  html +=
    wxT("PolygonFromWKB( wkbPolygon Binary [ , SRID Integer] ) : Polygon</td>");
  html += wxT("<td bgcolor=\"#f0fff0\">construct a Polygon</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">MPointFromWKB( wkbMultiPoint Binary [ , SRID Integer] ) : MultiPoint<hr>");
  html +=
    wxT
    ("MultiPointFromWKB( wkbMultiPoint Binary [ , SRID Integer] ) : MultiPoint</td>");
  html += wxT("<td bgcolor=\"#f0fff0\">construct a MultiPoint</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">MLineFromWKB( wkbMultiLineString Binary [ , SRID Integer] ) : MultiLinestring<hr>");
  html +=
    wxT
    ("MultiLineStringFromWKB( wkbMultiLineString Binary [ , SRID Integer] ) : MultiLinestring</td>");
  html += wxT("<td bgcolor=\"#f0fff0\">construct a MultiLinestring</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">MPolyFromWKB( wkbMultiPolygon Binary [ , SRID Integer] ) : MultiPolygon<hr>");
  html +=
    wxT
    ("MultiPolygonFromWKB( wkbMultiPolygon Binary [ , SRID Integer] ) : MultiPolygon</td>");
  html += wxT("<td bgcolor=\"#f0fff0\">construct a MultiPolygon</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">GeomCollFromWKB( wkbGeometryCollection Binary [ , SRID Integer] ) : GeometryCollection<hr>");
  html +=
    wxT
    ("GeometryCollectionFromWKB( wkbGeometryCollection Binary [ , SRID Integer] ) : GeometryCollection</td>");
  html +=
    wxT("<td bgcolor=\"#f0fff0\">construct a GeometryCollection</td></tr>");
  html +=
    wxT
    ("<tr><td align=\"center\" bgcolor=\"#e0ffe0\" colspan=\"2\"><a name=\"c33\">functions for obtaining the Well-known Text / Well-known Binary Representation of a geometric object</a>");
  html += wxT("<br><a href=\"#index\">back to index</a></td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">AsText( geom Geometry ) : String</td><td bgcolor=\"#f0fff0\">return the Well-known Text representation</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">AsBinary( geom Geometry ) : Binary</td><td bgcolor=\"#f0fff0\">return the Well-known Binary representation</td></tr>");
  html +=
    wxT
    ("<tr><td align=\"center\" bgcolor=\"#e0ffe0\" colspan=\"2\"><a name=\"c33misc\">SQL functions supporting exotic geometric formats</a>");
  html += wxT("<br><a href=\"#index\">back to index</a></td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">AsSVG( geom Geometry ) : String</td><td bgcolor=\"#f0fff0\">returns the SVG [<i>Scalable Vector Graphics</i>] representation</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">AsFGF( geom Geometry ) : String</td><td bgcolor=\"#f0fff0\">returns the FGF [<i>FDO Geometry Binary Format</i>] representation</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">GeomFromFGF( fgfGeometry Binary [ , SRID Integer] ) : Geometry</td><td bgcolor=\"#f0fff0\">construct a geometric object given its FGF binary Representation</td></tr>");
  html +=
    wxT
    ("<tr><td align=\"center\" bgcolor=\"#e0ffe0\" colspan=\"2\"><a name=\"c34\">functions on type Geometry</a>");
  html += wxT("<br><a href=\"#index\">back to index</a></td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">Dimension( geom Geometry ) : Integer</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">return the dimension of the geometric object, which is less than or equal to the dimension of the coordinate space</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">GeometryType( geom Geometry ) : String</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">return the name of the instantiable subtype of Geometry of which this geometric object is a member, as a string</td></tr>");
  html +=
    wxT("<tr><td bgcolor=\"#fffff0\">SRID( geom Geometry ) : Integer</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">return the Spatial Reference System ID for this geometric object</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">SetSRID( geom Geometry , SRID Integer ) : Integer</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">directly sets the Spatial Reference System ID for this geometric object [no reprojection is applied].<br>");
  html +=
    wxT
    ("The return type is Integer, with a return value of 1 for TRUE, 0 for FALSE, and -1 for UNKNOWN corresponding to a ");
  html += wxT("function invocation on NULL arguments</td></tr>");
  html +=
    wxT("<tr><td bgcolor=\"#fffff0\">IsEmpty( geom Geometry ) : Integer</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">The return type is Integer, with a return value of 1 for TRUE, 0 for FALSE, and -1 for UNKNOWN corresponding to a function invocation on NULL arguments.<br>");
  html +=
    wxT("TRUE if this geometric object corresponds to the empty set</td></tr>");
  html +=
    wxT("<tr><td bgcolor=\"#fffff0\">IsSimple( geom Geometry ) : Integer</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">The return type is Integer, with a return value of 1 for TRUE, 0 for FALSE, and -1 for UNKNOWN corresponding to a function invocation on NULL arguments.<br>");
  html +=
    wxT
    ("TRUE if this geometric object is simple, as defined in the Geometry Model</td></tr>");
  html +=
    wxT("<tr><td bgcolor=\"#fffff0\">IsValid( geom Geometry ) : Integer</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">The return type is Integer, with a return value of 1 for TRUE, 0 for FALSE, and -1 for UNKNOWN corresponding to a function invocation on NULL arguments.<br>");
  html +=
    wxT
    ("TRUE if this geometric object does not contains any topological error</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">Boundary( geom Geometry ) : Geometry</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">return a geometric object that is the combinatorial boundary of g as defined in the Geometry Model</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">Envelope( geom Geometry ) : Geometry</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">return the rectangle bounding g as a Polygon. ");
  html +=
    wxT
    ("The Polygon is defined by the corner points of the bounding box [(MINX, MINY),(MAXX, MINY), (MAXX, MAXY), (MINX, MAXY), (MINX, MINY)].</td></tr>");
  html +=
    wxT
    ("<tr><td align=\"center\" bgcolor=\"#e0ffe0\" colspan=\"2\"><a name=\"c35\">functions on type Point</a>");
  html += wxT("<br><a href=\"#index\">back to index</a></td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">X( pt Point ) : Double precision</td><td bgcolor=\"#f0fff0\">return the x-coordinate of Point p as a double precision number</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">Y( pt Point ) : Double precision</td><td bgcolor=\"#f0fff0\">return the y-coordinate of Point p as a double precision number</td></tr>");
  html +=
    wxT
    ("<tr><td align=\"center\" bgcolor=\"#e0ffe0\" colspan=\"2\">functions on type Curve [Linestring or Ring]</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">StartPoint( c Curve ) : Point</td><td bgcolor=\"#f0fff0\">return a Point containing the first Point of c</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">EndPoint( c Curve ) : Point</td><td bgcolor=\"#f0fff0\">return a Point containing the last Point of c</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">NumPoints( line LineString ) : Integer</td><td bgcolor=\"#f0fff0\">return the number of Points in the LineString</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">PointN( line LineString , n Integer ) : Point</td><td bgcolor=\"#f0fff0\">return a Point containing Point n of line</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">GLength( c Curve ) : Double precision</td><td bgcolor=\"#f0fff0\">return the length of c</td></tr>");
  html += wxT("<tr><td bgcolor=\"#fffff0\">IsClosed( c Curve ) : Integer</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">The return type is Integer, with a return value of 1 for TRUE, 0 for FALSE, and -1 for UNKNOWN corresponding to a function invocation on NULL arguments<br>");
  html +=
    wxT
    ("return TRUE if c is closed, i.e., if StartPoint(c) = EndPoint(c)</td></tr>");
  html += wxT("<tr><td bgcolor=\"#fffff0\">IsRing( c Curve ) : Integer</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">The return type is Integer, with a return value of 1 for TRUE, 0 for FALSE, and -1 for UNKNOWN corresponding to a function invocation on NULL arguments<br>");
  html +=
    wxT
    ("return TRUE if c is a ring, i.e., if c is closed and simple. A simple Curve does not pass through the same Point more than once.</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">Simplify( c Curve , tolerance Double precision ) : Curve</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">return a geometric object representing a simplified version of c applying the Douglas-Peukert algorithm with given tolerance</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">SimplifyPreserveTopology( c Curve , tolerance Double precision ) : Curve</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">return a geometric object representing a simplified version of c ");
  html +=
    wxT
    ("applying the Douglas-Peukert algorithm with given tolerance and respecting topology</td></tr>");
  html +=
    wxT
    ("<tr><td align=\"center\" bgcolor=\"#e0ffe0\" colspan=\"2\"><a name=\"c36\">functions on type Surface [Polygon or Ring]</a>");
  html += wxT("<br><a href=\"#index\">back to index</a></td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">Centroid( s Surface ) : Point</td><td bgcolor=\"#f0fff0\">return the centroid of s, which may lie outside s</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">PointOnSurface( s Surface ) : Point</td><td bgcolor=\"#f0fff0\">return a Point guaranteed to lie on the Surface</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">Area( s Surface ) : Double precision</td><td bgcolor=\"#f0fff0\">return the area of s</td></tr>");
  html +=
    wxT
    ("<tr><td align=\"center\" bgcolor=\"#e0ffe0\" colspan=\"2\"><a name=\"c37\">functions on type Polygon</a>");
  html += wxT("<br><a href=\"#index\">back to index</a></td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">ExteriorRing( polyg Polygon ) : LineString</td><td bgcolor=\"#f0fff0\">return the exteriorRing of p</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">NumInteriorRing( polyg Polygon ) : Integer<hr>NumInteriorRings( polyg Polygon ) : Integer</td>");
  html +=
    wxT("<td bgcolor=\"#f0fff0\">return the number of interiorRings</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">InteriorRingN( polyg Polygon , n Integer ) : LineString</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">return the nth interiorRing. The order of Rings is not geometrically significant.</td></tr>");
  html +=
    wxT
    ("<tr><td align=\"center\" bgcolor=\"#e0ffe0\" colspan=\"2\"><a name=\"c38\">functions on type GeomCollection</a>");
  html += wxT("<br><a href=\"#index\">back to index</a></td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">NumGeometries( geom GeomCollection ) : Integer</td><td bgcolor=\"#f0fff0\">return the number of geometries</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">GeometryN( geom GeomCollection , n Integer ) : Geometry</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">return the nth geometric object in the collection. The order of the elements in the collection is not geometrically significant.</td></tr>");
  html +=
    wxT
    ("<tr><td align=\"center\" bgcolor=\"#e0ffe0\" colspan=\"2\"><a name=\"c39\">functions testing approximative spatial relationships via MBRs</a>");
  html += wxT("<br><a href=\"#index\">back to index</a></td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">MbrEqual( geom1 Geometry , geom2 Geometry ) : Integer</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">The return type is Integer, with a return value of 1 for TRUE, 0 for FALSE, and -1 for UNKNOWN corresponding to a function invocation on NULL arguments.<br>");
  html += wxT("TRUE if g1 and g2 have equal MBRs</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">MbrDisjoint( geom1 Geometry , geom2 Geometry ) : Integer</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">The return type is Integer, with a return value of 1 for TRUE, 0 for FALSE, and -1 for UNKNOWN corresponding to a function invocation on NULL arguments.<br>");
  html +=
    wxT
    ("TRUE if the intersection of g1 and g2 MBRs is the empty set</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">MbrTouches( geom1 Geometry , geom2 Geometry ) : Integer</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">The return type is Integer, with a return value of 1 for TRUE, 0 for FALSE, and -1 for UNKNOWN corresponding to a function invocation on NULL arguments.<br>");
  html +=
    wxT
    ("TRUE if the only Points in common between g1 and g2 MBRs lie in the union of the boundaries of g1 and g2</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">MbrWithin( geom1 Geometry , geom2 Geometry ) : Integer</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">The return type is Integer, with a return value of 1 for TRUE, 0 for FALSE, and -1 for UNKNOWN corresponding to a function invocation on NULL arguments.<br>");
  html += wxT("TRUE if g1 MBR is completely contained in g2 MBR</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">MbrOverlaps( geom1 Geometry , geom2 Geometry ) : Integer</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">The return type is Integer, with a return value of 1 for TRUE, 0 for FALSE, and -1 for UNKNOWN corresponding to a function invocation on NULL arguments.<br>");
  html +=
    wxT
    ("TRUE if the intersection of g1 and g2 MBRs results in a value of the same dimension as g1 and g2 that is different from both g1 and g2</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">MbrIntersects( geom1 Geometry , geom2 Geometry ) : Integer</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">The return type is Integer, with a return value of 1 for TRUE, 0 for FALSE, and -1 for UNKNOWN corresponding to a function invocation on NULL arguments<br>");
  html +=
    wxT
    ("convenience predicate: TRUE if the intersection of g1 and g2 MBRs is not empty</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">MbrContains( geom1 Geometry , geom2 Geometry ) : Integer</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">The return type is Integer, with a return value of 1 for TRUE, 0 for FALSE, and -1 for UNKNOWN corresponding to a function invocation on NULL arguments<br>");
  html +=
    wxT
    ("convenience predicate: TRUE if g2 MBR is completely contained in g1 MBR</td></tr>");
  html +=
    wxT
    ("<tr><td align=\"center\" bgcolor=\"#e0ffe0\" colspan=\"2\"><a name=\"c40\">functions testing spatial relationships</a>");
  html += wxT("<br><a href=\"#index\">back to index</a></td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">Equals( geom1 Geometry , geom2 Geometry ) : Integer</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">The return type is Integer, with a return value of 1 for TRUE, 0 for FALSE, and -1 for UNKNOWN corresponding to a function invocation on NULL arguments.<br>");
  html += wxT("TRUE if g1 and g2 are equal</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">Disjoint( geom1 Geometry , geom2 Geometry ) : Integer</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">The return type is Integer, with a return value of 1 for TRUE, 0 for FALSE, and -1 for UNKNOWN corresponding to a function invocation on NULL arguments.<br>");
  html +=
    wxT("TRUE if the intersection of g1 and g2 is the empty set</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">Touches( geom1 Geometry , geom2 Geometry ) : Integer</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">The return type is Integer, with a return value of 1 for TRUE, 0 for FALSE, and -1 for UNKNOWN corresponding to a function invocation on NULL arguments.<br>");
  html +=
    wxT
    ("TRUE if the only Points in common between g1 and g2 lie in the union of the boundaries of g1 and g2</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">Within( geom1 Geometry , geom2 Geometry ) : Integer</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">The return type is Integer, with a return value of 1 for TRUE, 0 for FALSE, and -1 for UNKNOWN corresponding to a function invocation on NULL arguments.<br>");
  html += wxT("TRUE if g1 is completely contained in g2</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">Overlaps( geom1 Geometry , geom2 Geometry ) : Integer</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">The return type is Integer, with a return value of 1 for TRUE, 0 for FALSE, and -1 for UNKNOWN corresponding to a function invocation on NULL arguments.<br>");
  html +=
    wxT
    ("TRUE if the intersection of g1 and g2 results in a value of the same dimension as g1 and g2 that is different from both g1 and g2</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">Crosses( geom1 Geometry , geom2 Geometry ) : Integer</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">The return type is Integer, with a return value of 1 for TRUE, 0 for FALSE, and -1 for UNKNOWN corresponding to a function invocation on NULL arguments.<br>");
  html +=
    wxT
    ("TRUE if the intersection of g1 and g2 results in a value whose dimension is less than the maximum dimension of g1 and g2 ");
  html +=
    wxT
    ("and the intersection value includes Points interior to both g1 and g2, and the intersection value is not equal to either g1 or g2</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">Intersects( geom1 Geometry , geom2 Geometry ) : Integer</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">The return type is Integer, with a return value of 1 for TRUE, 0 for FALSE, and -1 for UNKNOWN corresponding to a function invocation on NULL arguments<br>");
  html +=
    wxT
    ("convenience predicate: TRUE if the intersection of g1 and g2 is not empty</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">Contains( geom1 Geometry , geom2 Geometry ) : Integer</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">The return type is Integer, with a return value of 1 for TRUE, 0 for FALSE, and -1 for UNKNOWN corresponding to a function invocation on NULL arguments<br>");
  html +=
    wxT
    ("convenience predicate: TRUE if g2 is completely contained in g1</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">Relate( geom1 Geometry , geom2 Geometry , patternMatrix String ) : Integer</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">The return type is Integer, with a return value of 1 for TRUE, 0 for FALSE, and -1 for UNKNOWN corresponding to a function invocation on NULL arguments.<br>");
  html +=
    wxT
    ("return TRUE if the spatial relationship specified by the patternMatrix holds</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">Distance( geom1 Geometry , geom2 Geometry ) : Double precision</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">return the distance between geom1 and geom2</td></tr>");
  html +=
    wxT
    ("<tr><td align=\"center\" bgcolor=\"#e0ffe0\" colspan=\"2\"><a name=\"c41\">functions implementing spatial operators</a>");
  html += wxT("<br><a href=\"#index\">back to index</a></td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">Intersection( geom1 Geometry , geom2 Geometry ) : Geometry</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">return a geometric object that is the intersection of geometric objects geom1 and geom2</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">Difference( geom1 Geometry , geom2 Geometry ) : Geometry</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">return a geometric object that is the closure of the set difference of geom1 and geom2</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">GUnion( geom1 Geometry , geom2 Geometry ) : Geometry</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">return a geometric object that is the set union of geom1 and geom2</td></tr>");
  html +=
    wxT("<tr><td bgcolor=\"#fffff0\">GUnion( geom Geometry ) : Geometry</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">return a geometric object that is the set union of input values<br>");
  html += wxT("<b><u>aggregate function</u></b></td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">SymDifference( geom1 Geometry , geom2 Geometry ) : Geometry</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">return a geometric object that is the closure of the set symmetric difference of geom1 and geom2 (logical XOR of space)</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">Buffer( geom Geometry , dist Double precision ) : Geometry</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">return a geometric object defined by buffering a distance d around geom, ");
  html +=
    wxT
    ("where dist is in the distance units for the Spatial Reference of geom</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">ConvexHull( geom Geometry ) : Geometry</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">return a geometric object that is the convex hull of geom</td></tr>");
  html +=
    wxT
    ("<tr><td align=\"center\" bgcolor=\"#e0ffe0\" colspan=\"2\"><a name=\"c42\">functions for coordinate transformations</a>");
  html += wxT("<br><a href=\"#index\">back to index</a></td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">Transform( geom Geometry , newSRID Integer ) : Geometry</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">return a geometric object obtained by reprojecting coordinates into the Reference System identified by newSRID</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">ShiftCoords( geom Geometry , shiftX Double precision , shiftY Double precision ) : Geometry<hr>");
  html +=
    wxT
    ("ShiftCoordinates( geom Geometry , shiftX Double precision , shiftY Double precision ) : Geometry</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">return a geometric object obtained by translating coordinates according to shiftX and shiftY values</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">ScaleCoords( geom Geometry , scaleX Double precision [ , scaleY Double precision ] ) : Geometry<hr>");
  html +=
    wxT
    ("ScaleCoordinates( geom Geometry , scaleX Double precision [ , scaleY Double precision ] ) : Geometry</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">return a geometric object obtained by scaling coordinates according to scaleX and scaleY values<br>");
  html +=
    wxT
    ("if only one scale factor is specified, then an isotropic scaling occurs [i.e. the same scale factor is applied to both axis]");
  html +=
    wxT
    ("otherwise an anisotropic scaling occurs [i.e. each axis is scaled according to its own scale factor]</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">RotateCoords( geom Geometry , angleInDegrees Double precision ) : Geometry<hr>");
  html +=
    wxT
    ("RotateCoordinates( geom Geometry , angleInDegrees Double precision ) : Geometry</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">return a geometric object obtained by rotating coordinates according to angleInDegrees value</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">ReflectCoords( geom Geometry , xAxis Integer , yAxis Integer ) : Geometry<hr>");
  html +=
    wxT
    ("ReflectCoordinates( geom Geometry , xAxis Integer , yAxis Integer ) : Geometry</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">return a geometric object obtained by reflecting coordinates according to xAxis and yAxis switches<br>");
  html +=
    wxT
    ("i.e. if xAxis is 0 (FALSE), then x-coordinates remains untouched; otherwise x-coordinates will be reflected</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">SwapCoords( geom Geometry ) : Geometry<hr>SwapCoordinates( geom Geometry ) : Geometry</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">return a geometric object obtained by swapping x- and y-coordinates</td></tr>");
  html +=
    wxT
    ("<tr><td align=\"center\" bgcolor=\"#e0ffe0\" colspan=\"2\"><a name=\"c43\">functions for Spatial-MetaData and Spatial-Index handling</a>");
  html += wxT("<br><a href=\"#index\">back to index</a></td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">InitSpatialMetaData( void ) : Integer</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">Creates the geometry_columns and spatial_ref_sys metadata tables");
  html +=
    wxT
    ("the return type is Integer, with a return value of 1 for TRUE or 0 for FALSE<br>");
  html +=
    wxT
    ("direct invocation of these function is discouraged; you have to run the init_spatialite.sql ");
  html +=
    wxT
    ("script in order to fully initialize the Spatial MetaData tables</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">AddGeometryColumn( table String , column String , srid Integer , geom_type String , dimension Integer [ , not_null Integer ] ) : Integer</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">Creates a new geometry column updating the Spatial Metadata tables and creating any required trigger in order to enforce constraints<br>");
  html +=
    wxT
    ("the return type is Integer, with a return value of 1 for TRUE or 0 for FALSE</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">RecoverGeometryColumn( table String , column String , srid Integer , geom_type String , dimension Integer ) : Integer</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">Validates an existing ordinary column in order to possibly transform it in a real geometry column, ");
  html +=
    wxT
    ("thus updating the Spatial Metadata tables and creating any required trigger in order to enforce constraints<br>");
  html +=
    wxT
    ("the return type is Integer, with a return value of 1 for TRUE or 0 for FALSE</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">DiscardGeometryColumn( table String , column String ) : Integer</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">Removes a geometry column from Spatial MetaData tables and drops any related trigger<br>");
  html +=
    wxT
    ("the column itself still continues to exist untouched as an ordinary, unconstrained column<br>");
  html +=
    wxT
    ("the return type is Integer, with a return value of 1 for TRUE or 0 for FALSE</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">CreateSpatialIndex( table String , column String ) : Integer</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">Builds an RTree Spatial Index on a geometry column, ");
  html +=
    wxT
    ("creating any required trigger required in order to enforce full data coherency between the main table and Spatial Index<br>");
  html +=
    wxT
    ("the return type is Integer, with a return value of 1 for TRUE or 0 for FALSE</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">DisableSpatialIndex( table String , column String ) : Integer</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">Disables an RTree Spatial Index, removing any related trigger<br>");
  html +=
    wxT
    ("the return type is Integer, with a return value of 1 for TRUE or 0 for FALSE</td></tr>");
  html +=
    wxT
    ("<tr><td align=\"center\" bgcolor=\"#e0ffe0\" colspan=\"2\"><a name=\"c43fdo\">functions implementing FDO/OGR compatibily</a>");
  html += wxT("<br><a href=\"#index\">back to index</a></td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">CheckSpatialMetaData( void ) : Integer</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">Checks the Spatial Metadata type, then returning:<br>");
  html +=
    wxT
    ("<b>0</b> if <i>geometry_columns</i> and <i>spatial_ref_sys</i> tables does not exists<br>");
  html +=
    wxT
    ("<b>1</b> if both tables exist, and their layout is the one used by <i>SpatiaLite</i><br>");
  html +=
    wxT
    ("<b>2</b> if both tables exist, and their layout is the one used by <i>FDO/OGR</i></td></tr>");
  html +=
    wxT("<tr><td bgcolor=\"#fffff0\">AutoFDOStart( void ) : Integer</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">This function will inspect the Spatial Metadata, then automatically creating/refreshing a <i>VirtualFDO</i>");
  html +=
    wxT
    (" wrapper for each FDO/OGR geometry table<br>the return type is Integer [how many VirtualFDO tables have been created]</td></tr>");
  html += wxT("<tr><td bgcolor=\"#fffff0\">AutoFDOStop( void ) : Integer</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">This function will inspect the Spatial Metadata, then automatically destroying any <i>VirtualFDO</i>");
  html +=
    wxT
    (" wrapper found<br>the return type is Integer [how many VirtualFDO tables have been destroyed]</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">InitFDOSpatialMetaData( void ) : Integer</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">Creates the geometry_columns and spatial_ref_sys metadata tables");
  html +=
    wxT
    ("the return type is Integer, with a return value of 1 for TRUE or 0 for FALSE<br>");
  html +=
    wxT
    ("<u>Please note:</u> Spatial Metadata created using this function will have the FDO/OGR layout, and not the SpatiaLite's own</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">AddFDOGeometryColumn( table String , column String , srid Integer , geom_type String , dimension Integer , geometry_type String ) : Integer</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">Creates a new geometry column updating the FDO/OGR Spatial Metadata tables<br>");
  html +=
    wxT
    ("the return type is Integer, with a return value of 1 for TRUE or 0 for FALSE</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">RecoverFDOGeometryColumn( table String , column String , srid Integer , geom_type String , dimension Integer , geometry_type String ) : Integer</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">Validates an existing ordinary column in order to possibly transform it in a real geometry column, ");
  html += wxT("thus updating the FDO/OGR Spatial Metadata tables<br>");
  html +=
    wxT
    ("the return type is Integer, with a return value of 1 for TRUE or 0 for FALSE</td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">DiscardFDOGeometryColumn( table String , column String ) : Integer</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">Removes a geometry column from FDO/OGR Spatial MetaData tables<br>");
  html +=
    wxT
    ("the column itself still continues to exist untouched as an ordinary column<br>");
  html +=
    wxT
    ("the return type is Integer, with a return value of 1 for TRUE or 0 for FALSE</td></tr>");
  html +=
    wxT
    ("<tr><td align=\"center\" bgcolor=\"#e0ffe0\" colspan=\"2\"><a name=\"c44\">functions for MbrCache-based queries</a>");
  html += wxT("<br><a href=\"#index\">back to index</a></td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">FilterMbrWithin( x1 Double precision , y1 Double precision , x2 Double precision , y2 Double precision  ) : Integer</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">Retrieves from an MbrCache any entity whose MBR falls <u><i>within</i></u>");
  html +=
    wxT
    (" the rectangle identified by extreme points <i>x1 y1</i> and <i>x2 y2</i></td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">FilterMbrContains( x1 Double precision , y1 Double precision , x2 Double precision , y2 Double precision  ) : Integer</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">Retrieves from an MbrCache any entity whose MBR <u><i>contains</i></u>");
  html +=
    wxT
    (" the rectangle identified by extreme points <i>x1 y1</i> and <i>x2 y2</i></td></tr>");
  html +=
    wxT
    ("<tr><td bgcolor=\"#fffff0\">FilterMbrIntersects( x1 Double precision , y1 Double precision , x2 Double precision , y2 Double precision  ) : Integer</td>");
  html +=
    wxT
    ("<td bgcolor=\"#f0fff0\">Retrieves from an MbrCache any entity whose MBR <u><i>intersects</i></u>");
  html +=
    wxT
    (" the rectangle identified by extreme points <i>x1 y1</i> and <i>x2 y2</i></td></tr>");


  html += wxT("</table>");
  html += wxT("<a href=\"#index\">back to index</a>");
  html += wxT("</body>");
  html += wxT("</html>");
}

Changes to Makefile-MinGW.

1
2
3
4

5
6

7
8
9
10
11
12
13
14


15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
..
31
32
33
34
35
36
37



38
39
40
41
42
43
44
45
46






47
48
49
50
51



52
53
54
# SandroFurieri (c) 2008
# Makefile ( Mingw & wxwidgets) for spatialite-GUI

SRC = Main.cpp TableTree.cpp QueryView.cpp BlobExplorer.cpp Dialogs.cpp \

	Shapefiles.cpp TextCsv.cpp Objects.cpp win_resource/resource.rc
OBJ = Main.o TableTree.o QueryView.o BlobExplorer.o Dialogs.o Shapefiles.o \

	TextCsv.o Objects.o win_resource/resource.o 
EXE = ./bin/spatialite-gui.exe
INCLUDE = Classdef.h 

# Define default flags:
CXXFLAGS = $(shell wx-config --cxxflags) 
LIB = $(shell wx-config --libs)
EXTRAFLAGS = -O3 -march=i686 -Wall -Wundef -Wno-ctor-dtor-privacy  -fno-strict-aliasing -I/usr/local/include 


REZ = $(shell wx-config --rescomp)
EXTRALIBS = /usr/local/lib/libspatialite.a /usr/local/lib/libsqlite3.a \
	/usr/local/lib/libgeos_c.a /usr/local/lib/libiconv.a \
	/usr/local/lib/libgeos.a /usr/local/lib/libproj.a 

all: $(EXE)

$(EXE): $(OBJ)
	$(CXX) $(OBJ) -o $(EXE) $(LIB) $(EXTRALIBS)
	strip --strip-all  $(EXE)

clean :
	$(RM) $(OBJ) $(EXE)
	
Main.o: Main.cpp $(INCLUDE)
................................................................................

TableTree.o: TableTree.cpp $(INCLUDE)
	$(CXX) -c TableTree.cpp $(CXXFLAGS) $(EXTRAFLAGS)

QueryView.o: QueryView.cpp $(INCLUDE)
	$(CXX) -c QueryView.cpp $(CXXFLAGS) $(EXTRAFLAGS)




BlobExplorer.o: BlobExplorer.cpp $(INCLUDE)
	$(CXX) -c BlobExplorer.cpp $(CXXFLAGS) $(EXTRAFLAGS)

Dialogs.o: Dialogs.cpp $(INCLUDE)
	$(CXX) -c Dialogs.cpp $(CXXFLAGS) $(EXTRAFLAGS)

Shapefiles.o: Shapefiles.cpp $(INCLUDE)
	$(CXX) -c Shapefiles.cpp $(CXXFLAGS) $(EXTRAFLAGS)







TextCsv.o: TextCsv.cpp $(INCLUDE)
	$(CXX) -c TextCsv.cpp $(CXXFLAGS) $(EXTRAFLAGS)

Objects.o: Objects.cpp $(INCLUDE)
	$(CXX) -c Objects.cpp $(CXXFLAGS) $(EXTRAFLAGS)



		
win_resource/resource.o: win_resource/resource.rc
	$(REZ) -i win_resource/resource.rc -o win_resource/resource.o 



|
>
|
|
>
|






|
>
>
|
|
|
|



|







 







>
>
>









>
>
>
>
>
>





>
>
>



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
..
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# SandroFurieri (c) 2008
# Makefile ( Mingw & wxwidgets) for spatialite-GUI

SRC = Main.cpp TableTree.cpp QueryView.cpp ResultSetView.cpp BlobExplorer.cpp \
	Dialogs.cpp Shapefiles.cpp Network.cpp Exif.cpp TextCsv.cpp Objects.cpp \
	MetadataInit.cpp win_resource/resource.rc
OBJ = Main.o TableTree.o QueryView.o ResultSetView.o BlobExplorer.o \
	Dialogs.o Shapefiles.o Network.o Exif.o TextCsv.o Objects.o \
	MetadataInit.o win_resource/resource.o 
EXE = ./bin/spatialite-gui.exe
INCLUDE = Classdef.h 

# Define default flags:
CXXFLAGS = $(shell wx-config --cxxflags) 
LIB = $(shell wx-config --libs)
EXTRAFLAGS = -O3 -march=i686 -Wall -Wundef -Wno-ctor-dtor-privacy \
	-fno-strict-aliasing -I/usr/local/include -D_LARGE_FILE=1 \
	-D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE=1
REZ = $(shell wx-config --rescomp)
EXTRALIBS = /usr/local/lib/libspatialite.a /usr/local/lib/libgeos_c.a \
	/usr/local/lib/libiconv.a /usr/local/lib/libgeos.a \
	/usr/local/lib/libproj.a 

all: $(EXE)

$(EXE): $(OBJ) $(EXTRALIBS)
	$(CXX) $(OBJ) -o $(EXE) $(LIB) $(EXTRALIBS)
	strip --strip-all  $(EXE)

clean :
	$(RM) $(OBJ) $(EXE)
	
Main.o: Main.cpp $(INCLUDE)
................................................................................

TableTree.o: TableTree.cpp $(INCLUDE)
	$(CXX) -c TableTree.cpp $(CXXFLAGS) $(EXTRAFLAGS)

QueryView.o: QueryView.cpp $(INCLUDE)
	$(CXX) -c QueryView.cpp $(CXXFLAGS) $(EXTRAFLAGS)

ResultSetView.o: ResultSetView.cpp $(INCLUDE)
	$(CXX) -c ResultSetView.cpp $(CXXFLAGS) $(EXTRAFLAGS)

BlobExplorer.o: BlobExplorer.cpp $(INCLUDE)
	$(CXX) -c BlobExplorer.cpp $(CXXFLAGS) $(EXTRAFLAGS)

Dialogs.o: Dialogs.cpp $(INCLUDE)
	$(CXX) -c Dialogs.cpp $(CXXFLAGS) $(EXTRAFLAGS)

Shapefiles.o: Shapefiles.cpp $(INCLUDE)
	$(CXX) -c Shapefiles.cpp $(CXXFLAGS) $(EXTRAFLAGS)

Network.o: Network.cpp $(INCLUDE)
	$(CXX) -c Network.cpp $(CXXFLAGS) $(EXTRAFLAGS)

Exif.o: Exif.cpp $(INCLUDE)
	$(CXX) -c Exif.cpp $(CXXFLAGS) $(EXTRAFLAGS)

TextCsv.o: TextCsv.cpp $(INCLUDE)
	$(CXX) -c TextCsv.cpp $(CXXFLAGS) $(EXTRAFLAGS)

Objects.o: Objects.cpp $(INCLUDE)
	$(CXX) -c Objects.cpp $(CXXFLAGS) $(EXTRAFLAGS)

MetadataInit.o: MetadataInit.cpp $(INCLUDE)
	$(CXX) -c MetadataInit.cpp $(CXXFLAGS) $(EXTRAFLAGS)
		
win_resource/resource.o: win_resource/resource.rc
	$(REZ) -i win_resource/resource.rc -o win_resource/resource.o 

Changes to Makefile-OsX.

1
2
3
4
5

6
7
8
9
10
11
12
13
14


15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
..
31
32
33
34
35
36
37



38
39
40
41
42
43
44
45
46






47
48
49
50
51
52



# SandroFurieri (c) 2008
# Makefile ( wxwidgets MacOsX) for spatialite-GUI

SRC = Main.cpp TableTree.cpp QueryView.cpp BlobExplorer.cpp Dialogs.cpp \
	Shapefiles.cpp TextCsv.cpp Objects.cpp 

OBJ = Main.o TableTree.o QueryView.o BlobExplorer.o Dialogs.o Shapefiles.o \
	TextCsv.o Objects.o 
EXE = ./bin/spatialite-gui
INCLUDE = Classdef.h 

# Define default flags:
CXXFLAGS = $(shell wx-config --cxxflags) 
LIB = $(shell wx-config --libs)
EXTRAFLAGS = -O3 -Wall -Wundef -Wno-ctor-dtor-privacy  -fno-strict-aliasing -I/usr/local/include 


EXTRALIBS = /usr/local/lib/libspatialite.a /usr/local/lib/libsqlite3.a \
	/usr/local/lib/libgeos_c.a /usr/local/lib/libgeos.a \
	/usr/local/lib/libproj.a \
	-liconv

all: $(EXE)

$(EXE): $(OBJ)
	$(CXX) $(OBJ) -o $(EXE) $(LIB) $(EXTRALIBS)
	strip $(EXE)

clean :
	$(RM) $(OBJ) $(EXE)
	
Main.o: Main.cpp $(INCLUDE)
	$(CXX) -c Main.cpp $(CXXFLAGS) $(EXTRAFLAGS)
................................................................................

TableTree.o: TableTree.cpp $(INCLUDE)
	$(CXX) -c TableTree.cpp $(CXXFLAGS) $(EXTRAFLAGS)

QueryView.o: QueryView.cpp $(INCLUDE)
	$(CXX) -c QueryView.cpp $(CXXFLAGS) $(EXTRAFLAGS)




BlobExplorer.o: BlobExplorer.cpp $(INCLUDE)
	$(CXX) -c BlobExplorer.cpp $(CXXFLAGS) $(EXTRAFLAGS)

Dialogs.o: Dialogs.cpp $(INCLUDE)
	$(CXX) -c Dialogs.cpp $(CXXFLAGS) $(EXTRAFLAGS)

Shapefiles.o: Shapefiles.cpp $(INCLUDE)
	$(CXX) -c Shapefiles.cpp $(CXXFLAGS) $(EXTRAFLAGS)







TextCsv.o: TextCsv.cpp $(INCLUDE)
	$(CXX) -c TextCsv.cpp $(CXXFLAGS) $(EXTRAFLAGS)

Objects.o: Objects.cpp $(INCLUDE)
	$(CXX) -c Objects.cpp $(CXXFLAGS) $(EXTRAFLAGS)
		






|
|
>
|
|






|
>
>
|
|
<
|



|
|







 







>
>
>









>
>
>
>
>
>





|
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

20
21
22
23
24
25
26
27
28
29
30
31
32
..
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# SandroFurieri (c) 2008
# Makefile ( wxwidgets MacOsX) for spatialite-GUI

SRC = Main.cpp TableTree.cpp QueryView.cpp ResultSetView.cpp BlobExplorer.cpp \
	Dialogs.cpp Shapefiles.cpp Network.cpp Exif.cpp TextCsv.cpp Objects.cpp \
	MetadataInit.cpp
OBJ = Main.o TableTree.o QueryView.o ResultSetView.o BlobExplorer.o Dialogs.o \
	Shapefiles.o Network.o Exif.o TextCsv.o Objects.o MetadataInit.o 
EXE = ./bin/spatialite-gui
INCLUDE = Classdef.h 

# Define default flags:
CXXFLAGS = $(shell wx-config --cxxflags) 
LIB = $(shell wx-config --libs)
EXTRAFLAGS = -O3 -Wall -Wundef -Wno-ctor-dtor-privacy \
	-fno-strict-aliasing -I/usr/local/include -D_LARGE_FILE=1 \
	-D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE=1
EXTRALIBS = /usr/local/lib/libspatialite.a /usr/local/lib/libgeos_c.a \
	/usr/local/lib/libgeos.a /usr/local/lib/libproj.a

EXTRALIB2 = -liconv

all: $(EXE)

$(EXE): $(OBJ) $(EXTRALIBS)
	$(CXX) $(OBJ) -o $(EXE) $(LIB) $(EXTRALIBS) $(EXTRALIB2)
	strip $(EXE)

clean :
	$(RM) $(OBJ) $(EXE)
	
Main.o: Main.cpp $(INCLUDE)
	$(CXX) -c Main.cpp $(CXXFLAGS) $(EXTRAFLAGS)
................................................................................

TableTree.o: TableTree.cpp $(INCLUDE)
	$(CXX) -c TableTree.cpp $(CXXFLAGS) $(EXTRAFLAGS)

QueryView.o: QueryView.cpp $(INCLUDE)
	$(CXX) -c QueryView.cpp $(CXXFLAGS) $(EXTRAFLAGS)

ResultSetView.o: ResultSetView.cpp $(INCLUDE)
	$(CXX) -c ResultSetView.cpp $(CXXFLAGS) $(EXTRAFLAGS)

BlobExplorer.o: BlobExplorer.cpp $(INCLUDE)
	$(CXX) -c BlobExplorer.cpp $(CXXFLAGS) $(EXTRAFLAGS)

Dialogs.o: Dialogs.cpp $(INCLUDE)
	$(CXX) -c Dialogs.cpp $(CXXFLAGS) $(EXTRAFLAGS)

Shapefiles.o: Shapefiles.cpp $(INCLUDE)
	$(CXX) -c Shapefiles.cpp $(CXXFLAGS) $(EXTRAFLAGS)

Network.o: Network.cpp $(INCLUDE)
	$(CXX) -c Network.cpp $(CXXFLAGS) $(EXTRAFLAGS)

Exif.o: Exif.cpp $(INCLUDE)
	$(CXX) -c Exif.cpp $(CXXFLAGS) $(EXTRAFLAGS)

TextCsv.o: TextCsv.cpp $(INCLUDE)
	$(CXX) -c TextCsv.cpp $(CXXFLAGS) $(EXTRAFLAGS)

Objects.o: Objects.cpp $(INCLUDE)
	$(CXX) -c Objects.cpp $(CXXFLAGS) $(EXTRAFLAGS)

MetadataInit.o: MetadataInit.cpp $(INCLUDE)
	$(CXX) -c MetadataInit.cpp $(CXXFLAGS) $(EXTRAFLAGS)
		

Changes to Makefile-linux32.

1
2
3
4
5

6
7
8
9
10
11
12
13
14


15
16
17
18
19
20
21
22
23
24
25
26
27
28
..
30
31
32
33
34
35
36



37
38
39
40
41
42
43
44
45






46
47
48
49
50
51


# SandroFurieri (c) 2008
# Makefile ( wxwidgets GTK) for spatialite-GUI

SRC = Main.cpp TableTree.cpp QueryView.cpp BlobExplorer.cpp Dialogs.cpp \
	Shapefiles.cpp TextCsv.cpp Objects.cpp 

OBJ = Main.o TableTree.o QueryView.o BlobExplorer.o Dialogs.o Shapefiles.o \
	TextCsv.o Objects.o 
EXE = ./bin/spatialite-gui
INCLUDE = Classdef.h 

# Define default flags:
CXXFLAGS = $(shell wx-config --cxxflags) 
LIB = $(shell wx-config --libs)
EXTRAFLAGS = -O3 -march=i686 -Wall -Wundef -Wno-ctor-dtor-privacy  -fno-strict-aliasing -I/usr/local/include 


EXTRALIBS = /usr/local/lib/libspatialite.a /usr/local/lib/libsqlite3.a \
	/usr/local/lib/libgeos_c.a /usr/local/lib/libgeos.a \
	/usr/local/lib/libproj.a 

all: $(EXE)

$(EXE): $(OBJ)
	$(CXX) $(OBJ) -o $(EXE) $(LIB) $(EXTRALIBS)
	strip --strip-all  $(EXE)

clean :
	$(RM) $(OBJ) $(EXE)
	
Main.o: Main.cpp $(INCLUDE)
................................................................................

TableTree.o: TableTree.cpp $(INCLUDE)
	$(CXX) -c TableTree.cpp $(CXXFLAGS) $(EXTRAFLAGS)

QueryView.o: QueryView.cpp $(INCLUDE)
	$(CXX) -c QueryView.cpp $(CXXFLAGS) $(EXTRAFLAGS)




BlobExplorer.o: BlobExplorer.cpp $(INCLUDE)
	$(CXX) -c BlobExplorer.cpp $(CXXFLAGS) $(EXTRAFLAGS)

Dialogs.o: Dialogs.cpp $(INCLUDE)
	$(CXX) -c Dialogs.cpp $(CXXFLAGS) $(EXTRAFLAGS)

Shapefiles.o: Shapefiles.cpp $(INCLUDE)
	$(CXX) -c Shapefiles.cpp $(CXXFLAGS) $(EXTRAFLAGS)







TextCsv.o: TextCsv.cpp $(INCLUDE)
	$(CXX) -c TextCsv.cpp $(CXXFLAGS) $(EXTRAFLAGS)

Objects.o: Objects.cpp $(INCLUDE)
	$(CXX) -c Objects.cpp $(CXXFLAGS) $(EXTRAFLAGS)
		





|
|
>
|
|






|
>
>
|
|
<



|







 







>
>
>









>
>
>
>
>
>





|
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

20
21
22
23
24
25
26
27
28
29
30
..
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# SandroFurieri (c) 2008
# Makefile ( wxwidgets GTK) for spatialite-GUI

SRC = Main.cpp TableTree.cpp QueryView.cpp ResultSetView.cpp BlobExplorer.cpp \
	Dialogs.cpp Shapefiles.cpp Network.cpp Exif.cpp TextCsv.cpp Objects.cpp \
	MetadataInit.cpp
OBJ = Main.o TableTree.o QueryView.o ResultSetView.o BlobExplorer.o Dialogs.o \
	Shapefiles.o Network.o Exif.o TextCsv.o Objects.o MetadataInit.o 
EXE = ./bin/spatialite-gui
INCLUDE = Classdef.h 

# Define default flags:
CXXFLAGS = $(shell wx-config --cxxflags) 
LIB = $(shell wx-config --libs)
EXTRAFLAGS = -O3 -march=i686 -Wall -Wundef -Wno-ctor-dtor-privacy \
	-fno-strict-aliasing -I/usr/local/include -D_LARGE_FILE=1 \
	-D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE=1
EXTRALIBS = /usr/local/lib/libspatialite.a /usr/local/lib/libgeos_c.a \
	/usr/local/lib/libgeos.a /usr/local/lib/libproj.a 


all: $(EXE)

$(EXE): $(OBJ) $(EXTRALIBS)
	$(CXX) $(OBJ) -o $(EXE) $(LIB) $(EXTRALIBS)
	strip --strip-all  $(EXE)

clean :
	$(RM) $(OBJ) $(EXE)
	
Main.o: Main.cpp $(INCLUDE)
................................................................................

TableTree.o: TableTree.cpp $(INCLUDE)
	$(CXX) -c TableTree.cpp $(CXXFLAGS) $(EXTRAFLAGS)

QueryView.o: QueryView.cpp $(INCLUDE)
	$(CXX) -c QueryView.cpp $(CXXFLAGS) $(EXTRAFLAGS)

ResultSetView.o: ResultSetView.cpp $(INCLUDE)
	$(CXX) -c ResultSetView.cpp $(CXXFLAGS) $(EXTRAFLAGS)

BlobExplorer.o: BlobExplorer.cpp $(INCLUDE)
	$(CXX) -c BlobExplorer.cpp $(CXXFLAGS) $(EXTRAFLAGS)

Dialogs.o: Dialogs.cpp $(INCLUDE)
	$(CXX) -c Dialogs.cpp $(CXXFLAGS) $(EXTRAFLAGS)

Shapefiles.o: Shapefiles.cpp $(INCLUDE)
	$(CXX) -c Shapefiles.cpp $(CXXFLAGS) $(EXTRAFLAGS)

Network.o: Network.cpp $(INCLUDE)
	$(CXX) -c Network.cpp $(CXXFLAGS) $(EXTRAFLAGS)

Exif.o: Exif.cpp $(INCLUDE)
	$(CXX) -c Exif.cpp $(CXXFLAGS) $(EXTRAFLAGS)

TextCsv.o: TextCsv.cpp $(INCLUDE)
	$(CXX) -c TextCsv.cpp $(CXXFLAGS) $(EXTRAFLAGS)

Objects.o: Objects.cpp $(INCLUDE)
	$(CXX) -c Objects.cpp $(CXXFLAGS) $(EXTRAFLAGS)

MetadataInit.o: MetadataInit.cpp $(INCLUDE)
	$(CXX) -c MetadataInit.cpp $(CXXFLAGS) $(EXTRAFLAGS)	

Added MetadataInit.cpp.

more than 10,000 changes

Added Network.cpp.







































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
/*
/ Network.cpp
/ methods related to Network building
/
/ version 1.2, 2008 October 9
/
/ Author: Sandro Furieri a-furieri@lqt.it
/
/ Copyright (C) 2008  Alessandro Furieri
/
/    This program is free software: you can redistribute it and/or modify
/    it under the terms of the GNU General Public License as published by
/    the Free Software Foundation, either version 3 of the License, or
/    (at your option) any later version.
/
/    This program is distributed in the hope that it will be useful,
/    but WITHOUT ANY WARRANTY; without even the implied warranty of
/    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
/    GNU General Public License for more details.
/
/    You should have received a copy of the GNU General Public License
/    along with this program.  If not, see <http://www.gnu.org/licenses/>.
/
*/

#include "Classdef.h"
#include <float.h>

#define MAX_BLOCK	1048576

void
  MyFrame::BuildNetwork(wxString & table, wxString & from, wxString & to,
                        wxString & geometry, bool cost_length, wxString & cost,
                        bool bidirectional, bool one_way,
                        wxString & one_way_from_to, wxString & one_way_to_from)
{
//
// trying to build a Network
// 
  int ret;
  sqlite3_stmt *stmt;
  Network *p_graph = NULL;
  wxString sql;
  char xsql[2048];
  char **results;
  int n_rows;
  int n_columns;
  int i;
  char *errMsg = NULL;
  char *col_name;
  int type;
  bool ok_from_column = false;
  bool ok_to_column = false;
  bool ok_cost_column = false;
  bool ok_geom_column = false;
  bool ok_oneway_tofrom = false;
  bool ok_oneway_fromto = false;
  bool from_null = false;
  bool from_int = false;
  bool from_double = false;
  bool from_text = false;
  bool from_blob = false;
  bool to_null = false;
  bool to_int = false;
  bool to_double = false;
  bool to_text = false;
  bool to_blob = false;
  bool cost_null = false;
  bool cost_int = false;
  bool cost_double = false;
  bool cost_text = false;
  bool cost_blob = false;
  bool tofrom_null = false;
  bool tofrom_int = false;
  bool tofrom_double = false;
  bool tofrom_text = false;
  bool tofrom_blob = false;
  bool fromto_null = false;
  bool fromto_int = false;
  bool fromto_double = false;
  bool fromto_text = false;
  bool fromto_blob = false;
  bool geom_null = false;
  bool geom_not_linestring = false;
  int col_n;
  int cost_n;
  int fromto_n = 0;
  int tofrom_n = 0;
  int rowid;
  int id_from = -1;
  int id_to = -1;
  char code_from[1024];
  char code_to[1024];
  double node_from_x;
  double node_from_y;
  double node_to_x;
  double node_to_y;
  double cost_val;
  int fromto;
  int tofrom;
  wxString endMsg;
  wxString msg;
  bool wr;
  ::wxBeginBusyCursor();
// checking for table existence
  sql = wxT("SELECT tbl_name FROM sqlite_master WHERE tbl_name LIKE '");
  sql += table;
  sql += wxT("' AND type = 'table'");
  strcpy(xsql, sql.ToUTF8());
  ret =
    sqlite3_get_table(SqliteHandle, xsql, &results, &n_rows, &n_columns,
                      &errMsg);
  if (ret != SQLITE_OK)
    {
// some error occurred 
      wxMessageBox(wxT("SQLite SQL error: ") + wxString::FromUTF8(errMsg),
                   wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
      sqlite3_free(errMsg);
      goto abort;
    }
  if (n_rows == 0)
    {
      // required table does not exists 
      wxMessageBox(wxT("ERROR: table \"") + table + wxT("\" does not exists"),
                   wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
      goto abort;
  } else
    sqlite3_free_table(results);
// checking for columns existence
  sql = wxT("PRAGMA table_info(\"");
  sql += table;
  sql += wxT("\")");
  strcpy(xsql, sql.ToUTF8());
  ret =
    sqlite3_get_table(SqliteHandle, xsql, &results, &n_rows, &n_columns,
                      &errMsg);
  if (ret != SQLITE_OK)
    {
// some error occurred 
      wxMessageBox(wxT("SQLite SQL error: ") + wxString::FromUTF8(errMsg),
                   wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
      sqlite3_free(errMsg);
      goto abort;
    }
  if (n_rows > 1)
    {
      for (i = 1; i <= n_rows; i++)
        {
          char xcol[256];
          col_name = results[(i * n_columns) + 1];
          strcpy(xcol, from.ToUTF8());
          if (strcasecmp(xcol, col_name) == 0)
            ok_from_column = true;
          strcpy(xcol, to.ToUTF8());
          if (strcasecmp(xcol, col_name) == 0)
            ok_to_column = true;
          if (cost_length == false)
            {
              strcpy(xcol, cost.ToUTF8());
              if (strcasecmp(xcol, col_name) == 0)
                ok_cost_column = true;
            }
          strcpy(xcol, geometry.ToUTF8());
          if (strcasecmp(xcol, col_name) == 0)
            ok_geom_column = true;
          if (one_way == true)
            {
              strcpy(xcol, one_way_from_to.ToUTF8());
              if (strcasecmp(xcol, col_name) == 0)
                ok_oneway_tofrom = true;
            }
          if (one_way == true)
            {
              strcpy(xcol, one_way_to_from.ToUTF8());
              if (strcasecmp(xcol, col_name) == 0)
                ok_oneway_fromto = true;
            }
        }
      sqlite3_free_table(results);
    }
  if (ok_from_column == true && ok_to_column == true && ok_geom_column == true)
    ;
  else
    goto abort;
  if (cost_length == false && ok_cost_column == false)
    goto abort;
  if (one_way == true && ok_oneway_tofrom == false)
    goto abort;
  if (one_way == true && ok_oneway_fromto == false)
    goto abort;
// checking column types
  p_graph = new Network();
  sql =
    wxT("SELECT \"") + from + wxT("\", \"") + to + wxT("\", GeometryType(\"") +
    geometry + wxT("\")");
  col_n = 3;
  if (cost_length == false)
    {
      sql += wxT(", \"") + cost + wxT("\"");
      cost_n = col_n;
      col_n++;
    }
  if (one_way == true)
    {
      sql += wxT(", \"") + one_way_to_from + wxT("\"");
      tofrom_n = col_n;
      col_n++;
      sql += wxT(", \"") + one_way_from_to + wxT("\"");
      fromto_n = col_n;
      col_n++;
    }
  sql += wxT(" FROM \"") + table;
  sql += wxT("\"");
  strcpy(xsql, sql.ToUTF8());
  ret = sqlite3_prepare_v2(SqliteHandle, xsql, strlen(xsql), &stmt, NULL);
  if (ret != SQLITE_OK)
    {
      wxString err = wxString::FromUTF8(sqlite3_errmsg(SqliteHandle));
      wxMessageBox(wxT("SQL error: ") + err, wxT("spatialite-gui"),
                   wxOK | wxICON_ERROR, this);
      goto abort;
    }
  n_columns = sqlite3_column_count(stmt);
  while (1)
    {
      ret = sqlite3_step(stmt);
      if (ret == SQLITE_DONE)
        break;
      if (ret == SQLITE_ROW)
        {
          // the NodeFrom type 
          type = sqlite3_column_type(stmt, 0);
          if (type == SQLITE_NULL)
            from_null = true;
          if (type == SQLITE_INTEGER)
            {
              from_int = true;
              id_from = sqlite3_column_int(stmt, 0);
              p_graph->InsertNode(id_from);
            }
          if (type == SQLITE_FLOAT)
            from_double = true;
          if (type == SQLITE_TEXT)
            {
              from_text = true;
              strcpy(code_from, (char *) sqlite3_column_text(stmt, 0));
              p_graph->InsertNode(code_from);
            }
          if (type == SQLITE_BLOB)
            from_blob = true;
          // the NodeTo type 
          type = sqlite3_column_type(stmt, 1);
          if (type == SQLITE_NULL)
            to_null = true;
          if (type == SQLITE_INTEGER)
            {
              to_int = true;
              id_to = sqlite3_column_int(stmt, 1);
              p_graph->InsertNode(id_to);
            }
          if (type == SQLITE_FLOAT)
            to_double = true;
          if (type == SQLITE_TEXT)
            {
              to_text = true;
              strcpy(code_to, (char *) sqlite3_column_text(stmt, 1));
              p_graph->InsertNode(code_to);
            }
          if (type == SQLITE_BLOB)
            to_blob = true;
          // the Geometry type 
          type = sqlite3_column_type(stmt, 2);
          if (type == SQLITE_NULL)
            geom_null = true;
          else if (strcmp("LINESTRING", (char *) sqlite3_column_text(stmt, 2))
                   != 0)
            geom_not_linestring = true;
          if (cost_length == false)
            {
              // the Cost type 
              type = sqlite3_column_type(stmt, 3);
              if (type == SQLITE_NULL)
                cost_null = true;
              if (type == SQLITE_INTEGER)
                cost_int = true;
              if (type == SQLITE_FLOAT)
                cost_double = true;
              if (type == SQLITE_TEXT)
                cost_text = true;
              if (type == SQLITE_BLOB)
                cost_blob = true;
            }
          if (one_way == true)
            {
              // the FromTo type
              type = sqlite3_column_type(stmt, 4);
              if (type == SQLITE_NULL)
                fromto_null = true;
              if (type == SQLITE_INTEGER)
                fromto_int = true;
              if (type == SQLITE_FLOAT)
                fromto_double = true;
              if (type == SQLITE_TEXT)
                fromto_text = true;
              if (type == SQLITE_BLOB)
                fromto_blob = true;
              // the ToFrom type 
              type = sqlite3_column_type(stmt, 5);
              if (type == SQLITE_NULL)
                tofrom_null = true;
              if (type == SQLITE_INTEGER)
                tofrom_int = true;
              if (type == SQLITE_FLOAT)
                tofrom_double = true;
              if (type == SQLITE_TEXT)
                tofrom_text = true;
              if (type == SQLITE_BLOB)
                tofrom_blob = true;
            }
      } else
        {
          wxString err = wxString::FromUTF8(sqlite3_errmsg(SqliteHandle));
          wxMessageBox(wxT("sqlite3_step error: ") + err, wxT("spatialite-gui"),
                       wxOK | wxICON_ERROR, this);
          sqlite3_finalize(stmt);
          goto abort;
        }
    }
  sqlite3_finalize(stmt);
  ret = 1;
  if (from_null == true)
    ret = 0;
  if (from_blob == true)
    ret = 0;
  if (from_double == true)
    ret = 0;
  if (to_null == true)
    ret = 0;
  if (to_blob == true)
    ret = 0;
  if (to_double == true)
    ret = 0;
  if (geom_null == true)
    ret = 0;
  if (geom_not_linestring == true)
    ret = 0;
  if (cost_length == false)
    {
      if (cost_null == true)
        ret = 0;
      if (cost_blob == true)
        ret = 0;
      if (cost_text == true)
        ret = 0;
    }
  if (one_way == true)
    {
      if (fromto_null == true)
        ret = 0;
      if (fromto_blob == true)
        ret = 0;
      if (fromto_text == true)
        ret = 0;
      if (fromto_double == true)
        ret = 0;
      if (tofrom_null == true)
        ret = 0;
      if (tofrom_blob == true)
        ret = 0;
      if (tofrom_text == true)
        ret = 0;
      if (tofrom_double == true)
        ret = 0;
    }
  if (!ret)
    goto abort;
  if (from_int == true && to_int == true)
    {
      // each node is identified by an INTEGER id 
      p_graph->SetNodeCode(false);
  } else if (from_text == true && to_text == true)
    {
      // each node is identified by a TEXT code
      p_graph->SetNodeCode(true);
  } else
    goto abort;
  p_graph->InitNodes();
// checking topologic consistency 
  sql = wxT("SELECT ROWID, \"") + from + wxT("\", \"") + to + wxT("\", ");
  sql +=
    wxT("X(StartPoint(\"") + geometry + wxT("\")), Y(StartPoint(\"") +
    geometry + wxT("\")), ");
  sql +=
    wxT("X(EndPoint(\"") + geometry + wxT("\")), Y(EndPoint(\"") + geometry +
    wxT("\"))");
  if (cost_length == false)
    sql += wxT(", ") + cost;
  else
    sql += wxT(", GLength(\"") + geometry + wxT("\")");
  col_n = 8;
  if (one_way == true)
    {
      sql += wxT(", \"") + one_way_to_from + wxT("\"");
      tofrom_n = col_n;
      col_n++;
      sql += wxT(", \"") + one_way_from_to + wxT("\"");
      fromto_n = col_n;
      col_n++;
    }
  sql += wxT(" FROM \"") + table + wxT("\"");
  strcpy(xsql, sql.ToUTF8());
  ret = sqlite3_prepare_v2(SqliteHandle, xsql, strlen(xsql), &stmt, NULL);
  if (ret != SQLITE_OK)
    {
      wxString err = wxString::FromUTF8(sqlite3_errmsg(SqliteHandle));
      wxMessageBox(wxT("SQL error: ") + err, wxT("spatialite-gui"),
                   wxOK | wxICON_ERROR, this);
      goto abort;
    }
  n_columns = sqlite3_column_count(stmt);
  while (1)
    {
      ret = sqlite3_step(stmt);
      if (ret == SQLITE_DONE)
        break;
      if (ret == SQLITE_ROW)
        {
          fromto = true;
          tofrom = true;
          if (p_graph->IsNodeCode() == true)
            {
              id_from = -1;
              id_to = -1;
          } else
            {
              *code_from = '\0';
              *code_to = '\0';
            }
          // fetching the ROWID 
          rowid = sqlite3_column_int(stmt, 0);
          // fetching the NodeFrom value
          if (p_graph->IsNodeCode() == true)
            strcpy(code_from, (char *) sqlite3_column_text(stmt, 1));
          else
            id_from = sqlite3_column_int(stmt, 1);
          // fetching the NodeTo value
          if (p_graph->IsNodeCode() == true)
            strcpy(code_to, (char *) sqlite3_column_text(stmt, 2));
          else
            id_to = sqlite3_column_int(stmt, 2);
          // fetching the NodeFromX value
          node_from_x = sqlite3_column_double(stmt, 3);
          // fetching the NodeFromY value 
          node_from_y = sqlite3_column_double(stmt, 4);
          // fetching the NodeFromX value 
          node_to_x = sqlite3_column_double(stmt, 5);
          // fetching the NodeFromY value 
          node_to_y = sqlite3_column_double(stmt, 6);
          // fetching the Cost value 
          cost_val = sqlite3_column_double(stmt, 7);
          if (one_way == true)
            {
              // fetching the OneWay-FromTo value
              fromto = sqlite3_column_int(stmt, fromto_n);
              // fetching the OneWay-ToFrom value
              tofrom = sqlite3_column_int(stmt, tofrom_n);
            }
          if (cost_val <= 0.0)
            p_graph->SetError();
          if (bidirectional == true)
            {
              if (fromto)
                {
                  if (p_graph->IsNodeCode() == true)
                    p_graph->AddArc(rowid, code_from, code_to, node_from_x,
                                    node_from_y, node_to_x, node_to_y,
                                    cost_val);
                  else
                    p_graph->AddArc(rowid, id_from, id_to, node_from_x,
                                    node_from_y, node_to_x, node_to_y,
                                    cost_val);
                }
              if (tofrom)
                {
                  if (p_graph->IsNodeCode() == true)
                    p_graph->AddArc(rowid, code_to, code_from, node_to_x,
                                    node_to_y, node_from_x, node_from_y,
                                    cost_val);
                  else
                    p_graph->AddArc(rowid, id_to, id_from, node_to_x, node_to_y,
                                    node_from_x, node_from_y, cost_val);
                }
          } else
            {
              if (p_graph->IsNodeCode() == true)
                p_graph->AddArc(rowid, code_from, code_to, node_from_x,
                                node_from_y, node_to_x, node_to_y, cost_val);
              else
                p_graph->AddArc(rowid, id_from, id_to, node_from_x, node_from_y,
                                node_to_x, node_to_y, cost_val);
            }
          if (p_graph->IsError() == true)
            {
              sqlite3_finalize(stmt);
              goto abort;
            }
      } else
        {
          wxString err = wxString::FromUTF8(sqlite3_errmsg(SqliteHandle));
          wxMessageBox(wxT("sqlite3_step error: ") + err, wxT("spatialite-gui"),
                       wxOK | wxICON_ERROR, this);
          sqlite3_finalize(stmt);
          goto abort;
        }
    }
  sqlite3_finalize(stmt);
  ::wxEndBusyCursor();
  wr = CreateNetwork(p_graph, table, from, to, geometry);
  if (wr == true)
    {
      endMsg =
        wxT("OK: VirtualNetwork table '") + table +
        wxT("_net' successfully created");
      wxMessageBox(endMsg, wxT("spatialite-gui"), wxOK | wxICON_INFORMATION,
                   this);
  } else
    {
      endMsg =
        wxT("DB ERROR: VirtualNetwork table '") + table +
        wxT("_net' was not created");
      wxMessageBox(endMsg, wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
    }
  if (p_graph)
    delete p_graph;
  InitTableTree();
  return;
abort:
  ::wxEndBusyCursor();
  msg =
    wxT
    ("It's impossible to build a Network using the given configuration;\nsome fatal error occurred\n\n");
  msg += wxT("please note: using the 'spatialite_network' command-line tool\n");
  msg +=
    wxT
    ("you can obtain a full detailed report explaining causes for this failure");
  wxMessageBox(msg, wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
  if (p_graph)
    delete p_graph;
}

void
  MyFrame::OutputNetNode(unsigned char *auxbuf, int *size, int ind,
                         bool node_code, int max_node_length, NetNode * pN,
                         int endian_arch)
{
//
// exporting a Node into NETWORK-DATA
//
  int n_star;
  int i;
  NetArc **arc_array;
  NetArc *pA;
  unsigned char *out = auxbuf;
  *out++ = GAIA_NET_NODE;
  gaiaExport32(out, ind, 1, endian_arch); // the Node internal index 
  out += 4;
  if (node_code)
    {
      // Nodes are identified by a TEXT Code 
      memset(out, '\0', max_node_length);
      strcpy((char *) out, pN->GetCode().ToUTF8());
      out += max_node_length;
  } else
    {
      // Nodes are identified by an INTEGER Id 
      gaiaExport32(out, pN->GetId(), 1, endian_arch); // the Node ID 
      out += 4;
    }
  arc_array = pN->PrepareOutcomings(&n_star);
  gaiaExport16(out, n_star, 1, endian_arch);  // # of outcoming arcs
  out += 2;
  for (i = 0; i < n_star; i++)
    {
      // exporting the outcoming arcs 
      pA = *(arc_array + i);
      *out++ = GAIA_NET_ARC;
      gaiaExport32(out, pA->GetRowId(), 1, endian_arch);  // the Arc rowid
      out += 4;
      gaiaExport32(out, pA->GetTo()->GetInternalIndex(), 1, endian_arch); // the ToNode internal index
      out += 4;
      gaiaExport64(out, pA->GetCost(), 1, endian_arch); // the Arc Cost 
      out += 8;
      *out++ = GAIA_NET_END;
    }
  if (arc_array)
    delete[]arc_array;
  *out++ = GAIA_NET_END;
  *size = out - auxbuf;
}

bool MyFrame::CreateNetwork(Network * p_graph, wxString & table,
                            wxString & from, wxString & to, wxString & geometry)
{
//
// creates the NETWORK-DATA table 
//
  int ret;
  wxString sql;
  char xsql[1024];
  char *errMsg = NULL;
  unsigned char *auxbuf = new unsigned char[MAX_BLOCK];
  unsigned char *buf = new unsigned char[MAX_BLOCK];
  unsigned char *out;
  sqlite3_stmt *stmt;
  int i;
  int size;
  int endian_arch = gaiaEndianArch();
  NetNode *pN;
  int pk = 0;
  int nodes_cnt = 0;
  int len;
  bool net_data_exists = false;
  bool net_exists = false;
  bool delete_existing = false;
  wxString data_table = table + wxT("_net_data");
  wxString net_table = table + wxT("_net");
  net_data_exists = TableAlreadyExists(data_table);
  net_exists = TableAlreadyExists(net_table);
  if (net_data_exists == true || net_exists == true)
    {
      // asking permission to overwrite existing tables
      wxString msg;
      if (net_data_exists == true)
        msg += wxT("A table named '") + data_table + wxT("' already exists\n");
      if (net_exists == true)
        msg += wxT("A table named '") + net_table + wxT("' already exists\n");
      msg += wxT("\nDo you allow DROPping existing table(s) ?");
      wxMessageDialog confirm(this, msg, wxT("Confirm overwrite"),
                              wxYES_NO | wxICON_QUESTION);
      ret = confirm.ShowModal();
      if (ret == wxID_YES)
        delete_existing = true;
    }
  ::wxBeginBusyCursor();
  for (i = 0; i < p_graph->GetNumNodes(); i++)
    {
      // setting the internal index to each Node 
      pN = p_graph->GetSortedNode(i);
      pN->SetInternalIndex(i);
    }
// starts a transaction 
  ret = sqlite3_exec(SqliteHandle, "BEGIN", NULL, NULL, &errMsg);
  if (ret != SQLITE_OK)
    {
      wxMessageBox(wxT("BEGIN error: ") + wxString::FromUTF8(errMsg),
                   wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
      sqlite3_free(errMsg);
      goto abort;
    }
  if (delete_existing == true)
    {
      sql = wxT("DROP TABLE IF EXISTS \"") + net_table + wxT("\"");
      strcpy(xsql, sql.ToUTF8());
      ret = sqlite3_exec(SqliteHandle, xsql, NULL, NULL, &errMsg);
      if (ret != SQLITE_OK)
        {
          wxMessageBox(wxT("DROP TABLE error: ") + wxString::FromUTF8(errMsg),
                       wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
          sqlite3_free(errMsg);
          goto abort;
        }
      sql = wxT("DROP TABLE IF EXISTS \"") + data_table + wxT("\"");
      strcpy(xsql, sql.ToUTF8());
      ret = sqlite3_exec(SqliteHandle, xsql, NULL, NULL, &errMsg);
      if (ret != SQLITE_OK)
        {
          wxMessageBox(wxT("DROP TABLE error: ") + wxString::FromUTF8(errMsg),
                       wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
          sqlite3_free(errMsg);
          goto abort;
        }
    }
// creating the NETWORK-DATA table 
  sql = wxT("CREATE TABLE \"") + data_table;
  sql += wxT("\" (\"Id\" INTEGER PRIMARY KEY, \"NetworkData\" BLOB NOT NULL)");
  strcpy(xsql, sql.ToUTF8());
  ret = sqlite3_exec(SqliteHandle, xsql, NULL, NULL, &errMsg);
  if (ret != SQLITE_OK)
    {
      wxMessageBox(wxT("CREATE TABLE error: ") + wxString::FromUTF8(errMsg),
                   wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
      sqlite3_free(errMsg);
      goto abort;
    }
// preparing the SQL statement 
  sql =
    wxT("INSERT INTO \"") + data_table +
    wxT("\" (\"Id\", \"NetworkData\") VALUES (?, ?)");
  strcpy(xsql, sql.ToUTF8());
  ret = sqlite3_prepare_v2(SqliteHandle, xsql, strlen(xsql), &stmt, NULL);
  if (ret != SQLITE_OK)
    {
      wxString err = wxString::FromUTF8(sqlite3_errmsg(SqliteHandle));
      wxMessageBox(wxT("INSERT error: ") + err, wxT("spatialite-gui"),
                   wxOK | wxICON_ERROR, this);
      goto abort;
    }
  if (pk == 0)
    {
      // preparing the HEADER block 
      out = buf;
      *out++ = GAIA_NET_START;
      *out++ = GAIA_NET_HEADER;
      gaiaExport32(out, p_graph->GetNumNodes(), 1, endian_arch);  // how many Nodes are there
      out += 4;
      if (p_graph->IsNodeCode() == true)
        *out++ = GAIA_NET_CODE; // Nodes are identified by a TEXT code 
      else
        *out++ = GAIA_NET_ID;   // Nodes are identified by an INTEGER id 
      if (p_graph->IsNodeCode() == true)
        *out++ = p_graph->GetMaxCodeLength(); // max TEXT code length
      else
        *out++ = 0x00;
      // inserting the main Table name 
      *out++ = GAIA_NET_TABLE;
      len = table.Len() + 1;
      gaiaExport16(out, len, 1, endian_arch); // the Table Name length, including last '\0'
      out += 2;
      memset(out, '\0', len);
      strcpy((char *) out, table.ToUTF8());
      out += len;
      // inserting the NodeFrom column name 
      *out++ = GAIA_NET_FROM;
      len = from.Len() + 1;
      gaiaExport16(out, len, 1, endian_arch); // the NodeFrom column Name length, including last '\0'
      out += 2;
      memset(out, '\0', len);
      strcpy((char *) out, from.ToUTF8());
      out += len;
      // inserting the NodeTo column name
      *out++ = GAIA_NET_TO;
      len = to.Len() + 1;
      gaiaExport16(out, len, 1, endian_arch); // the NodeTo column Name length, including last '\0'
      out += 2;
      memset(out, '\0', len);
      strcpy((char *) out, to.ToUTF8());
      out += len;
      // inserting the Geometry column name
      *out++ = GAIA_NET_GEOM;
      len = geometry.Len() + 1;
      gaiaExport16(out, len, 1, endian_arch); // the Geometry column Name length, including last '\0'
      out += 2;
      memset(out, '\0', len);
      strcpy((char *) out, geometry.ToUTF8());
      out += len;
      *out++ = GAIA_NET_END;
      // INSERTing the Header block 
      sqlite3_reset(stmt);
      sqlite3_clear_bindings(stmt);
      sqlite3_bind_int64(stmt, 1, pk);
      sqlite3_bind_blob(stmt, 2, buf, out - buf, SQLITE_STATIC);
      ret = sqlite3_step(stmt);
      if (ret == SQLITE_DONE || ret == SQLITE_ROW)
        ;
      else
        {
          wxString err = wxString::FromUTF8(sqlite3_errmsg(SqliteHandle));
          wxMessageBox(wxT("sqlite3_step error: ") + err, wxT("spatialite-gui"),
                       wxOK | wxICON_ERROR, this);
          sqlite3_finalize(stmt);
          goto abort;
        }
      pk++;
      // preparing a new block 
      out = buf;
      *out++ = GAIA_NET_BLOCK;
      gaiaExport16(out, 0, 1, endian_arch); // how many Nodes are into this block 
      out += 2;
      nodes_cnt = 0;
    }
  for (i = 0; i < p_graph->GetNumNodes(); i++)
    {
      // looping on each Node 
      pN = p_graph->GetSortedNode(i);
      OutputNetNode(auxbuf, &size, i, p_graph->IsNodeCode(),
                    p_graph->GetMaxCodeLength(), pN, endian_arch);
      if (size >= (MAX_BLOCK - (out - buf)))
        {
          // inserting the last block 
          gaiaExport16(buf + 1, nodes_cnt, 1, endian_arch); // how many Nodes are into this block
          sqlite3_reset(stmt);
          sqlite3_clear_bindings(stmt);
          sqlite3_bind_int64(stmt, 1, pk);
          sqlite3_bind_blob(stmt, 2, buf, out - buf, SQLITE_STATIC);
          ret = sqlite3_step(stmt);
          if (ret == SQLITE_DONE || ret == SQLITE_ROW)
            ;
          else
            {
              wxString err = wxString::FromUTF8(sqlite3_errmsg(SqliteHandle));
              wxMessageBox(wxT("sqlite3_step error: ") + err,
                           wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
              sqlite3_finalize(stmt);
              goto abort;
            }
          pk++;
          // preparing a new block 
          out = buf;
          *out++ = GAIA_NET_BLOCK;
          gaiaExport16(out, 0, 1, endian_arch); // how many Nodes are into this block
          out += 2;
          nodes_cnt = 0;
        }
      // inserting the current Node into the block 
      nodes_cnt++;
      memcpy(out, auxbuf, size);
      out += size;
    }
  if (nodes_cnt)
    {
      // inserting the last block
      gaiaExport16(buf + 1, nodes_cnt, 1, endian_arch); // how many Nodes are into this block
      sqlite3_reset(stmt);
      sqlite3_clear_bindings(stmt);
      sqlite3_bind_int64(stmt, 1, pk);
      sqlite3_bind_blob(stmt, 2, buf, out - buf, SQLITE_STATIC);
      ret = sqlite3_step(stmt);
      if (ret == SQLITE_DONE || ret == SQLITE_ROW)
        ;
      else
        {
          wxString err = wxString::FromUTF8(sqlite3_errmsg(SqliteHandle));
          wxMessageBox(wxT("sqlite3_step error: ") + err, wxT("spatialite-gui"),
                       wxOK | wxICON_ERROR, this);
          sqlite3_finalize(stmt);
          goto abort;
        }
    }
  sqlite3_finalize(stmt);
// creating the VirtualNetwork NET-table 
  sql = wxT("CREATE VIRTUAL TABLE \"") + net_table;
  sql += wxT("\" USING VirtualNetwork(");
  sql += data_table + wxT(")");
  strcpy(xsql, sql.ToUTF8());
  ret = sqlite3_exec(SqliteHandle, xsql, NULL, NULL, &errMsg);
  if (ret != SQLITE_OK)
    {
      wxMessageBox(wxT("CREATE VIRTUAL TABLE error: ") +
                   wxString::FromUTF8(errMsg), wxT("spatialite-gui"),
                   wxOK | wxICON_ERROR, this);
      sqlite3_free(errMsg);
      goto abort;
    }
// commits the transaction 
  ret = sqlite3_exec(SqliteHandle, "COMMIT", NULL, NULL, &errMsg);
  if (ret != SQLITE_OK)
    {
      wxMessageBox(wxT("COMMIT error: ") + wxString::FromUTF8(errMsg),
                   wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
      sqlite3_free(errMsg);
      goto abort;
    }
  if (buf)
    delete[]buf;
  if (auxbuf)
    delete[]auxbuf;
  ::wxEndBusyCursor();
  return true;
abort:
  ::wxEndBusyCursor();
  if (buf)
    delete[]buf;
  if (auxbuf)
    delete[]auxbuf;
  return true;
  return false;
}

int cmp_prenodes_code(const void *p1, const void *p2)
{
//
// compares two preliminary nodes  by CODE [for QSORT] 
//
  NetNodePre *pP1 = *((NetNodePre **) p1);
  NetNodePre *pP2 = *((NetNodePre **) p2);
  return pP1->GetCode().Cmp(pP2->GetCode());
}

int cmp_prenodes_id(const void *p1, const void *p2)
{
//
// compares two preliminary nodes  by ID [for QSORT] 
//
  NetNodePre *pP1 = *((NetNodePre **) p1);
  NetNodePre *pP2 = *((NetNodePre **) p2);
  return pP1->GetId() - pP2->GetId();
}

int cmp_nodes2_code(const void *p1, const void *p2)
{
//
// compares two nodes  by CODE [for BSEARCH] 
//
  NetNode *pN1 = (NetNode *) p1;
  NetNode *pN2 = *((NetNode **) p2);
  return pN1->GetCode().Cmp(pN2->GetCode());
}

int cmp_nodes2_id(const void *p1, const void *p2)
{
//
// compares two nodes  by ID [for BSEARCH] 
//
  NetNode *pN1 = (NetNode *) p1;
  NetNode *pN2 = *((NetNode **) p2);
  return pN1->GetId() - pN2->GetId();
}

int cmp_nodes1_code(const void *p1, const void *p2)
{
//
// compares two nodes  by CODE [for QSORT] 
//
  NetNode *pN1 = *((NetNode **) p1);
  NetNode *pN2 = *((NetNode **) p2);
  return pN1->GetCode().Cmp(pN2->GetCode());
}

int cmp_nodes1_id(const void *p1, const void *p2)
{
//
// compares two nodes  by ID [for QSORT ]
//
  NetNode *pN1 = *((NetNode **) p1);
  NetNode *pN2 = *((NetNode **) p2);
  return pN1->GetId() - pN2->GetId();
}

NetNodePre::NetNodePre(int id)
{
//
// Network Node [preliminary] constructor
//
  Id = id;
  Code = wxT("");
  Next = NULL;
}

NetNodePre::NetNodePre(const char *code)
{
//
// Network Node [preliminary] constructor
//
  Id = -1;
  Code = wxString::FromUTF8(code);
  Code.Truncate(30);
  Next = NULL;
}

NetNode::NetNode(int id)
{
//
// Network Node [final] constructor
//
  InternalIndex = -1;
  Id = id;
  Code = wxT("");
  X = DBL_MAX;
  Y = DBL_MAX;
  First = NULL;
  Last = NULL;
  Next = NULL;
}

NetNode::NetNode(wxString & code)
{
//
// Network Node [final] constructor
//
  InternalIndex = -1;
  Id = -1;
  Code = code;
  X = DBL_MAX;
  Y = DBL_MAX;
  First = NULL;
  Last = NULL;
  Next = NULL;
}

NetNode::~NetNode()
{
// Network Node [final] destructor
  NetArcRef *pAR;
  NetArcRef *pARn;
  pAR = First;
  while (pAR)
    {
      pARn = pAR->GetNext();
      delete pAR;
      pAR = pARn;
    }
}

void NetNode::AddOutcoming(NetArc * pA)
{
//
// adds an outcoming Arc to a Node 
//
  NetArcRef *pAR = new NetArcRef(pA);
  if (!First)
    First = pAR;
  if (Last)
    Last->SetNext(pAR);
  Last = pAR;
}

NetArc **NetNode::PrepareOutcomings(int *count)
{
//
// preparing the outcoming arc array 
//
  NetArc **arc_array;
  int n = 0;
  int i;
  bool ok;
  NetArcRef *pAR;
  NetArc *pA0;
  NetArc *pA1;
  pAR = First;
  while (pAR)
    {
      // counting how many outcoming arcs are there 
      n++;
      pAR = pAR->GetNext();
    }
  if (!n)
    {
      *count = 0;
      return NULL;
    }
  arc_array = new NetArc *[n];
  i = 0;
  pAR = First;
  while (pAR)
    {
      // populating the arcs array 
      *(arc_array + i++) = pAR->GetReference();
      pAR = pAR->GetNext();
    }
  ok = true;
  while (ok == true)
    {
      // bubble sorting the arcs by Cost 
      ok = false;
      for (i = 1; i < n; i++)
        {
          pA0 = *(arc_array + i - 1);
          pA1 = *(arc_array + i);
          if (pA0->GetCost() > pA1->GetCost())
            {
              // swapping the arcs 
              *(arc_array + i - 1) = pA1;
              *(arc_array + i) = pA0;
              ok = true;
            }
        }
    }
  *count = n;
  return arc_array;
}

NetArc::NetArc(int rowid, NetNode * from, NetNode * to, double cost)
{
//
// Network Arc constructor
//
  RowId = rowid;
  From = from;
  To = to;
  Cost = cost;
  Next = NULL;
}

Network::Network()
{
//
// Network constructor
//
  FirstPre = NULL;
  LastPre = NULL;
  NumPreNodes = 0;
  SortedPreNodes = NULL;
  NumPreNodes = 0;
  SortedPreNodes = NULL;
  FirstArc = NULL;
  LastArc = NULL;
  FirstNode = NULL;
  LastNode = NULL;
  NumNodes = 0;
  SortedNodes = NULL;
  Error = false;
  NodeCode = false;
  MaxCodeLength = 0;
}

Network::~Network()
{
//
// Network destructor
//
  NetArc *pA;
  NetArc *pAn;
  NetNode *pN;
  NetNode *pNn;
  CleanPreNodes();
  pA = FirstArc;
  while (pA)
    {
      pAn = pA->GetNext();
      delete pA;
      pA = pAn;
    }
  pN = FirstNode;
  while (pN)
    {
      pNn = pN->GetNext();
      delete pN;
      pN = pNn;
    }
  if (SortedNodes)
    delete[]SortedNodes;
}

void Network::CleanPreNodes()
{
//
// cleaning up the preliminary Nodes list
//
  NetNodePre *pP;
  NetNodePre *pPn;
  pP = FirstPre;
  while (pP)
    {
      pPn = pP->GetNext();
      delete pP;
      pP = pPn;
    }
  FirstPre = NULL;
  LastPre = NULL;
  NumPreNodes = 0;
  if (SortedPreNodes)
    delete[]SortedPreNodes;
  SortedPreNodes = NULL;
}

void Network::InsertNode(int id)
{
//
// inserts a Node into the preliminary list 
//
  NetNodePre *pP = new NetNodePre(id);
  if (!FirstPre)
    FirstPre = pP;
  if (LastPre)
    LastPre->SetNext(pP);
  LastPre = pP;
}

void Network::InsertNode(const char *code)
{
//
// inserts a Node into the preliminary list 
//
  NetNodePre *pP = new NetNodePre(code);
  if (!FirstPre)
    FirstPre = pP;
  if (LastPre)
    LastPre->SetNext(pP);
  LastPre = pP;
}

void Network::AddNode(int id)
{
//
// inserts a Node into the final list 
//
  NetNode *pN = new NetNode(id);
  if (!FirstNode)
    FirstNode = pN;
  if (LastNode)
    LastNode->SetNext(pN);
  LastNode = pN;
}

void Network::AddNode(wxString & code)
{
//
// inserts a Node into the final list 
//
  int len;
  NetNode *pN = new NetNode(code);
  len = pN->GetCode().Len() + 1;
  if (len > MaxCodeLength)
    MaxCodeLength = len;
  if (!FirstNode)
    FirstNode = pN;
  if (LastNode)
    LastNode->SetNext(pN);
  LastNode = pN;
}

NetNode *Network::ProcessNode(int id, double x, double y, NetNode ** pOther)
{
//
// inserts a new node or retrieves an already defined one 
//
  NetNode *pN = Find(id);
  *pOther = NULL;
  if (pN)
    {
      // this Node already exists into the sorted list
      if (pN->GetX() == DBL_MAX && pN->GetY() == DBL_MAX)
        ;
      else
        {
          if (pN->GetX() == x && pN->GetY() == y)
            ;
          else
            *pOther = pN;
        }
      return pN;
    }
// unexpected error; undefined Node
  return NULL;
}

NetNode *Network::ProcessNode(wxString & code, double x, double y,
                              NetNode ** pOther)
{
//
// inserts a new node or retrieves an already defined one 
//
  NetNode *pN = Find(code);
  *pOther = NULL;
  if (pN)
    {
      // this Node already exists into the sorted list
      if (pN->GetX() == DBL_MAX && pN->GetY() == DBL_MAX)
        ;
      else
        {
          if (pN->GetX() == x && pN->GetY() == y)
            ;
          else
            *pOther = pN;
        }
      return pN;
    }
// unexpected error; undefined Node
  return NULL;
}

void
  Network::AddArc(int rowid, int id_from, int id_to, double node_from_x,
                  double node_from_y, double node_to_x, double node_to_y,
                  double cost)
{
//
// inserting an arc into the memory structures 
//
  NetNode *pFrom;
  NetNode *pTo;
  NetNode *pN2;
  NetArc *pA;
  pFrom = ProcessNode(id_from, node_from_x, node_from_y, &pN2);
  if (pN2)
    Error = true;
  pTo = ProcessNode(id_to, node_to_x, node_to_y, &pN2);
  if (pN2)
    Error = true;
  if (!pFrom)
    Error = true;
  if (!pTo)
    Error = true;
  if (pFrom == pTo)
    Error = true;
  if (Error == true)
    return;
  pA = new NetArc(rowid, pFrom, pTo, cost);
  if (!FirstArc)
    FirstArc = pA;
  if (LastArc)
    LastArc->SetNext(pA);
  LastArc = pA;
// updating Node connections 
  pFrom->AddOutcoming(pA);
}

void
  Network::AddArc(int rowid, const char *code_from, const char *code_to,
                  double node_from_x, double node_from_y, double node_to_x,
                  double node_to_y, double cost)
{
//
// inserting an arc into the memory structures 
//
  NetNode *pFrom;
  NetNode *pTo;
  NetNode *pN2;
  NetArc *pA;
  wxString stCode = wxString::FromUTF8(code_from);
  pFrom = ProcessNode(stCode, node_from_x, node_from_y, &pN2);
  if (pN2)
    Error = true;
  stCode = wxString::FromUTF8(code_to);
  pTo = ProcessNode(stCode, node_to_x, node_to_y, &pN2);
  if (pN2)
    Error = true;
  if (!pFrom)
    Error = true;
  if (!pTo)
    Error = true;
  if (pFrom == pTo)
    Error = true;
  if (Error == true)
    return;
  pA = new NetArc(rowid, pFrom, pTo, cost);
  if (!FirstArc)
    FirstArc = pA;
  if (LastArc)
    LastArc->SetNext(pA);
  LastArc = pA;
// updating Node connections 
  pFrom->AddOutcoming(pA);
}

void Network::Sort()
{
//
// updating the Nodes sorted list 
//
  int i;
  NetNode *pN;
  NumNodes = 0;
  if (SortedNodes)
    {
      // we must free the already existent sorted list
      delete[]SortedNodes;
    }
  SortedNodes = NULL;
  pN = FirstNode;
  while (pN)
    {
      NumNodes++;
      pN = pN->GetNext();
    }
  if (!NumNodes)
    return;
  SortedNodes = new NetNode *[NumNodes];
  i = 0;
  pN = FirstNode;
  while (pN)
    {
      *(SortedNodes + i++) = pN;
      pN = pN->GetNext();
    }
  if (NodeCode == true)
    {
      // Nodes are identified by a TEXT code 
      qsort(SortedNodes, NumNodes, sizeof(NetNode *), cmp_nodes1_code);
  } else
    {
      // Nodes are identified by an INTEGER id 
      qsort(SortedNodes, NumNodes, sizeof(NetNode *), cmp_nodes1_id);
    }
}

NetNode *Network::GetSortedNode(int x)
{
//
// return a sorted Node [by position]
//
  if (x >= 0 && x < NumNodes)
    return *(SortedNodes + x);
  return NULL;
}

NetNode *Network::Find(int id)
{
//
// searching a Node into the sorted list 
//
  NetNode **ret;
  NetNode pN(id);
  if (!SortedNodes)
    return NULL;
// Nodes are identified by an INTEGER id
  ret =
    (NetNode **) bsearch(&pN, SortedNodes, NumNodes, sizeof(NetNode *),
                         cmp_nodes2_id);
  if (!ret)
    return NULL;
  return *ret;
}

NetNode *Network::Find(wxString & code)
{
//
// searching a Node into the sorted list 
//
  NetNode **ret;
  NetNode pN(code);
  if (!SortedNodes)
    return NULL;
// Nodes are identified by a TEXT code
  ret =
    (NetNode **) bsearch(&pN, SortedNodes, NumNodes, sizeof(NetNode *),
                         cmp_nodes2_code);
  if (!ret)
    return NULL;
  return *ret;
}

void Network::InitNodes()
{
//
// prepares the final Nodes list 
//
  int last_id;
  wxString last_code;
  int i;
  NetNodePre *pP;
  NumPreNodes = 0;
// sorting preliminary nodes 
  if (SortedPreNodes)
    {
      // we must free the already existent sorted list
      delete[]SortedPreNodes;
    }
  SortedPreNodes = NULL;
  pP = FirstPre;
  while (pP)
    {
      NumPreNodes++;
      pP = pP->GetNext();
    }
  if (!NumPreNodes)
    return;
  SortedPreNodes = new NetNodePre *[NumPreNodes];
  i = 0;
  pP = FirstPre;
  while (pP)
    {
      *(SortedPreNodes + i++) = pP;
      pP = pP->GetNext();
    }
  if (NodeCode == true)
    {
      // Nodes are identified by a TEXT code
      qsort(SortedPreNodes, NumPreNodes, sizeof(NetNodePre *),
            cmp_prenodes_code);
  } else
    {
      // Nodes are identified by an INTEGER id 
      qsort(SortedPreNodes, NumPreNodes, sizeof(NetNodePre *), cmp_prenodes_id);
    }
// creating the final Nodes linked list 
  last_id = -1;
  last_code = wxT("");
  for (i = 0; i < NumPreNodes; i++)
    {
      pP = *(SortedPreNodes + i);
      if (NodeCode == true)
        {
          // Nodes are identified by a TEXT code
          if (pP->GetCode().Cmp(last_code) != 0)
            AddNode(pP->GetCode());
      } else
        {
          // Nodes are identified by an INTEGER id
          if (pP->GetId() != last_id)
            AddNode(pP->GetId());
        }
      last_id = pP->GetId();
      last_code = pP->GetCode();
    }
// sorting the final Nodes list 
  Sort();
// cleaning up the preliminary Nodes structs 
  CleanPreNodes();
}

Changes to Objects.cpp.

1
2
3
4
5
6
7
8
9
10
11
12
..
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464

465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720





























/*
/ Objects.cpp
/ miscellaneous ancillary classes implementation
/
/ version 1.1, 2008 September 13
/
/ Author: Sandro Furieri a-furieri@lqt.it
/
/ Copyright (C) 2008  Alessandro Furieri
/
/    This program is free software: you can redistribute it and/or modify
/    it under the terms of the GNU General Public License as published by
................................................................................
/    You should have received a copy of the GNU General Public License
/    along with this program.  If not, see <http://www.gnu.org/licenses/>.
/
*/

#include "Classdef.h"

MyObject::MyObject (int type, wxString & name)
{
//
// constructor - TreeItemData
//
    Type = type;
    Name = name;
    Column = wxT ("");
}

MyObject::MyObject (int type, wxString & name, wxString & column)
{
//
// constructor - TreeItemData
//
    Type = type;
    Name = name;
    Column = column;
}

void
MyVariant::Copy (MyVariant * other)
{
// 
// transfers a BLOB value
//
    if (other->Type != MY_BLOB_VARIANT)
	return;
    if (!(other->Blob))
	return;
    if (Blob)
	delete[]Blob;
    Type = MY_BLOB_VARIANT;
    BlobSize = other->BlobSize;
    Blob = other->Blob;
    other->Type = MY_NULL_VARIANT;
    other->Blob = NULL;
    other->BlobSize = 0;
}

void
MyVariant::Set (const unsigned char *text)
{
//
// sets a String value for this Variant value
//
    Type = MY_TXT_VARIANT;
    TxtValue = wxString::FromUTF8 ((const char *) text);
}

void
MyVariant::Set (const void *blob, int size)
{
//
// sets a BLOB value for this Variant value
//
    if (size <= 0)
	return;
    Type = MY_BLOB_VARIANT;
    BlobSize = size;
    Blob = new unsigned char[size];
    memcpy (Blob, blob, size);
}

void
MyRowVariant::Create (int cols)
{
//
// creating the row variant
//
    if (ColumnArray)
	delete[]ColumnArray;
    NumCols = cols;
    ColumnArray = new MyVariant[NumCols];
}

void
MyRowVariant::Set (int col, int value)
{
//
// setting an Integer value for the Nth column
//
    MyVariant *var;
    if (col < 0 || col >= NumCols)
	return;
    var = ColumnArray + col;
    var->Set (value);
}

void
MyRowVariant::Set (int col, double value)
{
//
// setting a Double value for the Nth column
//
    MyVariant *var;
    if (col < 0 || col >= NumCols)
	return;
    var = ColumnArray + col;
    var->Set (value);
}

void
MyRowVariant::Set (int col, const unsigned char *value)
{
//
// setting a String value for the Nth column
//
    MyVariant *var;
    if (col < 0 || col >= NumCols)
	return;
    var = ColumnArray + col;
    var->Set (value);
}

void
MyRowVariant::Set (int col, const void *blob, int size)
{
//
// setting a BLOB value for the Nth column
//
    MyVariant *var;
    if (col < 0 || col >= NumCols)
	return;
    var = ColumnArray + col;
    var->Set (blob, size);
}

MyVariant *
MyRowVariant::GetColumn (int col)
{
//
// returns a Column Variant Value
//
    MyVariant *var;
    if (col < 0 || col >= NumCols)
	return NULL;
    var = ColumnArray + col;
    return var;
}

MyVariantList::MyVariantList ()
{
//
// constructor - result set container
//
    NumCols = 0;
    ColumnName = NULL;
    First = NULL;
    Last = NULL;
}

MyVariantList::~MyVariantList ()
{
//
// destructor - result set container
//
    MyRowVariant *el;
    MyRowVariant *elN;
    if (ColumnName)
	delete[]ColumnName;
    el = First;
    while (el)
      {
	  elN = el->GetNext ();
	  delete el;
	  el = elN;
      }
}

int
MyVariantList::GetRows ()
{
//
// counting how many rows are there
//
    int cnt = 0;
    MyRowVariant *el = First;
    while (el)
      {
	  cnt++;
	  el = el->GetNext ();
      }
    return cnt;
}

MyRowVariant *
MyVariantList::Add (int columns)
{
//
// adds a row into the result set
//
    if (!NumCols)
      {
	  NumCols = columns;
	  ColumnName = new wxString[NumCols];
      }
    MyRowVariant *el = new MyRowVariant (columns);
    if (!First)
	First = el;
    if (Last)
	Last->SetNext (el);
    Last = el;
    return el;
}

void
MyVariantList::SetColumnName (int col, const char *name)
{
//
// storing a column name
//
    if (col < 0 || col >= NumCols)
	return;
    ColumnName[col] = wxString::FromUTF8 (name);
}

wxString & MyVariantList::GetColumnName (int col)
{
//
// retrieving a column name
//
    return ColumnName[col];
}

MyBlobs::MyBlobs (int rows, int cols)
{
//
// constructor - a BLOB matrix
//
    int r;
    MyRowVariant *rowVar;
    NumRows = 0;
    NumCols = 0;
    Rows = NULL;
    if (rows < 1 || cols < 1)
	return;
    NumRows = rows;
    NumCols = cols;
    Rows = new MyRowVariant[rows];
    for (r = 0; r < rows; r++)
      {
	  rowVar = Rows + r;
	  rowVar->Create (cols);
      }
}

MyBlobs::~MyBlobs ()
{
//
// destructor - a BLOB matrix
//
    if (Rows)
	delete[]Rows;
}

void
MyBlobs::SetBlob (int row, int col, MyVariant * org)
{
//
// setting a BLOB value
//
    MyRowVariant *rowVar;
    MyVariant *dest;
    if (row < 0 || row >= NumRows)
	return;
    if (col < 0 || col >= NumCols)
	return;
    rowVar = Rows + row;
    if (!rowVar)
	return;
    dest = rowVar->GetColumn (col);
    if (!dest)
	return;
    dest->Copy (org);
}

MyVariant *
MyBlobs::GetBlob (int row, int col)
{
//
// return a BLOB value
//
    MyRowVariant *rowVar;
    MyVariant *dest;
    if (row < 0 || row >= NumRows)
	return NULL;
    if (col < 0 || col >= NumCols)
	return NULL;
    rowVar = Rows + row;
    if (!rowVar)
	return NULL;
    dest = rowVar->GetColumn (col);
    if (!dest)
	return NULL;
    if (dest->GetType () != MY_BLOB_VARIANT)
	return NULL;
    return dest;
}

MyValues::MyValues (int rows, int cols)
{
//
// constructor - a generic values matrix
//
    int r;
    MyRowVariant *rowVar;
    NumRows = 0;
    NumCols = 0;
    Rows = NULL;
    if (rows < 1 || cols < 1)
	return;
    NumRows = rows;
    NumCols = cols;
    Rows = new MyRowVariant[rows];
    for (r = 0; r < rows; r++)
      {
	  rowVar = Rows + r;
	  rowVar->Create (cols);
      }
}

MyValues::~MyValues ()
{
//
// destructor - a generic values matrix
//
    if (Rows)
	delete[]Rows;
}

void
MyValues::SetValue (int row, int col, int value)
{
//
// setting an integer value
//
    MyRowVariant *rowVar;
    MyVariant *dest;
    if (row < 0 || row >= NumRows)
	return;
    if (col < 0 || col >= NumCols)
	return;
    rowVar = Rows + row;
    if (!rowVar)
	return;
    dest = rowVar->GetColumn (col);
    if (!dest)
	return;
    dest->Set (value);
}

void
MyValues::SetValue (int row, int col, double value)
{
//
// setting a double value
//
    MyRowVariant *rowVar;
    MyVariant *dest;
    if (row < 0 || row >= NumRows)
	return;
    if (col < 0 || col >= NumCols)
	return;
    rowVar = Rows + row;
    if (!rowVar)
	return;
    dest = rowVar->GetColumn (col);
    if (!dest)
	return;
    dest->Set (value);
}

void
MyValues::SetValue (int row, int col, wxString & value)
{
//
// setting a string value
//
    MyRowVariant *rowVar;
    MyVariant *dest;
    if (row < 0 || row >= NumRows)
	return;
    if (col < 0 || col >= NumCols)
	return;
    rowVar = Rows + row;
    if (!rowVar)
	return;
    dest = rowVar->GetColumn (col);
    if (!dest)
	return;
    dest->Set (value);
}

MyVariant *
MyValues::GetValue (int row, int col)
{
//
// return a generic value
//
    MyRowVariant *rowVar;
    MyVariant *dest;
    if (row < 0 || row >= NumRows)
	return NULL;
    if (col < 0 || col >= NumCols)
	return NULL;
    rowVar = Rows + row;
    if (!rowVar)
	return NULL;
    dest = rowVar->GetColumn (col);
    if (!dest)
	return NULL;
    return dest;
}

MyRowVariant *
MyValues::GetRow (int row)
{
//
// return a row of generic values
//
    MyRowVariant *rowVar;
    if (row < 0 || row >= NumRows)
	return NULL;
    rowVar = Rows + row;
    return rowVar;
}

MyColumnInfo::MyColumnInfo (wxString & name, bool pkey)
{
//
// constructor - a table column object
//
    Name = name;
    PrimaryKey = pkey;
    Geometry = false;
    GeometryIndex = false;

    Next = NULL;
}

MyIndexInfo::MyIndexInfo (wxString & name)
{
//
// constructor - a table index object
//
    Name = name;
    Next = NULL;
}

MyTriggerInfo::MyTriggerInfo (wxString & name)
{
//
// constructor - a table trigger object
//
    Name = name;
    Next = NULL;
}

MyTableInfo::~MyTableInfo ()
{
//
// destructor - a table columns collection
//
    MyColumnInfo *elc;
    MyColumnInfo *elcN;
    MyIndexInfo *eli;
    MyIndexInfo *eliN;
    MyTriggerInfo *elt;
    MyTriggerInfo *eltN;
    elc = FirstColumn;
    while (elc)
      {
	  elcN = elc->GetNext ();
	  delete elc;
	  elc = elcN;
      }
    eli = FirstIndex;
    while (eli)
      {
	  eliN = eli->GetNext ();
	  delete eli;
	  eli = eliN;
      }
    elt = FirstTrigger;
    while (elt)
      {
	  eltN = elt->GetNext ();
	  delete elt;
	  elt = eltN;
      }
}

void
MyTableInfo::AddColumn (wxString & name, bool pkey)
{
//
// inserting a column def into a table
//
    MyColumnInfo *el = new MyColumnInfo (name, pkey);
    if (!FirstColumn)
	FirstColumn = el;
    if (LastColumn)
	LastColumn->SetNext (el);
    LastColumn = el;
}

void
MyTableInfo::SetGeometry (wxString & name, bool index, bool cached)
{
//
//setting a geometry column
//
    MyColumnInfo *elc;
    elc = FirstColumn;
    while (elc)
      {
	  if (name == elc->GetName ())
	    {
		elc->SetGeometry ();
		if (index == true)
		    elc->SetGeometryIndex ();
		if (cached == true)
		    elc->SetMbrCache ();
	    }
	  elc = elc->GetNext ();
      }
}

void
MyTableInfo::AddIndex (wxString & name)
{
//
// inserting an index def into a table
//
    MyIndexInfo *el = new MyIndexInfo (name);
    if (!FirstIndex)
	FirstIndex = el;
    if (LastIndex)
	LastIndex->SetNext (el);
    LastIndex = el;
}

void
MyTableInfo::AddTrigger (wxString & name)
{
//
// inserting a trigger def into a table
//
    MyTriggerInfo *el = new MyTriggerInfo (name);
    if (!FirstTrigger)
	FirstTrigger = el;
    if (LastTrigger)
	LastTrigger->SetNext (el);
    LastTrigger = el;
}

MyViewInfo::~MyViewInfo ()
{
//
// destructor - a view columns collection
//
    MyColumnInfo *elc;
    MyColumnInfo *elcN;
    elc = First;
    while (elc)
      {
	  elcN = elc->GetNext ();
	  delete elc;
	  elc = elcN;
      }
}

void
MyViewInfo::AddColumn (wxString & name)
{
//
// inserting a column def into a view
//
    MyColumnInfo *el = new MyColumnInfo (name, false);
    if (!First)
	First = el;
    if (Last)
	Last->SetNext (el);
    Last = el;
}

MySqlHistory::~MySqlHistory ()
{
//
// destructor - the SQL queries history
//
    MySqlQuery *elq;
    MySqlQuery *elqN;
    elq = First;
    while (elq)
      {
	  elqN = elq->GetNext ();
	  delete elq;
	  elq = elqN;
      }
}

void
MySqlHistory::Add (wxString & sql)
{
//
// inserting an SQL query into the history
//
    if (Last)
      {
	  // avoiding stupid duplicates
	  if (Last->GetSql () == sql)
	      return;
      }
    MySqlQuery *el = new MySqlQuery (sql);
    if (!First)
	First = el;
    el->SetPrev (Last);
    if (Last)
	Last->SetNext (el);
    Last = el;
    Current = el;
}

MySqlQuery *
MySqlHistory::GetNext ()
{
//
// return the next SQL query
//
    if (Current)
      {
	  if (Current->GetNext ())
	    {
		Current = Current->GetNext ();
		return Current;
	    }
	  else
	      return NULL;
      }
    return NULL;
}

MySqlQuery *
MySqlHistory::GetPrev ()
{
//
// return the previous SQL query
//
    if (Current)
      {
	  if (Current->GetPrev ())
	    {
		Current = Current->GetPrev ();
		return Current;
	    }
	  else
	      return NULL;
      }
    return NULL;
}

bool
MySqlHistory::TestNext ()
{
//
// tests if the next SQL query exists
//
    if (Current)
      {
	  if (Current->GetNext ())
	      return true;
	  else
	      return false;
      }
    return false;
}

bool
MySqlHistory::TestPrev ()
{
//
// tests if the previous SQL query exists
//
    if (Current)
      {
	  if (Current->GetPrev ())
	      return true;
	  else
	      return false;
      }
    return false;
}

































|







 







|




|
|
|


|




|
|
|


<
|




|
|
|
|
|
|
|
|
|
|
|
|


<
|




|
|


<
|




|
|
|
|
|
|


<
|




|
|
|
|


<
|




|
|
|
|
|


<
|




|
|
|
|
|


<
|




|
|
|
|
|


<
|




|
|
|
|
|


<
|




|
|
|
|
|


|




|
|
|
|


|




|
|
|
|
|
|
|
|
|
|
|


<
|




|
|
|
|
|
|
|
|


|
<




|
|
|
|
|
|
|
|
|
|
|
|


<
|




|
|
|


|




|


|




|
|
|
|
|
|
|
|
|
|
|
|
|
|
|


|




|
|


<
|




|
|
|
|
|
|
|
|
|
|
|
|
|


<
|




|
|
|
|
|
|
|
|
|
|
|
|
|
|
|


|




|
|
|
|
|
|
|
|
|
|
|
|
|
|
|


|




|
|


|
<




|
|
|
|
|
|
|
|
|
|
|
|
|


<
|




|
|
|
|
|
|
|
|
|
|
|
|
|


<
|




|
|
|
|
|
|
|
|
|
|
|
|
|


<
|




|
|
|
|
|
|
|
|
|
|
|
|
|


|
<




|
|
|
|
|


|




|
|
|
|
>
|


|




|
|


|




|
|


|




|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|


<
|




|
|
|
|
|
|


<
|




|
|
|
|
|
|
|
|
|
|
|
|
|
|


<
|




|
|
|
|
|
|


<
|




|
|
|
|
|
|


|




|
|
|
|
|
|
|
|
|


<
|




|
|
|
|
|
|


|




|
|
|
|
|
|
|
|
|


<
|




|
|
|
|
|
|
|
|
|
|
|
|
|
|


<
|




|
|
|
|
|
|
<
|
|
|
|


<
|




|
|
|
|
|
|
<
|
|
|
|


<
|




|
|
|
|
|
|
|
|


<
|




|
|
|
|
|
|
|
|

>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
..
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47

48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66

67
68
69
70
71
72
73
74
75

76
77
78
79
80
81
82
83
84
85
86
87
88

89
90
91
92
93
94
95
96
97
98
99

100
101
102
103
104
105
106
107
108
109
110
111

112
113
114
115
116
117
118
119
120
121
122
123

124
125
126
127
128
129
130
131
132
133
134
135

136
137
138
139
140
141
142
143
144
145
146
147

148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188

189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204

205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222

223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271

272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291

292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345

346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364

365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384

385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404

405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425

426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501

502
503
504
505
506
507
508
509
510
511
512
513
514

515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535

536
537
538
539
540
541
542
543
544
545
546
547
548

549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577

578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606

607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627

628
629
630
631
632
633
634
635
636
637
638

639
640
641
642
643
644

645
646
647
648
649
650
651
652
653
654
655

656
657
658
659
660
661

662
663
664
665
666
667
668
669
670
671
672
673
674
675
676

677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
/*
/ Objects.cpp
/ miscellaneous ancillary classes implementation
/
/ version 1.2, 2008 October 9
/
/ Author: Sandro Furieri a-furieri@lqt.it
/
/ Copyright (C) 2008  Alessandro Furieri
/
/    This program is free software: you can redistribute it and/or modify
/    it under the terms of the GNU General Public License as published by
................................................................................
/    You should have received a copy of the GNU General Public License
/    along with this program.  If not, see <http://www.gnu.org/licenses/>.
/
*/

#include "Classdef.h"

MyObject::MyObject(int type, wxString & name)
{
//
// constructor - TreeItemData
//
  Type = type;
  Name = name;
  Column = wxT("");
}

MyObject::MyObject(int type, wxString & name, wxString & column)
{
//
// constructor - TreeItemData
//
  Type = type;
  Name = name;
  Column = column;
}


void MyVariant::Copy(MyVariant * other)
{
// 
// transfers a BLOB value
//
  if (other->Type != MY_BLOB_VARIANT)
    return;
  if (!(other->Blob))
    return;
  if (Blob)
    delete[]Blob;
  Type = MY_BLOB_VARIANT;
  BlobSize = other->BlobSize;
  Blob = other->Blob;
  other->Type = MY_NULL_VARIANT;
  other->Blob = NULL;
  other->BlobSize = 0;
}


void MyVariant::Set(const unsigned char *text)
{
//
// sets a String value for this Variant value
//
  Type = MY_TXT_VARIANT;
  TxtValue = wxString::FromUTF8((const char *) text);
}


void MyVariant::Set(const void *blob, int size)
{
//
// sets a BLOB value for this Variant value
//
  if (size <= 0)
    return;
  Type = MY_BLOB_VARIANT;
  BlobSize = size;
  Blob = new unsigned char[size];
  memcpy(Blob, blob, size);
}


void MyRowVariant::Create(int cols)
{
//
// creating the row variant
//
  if (ColumnArray)
    delete[]ColumnArray;
  NumCols = cols;
  ColumnArray = new MyVariant[NumCols];
}


void MyRowVariant::Set(int col, sqlite3_int64 value)
{
//
// setting an Integer value for the Nth column
//
  MyVariant *var;
  if (col < 0 || col >= NumCols)
    return;
  var = ColumnArray + col;
  var->Set(value);
}


void MyRowVariant::Set(int col, double value)
{
//
// setting a Double value for the Nth column
//
  MyVariant *var;
  if (col < 0 || col >= NumCols)
    return;
  var = ColumnArray + col;
  var->Set(value);
}


void MyRowVariant::Set(int col, const unsigned char *value)
{
//
// setting a String value for the Nth column
//
  MyVariant *var;
  if (col < 0 || col >= NumCols)
    return;
  var = ColumnArray + col;
  var->Set(value);
}


void MyRowVariant::Set(int col, const void *blob, int size)
{
//
// setting a BLOB value for the Nth column
//
  MyVariant *var;
  if (col < 0 || col >= NumCols)
    return;
  var = ColumnArray + col;
  var->Set(blob, size);
}


MyVariant *MyRowVariant::GetColumn(int col)
{
//
// returns a Column Variant Value
//
  MyVariant *var;
  if (col < 0 || col >= NumCols)
    return NULL;
  var = ColumnArray + col;
  return var;
}

MyVariantList::MyVariantList()
{
//
// constructor - result set container
//
  NumCols = 0;
  ColumnName = NULL;
  First = NULL;
  Last = NULL;
}

MyVariantList::~MyVariantList()
{
//
// destructor - result set container
//
  MyRowVariant *el;
  MyRowVariant *elN;
  if (ColumnName)
    delete[]ColumnName;
  el = First;
  while (el)
    {
      elN = el->GetNext();
      delete el;
      el = elN;
    }
}


int MyVariantList::GetRows()
{
//
// counting how many rows are there
//
  int cnt = 0;
  MyRowVariant *el = First;
  while (el)
    {
      cnt++;
      el = el->GetNext();
    }
  return cnt;
}

MyRowVariant *MyVariantList::Add(int columns)

{
//
// adds a row into the result set
//
  if (!NumCols)
    {
      NumCols = columns;
      ColumnName = new wxString[NumCols];
    }
  MyRowVariant *el = new MyRowVariant(columns);
  if (!First)
    First = el;
  if (Last)
    Last->SetNext(el);
  Last = el;
  return el;
}


void MyVariantList::SetColumnName(int col, const char *name)
{
//
// storing a column name
//
  if (col < 0 || col >= NumCols)
    return;
  ColumnName[col] = wxString::FromUTF8(name);
}

wxString & MyVariantList::GetColumnName(int col)
{
//
// retrieving a column name
//
  return ColumnName[col];
}

MyBlobs::MyBlobs(int rows, int cols)
{
//
// constructor - a BLOB matrix
//
  int r;
  MyRowVariant *rowVar;
  NumRows = 0;
  NumCols = 0;
  Rows = NULL;
  if (rows < 1 || cols < 1)
    return;
  NumRows = rows;
  NumCols = cols;
  Rows = new MyRowVariant[rows];
  for (r = 0; r < rows; r++)
    {
      rowVar = Rows + r;
      rowVar->Create(cols);
    }
}

MyBlobs::~MyBlobs()
{
//
// destructor - a BLOB matrix
//
  if (Rows)
    delete[]Rows;
}


void MyBlobs::SetBlob(int row, int col, MyVariant * org)
{
//
// setting a BLOB value
//
  MyRowVariant *rowVar;
  MyVariant *dest;
  if (row < 0 || row >= NumRows)
    return;
  if (col < 0 || col >= NumCols)
    return;
  rowVar = Rows + row;
  if (!rowVar)
    return;
  dest = rowVar->GetColumn(col);
  if (!dest)
    return;
  dest->Copy(org);
}


MyVariant *MyBlobs::GetBlob(int row, int col)
{
//
// return a BLOB value
//
  MyRowVariant *rowVar;
  MyVariant *dest;
  if (row < 0 || row >= NumRows)
    return NULL;
  if (col < 0 || col >= NumCols)
    return NULL;
  rowVar = Rows + row;
  if (!rowVar)
    return NULL;
  dest = rowVar->GetColumn(col);
  if (!dest)
    return NULL;
  if (dest->GetType() != MY_BLOB_VARIANT)
    return NULL;
  return dest;
}

MyValues::MyValues(int rows, int cols)
{
//
// constructor - a generic values matrix
//
  int r;
  MyRowVariant *rowVar;
  NumRows = 0;
  NumCols = 0;
  Rows = NULL;
  if (rows < 1 || cols < 1)
    return;
  NumRows = rows;
  NumCols = cols;
  Rows = new MyRowVariant[rows];
  for (r = 0; r < rows; r++)
    {
      rowVar = Rows + r;
      rowVar->Create(cols);
    }
}

MyValues::~MyValues()
{
//
// destructor - a generic values matrix
//
  if (Rows)
    delete[]Rows;
}

void MyValues::SetValue(int row, int col, sqlite3_int64 value)

{
//
// setting an integer value
//
  MyRowVariant *rowVar;
  MyVariant *dest;
  if (row < 0 || row >= NumRows)
    return;
  if (col < 0 || col >= NumCols)
    return;
  rowVar = Rows + row;
  if (!rowVar)
    return;
  dest = rowVar->GetColumn(col);
  if (!dest)
    return;
  dest->Set(value);
}


void MyValues::SetValue(int row, int col, double value)
{
//
// setting a double value
//
  MyRowVariant *rowVar;
  MyVariant *dest;
  if (row < 0 || row >= NumRows)
    return;
  if (col < 0 || col >= NumCols)
    return;
  rowVar = Rows + row;
  if (!rowVar)
    return;
  dest = rowVar->GetColumn(col);
  if (!dest)
    return;
  dest->Set(value);
}


void MyValues::SetValue(int row, int col, wxString & value)
{
//
// setting a string value
//
  MyRowVariant *rowVar;
  MyVariant *dest;
  if (row < 0 || row >= NumRows)
    return;
  if (col < 0 || col >= NumCols)
    return;
  rowVar = Rows + row;
  if (!rowVar)
    return;
  dest = rowVar->GetColumn(col);
  if (!dest)
    return;
  dest->Set(value);
}


MyVariant *MyValues::GetValue(int row, int col)
{
//
// return a generic value
//
  MyRowVariant *rowVar;
  MyVariant *dest;
  if (row < 0 || row >= NumRows)
    return NULL;
  if (col < 0 || col >= NumCols)
    return NULL;
  rowVar = Rows + row;
  if (!rowVar)
    return NULL;
  dest = rowVar->GetColumn(col);
  if (!dest)
    return NULL;
  return dest;
}

MyRowVariant *MyValues::GetRow(int row)

{
//
// return a row of generic values
//
  MyRowVariant *rowVar;
  if (row < 0 || row >= NumRows)
    return NULL;
  rowVar = Rows + row;
  return rowVar;
}

MyColumnInfo::MyColumnInfo(wxString & name, bool pkey)
{
//
// constructor - a table column object
//
  Name = name;
  PrimaryKey = pkey;
  Geometry = false;
  GeometryIndex = false;
  MbrCache = false;
  Next = NULL;
}

MyIndexInfo::MyIndexInfo(wxString & name)
{
//
// constructor - a table index object
//
  Name = name;
  Next = NULL;
}

MyTriggerInfo::MyTriggerInfo(wxString & name)
{
//
// constructor - a table trigger object
//
  Name = name;
  Next = NULL;
}

MyTableInfo::~MyTableInfo()
{
//
// destructor - a table columns collection
//
  MyColumnInfo *elc;
  MyColumnInfo *elcN;
  MyIndexInfo *eli;
  MyIndexInfo *eliN;
  MyTriggerInfo *elt;
  MyTriggerInfo *eltN;
  elc = FirstColumn;
  while (elc)
    {
      elcN = elc->GetNext();
      delete elc;
      elc = elcN;
    }
  eli = FirstIndex;
  while (eli)
    {
      eliN = eli->GetNext();
      delete eli;
      eli = eliN;
    }
  elt = FirstTrigger;
  while (elt)
    {
      eltN = elt->GetNext();
      delete elt;
      elt = eltN;
    }
}


void MyTableInfo::AddColumn(wxString & name, bool pkey)
{
//
// inserting a column def into a table
//
  MyColumnInfo *el = new MyColumnInfo(name, pkey);
  if (!FirstColumn)
    FirstColumn = el;
  if (LastColumn)
    LastColumn->SetNext(el);
  LastColumn = el;
}


void MyTableInfo::SetGeometry(wxString & name, bool index, bool cached)
{
//
//setting a geometry column
//
  MyColumnInfo *elc;
  elc = FirstColumn;
  while (elc)
    {
      if (name == elc->GetName())
        {
          elc->SetGeometry();
          if (index == true)
            elc->SetGeometryIndex();
          if (cached == true)
            elc->SetMbrCache();
        }
      elc = elc->GetNext();
    }
}


void MyTableInfo::AddIndex(wxString & name)
{
//
// inserting an index def into a table
//
  MyIndexInfo *el = new MyIndexInfo(name);
  if (!FirstIndex)
    FirstIndex = el;
  if (LastIndex)
    LastIndex->SetNext(el);
  LastIndex = el;
}


void MyTableInfo::AddTrigger(wxString & name)
{
//
// inserting a trigger def into a table
//
  MyTriggerInfo *el = new MyTriggerInfo(name);
  if (!FirstTrigger)
    FirstTrigger = el;
  if (LastTrigger)
    LastTrigger->SetNext(el);
  LastTrigger = el;
}

MyViewInfo::~MyViewInfo()
{
//
// destructor - a view columns collection
//
  MyColumnInfo *elc;
  MyColumnInfo *elcN;
  elc = First;
  while (elc)
    {
      elcN = elc->GetNext();
      delete elc;
      elc = elcN;
    }
}


void MyViewInfo::AddColumn(wxString & name)
{
//
// inserting a column def into a view
//
  MyColumnInfo *el = new MyColumnInfo(name, false);
  if (!First)
    First = el;
  if (Last)
    Last->SetNext(el);
  Last = el;
}

MySqlHistory::~MySqlHistory()
{
//
// destructor - the SQL queries history
//
  MySqlQuery *elq;
  MySqlQuery *elqN;
  elq = First;
  while (elq)
    {
      elqN = elq->GetNext();
      delete elq;
      elq = elqN;
    }
}


void MySqlHistory::Add(wxString & sql)
{
//
// inserting an SQL query into the history
//
  if (Last)
    {
      // avoiding stupid duplicates
      if (Last->GetSql() == sql)
        return;
    }
  MySqlQuery *el = new MySqlQuery(sql);
  if (!First)
    First = el;
  el->SetPrev(Last);
  if (Last)
    Last->SetNext(el);
  Last = el;
  Current = el;
}


MySqlQuery *MySqlHistory::GetNext()
{
//
// return the next SQL query
//
  if (Current)
    {
      if (Current->GetNext())
        {
          Current = Current->GetNext();
          return Current;

      } else
        return NULL;
    }
  return NULL;
}


MySqlQuery *MySqlHistory::GetPrev()
{
//
// return the previous SQL query
//
  if (Current)
    {
      if (Current->GetPrev())
        {
          Current = Current->GetPrev();
          return Current;

      } else
        return NULL;
    }
  return NULL;
}


bool MySqlHistory::TestNext()
{
//
// tests if the next SQL query exists
//
  if (Current)
    {
      if (Current->GetNext())
        return true;
      else
        return false;
    }
  return false;
}


bool MySqlHistory::TestPrev()
{
//
// tests if the previous SQL query exists
//
  if (Current)
    {
      if (Current->GetPrev())
        return true;
      else
        return false;
    }
  return false;
}

AutoFDOTables::~AutoFDOTables()
{
//
// destructor - auto FDO-OGR wrapper linked list
//
  AutoFDOTable *el;
  AutoFDOTable *elN;
  el = First;
  while (el)
    {
      elN = el->GetNext();
      delete el;
      el = elN;
    }
}

void AutoFDOTables::Add(const char *name, const int len)
{
//
// adding a table name to the auto FDO-OGR wrapper linked list
//
  AutoFDOTable *el = new AutoFDOTable(name, len);
  if (!First)
    First = el;
  if (Last)
    Last->SetNext(el);
  Last = el;
}

Changes to QueryView.cpp.

1
2
3
4
5
6
7
8
9
10
11
12
..
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55



56
57
58

59
60
61
62
63
64

65
66
67
68
69
70
71
72
73

74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206


207
208

209
210
211
212
213
214
215
216
217


218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262


263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650


651
652
653
654
655
656
657
658
659
660
661
























662
663
664
665
666
667
668
669
670
671
672


673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
/*
/ QueryView.cpp
/ a panel to set and show SQL queries
/
/ version 1.1, 2008 September 13
/
/ Author: Sandro Furieri a-furieri@lqt.it
/
/ Copyright (C) 2008  Alessandro Furieri
/
/    This program is free software: you can redistribute it and/or modify
/    it under the terms of the GNU General Public License as published by
................................................................................
// ICONs in XPM format [universally portable]
//
#include "icons/sql_go.xpm"
#include "icons/hs_back.xpm"
#include "icons/hs_back_no.xpm"
#include "icons/hs_forward.xpm"
#include "icons/hs_forward_no.xpm"
#include "icons/rs_first.xpm"
#include "icons/rs_last.xpm"
#include "icons/rs_next.xpm"
#include "icons/rs_previous.xpm"
#include "icons/refresh.xpm"

MyQueryView::MyQueryView (MyFrame * parent, wxWindowID id):
wxPanel (parent, id, wxDefaultPosition, wxSize (440, 480), wxBORDER_SUNKEN)
{
//
// constructor: a frame for SQL Queries
//
    RsBlock = 500;		// the ResultSet block size
    RowIds = new int[RsBlock];
    ReadOnly = true;
    InsertRow = NULL;
    MainFrame = parent;



// SQL statement
    SqlCtrl =
	new wxTextCtrl (this, ID_SQL, wxT (""), wxPoint (40, 5),

			wxSize (200, 20),
			wxTE_MULTILINE | wxTE_PROCESS_ENTER | wxTE_PROCESS_TAB |
			wxHSCROLL);
    BtnSqlGo =
	new wxBitmapButton (this, ID_SQL_GO, wxBitmap (sql_go_xpm),
			    wxPoint (340, 30), wxSize (32, 48));

    BtnSqlGo->SetToolTip (wxT ("Execute SQL statement"));
    BtnHistoryBack =
	new wxBitmapButton (this, ID_HISTORY_BACK, wxBitmap (hs_back_xpm),
			    wxPoint (5, 5), wxSize (32, 48));
    BtnHistoryBack->SetBitmapDisabled (wxBitmap (hs_back_no_xpm));
    BtnHistoryBack->SetToolTip (wxT ("History: previous SQL statement"));
    BtnHistoryForward =
	new wxBitmapButton (this, ID_HISTORY_FORWARD, wxBitmap (hs_forward_xpm),
			    wxPoint (5, 55), wxSize (32, 48));

    BtnHistoryForward->SetBitmapDisabled (wxBitmap (hs_forward_no_xpm));
    BtnHistoryForward->SetToolTip (wxT ("History: next SQL statement"));
    BtnRsFirst =
	new wxBitmapButton (this, ID_RS_FIRST, wxBitmap (rs_first_xpm),
			    wxPoint (5, 400), wxSize (32, 32));
    BtnRsFirst->SetToolTip (wxT ("ResultSet: go to first row"));
    BtnRsPrevious =
	new wxBitmapButton (this, ID_RS_PREVIOUS, wxBitmap (rs_previous_xpm),
			    wxPoint (55, 400), wxSize (32, 32));
    BtnRsPrevious->SetToolTip (wxT ("ResultSet: go to previous block"));
    BtnRefresh =
	new wxBitmapButton (this, ID_REFRESH, wxBitmap (refresh_xpm),
			    wxPoint (55, 400), wxSize (32, 32));
    BtnRefresh->SetToolTip (wxT ("ResultSet: refresh"));
    BtnRsNext =
	new wxBitmapButton (this, ID_RS_NEXT, wxBitmap (rs_next_xpm),
			    wxPoint (105, 400), wxSize (32, 32));
    BtnRsNext->SetToolTip (wxT ("ResultSet: go to next block"));
    BtnRsLast =
	new wxBitmapButton (this, ID_RS_LAST, wxBitmap (rs_last_xpm),
			    wxPoint (155, 400), wxSize (32, 32));
    BtnRsLast->SetToolTip (wxT ("ResultSet: go to last row"));
    RsCurrentBlock =
	new wxStaticText (this, ID_RS_BLOCK, wxT (""), wxPoint (210, 400),
			  wxSize (200, 18));
    TableView = NULL;
    TableBlobs = NULL;
    TableValues = NULL;
    CurrentBlob = NULL;
    SetHistoryStates ();
// setting up event handlers
    Connect (ID_SQL_GO, wxEVT_COMMAND_BUTTON_CLICKED,
	     (wxObjectEventFunction) & MyQueryView::OnSqlGo);
    Connect (ID_HISTORY_BACK, wxEVT_COMMAND_BUTTON_CLICKED,
	     (wxObjectEventFunction) & MyQueryView::OnHistoryBack);
    Connect (ID_HISTORY_FORWARD, wxEVT_COMMAND_BUTTON_CLICKED,
	     (wxObjectEventFunction) & MyQueryView::OnHistoryForward);
    Connect (ID_RS_FIRST, wxEVT_COMMAND_BUTTON_CLICKED,
	     (wxObjectEventFunction) & MyQueryView::OnRsFirst);
    Connect (ID_RS_PREVIOUS, wxEVT_COMMAND_BUTTON_CLICKED,
	     (wxObjectEventFunction) & MyQueryView::OnRsPrevious);
    Connect (ID_RS_NEXT, wxEVT_COMMAND_BUTTON_CLICKED,
	     (wxObjectEventFunction) & MyQueryView::OnRsNext);
    Connect (ID_RS_LAST, wxEVT_COMMAND_BUTTON_CLICKED,
	     (wxObjectEventFunction) & MyQueryView::OnRsLast);
    Connect (ID_REFRESH, wxEVT_COMMAND_BUTTON_CLICKED,
	     (wxObjectEventFunction) & MyQueryView::OnRefresh);
    Connect (wxID_ANY, wxEVT_SIZE,
	     (wxObjectEventFunction) & MyQueryView::OnSize);
    Connect (wxID_ANY, wxEVT_GRID_SELECT_CELL,
	     (wxObjectEventFunction) & MyQueryView::OnCellSelected);
    Connect (wxID_ANY, wxEVT_GRID_CELL_RIGHT_CLICK,
	     (wxObjectEventFunction) & MyQueryView::OnRightClick);
    Connect (wxID_ANY, wxEVT_GRID_CELL_CHANGE,
	     (wxObjectEventFunction) & MyQueryView::OnCellChanged);
    Connect (Grid_Delete, wxEVT_COMMAND_MENU_SELECTED,
	     (wxObjectEventFunction) & MyQueryView::OnCmdDelete);
    Connect (Grid_Insert, wxEVT_COMMAND_MENU_SELECTED,
	     (wxObjectEventFunction) & MyQueryView::OnCmdInsert);
    Connect (Grid_Abort, wxEVT_COMMAND_MENU_SELECTED,
	     (wxObjectEventFunction) & MyQueryView::OnCmdAbort);
    Connect (Grid_Clear, wxEVT_COMMAND_MENU_SELECTED,
	     (wxObjectEventFunction) & MyQueryView::OnCmdClearSelection);
    Connect (Grid_All, wxEVT_COMMAND_MENU_SELECTED,
	     (wxObjectEventFunction) & MyQueryView::OnCmdSelectAll);
    Connect (Grid_Row, wxEVT_COMMAND_MENU_SELECTED,
	     (wxObjectEventFunction) & MyQueryView::OnCmdSelectRow);
    Connect (Grid_Column, wxEVT_COMMAND_MENU_SELECTED,
	     (wxObjectEventFunction) & MyQueryView::OnCmdSelectColumn);
    Connect (Grid_Copy, wxEVT_COMMAND_MENU_SELECTED,
	     (wxObjectEventFunction) & MyQueryView::OnCmdCopy);
    Connect (Grid_Blob, wxEVT_COMMAND_MENU_SELECTED,
	     (wxObjectEventFunction) & MyQueryView::OnCmdBlob);
    Connect (Grid_BlobIn, wxEVT_COMMAND_MENU_SELECTED,
	     (wxObjectEventFunction) & MyQueryView::OnCmdBlobIn);
    Connect (Grid_BlobOut, wxEVT_COMMAND_MENU_SELECTED,
	     (wxObjectEventFunction) & MyQueryView::OnCmdBlobOut);
    Connect (Grid_BlobNull, wxEVT_COMMAND_MENU_SELECTED,
	     (wxObjectEventFunction) & MyQueryView::OnCmdBlobNull);
}

void
MyQueryView::ShowSqlControls ()
{
//
// making all SQL controls to be visible
//
    SqlCtrl->Show (true);
    BtnSqlGo->Show (true);
    BtnHistoryBack->Show (true);
    BtnHistoryForward->Show (true);
    SetHistoryStates ();
}

void
MyQueryView::ShowRsControls ()
{
//
// making all ResultSet controls to be visible
//
    BtnRsFirst->Show (true);
    BtnRsPrevious->Show (true);
    BtnRsNext->Show (true);
    BtnRsLast->Show (true);
    BtnRefresh->Show (true);
    RsCurrentBlock->Show (true);
    if (TableView)
	TableView->Show (true);
}

void
MyQueryView::HideControls ()
{
//
// making all controls to be invisible
//
    SqlCtrl->Show (false);
    BtnSqlGo->Show (false);
    BtnHistoryBack->Show (false);
    BtnHistoryForward->Show (false);
    BtnRsFirst->Show (false);
    BtnRsPrevious->Show (false);
    BtnRsNext->Show (false);
    BtnRsLast->Show (false);
    BtnRefresh->Show (false);
    RsCurrentBlock->Show (false);
    if (TableView)
	TableView->Show (false);
}

void
MyQueryView::HideRsControls ()
{


//
// making all ResultSet controls to be invisible

//
    BtnRsFirst->Show (false);
    BtnRsPrevious->Show (false);
    BtnRsNext->Show (false);
    BtnRsLast->Show (false);
    BtnRefresh->Show (false);
    RsCurrentBlock->Show (false);
    if (TableView)
	TableView->Show (false);


}

void
MyQueryView::SetHistoryStates ()
{
//
// updates the history buttons state
//
    BtnHistoryForward->Enable (History.TestNext ());
    BtnHistoryBack->Enable (History.TestPrev ());
}

void
MyQueryView::EditTable (wxString & sql, int *primaryKeys, int *blobCols,
			wxString & table)
{
//
// starting the edit table sequence
//
    int i;
    for (i = 0; i < 1024; i++)
      {
	  PrimaryKeys[i] = *(primaryKeys + i);
	  BlobColumns[i] = *(blobCols + i);
      }
    ReadOnly = false;
    TableName = table;
    SqlCtrl->SetValue (sql);
    if (ExecuteSql (sql, 0) == false)
	wxMessageBox (SqlErrorMsg, wxT ("spatialite-gui"), wxOK | wxICON_ERROR,
		      MainFrame);
}

void
MyQueryView::SetSql (wxString & sql, bool execute)
{
//
// sets an SQL statement [and maybe executes it]
//
    ReadOnly = true;
    SqlCtrl->SetValue (sql);
    if (execute == true)
      {
	  if (ExecuteSql (sql, 0) == false)
	      wxMessageBox (SqlErrorMsg, wxT ("spatialite-gui"),


			    wxOK | wxICON_ERROR, MainFrame);
      }
}

bool
MyQueryView::ExecuteSql (wxString & sql, int from)
{
//
// executing some SQL statement
//
    char *xSql = NULL;
    char err_msg[2048];
    int columns;
    int i_col;
    int i_row;
    int end_row = 0;
    wxString blobType;
    MyVariantList list;
    MyRowVariant *row;
    MyVariant *value;
    wxString cellValue;
    wxString currentBlock;
    sqlite3_stmt *stmt;
    sqlite3 *sqlite = MainFrame->GetSqlite ();
    SqlErrorMsg = wxT ("");
    if (TableView)
	TableView->Destroy ();
    TableView = NULL;
    if (TableBlobs)
	delete TableBlobs;
    if (TableValues)
	delete TableValues;
    TableBlobs = NULL;
    TableValues = NULL;
    CurrentBlob = NULL;
    HideRsControls ();
    RsBeginRow = 0;
    RsEndRow = 0;
    RsMaxRow = 0;
    for (i_row = 0; i_row < RsBlock; i_row++)
	RowIds[i_row] = -1;
    i_row = 0;
    xSql = new char[65536];
    strcpy (xSql, sql.ToUTF8 ());
    ::wxBeginBusyCursor ();
    int ret = sqlite3_prepare_v2 (sqlite, xSql, strlen (xSql), &stmt, NULL);
    if (ret != SQLITE_OK)
      {
	  sprintf (err_msg, "SQL error: \"%s\"", sqlite3_errmsg (sqlite));
	  SqlErrorMsg = wxString::FromUTF8 (err_msg);
	  ::wxEndBusyCursor ();
	  delete[]xSql;
	  return false;
      }
    RsCurrentBlock->Show (true);
    while (1)
      {
	  //
	  // fetching the result set rows 
	  //
	  ret = sqlite3_step (stmt);
	  if (ret == SQLITE_DONE)
	      break;		// end of result set
	  if (ret == SQLITE_ROW)
	    {
		//
		// fetching a row
		//
		if ((i_row % 100) == 0)
		  {
		      currentBlock.Printf (wxT
					   ("fetching the result set: %d rows"),
					   i_row);
		      RsCurrentBlock->SetLabel (currentBlock);
		  }
		if (i_row < from)
		  {
		      i_row++;
		      continue;
		  }
		if ((i_row - from) >= RsBlock)
		  {
		      i_row++;
		      continue;
		  }
		end_row = i_row;
		columns = sqlite3_column_count (stmt);
		MyRowVariant *rowVariant = list.Add (columns);
		for (i_col = 0; i_col < columns; i_col++)
		  {
		      int int_value;
		      double dbl_value;
		      const unsigned char *txt_value;
		      const void *blob_value;
		      int blobSize;
		      list.SetColumnName (i_col,
					  sqlite3_column_name (stmt, i_col));
		      switch (sqlite3_column_type (stmt, i_col))
			{
			case SQLITE_INTEGER:
			    int_value = sqlite3_column_int (stmt, i_col);
			    rowVariant->Set (i_col, int_value);
			    break;
			case SQLITE_FLOAT:
			    dbl_value = sqlite3_column_double (stmt, i_col);
			    rowVariant->Set (i_col, dbl_value);
			    break;
			case SQLITE_TEXT:
			    txt_value = sqlite3_column_text (stmt, i_col);
			    rowVariant->Set (i_col, txt_value);
			    break;
			case SQLITE_BLOB:
			    blob_value = sqlite3_column_blob (stmt, i_col);
			    blobSize = sqlite3_column_bytes (stmt, i_col);
			    rowVariant->Set (i_col, blob_value, blobSize);
			    break;
			case SQLITE_NULL:
			default:
			    break;
			};
		  }
		i_row++;
	    }
	  else
	    {
		sprintf (err_msg, "SQL error: \"%s\"", sqlite3_errmsg (sqlite));
		SqlErrorMsg = wxString::FromUTF8 (err_msg);
		goto error;
	    }
      }
    sqlite3_finalize (stmt);
    RsBeginRow = from;
    RsEndRow = end_row;
    RsMaxRow = i_row;
    if (list.GetRows () == 0)
      {
	  //
	  // this one is an EMPTY Result Set
	  //
	  if (ReadOnly == false)
	    {
		// preparing the insert row
		int numCols = 0;
		wxString *colNames =
		    MainFrame->GetColumnNames (TableName, &numCols);
		CreateGrid (0, numCols + 1);
		TableView->SetColLabelValue (0, wxT ("ROWID"));
		for (i_col = 0; i_col < numCols; i_col++)
		    TableView->SetColLabelValue (i_col + 1,
						 *(colNames + i_col));
		TableView->EnableEditing (true);
		delete[]colNames;
	    }
	  else
	    {
		// simply showing a warning message
		CreateGrid (1, 1);
		TableView->SetColLabelValue (0, wxT ("Message"));
		TableView->SetRowLabelValue (0, wxT ("Message"));
		TableView->SetCellValue (0, 0,
					 wxT
					 ("SQL query returned an empty ResultSet\n\nThis is not an error"));
	    }
      }
    else
      {
	  //
	  // preparing the Grid to show the result set
	  //
	  CreateGrid (list.GetRows (), list.GetColumns ());
	  if (ReadOnly == true)
	      TableView->EnableEditing (false);
	  else
	      TableView->EnableEditing (true);
	  for (i_col = 0; i_col < list.GetColumns (); i_col++)
	      TableView->SetColLabelValue (i_col, list.GetColumnName (i_col));
	  if (ReadOnly == false)
	      TableView->SetColLabelValue (0, wxT ("ROWID"));
	  i_row = 0;
	  row = list.GetFirst ();
	  while (row)
	    {
		cellValue.Printf (wxT ("%d"), i_row + RsBeginRow + 1);
		TableView->SetRowLabelValue (i_row, cellValue);
		if (ReadOnly == false)
		  {
		      // storing the ROWID value into the RowIds array
		      value = row->GetColumn (0);
		      if (value->GetType () == MY_INT_VARIANT)
			  RowIds[i_row] = value->GetIntValue ();
		  }
		for (i_col = 0; i_col < row->GetNumCols (); i_col++)
		  {
		      value = row->GetColumn (i_col);
		      if (value)
			{
			    switch (value->GetType ())
			      {
			      case MY_INT_VARIANT:
				  cellValue.Printf (wxT ("%d"),
						    value->GetIntValue ());
				  TableView->SetCellValue (i_row, i_col,
							   cellValue);
				  if (ReadOnly == false)
				      TableValues->SetValue (i_row, i_col,
							     value->GetIntValue
							     ());
				  break;
			      case MY_DBL_VARIANT:
				  cellValue.Printf (wxT ("%1.4lf"),
						    value->GetDblValue ());
				  TableView->SetCellValue (i_row, i_col,
							   cellValue);
				  if (ReadOnly == false)
				      TableValues->SetValue (i_row, i_col,
							     value->GetDblValue
							     ());
				  break;
			      case MY_TXT_VARIANT:
				  TableView->SetCellValue (i_row, i_col,
							   value->GetTxtValue
							   ());
				  if (ReadOnly == false)
				      TableValues->SetValue (i_row, i_col,
							     value->GetTxtValue
							     ());
				  break;
			      case MY_BLOB_VARIANT:
				  blobType = wxT ("UNKNOWN type");
				  switch (MainFrame->GuessBlobType
					  (value->GetBlobSize (),
					   value->GetBlob ()))
				    {
				    case MyFrame::BLOB_GEOMETRY:
					blobType = wxT ("GEOMETRY");
					break;
				    case MyFrame::BLOB_EXIF:
				    case MyFrame::BLOB_JFIF:
				    case MyFrame::BLOB_JPEG:
					blobType = wxT ("JPEG image");
					break;
				    case MyFrame::BLOB_PNG:
					blobType = wxT ("PNG image");
					break;
				    case MyFrame::BLOB_GIF:
					blobType = wxT ("GIF image");
					break;
				    case MyFrame::BLOB_PDF:
					blobType = wxT ("PDF document");
					break;
				    case MyFrame::BLOB_ZIP:
					blobType = wxT ("ZIP archive");
					break;
				    };
				  cellValue.Printf (wxT ("BLOB sz=%d "),
						    value->GetBlobSize ());
				  cellValue += blobType;
				  TableView->SetCellValue (i_row, i_col,
							   cellValue);
				  TableView->SetReadOnly (i_row, i_col);
				  TableBlobs->SetBlob (i_row, i_col, value);
				  break;
			      case MY_NULL_VARIANT:
			      default:
				  TableView->SetCellValue (i_row, i_col,
							   wxT ("NULL"));
				  break;
			      };
			}
		      else
			  TableView->SetCellValue (i_row, i_col, wxT ("NULL"));
		      if (ReadOnly == false)
			{
			    if (IsPrimaryKey (i_col) == true)
				TableView->SetReadOnly (i_row, i_col);
			    if (IsBlobColumn (i_col) == true)
				TableView->SetReadOnly (i_row, i_col);
			}
		  }
		i_row++;
		row = row->GetNext ();
	    }
      }
    if (ReadOnly == false)
      {
	  // prepearing the insert row
	  TableView->SetRowLabelValue (TableView->GetNumberRows () - 1,
				       wxT ("Insert row"));
	  InsertPending = false;
	  for (i_col = 0; i_col < TableView->GetNumberCols (); i_col++)
	    {
		TableView->SetCellValue (TableView->GetNumberRows () - 1, i_col,
					 wxT (""));
		TableView->SetCellBackgroundColour (TableView->
						    GetNumberRows () - 1, i_col,
						    wxColour (0, 0, 0));
		TableView->SetReadOnly (TableView->GetNumberRows () - 1, i_col);
	    }
      }
    TableView->AutoSize ();
    ResizeTableView ();
    currentBlock.Printf (wxT ("current block: %d / %d [%d rows]"),
			 RsBeginRow + 1, RsEndRow + 1, RsMaxRow);
    RsCurrentBlock->SetLabel (currentBlock);
    ShowRsControls ();
    History.Add (sql);
    SetHistoryStates ();
    ::wxEndBusyCursor ();
    if (xSql)
	delete[]xSql;
    return true;
  error:
    ::wxEndBusyCursor ();
    sqlite3_finalize (stmt);
    if (xSql)
	delete[]xSql;
    return false;
}

bool
MyQueryView::IsPrimaryKey (int column)
{
//
// checks if this column is a Primary Key one
//
    int i;
    for (i = 0; i < 1024; i++)
      {
	  if (PrimaryKeys[i] == column)
	      return true;
      }
    return false;
}

bool
MyQueryView::IsBlobColumn (int column)
{
//
// checks if this column is a BLOB-type column
//
    int i;
    for (i = 0; i < 1024; i++)
      {
	  if (BlobColumns[i] == column)
	      return true;
      }
    return false;
}

void
MyQueryView::CreateGrid (int rows, int cols)
{
//
// creating a new Grid to show the result set
//
    int extra = 0;
    if (ReadOnly == false)
	extra = 1;
    wxSize sz = GetClientSize ();
    TableView =
	new wxGrid (this, wxID_ANY, wxPoint (5, 120), wxSize (200, 200));
    TableView->Show (false);
    TableView->CreateGrid (rows + extra, cols);
    TableBlobs = new MyBlobs (rows, cols);
    if (ReadOnly == false)
	TableValues = new MyValues (rows, cols);
}

void
MyQueryView::ResizeTableView ()
{
//
// resizing the Grid to show the result set
//
    wxSize sz = GetClientSize ();
    if (TableView)
      {
	  TableView->SetSize (sz.GetWidth () - 10, sz.GetHeight () - 160);
	  TableView->Show (true);
      }
}

void
MyQueryView::OnSize (wxSizeEvent & event)
{
//
// this window has changed its size
//


    wxSize sz = GetClientSize ();
    SqlCtrl->SetSize (sz.GetWidth () - 80, 100);
    BtnSqlGo->Move (sz.GetWidth () - 35, 30);
    if (TableView)
	TableView->SetSize (sz.GetWidth () - 10, sz.GetHeight () - 160);
    BtnRsFirst->Move (5, sz.GetHeight () - 35);
    BtnRsPrevious->Move (40, sz.GetHeight () - 35);
    BtnRefresh->Move (75, sz.GetHeight () - 35);
    BtnRsNext->Move (110, sz.GetHeight () - 35);
    BtnRsLast->Move (145, sz.GetHeight () - 35);
    RsCurrentBlock->Move (180, sz.GetHeight () - 25);
























}

void
MyQueryView::OnSqlGo (wxCommandEvent & WXUNUSED (event))
{
//
// executing an SQL statement
//
    ReadOnly = true;
    wxString sql = SqlCtrl->GetValue ();
    if (ExecuteSql (sql, 0) == false)


	wxMessageBox (SqlErrorMsg, wxT ("spatialite-gui"), wxOK | wxICON_ERROR,
		      MainFrame);
}

void
MyQueryView::OnHistoryBack (wxCommandEvent & WXUNUSED (event))
{
//
// going backward into the SQL Queries History
//
    MySqlQuery *sql = History.GetPrev ();
    if (sql)
      {
	  SetSql (sql->GetSql (), false);
	  SetHistoryStates ();
      }
}

void
MyQueryView::OnHistoryForward (wxCommandEvent & WXUNUSED (event))
{
//
// going forward into the SQL Queries History
//
    MySqlQuery *sql = History.GetNext ();
    if (sql)
      {
	  SetSql (sql->GetSql (), false);
	  SetHistoryStates ();
      }
}

void
MyQueryView::OnRsFirst (wxCommandEvent & WXUNUSED (event))
{
//
// scrolling to the result set beginning
//
    wxString sql = SqlCtrl->GetValue ();
    if (ExecuteSql (sql, 0) == false)
	wxMessageBox (SqlErrorMsg, wxT ("spatialite-gui"), wxOK | wxICON_ERROR,
		      MainFrame);
}

void
MyQueryView::OnRsPrevious (wxCommandEvent & WXUNUSED (event))
{
//
// scrolling to the result set previous block
//
    wxString sql = SqlCtrl->GetValue ();
    int start = RsBeginRow - RsBlock;
    if (start < 0)
	start = 0;
    if (ExecuteSql (sql, start) == false)
	wxMessageBox (SqlErrorMsg, wxT ("spatialite-gui"), wxOK | wxICON_ERROR,
		      MainFrame);
}

void
MyQueryView::OnRsNext (wxCommandEvent & WXUNUSED (event))
{
//
// scrolling to the result set next block
//
    wxString sql = SqlCtrl->GetValue ();
    int start = RsEndRow + 1;
    if (ExecuteSql (sql, start) == false)
	wxMessageBox (SqlErrorMsg, wxT ("spatialite-gui"), wxOK | wxICON_ERROR,
		      MainFrame);
}

void
MyQueryView::OnRsLast (wxCommandEvent & WXUNUSED (event))
{
//
// scrolling to the result set ending
//
    wxString sql = SqlCtrl->GetValue ();
    int start = RsMaxRow - RsBlock;
    if (start < 0)
	start = 0;
    if (ExecuteSql (sql, start) == false)
	wxMessageBox (SqlErrorMsg, wxT ("spatialite-gui"), wxOK | wxICON_ERROR,
		      MainFrame);
}

void
MyQueryView::OnRefresh (wxCommandEvent & WXUNUSED (event))
{
//
// refreshing the result set
//
    wxString sql = SqlCtrl->GetValue ();
    int start = RsBeginRow;
    if (ExecuteSql (sql, start) == false)
	wxMessageBox (SqlErrorMsg, wxT ("spatialite-gui"), wxOK | wxICON_ERROR,
		      MainFrame);
}

void
MyQueryView::OnRightClick (wxGridEvent & event)
{
//
// right click on some cell [mouse action]
//
    MyVariant *blobVar;
    wxMenu menu;
    wxMenuItem *menuItem;
    wxPoint pt = event.GetPosition ();
    if (ReadOnly == false && event.GetRow () == TableView->GetNumberRows () - 1)
      {
	  // this is the INSERT ROW
	  if (InsertPending == true)
	    {
		menuItem =
		    new wxMenuItem (&menu, Grid_Insert,
				    wxT ("&Confirm insertion"));
		menu.Append (menuItem);
		menuItem =
		    new wxMenuItem (&menu, Grid_Abort,
				    wxT ("&Abort insertion"));
		menu.Append (menuItem);
	    }
	  else
	    {
		menuItem =
		    new wxMenuItem (&menu, Grid_Insert,
				    wxT ("&Insert new row"));
		menu.Append (menuItem);
	    }
	  TableView->PopupMenu (&menu, pt);
	  return;
      }
    CurrentEvtRow = event.GetRow ();
    CurrentEvtColumn = event.GetCol ();
    blobVar = TableBlobs->GetBlob (CurrentEvtRow, CurrentEvtColumn);
    if (blobVar)
      {
	  // this one is a BLOB cell
	  if (ReadOnly == false)
	    {
		MyRowVariant *varRow = TableValues->GetRow (CurrentEvtRow);
		if (varRow->IsDeleted () == false)
		  {
		      menuItem =
			  new wxMenuItem (&menu, Grid_Delete,
					  wxT ("&Delete row"));
		      menu.Append (menuItem);
		      menuItem =
			  new wxMenuItem (&menu, Grid_Insert,
					  wxT ("&Insert new row"));
		      menu.Append (menuItem);
		      menu.AppendSeparator ();
		  }
	    }
	  menuItem = new wxMenuItem (&menu, Grid_Blob, wxT ("BLOB &explore"));
	  menu.Append (menuItem);
	  if (MainFrame->GuessBlobType (blobVar->GetBlobSize (),
					blobVar->GetBlob ()) ==
	      MyFrame::BLOB_GEOMETRY)
	      ;
	  else
	    {
		menu.AppendSeparator ();
		menuItem =
		    new wxMenuItem (&menu, Grid_BlobIn, wxT ("BLOB &import"));
		menu.Append (menuItem);
		menuItem =
		    new wxMenuItem (&menu, Grid_BlobOut, wxT ("BLOB &export"));
		menu.Append (menuItem);
		menuItem =
		    new wxMenuItem (&menu, Grid_BlobNull,
				    wxT ("Set BLOB as &NULL"));
		menu.Append (menuItem);
	    }
	  CurrentBlob = blobVar;
      }
    else
      {
	  // this one is an ordinary cell
	  CurrentBlob = NULL;
	  if (ReadOnly == false)
	    {
		MyRowVariant *varRow = TableValues->GetRow (CurrentEvtRow);
		if (varRow->IsDeleted () == false)
		  {
		      menuItem =
			  new wxMenuItem (&menu, Grid_Delete,
					  wxT ("&Delete row"));
		      menu.Append (menuItem);
		      menuItem =
			  new wxMenuItem (&menu, Grid_Insert,
					  wxT ("&Insert new row"));
		      menu.Append (menuItem);
		      if (IsBlobColumn (CurrentEvtColumn) == true)
			{
			    menu.AppendSeparator ();
			    menuItem =
				new wxMenuItem (&menu, Grid_BlobIn,
						wxT ("BLOB &import"));
			    menu.Append (menuItem);
			}
		      menu.AppendSeparator ();
		  }
	    }
	  menuItem =
	      new wxMenuItem (&menu, Grid_Clear, wxT ("&Clear selection"));
	  menu.Append (menuItem);
	  menuItem = new wxMenuItem (&menu, Grid_All, wxT ("Select &all"));
	  menu.Append (menuItem);
	  menuItem = new wxMenuItem (&menu, Grid_Row, wxT ("Select &row"));
	  menu.Append (menuItem);
	  menuItem =
	      new wxMenuItem (&menu, Grid_Column, wxT ("&Select column"));
	  menu.Append (menuItem);
	  menu.AppendSeparator ();
	  menuItem = new wxMenuItem (&menu, Grid_Copy, wxT ("&Copy"));
	  menu.Append (menuItem);
	  if (TableView->IsSelection () == false)
	      menuItem->Enable (false);
      }
    TableView->PopupMenu (&menu, pt);
}

void
MyQueryView::OnCellSelected (wxGridEvent & event)
{
//
// cell selection changed
//
    if (InsertPending == true)
      {
	  // an INSERT row is still pending
	  if (event.GetRow () != TableView->GetNumberRows () - 1)
	      DoInsert (false);
      }
    event.Skip ();
}

void
MyQueryView::OnCellChanged (wxGridEvent & event)
{
//
// user changed value in some cell
//
    MyVariant *oldValue;
    MyVariant *insValue;
    wxString value;
    wxString numValue;
    wxString newValue = wxT ("NULL");
    wxString sql;
    wxString rowid;
    char *errMsg = NULL;
    bool error = false;
    long int_value;
    bool okIntValue = false;
    double dbl_value;
    bool okDblValue = false;
    int ret;
    int row = event.GetRow ();
    int column = event.GetCol ();
    value = TableView->GetCellValue (row, column);
    if (InsertPending == true)
      {
	  // an INSERT row is still pending
	  insValue = InsertRow->GetColumn (column);
	  numValue = value;
	  numValue.Replace (wxT (","), wxT ("."));
	  okIntValue = numValue.ToLong (&int_value);
	  okDblValue = numValue.ToDouble (&dbl_value);
	  if (okIntValue == true)
	      insValue->Set ((int) int_value);
	  else if (okDblValue == true)
	      insValue->Set (dbl_value);
	  else
	      insValue->Set (value);
	  if (row != TableView->GetNumberRows () - 1)
	      DoInsert (false);
	  return;
      }
    if (value.Len () > 0)
      {
	  numValue = value;
	  numValue.Replace (wxT (","), wxT ("."));
	  okIntValue = numValue.ToLong (&int_value);
	  okDblValue = numValue.ToDouble (&dbl_value);
	  if (okIntValue == true)
	      newValue.Printf (wxT ("%d"), int_value);
	  else if (okDblValue == true)
	      newValue.Printf (wxT ("%1.6lf"), dbl_value);
	  else
	    {
		value.Replace (wxT ("'"), wxT ("''"));
		newValue = wxT ("'") + value + wxT ("'");
	    }
      }
    oldValue = TableValues->GetValue (row, 0);
    rowid.Printf (wxT ("%d"), oldValue->GetIntValue ());
    sql =
	wxT ("UPDATE ") + TableName + wxT (" SET ") +
	TableView->GetColLabelValue (column) + wxT (" = ") + newValue +
	wxT (" WHERE ROWID = ") + rowid;
    ret =
	sqlite3_exec (MainFrame->GetSqlite (), sql.ToUTF8 (), NULL, NULL,
		      &errMsg);
    if (ret != SQLITE_OK)
      {
	  wxMessageBox (wxT ("SQLite SQL error: ") +
			wxString::FromUTF8 (errMsg), wxT ("spatialite-gui"),
			wxOK | wxICON_ERROR, this);
	  sqlite3_free (errMsg);
	  error = true;
      }
    oldValue = TableValues->GetValue (row, column);
    if (error == true)
      {
	  // update failed; restorig old cell value
	  value = wxT ("NULL");
	  if (oldValue)
	    {
		if (oldValue->GetType () == MY_INT_VARIANT)
		    value.Printf (wxT ("%d"), oldValue->GetIntValue ());
		if (oldValue->GetType () == MY_DBL_VARIANT)
		    value.Printf (wxT ("%1.6lf"), oldValue->GetDblValue ());
		if (oldValue->GetType () == MY_TXT_VARIANT)
		    value = oldValue->GetTxtValue ();
	    }
	  TableView->SetCellValue (row, column, value);
	  TableView->ForceRefresh ();
      }
    else
      {
	  // marking cell as modified
	  TableView->SetCellTextColour (row, column, wxColour (0, 0, 192));
	  TableView->SetCellBackgroundColour (row, column,
					      wxColour (255, 255, 204));
	  TableView->ForceRefresh ();
      }
}

void
MyQueryView::DoInsert (bool confirmed)
{
//
// performing actual row INSERT
//
    int i;
    int ret;
    MyVariant *var;
    wxString value;
    wxString strValue;
    wxString sql;
    char *errMsg = NULL;
    if (confirmed == false)
      {
	  ret =
	      wxMessageBox (wxT
			    ("A new row is ready for insertion\n\nConfirm ?"),
			    wxT ("spatialite-gui"), wxYES_NO | wxICON_QUESTION,
			    this);
	  if (ret != wxYES)
	      goto close_insert;
      }
    sql = wxT ("INSERT INTO ") + TableName + wxT (" (");
    for (i = 1; i < TableView->GetNumberCols (); i++)
      {
	  if (i > 1)
	      sql += wxT (", ");
	  sql += TableView->GetColLabelValue (i);
      }
    sql += wxT (") VALUES (");
    for (i = 1; i < InsertRow->GetNumCols (); i++)
      {
	  if (i > 1)
	      sql += wxT (", ");
	  var = InsertRow->GetColumn (i);
	  value = wxT ("NULL");
	  if (var->GetType () == MY_INT_VARIANT)
	      value.Printf (wxT ("%d"), var->GetIntValue ());
	  if (var->GetType () == MY_DBL_VARIANT)
	      value.Printf (wxT ("%d"), var->GetDblValue ());
	  if (var->GetType () == MY_TXT_VARIANT)
	    {
		strValue = var->GetTxtValue ();
		strValue.Replace (wxT ("'"), wxT ("''"));
		value = wxT ("'") + strValue + wxT ("'");
	    }
	  sql += value;
      }
    sql += wxT (")");
    ret =
	sqlite3_exec (MainFrame->GetSqlite (), sql.ToUTF8 (), NULL, NULL,
		      &errMsg);
    if (ret != SQLITE_OK)
      {
	  wxMessageBox (wxT ("SQLite SQL error: ") +
			wxString::FromUTF8 (errMsg), wxT ("spatialite-gui"),
			wxOK | wxICON_ERROR, this);
	  sqlite3_free (errMsg);
      }
  close_insert:
//
// closing insert row
//
    InsertPending = false;
    delete InsertRow;
    InsertRow = NULL;
    for (i = 0; i < TableView->GetNumberCols (); i++)
      {
	  TableView->SetCellValue (TableView->GetNumberRows () - 1, i,
				   wxT (""));
	  TableView->SetCellBackgroundColour (TableView->GetNumberRows () - 1,
					      i, wxColour (0, 0, 0));
	  TableView->SetReadOnly (TableView->GetNumberRows () - 1, i);
      }
}

void
MyQueryView::OnCmdDelete (wxCommandEvent & event)
{
//
// user required row deletion
//
    char *errMsg = NULL;
    bool error = false;
    int ret;
    int i;
    wxString sql;
    wxString rowid;
    MyVariant *value;
    MyRowVariant *varRow = TableValues->GetRow (CurrentEvtRow);
    if (varRow->IsDeleted () == true)
	return;
    value = TableValues->GetValue (CurrentEvtRow, 0);
    rowid.Printf (wxT ("%d"), value->GetIntValue ());
    ret =
	wxMessageBox (wxT ("Requested deletion for row identified by RowId = ")
		      + rowid + wxT ("\n\nConfirm ?"), wxT ("spatialite-gui"),
		      wxYES_NO | wxICON_QUESTION, this);
    if (ret != wxYES)
	return;
    sql = wxT ("DELETE FROM ") + TableName + wxT (" WHERE ROWID = ") + rowid;
    ret =
	sqlite3_exec (MainFrame->GetSqlite (), sql.ToUTF8 (), NULL, NULL,
		      &errMsg);
    if (ret != SQLITE_OK)
      {
	  wxMessageBox (wxT ("SQLite SQL error: ") +
			wxString::FromUTF8 (errMsg), wxT ("spatialite-gui"),
			wxOK | wxICON_ERROR, this);
	  sqlite3_free (errMsg);
	  error = true;
      }
    if (error == false)
      {
	  // marking row as deleted
	  varRow->SetDeleted ();
	  for (i = 0; i < TableView->GetNumberCols (); i++)
	    {
		TableView->SetCellTextColour (CurrentEvtRow, i,
					      wxColour (0, 0, 0));
		TableView->SetCellBackgroundColour (CurrentEvtRow, i,
						    wxColour (128, 128, 128));
		TableView->SetReadOnly (CurrentEvtRow, i);
	    }
	  TableView->ForceRefresh ();
      }
}

void
MyQueryView::OnCmdInsert (wxCommandEvent & event)
{
//
// user required row insertion
//
    int i;
    if (ReadOnly == true)
	return;
    if (InsertPending == true)
      {
	  // an INSERT is still pending, and the user required actual insertion
	  DoInsert (true);
	  return;
      }
    InsertRow = new MyRowVariant (TableView->GetNumberCols ());
    TableView->MakeCellVisible (TableView->GetNumberRows () - 1, 1);
    InsertPending = true;
    for (i = 1; i < TableView->GetNumberCols (); i++)
      {
	  TableView->SetCellValue (TableView->GetNumberRows () - 1, i,
				   wxT (""));
	  TableView->SetCellBackgroundColour (TableView->GetNumberRows () - 1,
					      i, wxColour (255, 255, 255));
	  TableView->SetReadOnly (TableView->GetNumberRows () - 1, i, false);
      }
}

void
MyQueryView::OnCmdAbort (wxCommandEvent & event)
{
//
// user cancelled current row insertion
//
    int i;
    if (InsertPending)
      {
	  InsertPending = false;
	  delete InsertRow;
	  InsertRow = NULL;
	  for (i = 0; i < TableView->GetNumberCols (); i++)
	    {
		TableView->SetCellValue (TableView->GetNumberRows () - 1, i,
					 wxT (""));
		TableView->SetCellBackgroundColour (TableView->
						    GetNumberRows () - 1, i,
						    wxColour (0, 0, 0));
		TableView->SetReadOnly (TableView->GetNumberRows () - 1, i);
	    }
      }
}

void
MyQueryView::OnCmdClearSelection (wxCommandEvent & event)
{
//
// clearing current selection
//
    TableView->ClearSelection ();
}

void
MyQueryView::OnCmdSelectAll (wxCommandEvent & event)
{
//
// selecting all
//
    TableView->SelectAll ();
}

void
MyQueryView::OnCmdSelectRow (wxCommandEvent & event)
{
//
// selecting the current row
//
    TableView->SelectRow (CurrentEvtRow);
}

void
MyQueryView::OnCmdSelectColumn (wxCommandEvent & event)
{
//
// selecting column
//
    TableView->SelectCol (CurrentEvtColumn);
}

void
MyQueryView::OnCmdCopy (wxCommandEvent & event)
{
//
// copying the selection into the clipboard
//
    wxString copyData;
    int row;
    int col;
    bool newRow;
    bool firstRow = true;
    for (row = 0; row < TableView->GetNumberRows (); row++)
      {
	  newRow = true;
	  for (col = 0; col < TableView->GetNumberCols (); col++)
	    {
		if (TableView->IsInSelection (row, col) == true)
		  {
		      // ok, this cell is included into the selection to copy
		      if (firstRow == true)
			{
			    newRow = false;
			    firstRow = false;
			}
		      else if (newRow == true)
			{
			    newRow = false;
			    copyData += wxT ("\n");
			}
		      else
			  copyData += wxT ("\t");
		      copyData += TableView->GetCellValue (row, col);
		  }
	    }
      }
    if (wxTheClipboard->Open ())
      {
	  wxTheClipboard->SetData (new wxTextDataObject (copyData));
	  wxTheClipboard->Close ();
      }
}

void
MyQueryView::OnCmdBlob (wxCommandEvent & event)
{
//
// exploring some BLOB value
//
    if (!CurrentBlob)
	return;
    BlobExplorerDialog dlg;
    dlg.Create (MainFrame, CurrentBlob->GetBlobSize (),
		CurrentBlob->GetBlob ());
    dlg.ShowModal ();
}

void
MyQueryView::OnCmdBlobIn (wxCommandEvent & event)
{
// importing an external file into a BLOB-value
    FILE *in = NULL;
    char path[2048];
    int rd;
    int maxSize = 1024 * 1024;	// limit BLOB size to 1MB
    wxString fileList;
    wxString rowid;
    wxString sql;
    wxString blobValue;
    wxString hex;
    MyVariant *value;
    bool error = false;
    unsigned char *buffer = NULL;
    int ret;
    char *errMsg = NULL;
    wxString lastDir;
    fileList =
	wxT
	("BLOB Document (*.jpg;*.jpeg;*.png;*.gif;*.pdf;*.zip)|*.jpg;*.jpeg;*.png;*.gif;*.pdf;*.zip|");
    fileList +=
	wxT ("Image (*.jpg;*.jpeg;*.png;*.gif)|*.jpg;*.jpeg;*.png;*.gif|");
    fileList +=
	wxT
	("JPEG Image (*.jpg;*.jpeg)|*.jpg;*.jpeg|PNG Image (*.png)|*.png|GIF Image (*.gif)|*.gif");
    fileList +=
	wxT
	("PDF Document (*.pdf)|*.pdf|ZIP Archive|(*.zip)|All files (*.*)|*.*");
    wxFileDialog *fileDialog =
	new wxFileDialog (this, wxT ("loading a BLOB value"),
			  wxT (""), wxT (""), fileList,
			  wxFD_OPEN | wxFD_FILE_MUST_EXIST, wxDefaultPosition,
			  wxDefaultSize, wxT ("filedlg"));
    lastDir = MainFrame->GetLastDirectory ();
    if (lastDir.Len () >= 1)
	fileDialog->SetDirectory (lastDir);
    ret = fileDialog->ShowModal ();
    if (ret == wxID_OK)
      {
	  strcpy (path, fileDialog->GetPath ().ToUTF8 ());
	  in = fopen (path, "rb");
	  if (!in)
	    {
		wxMessageBox (wxT ("Cannot open '") + fileDialog->GetPath () +
			      wxT ("' for reading"), wxT ("spatialite-gui"),
			      wxOK | wxICON_ERROR, this);
		return;
	    }
	  wxFileName file (fileDialog->GetPath ());
	  lastDir = file.GetPath ();
	  MainFrame->SetLastDirectory (lastDir);
	  ::wxBeginBusyCursor ();
	  buffer = new unsigned char[maxSize];
	  rd = fread (buffer, 1, maxSize, in);
	  if (rd == maxSize && !(feof (in)))
	    {
		// exceding 1MB; it's too big for a BLOB
		wxMessageBox (wxT
			      ("Selected file excedes 1MB; cowardly refusing to load it as a BLOB value ..."),
			      wxT ("spatialite-gui"), wxOK | wxICON_ERROR,
			      this);
		goto end;
	    }
	  if (ferror (in))
	    {
		// I/O error
		wxMessageBox (wxT ("an I/O error occurred"),
			      wxT ("spatialite-gui"), wxOK | wxICON_ERROR,
			      this);
		goto end;
	    }
	  //
	  // preparing  theSQL UPDATE statement
	  //
	  value = TableValues->GetValue (CurrentEvtRow, 0);
	  rowid.Printf (wxT ("%d"), value->GetIntValue ());
	  HexBlobValue (buffer, rd, hex);
	  sql =
	      wxT ("UPDATE ") + TableName + wxT (" SET ") +
	      TableView->GetColLabelValue (CurrentEvtColumn);
	  sql += wxT (" = ") + hex + wxT (" WHERE ROWID = ") + rowid;
	  ret =
	      sqlite3_exec (MainFrame->GetSqlite (), sql.ToUTF8 (), NULL, NULL,
			    &errMsg);
	  if (ret != SQLITE_OK)
	    {
		wxMessageBox (wxT ("SQLite SQL error: ") +
			      wxString::FromUTF8 (errMsg),
			      wxT ("spatialite-gui"), wxOK | wxICON_ERROR,
			      this);
		sqlite3_free (errMsg);
		error = true;
	    }
	  ::wxEndBusyCursor ();
	  value = TableValues->GetValue (CurrentEvtRow, CurrentEvtColumn);
	  if (error == false)
	    {
		// updating the Grid cell
		blobValue.Printf (wxT ("BLOB sz=%d "), rd);
		switch (MainFrame->GuessBlobType (rd, buffer))
		  {
		  case MyFrame::BLOB_EXIF:
		  case MyFrame::BLOB_JFIF:
		  case MyFrame::BLOB_JPEG:
		      blobValue += wxT ("JPEG image");
		      break;
		  case MyFrame::BLOB_PNG:
		      blobValue += wxT ("PNG image");
		      break;
		  case MyFrame::BLOB_GIF:
		      blobValue += wxT ("GIF image");
		      break;
		  case MyFrame::BLOB_PDF:
		      blobValue += wxT ("PDF document");
		      break;
		  case MyFrame::BLOB_ZIP:
		      blobValue += wxT ("ZIP archive");
		      break;
		  default:
		      blobValue += wxT ("UNKNOWN type");
		  };
		TableView->SetCellValue (CurrentEvtRow, CurrentEvtColumn,
					 blobValue);
		TableView->SetCellTextColour (CurrentEvtRow, CurrentEvtColumn,
					      wxColour (0, 0, 192));
		TableView->SetCellBackgroundColour (CurrentEvtRow,
						    CurrentEvtColumn,
						    wxColour (255, 255, 204));
		TableView->ForceRefresh ();
	    }
      }
  end:
// clean-up
    if (in)
	fclose (in);
    if (buffer)
	delete[]buffer;
}

void
MyQueryView::HexBlobValue (unsigned char *blob, int size, wxString & hex)
{
//
// builds the HEX BLOB as X'01234567890abcdef'
//
    int i;
    wxString digit;
    hex = wxT ("X'");
    for (i = 0; i < size; i++)
      {
	  digit.Printf (wxT ("%02x"), *(blob + i));
	  hex += digit;
      }
    hex += wxT ("'");
}

void
MyQueryView::OnCmdBlobOut (wxCommandEvent & event)
{
// exporting to external file a BLOB-value
    int blobType;
    wxString fileName;
    wxString fileType;
    int ret;
    wxString path;
    FILE *out = NULL;
    char xpath[2048];
    int wr;
    wxString lastDir;
    if (!CurrentBlob)
	return;
    blobType =
	MainFrame->GuessBlobType (CurrentBlob->GetBlobSize (),
				  CurrentBlob->GetBlob ());
    switch (blobType)
      {
      case MyFrame::BLOB_EXIF:
      case MyFrame::BLOB_JFIF:
      case MyFrame::BLOB_JPEG:
	  fileName = wxT ("image.jpg");
	  fileType = wxT ("File JPEG (*.jpg;*.jpeg)|*.jpg");
	  break;
      case MyFrame::BLOB_PNG:
	  fileName = wxT ("image.png");
	  fileType = wxT ("File PNG (*.png)|*.png");
	  break;
      case MyFrame::BLOB_GIF:
	  fileName = wxT ("image.gif");
	  fileType = wxT ("File GIF (*.gif)|*.gif");
	  break;
      case MyFrame::BLOB_PDF:
	  fileName = wxT ("document.pdf");
	  fileType = wxT ("PDF document (*.jpg;*.jpeg)|*.jpg");
	  break;
      case MyFrame::BLOB_ZIP:
	  fileName = wxT ("archive.zip");
	  fileType = wxT ("ZIP Archive (*.zip)|*.zip");
	  break;
      default:
	  fileName = wxT ("file");
      };
    fileType += wxT ("|All files (*.*)|*.*");
    wxFileDialog *fileDialog =
	new wxFileDialog (this, wxT ("exporting a BLOB value to file"),
			  wxT (""), fileName, fileType,
			  wxFD_SAVE | wxFD_OVERWRITE_PROMPT, wxDefaultPosition,
			  wxDefaultSize, wxT ("filedlg"));
    lastDir = MainFrame->GetLastDirectory ();
    if (lastDir.Len () >= 1)
	fileDialog->SetDirectory (lastDir);
    ret = fileDialog->ShowModal ();
    if (ret == wxID_OK)
      {
	  wxFileName file (fileDialog->GetPath ());
	  path = file.GetPath ();
	  path += file.GetPathSeparator ();
	  path += file.GetName ();
	  switch (blobType)
	    {
	    case MyFrame::BLOB_EXIF:
	    case MyFrame::BLOB_JFIF:
	    case MyFrame::BLOB_JPEG:
		path += wxT (".jpg");
		break;
	    case MyFrame::BLOB_PNG:
		path += wxT (".png");
		break;
	    case MyFrame::BLOB_GIF:
		path += wxT (".gif");
		break;
	    case MyFrame::BLOB_PDF:
		path += wxT (".pdf");
		break;
	    case MyFrame::BLOB_ZIP:
		path += wxT (".zip");
		break;
	    default:
		path += file.GetExt ();
	    };
	  strcpy (xpath, path.ToUTF8 ());
	  out = fopen (xpath, "wb");
	  if (!out)
	    {
		wxMessageBox (wxT ("Cannot open '") + path +
			      wxT ("' for writing"), wxT ("spatialite-gui"),
			      wxOK | wxICON_ERROR, this);
		return;
	    }
	  lastDir = file.GetPath ();
	  MainFrame->SetLastDirectory (lastDir);
	  ::wxBeginBusyCursor ();
	  wr = fwrite (CurrentBlob->GetBlob (), 1, CurrentBlob->GetBlobSize (),
		       out);
	  if (wr != CurrentBlob->GetBlobSize ())
	    {
		wxMessageBox (wxT ("an I/O error occurred"),
			      wxT ("spatialite-gui"), wxOK | wxICON_ERROR,
			      this);
	    }
	  fclose (out);
	  ::wxEndBusyCursor ();
      }
}

void
MyQueryView::OnCmdBlobNull (wxCommandEvent & event)
{
// setting to NULL a BLOB-value
    wxString rowid;
    wxString sql;
    int ret;
    char *errMsg = NULL;
    bool error = false;
    MyVariant *value;
    value = TableValues->GetValue (CurrentEvtRow, 0);
    rowid.Printf (wxT ("%d"), value->GetIntValue ());
    sql =
	wxT ("UPDATE ") + TableName + wxT (" SET ") +
	TableView->GetColLabelValue (CurrentEvtColumn);
    sql += wxT (" = NULL WHERE ROWID = ") + rowid;
    ret =
	sqlite3_exec (MainFrame->GetSqlite (), sql.ToUTF8 (), NULL, NULL,
		      &errMsg);
    if (ret != SQLITE_OK)
      {
	  wxMessageBox (wxT ("SQLite SQL error: ") +
			wxString::FromUTF8 (errMsg), wxT ("spatialite-gui"),
			wxOK | wxICON_ERROR, this);
	  sqlite3_free (errMsg);
	  error = true;
      }
    if (error == false)
      {
	  // updating the Grid cell
	  TableView->SetCellValue (CurrentEvtRow, CurrentEvtColumn,
				   wxT ("NULL"));
	  TableView->SetCellTextColour (CurrentEvtRow, CurrentEvtColumn,
					wxColour (0, 0, 192));
	  TableView->SetCellBackgroundColour (CurrentEvtRow, CurrentEvtColumn,
					      wxColour (255, 255, 204));
	  TableView->ForceRefresh ();
      }
}


|

|







 







<
<
<
<
<

|
|




<
<
<
<
|
>
>
>

|
<
>
|
|
|
|
|
<
>
|
|
|
|
|
|
|
|
<
>
|
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|

|
|
|
|
|
|
<
<
<
<
<
<
<
<
<
<
<
|
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
<
<
<
<
<
<
<
<


<
|




|
|
|
|
|


<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|




|
|
|
|
<
<
<
<
<
<
<
<
|
|
<
<
|
>
>

<
>

<
<
<
<
<
<
<
<
>
>


<
|




|
|


<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|




<
|
|
|
<
<
>
>
|
|


<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|




>
>
|
<
<
<
<
<
<
<
<
<
<
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>


<
|




<
|
<
>
>
|
<


<
|




|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
1
2
3
4
5
6
7
8
9
10
11
12
..
32
33
34
35
36
37
38





39
40
41
42
43
44
45




46
47
48
49
50
51

52
53
54
55
56
57

58
59
60
61
62
63
64
65
66

67
68
69



























70
71
72
73
74
75
76
77











78
79




















80








81
82

83
84
85
86
87
88
89
90
91
92
93
94

















95
96
97
98
99
100
101
102
103








104
105


106
107
108
109

110
111








112
113
114
115

116
117
118
119
120
121
122
123
124






















125
126
127
128
129

130
131
132


133
134
135
136
137
138



























































































































































































































































































































































































139
140
141
142
143
144
145
146










147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172

173
174
175
176
177

178

179
180
181

182
183

184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012





















































































/*
/ QueryView.cpp
/ a panel to set SQL queries
/
/ version 1.2, 2008 October 9
/
/ Author: Sandro Furieri a-furieri@lqt.it
/
/ Copyright (C) 2008  Alessandro Furieri
/
/    This program is free software: you can redistribute it and/or modify
/    it under the terms of the GNU General Public License as published by
................................................................................
// ICONs in XPM format [universally portable]
//
#include "icons/sql_go.xpm"
#include "icons/hs_back.xpm"
#include "icons/hs_back_no.xpm"
#include "icons/hs_forward.xpm"
#include "icons/hs_forward_no.xpm"






MyQueryView::MyQueryView(MyFrame * parent, wxWindowID id):
wxPanel(parent, id, wxDefaultPosition, wxSize(440, 76), wxBORDER_SUNKEN)
{
//
// constructor: a frame for SQL Queries
//




  MainFrame = parent;
  BracketStart = -1;
  BracketEnd = -1;
  IgnoreEvent = false;
// SQL statement
  SqlCtrl =

    new MySqlControl(this, ID_SQL, wxT(""), wxPoint(40, 5),
                     wxSize(20, 20),
                     wxTE_MULTILINE | wxTE_PROCESS_ENTER | wxTE_PROCESS_TAB |
                     wxHSCROLL | wxTE_RICH);
  BtnSqlGo =
    new wxBitmapButton(this, ID_SQL_GO, wxBitmap(sql_go_xpm), wxPoint(340, 5),

                       wxSize(32, 69));
  BtnSqlGo->SetToolTip(wxT("Execute SQL statement"));
  BtnHistoryBack =
    new wxBitmapButton(this, ID_HISTORY_BACK, wxBitmap(hs_back_xpm),
                       wxPoint(5, 5), wxSize(32, 32));
  BtnHistoryBack->SetBitmapDisabled(wxBitmap(hs_back_no_xpm));
  BtnHistoryBack->SetToolTip(wxT("History: previous SQL statement"));
  BtnHistoryForward =
    new wxBitmapButton(this, ID_HISTORY_FORWARD, wxBitmap(hs_forward_xpm),

                       wxPoint(5, 40), wxSize(32, 32));
  BtnHistoryForward->SetBitmapDisabled(wxBitmap(hs_forward_no_xpm));
  BtnHistoryForward->SetToolTip(wxT("History: next SQL statement"));



























  SetHistoryStates();
// setting up event handlers
  Connect(ID_SQL_GO, wxEVT_COMMAND_BUTTON_CLICKED,
          (wxObjectEventFunction) & MyQueryView::OnSqlGo);
  Connect(ID_HISTORY_BACK, wxEVT_COMMAND_BUTTON_CLICKED,
          (wxObjectEventFunction) & MyQueryView::OnHistoryBack);
  Connect(ID_HISTORY_FORWARD, wxEVT_COMMAND_BUTTON_CLICKED,
          (wxObjectEventFunction) & MyQueryView::OnHistoryForward);











  Connect(wxID_ANY, wxEVT_SIZE, (wxObjectEventFunction) & MyQueryView::OnSize);
  Connect(wxID_ANY, wxEVT_COMMAND_TEXT_UPDATED,




















          (wxObjectEventFunction) & MyQueryView::OnSqlSyntaxColor);








}


void MyQueryView::ShowControls()
{
//
// making all SQL controls to be visible
//
  SqlCtrl->Show(true);
  BtnSqlGo->Show(true);
  BtnHistoryBack->Show(true);
  BtnHistoryForward->Show(true);
  SetHistoryStates();
}


















void MyQueryView::HideControls()
{
//
// making all controls to be invisible
//
  SqlCtrl->Show(false);
  BtnSqlGo->Show(false);
  BtnHistoryBack->Show(false);
  BtnHistoryForward->Show(false);









}



void MyQueryView::AddToHistory(wxString & sql)
{
//

// adds an SQL statement to history
//








  History.Add(sql);
  SetHistoryStates();
}


void MyQueryView::SetHistoryStates()
{
//
// updates the history buttons state
//
  BtnHistoryForward->Enable(History.TestNext());
  BtnHistoryBack->Enable(History.TestPrev());
}























void MyQueryView::SetSql(wxString & sql, bool execute)
{
//
// sets an SQL statement [and maybe executes it]
//

  SqlCtrl->SetValue(sql);
  if (execute == true)
    {


      if (MainFrame->GetRsView()->ExecuteSql(sql, 0, true) == false)
        wxMessageBox(MainFrame->GetRsView()->GetSqlErrorMsg(),
                     wxT("spatialite-gui"), wxOK | wxICON_ERROR, MainFrame);
    }
}




























































































































































































































































































































































































void MyQueryView::OnSize(wxSizeEvent & event)
{
//
// this window has changed its size
//
  int vert;
  int vertBack;
  wxSize sz = GetClientSize();










// setting the SQL statement pane size
  SqlCtrl->SetSize(sz.GetWidth() - 80, sz.GetHeight() - 10);
// setting the SQL GO button position
  vert = (sz.GetHeight() - 69) / 2;
  if (vert < 5)
    vert = 5;
  BtnSqlGo->Move(sz.GetWidth() - 35, 5);
// setting the SQL GO button size
  vert = sz.GetHeight() - 10;
  if (vert < 66)
    vert = 66;
  BtnSqlGo->SetSize(32, vert);
// setting the HISTORY BACK button position
  BtnHistoryBack->Move(5, 5);
// setting the HISTORY BACK button size
  vert = (sz.GetHeight() - 15) / 2;
  if (vert < 32)
    vert = 32;
  BtnHistoryBack->SetSize(32, vert);
  vertBack = 10 + vert;
// setting the HISTORY FORWARD button position
  BtnHistoryForward->Move(5, vertBack);
// setting the HISTORY FORWARD button size
  BtnHistoryForward->SetSize(32, vert);
}


void MyQueryView::OnSqlGo(wxCommandEvent & WXUNUSED(event))
{
//
// executing an SQL statement
//

  wxString sql = SqlCtrl->GetValue();

  if (MainFrame->GetRsView()->ExecuteSql(sql, 0, true) == false)
    wxMessageBox(MainFrame->GetRsView()->GetSqlErrorMsg(),
                 wxT("spatialite-gui"), wxOK | wxICON_ERROR, MainFrame);

}


void MyQueryView::OnHistoryBack(wxCommandEvent & WXUNUSED(event))
{
//
// going backward into the SQL Queries History
//
  MySqlQuery *sql = History.GetPrev();
  if (sql)
    {
      SetSql(sql->GetSql(), false);
      SetHistoryStates();
    }
}

void MyQueryView::OnHistoryForward(wxCommandEvent & WXUNUSED(event))
{
//
// going forward into the SQL Queries History
//
  MySqlQuery *sql = History.GetNext();
  if (sql)
    {
      SetSql(sql->GetSql(), false);
      SetHistoryStates();
    }
}

bool MyQueryView::IsSqlString(wxString & str)
{
// checks if this one is an SQL string constant
  char word[4096];
  strcpy(word, str.ToUTF8());
  int len = strlen(word);
  if (len < 2)
    return false;
  if (word[0] == '\'' && word[len - 1] == '\'')
    return true;
  if (word[0] == '"' && word[len - 1] == '"')
    return true;
  return false;
}

bool MyQueryView::IsSqlNumber(wxString & str)
{
// checks if this one is an SQL numeric constant
  double dbl;
  return str.ToDouble(&dbl);
}

bool MyQueryView::IsSqliteExtra(wxString & str)
{
// checks if this one is an extra SQLite keyword
  if (str.CmpNoCase(wxT("asc")) == 0)
    return true;
  if (str.CmpNoCase(wxT("desc")) == 0)
    return true;
  if (str.CmpNoCase(wxT("null")) == 0)
    return true;
  if (str.CmpNoCase(wxT("trigger")) == 0)
    return true;
  if (str.CmpNoCase(wxT("for")) == 0)
    return true;
  if (str.CmpNoCase(wxT("each")) == 0)
    return true;
  if (str.CmpNoCase(wxT("row")) == 0)
    return true;
  if (str.CmpNoCase(wxT("begin")) == 0)
    return true;
  if (str.CmpNoCase(wxT("end")) == 0)
    return true;
  if (str.CmpNoCase(wxT("before")) == 0)
    return true;
  if (str.CmpNoCase(wxT("after")) == 0)
    return true;
  if (str.CmpNoCase(wxT("virtual")) == 0)
    return true;
  return false;
}

bool MyQueryView::IsSqlFunction(wxString & str, char next_c)
{
// checks if this one is an SQL function
  if (next_c != '(')
    return false;
  if (str.CmpNoCase(wxT("raise")) == 0)
    return true;
  if (str.CmpNoCase(wxT("avg")) == 0)
    return true;
  if (str.CmpNoCase(wxT("count")) == 0)
    return true;
  if (str.CmpNoCase(wxT("group_concat")) == 0)
    return true;
  if (str.CmpNoCase(wxT("max")) == 0)
    return true;
  if (str.CmpNoCase(wxT("min")) == 0)
    return true;
  if (str.CmpNoCase(wxT("sum")) == 0)
    return true;
  if (str.CmpNoCase(wxT("total")) == 0)
    return true;
  if (str.CmpNoCase(wxT("abs")) == 0)
    return true;
  if (str.CmpNoCase(wxT("coalesce")) == 0)
    return true;
  if (str.CmpNoCase(wxT("glob")) == 0)
    return true;
  if (str.CmpNoCase(wxT("ifnull")) == 0)
    return true;
  if (str.CmpNoCase(wxT("hex")) == 0)
    return true;
  if (str.CmpNoCase(wxT("last_insert_rowid")) == 0)
    return true;
  if (str.CmpNoCase(wxT("length")) == 0)
    return true;
  if (str.CmpNoCase(wxT("load_extension")) == 0)
    return true;
  if (str.CmpNoCase(wxT("lower")) == 0)
    return true;
  if (str.CmpNoCase(wxT("ltrim")) == 0)
    return true;
  if (str.CmpNoCase(wxT("nullif")) == 0)
    return true;
  if (str.CmpNoCase(wxT("quote")) == 0)
    return true;
  if (str.CmpNoCase(wxT("random")) == 0)
    return true;
  if (str.CmpNoCase(wxT("randomblob")) == 0)
    return true;
  if (str.CmpNoCase(wxT("replace")) == 0)
    return true;
  if (str.CmpNoCase(wxT("round")) == 0)
    return true;
  if (str.CmpNoCase(wxT("rtrim")) == 0)
    return true;
  if (str.CmpNoCase(wxT("soundex")) == 0)
    return true;
  if (str.CmpNoCase(wxT("sqlite_version")) == 0)
    return true;
  if (str.CmpNoCase(wxT("substr")) == 0)
    return true;
  if (str.CmpNoCase(wxT("trim")) == 0)
    return true;
  if (str.CmpNoCase(wxT("typeof")) == 0)
    return true;
  if (str.CmpNoCase(wxT("upper")) == 0)
    return true;
  if (str.CmpNoCase(wxT("zeroblob")) == 0)
    return true;
  return false;
}

bool MyQueryView::IsSqlGeoFunction(wxString & str, char next_c)
{
// checks if this one is an SQL geo-function
  if (next_c != '(')
    return false;
  if (str.CmpNoCase(wxT("MakePoint")) == 0)
    return true;
  if (str.CmpNoCase(wxT("BuildMbr")) == 0)
    return true;
  if (str.CmpNoCase(wxT("BuildCircleMbr")) == 0)
    return true;
  if (str.CmpNoCase(wxT("MbrMinX")) == 0)
    return true;
  if (str.CmpNoCase(wxT("MbrMinY")) == 0)
    return true;
  if (str.CmpNoCase(wxT("MbrMaxX")) == 0)
    return true;
  if (str.CmpNoCase(wxT("MbrMaxY")) == 0)
    return true;
  if (str.CmpNoCase(wxT("GeomFromText")) == 0)
    return true;
  if (str.CmpNoCase(wxT("PointFromText")) == 0)
    return true;
  if (str.CmpNoCase(wxT("LineFromText")) == 0)
    return true;
  if (str.CmpNoCase(wxT("LineStringFromText")) == 0)
    return true;
  if (str.CmpNoCase(wxT("PolyFromText")) == 0)
    return true;
  if (str.CmpNoCase(wxT("PolygonFromText")) == 0)
    return true;
  if (str.CmpNoCase(wxT("MPointFromText")) == 0)
    return true;
  if (str.CmpNoCase(wxT("MultiPointFromText")) == 0)
    return true;
  if (str.CmpNoCase(wxT("MLineFromText")) == 0)
    return true;
  if (str.CmpNoCase(wxT("MultiLineStringFromText")) == 0)
    return true;
  if (str.CmpNoCase(wxT("MPolyFromText")) == 0)
    return true;
  if (str.CmpNoCase(wxT("MultiPolygonFromText")) == 0)
    return true;
  if (str.CmpNoCase(wxT("GeomCollFromText")) == 0)
    return true;
  if (str.CmpNoCase(wxT("GeometryCollectionFromText")) == 0)
    return true;
  if (str.CmpNoCase(wxT("GeomFromWKB")) == 0)
    return true;
  if (str.CmpNoCase(wxT("PointFromWKB")) == 0)
    return true;
  if (str.CmpNoCase(wxT("LineFromWKB")) == 0)
    return true;
  if (str.CmpNoCase(wxT("LineStringFromWKB")) == 0)
    return true;
  if (str.CmpNoCase(wxT("PolyFromWKB")) == 0)
    return true;
  if (str.CmpNoCase(wxT("PolygonFromWKB")) == 0)
    return true;
  if (str.CmpNoCase(wxT("MPointFromWKB")) == 0)
    return true;
  if (str.CmpNoCase(wxT("MultiPointFromWKB")) == 0)
    return true;
  if (str.CmpNoCase(wxT("MLineFromWKB")) == 0)
    return true;
  if (str.CmpNoCase(wxT("MultiLineStringFromWKB")) == 0)
    return true;
  if (str.CmpNoCase(wxT("MPolyFromWKB")) == 0)
    return true;
  if (str.CmpNoCase(wxT("MultiPolygonFromWKB")) == 0)
    return true;
  if (str.CmpNoCase(wxT("GeomCollFromWKB")) == 0)
    return true;
  if (str.CmpNoCase(wxT("GeometryCollectionFromWKB")) == 0)
    return true;
  if (str.CmpNoCase(wxT("AsText")) == 0)
    return true;
  if (str.CmpNoCase(wxT("AsBinary")) == 0)
    return true;
  if (str.CmpNoCase(wxT("Dimension")) == 0)
    return true;
  if (str.CmpNoCase(wxT("GeometryType")) == 0)
    return true;
  if (str.CmpNoCase(wxT("SRID")) == 0)
    return true;
  if (str.CmpNoCase(wxT("SetSRID")) == 0)
    return true;
  if (str.CmpNoCase(wxT("IsEmpty")) == 0)
    return true;
  if (str.CmpNoCase(wxT("IsSimple")) == 0)
    return true;
  if (str.CmpNoCase(wxT("IsValid")) == 0)
    return true;
  if (str.CmpNoCase(wxT("Boundary")) == 0)
    return true;
  if (str.CmpNoCase(wxT("Envelope")) == 0)
    return true;
  if (str.CmpNoCase(wxT("X")) == 0)
    return true;
  if (str.CmpNoCase(wxT("Y")) == 0)
    return true;
  if (str.CmpNoCase(wxT("StartPoint")) == 0)
    return true;
  if (str.CmpNoCase(wxT("EndPoint")) == 0)
    return true;
  if (str.CmpNoCase(wxT("GLength")) == 0)
    return true;
  if (str.CmpNoCase(wxT("IsClosed")) == 0)
    return true;
  if (str.CmpNoCase(wxT("IsRing")) == 0)
    return true;
  if (str.CmpNoCase(wxT("Simplify")) == 0)
    return true;
  if (str.CmpNoCase(wxT("SimplifyPreserveTopology")) == 0)
    return true;
  if (str.CmpNoCase(wxT("NumPoints")) == 0)
    return true;
  if (str.CmpNoCase(wxT("PointN")) == 0)
    return true;
  if (str.CmpNoCase(wxT("Centroid")) == 0)
    return true;
  if (str.CmpNoCase(wxT("PointOnSurface")) == 0)
    return true;
  if (str.CmpNoCase(wxT("Area")) == 0)
    return true;
  if (str.CmpNoCase(wxT("ExteriorRing")) == 0)
    return true;
  if (str.CmpNoCase(wxT("NumInteriorRing")) == 0)
    return true;
  if (str.CmpNoCase(wxT("NumInteriorRings")) == 0)
    return true;
  if (str.CmpNoCase(wxT("InteriorRingN")) == 0)
    return true;
  if (str.CmpNoCase(wxT("NumGeometries")) == 0)
    return true;
  if (str.CmpNoCase(wxT("GeometryN")) == 0)
    return true;
  if (str.CmpNoCase(wxT("MbrEqual")) == 0)
    return true;
  if (str.CmpNoCase(wxT("MbrDisjoint")) == 0)
    return true;
  if (str.CmpNoCase(wxT("MbrTouches")) == 0)
    return true;
  if (str.CmpNoCase(wxT("MbrWithin")) == 0)
    return true;
  if (str.CmpNoCase(wxT("MbrOverlaps")) == 0)
    return true;
  if (str.CmpNoCase(wxT("MbrIntersects")) == 0)
    return true;
  if (str.CmpNoCase(wxT("MbrContains")) == 0)
    return true;
  if (str.CmpNoCase(wxT("Equals")) == 0)
    return true;
  if (str.CmpNoCase(wxT("Disjoint")) == 0)
    return true;
  if (str.CmpNoCase(wxT("Touches")) == 0)
    return true;
  if (str.CmpNoCase(wxT("Within")) == 0)
    return true;
  if (str.CmpNoCase(wxT("Overlaps")) == 0)
    return true;
  if (str.CmpNoCase(wxT("Crosses")) == 0)
    return true;
  if (str.CmpNoCase(wxT("Intersects")) == 0)
    return true;
  if (str.CmpNoCase(wxT("Contains")) == 0)
    return true;
  if (str.CmpNoCase(wxT("Relate")) == 0)
    return true;
  if (str.CmpNoCase(wxT("Distance")) == 0)
    return true;
  if (str.CmpNoCase(wxT("Intersection")) == 0)
    return true;
  if (str.CmpNoCase(wxT("Difference")) == 0)
    return true;
  if (str.CmpNoCase(wxT("GUnion")) == 0)
    return true;
  if (str.CmpNoCase(wxT("SymDifference")) == 0)
    return true;
  if (str.CmpNoCase(wxT("Buffer")) == 0)
    return true;
  if (str.CmpNoCase(wxT("ConvexHull")) == 0)
    return true;
  if (str.CmpNoCase(wxT("Transform")) == 0)
    return true;
  if (str.CmpNoCase(wxT("ShiftCoords")) == 0)
    return true;
  if (str.CmpNoCase(wxT("ShiftCoordinates")) == 0)
    return true;
  if (str.CmpNoCase(wxT("ScaleCoords")) == 0)
    return true;
  if (str.CmpNoCase(wxT("ScaleCoordinates")) == 0)
    return true;
  if (str.CmpNoCase(wxT("RotateCoords")) == 0)
    return true;
  if (str.CmpNoCase(wxT("RotateCoordinates")) == 0)
    return true;
  if (str.CmpNoCase(wxT("ReflectCoords")) == 0)
    return true;
  if (str.CmpNoCase(wxT("ReflectCoordinates")) == 0)
    return true;
  if (str.CmpNoCase(wxT("SwapCoords")) == 0)
    return true;
  if (str.CmpNoCase(wxT("SwapCoordinates")) == 0)
    return true;
  if (str.CmpNoCase(wxT("InitSpatialMetaData")) == 0)
    return true;
  if (str.CmpNoCase(wxT("AddGeometryColumn")) == 0)
    return true;
  if (str.CmpNoCase(wxT("RecoverGeometryColumn")) == 0)
    return true;
  if (str.CmpNoCase(wxT("DiscardGeometryColumn")) == 0)
    return true;
  if (str.CmpNoCase(wxT("CreateSpatialIndex")) == 0)
    return true;
  if (str.CmpNoCase(wxT("CreateMbrCache")) == 0)
    return true;
  if (str.CmpNoCase(wxT("DisableSpatialIndex")) == 0)
    return true;
  if (str.CmpNoCase(wxT("FilterMbrWithin")) == 0)
    return true;
  if (str.CmpNoCase(wxT("FilterMbrContains")) == 0)
    return true;
  if (str.CmpNoCase(wxT("FilterMbrIntersects")) == 0)
    return true;
  if (str.CmpNoCase(wxT("BuildMbrFilter")) == 0)
    return true;
  return false;
}

void MyQueryView::DoSqlSyntaxColor()
{
//
// evidencing a nice colored SQL syntax 
//
  IgnoreEvent = true;
  SqlCtrl->Hide();
  wxTextAttr normal_style(wxColour(128, 128, 128), wxColour(255, 255, 255),
                          wxFont(10, wxFONTFAMILY_MODERN, wxFONTSTYLE_NORMAL,
                                 wxFONTWEIGHT_NORMAL));
  wxTextAttr sql_style(wxColour(0, 0, 255), wxColour(255, 255, 255),
                       wxFont(10, wxFONTFAMILY_MODERN, wxFONTSTYLE_NORMAL,
                              wxFONTWEIGHT_BOLD));
  wxTextAttr const_style(wxColour(255, 0, 255), wxColour(255, 255, 255),
                         wxFont(10, wxFONTFAMILY_MODERN, wxFONTSTYLE_NORMAL,
                                wxFONTWEIGHT_NORMAL));
  wxTextAttr fnct_style(wxColour(192, 128, 0), wxColour(255, 255, 255),
                        wxFont(10, wxFONTFAMILY_MODERN, wxFONTSTYLE_NORMAL,
                               wxFONTWEIGHT_BOLD));
  wxTextAttr bracket_style(wxColour(255, 0, 0), wxColour(192, 192, 192),
                           wxFont(12, wxFONTFAMILY_ROMAN, wxFONTSTYLE_NORMAL,
                                  wxFONTWEIGHT_BOLD));
  wxString sql = SqlCtrl->GetValue();
// setting the base style
  SqlCtrl->SetStyle(0, sql.Len(), normal_style);
  wxString right = sql;
  int from;
  int to = 0;
  int i;
  char c;
  char next_c;
  SqlTokenizer tokenizer(sql);
  while (tokenizer.HasMoreTokens())
    {
      wxString token = tokenizer.GetNextToken();
      from = to + right.Find(token);
      to = from + token.Len();
      // extracting the unparsed portion of the SQL string
      right = sql.Mid(to);
      next_c = '\0';
      for (i = 0; i < (int) right.Len(); i++)
        {
          c = right.GetChar(i);
          if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
            continue;
          next_c = c;
          break;
        }
      char word[4096];
      strcpy(word, token.ToUTF8());
      if (gaiaIsReservedSqliteName(word))
        {
          // setting the SQL keyword style
          SqlCtrl->SetStyle(from, to, sql_style);
      } else if (IsSqliteExtra(token))
        {
          // setting the SQL keyword style
          SqlCtrl->SetStyle(from, to, sql_style);
      } else if (IsSqlString(token) == true)
        {
          // setting the SQL string constant style
          SqlCtrl->SetStyle(from, to, const_style);
      } else if (IsSqlNumber(token) == true)
        {
          // setting the SQL numeric constant style
          SqlCtrl->SetStyle(from, to, const_style);
      } else if (IsSqlFunction(token, next_c) == true)
        {
          // setting the SQL function style
          SqlCtrl->SetStyle(from, to, fnct_style);
      } else if (IsSqlGeoFunction(token, next_c) == true)
        {
          // setting the SQL geo-function style
          SqlCtrl->SetStyle(from, to, fnct_style);
        }
    }
  if (BracketStart >= 0)
    {
      // evidencing an opening bracket
      SqlCtrl->SetStyle(BracketStart, BracketStart + 1, bracket_style);
    }
  if (BracketEnd >= 0)
    {
      // evidencing a closing bracket
      SqlCtrl->SetStyle(BracketEnd, BracketEnd + 1, bracket_style);
    }
  SqlCtrl->Show();
  SqlCtrl->SetFocus();
  IgnoreEvent = false;
}

void MyQueryView::OnSqlSyntaxColor(wxCommandEvent & event)
{
//
// EVENT: updating the SQL syntax 
//
  if (IgnoreEvent == true)
    {
      // processing is still in progress; ignoring any internally generated call
      return;
    }
  event.Skip();
  EventBrackets();
}

void MyQueryView::EvidBrackets(int on, int off)
{
// evidencing corresponding brackets [open/close]
  BracketStart = -1;
  BracketEnd = -1;
  if (on >= 0)
    BracketStart = on;
  if (off >= 0)
    BracketEnd = off;
  DoSqlSyntaxColor();
}

void MyQueryView::EventBrackets()
{
//
// evidencing brackets [balancing open-close pairs] 
//
  if (IgnoreEvent == true)
    {
      // processing is still in progress; ignoring any internally generated call
      return;
    }
  int pos = SqlCtrl->GetInsertionPoint();
  int on;
  int off;
  wxString sql = SqlCtrl->GetValue();
  char pre = '\0';
  char post = '\0';
  if (pos > 0)
    pre = sql.GetChar(pos - 1);
  if (pos < (int) sql.Len())
    post = sql.GetChar(pos);
  if (post == '(')
    {
      // positioned before an opening bracket
      if (CheckBrackets(pos, false, &on, &off) == true)
        EvidBrackets(on, off);
      else
        EvidBrackets(pos, -1);
      return;
    }
  if (pre == ')')
    {
      // positioned after a closing bracket
      if (CheckBrackets(pos - 1, true, &on, &off) == true)
        EvidBrackets(on, off);
      else
        EvidBrackets(-1, pos - 1);
      return;
    }
  EvidBrackets(-1, -1);
}

bool MyQueryView::CheckBrackets(int pos, bool reverse_direction, int *on,
                                int *off)
{
// trying to balance a brackets pair [opening/closing]
  int i;
  int len;
  int level = 0;
  char c;
  int single_quoted = 0;
  int double_quoted = 0;
  wxString sql = SqlCtrl->GetValue();
  if (reverse_direction == true)
    {
      // going backward from CLOSE to OPEN
      for (i = pos - 1; i >= 0; i--)
        {
          c = sql.GetChar(i);
          if (c == '\'' && !double_quoted)
            {
              // single quoting start-stop
              if (single_quoted)
                single_quoted = 0;
              else
                single_quoted = 1;
            }
          if (c == '"' && !single_quoted)
            {
              // double quoting start-stop
              if (double_quoted)
                double_quoted = 0;
              else
                double_quoted = 1;
            }
          if (single_quoted || double_quoted)
            continue;
          if (c == ')')
            level++;
          if (c == '(')
            {
              if (level == 0)
                {
                  *on = i;
                  *off = pos;
                  return true;
                }
              level--;
            }
        }
  } else
    {
      // going forward from OPEN to CLOSE
      len = sql.Len();
      for (i = pos + 1; i < len; i++)
        {
          c = sql.GetChar(i);
          if (c == '\'' && !double_quoted)
            {
              // single quoting start-stop
              if (single_quoted)
                single_quoted = 0;
              else
                single_quoted = 1;
            }
          if (c == '"' && !single_quoted)
            {
              // double quoting start-stop
              if (double_quoted)
                double_quoted = 0;
              else
                double_quoted = 1;
            }
          if (single_quoted || double_quoted)
            continue;
          if (c == '(')
            level++;
          if (c == ')')
            {
              if (level == 0)
                {
                  *on = pos;
                  *off = i;
                  return true;
                }
              level--;
            }
        }
    }
  return false;
}

MySqlControl::MySqlControl(MyQueryView * parent, wxWindowID id, const wxString & value, const wxPoint & pos, const wxSize & size, long style):
wxTextCtrl(parent, id, value, pos, size, style)
{
//
// constructor: SQL text control
//
  Parent = parent;
  Connect(wxID_ANY, wxEVT_LEFT_DOWN,
          (wxObjectEventFunction) & MySqlControl::OnSqlMousePosition);
  Connect(wxID_ANY, wxEVT_KEY_UP,
          (wxObjectEventFunction) & MySqlControl::OnSqlArrowPosition);
}

void MySqlControl::OnSqlMousePosition(wxMouseEvent & event)
{
//
// intercepting mouse clicks
//
  if (Parent->IsIgnoreEvent() == true)
    return;
  event.Skip();
  Parent->EventBrackets();
}

void MySqlControl::OnSqlArrowPosition(wxKeyEvent & event)
{
//
// intercepting arrow keys
//
  if (Parent->IsIgnoreEvent() == true)
    return;
  event.Skip();
  int key_code = event.GetKeyCode();
  switch (key_code)
    {
      case WXK_DELETE:
      case WXK_HOME:
      case WXK_LEFT:
      case WXK_UP:
      case WXK_RIGHT:
      case WXK_DOWN:
      case WXK_PAGEUP:
      case WXK_PAGEDOWN:
      case WXK_NUMPAD_DELETE:
      case WXK_NUMPAD_HOME:
      case WXK_NUMPAD_LEFT:
      case WXK_NUMPAD_UP:
      case WXK_NUMPAD_RIGHT:
      case WXK_NUMPAD_DOWN:
      case WXK_NUMPAD_PAGEUP:
      case WXK_NUMPAD_PAGEDOWN:
        Parent->EventBrackets();
        break;
      default:
        break;
    };
}

SqlTokenizer::SqlTokenizer(wxString & sql)
{
// breaking tokens from an SQL expression
  Block = 1024;
  Max = Block;
  int i;
  char c;
  int single_quoted = 0;
  int double_quoted = 0;
  int white_space = 0;
  int start = -1;
  int len;
// initial allocation for the token list
  TokenList = new wxString *[Max];
  for (i = 0; i < Max; i++)
    TokenList[i] = NULL;
  Index = 0;
  for (i = 0; i < (int) sql.Len(); i++)
    {
      // scanning the SQL statement
      c = sql.GetChar(i);
      if (c == '\'' && !double_quoted)
        {
          if (single_quoted)
            {
              single_quoted = 0;
              len = i - start;
              len++;
              wxString *token = new wxString(sql.Mid(start, len));
              Insert(token);
              start = -1;
          } else
            {
              single_quoted = 1;
              start = i;
            }
          continue;
        }
      if (c == '"' && !single_quoted)
        {
          if (double_quoted)
            {
              double_quoted = 0;
              len = i - start;
              len++;
              wxString *token = new wxString(sql.Mid(start, len));
              Insert(token);
              start = -1;
          } else
            {
              double_quoted = 1;
              start = i;
            }
          continue;
        }
      if (single_quoted || double_quoted)
        continue;
      if (c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '('
          || c == ')' || c == ';' || c == ',')
        {
          if (white_space)
            continue;
          if (start >= 0)
            {
              // ok, we have a valid SQL token
              len = i - start;
              wxString *token = new wxString(sql.Mid(start, len));
              Insert(token);
            }
          start = -1;
          white_space = 1;
          continue;
        }
      white_space = 0;
      if (start < 0)
        start = i;
    }
  if (start >= 0)
    {
      // fetching the last token
      i = sql.Len();
      len = i - start;
      wxString *token = new wxString(sql.Mid(start, len));
      Insert(token);
    }
  Index = 0;
}

SqlTokenizer::~SqlTokenizer()
{
// destructor
  wxString *token;
  Index = 0;
  while (1)
    {
      token = TokenList[Index];
      if (token == NULL)
        break;
      delete token;
      Index++;
    }
  delete[]TokenList;
}

void SqlTokenizer::Expand()
{
// expanding the token list
  int newSize = Max + Block;
  int i;
  wxString **newList = new wxString *[newSize];
  for (i = 0; i < newSize; i++)
    newList[i] = NULL;
  for (i = 0; i < Max; i++)
    newList[i] = TokenList[i];
  delete[]TokenList;
  TokenList = newList;
  Max = newSize;
}

void SqlTokenizer::Insert(wxString * token)
{
// inserting a new token
  if (Index == (Max - 1))
    Expand();
  TokenList[Index++] = token;
}

bool SqlTokenizer::HasMoreTokens()
{
  wxString *token = TokenList[Index];
  if (token == NULL)
    return false;
  return true;
}

wxString & SqlTokenizer::GetNextToken()
{
// return the next token
  wxString *token = TokenList[Index];
  Index++;
  CurrentToken = *token;
  return CurrentToken;
}





















































































Added ResultSetView.cpp.







































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
/*
/ ResultSetView.cpp
/ a panel to show SQL query results
/
/ version 1.2, 2008 October 9
/
/ Author: Sandro Furieri a-furieri@lqt.it
/
/ Copyright (C) 2008  Alessandro Furieri
/
/    This program is free software: you can redistribute it and/or modify
/    it under the terms of the GNU General Public License as published by
/    the Free Software Foundation, either version 3 of the License, or
/    (at your option) any later version.
/
/    This program is distributed in the hope that it will be useful,
/    but WITHOUT ANY WARRANTY; without even the implied warranty of
/    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
/    GNU General Public License for more details.
/
/    You should have received a copy of the GNU General Public License
/    along with this program.  If not, see <http://www.gnu.org/licenses/>.
/
*/

#include "Classdef.h"

#include "wx/clipbrd.h"
#include "wx/filename.h"

//
// ICONs in XPM format [universally portable]
//
#include "icons/rs_first.xpm"
#include "icons/rs_last.xpm"
#include "icons/rs_next.xpm"
#include "icons/rs_previous.xpm"
#include "icons/refresh.xpm"

#if defined(_WIN32) || defined (__MINGW32__)
#define FORMAT_64	"%I64d"
#else
#define FORMAT_64	"%lld"
#endif

MyResultSetView::MyResultSetView(MyFrame * parent, wxWindowID id):
wxPanel(parent, id, wxDefaultPosition, wxSize(440, 480), wxBORDER_SUNKEN)
{
//
// constructor: a frame for SQL Result Sets
//
  RsBlock = 500;                // the ResultSet block size
  RowIds = new sqlite3_int64[RsBlock];
  ReadOnly = true;
  InsertRow = NULL;
  MainFrame = parent;
  BtnRsFirst =
    new wxBitmapButton(this, ID_RS_FIRST, wxBitmap(rs_first_xpm),
                       wxPoint(5, 400), wxSize(32, 32));
  BtnRsFirst->SetToolTip(wxT("ResultSet: go to first row"));
  BtnRsPrevious =
    new wxBitmapButton(this, ID_RS_PREVIOUS, wxBitmap(rs_previous_xpm),
                       wxPoint(55, 400), wxSize(32, 32));
  BtnRsPrevious->SetToolTip(wxT("ResultSet: go to previous block"));
  BtnRefresh =
    new wxBitmapButton(this, ID_REFRESH, wxBitmap(refresh_xpm),
                       wxPoint(55, 400), wxSize(32, 32));
  BtnRefresh->SetToolTip(wxT("ResultSet: refresh"));
  BtnRsNext =
    new wxBitmapButton(this, ID_RS_NEXT, wxBitmap(rs_next_xpm),
                       wxPoint(105, 400), wxSize(32, 32));
  BtnRsNext->SetToolTip(wxT("ResultSet: go to next block"));
  BtnRsLast =
    new wxBitmapButton(this, ID_RS_LAST, wxBitmap(rs_last_xpm),
                       wxPoint(155, 400), wxSize(32, 32));
  BtnRsLast->SetToolTip(wxT("ResultSet: go to last row"));
  RsCurrentBlock =
    new wxStaticText(this, ID_RS_BLOCK, wxT(""), wxPoint(210, 400),
                     wxSize(200, 18));
  TableView = NULL;
  TableBlobs = NULL;
  TableValues = NULL;
  CurrentBlob = NULL;
// setting up event handlers
  Connect(ID_RS_FIRST, wxEVT_COMMAND_BUTTON_CLICKED,
          (wxObjectEventFunction) & MyResultSetView::OnRsFirst);
  Connect(ID_RS_PREVIOUS, wxEVT_COMMAND_BUTTON_CLICKED,
          (wxObjectEventFunction) & MyResultSetView::OnRsPrevious);
  Connect(ID_RS_NEXT, wxEVT_COMMAND_BUTTON_CLICKED,
          (wxObjectEventFunction) & MyResultSetView::OnRsNext);
  Connect(ID_RS_LAST, wxEVT_COMMAND_BUTTON_CLICKED,
          (wxObjectEventFunction) & MyResultSetView::OnRsLast);
  Connect(ID_REFRESH, wxEVT_COMMAND_BUTTON_CLICKED,
          (wxObjectEventFunction) & MyResultSetView::OnRefresh);
  Connect(wxID_ANY, wxEVT_SIZE,
          (wxObjectEventFunction) & MyResultSetView::OnSize);
  Connect(wxID_ANY, wxEVT_GRID_SELECT_CELL,
          (wxObjectEventFunction) & MyResultSetView::OnCellSelected);
  Connect(wxID_ANY, wxEVT_GRID_CELL_RIGHT_CLICK,
          (wxObjectEventFunction) & MyResultSetView::OnRightClick);
  Connect(wxID_ANY, wxEVT_GRID_CELL_CHANGE,
          (wxObjectEventFunction) & MyResultSetView::OnCellChanged);
  Connect(Grid_Delete, wxEVT_COMMAND_MENU_SELECTED,
          (wxObjectEventFunction) & MyResultSetView::OnCmdDelete);
  Connect(Grid_Insert, wxEVT_COMMAND_MENU_SELECTED,
          (wxObjectEventFunction) & MyResultSetView::OnCmdInsert);
  Connect(Grid_Abort, wxEVT_COMMAND_MENU_SELECTED,
          (wxObjectEventFunction) & MyResultSetView::OnCmdAbort);
  Connect(Grid_Clear, wxEVT_COMMAND_MENU_SELECTED,
          (wxObjectEventFunction) & MyResultSetView::OnCmdClearSelection);
  Connect(Grid_All, wxEVT_COMMAND_MENU_SELECTED,
          (wxObjectEventFunction) & MyResultSetView::OnCmdSelectAll);
  Connect(Grid_Row, wxEVT_COMMAND_MENU_SELECTED,
          (wxObjectEventFunction) & MyResultSetView::OnCmdSelectRow);
  Connect(Grid_Column, wxEVT_COMMAND_MENU_SELECTED,
          (wxObjectEventFunction) & MyResultSetView::OnCmdSelectColumn);
  Connect(Grid_Copy, wxEVT_COMMAND_MENU_SELECTED,
          (wxObjectEventFunction) & MyResultSetView::OnCmdCopy);
  Connect(Grid_Blob, wxEVT_COMMAND_MENU_SELECTED,
          (wxObjectEventFunction) & MyResultSetView::OnCmdBlob);
  Connect(Grid_BlobIn, wxEVT_COMMAND_MENU_SELECTED,
          (wxObjectEventFunction) & MyResultSetView::OnCmdBlobIn);
  Connect(Grid_BlobOut, wxEVT_COMMAND_MENU_SELECTED,
          (wxObjectEventFunction) & MyResultSetView::OnCmdBlobOut);
  Connect(Grid_BlobNull, wxEVT_COMMAND_MENU_SELECTED,
          (wxObjectEventFunction) & MyResultSetView::OnCmdBlobNull);
}

MyResultSetView::~MyResultSetView()
{
// destructor
  if (RowIds)
    delete[]RowIds;
  if (InsertRow)
    delete InsertRow;
  if (TableBlobs)
    delete TableBlobs;
  if (TableValues)
    delete TableValues;
}

void MyResultSetView::ShowControls()
{
//
// making all ResultSet controls to be visible
//
  BtnRsFirst->Show(true);
  BtnRsPrevious->Show(true);
  BtnRsNext->Show(true);
  BtnRsLast->Show(true);
  BtnRefresh->Show(true);
  RsCurrentBlock->Show(true);
  if (TableView)
    TableView->Show(true);
}

void MyResultSetView::HideControls()
{
//
// making all controls to be invisible
//
  BtnRsFirst->Show(false);
  BtnRsPrevious->Show(false);
  BtnRsNext->Show(false);
  BtnRsLast->Show(false);
  BtnRefresh->Show(false);
  RsCurrentBlock->Show(false);
  if (TableView)
    TableView->Show(false);
}

void MyResultSetView::EditTable(wxString & sql, int *primaryKeys, int *blobCols,
                                wxString & table)
{
//
// starting the edit table sequence
//
  int i;
  for (i = 0; i < 1024; i++)
    {
      PrimaryKeys[i] = *(primaryKeys + i);
      BlobColumns[i] = *(blobCols + i);
    }
  ReadOnly = false;
  TableName = table;
  MainFrame->GetQueryView()->GetSqlCtrl()->SetValue(sql);
  if (ExecuteSql(sql, 0, ReadOnly) == false)
    wxMessageBox(SqlErrorMsg, wxT("spatialite-gui"), wxOK | wxICON_ERROR,
                 MainFrame);
}

bool MyResultSetView::ExecuteSql(wxString & sql, int from, bool read_only)
{
//
// executing some SQL statement
//
  ReadOnly = read_only;
  char *xSql = NULL;
  char err_msg[2048];
  char dummy[1024];
  int columns;
  int i_col;
  int i_row;
  int end_row = 0;
  wxString blobType;
  MyVariantList list;
  MyRowVariant *row;
  MyVariant *value;
  wxString cellValue;
  wxString currentBlock;
  sqlite3_stmt *stmt;
  sqlite3 *sqlite = MainFrame->GetSqlite();
  SqlErrorMsg = wxT("");
  if (TableView)
    TableView->Destroy();
  TableView = NULL;
  if (TableBlobs)
    delete TableBlobs;
  if (TableValues)
    delete TableValues;
  TableBlobs = NULL;
  TableValues = NULL;
  CurrentBlob = NULL;
  HideControls();
  RsBeginRow = 0;
  RsEndRow = 0;
  RsMaxRow = 0;
  for (i_row = 0; i_row < RsBlock; i_row++)
    RowIds[i_row] = -1;
  i_row = 0;
  xSql = new char[65536];
  strcpy(xSql, sql.ToUTF8());
  ::wxBeginBusyCursor();
  int ret = sqlite3_prepare_v2(sqlite, xSql, strlen(xSql), &stmt, NULL);
  if (ret != SQLITE_OK)
    {
      sprintf(err_msg, "SQL error: \"%s\"", sqlite3_errmsg(sqlite));
      SqlErrorMsg = wxString::FromUTF8(err_msg);
      ::wxEndBusyCursor();
      delete[]xSql;
      return false;
    }
  RsCurrentBlock->Show(true);
  while (1)
    {
      //
      // fetching the result set rows 
      //
      ret = sqlite3_step(stmt);
      if (ret == SQLITE_DONE)
        break;                  // end of result set
      if (ret == SQLITE_ROW)
        {
          //
          // fetching a row
          //
          if ((i_row % 100) == 0)
            {
              sprintf(dummy, "fetching the result set: %d rows", i_row);
              currentBlock = wxString::FromUTF8(dummy);
              RsCurrentBlock->SetLabel(currentBlock);
            }
          if (i_row < from)
            {
              i_row++;
              continue;
            }
          if ((i_row - from) >= RsBlock)
            {
              i_row++;
              continue;
            }
          end_row = i_row;
          columns = sqlite3_column_count(stmt);
          MyRowVariant *rowVariant = list.Add(columns);
          for (i_col = 0; i_col < columns; i_col++)
            {
              sqlite3_int64 int_value;
              double dbl_value;
              const unsigned char *txt_value;
              const void *blob_value;
              int blobSize;
              list.SetColumnName(i_col, sqlite3_column_name(stmt, i_col));
              switch (sqlite3_column_type(stmt, i_col))
                {
                  case SQLITE_INTEGER:
                    int_value = sqlite3_column_int64(stmt, i_col);
                    rowVariant->Set(i_col, int_value);
                    break;
                  case SQLITE_FLOAT:
                    dbl_value = sqlite3_column_double(stmt, i_col);
                    rowVariant->Set(i_col, dbl_value);
                    break;
                  case SQLITE_TEXT:
                    txt_value = sqlite3_column_text(stmt, i_col);
                    rowVariant->Set(i_col, txt_value);
                    break;
                  case SQLITE_BLOB:
                    blob_value = sqlite3_column_blob(stmt, i_col);
                    blobSize = sqlite3_column_bytes(stmt, i_col);
                    rowVariant->Set(i_col, blob_value, blobSize);
                    break;
                  case SQLITE_NULL:
                  default:
                    break;
                };
            }
          i_row++;
      } else
        {
          sprintf(err_msg, "SQL error: \"%s\"", sqlite3_errmsg(sqlite));
          SqlErrorMsg = wxString::FromUTF8(err_msg);
          goto error;
        }
    }
  sqlite3_finalize(stmt);
  RsBeginRow = from;
  RsEndRow = end_row;
  RsMaxRow = i_row;
  if (list.GetRows() == 0)
    {
      //
      // this one is an EMPTY Result Set
      //
      if (ReadOnly == false)
        {
          // preparing the insert row
          int numCols = 0;
          wxString *colNames = MainFrame->GetColumnNames(TableName, &numCols);
          CreateGrid(0, numCols + 1);
          TableView->SetColLabelValue(0, wxT("ROWID"));
          for (i_col = 0; i_col < numCols; i_col++)
            TableView->SetColLabelValue(i_col + 1, *(colNames + i_col));
          TableView->EnableEditing(true);
          delete[]colNames;
      } else
        {
          // simply showing a warning message
          CreateGrid(1, 1);
          TableView->SetColLabelValue(0, wxT("Message"));
          TableView->SetRowLabelValue(0, wxT("Message"));
          TableView->SetCellValue(0, 0,
                                  wxT
                                  ("SQL query returned an empty ResultSet\n\nThis is not an error"));
        }
  } else
    {
      //
      // preparing the Grid to show the result set
      //
      CreateGrid(list.GetRows(), list.GetColumns());
      if (ReadOnly == true)
        TableView->EnableEditing(false);
      else
        TableView->EnableEditing(true);
      for (i_col = 0; i_col < list.GetColumns(); i_col++)
        TableView->SetColLabelValue(i_col, list.GetColumnName(i_col));
      if (ReadOnly == false)
        TableView->SetColLabelValue(0, wxT("ROWID"));
      i_row = 0;
      row = list.GetFirst();
      while (row)
        {
          sprintf(dummy, "%d", i_row + RsBeginRow + 1);
          cellValue = wxString::FromUTF8(dummy);
          TableView->SetRowLabelValue(i_row, cellValue);
          if (ReadOnly == false)
            {
              // storing the ROWID value into the RowIds array
              value = row->GetColumn(0);
              if (value->GetType() == MY_INT_VARIANT)
                RowIds[i_row] = value->GetIntValue();
            }
          for (i_col = 0; i_col < row->GetNumCols(); i_col++)
            {
              value = row->GetColumn(i_col);
              if (value)
                {
                  switch (value->GetType())
                    {
                      case MY_INT_VARIANT:
                        sprintf(dummy, FORMAT_64, value->GetIntValue());
                        cellValue = wxString::FromUTF8(dummy);
                        TableView->SetCellValue(i_row, i_col, cellValue);
                        if (ReadOnly == false)
                          TableValues->SetValue(i_row, i_col,
                                                value->GetIntValue());
                        break;
                      case MY_DBL_VARIANT:
                        sprintf(dummy, "%1.6lf", value->GetDblValue());
                        cellValue = wxString::FromUTF8(dummy);
                        TableView->SetCellValue(i_row, i_col, cellValue);
                        if (ReadOnly == false)
                          TableValues->SetValue(i_row, i_col,
                                                value->GetDblValue());
                        break;
                      case MY_TXT_VARIANT:
                        TableView->SetCellValue(i_row, i_col,
                                                value->GetTxtValue());
                        if (ReadOnly == false)
                          TableValues->SetValue(i_row, i_col,
                                                value->GetTxtValue());
                        break;
                      case MY_BLOB_VARIANT:
                        blobType = wxT("UNKNOWN type");
                        switch (gaiaGuessBlobType
                                (value->GetBlob(), value->GetBlobSize()))
                          {
                            case GAIA_GEOMETRY_BLOB:
                              blobType = wxT("GEOMETRY");
                              break;
                            case GAIA_JPEG_BLOB:
                              blobType = wxT("JPEG image");
                              break;
                            case GAIA_EXIF_BLOB:
                              blobType = wxT("JPEG-EXIF image");
                              break;
                            case GAIA_EXIF_GPS_BLOB:
                              blobType = wxT("JPEG-EXIF-GPS image");
                              break;
                            case GAIA_PNG_BLOB:
                              blobType = wxT("PNG image");
                              break;
                            case GAIA_GIF_BLOB:
                              blobType = wxT("GIF image");
                              break;
                            case GAIA_PDF_BLOB:
                              blobType = wxT("PDF document");
                              break;
                            case GAIA_ZIP_BLOB:
                              blobType = wxT("ZIP archive");
                              break;
                          };
                        sprintf(dummy, "BLOB sz=%d ", value->GetBlobSize());
                        cellValue = wxString::FromUTF8(dummy);
                        cellValue += blobType;
                        TableView->SetCellValue(i_row, i_col, cellValue);
                        TableView->SetReadOnly(i_row, i_col);
                        TableBlobs->SetBlob(i_row, i_col, value);
                        break;
                      case MY_NULL_VARIANT:
                      default:
                        TableView->SetCellValue(i_row, i_col, wxT("NULL"));
                        break;
                    };
              } else
                TableView->SetCellValue(i_row, i_col, wxT("NULL"));
              if (ReadOnly == false)
                {
                  if (IsPrimaryKey(i_col) == true)
                    TableView->SetReadOnly(i_row, i_col);
                  if (IsBlobColumn(i_col) == true)
                    TableView->SetReadOnly(i_row, i_col);
                }
            }
          i_row++;
          row = row->GetNext();
        }
    }
  if (ReadOnly == false)
    {
      // prepearing the insert row
      TableView->SetRowLabelValue(TableView->GetNumberRows() - 1,
                                  wxT("Insert row"));
      InsertPending = false;
      for (i_col = 0; i_col < TableView->GetNumberCols(); i_col++)
        {
          TableView->SetCellValue(TableView->GetNumberRows() - 1, i_col,
                                  wxT(""));
          TableView->SetCellBackgroundColour(TableView->GetNumberRows() - 1,
                                             i_col, wxColour(0, 0, 0));
          TableView->SetReadOnly(TableView->GetNumberRows() - 1, i_col);
        }
    }
  TableView->SetRowLabelSize(wxGRID_AUTOSIZE);
  TableView->AutoSize();
  ResizeView();
  sprintf(dummy, "current block: %d / %d [%d rows]", RsBeginRow + 1,
          RsEndRow + 1, RsMaxRow);
  currentBlock = wxString::FromUTF8(dummy);
  RsCurrentBlock->SetLabel(currentBlock);
  ShowControls();
  MainFrame->GetQueryView()->AddToHistory(sql);
  ::wxEndBusyCursor();
  if (xSql)
    delete[]xSql;
  return true;
error:
  ::wxEndBusyCursor();
  sqlite3_finalize(stmt);
  if (xSql)
    delete[]xSql;
  return false;
}

bool MyResultSetView::IsPrimaryKey(int column)
{
//
// checks if this column is a Primary Key one
//
  int i;
  for (i = 0; i < 1024; i++)
    {
      if (PrimaryKeys[i] == column)
        return true;
    }
  return false;
}

bool MyResultSetView::IsBlobColumn(int column)
{
//
// checks if this column is a BLOB-type column
//
  int i;
  for (i = 0; i < 1024; i++)
    {
      if (BlobColumns[i] == column)
        return true;
    }
  return false;
}

void MyResultSetView::CreateGrid(int rows, int cols)
{
//
// creating a new Grid to show the result set
//
  int extra = 0;
  if (ReadOnly == false)
    extra = 1;
  wxSize sz = GetClientSize();
  TableView = new wxGrid(this, wxID_ANY, wxPoint(5, 5), wxSize(200, 200));
  TableView->Show(false);
  TableView->CreateGrid(rows + extra, cols);
  TableBlobs = new MyBlobs(rows, cols);
  if (ReadOnly == false)
    TableValues = new MyValues(rows, cols);
}

void MyResultSetView::ResizeView()
{
//
// resizing the Grid to show the result set
//
  wxSize sz = GetClientSize();
  if (TableView)
    {
      TableView->SetSize(sz.GetWidth() - 10, sz.GetHeight() - 45);
      TableView->Show(true);
    }
}

void MyResultSetView::OnSize(wxSizeEvent & event)
{
//
// this window has changed its size
//
  wxSize sz = GetClientSize();
  if (TableView)
    TableView->SetSize(sz.GetWidth() - 10, sz.GetHeight() - 45);
  BtnRsFirst->Move(5, sz.GetHeight() - 35);
  BtnRsPrevious->Move(40, sz.GetHeight() - 35);
  BtnRefresh->Move(75, sz.GetHeight() - 35);
  BtnRsNext->Move(110, sz.GetHeight() - 35);
  BtnRsLast->Move(145, sz.GetHeight() - 35);
  RsCurrentBlock->Move(180, sz.GetHeight() - 25);
}

void MyResultSetView::OnRsFirst(wxCommandEvent & WXUNUSED(event))
{
//
// scrolling to the result set beginning
//
  wxString sql = MainFrame->GetQueryView()->GetSqlCtrl()->GetValue();
  if (ExecuteSql(sql, 0, ReadOnly) == false)
    wxMessageBox(SqlErrorMsg, wxT("spatialite-gui"), wxOK | wxICON_ERROR,
                 MainFrame);
}

void MyResultSetView::OnRsPrevious(wxCommandEvent & WXUNUSED(event))
{
//
// scrolling to the result set previous block
//
  wxString sql = MainFrame->GetQueryView()->GetSqlCtrl()->GetValue();
  int start = RsBeginRow - RsBlock;
  if (start < 0)
    start = 0;
  if (ExecuteSql(sql, start, ReadOnly) == false)
    wxMessageBox(SqlErrorMsg, wxT("spatialite-gui"), wxOK | wxICON_ERROR,
                 MainFrame);
}

void MyResultSetView::OnRsNext(wxCommandEvent & WXUNUSED(event))
{
//
// scrolling to the result set next block
//
  wxString sql = MainFrame->GetQueryView()->GetSqlCtrl()->GetValue();
  int start = RsEndRow + 1;
  if (ExecuteSql(sql, start, ReadOnly) == false)
    wxMessageBox(SqlErrorMsg, wxT("spatialite-gui"), wxOK | wxICON_ERROR,
                 MainFrame);
}

void MyResultSetView::OnRsLast(wxCommandEvent & WXUNUSED(event))
{
//
// scrolling to the result set ending
//
  wxString sql = MainFrame->GetQueryView()->GetSqlCtrl()->GetValue();
  int start = RsMaxRow - RsBlock;
  if (start < 0)
    start = 0;
  if (ExecuteSql(sql, start, ReadOnly) == false)
    wxMessageBox(SqlErrorMsg, wxT("spatialite-gui"), wxOK | wxICON_ERROR,
                 MainFrame);
}

void MyResultSetView::OnRefresh(wxCommandEvent & WXUNUSED(event))
{
//
// refreshing the result set
//
  wxString sql = MainFrame->GetQueryView()->GetSqlCtrl()->GetValue();
  int start = RsBeginRow;
  if (ExecuteSql(sql, start, ReadOnly) == false)
    wxMessageBox(SqlErrorMsg, wxT("spatialite-gui"), wxOK | wxICON_ERROR,
                 MainFrame);
}

void MyResultSetView::OnRightClick(wxGridEvent & event)
{
//
// right click on some cell [mouse action]
//
  MyVariant *blobVar;
  wxMenu *menu = new wxMenu();
  wxMenuItem *menuItem;
  wxPoint pt = event.GetPosition();
  if (ReadOnly == false && event.GetRow() == TableView->GetNumberRows() - 1)
    {
      // this is the INSERT ROW
      if (InsertPending == true)
        {
          menuItem =
            new wxMenuItem(menu, Grid_Insert, wxT("&Confirm insertion"));
          menu->Append(menuItem);
          menuItem = new wxMenuItem(menu, Grid_Abort, wxT("&Abort insertion"));
          menu->Append(menuItem);
      } else
        {
          menuItem = new wxMenuItem(menu, Grid_Insert, wxT("&Insert new row"));
          menu->Append(menuItem);
        }
      TableView->PopupMenu(menu, pt);
      return;
    }
  CurrentEvtRow = event.GetRow();
  CurrentEvtColumn = event.GetCol();
  blobVar = TableBlobs->GetBlob(CurrentEvtRow, CurrentEvtColumn);
  if (blobVar)
    {
      // this one is a BLOB cell
      if (ReadOnly == false)
        {
          MyRowVariant *varRow = TableValues->GetRow(CurrentEvtRow);
          if (varRow->IsDeleted() == false)
            {
              menuItem = new wxMenuItem(menu, Grid_Delete, wxT("&Delete row"));
              menu->Append(menuItem);
              menuItem =
                new wxMenuItem(menu, Grid_Insert, wxT("&Insert new row"));
              menu->Append(menuItem);
              menu->AppendSeparator();
            }
        }
      menuItem = new wxMenuItem(menu, Grid_Blob, wxT("BLOB &explore"));
      menu->Append(menuItem);
      if (gaiaGuessBlobType(blobVar->GetBlob(), blobVar->GetBlobSize()) ==
          GAIA_GEOMETRY_BLOB)
        ;
      else
        {
          menu->AppendSeparator();
          menuItem = new wxMenuItem(menu, Grid_BlobIn, wxT("BLOB &import"));
          menu->Append(menuItem);
          menuItem = new wxMenuItem(menu, Grid_BlobOut, wxT("BLOB &export"));
          menu->Append(menuItem);
          menuItem =
            new wxMenuItem(menu, Grid_BlobNull, wxT("Set BLOB as &NULL"));
          menu->Append(menuItem);
        }
      CurrentBlob = blobVar;
  } else
    {
      // this one is an ordinary cell
      CurrentBlob = NULL;
      if (ReadOnly == false)
        {
          MyRowVariant *varRow = TableValues->GetRow(CurrentEvtRow);
          if (varRow->IsDeleted() == false)
            {
              menuItem = new wxMenuItem(menu, Grid_Delete, wxT("&Delete row"));
              menu->Append(menuItem);
              menuItem =
                new wxMenuItem(menu, Grid_Insert, wxT("&Insert new row"));
              menu->Append(menuItem);
              if (IsBlobColumn(CurrentEvtColumn) == true)
                {
                  menu->AppendSeparator();
                  menuItem =
                    new wxMenuItem(menu, Grid_BlobIn, wxT("BLOB &import"));
                  menu->Append(menuItem);
                }
              menu->AppendSeparator();
            }
        }
      menuItem = new wxMenuItem(menu, Grid_Clear, wxT("&Clear selection"));
      menu->Append(menuItem);
      menuItem = new wxMenuItem(menu, Grid_All, wxT("Select &all"));
      menu->Append(menuItem);
      menuItem = new wxMenuItem(menu, Grid_Row, wxT("Select &row"));
      menu->Append(menuItem);
      menuItem = new wxMenuItem(menu, Grid_Column, wxT("&Select column"));
      menu->Append(menuItem);
      menu->AppendSeparator();
      menuItem = new wxMenuItem(menu, Grid_Copy, wxT("&Copy"));
      menu->Append(menuItem);
      if (TableView->IsSelection() == false)
        menuItem->Enable(false);
    }
  TableView->PopupMenu(menu, pt);
}

void MyResultSetView::OnCellSelected(wxGridEvent & event)
{
//
// cell selection changed
//
  if (InsertPending == true)
    {
      // an INSERT row is still pending
      if (event.GetRow() != TableView->GetNumberRows() - 1)
        DoInsert(false);
    }
  event.Skip();
}

void MyResultSetView::OnCellChanged(wxGridEvent & event)
{
//
// user changed value in some cell
//
  MyVariant *oldValue;
  MyVariant *insValue;
  wxString value;
  wxString numValue;
  wxString newValue = wxT("NULL");
  wxString sql;
  wxString rowid;
  char *errMsg = NULL;
  bool error = false;
  sqlite3_int64 int64_value;
  long long_value;
  bool okIntValue = false;
  double dbl_value;
  bool okDblValue = false;
  int ret;
  char dummy[256];
  int row = event.GetRow();
  int column = event.GetCol();
  value = TableView->GetCellValue(row, column);
  if (InsertPending == true)
    {
      // an INSERT row is still pending
      insValue = InsertRow->GetColumn(column);
      numValue = value;
      numValue.Replace(wxT(","), wxT("."));
      okIntValue = numValue.ToLong(&long_value);
      okDblValue = numValue.ToDouble(&dbl_value);
      if (okIntValue == true)
        {
          int64_value = long_value;
          insValue->Set(int64_value);
      } else if (okDblValue == true)
        insValue->Set(dbl_value);
      else
        insValue->Set(value);
      if (row != TableView->GetNumberRows() - 1)
        DoInsert(false);
      return;
    }
  if (value.Len() > 0)
    {
      numValue = value;
      numValue.Replace(wxT(","), wxT("."));
      okIntValue = numValue.ToLong(&long_value);
      okDblValue = numValue.ToDouble(&dbl_value);
      if (okIntValue == true)
        {
          int64_value = long_value;
          sprintf(dummy, FORMAT_64, int64_value);
          newValue = wxString::FromUTF8(dummy);
      } else if (okDblValue == true)
        {
          sprintf(dummy, "%1.6lf", dbl_value);
          newValue = wxString::FromUTF8(dummy);
      } else
        {
          value.Replace(wxT("'"), wxT("''"));
          newValue = wxT("'") + value + wxT("'");
        }
    }
  oldValue = TableValues->GetValue(row, 0);
  sprintf(dummy, FORMAT_64, oldValue->GetIntValue());
  rowid = wxString::FromUTF8(dummy);
  sql =
    wxT("UPDATE \"") + TableName + wxT("\" SET \"") +
    TableView->GetColLabelValue(column) + wxT("\" = ") + newValue +
    wxT(" WHERE ROWID = ") + rowid;
  ret = sqlite3_exec(MainFrame->GetSqlite(), sql.ToUTF8(), NULL, NULL, &errMsg);
  if (ret != SQLITE_OK)
    {
      wxMessageBox(wxT("SQLite SQL error: ") + wxString::FromUTF8(errMsg),
                   wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
      sqlite3_free(errMsg);
      error = true;
    }
  oldValue = TableValues->GetValue(row, column);
  if (error == true)
    {
      // update failed; restorig old cell value
      value = wxT("NULL");
      if (oldValue)
        {
          if (oldValue->GetType() == MY_INT_VARIANT)
            {
              sprintf(dummy, FORMAT_64, oldValue->GetIntValue());
              value = wxString::FromUTF8(dummy);
            }
          if (oldValue->GetType() == MY_DBL_VARIANT)
            {
              sprintf(dummy, "%1.6lf", oldValue->GetDblValue());
              value = wxString::FromUTF8(dummy);
            }
          if (oldValue->GetType() == MY_TXT_VARIANT)
            value = oldValue->GetTxtValue();
        }
      TableView->SetCellValue(row, column, value);
      TableView->ForceRefresh();
  } else
    {
      // marking cell as modified
      TableView->SetCellTextColour(row, column, wxColour(0, 0, 192));
      TableView->SetCellBackgroundColour(row, column, wxColour(255, 255, 204));
      TableView->ForceRefresh();
    }
}

void MyResultSetView::DoInsert(bool confirmed)
{
//
// performing actual row INSERT
//
  int i;
  int ret;
  MyVariant *var;
  wxString value;
  wxString strValue;
  wxString sql;
  char dummy[256];
  char *errMsg = NULL;
  if (confirmed == false)
    {
      ret =
        wxMessageBox(wxT("A new row is ready for insertion\n\nConfirm ?"),
                     wxT("spatialite-gui"), wxYES_NO | wxICON_QUESTION, this);
      if (ret != wxYES)
        goto close_insert;
    }
  sql = wxT("INSERT INTO \"") + TableName + wxT("\" (");
  for (i = 1; i < TableView->GetNumberCols(); i++)
    {
      if (i > 1)
        sql += wxT(", ");
      sql += wxT("\"") + TableView->GetColLabelValue(i) + wxT("\"");
    }
  sql += wxT(") VALUES (");
  for (i = 1; i < InsertRow->GetNumCols(); i++)
    {
      if (i > 1)
        sql += wxT(", ");
      var = InsertRow->GetColumn(i);
      value = wxT("NULL");
      if (var->GetType() == MY_INT_VARIANT)
        {
          sprintf(dummy, FORMAT_64, var->GetIntValue());
          value = wxString::FromUTF8(dummy);
        }
      if (var->GetType() == MY_DBL_VARIANT)
        {
          sprintf(dummy, "%1.6lf", var->GetDblValue());
          value = wxString::FromUTF8(dummy);
        }
      if (var->GetType() == MY_TXT_VARIANT)
        {
          strValue = var->GetTxtValue();
          strValue.Replace(wxT("'"), wxT("''"));
          value = wxT("'") + strValue + wxT("'");
        }
      sql += value;
    }
  sql += wxT(")");
  ret = sqlite3_exec(MainFrame->GetSqlite(), sql.ToUTF8(), NULL, NULL, &errMsg);
  if (ret != SQLITE_OK)
    {
      wxMessageBox(wxT("SQLite SQL error: ") + wxString::FromUTF8(errMsg),
                   wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
      sqlite3_free(errMsg);
    }
close_insert:
//
// closing insert row
//
  InsertPending = false;
  delete InsertRow;
  InsertRow = NULL;
  for (i = 0; i < TableView->GetNumberCols(); i++)
    {
      TableView->SetCellValue(TableView->GetNumberRows() - 1, i, wxT(""));
      TableView->SetCellBackgroundColour(TableView->GetNumberRows() - 1, i,
                                         wxColour(0, 0, 0));
      TableView->SetReadOnly(TableView->GetNumberRows() - 1, i);
    }
}

void MyResultSetView::OnCmdDelete(wxCommandEvent & event)
{
//
// user required row deletion
//
  char *errMsg = NULL;
  bool error = false;
  int ret;
  int i;
  wxString sql;
  wxString rowid;
  MyVariant *value;
  char dummy[256];
  MyRowVariant *varRow = TableValues->GetRow(CurrentEvtRow);
  if (varRow->IsDeleted() == true)
    return;
  value = TableValues->GetValue(CurrentEvtRow, 0);
  sprintf(dummy, FORMAT_64, value->GetIntValue());
  rowid = wxString::FromUTF8(dummy);
  ret =
    wxMessageBox(wxT("Requested deletion for row identified by RowId = ")
                 + rowid + wxT("\n\nConfirm ?"), wxT("spatialite-gui"),
                 wxYES_NO | wxICON_QUESTION, this);
  if (ret != wxYES)
    return;
  sql = wxT("DELETE FROM \"") + TableName + wxT("\" WHERE ROWID = ") + rowid;
  ret = sqlite3_exec(MainFrame->GetSqlite(), sql.ToUTF8(), NULL, NULL, &errMsg);
  if (ret != SQLITE_OK)
    {
      wxMessageBox(wxT("SQLite SQL error: ") + wxString::FromUTF8(errMsg),
                   wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
      sqlite3_free(errMsg);
      error = true;
    }
  if (error == false)
    {
      // marking row as deleted
      varRow->SetDeleted();
      for (i = 0; i < TableView->GetNumberCols(); i++)
        {
          TableView->SetCellTextColour(CurrentEvtRow, i, wxColour(0, 0, 0));
          TableView->SetCellBackgroundColour(CurrentEvtRow, i,
                                             wxColour(128, 128, 128));
          TableView->SetReadOnly(CurrentEvtRow, i);
        }
      TableView->ForceRefresh();
    }
}

void MyResultSetView::OnCmdInsert(wxCommandEvent & event)
{
//
// user required row insertion
//
  int i;
  if (ReadOnly == true)
    return;
  if (InsertPending == true)
    {
      // an INSERT is still pending, and the user required actual insertion
      DoInsert(true);
      return;
    }
  InsertRow = new MyRowVariant(TableView->GetNumberCols());
  TableView->MakeCellVisible(TableView->GetNumberRows() - 1, 1);
  InsertPending = true;
  for (i = 1; i < TableView->GetNumberCols(); i++)
    {
      TableView->SetCellValue(TableView->GetNumberRows() - 1, i, wxT(""));
      TableView->SetCellBackgroundColour(TableView->GetNumberRows() - 1, i,
                                         wxColour(255, 255, 255));
      TableView->SetReadOnly(TableView->GetNumberRows() - 1, i, false);
    }
}

void MyResultSetView::OnCmdAbort(wxCommandEvent & event)
{
//
// user cancelled current row insertion
//
  int i;
  if (InsertPending)
    {
      InsertPending = false;
      delete InsertRow;
      InsertRow = NULL;
      for (i = 0; i < TableView->GetNumberCols(); i++)
        {
          TableView->SetCellValue(TableView->GetNumberRows() - 1, i, wxT(""));
          TableView->SetCellBackgroundColour(TableView->GetNumberRows() - 1, i,
                                             wxColour(0, 0, 0));
          TableView->SetReadOnly(TableView->GetNumberRows() - 1, i);
        }
    }
}

void MyResultSetView::OnCmdClearSelection(wxCommandEvent & event)
{
//
// clearing current selection
//
  TableView->ClearSelection();
}

void MyResultSetView::OnCmdSelectAll(wxCommandEvent & event)
{
//
// selecting all
//
  TableView->SelectAll();
}

void MyResultSetView::OnCmdSelectRow(wxCommandEvent & event)
{
//
// selecting the current row
//
  TableView->SelectRow(CurrentEvtRow);
}

void MyResultSetView::OnCmdSelectColumn(wxCommandEvent & event)
{
//
// selecting column
//
  TableView->SelectCol(CurrentEvtColumn);
}

void MyResultSetView::OnCmdCopy(wxCommandEvent & event)
{
//
// copying the selection into the clipboard
//
  wxString copyData;
  int row;
  int col;
  bool newRow;
  bool firstRow = true;
  for (row = 0; row < TableView->GetNumberRows(); row++)
    {
      newRow = true;
      for (col = 0; col < TableView->GetNumberCols(); col++)
        {
          if (TableView->IsInSelection(row, col) == true)
            {
              // ok, this cell is included into the selection to copy
              if (firstRow == true)
                {
                  newRow = false;
                  firstRow = false;
              } else if (newRow == true)
                {
                  newRow = false;
                  copyData += wxT("\n");
              } else
                copyData += wxT("\t");
              copyData += TableView->GetCellValue(row, col);
            }
        }
    }
  if (wxTheClipboard->Open())
    {
      wxTheClipboard->SetData(new wxTextDataObject(copyData));
      wxTheClipboard->Close();
    }
}

void MyResultSetView::OnCmdBlob(wxCommandEvent & event)
{
//
// exploring some BLOB value
//
  if (!CurrentBlob)
    return;
  BlobExplorerDialog dlg;
  dlg.Create(MainFrame, CurrentBlob->GetBlobSize(), CurrentBlob->GetBlob());
  dlg.ShowModal();
}

void MyResultSetView::OnCmdBlobIn(wxCommandEvent & event)
{
// importing an external file into a BLOB-value
  FILE *in = NULL;
  char path[2048];
  int rd;
  int maxSize = 1024 * 1024;    // limit BLOB size to 1MB
  wxString fileList;
  wxString rowid;
  wxString sql;
  wxString blobValue;
  wxString hex;
  MyVariant *value;
  char dummy[1024];
  bool error = false;
  unsigned char *buffer = NULL;
  int ret;
  char *errMsg = NULL;
  wxString lastDir;
  fileList =
    wxT
    ("BLOB Document (*.jpg;*.jpeg;*.png;*.gif;*.pdf;*.zip)|*.jpg;*.jpeg;*.png;*.gif;*.pdf;*.zip|");
  fileList += wxT("Image (*.jpg;*.jpeg;*.png;*.gif)|*.jpg;*.jpeg;*.png;*.gif|");
  fileList +=
    wxT
    ("JPEG Image (*.jpg;*.jpeg)|*.jpg;*.jpeg|PNG Image (*.png)|*.png|GIF Image (*.gif)|*.gif");
  fileList +=
    wxT("PDF Document (*.pdf)|*.pdf|ZIP Archive|(*.zip)|All files (*.*)|*.*");
  wxFileDialog *fileDialog = new wxFileDialog(this, wxT("loading a BLOB value"),
                                              wxT(""), wxT(""), fileList,
                                              wxFD_OPEN | wxFD_FILE_MUST_EXIST,
                                              wxDefaultPosition,
                                              wxDefaultSize, wxT("filedlg"));
  lastDir = MainFrame->GetLastDirectory();
  if (lastDir.Len() >= 1)
    fileDialog->SetDirectory(lastDir);
  ret = fileDialog->ShowModal();
  if (ret == wxID_OK)
    {
      strcpy(path, fileDialog->GetPath().ToUTF8());
      in = fopen(path, "rb");
      if (!in)
        {
          wxMessageBox(wxT("Cannot open '") + fileDialog->GetPath() +
                       wxT("' for reading"), wxT("spatialite-gui"),
                       wxOK | wxICON_ERROR, this);
          return;
        }
      wxFileName file(fileDialog->GetPath());
      lastDir = file.GetPath();
      MainFrame->SetLastDirectory(lastDir);
      ::wxBeginBusyCursor();
      buffer = new unsigned char[maxSize];
      rd = fread(buffer, 1, maxSize, in);
      if (rd == maxSize && !(feof(in)))
        {
          // exceding 1MB; it's too big for a BLOB
          wxMessageBox(wxT
                       ("Selected file excedes 1MB; cowardly refusing to load it as a BLOB value ..."),
                       wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
          goto end;
        }
      if (ferror(in))
        {
          // I/O error
          wxMessageBox(wxT("an I/O error occurred"), wxT("spatialite-gui"),
                       wxOK | wxICON_ERROR, this);
          goto end;
        }
      //
      // preparing  theSQL UPDATE statement
      //
      value = TableValues->GetValue(CurrentEvtRow, 0);
      sprintf(dummy, FORMAT_64, value->GetIntValue());
      rowid = wxString::FromUTF8(dummy);
      HexBlobValue(buffer, rd, hex);
      sql =
        wxT("UPDATE \"") + TableName + wxT("\" SET \"") +
        TableView->GetColLabelValue(CurrentEvtColumn);
      sql += wxT("\" = ") + hex + wxT(" WHERE ROWID = ") + rowid;
      ret =
        sqlite3_exec(MainFrame->GetSqlite(), sql.ToUTF8(), NULL, NULL, &errMsg);
      if (ret != SQLITE_OK)
        {
          wxMessageBox(wxT("SQLite SQL error: ") + wxString::FromUTF8(errMsg),
                       wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
          sqlite3_free(errMsg);
          error = true;
        }
      ::wxEndBusyCursor();
      value = TableValues->GetValue(CurrentEvtRow, CurrentEvtColumn);
      if (error == false)
        {
          // updating the Grid cell
          sprintf(dummy, "BLOB sz=%d ", rd);
          blobValue = wxString::FromUTF8(dummy);
          switch (gaiaGuessBlobType(buffer, rd))
            {
              case GAIA_JPEG_BLOB:
                blobValue += wxT("JPEG image");
                break;
              case GAIA_EXIF_BLOB:
                blobValue += wxT("JPEG-EXIF image");
                break;
              case GAIA_EXIF_GPS_BLOB:
                blobValue += wxT("JPEG-EXIF-GPS image");
                break;
              case GAIA_PNG_BLOB:
                blobValue += wxT("PNG image");
                break;
              case GAIA_GIF_BLOB:
                blobValue += wxT("GIF image");
                break;
              case GAIA_PDF_BLOB:
                blobValue += wxT("PDF document");
                break;
              case GAIA_ZIP_BLOB:
                blobValue += wxT("ZIP archive");
                break;
              default:
                blobValue += wxT("UNKNOWN type");
            };
          TableView->SetCellValue(CurrentEvtRow, CurrentEvtColumn, blobValue);
          TableView->SetCellTextColour(CurrentEvtRow, CurrentEvtColumn,
                                       wxColour(0, 0, 192));
          TableView->SetCellBackgroundColour(CurrentEvtRow, CurrentEvtColumn,
                                             wxColour(255, 255, 204));
          TableView->ForceRefresh();
        }
    }
end:
// clean-up
  if (in)
    fclose(in);
  if (buffer)
    delete[]buffer;
}

void MyResultSetView::HexBlobValue(unsigned char *blob, int size,
                                   wxString & hex)
{
//
// builds the HEX BLOB as X'01234567890abcdef'
//
  int i;
  char digit[16];
  hex = wxT("X'");
  for (i = 0; i < size; i++)
    {
      sprintf(digit, "%02x", *(blob + i));
      hex += wxString::FromUTF8(digit);
    }
  hex += wxT("'");
}

void MyResultSetView::OnCmdBlobOut(wxCommandEvent & event)
{
// exporting to external file a BLOB-value
  int blobType;
  wxString fileName;
  wxString fileType;
  int ret;
  wxString path;
  FILE *out = NULL;
  char xpath[2048];
  int wr;
  wxString lastDir;
  if (!CurrentBlob)
    return;
  blobType =
    gaiaGuessBlobType(CurrentBlob->GetBlob(), CurrentBlob->GetBlobSize());
  switch (blobType)
    {
      case GAIA_JPEG_BLOB:
      case GAIA_EXIF_BLOB:
      case GAIA_EXIF_GPS_BLOB:
        fileName = wxT("image.jpg");
        fileType = wxT("File JPEG (*.jpg;*.jpeg)|*.jpg");
        break;
      case GAIA_PNG_BLOB:
        fileName = wxT("image.png");
        fileType = wxT("File PNG (*.png)|*.png");
        break;
      case GAIA_GIF_BLOB:
        fileName = wxT("image.gif");
        fileType = wxT("File GIF (*.gif)|*.gif");
        break;
      case GAIA_PDF_BLOB:
        fileName = wxT("document.pdf");
        fileType = wxT("PDF document (*.jpg;*.jpeg)|*.jpg");
        break;
      case GAIA_ZIP_BLOB:
        fileName = wxT("archive.zip");
        fileType = wxT("ZIP Archive (*.zip)|*.zip");
        break;
      default:
        fileName = wxT("file");
    };
  fileType += wxT("|All files (*.*)|*.*");
  wxFileDialog *fileDialog =
    new wxFileDialog(this, wxT("exporting a BLOB value to file"),
                     wxT(""), fileName, fileType,
                     wxFD_SAVE | wxFD_OVERWRITE_PROMPT, wxDefaultPosition,
                     wxDefaultSize, wxT("filedlg"));
  lastDir = MainFrame->GetLastDirectory();
  if (lastDir.Len() >= 1)
    fileDialog->SetDirectory(lastDir);
  ret = fileDialog->ShowModal();
  if (ret == wxID_OK)
    {
      wxFileName file(fileDialog->GetPath());
      path = file.GetPath();
      path += file.GetPathSeparator();
      path += file.GetName();
      switch (blobType)
        {
          case GAIA_JPEG_BLOB:
          case GAIA_EXIF_BLOB:
          case GAIA_EXIF_GPS_BLOB:
            path += wxT(".jpg");
            break;
          case GAIA_PNG_BLOB:
            path += wxT(".png");
            break;
          case GAIA_GIF_BLOB:
            path += wxT(".gif");
            break;
          case GAIA_PDF_BLOB:
            path += wxT(".pdf");
            break;
          case GAIA_ZIP_BLOB:
            path += wxT(".zip");
            break;
          default:
            path += file.GetExt();
        };
      strcpy(xpath, path.ToUTF8());
      out = fopen(xpath, "wb");
      if (!out)
        {
          wxMessageBox(wxT("Cannot open '") + path + wxT("' for writing"),
                       wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
          return;
        }
      lastDir = file.GetPath();
      MainFrame->SetLastDirectory(lastDir);
      ::wxBeginBusyCursor();
      wr = fwrite(CurrentBlob->GetBlob(), 1, CurrentBlob->GetBlobSize(), out);
      if (wr != CurrentBlob->GetBlobSize())
        {
          wxMessageBox(wxT("an I/O error occurred"), wxT("spatialite-gui"),
                       wxOK | wxICON_ERROR, this);
        }
      fclose(out);
      ::wxEndBusyCursor();
    }
}

void MyResultSetView::OnCmdBlobNull(wxCommandEvent & event)
{
// setting to NULL a BLOB-value
  wxString rowid;
  wxString sql;
  int ret;
  char *errMsg = NULL;
  bool error = false;
  MyVariant *value;
  char dummy[256];
  value = TableValues->GetValue(CurrentEvtRow, 0);
  sprintf(dummy, FORMAT_64, value->GetIntValue());
  rowid = wxString::FromUTF8(dummy);
  sql =
    wxT("UPDATE \"") + TableName + wxT("\" SET \"") +
    TableView->GetColLabelValue(CurrentEvtColumn);
  sql += wxT("\" = NULL WHERE ROWID = ") + rowid;
  ret = sqlite3_exec(MainFrame->GetSqlite(), sql.ToUTF8(), NULL, NULL, &errMsg);
  if (ret != SQLITE_OK)
    {
      wxMessageBox(wxT("SQLite SQL error: ") + wxString::FromUTF8(errMsg),
                   wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
      sqlite3_free(errMsg);
      error = true;
    }
  if (error == false)
    {
      // updating the Grid cell
      TableView->SetCellValue(CurrentEvtRow, CurrentEvtColumn, wxT("NULL"));
      TableView->SetCellTextColour(CurrentEvtRow, CurrentEvtColumn,
                                   wxColour(0, 0, 192));
      TableView->SetCellBackgroundColour(CurrentEvtRow, CurrentEvtColumn,
                                         wxColour(255, 255, 204));
      TableView->ForceRefresh();
    }
}

Changes to Shapefiles.cpp.

1
2
3
4
5
6
7
8
9
10
11
12
..
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204

205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271


272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236

1237
1238
1239
1240
1241
1242

1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303

1304
1305
1306
1307
1308
1309
1310
1311
1312

1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380

1381
1382
1383
1384
1385
1386

1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443

1444
1445
1446
1447
1448
1449
1450
1451
1452

1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
/*
/ Shapefiles.cpp
/ methods related to Shapefile loading and saving
/
/ version 1.1, 2008 September 13
/
/ Author: Sandro Furieri a-furieri@lqt.it
/
/ Copyright (C) 2008  Alessandro Furieri
/
/    This program is free software: you can redistribute it and/or modify
/    it under the terms of the GNU General Public License as published by
................................................................................
/    You should have received a copy of the GNU General Public License
/    along with this program.  If not, see <http://www.gnu.org/licenses/>.
/
*/

#include "Classdef.h"

void
MyFrame::CleanTxtTab (char *buf)
{
// well-formatting a string to be used as a Txt/Tab string
    char tmp[65536];
    char *in = tmp;
    char *out = buf;
    strcpy (tmp, buf);
    while (*in != '\0')
      {
	  if (*in == '\t' || *in == '\r' || *in == '\n')
	    {
		in++;
		*out++ = ' ';
	    }
	  else
	      *out++ = *in++;
      }
    *out = '\0';
}

void
MyFrame::CleanCsv (char *buf)
{
// well-formatting a string to be used as a Csv string
    char tmp[65536];
    char *in = tmp;
    char *out = buf;
    bool special = false;
    strcpy (tmp, buf);
    while (*in != '\0')
      {
	  if (*in == ',' || *in == '\r' || *in == '\n')
	      special = true;
	  if (*in == '"')
	      *out++ = '"';
	  *out++ = *in++;
      }
    *out = '\0';
    if (special == true)
      {
	  sprintf (tmp, "\"%s\"", buf);
	  strcpy (buf, tmp);
      }
}

void
MyFrame::CleanHtml (char *buf)
{
// well-formatting a string to be used as an Html string
    char tmp[65536];
    char *in = tmp;
    char *out = buf;
    strcpy (tmp, buf);
    while (*in != '\0')
      {
	  if (*in == '<')
	    {
		*out++ = '&';
		*out++ = 'l';
		*out++ = 't';
		*out++ = ';';
		in++;
		continue;
	    }
	  if (*in == '>')
	    {
		*out++ = '&';
		*out++ = 'g';
		*out++ = 't';
		*out++ = ';';
		in++;
		continue;
	    }
	  if (*in == ' ')
	    {
		*out++ = '&';
		*out++ = 'n';
		*out++ = 'b';
		*out++ = 's';
		*out++ = 'p';
		*out++ = ';';
		in++;
		continue;
	    }
	  if (*in == '"')
	    {
		*out++ = '&';
		*out++ = 'q';
		*out++ = 'u';
		*out++ = 'o';
		*out++ = 't';
		*out++ = ';';
		in++;
		continue;
	    }
	  if (*in == '&')
	    {
		*out++ = '&';
		*out++ = 'a';
		*out++ = 'm';
		*out++ = 'p';
		*out++ = ';';
		in++;
		continue;
	    }
	  *out++ = *in++;
      }
    *out = '\0';
}

bool MyFrame::TableAlreadyExists (wxString & name)
{
//
// checks if a table of this name already exists 
//
    char **
	results;
    int
	rows;
    int
	columns;
    int
	i;
    char *
	errMsg = NULL;
    bool
	already_exists = false;
    wxString
	sql =
	wxT
	("SELECT name FROM sqlite_master WHERE type = 'table' AND name = '");
    sql += name;
    sql += wxT ("'");
    int
	ret = sqlite3_get_table (SqliteHandle, sql.ToUTF8 (), &results,
				 &rows, &columns, &errMsg);
    if (ret != SQLITE_OK)
      {
	  wxMessageBox (wxT ("SQLite SQL error: ") +
			wxString::FromUTF8 (errMsg), wxT ("spatialite-gui"),
			wxOK | wxICON_ERROR, this);
	  sqlite3_free (errMsg);
	  return false;
      }
    if (rows < 1)
	;
    else
      {
	  for (i = 1; i <= rows; i++)
	      already_exists = true;
      }
    sqlite3_free_table (results);
    return already_exists;
}

bool MyFrame::SridNotExists (int srid)
{
//
// checks if a SRID value is a valid one
//
    char **
	results;
    int
	rows;
    int
	columns;
    int
	i;
    char *
	errMsg = NULL;
    bool
	constrained = false;
    bool
	not_exists = true;
    wxString
	RefSysName;

    wxString
	sql =
	wxT
	("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'spatial_ref_sys'");
    int
	ret = sqlite3_get_table (SqliteHandle, sql.ToUTF8 (), &results,
				 &rows, &columns, &errMsg);
    if (ret != SQLITE_OK)
      {
	  wxMessageBox (wxT ("SQLite SQL error: ") +
			wxString::FromUTF8 (errMsg), wxT ("spatialite-gui"),
			wxOK | wxICON_ERROR, this);
	  sqlite3_free (errMsg);
	  return false;
      }
    if (rows < 1)
	;
    else
      {
	  for (i = 1; i <= rows; i++)
	      constrained = true;
      }
    sqlite3_free_table (results);
    if (constrained == false)
	return false;
    sql.Printf (wxT
		("SELECT ref_sys_name FROM spatial_ref_sys WHERE srid = %d"),
		srid);
    ret =
	sqlite3_get_table (SqliteHandle, sql.ToUTF8 (), &results, &rows,
			   &columns, &errMsg);
    if (ret != SQLITE_OK)
      {
	  wxMessageBox (wxT ("SQLite SQL error: ") +
			wxString::FromUTF8 (errMsg), wxT ("spatialite-gui"),
			wxOK | wxICON_ERROR, this);
	  sqlite3_free (errMsg);
	  return false;
      }
    if (rows < 1)
	;
    else
      {
	  for (i = 1; i <= rows; i++)
	      not_exists = false;
      }
    sqlite3_free_table (results);
    return not_exists;
}

bool MyFrame::CheckMetadata ()
{
//
// checking if METADATA tables are defined
//
    char **
	results;
    int
	rows;
    int
	columns;
    int
	i;
    char *
	errMsg = NULL;
    bool
	constrained = false;


    wxString
	sql =
	wxT
	("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'geometry_columns'");
    int
	ret = sqlite3_get_table (SqliteHandle, sql.ToUTF8 (), &results,
				 &rows, &columns, &errMsg);
    if (ret != SQLITE_OK)
      {
	  wxMessageBox (wxT ("SQLite SQL error: ") +
			wxString::FromUTF8 (errMsg), wxT ("spatialite-gui"),
			wxOK | wxICON_ERROR, this);
	  sqlite3_free (errMsg);
	  return false;
      }
    if (rows < 1)
	;
    else
      {
	  for (i = 1; i <= rows; i++)
	      constrained = true;
      }
    sqlite3_free_table (results);
    return constrained;
}

void
MyFrame::CleanSqlString (char *value)
{
//
// returns a well formatted TEXT value for SQL
// 1] strips trailing spaces
// 2] masks any ' inside the string, appending another '
//
    char new_value[1024];
    char *p;
    int len;
    int i;
    len = strlen (value);
    for (i = (len - 1); i >= 0; i--)
      {
	  // stripping trailing spaces
	  if (value[i] == ' ')
	      value[i] = '\0';
	  else
	      break;
      }
    p = new_value;
    for (i = 0; i < len; i++)
      {
	  if (value[i] == '\'')
	      *(p++) = '\'';
	  *(p++) = value[i];
      }
    *p = '\0';
    strcpy (value, new_value);
}

void
MyFrame::LoadShapefile (wxString & path, wxString & table, int srid,
			wxString & column, wxString & charset)
{
//
// loading a Shapefile as a new DB table
//
    int cnt;
    int col_cnt;
    int seed;
    int len;
    int dup;
    int idup;
    int current_row;
    int ret;
    int rows = 0;
    char *errMsg = NULL;
    char xtable[1024];
    char xcolumn[1024];
    char dummy[65536];
    char dummyName[4096];
    char sql[65536];
    char **col_name = NULL;
    const char *geom_type = "UNKNOWN";
    char *hexWKB = NULL;
    int szSQL;
    char *bufSQL = NULL;
    wxString dummyStr;
    wxString msg;
    gaiaShapefilePtr shp = NULL;
    gaiaDbfFieldPtr dbf_field;
    bool metadata = CheckMetadata ();
    bool sqlError = false;
//
// performing some checks before starting
//
    if (TableAlreadyExists (table) == true)
      {
	  wxMessageBox (wxT ("a table name '") + table +
			wxT ("' already exists"), wxT ("spatialite-gui"),
			wxOK | wxICON_ERROR, this);
	  return;
      }
    if (gaiaIllegalSqlName (table.ToUTF8 ()) == 1
	|| gaiaIsReservedSqlName (table.ToUTF8 ()) == 1
	|| gaiaIsReservedSqliteName (table.ToUTF8 ()) == 1)
      {
	  wxMessageBox (wxT ("'") + table +
			wxT
			("' is an invalid TABLE NAME\n\nsame as SQL reserved keyword"),
			wxT ("spatialite-gui"), wxOK | wxICON_ERROR, this);
	  return;
      }
    if (gaiaIllegalSqlName (column.ToUTF8 ()) == 1
	|| gaiaIsReservedSqlName (column.ToUTF8 ()) == 1
	|| gaiaIsReservedSqliteName (column.ToUTF8 ()) == 1)
      {
	  wxMessageBox (wxT ("'") + column +
			wxT
			("' is an invalid COLUMN NAME\n\nsame as SQL reserved keyword"),
			wxT ("spatialite-gui"), wxOK | wxICON_ERROR, this);
	  return;
      }
    if (metadata == true)
      {
	  if (SridNotExists (srid) == true)
	    {
		wxMessageBox (wxT ("invalid SRID value"),
			      wxT ("spatialite-gui"), wxOK | wxICON_ERROR,
			      this);
		return;
	    }
      }
//
// initalizing the SHP struct
//
    shp = gaiaAllocShapefile ();
    gaiaOpenShpRead (shp, path.ToUTF8 (), charset.ToUTF8 (), "UTF-8");
    if (!(shp->Valid))
      {
	  gaiaFreeShapefile (shp);
	  return;
      }
    ::wxBeginBusyCursor ();
//
// checking for duplicate / illegal column names and antialising them 
//
    col_cnt = 0;
    dbf_field = shp->Dbf->First;
    while (dbf_field)
      {
	  // counting DBF fields
	  col_cnt++;
	  dbf_field = dbf_field->Next;
      }
    col_name = (char **) malloc (sizeof (char *) * col_cnt);
    cnt = 0;
    seed = 0;
    dbf_field = shp->Dbf->First;
    while (dbf_field)
      {
	  // preparing column names
	  if (gaiaIllegalSqlName (dbf_field->Name)
	      || gaiaIsReservedSqlName (dbf_field->Name)
	      || gaiaIsReservedSqliteName (dbf_field->Name))
	      sprintf (dummyName, "COL_%d", seed++);
	  else
	      strcpy (dummyName, dbf_field->Name);
	  dup = 0;
	  for (idup = 0; idup < cnt; idup++)
	    {
		if (strcasecmp (dummyName, *(col_name + idup)) == 0)
		    dup = 1;
	    }
	  if (strcasecmp (dummyName, "PK_UID") == 0)
	      dup = 1;
	  if (strcasecmp (dummyName, column.ToUTF8 ()) == 0)
	      dup = 1;
	  if (dup)
	      sprintf (dummyName, "COL_%d", seed++);
	  len = strlen (dummyName);
	  *(col_name + cnt) = (char *) malloc (len + 1);
	  strcpy (*(col_name + cnt), dummyName);
	  cnt++;
	  dbf_field = dbf_field->Next;
      }
//
// starting a transaction
//
    ret = sqlite3_exec (SqliteHandle, "BEGIN", NULL, 0, &errMsg);
    if (ret != SQLITE_OK)
      {
	  wxMessageBox (wxT ("load shapefile error:") +
			wxString::FromUTF8 (errMsg), wxT ("spatialite-gui"),
			wxOK | wxICON_ERROR, this);
	  sqlite3_free (errMsg);
	  sqlError = true;
	  goto clean_up;
      }
//
// creating the Table 
//
    strcpy (xtable, table.ToUTF8 ());
    strcpy (xcolumn, column.ToUTF8 ());
    sprintf (sql, "CREATE TABLE %s", xtable);
    strcat (sql, " (\nPK_UID INTEGER PRIMARY KEY AUTOINCREMENT");
    cnt = 0;
    dbf_field = shp->Dbf->First;
    while (dbf_field)
      {
	  strcat (sql, ",\n");
	  strcat (sql, *(col_name + cnt));
	  cnt++;
	  switch (dbf_field->Type)
	    {
	    case 'C':
		strcat (sql, " TEXT");
		break;
	    case 'N':
		if (dbf_field->Decimals)
		    strcat (sql, " DOUBLE");
		else
		  {
		      if (dbf_field->Length <= 9)
			  strcat (sql, " INTEGER");
		      else
			  strcat (sql, " DOUBLE");
		  }
		break;
	    case 'D':
		strcat (sql, " TEXT");
		break;
	    case 'L':
		strcat (sql, " INTEGER");
		break;
	    };
	  strcat (sql, " NOT NULL");
	  dbf_field = dbf_field->Next;
      }
    if (metadata == true)
	strcat (sql, ")");
    else
      {
	  strcat (sql, ",\n");
	  strcat (sql, xcolumn);
	  strcat (sql, " BLOB NOT NULL)");
      }
    ret = sqlite3_exec (SqliteHandle, sql, NULL, 0, &errMsg);
    if (ret != SQLITE_OK)
      {
	  wxMessageBox (wxT ("load shapefile error:") +
			wxString::FromUTF8 (errMsg), wxT ("spatialite-gui"),
			wxOK | wxICON_ERROR, this);
	  sqlite3_free (errMsg);
	  sqlError = true;
	  goto clean_up;
      }
    if (metadata)
      {
	  // creating Geometry column 
	  switch (shp->Shape)
	    {
	    case 1:
	    case 11:
	    case 21:
		geom_type = "POINT";
		break;
	    case 8:
		geom_type = "MULTIPOINT";
		break;
	    case 3:
	    case 13:
	    case 23:
		geom_type = "MULTILINESTRING";
		break;
	    case 5:
	    case 15:
	    case 25:
		geom_type = "MULTIPOLYGON";
		break;
	    };
	  sprintf (sql, "SELECT AddGeometryColumn('%s', '%s', %d, '%s', 2)",
		   xtable, xcolumn, srid, geom_type);
	  ret = sqlite3_exec (SqliteHandle, sql, NULL, 0, &errMsg);
	  if (ret != SQLITE_OK)
	    {
		wxMessageBox (wxT ("load shapefile error:") +
			      wxString::FromUTF8 (errMsg),
			      wxT ("spatialite-gui"), wxOK | wxICON_ERROR,
			      this);
		sqlite3_free (errMsg);
		sqlError = true;
		goto clean_up;
	    }
      }
    current_row = 0;
    while (1)
      {
	  //
	  // inserting rows from shapefile 
	  //
	  ret = gaiaReadShpEntity (shp, current_row, srid);
	  if (!ret)
	    {
		if (!(shp->LastError))	// normal SHP EOF
		    break;
		wxMessageBox (wxT ("load shapefile error:") +
			      wxString::FromUTF8 (shp->LastError),
			      wxT ("spatialite-gui"), wxOK | wxICON_ERROR,
			      this);
		sqlError = true;
		goto clean_up;
	    }
	  current_row++;
	  sprintf (sql, "INSERT INTO %s (\nPK_UID,", xtable);
	  cnt = 0;
	  dbf_field = shp->Dbf->First;
	  while (dbf_field)
	    {
		// columns corresponding to some DBF attribute 
		strcat (sql, *(col_name + cnt));
		cnt++;
		strcat (sql, ",");
		dbf_field = dbf_field->Next;
	    }
	  strcat (sql, xcolumn);	// the GEOMETRY column
	  strcat (sql, ")\nVALUES (");
	  sprintf (dummy, "%d,", current_row);
	  strcat (sql, dummy);
	  dbf_field = shp->Dbf->First;
	  while (dbf_field)
	    {
		// column values
		if (!(dbf_field->Value))
		    strcat (sql, "NULL");
		else
		  {
		      switch (dbf_field->Value->Type)
			{
			case GAIA_INT_VALUE:
			    sprintf (dummy, "%d", dbf_field->Value->IntValue);
			    strcat (sql, dummy);
			    break;
			case GAIA_DOUBLE_VALUE:
			    sprintf (dummy, "%1.6lf",
				     dbf_field->Value->DblValue);
			    strcat (sql, dummy);
			    break;
			case GAIA_TEXT_VALUE:
			    strcpy (dummy, dbf_field->Value->TxtValue);
			    CleanSqlString (dummy);
			    strcat (sql, "'");
			    strcat (sql, dummy);
			    strcat (sql, "'");
			    break;
			default:
			    strcat (sql, "NULL");
			    break;
			};
		  }
		strcat (sql, ",");
		dbf_field = dbf_field->Next;
	    }
	  hexWKB = gaiaToHexWkb (shp->Dbf->Geometry);
	  szSQL = strlen (sql) + strlen (hexWKB) + 1024;
	  bufSQL = (char *) malloc (szSQL);
	  strcpy (bufSQL, sql);
	  strcat (bufSQL, "\n");
	  strcat (bufSQL, "GeomFromWkb(X'");
	  strcat (bufSQL, hexWKB);
	  sprintf (dummy, "', %d))", srid);
	  strcat (bufSQL, dummy);
	  ret = sqlite3_exec (SqliteHandle, bufSQL, NULL, 0, &errMsg);
	  if (ret != SQLITE_OK)
	    {
		wxMessageBox (wxT ("load shapefile error:") +
			      wxString::FromUTF8 (errMsg),
			      wxT ("spatialite-gui"), wxOK | wxICON_ERROR,
			      this);
		sqlite3_free (errMsg);
		sqlError = true;
		goto clean_up;
	    }
	  rows++;
	  free (hexWKB);
	  hexWKB = NULL;
	  free (bufSQL);
	  bufSQL = NULL;
      }
  clean_up:
    if (hexWKB)
	free (hexWKB);
    if (bufSQL)
	free (bufSQL);
    gaiaFreeShapefile (shp);
    if (col_name)
      {
	  // releasing memory allocation for column names 
	  for (cnt = 0; cnt < col_cnt; cnt++)
	      free (*(col_name + cnt));
	  free (col_name);
      }
    if (sqlError == true)
      {
	  // some error occurred - ROLLBACK 
	  ret = sqlite3_exec (SqliteHandle, "ROLLBACK", NULL, 0, &errMsg);
	  if (ret != SQLITE_OK)
	    {
		wxMessageBox (wxT ("load shapefile error:") +
			      wxString::FromUTF8 (errMsg),
			      wxT ("spatialite-gui"), wxOK | wxICON_ERROR,
			      this);
		sqlite3_free (errMsg);
	    }
	  ::wxEndBusyCursor ();
	  msg.Printf (wxT
		      ("Shapefile not loaded\n\n\na ROLLBACK was automatically performed"));
	  wxMessageBox (msg, wxT ("spatialite-gui"), wxOK | wxICON_WARNING,
			this);
      }
    else
      {
	  // ok - confirming pending transaction - COMMIT 
	  ret = sqlite3_exec (SqliteHandle, "COMMIT", NULL, 0, &errMsg);
	  if (ret != SQLITE_OK)
	    {
		wxMessageBox (wxT ("load shapefile error:") +
			      wxString::FromUTF8 (errMsg),
			      wxT ("spatialite-gui"), wxOK | wxICON_ERROR,
			      this);
		sqlite3_free (errMsg);
		return;
	    }
	  ::wxEndBusyCursor ();
	  msg.Printf (wxT ("Shapefile loaded\n\n%d inserted rows"), rows);
	  wxMessageBox (msg, wxT ("spatialite-gui"),
			wxOK | wxICON_INFORMATION, this);
	  ClearTableTree ();
	  InitTableTree ();
      }
}

gaiaDbfFieldPtr MyFrame::GetDbfField (gaiaDbfListPtr list, char *name)
{
//
// find a DBF attribute by name 
//
    gaiaDbfFieldPtr
	fld = list->First;
    while (fld)
      {
	  if (strcasecmp (fld->Name, name) == 0)
	      return fld;
	  fld = fld->Next;
      }
    return NULL;
}

void
MyFrame::DumpShapefile (wxString & path, wxString & table, wxString & column,
			wxString & charset)
{
//
// dumping a  geometry table as Shapefile
//
    char **results;
    int rows;
    int columns;
    int i;
    char *errMsg = NULL;
    char *gtype;
    wxString geometryType;
    int shape = -1;
    char xtable[1024];
    char xcolumn[1024];
    char xpath[1024];
    char xsql[4096];
    sqlite3_stmt *stmt;
    int row1 = 0;
    int n_cols = 0;
    int offset = 0;
    int type;
    int multiple_entities = 0;
    const unsigned char *char_value;
    const void *blob_value;
    gaiaShapefilePtr shp = NULL;
    gaiaDbfListPtr dbf_export_list = NULL;
    gaiaDbfListPtr dbf_list = NULL;
    gaiaDbfListPtr dbf_write;
    gaiaDbfFieldPtr dbf_field;
    gaiaGeomCollPtr geom;
    int *max_length = NULL;
    int *sql_type = NULL;
    char dummy[1024];
    int len;
    wxString msg;
    wxString sql =
	wxT ("SELECT type FROM geometry_columns WHERE f_table_name = '");
    sql += table;
    sql += wxT ("' AND f_geometry_column = '");
    sql += column;
    sql += wxT ("'");
    int ret = sqlite3_get_table (SqliteHandle, sql.ToUTF8 (), &results,
				 &rows, &columns, &errMsg);
    if (ret != SQLITE_OK)
      {
	  wxMessageBox (wxT ("dump shapefile error:") +
			wxString::FromUTF8 (errMsg), wxT ("spatialite-gui"),
			wxOK | wxICON_ERROR, this);
	  sqlite3_free (errMsg);
	  return;
      }
    if (rows < 1)
	;
    else
      {
	  for (i = 1; i <= rows; i++)
	    {
		gtype = results[(i * columns) + 0];
		geometryType = wxString::FromUTF8 (gtype);
	    }
      }
    sqlite3_free_table (results);
    if (geometryType == wxT ("POINT"))
	shape = GAIA_POINT;
    if (geometryType == wxT ("MULTIPOINT"))
	shape = GAIA_MULTIPOINT;
    if (geometryType == wxT ("LINESTRING")
	|| geometryType == wxT ("MULTILINESTRING"))
	shape = GAIA_LINESTRING;
    if (geometryType == wxT ("POLYGON") || geometryType == wxT ("MULTIPOLYGON"))
	shape = GAIA_POLYGON;
    if (shape < 0)
      {
	  wxMessageBox (wxT ("Unable to detect GeometryType for '") +
			table + wxT (".") + column + wxT ("'"),
			wxT ("spatialite-gui"), wxOK | wxICON_ERROR, this);
	  return;
      }
//
// preparing SQL statement 
//
    strcpy (xtable, table.ToUTF8 ());
    strcpy (xcolumn, column.ToUTF8 ());
    sprintf (xsql, "SELECT * FROM %s WHERE GeometryType(%s) = ", xtable,
	     xcolumn);
    if (shape == GAIA_LINESTRING)
      {
	  strcat (xsql, "'LINESTRING' OR GeometryType(");
	  strcat (xsql, xcolumn);
	  strcat (xsql, ") = 'MULTILINESTRING'");
      }
    else if (shape == GAIA_POLYGON)
      {
	  strcat (xsql, "'POLYGON' OR GeometryType(");
	  strcat (xsql, xcolumn);
	  strcat (xsql, ") = 'MULTIPOLYGON'");
      }
    else if (shape == GAIA_MULTIPOINT)
      {
	  strcat (xsql, "'POINT' OR GeometryType(");
	  strcat (xsql, xcolumn);
	  strcat (xsql, ") = 'MULTIPOINT'");
      }
    else
	strcat (xsql, "'POINT'");
//
// compiling SQL prepared statement 
//
    ret = sqlite3_prepare_v2 (SqliteHandle, xsql, strlen (xsql), &stmt, NULL);
    if (ret != SQLITE_OK)
	goto sql_error;
    rows = 0;
    while (1)
      {
	  //
	  // Pass I - scrolling the result set to compute real DBF attributes' sizes and types 
	  //
	  ret = sqlite3_step (stmt);
	  if (ret == SQLITE_DONE)
	      break;		// end of result set
	  if (ret == SQLITE_ROW)
	    {
		// processing a result set row 
		row1++;
		if (n_cols == 0)
		  {
		      // this one is the first row, so we are going to prepare the DBF Fields list 
		      n_cols = sqlite3_column_count (stmt);
		      dbf_export_list = gaiaAllocDbfList ();
		      max_length = (int *) malloc (sizeof (int) * n_cols);
		      sql_type = (int *) malloc (sizeof (int) * n_cols);
		      for (i = 0; i < n_cols; i++)
			{
			    // initializes the DBF export fields
			    strcpy (dummy, sqlite3_column_name (stmt, i));
			    gaiaAddDbfField (dbf_export_list, dummy, '\0', 0,
					     0, 0);
			    max_length[i] = 0;
			    sql_type[i] = SQLITE_NULL;
			}
		  }
		for (i = 0; i < n_cols; i++)
		  {
		      // update the DBF export fields analyzing fetched data
		      type = sqlite3_column_type (stmt, i);
		      if (type == SQLITE_BLOB && strcasecmp ((char *) xcolumn,
							     (char *)
							     sqlite3_column_name
							     (stmt, i)) == 0
			  && shape == GAIA_POINT)
			{
			    // 
			    // we need to check if there is any MULTIPOINT,
			    // because shapefile handles simple-points shapes and multi-points shapes
			    // in a complete differet way
			    //
			    blob_value = sqlite3_column_blob (stmt, i);
			    len = sqlite3_column_bytes (stmt, i);
			    geom =
				gaiaFromSpatiaLiteBlobWkb ((unsigned char *)
							   blob_value, len);
			    if (geom)
			      {
				  if (geom->FirstPoint != geom->LastPoint)
				      multiple_entities = 1;
				  gaiaFreeGeomColl (geom);
			      }
			}
		      if (type == SQLITE_NULL || type == SQLITE_BLOB)
			  continue;
		      if (type == SQLITE_TEXT)
			{
			    char_value = sqlite3_column_text (stmt, i);
			    len = sqlite3_column_bytes (stmt, i);
			    sql_type[i] = SQLITE_TEXT;
			    if (len > max_length[i])
				max_length[i] = len;
			}
		      else if (type == SQLITE_FLOAT
			       && sql_type[i] != SQLITE_TEXT)
			  sql_type[i] = SQLITE_FLOAT;	// promoting a numeric column to be DOUBLE
		      else if (type == SQLITE_INTEGER
			       && (sql_type[i] == SQLITE_NULL
				   || sql_type[i] == SQLITE_INTEGER))
			  sql_type[i] = SQLITE_INTEGER;	// promoting a null column to be INTEGER
		  }
	    }
	  else
	      goto sql_error;
      }
    if (!row1)
	goto empty_result_set;
    i = 0;
    offset = 0;
    dbf_list = gaiaAllocDbfList ();
    dbf_field = dbf_export_list->First;
    while (dbf_field)
      {
	  // preparing the final DBF attribute list 
	  if (sql_type[i] == SQLITE_NULL)
	    {
		i++;
		dbf_field = dbf_field->Next;
		continue;
	    }
	  if (sql_type[i] == SQLITE_TEXT)
	    {
		gaiaAddDbfField (dbf_list, dbf_field->Name, 'C', offset,
				 max_length[i], 0);
		offset += max_length[i];
	    }
	  if (sql_type[i] == SQLITE_FLOAT)
	    {
		gaiaAddDbfField (dbf_list, dbf_field->Name, 'N', offset, 24, 6);
		offset += 24;
	    }
	  if (sql_type[i] == SQLITE_INTEGER)
	    {
		gaiaAddDbfField (dbf_list, dbf_field->Name, 'N', offset, 9, 0);
		offset += 9;
	    }
	  i++;
	  dbf_field = dbf_field->Next;
      }
    free (max_length);
    free (sql_type);
    gaiaFreeDbfList (dbf_export_list);
// resetting SQLite query 
    ret = sqlite3_reset (stmt);
    if (ret != SQLITE_OK)
	goto sql_error;
// trying to open shapefile files 
    shp = gaiaAllocShapefile ();
    strcpy (xpath, path.ToUTF8 ());
    gaiaOpenShpWrite (shp, xpath, shape, dbf_list, "UTF-8", charset.ToUTF8 ());
    if (!(shp->Valid))
	goto no_file;
    while (1)
      {
	  // Pass II - scrolling the result set to dump data into shapefile 
	  ret = sqlite3_step (stmt);
	  if (ret == SQLITE_DONE)
	      break;		// end of result set
	  if (ret == SQLITE_ROW)
	    {
		rows++;
		geom = NULL;
		dbf_write = gaiaCloneDbfEntity (dbf_list);
		for (i = 0; i < n_cols; i++)
		  {
		      if (strcasecmp
			  ((char *) xcolumn,
			   (char *) sqlite3_column_name (stmt, i)) == 0)
			{
			    // this one is the internal BLOB encoded GEOMETRY to be exported 
			    blob_value = sqlite3_column_blob (stmt, i);
			    len = sqlite3_column_bytes (stmt, i);
			    dbf_write->Geometry =
				gaiaFromSpatiaLiteBlobWkb ((unsigned char *)
							   blob_value, len);
			}
		      strcpy (dummy, sqlite3_column_name (stmt, i));
		      dbf_field = GetDbfField (dbf_write, dummy);
		      if (!dbf_field)
			  continue;
		      switch (dbf_field->Type)
			{
			case 'N':
			    if (sqlite3_column_type (stmt, i) == SQLITE_INTEGER)
				gaiaSetIntValue (dbf_field,
						 sqlite3_column_int (stmt, i));
			    else if (sqlite3_column_type (stmt, i) ==
				     SQLITE_FLOAT)
				gaiaSetDoubleValue (dbf_field,
						    sqlite3_column_double
						    (stmt, i));
			    else
				gaiaSetNullValue (dbf_field);
			    break;
			case 'C':
			    if (sqlite3_column_type (stmt, i) == SQLITE_TEXT)
			      {
				  strcpy (dummy,
					  (char *) sqlite3_column_text (stmt,
									i));
				  gaiaSetStrValue (dbf_field, dummy);
			      }
			    else
				gaiaSetNullValue (dbf_field);
			    break;
			};
		  }
		if (!(dbf_write->Geometry))
		  {
		      gaiaFreeDbfList (dbf_write);
		      continue;
		  }
		if (!gaiaWriteShpEntity (shp, dbf_write))
		  {
		      wxMessageBox (wxT ("Shapefile write error"),
				    wxT ("spatialite-gui"),
				    wxOK | wxICON_INFORMATION, this);
		  }
		gaiaFreeDbfList (dbf_write);
	    }
	  else
	      goto sql_error;
      }
    sqlite3_finalize (stmt);
    gaiaFlushShpHeaders (shp);
    gaiaFreeShapefile (shp);
    msg.Printf (wxT ("Exported %d rows into Shapefile"), rows);
    wxMessageBox (msg, wxT ("spatialite-gui"), wxOK | wxICON_INFORMATION, this);
    return;
  sql_error:
//
// some SQL error occurred
//
    sqlite3_finalize (stmt);
    if (dbf_export_list);
    gaiaFreeDbfList (dbf_export_list);
    if (dbf_list);
    gaiaFreeDbfList (dbf_list);
    if (shp)
	gaiaFreeShapefile (shp);
    wxMessageBox (wxT ("dump shapefile error:") +
		  wxString::FromUTF8 (sqlite3_errmsg (SqliteHandle)),
		  wxT ("spatialite-gui"), wxOK | wxICON_ERROR, this);
    return;
  no_file:
//
// shapefile can't be created/opened
//
    if (dbf_export_list);
    gaiaFreeDbfList (dbf_export_list);
    if (dbf_list);
    gaiaFreeDbfList (dbf_list);
    if (shp)
	gaiaFreeShapefile (shp);
    wxMessageBox (wxT ("ERROR: unable to open '") + path +
		  wxT ("' for writing"), wxT ("spatialite-gui"),
		  wxOK | wxICON_ERROR, this);
    return;
  empty_result_set:
//
// the result set is empty - nothing to do 
//
    sqlite3_finalize (stmt);
    if (dbf_export_list);
    gaiaFreeDbfList (dbf_export_list);
    if (dbf_list);
    gaiaFreeDbfList (dbf_list);
    if (shp)
	gaiaFreeShapefile (shp);
    wxMessageBox (wxT
		  ("The SQL SELECT returned an empty result set\n... there is nothing to export ..."),
		  wxT ("spatialite-gui"), wxOK | wxICON_WARNING, this);
}

void
MyFrame::DumpTxtTab (wxString & path, wxString & table, wxString & charset)
{
//
// dumping a  table as Txt/Tab
//
    wxString sql;
    sqlite3_stmt *stmt;
    int ret;
    int rows = 0;
    int i;
    int n_cols;
    char xpath[1024];
    char dummy[65536];
    char outCs[128];
    char *pDummy;
    wxString msg;
    strcpy (outCs, charset.ToUTF8 ());
    strcpy (xpath, path.ToUTF8 ());
    FILE *out = fopen (xpath, "w");
    if (!out)
	goto no_file;
//
// preparing SQL statement 
//
    sql = wxT ("SELECT * FROM ");
    sql += table;
//
// compiling SQL prepared statement 
//
    ret =
	sqlite3_prepare_v2 (SqliteHandle, sql.ToUTF8 (), sql.Len (), &stmt,
			    NULL);
    if (ret != SQLITE_OK)
	goto sql_error;
    rows = 0;
    while (1)
      {
	  ret = sqlite3_step (stmt);
	  if (ret == SQLITE_DONE)
	      break;		// end of result set
	  if (ret == SQLITE_ROW)
	    {
		n_cols = sqlite3_column_count (stmt);
		if (rows == 0)
		  {
		      // outputting the column titles
		      for (i = 0; i < n_cols; i++)
			{
			    if (i == 0)
				fprintf (out, "%s",
					 sqlite3_column_name (stmt, i));
			    else
				fprintf (out, "\t%s",
					 sqlite3_column_name (stmt, i));
			}
		      fprintf (out, "\n");
		  }
		rows++;
		for (i = 0; i < n_cols; i++)
		  {
		      if (i > 0)
			  fprintf (out, "\t");
		      if (sqlite3_column_type (stmt, i) == SQLITE_INTEGER)
			  fprintf (out, "%d", sqlite3_column_int (stmt, i));
		      else if (sqlite3_column_type (stmt, i) == SQLITE_FLOAT)
			  fprintf (out, "%1.6lf",
				   sqlite3_column_double (stmt, i));
		      else if (sqlite3_column_type (stmt, i) == SQLITE_TEXT)
			{
			    strcpy (dummy,
				    (char *) sqlite3_column_text (stmt, i));
			    CleanTxtTab (dummy);
			    pDummy = dummy;
			    if (!gaiaConvertCharset (&pDummy, "UTF-8", outCs))
				goto encoding_error;
			    fprintf (out, "%s", dummy);
			}
		  }
		fprintf (out, "\n");
	    }
	  else
	      goto sql_error;
      }
    sqlite3_finalize (stmt);
    fclose (out);
    msg.Printf (wxT ("Exported %d rows into Txt/Tab file"), rows);
    wxMessageBox (msg, wxT ("spatialite-gui"), wxOK | wxICON_INFORMATION, this);
    return;
  sql_error:
//
// some SQL error occurred
//
    sqlite3_finalize (stmt);
    wxMessageBox (wxT ("dump Txt/Tab error:") +
		  wxString::FromUTF8 (sqlite3_errmsg (SqliteHandle)),
		  wxT ("spatialite-gui"), wxOK | wxICON_ERROR, this);
    if (out)
	fclose (out);
    return;
  encoding_error:
//
// some CHARSET converion occurred
//
    sqlite3_finalize (stmt);
    wxMessageBox (wxT ("dump Txt/Tab: charset conversion reported an error"),
		  wxT ("spatialite-gui"), wxOK | wxICON_ERROR, this);
    if (out)
	fclose (out);
    return;
  no_file:
//
// output file can't be created/opened
//
    wxMessageBox (wxT ("ERROR: unable to open '") + path +
		  wxT ("' for writing"), wxT ("spatialite-gui"),
		  wxOK | wxICON_ERROR, this);
    return;
}

void
MyFrame::DumpCsv (wxString & path, wxString & table, wxString & charset)
{
//
// dumping a  table as CSV
//
    wxString sql;
    sqlite3_stmt *stmt;
    int ret;
    int rows = 0;
    int i;
    int n_cols;
    char xpath[1024];
    char dummy[65536];
    char outCs[128];
    char *pDummy;
    wxString msg;
    strcpy (outCs, charset.ToUTF8 ());
    strcpy (xpath, path.ToUTF8 ());
    FILE *out = fopen (xpath, "w");
    if (!out)
	goto no_file;
//
// preparing SQL statement 
//
    sql = wxT ("SELECT * FROM ");
    sql += table;

//
// compiling SQL prepared statement 
//
    ret =
	sqlite3_prepare_v2 (SqliteHandle, sql.ToUTF8 (), sql.Len (), &stmt,
			    NULL);

    if (ret != SQLITE_OK)
	goto sql_error;
    rows = 0;
    while (1)
      {
	  ret = sqlite3_step (stmt);
	  if (ret == SQLITE_DONE)
	      break;		// end of result set
	  if (ret == SQLITE_ROW)
	    {
		n_cols = sqlite3_column_count (stmt);
		if (rows == 0)
		  {
		      // outputting the column titles
		      for (i = 0; i < n_cols; i++)
			{
			    if (i == 0)
			      {
				  strcpy (dummy, sqlite3_column_name (stmt, i));
				  CleanCsv (dummy);
				  fprintf (out, "%s", dummy);
			      }
			    else
			      {
				  strcpy (dummy, sqlite3_column_name (stmt, i));
				  CleanCsv (dummy);
				  fprintf (out, ",%s", dummy);
			      }
			}
		      fprintf (out, "\n");
		  }
		rows++;
		for (i = 0; i < n_cols; i++)
		  {
		      if (i > 0)
			  fprintf (out, ",");
		      if (sqlite3_column_type (stmt, i) == SQLITE_INTEGER)
			  fprintf (out, "%d", sqlite3_column_int (stmt, i));
		      else if (sqlite3_column_type (stmt, i) == SQLITE_FLOAT)
			  fprintf (out, "%1.6lf",
				   sqlite3_column_double (stmt, i));
		      else if (sqlite3_column_type (stmt, i) == SQLITE_TEXT)
			{
			    strcpy (dummy,
				    (char *) sqlite3_column_text (stmt, i));
			    CleanCsv (dummy);
			    pDummy = dummy;
			    if (!gaiaConvertCharset
				(&pDummy, (const char *) "UTF-8", outCs))
				goto encoding_error;
			    fprintf (out, "%s", dummy);
			}
		  }
		fprintf (out, "\n");
	    }
	  else
	      goto sql_error;
      }
    sqlite3_finalize (stmt);
    fclose (out);
    msg.Printf (wxT ("Exported %d rows into CSV file"), rows);

    wxMessageBox (msg, wxT ("spatialite-gui"), wxOK | wxICON_INFORMATION, this);
    return;
  sql_error:
//
// some SQL error occurred
//
    sqlite3_finalize (stmt);
    wxMessageBox (wxT ("dump CSV error:") +
		  wxString::FromUTF8 (sqlite3_errmsg (SqliteHandle)),

		  wxT ("spatialite-gui"), wxOK | wxICON_ERROR, this);
    if (out)
	fclose (out);
    return;
  encoding_error:
//
// some CHARSET converion occurred
//
    sqlite3_finalize (stmt);
    wxMessageBox (wxT ("dump CSV: charset conversion reported an error"),
		  wxT ("spatialite-gui"), wxOK | wxICON_ERROR, this);
    if (out)
	fclose (out);
    return;
  no_file:
//
// output file can't be created/opened
//
    wxMessageBox (wxT ("ERROR: unable to open '") + path +
		  wxT ("' for writing"), wxT ("spatialite-gui"),
		  wxOK | wxICON_ERROR, this);
    return;
}

void
MyFrame::DumpHtml (wxString & path, wxString & table, wxString & charset)
{
//
// dumping a  table as HTML
//
    wxString sql;
    sqlite3_stmt *stmt;
    int ret;
    int rows = 0;
    int i;
    int n_cols;
    char xpath[1024];
    char xtable[1024];
    char dummy[65536];
    char outCs[128];
    char *pDummy;
    wxString msg;
    strcpy (outCs, charset.ToUTF8 ());
    strcpy (xpath, path.ToUTF8 ());
    strcpy (xtable, table.ToUTF8 ());
    FILE *out = fopen (xpath, "w");
    if (!out)
	goto no_file;
    fprintf (out,
	     "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n");
    fprintf (out, "<html>\n\t<head>\n");
    fprintf (out,
	     "\t\t<meta http-equiv=\"content-type\" content=\"text/html; charset=%s\">\n",
	     outCs);
    fprintf (out, "\t\t<title>\nTable '%s': from SQLite/SpatiaLite DB '%s'\n",
	     xtable, xpath);
    fprintf (out, "\t\t</title>\n");
    fprintf (out, "\t\t<style type=\"text/css\">\n");
    fprintf (out, "table { border: 1px; }\n");
    fprintf (out, "tr.t0 th { background-color: #c9c9df; }\n");
    fprintf (out, "tr.d0 td { background-color: #e0efe0; }\n");
    fprintf (out, "tr.d1 td { background-color: #d0d0df; }\n");
    fprintf (out, "\t\t</style>\n\t</head>\n\t<body>\n\t\t<table>\n");
//
// preparing SQL statement 
//
    sql = wxT ("SELECT * FROM ");
    sql += table;

//
// compiling SQL prepared statement 
//
    ret =
	sqlite3_prepare_v2 (SqliteHandle, sql.ToUTF8 (), sql.Len (), &stmt,
			    NULL);

    if (ret != SQLITE_OK)
	goto sql_error;
    rows = 0;
    while (1)
      {
	  ret = sqlite3_step (stmt);
	  if (ret == SQLITE_DONE)
	      break;		// end of result set
	  if (ret == SQLITE_ROW)
	    {
		n_cols = sqlite3_column_count (stmt);
		if (rows == 0)
		  {
		      // outputting the column titles
		      fprintf (out, "\t\t\t<tr class=\"t0\">\n");
		      for (i = 0; i < n_cols; i++)
			{
			    strcpy (dummy, sqlite3_column_name (stmt, i));
			    CleanHtml (dummy);
			    fprintf (out, "\t\t\t\t<th>%s</th>\n", dummy);
			}
		      fprintf (out, "\t\t\t</tr>\n");
		  }
		rows++;
		fprintf (out, "\t\t\t<tr class=\"%s\">\n",
			 (rows % 2) ? "d0" : "d1");
		for (i = 0; i < n_cols; i++)
		  {
		      if (sqlite3_column_type (stmt, i) == SQLITE_INTEGER)
			  fprintf (out,
				   "\t\t\t\t<td align=\"right\">%d</td>\n",
				   sqlite3_column_int (stmt, i));
		      else if (sqlite3_column_type (stmt, i) == SQLITE_FLOAT)
			  fprintf (out,
				   "\t\t\t\t<td align=\"right\">%1.6lf</td>\n",
				   sqlite3_column_double (stmt, i));
		      else if (sqlite3_column_type (stmt, i) == SQLITE_TEXT)
			{
			    strcpy (dummy,
				    (char *) sqlite3_column_text (stmt, i));
			    CleanHtml (dummy);
			    pDummy = dummy;
			    if (!gaiaConvertCharset
				(&pDummy, (const char *) "UTF-8", outCs))
				goto encoding_error;
			    fprintf (out, "\t\t\t\t<td>%s</td>\n", dummy);
			}
		  }
		fprintf (out, "\t\t\t</tr>\n");
	    }
	  else
	      goto sql_error;
      }
    sqlite3_finalize (stmt);
    fprintf (out, "\t\t</table>\n\t</body>\n</html>\n");
    fclose (out);
    msg.Printf (wxT ("Exported %d rows into HTML file"), rows);

    wxMessageBox (msg, wxT ("spatialite-gui"), wxOK | wxICON_INFORMATION, this);
    return;
  sql_error:
//
// some SQL error occurred
//
    sqlite3_finalize (stmt);
    wxMessageBox (wxT ("dump HTML error:") +
		  wxString::FromUTF8 (sqlite3_errmsg (SqliteHandle)),

		  wxT ("spatialite-gui"), wxOK | wxICON_ERROR, this);
    if (out)
	fclose (out);
    return;
  encoding_error:
//
// some CHARSET converion occurred
//
    sqlite3_finalize (stmt);
    wxMessageBox (wxT ("dump HTML: charset conversion reported an error"),
		  wxT ("spatialite-gui"), wxOK | wxICON_ERROR, this);
    if (out)
	fclose (out);
    return;
  no_file:
//
// output file can't be created/opened
//
    wxMessageBox (wxT ("ERROR: unable to open '") + path +
		  wxT ("' for writing"), wxT ("spatialite-gui"),
		  wxOK | wxICON_ERROR, this);
    return;
}




|







 







<
|


|
|
|
|
|
|
|
|
|
|
<
|
|
|
|


<
|


|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|


<
|


|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|


|




<
|
<
|
<
|
|
<
<
|
<
|
|
<
<
|
|
|
<
|
|
|
|
|
<
|
|
|
|
|
|
|
|
|
|
|
|
|


|




<
|
<
|
<
|
|
<
<
|
<
|
<
|
<
|
>
|
<
|
|
<
|
|
|
|
|
<
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<
|
|
|
<
|
|
|
|
<
|
|
|
|
|
|
|
|
|
|
|
|
|


|




<
|
<
|
<
|
|
<
<
|
<
|
>
>
|
<
|
|
<
|
|
|
|
|
<
|
|
|
|
|
|
|
|
|
|
|
|
|


<
|






|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<
<
<
<




|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<
<
<
<
<
<
<
<
<



|
<
|
|


<
|




|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|



|
|
>



<
<
<
>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<
|
|
|
<
|
|
|
|
|
|
|
|
|
|
<
|
|
|
|
|
|
>
|
|
|



|
|
<
>
|
|
|
|
|



|
|
|
|
|
|
|



|
<
|
|


<
|




|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|



|
|
>



<
<
<
>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<
|
|
|
<
|
|
|
<
|
|
|
|
<
|
|
|
|
|
|
|
|
|
|
<
|
|
|
|
|
|
|
>
|
|
|



|
|
<
>
|
|
|
|
|

|

|
|
|
|
|
|
|



|
<
|
|

1
2
3
4
5
6
7
8
9
10
11
12
..
21
22
23
24
25
26
27

28
29
30
31
32
33
34
35
36
37
38
39
40

41
42
43
44
45
46

47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70

71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139

140

141

142
143


144

145
146


147
148
149

150
151
152
153
154

155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174

175

176

177
178


179

180

181

182
183
184

185
186

187
188
189
190
191

192
193
194
195
196
197
198
199
200
201
202
203
204
205

206
207
208

209
210
211
212

213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232

233

234

235
236


237

238
239
240
241

242
243

244
245
246
247
248

249
250
251
252
253
254
255
256
257
258
259
260
261
262
263

264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673




674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152









1153
1154
1155
1156

1157
1158
1159
1160

1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190



1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212

1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229

1230
1231
1232

1233
1234
1235
1236
1237
1238
1239
1240
1241
1242

1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257

1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277

1278
1279
1280
1281

1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328



1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354

1355
1356
1357

1358
1359
1360

1361
1362
1363
1364

1365
1366
1367
1368
1369
1370
1371
1372
1373
1374

1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390

1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410

1411
1412
1413
/*
/ Shapefiles.cpp
/ methods related to Shapefile loading and saving
/
/ version 1.2, 2008 October 9
/
/ Author: Sandro Furieri a-furieri@lqt.it
/
/ Copyright (C) 2008  Alessandro Furieri
/
/    This program is free software: you can redistribute it and/or modify
/    it under the terms of the GNU General Public License as published by
................................................................................
/    You should have received a copy of the GNU General Public License
/    along with this program.  If not, see <http://www.gnu.org/licenses/>.
/
*/

#include "Classdef.h"


void MyFrame::CleanTxtTab(char *buf)
{
// well-formatting a string to be used as a Txt/Tab string
  char tmp[65536];
  char *in = tmp;
  char *out = buf;
  strcpy(tmp, buf);
  while (*in != '\0')
    {
      if (*in == '\t' || *in == '\r' || *in == '\n')
        {
          in++;
          *out++ = ' ';

      } else
        *out++ = *in++;
    }
  *out = '\0';
}


void MyFrame::CleanCsv(char *buf)
{
// well-formatting a string to be used as a Csv string
  char tmp[65536];
  char *in = tmp;
  char *out = buf;
  bool special = false;
  strcpy(tmp, buf);
  while (*in != '\0')
    {
      if (*in == ',' || *in == '\r' || *in == '\n')
        special = true;
      if (*in == '"')
        *out++ = '"';
      *out++ = *in++;
    }
  *out = '\0';
  if (special == true)
    {
      sprintf(tmp, "\"%s\"", buf);
      strcpy(buf, tmp);
    }
}


void MyFrame::CleanHtml(char *buf)
{
// well-formatting a string to be used as an Html string
  char tmp[65536];
  char *in = tmp;
  char *out = buf;
  strcpy(tmp, buf);
  while (*in != '\0')
    {
      if (*in == '<')
        {
          *out++ = '&';
          *out++ = 'l';
          *out++ = 't';
          *out++ = ';';
          in++;
          continue;
        }
      if (*in == '>')
        {
          *out++ = '&';
          *out++ = 'g';
          *out++ = 't';
          *out++ = ';';
          in++;
          continue;
        }
      if (*in == ' ')
        {
          *out++ = '&';
          *out++ = 'n';
          *out++ = 'b';
          *out++ = 's';
          *out++ = 'p';
          *out++ = ';';
          in++;
          continue;
        }
      if (*in == '"')
        {
          *out++ = '&';
          *out++ = 'q';
          *out++ = 'u';
          *out++ = 'o';
          *out++ = 't';
          *out++ = ';';
          in++;
          continue;
        }
      if (*in == '&')
        {
          *out++ = '&';
          *out++ = 'a';
          *out++ = 'm';
          *out++ = 'p';
          *out++ = ';';
          in++;
          continue;
        }
      *out++ = *in++;
    }
  *out = '\0';
}

bool MyFrame::TableAlreadyExists(wxString & name)
{
//
// checks if a table of this name already exists 
//

  char **results;

  int rows;

  int columns;
  int i;


  char *errMsg = NULL;

  bool already_exists = false;
  wxString sql =


    wxT("SELECT name FROM sqlite_master WHERE type = 'table' AND name LIKE '");
  sql += name;
  sql += wxT("'");

  int ret = sqlite3_get_table(SqliteHandle, sql.ToUTF8(), &results,
                              &rows, &columns, &errMsg);
  if (ret != SQLITE_OK)
    {
      wxMessageBox(wxT("SQLite SQL error: ") + wxString::FromUTF8(errMsg),

                   wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
      sqlite3_free(errMsg);
      return false;
    }
  if (rows < 1)
    ;
  else
    {
      for (i = 1; i <= rows; i++)
        already_exists = true;
    }
  sqlite3_free_table(results);
  return already_exists;
}

bool MyFrame::SridNotExists(int srid)
{
//
// checks if a SRID value is a valid one
//

  char **results;

  int rows;

  int columns;
  int i;


  char *errMsg = NULL;

  bool constrained = false;

  bool not_exists = true;

  wxString RefSysName;
  char xsql[128];
  wxString sql =

    wxT
    ("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'spatial_ref_sys'");

  int ret = sqlite3_get_table(SqliteHandle, sql.ToUTF8(), &results,
                              &rows, &columns, &errMsg);
  if (ret != SQLITE_OK)
    {
      wxMessageBox(wxT("SQLite SQL error: ") + wxString::FromUTF8(errMsg),

                   wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
      sqlite3_free(errMsg);
      return false;
    }
  if (rows < 1)
    ;
  else
    {
      for (i = 1; i <= rows; i++)
        constrained = true;
    }
  sqlite3_free_table(results);
  if (constrained == false)
    return false;

  sprintf(xsql, "SELECT ref_sys_name FROM spatial_ref_sys WHERE srid = %d",
          srid);
  ret =

    sqlite3_get_table(SqliteHandle, xsql, &results, &rows, &columns, &errMsg);
  if (ret != SQLITE_OK)
    {
      wxMessageBox(wxT("SQLite SQL error: ") + wxString::FromUTF8(errMsg),

                   wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
      sqlite3_free(errMsg);
      return false;
    }
  if (rows < 1)
    ;
  else
    {
      for (i = 1; i <= rows; i++)
        not_exists = false;
    }
  sqlite3_free_table(results);
  return not_exists;
}

bool MyFrame::CheckMetadata()
{
//
// checking if METADATA tables are defined
//

  char **results;

  int rows;

  int columns;
  int i;


  char *errMsg = NULL;

  bool constrained = false;
  if (SpatiaLiteMetadata == false)
    return false;
  wxString sql =

    wxT
    ("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'geometry_columns'");

  int ret = sqlite3_get_table(SqliteHandle, sql.ToUTF8(), &results,
                              &rows, &columns, &errMsg);
  if (ret != SQLITE_OK)
    {
      wxMessageBox(wxT("SQLite SQL error: ") + wxString::FromUTF8(errMsg),

                   wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
      sqlite3_free(errMsg);
      return false;
    }
  if (rows < 1)
    ;
  else
    {
      for (i = 1; i <= rows; i++)
        constrained = true;
    }
  sqlite3_free_table(results);
  return constrained;
}


void MyFrame::CleanSqlString(char *value)
{
//
// returns a well formatted TEXT value for SQL
// 1] strips trailing spaces
// 2] masks any ' inside the string, appending another '
//
  char new_value[1024];
  char *p;
  int len;
  int i;
  len = strlen(value);
  for (i = (len - 1); i >= 0; i--)
    {
      // stripping trailing spaces
      if (value[i] == ' ')
        value[i] = '\0';
      else
        break;
    }
  p = new_value;
  for (i = 0; i < len; i++)
    {
      if (value[i] == '\'')
        *(p++) = '\'';
      *(p++) = value[i];
    }
  *p = '\0';
  strcpy(value, new_value);
}

void MyFrame::LoadShapefile(wxString & path, wxString & table, int srid,
                            wxString & column, wxString & charset)
{
//
// loading a Shapefile as a new DB table
//
  sqlite3_stmt *stmt;
  int cnt;
  int col_cnt;
  int seed;
  int len;
  int dup;
  int idup;
  int current_row;
  int ret;
  int rows = 0;
  char *errMsg = NULL;
  char xtable[1024];
  char xcolumn[1024];
  char dummyName[4096];
  char sql[65536];
  char **col_name = NULL;
  unsigned char *blob;
  int blob_size;
  const char *geom_type = "UNKNOWN";
  wxString dummyStr;
  wxString msg;
  gaiaShapefilePtr shp = NULL;
  gaiaDbfFieldPtr dbf_field;
  bool metadata = CheckMetadata();
  bool sqlError = false;
//
// performing some checks before starting
//
  if (TableAlreadyExists(table) == true)
    {
      wxMessageBox(wxT("a table name '") + table + wxT("' already exists"),
                   wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
      return;
    }
  if (metadata == true)
    {
      if (SridNotExists(srid) == true)
        {
          wxMessageBox(wxT("invalid SRID value"), wxT("spatialite-gui"),
                       wxOK | wxICON_ERROR, this);
          return;
        }
    }
//
// initalizing the SHP struct
//
  shp = gaiaAllocShapefile();
  gaiaOpenShpRead(shp, path.ToUTF8(), charset.ToUTF8(), "UTF-8");
  if (!(shp->Valid))
    {
      wxString error = wxT("ERROR: invalid Shapefile\n\n");
      if (shp->LastError)
        error += wxString::FromUTF8(shp->LastError);
      gaiaFreeShapefile(shp);
      wxMessageBox(error, wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
      return;
    }
  ::wxBeginBusyCursor();
//
// checking for duplicate / illegal column names and antialising them 
//
  col_cnt = 0;
  dbf_field = shp->Dbf->First;
  while (dbf_field)
    {
      // counting DBF fields
      col_cnt++;
      dbf_field = dbf_field->Next;
    }
  col_name = (char **) malloc(sizeof(char *) * col_cnt);
  cnt = 0;
  seed = 0;
  dbf_field = shp->Dbf->First;
  while (dbf_field)
    {
      // preparing column names
      strcpy(dummyName, dbf_field->Name);
      dup = 0;
      for (idup = 0; idup < cnt; idup++)
        {
          if (strcasecmp(dummyName, *(col_name + idup)) == 0)
            dup = 1;
        }
      if (strcasecmp(dummyName, "PK_UID") == 0)
        dup = 1;
      if (strcasecmp(dummyName, column.ToUTF8()) == 0)
        dup = 1;
      if (dup)
        sprintf(dummyName, "COL_%d", seed++);
      len = strlen(dummyName);
      *(col_name + cnt) = (char *) malloc(len + 1);
      strcpy(*(col_name + cnt), dummyName);
      cnt++;
      dbf_field = dbf_field->Next;
    }
//
// starting a transaction
//
  ret = sqlite3_exec(SqliteHandle, "BEGIN", NULL, 0, &errMsg);
  if (ret != SQLITE_OK)
    {
      wxMessageBox(wxT("load shapefile error:") + wxString::FromUTF8(errMsg),
                   wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
      sqlite3_free(errMsg);
      sqlError = true;
      goto clean_up;
    }
//
// creating the Table 
//
  strcpy(xtable, table.ToUTF8());
  strcpy(xcolumn, column.ToUTF8());
  sprintf(sql, "CREATE TABLE \"%s\"", xtable);
  strcat(sql, " (\n\"PK_UID\" INTEGER PRIMARY KEY AUTOINCREMENT");
  cnt = 0;
  dbf_field = shp->Dbf->First;
  while (dbf_field)
    {
      strcat(sql, ",\n\"");
      strcat(sql, *(col_name + cnt));
      cnt++;
      switch (dbf_field->Type)
        {
          case 'C':
            strcat(sql, "\" TEXT");
            break;
          case 'N':
            if (dbf_field->Decimals)
              strcat(sql, "\" DOUBLE");
            else
              {
                if (dbf_field->Length <= 18)
                  strcat(sql, "\" INTEGER");
                else
                  strcat(sql, "\" DOUBLE");
              }
            break;
          case 'D':
            strcat(sql, "\" DOUBLE");
            break;
          case 'L':
            strcat(sql, "\" INTEGER");
            break;
        };
      dbf_field = dbf_field->Next;
    }
  if (metadata == true)
    strcat(sql, ")");
  else
    {
      strcat(sql, ",\n");
      strcat(sql, xcolumn);
      strcat(sql, " BLOB)");
    }
  ret = sqlite3_exec(SqliteHandle, sql, NULL, 0, &errMsg);
  if (ret != SQLITE_OK)
    {
      wxMessageBox(wxT("load shapefile error:") + wxString::FromUTF8(errMsg),
                   wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
      sqlite3_free(errMsg);
      sqlError = true;
      goto clean_up;
    }
  if (metadata)
    {
      // creating Geometry column 
      switch (shp->Shape)
        {
          case 1:
          case 11:
          case 21:
            geom_type = "POINT";
            break;
          case 8:
            geom_type = "MULTIPOINT";
            break;
          case 3:
          case 13:
          case 23:
            gaiaShpAnalyze(shp);
            if (shp->EffectiveType == GAIA_LINESTRING)
              geom_type = "LINESTRING";
            else
              geom_type = "MULTILINESTRING";
            break;
          case 5:
          case 15:
          case 25:
            gaiaShpAnalyze(shp);
            if (shp->EffectiveType == GAIA_POLYGON)
              geom_type = "POLYGON";
            else
              geom_type = "MULTIPOLYGON";
            break;
        };
      sprintf(sql, "SELECT AddGeometryColumn('%s', '%s', %d, '%s', 2)", xtable,
              xcolumn, srid, geom_type);
      ret = sqlite3_exec(SqliteHandle, sql, NULL, 0, &errMsg);
      if (ret != SQLITE_OK)
        {
          wxMessageBox(wxT("load shapefile error:") +
                       wxString::FromUTF8(errMsg), wxT("spatialite-gui"),
                       wxOK | wxICON_ERROR, this);
          sqlite3_free(errMsg);
          sqlError = true;
          goto clean_up;
        }
  } else
    {
      // no Metadata
      if (shp->Shape == 3 || shp->Shape == 13 || shp->Shape == 23
          || shp->Shape == 5 || shp->Shape == 15 || shp->Shape == 25)
        {
          // fixing anyway the Geometry type for LINESTRING/MULTILINESTRING or POLYGON/MULTIPOLYGON
          gaiaShpAnalyze(shp);
        }
    }
// preparing the INSERT INTO parameterized statement
  sprintf(sql, "INSERT INTO \"%s\" (\"PK_UID\",", xtable);
  cnt = 0;
  dbf_field = shp->Dbf->First;
  while (dbf_field)
    {
      // columns corresponding to some DBF attribute 
      strcat(sql, "\"");
      strcat(sql, *(col_name + cnt));
      cnt++;
      strcat(sql, "\",");
      dbf_field = dbf_field->Next;
    }
  strcat(sql, xcolumn);         // the GEOMETRY column
  strcat(sql, ")\nVALUES (? ");
  dbf_field = shp->Dbf->First;
  while (dbf_field)
    {
      // column values
      strcat(sql, ", ?");
      dbf_field = dbf_field->Next;
    }
  strcat(sql, ", ?)");          // the GEOMETRY column
  ret = sqlite3_prepare_v2(SqliteHandle, sql, strlen(sql), &stmt, NULL);
  if (ret != SQLITE_OK)
    {
      wxString err = wxString::FromUTF8(sqlite3_errmsg(SqliteHandle));
      wxMessageBox(wxT("load shapefile error: ") + err, wxT("spatialite-gui"),
                   wxOK | wxICON_ERROR, this);
      sqlError = true;
      goto clean_up;
    }
  current_row = 0;
  while (1)
    {
      //
      // inserting rows from shapefile 
      //
      ret = gaiaReadShpEntity(shp, current_row, srid);
      if (!ret)
        {
          if (!(shp->LastError))  // normal SHP EOF
            break;
          wxMessageBox(wxT("load shapefile error:") +
                       wxString::FromUTF8(shp->LastError),
                       wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
          sqlError = true;
          goto clean_up;
        }
      current_row++;
      // binding query params
      sqlite3_reset(stmt);
      sqlite3_clear_bindings(stmt);
      sqlite3_bind_int(stmt, 1, current_row);
      cnt = 0;
      dbf_field = shp->Dbf->First;
      while (dbf_field)
        {
          // column values
          if (!(dbf_field->Value))
            sqlite3_bind_null(stmt, cnt + 2);
          else
            {
              switch (dbf_field->Value->Type)
                {
                  case GAIA_INT_VALUE:
                    sqlite3_bind_int64(stmt, cnt + 2,
                                       dbf_field->Value->IntValue);
                    break;
                  case GAIA_DOUBLE_VALUE:
                    sqlite3_bind_double(stmt, cnt + 2,
                                        dbf_field->Value->DblValue);
                    break;
                  case GAIA_TEXT_VALUE:
                    sqlite3_bind_text(stmt, cnt + 2,
                                      dbf_field->Value->TxtValue,
                                      strlen(dbf_field->Value->
                                             TxtValue), SQLITE_STATIC);
                    break;
                  default:
                    sqlite3_bind_null(stmt, cnt + 2);;
                    break;
                };
            }
          cnt++;
          dbf_field = dbf_field->Next;
        }
      if (shp->Dbf->Geometry)
        {
          gaiaToSpatiaLiteBlobWkb(shp->Dbf->Geometry, &blob, &blob_size);
          sqlite3_bind_blob(stmt, cnt + 2, blob, blob_size, free);
      } else
        {
          /* handling a NULL-Geometry */
          sqlite3_bind_null(stmt, cnt + 2);
        }
      ret = sqlite3_step(stmt);
      if (ret == SQLITE_DONE || ret == SQLITE_ROW)
        ;
      else
        {
          wxString err = wxString::FromUTF8(sqlite3_errmsg(SqliteHandle));
          wxMessageBox(wxT("load shapefile error:") + err,
                       wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
          sqlite3_finalize(stmt);
          sqlError = true;
          goto clean_up;
        }
      rows++;
    }
  sqlite3_finalize(stmt);
clean_up:
  gaiaFreeShapefile(shp);
  if (col_name)
    {
      // releasing memory allocation for column names 
      for (cnt = 0; cnt < col_cnt; cnt++)
        free(*(col_name + cnt));
      free(col_name);
    }
  if (sqlError == true)
    {
      // some error occurred - ROLLBACK 
      ret = sqlite3_exec(SqliteHandle, "ROLLBACK", NULL, 0, &errMsg);
      if (ret != SQLITE_OK)
        {
          wxMessageBox(wxT("load shapefile error:") +
                       wxString::FromUTF8(errMsg), wxT("spatialite-gui"),
                       wxOK | wxICON_ERROR, this);
          sqlite3_free(errMsg);
        }
      ::wxEndBusyCursor();
      msg =
        wxT("Shapefile not loaded\n\n\na ROLLBACK was automatically performed");
      wxMessageBox(msg, wxT("spatialite-gui"), wxOK | wxICON_WARNING, this);
  } else
    {
      // ok - confirming pending transaction - COMMIT 
      ret = sqlite3_exec(SqliteHandle, "COMMIT", NULL, 0, &errMsg);
      if (ret != SQLITE_OK)
        {
          wxMessageBox(wxT("load shapefile error:") +
                       wxString::FromUTF8(errMsg), wxT("spatialite-gui"),
                       wxOK | wxICON_ERROR, this);
          sqlite3_free(errMsg);
          return;
        }
      ::wxEndBusyCursor();
      sprintf(dummyName, "Shapefile loaded\n\n%d inserted rows", rows);
      msg = wxString::FromUTF8(dummyName);
      wxMessageBox(msg, wxT("spatialite-gui"), wxOK | wxICON_INFORMATION, this);
      InitTableTree();
    }
}

gaiaDbfFieldPtr MyFrame::GetDbfField(gaiaDbfListPtr list, char *name)




{
//
// find a DBF attribute by name 
//
  gaiaDbfFieldPtr fld = list->First;
  while (fld)
    {
      if (strcasecmp(fld->Name, name) == 0)
        return fld;
      fld = fld->Next;
    }
  return NULL;
}

void MyFrame::DumpShapefile(wxString & path, wxString & table,
                            wxString & column, wxString & charset)
{
//
// dumping a  geometry table as Shapefile
//
  char **results;
  int rows;
  int columns;
  int i;
  char *errMsg = NULL;
  char *gtype;
  wxString geometryType;
  int shape = -1;
  char xtable[1024];
  char xcolumn[1024];
  char xpath[1024];
  char xsql[4096];
  sqlite3_stmt *stmt;
  int row1 = 0;
  int n_cols = 0;
  int offset = 0;
  int type;
  int multiple_entities = 0;
  const unsigned char *char_value;
  const void *blob_value;
  gaiaShapefilePtr shp = NULL;
  gaiaDbfListPtr dbf_export_list = NULL;
  gaiaDbfListPtr dbf_list = NULL;
  gaiaDbfListPtr dbf_write;
  gaiaDbfFieldPtr dbf_field;
  gaiaGeomCollPtr geom;
  int *max_length = NULL;
  int *sql_type = NULL;
  char dummy[1024];
  int len;
  wxString msg;
  wxString sql =
    wxT("SELECT type FROM geometry_columns WHERE f_table_name = '");
  sql += table;
  sql += wxT("' AND f_geometry_column = '");
  sql += column;
  sql += wxT("'");
  int ret = sqlite3_get_table(SqliteHandle, sql.ToUTF8(), &results,
                              &rows, &columns, &errMsg);
  if (ret != SQLITE_OK)
    {
      wxMessageBox(wxT("dump shapefile error:") + wxString::FromUTF8(errMsg),
                   wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
      sqlite3_free(errMsg);
      return;
    }
  if (rows < 1)
    ;
  else
    {
      for (i = 1; i <= rows; i++)
        {
          gtype = results[(i * columns) + 0];
          geometryType = wxString::FromUTF8(gtype);
        }
    }
  sqlite3_free_table(results);
  if (geometryType == wxT("POINT"))
    shape = GAIA_POINT;
  if (geometryType == wxT("MULTIPOINT"))
    shape = GAIA_MULTIPOINT;
  if (geometryType == wxT("LINESTRING")
      || geometryType == wxT("MULTILINESTRING"))
    shape = GAIA_LINESTRING;
  if (geometryType == wxT("POLYGON") || geometryType == wxT("MULTIPOLYGON"))
    shape = GAIA_POLYGON;
  if (shape < 0)
    {
      wxMessageBox(wxT("Unable to detect GeometryType for '") +
                   table + wxT(".") + column + wxT("'"), wxT("spatialite-gui"),
                   wxOK | wxICON_ERROR, this);
      return;
    }
//
// preparing SQL statement 
//
  strcpy(xtable, table.ToUTF8());
  strcpy(xcolumn, column.ToUTF8());
  sprintf(xsql, "SELECT * FROM \"%s\" WHERE GeometryType(\"%s\") = ", xtable,
          xcolumn);
  if (shape == GAIA_LINESTRING)
    {
      strcat(xsql, "'LINESTRING' OR GeometryType(\"");
      strcat(xsql, xcolumn);
      strcat(xsql, "\") = 'MULTILINESTRING'");
  } else if (shape == GAIA_POLYGON)
    {
      strcat(xsql, "'POLYGON' OR GeometryType(\"");
      strcat(xsql, xcolumn);
      strcat(xsql, "\") = 'MULTIPOLYGON'");
  } else if (shape == GAIA_MULTIPOINT)
    {
      strcat(xsql, "'POINT' OR GeometryType(\"");
      strcat(xsql, xcolumn);
      strcat(xsql, "\") = 'MULTIPOINT'");
  } else
    strcat(xsql, "'POINT'");
// fetching anyway NULL Geometries 
  strcat(xsql, " OR \"");
  strcat(xsql, xcolumn);
  strcat(xsql, "\" IS NULL");
//
// compiling SQL prepared statement 
//
  ret = sqlite3_prepare_v2(SqliteHandle, xsql, strlen(xsql), &stmt, NULL);
  if (ret != SQLITE_OK)
    goto sql_error;
  rows = 0;
  while (1)
    {
      //
      // Pass I - scrolling the result set to compute real DBF attributes' sizes and types 
      //
      ret = sqlite3_step(stmt);
      if (ret == SQLITE_DONE)
        break;                  // end of result set
      if (ret == SQLITE_ROW)
        {
          // processing a result set row 
          row1++;
          if (n_cols == 0)
            {
              // this one is the first row, so we are going to prepare the DBF Fields list 
              n_cols = sqlite3_column_count(stmt);
              dbf_export_list = gaiaAllocDbfList();
              max_length = (int *) malloc(sizeof(int) * n_cols);
              sql_type = (int *) malloc(sizeof(int) * n_cols);
              for (i = 0; i < n_cols; i++)
                {
                  // initializes the DBF export fields
                  strcpy(dummy, sqlite3_column_name(stmt, i));
                  gaiaAddDbfField(dbf_export_list, dummy, '\0', 0, 0, 0);
                  max_length[i] = 0;
                  sql_type[i] = SQLITE_NULL;
                }
            }
          for (i = 0; i < n_cols; i++)
            {
              // update the DBF export fields analyzing fetched data
              type = sqlite3_column_type(stmt, i);
              if (type == SQLITE_BLOB && strcasecmp((char *) xcolumn,
                                                    (char *)
                                                    sqlite3_column_name(stmt,
                                                                        i)) == 0
                  && shape == GAIA_POINT)
                {
                  // 
                  // we need to check if there is any MULTIPOINT,
                  // because shapefile handles simple-points shapes and multi-points shapes
                  // in a complete differet way
                  //
                  blob_value = sqlite3_column_blob(stmt, i);
                  len = sqlite3_column_bytes(stmt, i);
                  geom =
                    gaiaFromSpatiaLiteBlobWkb((unsigned char *) blob_value,
                                              len);
                  if (geom)
                    {
                      if (geom->FirstPoint != geom->LastPoint)
                        multiple_entities = 1;
                      gaiaFreeGeomColl(geom);
                    }
                }
              if (type == SQLITE_NULL || type == SQLITE_BLOB)
                continue;
              if (type == SQLITE_TEXT)
                {
                  char_value = sqlite3_column_text(stmt, i);
                  len = sqlite3_column_bytes(stmt, i);
                  sql_type[i] = SQLITE_TEXT;
                  if (len > max_length[i])
                    max_length[i] = len;
              } else if (type == SQLITE_FLOAT && sql_type[i] != SQLITE_TEXT)
                sql_type[i] = SQLITE_FLOAT; // promoting a numeric column to be DOUBLE
              else if (type == SQLITE_INTEGER
                       && (sql_type[i] == SQLITE_NULL
                           || sql_type[i] == SQLITE_INTEGER))
                sql_type[i] = SQLITE_INTEGER; // promoting a null column to be INTEGER
            }
      } else
        goto sql_error;
    }
  if (!row1)
    goto empty_result_set;
  i = 0;
  offset = 0;
  dbf_list = gaiaAllocDbfList();
  dbf_field = dbf_export_list->First;
  while (dbf_field)
    {
      // preparing the final DBF attribute list 
      if (sql_type[i] == SQLITE_NULL)
        {
          i++;
          dbf_field = dbf_field->Next;
          continue;
        }
      if (sql_type[i] == SQLITE_TEXT)
        {
          gaiaAddDbfField(dbf_list, dbf_field->Name, 'C', offset, max_length[i],
                          0);
          offset += max_length[i];
        }
      if (sql_type[i] == SQLITE_FLOAT)
        {
          gaiaAddDbfField(dbf_list, dbf_field->Name, 'N', offset, 24, 6);
          offset += 24;
        }
      if (sql_type[i] == SQLITE_INTEGER)
        {
          gaiaAddDbfField(dbf_list, dbf_field->Name, 'N', offset, 18, 0);
          offset += 18;
        }
      i++;
      dbf_field = dbf_field->Next;
    }
  free(max_length);
  free(sql_type);
  gaiaFreeDbfList(dbf_export_list);
// resetting SQLite query 
  ret = sqlite3_reset(stmt);
  if (ret != SQLITE_OK)
    goto sql_error;
// trying to open shapefile files 
  shp = gaiaAllocShapefile();
  strcpy(xpath, path.ToUTF8());
  gaiaOpenShpWrite(shp, xpath, shape, dbf_list, "UTF-8", charset.ToUTF8());
  if (!(shp->Valid))
    goto no_file;
  while (1)
    {
      // Pass II - scrolling the result set to dump data into shapefile 
      ret = sqlite3_step(stmt);
      if (ret == SQLITE_DONE)
        break;                  // end of result set
      if (ret == SQLITE_ROW)
        {
          rows++;
          geom = NULL;
          dbf_write = gaiaCloneDbfEntity(dbf_list);
          for (i = 0; i < n_cols; i++)
            {
              if (strcasecmp
                  ((char *) xcolumn,
                   (char *) sqlite3_column_name(stmt, i)) == 0)
                {
                  // this one is the internal BLOB encoded GEOMETRY to be exported 
                  if (sqlite3_column_type(stmt, i) != SQLITE_BLOB)
                    {
                      // this one is a NULL Geometry
                      dbf_write->Geometry = NULL;
                  } else
                    {
                      blob_value = sqlite3_column_blob(stmt, i);
                      len = sqlite3_column_bytes(stmt, i);
                      dbf_write->Geometry =
                        gaiaFromSpatiaLiteBlobWkb((unsigned char *) blob_value,
                                                  len);
                    }
                }
              strcpy(dummy, sqlite3_column_name(stmt, i));
              dbf_field = GetDbfField(dbf_write, dummy);
              if (!dbf_field)
                continue;
              if (sqlite3_column_type(stmt, i) == SQLITE_NULL)
                {
                  // handling NULL values
                  gaiaSetNullValue(dbf_field);
              } else
                {
                  switch (dbf_field->Type)
                    {
                      case 'N':
                        if (sqlite3_column_type(stmt, i) == SQLITE_INTEGER)
                          gaiaSetIntValue(dbf_field,
                                          sqlite3_column_int64(stmt, i));
                        else if (sqlite3_column_type(stmt, i) == SQLITE_FLOAT)
                          gaiaSetDoubleValue(dbf_field,
                                             sqlite3_column_double(stmt, i));
                        else
                          gaiaSetNullValue(dbf_field);
                        break;
                      case 'C':
                        if (sqlite3_column_type(stmt, i) == SQLITE_TEXT)
                          {
                            strcpy(dummy,
                                   (char *) sqlite3_column_text(stmt, i));
                            gaiaSetStrValue(dbf_field, dummy);
                        } else
                          gaiaSetNullValue(dbf_field);
                        break;
                    };
                }
            }
          if (!gaiaWriteShpEntity(shp, dbf_write))
            {
              wxMessageBox(wxT("Shapefile write error"), wxT("spatialite-gui"),
                           wxOK | wxICON_INFORMATION, this);
            }
          gaiaFreeDbfList(dbf_write);
      } else
        goto sql_error;
    }
  sqlite3_finalize(stmt);
  gaiaFlushShpHeaders(shp);
  gaiaFreeShapefile(shp);
  sprintf(dummy, "Exported %d rows into Shapefile", rows);
  msg = wxString::FromUTF8(dummy);
  wxMessageBox(msg, wxT("spatialite-gui"), wxOK | wxICON_INFORMATION, this);
  return;
sql_error:
//
// some SQL error occurred
//
  sqlite3_finalize(stmt);
  if (dbf_export_list);
  gaiaFreeDbfList(dbf_export_list);
  if (dbf_list);
  gaiaFreeDbfList(dbf_list);
  if (shp)
    gaiaFreeShapefile(shp);
  wxMessageBox(wxT("dump shapefile error:") +
               wxString::FromUTF8(sqlite3_errmsg(SqliteHandle)),
               wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
  return;
no_file:
//
// shapefile can't be created/opened
//
  if (dbf_export_list);
  gaiaFreeDbfList(dbf_export_list);
  if (dbf_list);
  gaiaFreeDbfList(dbf_list);
  if (shp)
    gaiaFreeShapefile(shp);
  wxMessageBox(wxT("ERROR: unable to open '") + path + wxT("' for writing"),
               wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
  return;
empty_result_set:
//
// the result set is empty - nothing to do 
//
  sqlite3_finalize(stmt);
  if (dbf_export_list);
  gaiaFreeDbfList(dbf_export_list);
  if (dbf_list);
  gaiaFreeDbfList(dbf_list);
  if (shp)
    gaiaFreeShapefile(shp);
  wxMessageBox(wxT
               ("The SQL SELECT returned an empty result set\n... there is nothing to export ..."),
               wxT("spatialite-gui"), wxOK | wxICON_WARNING, this);
}

void MyFrame::DumpTxtTab(wxString & path, wxString & table, wxString & charset)
{
//
// dumping a  table as Txt/Tab
//
  wxString sql;
  sqlite3_stmt *stmt;
  int ret;
  int rows = 0;
  int i;
  int n_cols;
  char xpath[1024];
  char dummy[65536];
  char outCs[128];
  char *pDummy;
  wxString msg;
  strcpy(outCs, charset.ToUTF8());
  strcpy(xpath, path.ToUTF8());
  FILE *out = fopen(xpath, "w");
  if (!out)
    goto no_file;
//
// preparing SQL statement 
//
  sql = wxT("SELECT * FROM \"");
  sql += table;
  sql += wxT("\"");
//
// compiling SQL prepared statement 
//
  ret = sqlite3_prepare_v2(SqliteHandle, sql.ToUTF8(), sql.Len(), &stmt, NULL);
  if (ret != SQLITE_OK)
    goto sql_error;
  rows = 0;
  while (1)
    {
      ret = sqlite3_step(stmt);
      if (ret == SQLITE_DONE)
        break;                  // end of result set
      if (ret == SQLITE_ROW)
        {
          n_cols = sqlite3_column_count(stmt);
          if (rows == 0)
            {
              // outputting the column titles
              for (i = 0; i < n_cols; i++)
                {
                  if (i == 0)
                    fprintf(out, "%s", sqlite3_column_name(stmt, i));
                  else
                    fprintf(out, "\t%s", sqlite3_column_name(stmt, i));
                }
              fprintf(out, "\n");
            }
          rows++;
          for (i = 0; i < n_cols; i++)
            {
              if (i > 0)
                fprintf(out, "\t");
              if (sqlite3_column_type(stmt, i) == SQLITE_INTEGER)
                fprintf(out, "%d", sqlite3_column_int(stmt, i));
              else if (sqlite3_column_type(stmt, i) == SQLITE_FLOAT)
                fprintf(out, "%1.6lf", sqlite3_column_double(stmt, i));
              else if (sqlite3_column_type(stmt, i) == SQLITE_TEXT)
                {
                  strcpy(dummy, (char *) sqlite3_column_text(stmt, i));
                  CleanTxtTab(dummy);
                  pDummy = dummy;
                  if (!gaiaConvertCharset(&pDummy, "UTF-8", outCs))
                    goto encoding_error;
                  fprintf(out, "%s", dummy);
                }
            }
          fprintf(out, "\n");
      } else
        goto sql_error;
    }
  sqlite3_finalize(stmt);
  fclose(out);
  sprintf(dummy, "Exported %d rows into Txt/Tab file", rows);
  msg = wxString::FromUTF8(dummy);
  wxMessageBox(msg, wxT("spatialite-gui"), wxOK | wxICON_INFORMATION, this);
  return;
sql_error:
//
// some SQL error occurred
//
  sqlite3_finalize(stmt);
  wxMessageBox(wxT("dump Txt/Tab error:") +
               wxString::FromUTF8(sqlite3_errmsg(SqliteHandle)),
               wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
  if (out)
    fclose(out);
  return;
encoding_error:
//
// some CHARSET converion occurred
//
  sqlite3_finalize(stmt);
  wxMessageBox(wxT("dump Txt/Tab: charset conversion reported an error"),
               wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
  if (out)
    fclose(out);
  return;
no_file:









//
// output file can't be created/opened
//
  wxMessageBox(wxT("ERROR: unable to open '") + path + wxT("' for writing"),

               wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
  return;
}


void MyFrame::DumpCsv(wxString & path, wxString & table, wxString & charset)
{
//
// dumping a  table as CSV
//
  wxString sql;
  sqlite3_stmt *stmt;
  int ret;
  int rows = 0;
  int i;
  int n_cols;
  char xpath[1024];
  char dummy[65536];
  char outCs[128];
  char *pDummy;
  wxString msg;
  strcpy(outCs, charset.ToUTF8());
  strcpy(xpath, path.ToUTF8());
  FILE *out = fopen(xpath, "w");
  if (!out)
    goto no_file;
//
// preparing SQL statement 
//
  sql = wxT("SELECT * FROM \"");
  sql += table;
  sql += wxT("\"");
//
// compiling SQL prepared statement 
//



  ret = sqlite3_prepare_v2(SqliteHandle, sql.ToUTF8(), sql.Len(), &stmt, NULL);
  if (ret != SQLITE_OK)
    goto sql_error;
  rows = 0;
  while (1)
    {
      ret = sqlite3_step(stmt);
      if (ret == SQLITE_DONE)
        break;                  // end of result set
      if (ret == SQLITE_ROW)
        {
          n_cols = sqlite3_column_count(stmt);
          if (rows == 0)
            {
              // outputting the column titles
              for (i = 0; i < n_cols; i++)
                {
                  if (i == 0)
                    {
                      strcpy(dummy, sqlite3_column_name(stmt, i));
                      CleanCsv(dummy);
                      fprintf(out, "%s", dummy);

                  } else
                    {
                      strcpy(dummy, sqlite3_column_name(stmt, i));
                      CleanCsv(dummy);
                      fprintf(out, ",%s", dummy);
                    }
                }
              fprintf(out, "\n");
            }
          rows++;
          for (i = 0; i < n_cols; i++)
            {
              if (i > 0)
                fprintf(out, ",");
              if (sqlite3_column_type(stmt, i) == SQLITE_INTEGER)
                fprintf(out, "%d", sqlite3_column_int(stmt, i));
              else if (sqlite3_column_type(stmt, i) == SQLITE_FLOAT)

                fprintf(out, "%1.6lf", sqlite3_column_double(stmt, i));
              else if (sqlite3_column_type(stmt, i) == SQLITE_TEXT)
                {

                  strcpy(dummy, (char *) sqlite3_column_text(stmt, i));
                  CleanCsv(dummy);
                  pDummy = dummy;
                  if (!gaiaConvertCharset
                      (&pDummy, (const char *) "UTF-8", outCs))
                    goto encoding_error;
                  fprintf(out, "%s", dummy);
                }
            }
          fprintf(out, "\n");

      } else
        goto sql_error;
    }
  sqlite3_finalize(stmt);
  fclose(out);
  sprintf(dummy, "Exported %d rows into CSV file", rows);
  msg = wxString::FromUTF8(dummy);
  wxMessageBox(msg, wxT("spatialite-gui"), wxOK | wxICON_INFORMATION, this);
  return;
sql_error:
//
// some SQL error occurred
//
  sqlite3_finalize(stmt);
  wxMessageBox(wxT("dump CSV error:") +

               wxString::FromUTF8(sqlite3_errmsg(SqliteHandle)),
               wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
  if (out)
    fclose(out);
  return;
encoding_error:
//
// some CHARSET converion occurred
//
  sqlite3_finalize(stmt);
  wxMessageBox(wxT("dump CSV: charset conversion reported an error"),
               wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
  if (out)
    fclose(out);
  return;
no_file:
//
// output file can't be created/opened
//
  wxMessageBox(wxT("ERROR: unable to open '") + path + wxT("' for writing"),

               wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
  return;
}


void MyFrame::DumpHtml(wxString & path, wxString & table, wxString & charset)
{
//
// dumping a  table as HTML
//
  wxString sql;
  sqlite3_stmt *stmt;
  int ret;
  int rows = 0;
  int i;
  int n_cols;
  char xpath[1024];
  char xtable[1024];
  char dummy[65536];
  char outCs[128];
  char *pDummy;
  wxString msg;
  strcpy(outCs, charset.ToUTF8());
  strcpy(xpath, path.ToUTF8());
  strcpy(xtable, table.ToUTF8());
  FILE *out = fopen(xpath, "w");
  if (!out)
    goto no_file;
  fprintf(out,
          "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n");
  fprintf(out, "<html>\n\t<head>\n");
  fprintf(out,
          "\t\t<meta http-equiv=\"content-type\" content=\"text/html; charset=%s\">\n",
          outCs);
  fprintf(out, "\t\t<title>\nTable '%s': from SQLite/SpatiaLite DB '%s'\n",
          xtable, xpath);
  fprintf(out, "\t\t</title>\n");
  fprintf(out, "\t\t<style type=\"text/css\">\n");
  fprintf(out, "table { border: 1px; }\n");
  fprintf(out, "tr.t0 th { background-color: #c9c9df; }\n");
  fprintf(out, "tr.d0 td { background-color: #e0efe0; }\n");
  fprintf(out, "tr.d1 td { background-color: #d0d0df; }\n");
  fprintf(out, "\t\t</style>\n\t</head>\n\t<body>\n\t\t<table>\n");
//
// preparing SQL statement 
//
  sql = wxT("SELECT * FROM \"");
  sql += table;
  sql += wxT("\"");
//
// compiling SQL prepared statement 
//



  ret = sqlite3_prepare_v2(SqliteHandle, sql.ToUTF8(), sql.Len(), &stmt, NULL);
  if (ret != SQLITE_OK)
    goto sql_error;
  rows = 0;
  while (1)
    {
      ret = sqlite3_step(stmt);
      if (ret == SQLITE_DONE)
        break;                  // end of result set
      if (ret == SQLITE_ROW)
        {
          n_cols = sqlite3_column_count(stmt);
          if (rows == 0)
            {
              // outputting the column titles
              fprintf(out, "\t\t\t<tr class=\"t0\">\n");
              for (i = 0; i < n_cols; i++)
                {
                  strcpy(dummy, sqlite3_column_name(stmt, i));
                  CleanHtml(dummy);
                  fprintf(out, "\t\t\t\t<th>%s</th>\n", dummy);
                }
              fprintf(out, "\t\t\t</tr>\n");
            }
          rows++;
          fprintf(out, "\t\t\t<tr class=\"%s\">\n", (rows % 2) ? "d0" : "d1");

          for (i = 0; i < n_cols; i++)
            {
              if (sqlite3_column_type(stmt, i) == SQLITE_INTEGER)

                fprintf(out, "\t\t\t\t<td align=\"right\">%d</td>\n",
                        sqlite3_column_int(stmt, i));
              else if (sqlite3_column_type(stmt, i) == SQLITE_FLOAT)

                fprintf(out, "\t\t\t\t<td align=\"right\">%1.6lf</td>\n",
                        sqlite3_column_double(stmt, i));
              else if (sqlite3_column_type(stmt, i) == SQLITE_TEXT)
                {

                  strcpy(dummy, (char *) sqlite3_column_text(stmt, i));
                  CleanHtml(dummy);
                  pDummy = dummy;
                  if (!gaiaConvertCharset
                      (&pDummy, (const char *) "UTF-8", outCs))
                    goto encoding_error;
                  fprintf(out, "\t\t\t\t<td>%s</td>\n", dummy);
                }
            }
          fprintf(out, "\t\t\t</tr>\n");

      } else
        goto sql_error;
    }
  sqlite3_finalize(stmt);
  fprintf(out, "\t\t</table>\n\t</body>\n</html>\n");
  fclose(out);
  sprintf(dummy, "Exported %d rows into HTML file", rows);
  msg = wxString::FromUTF8(dummy);
  wxMessageBox(msg, wxT("spatialite-gui"), wxOK | wxICON_INFORMATION, this);
  return;
sql_error:
//
// some SQL error occurred
//
  sqlite3_finalize(stmt);
  wxMessageBox(wxT("dump HTML error:") +

               wxString::FromUTF8(sqlite3_errmsg(SqliteHandle)),
               wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
  if (out)
    fclose(out);
  return;
encoding_error:
//
// some CHARSET convertion occurred
//
  sqlite3_finalize(stmt);
  wxMessageBox(wxT("dump HTML: charset conversion reported an error"),
               wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
  if (out)
    fclose(out);
  return;
no_file:
//
// output file can't be created/opened
//
  wxMessageBox(wxT("ERROR: unable to open '") + path + wxT("' for writing"),

               wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
  return;
}

Changes to TableTree.cpp.

1
2
3
4
5
6
7
8
9
10
11
12
..
39
40
41
42
43
44
45


46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755


756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
/*
/ TableTree.cpp
/ tree control to show tables, columns, indices and triggers
/
/ version 1.1, 2008 September 13
/
/ Author: Sandro Furieri a-furieri@lqt.it
/
/ Copyright (C) 2008  Alessandro Furieri
/
/    This program is free software: you can redistribute it and/or modify
/    it under the terms of the GNU General Public License as published by
................................................................................
#include "icons/pkey.xpm"
#include "icons/column.xpm"
#include "icons/index.xpm"
#include "icons/trigger.xpm"
#include "icons/geometry.xpm"
#include "icons/spatialidx.xpm"
#include "icons/mbrcache.xpm"



MyTableTree::MyTableTree (MyFrame * parent, wxWindowID id):wxTreeCtrl (parent,
	    id)
{
//
// constructor: TREE control to show DB objects
//
    MainFrame = parent;
    Root = AddRoot (wxT ("no current DB"));
// setting up icons 
    Images = new wxImageList (16, 16, true);
    wxIcon icons[12];
    icons[0] = wxIcon (db_xpm);
    icons[1] = wxIcon (table_xpm);
    icons[2] = wxIcon (pkey_xpm);
    icons[3] = wxIcon (column_xpm);
    icons[4] = wxIcon (index_xpm);
    icons[5] = wxIcon (trigger_xpm);
    icons[6] = wxIcon (geometry_xpm);
    icons[7] = wxIcon (spatialidx_xpm);
    icons[8] = wxIcon (vtable_xpm);
    icons[9] = wxIcon (view_xpm);
    icons[10] = wxIcon (geotable_xpm);
    icons[11] = wxIcon (mbrcache_xpm);
    Images->Add (icons[0]);
    Images->Add (icons[1]);
    Images->Add (icons[2]);
    Images->Add (icons[3]);
    Images->Add (icons[4]);
    Images->Add (icons[5]);
    Images->Add (icons[6]);
    Images->Add (icons[7]);
    Images->Add (icons[8]);
    Images->Add (icons[9]);
    Images->Add (icons[10]);
    Images->Add (icons[11]);
    SetImageList (Images);
    SetItemImage (Root, 0);
// setting up event handlers
    Connect (wxID_ANY, wxEVT_COMMAND_TREE_SEL_CHANGED,
	     (wxObjectEventFunction) & MyTableTree::OnSelChanged);
    Connect (wxID_ANY, wxEVT_COMMAND_TREE_ITEM_RIGHT_CLICK,
	     (wxObjectEventFunction) & MyTableTree::OnRightClick);
    Connect (Tree_NewTable, wxEVT_COMMAND_MENU_SELECTED,
	     (wxObjectEventFunction) & MyTableTree::OnCmdNewTable);
    Connect (Tree_NewView, wxEVT_COMMAND_MENU_SELECTED,
	     (wxObjectEventFunction) & MyTableTree::OnCmdNewView);
    Connect (Tree_NewIndex, wxEVT_COMMAND_MENU_SELECTED,
	     (wxObjectEventFunction) & MyTableTree::OnCmdNewIndex);
    Connect (Tree_NewTrigger, wxEVT_COMMAND_MENU_SELECTED,
	     (wxObjectEventFunction) & MyTableTree::OnCmdNewTrigger);
    Connect (Tree_NewColumn, wxEVT_COMMAND_MENU_SELECTED,
	     (wxObjectEventFunction) & MyTableTree::OnCmdNewColumn);
    Connect (Tree_Show, wxEVT_COMMAND_MENU_SELECTED,
	     (wxObjectEventFunction) & MyTableTree::OnCmdShow);
    Connect (Tree_Drop, wxEVT_COMMAND_MENU_SELECTED,
	     (wxObjectEventFunction) & MyTableTree::OnCmdDrop);
    Connect (Tree_Rename, wxEVT_COMMAND_MENU_SELECTED,
	     (wxObjectEventFunction) & MyTableTree::OnCmdRename);
    Connect (Tree_Select, wxEVT_COMMAND_MENU_SELECTED,
	     (wxObjectEventFunction) & MyTableTree::OnCmdSelect);
    Connect (Tree_Refresh, wxEVT_COMMAND_MENU_SELECTED,
	     (wxObjectEventFunction) & MyTableTree::OnCmdRefresh);
    Connect (Tree_Recover, wxEVT_COMMAND_MENU_SELECTED,
	     (wxObjectEventFunction) & MyTableTree::OnCmdRecover);
    Connect (Tree_ShowSql, wxEVT_COMMAND_MENU_SELECTED,
	     (wxObjectEventFunction) & MyTableTree::OnCmdShowSql);
    Connect (Tree_SpatialIndex, wxEVT_COMMAND_MENU_SELECTED,
	     (wxObjectEventFunction) & MyTableTree::OnCmdSpatialIndex);
    Connect (Tree_MbrCache, wxEVT_COMMAND_MENU_SELECTED,
	     (wxObjectEventFunction) & MyTableTree::OnCmdMbrCache);
    Connect (Tree_CheckGeometry, wxEVT_COMMAND_MENU_SELECTED,
	     (wxObjectEventFunction) & MyTableTree::OnCmdCheckGeometry);
    Connect (Tree_SetSrid, wxEVT_COMMAND_MENU_SELECTED,
	     (wxObjectEventFunction) & MyTableTree::OnCmdSetSrid);
    Connect (Tree_DumpShp, wxEVT_COMMAND_MENU_SELECTED,
	     (wxObjectEventFunction) & MyTableTree::OnCmdDumpShp);
    Connect (Tree_DumpTxtTab, wxEVT_COMMAND_MENU_SELECTED,
	     (wxObjectEventFunction) & MyTableTree::OnCmdDumpTxtTab);
    Connect (Tree_DumpCsv, wxEVT_COMMAND_MENU_SELECTED,
	     (wxObjectEventFunction) & MyTableTree::OnCmdDumpCsv);
    Connect (Tree_DumpHtml, wxEVT_COMMAND_MENU_SELECTED,
	     (wxObjectEventFunction) & MyTableTree::OnCmdDumpHtml);
    Connect (Tree_Edit, wxEVT_COMMAND_MENU_SELECTED,
	     (wxObjectEventFunction) & MyTableTree::OnCmdEdit);
}

void
MyTableTree::AddTable (wxString & tableName, bool virtualTable)
{
//
// appends a table to the TREE list
    MyTableInfo list;
    MyColumnInfo *col;
    MyIndexInfo *idx;
    MyTriggerInfo *trgr;
    wxTreeItemId item;
    wxTreeItemId item2;
    wxString columnInfo;
    wxString indexInfo;
    wxString triggerInfo;
    int icon = 1;
    if (virtualTable == true)
	icon = 8;
    item = AppendItem (Root, tableName, icon);
    if (virtualTable == true)
	SetItemData (item,
		     (wxTreeItemData *) (new MyObject (MY_VTABLE, tableName)));
    else
	SetItemData (item,
		     (wxTreeItemData *) (new MyObject (MY_TABLE, tableName)));
    MainFrame->GetTableColumns (tableName, &list);
    MainFrame->GetTableIndices (tableName, &list);
    MainFrame->GetTableTriggers (tableName, &list);
    col = list.GetFirstColumn ();
    while (col)
      {
	  int icon;
	  if (col->IsPrimaryKey () == true)
	      icon = 2;
	  else
	    {
		if (col->IsGeometry () == true)
		  {
		      if (virtualTable == false)
			  SetItemImage (item, 10);
		      if (col->IsGeometryIndex () == true)
			  icon = 7;
		      else if (col->IsMbrCache () == true)
			  icon = 11;
		      else
			  icon = 6;
		  }
		else
		    icon = 3;
	    }
	  columnInfo = col->GetName ();
	  item2 = AppendItem (item, columnInfo, icon);
	  if (col->IsGeometry () == true)
	    {
		if (col->IsGeometryIndex () == true)
		    SetItemData (item2,
				 (wxTreeItemData *) (new
						     MyObject
						     (MY_GEOMETRY_INDEX,
						      tableName,
						      col->GetName ())));
		else if (col->IsMbrCache () == true)
		    SetItemData (item2,
				 (wxTreeItemData *) (new
						     MyObject
						     (MY_GEOMETRY_CACHED,
						      tableName,
						      col->GetName ())));
		else
		    SetItemData (item2,
				 (wxTreeItemData *) (new
						     MyObject (MY_GEOMETRY,
							       tableName,
							       col->GetName
							       ())));
	    }
	  else
	      SetItemData (item2,
			   (wxTreeItemData *) (new
					       MyObject (MY_COLUMN, tableName,
							 col->GetName ())));
	  col = col->GetNext ();
      }
    idx = list.GetFirstIndex ();
    while (idx)
      {
	  indexInfo = idx->GetName ();
	  item2 = AppendItem (item, indexInfo, 4);
	  SetItemData (item2,
		       (wxTreeItemData *) (new
					   MyObject (MY_INDEX,
						     idx->GetName ())));
	  idx = idx->GetNext ();
      }
    trgr = list.GetFirstTrigger ();
    while (trgr)
      {
	  triggerInfo = trgr->GetName ();
	  item2 = AppendItem (item, triggerInfo, 5);
	  SetItemData (item2,
		       (wxTreeItemData *) (new
					   MyObject (MY_TRIGGER,
						     trgr->GetName ())));
	  trgr = trgr->GetNext ();
      }
}

void
MyTableTree::AddView (wxString & viewName)
{
//
// appends a view to the TREE list
    MyViewInfo list;
    MyColumnInfo *col;
    wxTreeItemId item;
    wxTreeItemId item2;
    wxString columnInfo;
    item = AppendItem (Root, viewName, 9);
    SetItemData (item, (wxTreeItemData *) (new MyObject (MY_VIEW, viewName)));
    MainFrame->GetViewColumns (viewName, &list);
    col = list.GetFirst ();
    while (col)
      {
	  columnInfo = col->GetName ();
	  item2 = AppendItem (item, columnInfo, 3);
	  SetItemData (item2,
		       (wxTreeItemData *) (new
					   MyObject (MY_COLUMN, viewName,
						     col->GetName ())));
	  col = col->GetNext ();
      }
}

void
MyTableTree::OnSelChanged (wxTreeEvent & event)
{
//
// selecting some node [mouse action]
//
    wxTreeItemId item = event.GetItem ();
    if (item == Root)
	return;
    MyObject *obj = (MyObject *) GetItemData (item);
    if (obj == NULL)
	return;
    CurrentItem = item;
}

void
MyTableTree::OnRightClick (wxTreeEvent & event)
{
//
// right click on some node [mouse action]
//
    wxMenu menu;
    wxMenuItem *menuItem;
    wxString title;
    bool table = false;
    bool canEdit = false;
    bool view = false;
    bool column = false;
    bool geometry = false;
    bool geometry_index = false;
    bool geometry_cached = false;
    bool index = false;
    bool trigger = false;
    bool metadata = MainFrame->CheckMetadata ();
    if (MainFrame->IsConnected () == false)
	return;
    wxTreeItemId item = event.GetItem ();
    SelectItem (item);
    wxPoint pt = event.GetPoint ();
    if (item == Root)
      {
	  CurrentItem = NULL;
	  menuItem = new wxMenuItem (&menu, Tree_Refresh, wxT ("&Refresh"));
	  menu.Append (menuItem);
	  menu.AppendSeparator ();
	  menuItem =
	      new wxMenuItem (&menu, Tree_NewTable, wxT ("Create New &Table"));
	  menu.Append (menuItem);
	  menuItem =
	      new wxMenuItem (&menu, Tree_NewView, wxT ("Create New &View"));
	  menu.Append (menuItem);
	  PopupMenu (&menu, pt);
	  return;
      }
    MyObject *obj = (MyObject *) GetItemData (item);
    if (obj == NULL)
      {
	  CurrentItem = NULL;
	  menuItem = new wxMenuItem (&menu, Tree_Refresh, wxT ("&Refresh"));
	  menu.Append (menuItem);
	  menu.AppendSeparator ();
	  menuItem =
	      new wxMenuItem (&menu, Tree_NewTable, wxT ("Create New &Table"));
	  menu.Append (menuItem);
	  menuItem =
	      new wxMenuItem (&menu, Tree_NewView, wxT ("Create New &View"));
	  menu.Append (menuItem);
	  PopupMenu (&menu, pt);
	  return;
      }
    switch (obj->GetType ())
      {
      case MY_VTABLE:
      case MY_TABLE:
	  table = true;
	  break;
      case MY_VIEW:
	  view = true;
	  break;
      case MY_COLUMN:
	  column = true;
	  break;
      case MY_GEOMETRY:
	  geometry = true;
	  break;
      case MY_GEOMETRY_INDEX:
	  geometry_index = true;
	  break;
      case MY_GEOMETRY_CACHED:
	  geometry_cached = true;
	  break;
      case MY_INDEX:
	  index = true;
	  break;
      case MY_TRIGGER:
	  trigger = true;
	  break;
      };
    if (obj->GetType () == MY_TABLE)
	canEdit = true;
    CurrentItem = item;
    menuItem = new wxMenuItem (&menu, Tree_Refresh, wxT ("&Refresh"));
    menu.Append (menuItem);
    if (table == true)
      {
	  wxString title = wxT ("Table: ") + obj->GetName ();
	  menu.SetTitle (title);
	  menu.AppendSeparator ();
	  menuItem =
	      new wxMenuItem (&menu, Tree_NewTable, wxT ("Create New &Table"));
	  menu.Append (menuItem);
	  menuItem =
	      new wxMenuItem (&menu, Tree_NewView, wxT ("Create New &View"));
	  menu.Append (menuItem);
	  menu.AppendSeparator ();
	  if (canEdit == true)
	    {
		menuItem =
		    new wxMenuItem (&menu, Tree_Edit, wxT ("&Edit table rows"));
		menu.Append (menuItem);
	    }
	  else
	    {
		menuItem =
		    new wxMenuItem (&menu, Tree_Select, wxT ("&Query table"));
		menu.Append (menuItem);
	    }
	  menuItem = new wxMenuItem (&menu, Tree_Show, wxT ("&Show columns"));
	  menu.Append (menuItem);
	  menuItem =
	      new wxMenuItem (&menu, Tree_ShowSql,
			      wxT ("&Show CREATE statement"));
	  menu.Append (menuItem);
	  menu.AppendSeparator ();
	  menuItem =
	      new wxMenuItem (&menu, Tree_NewColumn, wxT ("Add New &Column"));
	  menu.Append (menuItem);
	  menuItem = new wxMenuItem (&menu, Tree_Rename, wxT ("&Rename table"));
	  menu.Append (menuItem);
	  menuItem = new wxMenuItem (&menu, Tree_Drop, wxT ("&Drop table"));
	  menu.Append (menuItem);
	  menu.AppendSeparator ();
	  menuItem =
	      new wxMenuItem (&menu, Tree_NewIndex, wxT ("Create New &Index"));
	  menu.Append (menuItem);
	  menuItem =
	      new wxMenuItem (&menu, Tree_NewTrigger,
			      wxT ("Create New &Trigger"));
	  menu.Append (menuItem);
	  menu.AppendSeparator ();
	  menuItem =
	      new wxMenuItem (&menu, Tree_DumpTxtTab,
			      wxT ("Export as &Txt/Tab"));
	  menu.Append (menuItem);
	  menuItem =
	      new wxMenuItem (&menu, Tree_DumpCsv, wxT ("Export as &CSV"));
	  menu.Append (menuItem);
	  menuItem =
	      new wxMenuItem (&menu, Tree_DumpHtml, wxT ("Export as &HTML"));
	  menu.Append (menuItem);
      }
    if (view == true)
      {
	  wxString title = wxT ("View: ") + obj->GetName ();
	  menu.SetTitle (title);
	  menu.AppendSeparator ();
	  menuItem =
	      new wxMenuItem (&menu, Tree_NewTable, wxT ("Create New &Table"));
	  menu.Append (menuItem);
	  menuItem =
	      new wxMenuItem (&menu, Tree_NewView, wxT ("Create New &View"));
	  menu.Append (menuItem);
	  menu.AppendSeparator ();
	  menuItem = new wxMenuItem (&menu, Tree_Select, wxT ("&Query view"));
	  menu.Append (menuItem);
	  menuItem = new wxMenuItem (&menu, Tree_Show, wxT ("&Show columns"));
	  menu.Append (menuItem);
	  menuItem =
	      new wxMenuItem (&menu, Tree_ShowSql,
			      wxT ("&Show CREATE statement"));
	  menu.Append (menuItem);
	  menu.AppendSeparator ();
	  menuItem = new wxMenuItem (&menu, Tree_Drop, wxT ("&Drop view"));
	  menu.Append (menuItem);
	  menu.AppendSeparator ();
	  menuItem =
	      new wxMenuItem (&menu, Tree_DumpTxtTab,
			      wxT ("Export as &Txt/Tab"));
	  menu.Append (menuItem);
	  menuItem =
	      new wxMenuItem (&menu, Tree_DumpCsv, wxT ("Export as &CSV"));
	  menu.Append (menuItem);
	  menuItem =
	      new wxMenuItem (&menu, Tree_DumpHtml, wxT ("Export as &HTML"));
	  menu.Append (menuItem);
      }
    if (column == true)
      {
	  wxString title =
	      wxT ("Column: ") + obj->GetName () + wxT (".") +
	      obj->GetColumn ();
	  menu.SetTitle (title);
	  menuItem =
	      new wxMenuItem (&menu, Tree_CheckGeometry,
			      wxT ("&Check geometries"));
	  menu.Append (menuItem);
	  menuItem = new wxMenuItem (&menu, Tree_SetSrid, wxT ("&Set SRID"));
	  menu.Append (menuItem);
	  if (metadata == true)
	    {
		menu.AppendSeparator ();
		menuItem =
		    new wxMenuItem (&menu, Tree_Recover,
				    wxT ("&Recover geometry column"));
		menu.Append (menuItem);
	    }
      }
    if (geometry == true)
      {
	  wxString title =
	      wxT ("Column: ") + obj->GetName () + wxT (".") +
	      obj->GetColumn ();
	  menu.SetTitle (title);
	  menuItem =
	      new wxMenuItem (&menu, Tree_Show, wxT ("&Show Spatial Metadata"));
	  menu.Append (menuItem);
	  menuItem =
	      new wxMenuItem (&menu, Tree_CheckGeometry,
			      wxT ("&Check geometries"));
	  menu.Append (menuItem);
	  menu.AppendSeparator ();
	  menuItem =
	      new wxMenuItem (&menu, Tree_SpatialIndex,
			      wxT ("&Build Spatial Index"));
	  menu.Append (menuItem);
	  menuItem =
	      new wxMenuItem (&menu, Tree_MbrCache, wxT ("Build &MBR cache"));
	  menu.Append (menuItem);
	  menu.AppendSeparator ();
	  menuItem =
	      new wxMenuItem (&menu, Tree_DumpShp,
			      wxT ("Export as &Shapefile"));
	  menu.Append (menuItem);
      }
    if (geometry_index == true)
      {
	  wxString title =
	      wxT ("Column: ") + obj->GetName () + wxT (".") +
	      obj->GetColumn ();
	  menu.SetTitle (title);
	  menuItem =
	      new wxMenuItem (&menu, Tree_Show, wxT ("&Show Spatial Metadata"));
	  menu.Append (menuItem);
	  menuItem =
	      new wxMenuItem (&menu, Tree_CheckGeometry,
			      wxT ("&Check geometries"));
	  menu.Append (menuItem);
	  menu.AppendSeparator ();
	  menuItem =
	      new wxMenuItem (&menu, Tree_SpatialIndex,
			      wxT ("&Remove Spatial Index"));
	  menu.Append (menuItem);
	  menu.AppendSeparator ();
	  menuItem =
	      new wxMenuItem (&menu, Tree_DumpShp,
			      wxT ("Export as &Shapefile"));
	  menu.Append (menuItem);
      }
    if (geometry_cached == true)
      {
	  wxString title =
	      wxT ("Column: ") + obj->GetName () + wxT (".") +
	      obj->GetColumn ();
	  menu.SetTitle (title);
	  menuItem =
	      new wxMenuItem (&menu, Tree_Show, wxT ("&Show Spatial Metadata"));
	  menu.Append (menuItem);
	  menuItem =
	      new wxMenuItem (&menu, Tree_CheckGeometry,
			      wxT ("&Check geometries"));
	  menu.Append (menuItem);
	  menu.AppendSeparator ();
	  menuItem =
	      new wxMenuItem (&menu, Tree_MbrCache, wxT ("&Remove MBR cache"));
	  menu.Append (menuItem);
	  menu.AppendSeparator ();
	  menuItem =
	      new wxMenuItem (&menu, Tree_DumpShp,
			      wxT ("Export as &Shapefile"));
	  menu.Append (menuItem);
      }
    if (index == true)
      {
	  wxString title = wxT ("Index: ") + obj->GetName ();
	  menu.SetTitle (title);
	  menu.AppendSeparator ();
	  menuItem = new wxMenuItem (&menu, Tree_Show, wxT ("&Show index"));
	  menu.Append (menuItem);
	  menu.AppendSeparator ();
	  menuItem = new wxMenuItem (&menu, Tree_Drop, wxT ("&Drop index"));
	  menu.Append (menuItem);
      }
    if (trigger == true)
      {
	  wxString title = wxT ("Trigger: ") + obj->GetName ();
	  menu.SetTitle (title);
	  menu.AppendSeparator ();
	  menuItem = new wxMenuItem (&menu, Tree_Show, wxT ("&Show trigger"));
	  menu.Append (menuItem);
	  menu.AppendSeparator ();
	  menuItem = new wxMenuItem (&menu, Tree_Drop, wxT ("&Drop trigger"));
	  menu.Append (menuItem);
      }
    PopupMenu (&menu, pt);
}

void
MyTableTree::OnCmdNewTable (wxCommandEvent & event)
{
//
// menu event - new table creation required
//
    wxString sql;
    sql = wxT ("CREATE TABLE ...table-name... (\n");
    sql += wxT ("...column1,\n...column2,\n...columnN)");
    MainFrame->SetSql (sql, false);
}

void
MyTableTree::OnCmdNewView (wxCommandEvent & event)
{
//
// menu event - new view creation required
//
    wxString sql;
    sql = wxT ("CREATE VIEW ...view-name... AS\n");
    sql += wxT ("SELECT ...sql-select-statement...");
    MainFrame->SetSql (sql, false);
}

void
MyTableTree::OnCmdNewIndex (wxCommandEvent & event)
{
//
// menu event - new index creation required
//
    wxString sql;
    MyObject *obj = (MyObject *) GetItemData (CurrentItem);
    if (obj == NULL)
	return;
    if (obj->GetType () == MY_TABLE)
      {
	  sql = wxT ("CREATE [ UNIQUE ] INDEX ...index-name...\nON ");
	  sql += obj->GetName ();
	  sql += wxT ("\n(\n...column1, column2, columnN...\n)");
	  MainFrame->SetSql (sql, false);
      }
}

void
MyTableTree::OnCmdNewTrigger (wxCommandEvent & event)
{
//
// menu event - new trigger creation required
//
    wxString sql;
    MyObject *obj = (MyObject *) GetItemData (CurrentItem);
    if (obj == NULL)
	return;
    if (obj->GetType () == MY_TABLE)
      {
	  sql = wxT ("CREATE TRIGGER ...trigger-name...\n[ BEFORE | AFTER ]\n");
	  sql += wxT ("[ INSERT | UPDATE | DELETE ]\nON ");
	  sql += obj->GetName ();
	  sql += wxT ("\n...sql-statement...");
	  MainFrame->SetSql (sql, false);
      }
}

void
MyTableTree::OnCmdNewColumn (wxCommandEvent & event)
{
//
// menu event - new column creation required
//
    wxString sql;
    MyObject *obj = (MyObject *) GetItemData (CurrentItem);
    if (obj == NULL)
	return;
    if (obj->GetType () == MY_TABLE)
      {
	  sql = wxT ("ALTER TABLE ");
	  sql += obj->GetName ();
	  sql += wxT ("\nADD COLUMN ...column-name column-type...");
	  MainFrame->SetSql (sql, false);
      }
}

void
MyTableTree::OnCmdSelect (wxCommandEvent & event)
{
//
// menu event - examining table rows required
//
    wxString sql;
    MyObject *obj = (MyObject *) GetItemData (CurrentItem);
    if (obj == NULL)
	return;
    sql = wxT ("SELECT * FROM ");
    sql += obj->GetName ();
    MainFrame->SetSql (sql, true);
}

void
MyTableTree::OnCmdShow (wxCommandEvent & event)
{
//
// menu event - examining full infos required
//
    wxString sql;
    MyObject *obj = (MyObject *) GetItemData (CurrentItem);
    if (obj == NULL)
	return;
    if (obj->GetType () == MY_TABLE || obj->GetType () == MY_VTABLE
	|| obj->GetType () == MY_VIEW)
      {
	  sql = wxT ("PRAGMA table_info(");
	  sql += obj->GetName ();
	  sql += wxT (")");
      }
    if (obj->GetType () == MY_GEOMETRY || obj->GetType () == MY_GEOMETRY_INDEX
	|| obj->GetType () == MY_GEOMETRY_CACHED)
      {
	  sql = wxT ("SELECT * FROM geom_cols_ref_sys\n");
	  sql += wxT ("WHERE f_table_name = '");
	  sql += obj->GetName ();
	  sql += wxT ("'\nAND f_geometry_column = '");
	  sql += obj->GetColumn ();
	  sql += wxT ("'");
      }
    if (obj->GetType () == MY_INDEX)
      {
	  sql = wxT ("PRAGMA index_info(");
	  sql += obj->GetName ();
	  sql += wxT (")");
      }
    if (obj->GetType () == MY_TRIGGER)
      {
	  sql =
	      wxT
	      ("SELECT sql FROM sqlite_master\nWHERE type = 'trigger' AND name = '");
	  sql += obj->GetName ();
	  sql += wxT ("'");
      }
    if (sql.Len () < 1)
	return;
    MainFrame->SetSql (sql, true);
}

void
MyTableTree::OnCmdDrop (wxCommandEvent & event)
{
//
// menu event - dropping some object required
//
    wxString sql;
    wxString msg;
    char *errMsg = NULL;
    int ret;
    sqlite3 *sqlite = MainFrame->GetSqlite ();
    MyObject *obj = (MyObject *) GetItemData (CurrentItem);
    if (obj == NULL)
	return;
    if (obj->GetType () == MY_TABLE || obj->GetType () == MY_VTABLE)
      {
	  bool metadata = MainFrame->CheckMetadata ();
	  if (metadata == true)
	    {
		// SpatialMetadata exists; we must check for geometry_columns and SpatialIndices as well
		char *errMsg = NULL;
		int ret;
		int i;
		char **results;
		int rows;
		int columns;
		sqlite3 *sqlite = MainFrame->GetSqlite ();
		sql = wxT ("SELECT f_geometry_column, spatial_index_enabled ");
		sql += wxT ("FROM geometry_columns WHERE f_table_name = '");
		sql += obj->GetName ();
		sql += wxT ("'");
		ret = sqlite3_get_table (sqlite, sql.ToUTF8 (), &results,


					 &rows, &columns, &errMsg);
		if (ret != SQLITE_OK)
		  {
		      wxMessageBox (wxT ("SQLite SQL error: ") +
				    wxString::FromUTF8 (errMsg),
				    wxT ("spatialite-gui"), wxOK | wxICON_ERROR,
				    this);
		      sqlite3_free (errMsg);
		      return;
		  }
		sql = wxT ("BEGIN; ");
		if (rows < 1)
		    ;
		else
		  {
		      for (i = 1; i <= rows; i++)
			{
			    if (results[(i * columns) + 0])
			      {
				  const char *column =
				      results[(i * columns) + 0];
				  wxString geo_column =
				      wxString::FromUTF8 (column);
				  if (atoi (results[(i * columns) + 1]))
				    {
					// dropping the SpatialIndex
					sql +=
					    wxT ("DROP TABLE IF EXISTS idx_");
					sql += obj->GetName ();
					sql += wxT ("_");
					sql += geo_column;
					sql += wxT ("; ");
					// dropping the MBR cache
					sql +=
					    wxT ("DROP TABLE IF EXISTS cache_");
					sql += obj->GetName ();
					sql += wxT ("_");
					sql += geo_column;
					sql += wxT ("; ");
				    }
				  // deleting from geometry_columns
				  sql +=
				      wxT
				      ("DELETE FROM geometry_columns\n    WHERE f_table_name = '");
				  sql += obj->GetName ();
				  sql +=
				      wxT
				      ("'\n        AND f_geometry_column = '");
				  sql += geo_column;
				  sql += wxT ("'; ");
			      }
			}
		  }
		sqlite3_free_table (results);
		sql += wxT ("DROP TABLE IF EXISTS ");
		sql += obj->GetName ();
		sql += wxT ("; COMMIT;");
	    }
	  else
	    {
		// there are no SpatialMetadata at all; we'll simply try to drop the table
		sql = wxT ("BEGIN; ");
		sql += wxT ("DROP TABLE IF EXISTS ");
		sql += obj->GetName ();
		sql += wxT ("; COMMIT;");
	    }
	  msg = wxT ("Do you really intend to drop the Table named: '");
	  msg += obj->GetName ();
	  msg += wxT ("'\n[and any other related object] ?");
      }
    if (obj->GetType () == MY_VIEW)
      {
	  msg = wxT ("Do you really intend to drop the View named: '");
	  msg += obj->GetName ();
	  msg += wxT ("' ?");
	  sql = wxT ("BEGIN; DROP VIEW IF EXISTS ");
	  sql += obj->GetName ();
	  sql += wxT ("; COMMIT;");
      }
    if (obj->GetType () == MY_INDEX)
      {
	  sql = wxT ("BEGIN; DROP INDEX IF EXISTS ");
	  sql += obj->GetName ();
	  sql += wxT ("; COMMIT;");
      }
    if (obj->GetType () == MY_TRIGGER)
      {
	  msg = wxT ("Do you really intend to drop the Index named: '");
	  msg += obj->GetName ();
	  msg += wxT ("' ?");
	  sql = wxT ("BEGIN; DROP TRIGGER IF EXISTS ");
	  sql += obj->GetName ();
	  sql += wxT ("; COMMIT;");
      }
    if (sql.Len () < 1)
	return;
    wxMessageDialog confirm (this, msg, wxT ("Confirming DROP"),
			     wxOK | wxCANCEL | wxICON_QUESTION);
    ret = confirm.ShowModal ();
    if (ret != wxID_OK)
	return;
    ::wxBeginBusyCursor ();
    ret = sqlite3_exec (sqlite, sql.ToUTF8 (), NULL, NULL, &errMsg);
    if (ret != SQLITE_OK)
      {
	  wxMessageBox (wxT ("SQLite SQL error: ") +
			wxString::FromUTF8 (errMsg),
			wxT ("spatialite-gui"), wxOK | wxICON_ERROR, this);
	  sqlite3_free (errMsg);
	  ::wxEndBusyCursor ();
	  goto rollback;
      }
    ::wxEndBusyCursor ();
    wxMessageBox (wxT ("Selected object '") + obj->GetName () +
		  wxT ("' was successfully removed"),
		  wxT ("spatialite-gui"), wxOK | wxICON_INFORMATION, this);
    MainFrame->ClearTableTree ();
    MainFrame->InitTableTree ();
    return;
  rollback:
    ret = sqlite3_exec (sqlite, "ROLLBACK", NULL, NULL, &errMsg);
    if (ret != SQLITE_OK)
      {
	  wxMessageBox (wxT ("SQLite SQL error: ") +
			wxString::FromUTF8 (errMsg), wxT ("spatialite-gui"),
			wxOK | wxICON_ERROR, this);
	  sqlite3_free (errMsg);
	  ::wxEndBusyCursor ();
	  return;
      }
    ::wxEndBusyCursor ();
    wxMessageBox (wxT
		  ("An error occurred\n\na ROLLBACK was automatically performed"),
		  wxT ("spatialite-gui"), wxOK | wxICON_WARNING, this);
}

void
MyTableTree::OnCmdRename (wxCommandEvent & event)
{
//
// menu event - table renaming required
//
    wxString sql;
    MyObject *obj = (MyObject *) GetItemData (CurrentItem);
    if (obj == NULL)
	return;
    if (obj->GetType () == MY_TABLE || obj->GetType () == MY_VTABLE)
      {
	  sql = wxT ("ALTER TABLE ");
	  sql += obj->GetName ();
	  sql += wxT ("\nRENAME TO ...new-table-name...");
	  MainFrame->SetSql (sql, false);
      }
}

void
MyTableTree::OnCmdRefresh (wxCommandEvent & event)
{
//
// menu event - refreshing the Tree
//
    MainFrame->ClearTableTree ();
    MainFrame->InitTableTree ();
}

void
MyTableTree::OnCmdRecover (wxCommandEvent & event)
{
//
// menu event - Recover Geometry
//
    char *errMsg = NULL;
    int ret;
    wxString sql;
    int i;
    char **results;
    int rows;
    int columns;
    int retval = 0;
    int srid = -1;
    wxString strSrid;
    wxString type;
    RecoverDialog dlg;
    sqlite3 *sqlite = MainFrame->GetSqlite ();
    MyObject *obj = (MyObject *) GetItemData (CurrentItem);
    if (obj == NULL)
	return;
    if (obj->GetType () == MY_COLUMN)
      {
	  // trying to recover a geometry column
	  if (MainFrame->CheckMetadata () == false)
	    {
		wxMessageBox (wxT
			      ("Missing Spatial Metadata tables\n\ntry to run the 'init_spatialite.sql' script ..."),
			      wxT ("spatialite-gui"), wxOK | wxICON_ERROR,
			      this);
		return;
	    }
	  dlg.Create (MainFrame, obj->GetName (), obj->GetColumn ());
	  ret = dlg.ShowModal ();
	  if (ret == wxID_OK)
	    {
		srid = dlg.GetSrid ();
		type = dlg.GetType ();
		::wxBeginBusyCursor ();
		ret = sqlite3_exec (sqlite, "BEGIN", NULL, NULL, &errMsg);
		if (ret != SQLITE_OK)
		  {
		      wxMessageBox (wxT ("SQLite SQL error: ") +
				    wxString::FromUTF8 (errMsg),
				    wxT ("spatialite-gui"), wxOK | wxICON_ERROR,
				    this);
		      sqlite3_free (errMsg);
		      ::wxEndBusyCursor ();
		      return;
		  }
		sql = wxT ("SELECT RecoverGeometryColumn('");
		sql += obj->GetName ();
		sql += wxT ("', '");
		sql += obj->GetColumn ();
		strSrid.Printf (wxT ("', %d, '"), srid);
		sql += strSrid;
		sql += type;
		sql += wxT ("', 2)");
		ret = sqlite3_get_table (sqlite, sql.ToUTF8 (), &results,
					 &rows, &columns, &errMsg);
		if (ret != SQLITE_OK)
		  {
		      wxMessageBox (wxT ("SQLite SQL error: ") +
				    wxString::FromUTF8 (errMsg),
				    wxT ("spatialite-gui"), wxOK | wxICON_ERROR,
				    this);
		      sqlite3_free (errMsg);
		      goto rollback;
		  }
		if (rows < 1)
		    ;
		else
		  {
		      for (i = 1; i <= rows; i++)
			{
			    if (results[(i * columns) + 0])
				retval = atoi (results[(i * columns) + 0]);
			}
		  }
		sqlite3_free_table (results);
		if (!retval)
		    goto rollback;
		ret = sqlite3_exec (sqlite, "COMMIT", NULL, NULL, &errMsg);
		if (ret != SQLITE_OK)
		  {
		      wxMessageBox (wxT ("SQLite SQL error: ") +
				    wxString::FromUTF8 (errMsg),
				    wxT ("spatialite-gui"), wxOK | wxICON_ERROR,
				    this);
		      sqlite3_free (errMsg);
		      ::wxEndBusyCursor ();
		      return;
		  }
		::wxEndBusyCursor ();
		wxMessageBox (wxT ("Geometry column '") + obj->GetName () +
			      wxT (".") + obj->GetColumn () +
			      wxT ("' was successfully recovered"),
			      wxT ("spatialite-gui"), wxOK | wxICON_INFORMATION,
			      this);
	    }
      }
    return;
  rollback:
    ret = sqlite3_exec (sqlite, "ROLLBACK", NULL, NULL, &errMsg);
    if (ret != SQLITE_OK)
      {
	  wxMessageBox (wxT ("SQLite SQL error: ") +
			wxString::FromUTF8 (errMsg), wxT ("spatialite-gui"),
			wxOK | wxICON_ERROR, this);
	  sqlite3_free (errMsg);
	  ::wxEndBusyCursor ();
	  return;
      }
    ::wxEndBusyCursor ();
    wxMessageBox (wxT
		  ("Geometry column doesn't satisfies required constraints\n\na ROLLBACK was automatically performed"),
		  wxT ("spatialite-gui"), wxOK | wxICON_WARNING, this);
}

void
MyTableTree::OnCmdShowSql (wxCommandEvent & event)
{
//
// menu event - Showing CREATE TABLE statement
//
    wxString sql;
    MyObject *obj = (MyObject *) GetItemData (CurrentItem);
    if (obj == NULL)
	return;
    if (obj->GetType () == MY_TABLE || obj->GetType () == MY_VTABLE)
      {
	  sql =
	      wxT
	      ("SELECT sql FROM sqlite_master\nWHERE type = 'table' AND name = '");
	  sql += obj->GetName ();
	  sql += wxT ("'");
	  MainFrame->SetSql (sql, true);
      }
    if (obj->GetType () == MY_VIEW)
      {
	  sql =
	      wxT
	      ("SELECT sql FROM sqlite_master\nWHERE type = 'view' AND name = '");
	  sql += obj->GetName ();
	  sql += wxT ("'");
	  MainFrame->SetSql (sql, true);
      }
}

void
MyTableTree::OnCmdSpatialIndex (wxCommandEvent & event)
{
//
// menu event - Spatial Index creation-destruction
//
    char *errMsg = NULL;
    int ret;
    wxString sql;
    wxString msg;
    int i;
    char **results;
    int rows;
    int columns;
    int retval = 0;
    sqlite3 *sqlite = MainFrame->GetSqlite ();
    MyObject *obj = (MyObject *) GetItemData (CurrentItem);
    if (obj == NULL)
	return;
    if (obj->GetType () == MY_GEOMETRY)
      {
	  // creating the Spatial Index
	  ::wxBeginBusyCursor ();
	  ret = sqlite3_exec (sqlite, "BEGIN", NULL, NULL, &errMsg);
	  if (ret != SQLITE_OK)
	    {
		wxMessageBox (wxT ("SQLite SQL error: ") +
			      wxString::FromUTF8 (errMsg),
			      wxT ("spatialite-gui"), wxOK | wxICON_ERROR,
			      this);
		sqlite3_free (errMsg);
		::wxEndBusyCursor ();
		return;
	    }
	  sql = wxT ("SELECT CreateSpatialIndex('");
	  sql += obj->GetName ();
	  sql += wxT ("', '");
	  sql += obj->GetColumn ();
	  sql += wxT ("')");
	  ret = sqlite3_get_table (sqlite, sql.ToUTF8 (), &results,
				   &rows, &columns, &errMsg);
	  if (ret != SQLITE_OK)
	    {
		wxMessageBox (wxT ("SQLite SQL error: ") +
			      wxString::FromUTF8 (errMsg),
			      wxT ("spatialite-gui"), wxOK | wxICON_ERROR,
			      this);
		sqlite3_free (errMsg);
		goto rollback;
	    }
	  if (rows < 1)
	      ;
	  else
	    {
		for (i = 1; i <= rows; i++)
		  {
		      if (results[(i * columns) + 0])
			  retval = atoi (results[(i * columns) + 0]);
		  }
	    }
	  sqlite3_free_table (results);
	  if (!retval)
	      goto rollback;
	  ret = sqlite3_exec (sqlite, "COMMIT", NULL, NULL, &errMsg);
	  if (ret != SQLITE_OK)
	    {
		wxMessageBox (wxT ("SQLite SQL error: ") +
			      wxString::FromUTF8 (errMsg),
			      wxT ("spatialite-gui"), wxOK | wxICON_ERROR,
			      this);
		sqlite3_free (errMsg);
		::wxEndBusyCursor ();
		return;
	    }
	  ::wxEndBusyCursor ();
	  wxMessageBox (wxT ("Spatial Index idx_") + obj->GetName () +
			wxT ("_") + obj->GetColumn () +
			wxT (" was successfully created"),
			wxT ("spatialite-gui"), wxOK | wxICON_INFORMATION,
			this);
	  MainFrame->ClearTableTree ();
	  MainFrame->InitTableTree ();
      }
    else if (obj->GetType () == MY_GEOMETRY_INDEX)
      {
	  // dropping the Spatial Index
	  ::wxBeginBusyCursor ();
	  ret = sqlite3_exec (sqlite, "BEGIN", NULL, NULL, &errMsg);
	  if (ret != SQLITE_OK)
	    {
		wxMessageBox (wxT ("SQLite SQL error: ") +
			      wxString::FromUTF8 (errMsg),
			      wxT ("spatialite-gui"), wxOK | wxICON_ERROR,
			      this);
		sqlite3_free (errMsg);
		::wxEndBusyCursor ();
		return;
	    }
	  sql = wxT ("SELECT DisableSpatialIndex('");
	  sql += obj->GetName ();
	  sql += wxT ("', '");
	  sql += obj->GetColumn ();
	  sql += wxT ("')");
	  msg = wxT ("Do you really intend to delete the SpatialIndex\n");
	  msg += wxT ("on column '");
	  msg += obj->GetName ();
	  msg += wxT (".");
	  msg += obj->GetColumn ();
	  msg += wxT ("' ?");
	  wxMessageDialog confirm (this, msg,
				   wxT ("Confirming Delete Spatial Index"),
				   wxOK | wxCANCEL | wxICON_QUESTION);
	  ret = confirm.ShowModal ();
	  if (ret != wxID_OK)
	      return;
	  ret = sqlite3_get_table (sqlite, sql.ToUTF8 (), &results,
				   &rows, &columns, &errMsg);
	  if (ret != SQLITE_OK)
	    {
		wxMessageBox (wxT ("SQLite SQL error: ") +
			      wxString::FromUTF8 (errMsg),
			      wxT ("spatialite-gui"), wxOK | wxICON_ERROR,
			      this);
		sqlite3_free (errMsg);
		goto rollback;
	    }
	  if (rows < 1)
	      ;
	  else
	    {
		for (i = 1; i <= rows; i++)
		  {
		      if (results[(i * columns) + 0])
			  retval = atoi (results[(i * columns) + 0]);
		  }
	    }
	  sqlite3_free_table (results);
	  if (!retval)
	      goto rollback;
	  sql = wxT ("DROP TABLE IF EXISTS idx_");
	  sql += obj->GetName ();
	  sql += wxT ("_");
	  sql += obj->GetColumn ();
	  ret = sqlite3_exec (sqlite, sql.ToUTF8 (), NULL, NULL, &errMsg);
	  if (ret != SQLITE_OK)
	    {
		wxMessageBox (wxT ("SQLite SQL error: ") +
			      wxString::FromUTF8 (errMsg),
			      wxT ("spatialite-gui"), wxOK | wxICON_ERROR,
			      this);
		sqlite3_free (errMsg);
		::wxEndBusyCursor ();
		return;
	    }
	  ret = sqlite3_exec (sqlite, "COMMIT", NULL, NULL, &errMsg);
	  if (ret != SQLITE_OK)
	    {
		wxMessageBox (wxT ("SQLite SQL error: ") +
			      wxString::FromUTF8 (errMsg),
			      wxT ("spatialite-gui"), wxOK | wxICON_ERROR,
			      this);
		sqlite3_free (errMsg);
		::wxEndBusyCursor ();
		return;
	    }
	  ::wxEndBusyCursor ();
	  wxMessageBox (wxT ("Spatial Index idx_") + obj->GetName () +
			wxT ("_") + obj->GetColumn () +
			wxT (" was successfully removed"),
			wxT ("spatialite-gui"), wxOK | wxICON_INFORMATION,
			this);
	  MainFrame->ClearTableTree ();
	  MainFrame->InitTableTree ();
      }
    return;
  rollback:
    ret = sqlite3_exec (sqlite, "ROLLBACK", NULL, NULL, &errMsg);
    if (ret != SQLITE_OK)
      {
	  wxMessageBox (wxT ("SQLite SQL error: ") +
			wxString::FromUTF8 (errMsg), wxT ("spatialite-gui"),
			wxOK | wxICON_ERROR, this);
	  sqlite3_free (errMsg);
	  ::wxEndBusyCursor ();
	  return;
      }
    ::wxEndBusyCursor ();
    wxMessageBox (wxT
		  ("An error occurred\n\na ROLLBACK was automatically performed"),
		  wxT ("spatialite-gui"), wxOK | wxICON_WARNING, this);
}

void
MyTableTree::OnCmdMbrCache (wxCommandEvent & event)
{
//
// menu event - MBR cache creation-destruction
//
    char *errMsg = NULL;
    int ret;
    wxString sql;
    wxString msg;
    int i;
    char **results;
    int rows;
    int columns;
    int retval = 0;
    sqlite3 *sqlite = MainFrame->GetSqlite ();
    MyObject *obj = (MyObject *) GetItemData (CurrentItem);
    if (obj == NULL)
	return;
    if (obj->GetType () == MY_GEOMETRY)
      {
	  // creating the MBR cache
	  ::wxBeginBusyCursor ();
	  ret = sqlite3_exec (sqlite, "BEGIN", NULL, NULL, &errMsg);
	  if (ret != SQLITE_OK)
	    {
		wxMessageBox (wxT ("SQLite SQL error: ") +
			      wxString::FromUTF8 (errMsg),
			      wxT ("spatialite-gui"), wxOK | wxICON_ERROR,
			      this);
		sqlite3_free (errMsg);
		::wxEndBusyCursor ();
		return;
	    }
	  sql = wxT ("SELECT CreateMbrCache('");
	  sql += obj->GetName ();
	  sql += wxT ("', '");
	  sql += obj->GetColumn ();
	  sql += wxT ("')");
	  ret = sqlite3_get_table (sqlite, sql.ToUTF8 (), &results,
				   &rows, &columns, &errMsg);
	  if (ret != SQLITE_OK)
	    {
		wxMessageBox (wxT ("SQLite SQL error: ") +
			      wxString::FromUTF8 (errMsg),
			      wxT ("spatialite-gui"), wxOK | wxICON_ERROR,
			      this);
		sqlite3_free (errMsg);
		goto rollback;
	    }
	  if (rows < 1)
	      ;
	  else
	    {
		for (i = 1; i <= rows; i++)
		  {
		      if (results[(i * columns) + 0])
			  retval = atoi (results[(i * columns) + 0]);
		  }
	    }
	  sqlite3_free_table (results);
	  if (!retval)
	      goto rollback;
	  ret = sqlite3_exec (sqlite, "COMMIT", NULL, NULL, &errMsg);
	  if (ret != SQLITE_OK)
	    {
		wxMessageBox (wxT ("SQLite SQL error: ") +
			      wxString::FromUTF8 (errMsg),
			      wxT ("spatialite-gui"), wxOK | wxICON_ERROR,
			      this);
		sqlite3_free (errMsg);
		::wxEndBusyCursor ();
		return;
	    }
	  ::wxEndBusyCursor ();
	  wxMessageBox (wxT ("MBR cache cache_") + obj->GetName () +
			wxT ("_") + obj->GetColumn () +
			wxT (" was successfully created"),
			wxT ("spatialite-gui"), wxOK | wxICON_INFORMATION,
			this);
	  MainFrame->ClearTableTree ();
	  MainFrame->InitTableTree ();
      }
    else if (obj->GetType () == MY_GEOMETRY_CACHED)
      {
	  // dropping the MBR cache
	  ::wxBeginBusyCursor ();
	  ret = sqlite3_exec (sqlite, "BEGIN", NULL, NULL, &errMsg);
	  if (ret != SQLITE_OK)
	    {
		wxMessageBox (wxT ("SQLite SQL error: ") +
			      wxString::FromUTF8 (errMsg),
			      wxT ("spatialite-gui"), wxOK | wxICON_ERROR,
			      this);
		sqlite3_free (errMsg);
		::wxEndBusyCursor ();
		return;
	    }
	  sql = wxT ("SELECT DisableSpatialIndex('");
	  sql += obj->GetName ();
	  sql += wxT ("', '");
	  sql += obj->GetColumn ();
	  sql += wxT ("')");
	  msg = wxT ("Do you really intend to delete the MBR cache\n");
	  msg += wxT ("on column '");
	  msg += obj->GetName ();
	  msg += wxT (".");
	  msg += obj->GetColumn ();
	  msg += wxT ("' ?");
	  wxMessageDialog confirm (this, msg,
				   wxT ("Confirming Delete MBR cache"),
				   wxOK | wxCANCEL | wxICON_QUESTION);
	  ret = confirm.ShowModal ();
	  if (ret != wxID_OK)
	      return;
	  ret = sqlite3_get_table (sqlite, sql.ToUTF8 (), &results,
				   &rows, &columns, &errMsg);
	  if (ret != SQLITE_OK)
	    {
		wxMessageBox (wxT ("SQLite SQL error: ") +
			      wxString::FromUTF8 (errMsg),
			      wxT ("spatialite-gui"), wxOK | wxICON_ERROR,
			      this);
		sqlite3_free (errMsg);
		goto rollback;
	    }
	  if (rows < 1)
	      ;
	  else
	    {
		for (i = 1; i <= rows; i++)
		  {
		      if (results[(i * columns) + 0])
			  retval = atoi (results[(i * columns) + 0]);
		  }
	    }
	  sqlite3_free_table (results);
	  if (!retval)
	      goto rollback;
	  sql = wxT ("DROP TABLE IF EXISTS cache_");
	  sql += obj->GetName ();
	  sql += wxT ("_");
	  sql += obj->GetColumn ();
	  ret = sqlite3_exec (sqlite, sql.ToUTF8 (), NULL, NULL, &errMsg);
	  if (ret != SQLITE_OK)
	    {
		wxMessageBox (wxT ("SQLite SQL error: ") +
			      wxString::FromUTF8 (errMsg),
			      wxT ("spatialite-gui"), wxOK | wxICON_ERROR,
			      this);
		sqlite3_free (errMsg);
		::wxEndBusyCursor ();
		return;
	    }
	  ret = sqlite3_exec (sqlite, "COMMIT", NULL, NULL, &errMsg);
	  if (ret != SQLITE_OK)
	    {
		wxMessageBox (wxT ("SQLite SQL error: ") +
			      wxString::FromUTF8 (errMsg),
			      wxT ("spatialite-gui"), wxOK | wxICON_ERROR,
			      this);
		sqlite3_free (errMsg);
		::wxEndBusyCursor ();
		return;
	    }
	  ::wxEndBusyCursor ();
	  wxMessageBox (wxT ("MBR cache cache_") + obj->GetName () +
			wxT ("_") + obj->GetColumn () +
			wxT (" was successfully removed"),
			wxT ("spatialite-gui"), wxOK | wxICON_INFORMATION,
			this);
	  MainFrame->ClearTableTree ();
	  MainFrame->InitTableTree ();
      }
    return;
  rollback:
    ret = sqlite3_exec (sqlite, "ROLLBACK", NULL, NULL, &errMsg);
    if (ret != SQLITE_OK)
      {
	  wxMessageBox (wxT ("SQLite SQL error: ") +
			wxString::FromUTF8 (errMsg), wxT ("spatialite-gui"),
			wxOK | wxICON_ERROR, this);
	  sqlite3_free (errMsg);
	  ::wxEndBusyCursor ();
	  return;
      }
    ::wxEndBusyCursor ();
    wxMessageBox (wxT
		  ("An error occurred\n\na ROLLBACK was automatically performed"),
		  wxT ("spatialite-gui"), wxOK | wxICON_WARNING, this);
}

void
MyTableTree::OnCmdCheckGeometry (wxCommandEvent & event)
{
//
// menu event - checking geometries
//
    wxString sql;
    MyObject *obj = (MyObject *) GetItemData (CurrentItem);
    if (obj == NULL)
	return;
    if (obj->GetType () == MY_COLUMN)
      {
	  sql = wxT ("SELECT Count(*), GeometryType(");
	  sql += obj->GetColumn ();
	  sql += wxT ("), Srid(");
	  sql += obj->GetColumn ();
	  sql += wxT (")\nFROM ");
	  sql += obj->GetName ();
	  sql += wxT ("\nGROUP BY 2, 3");
	  MainFrame->SetSql (sql, true);
      }
}

void
MyTableTree::OnCmdSetSrid (wxCommandEvent & event)
{
//
// menu event - setting SRID for geometries
//
    SetSridDialog dlg;
    wxString sql;
    wxString strSrid;
    int srid;
    int oldSrid;
    int ret;
    MyObject *obj = (MyObject *) GetItemData (CurrentItem);
    if (obj == NULL)
	return;
    if (obj->GetType () == MY_COLUMN)
      {
	  dlg.Create (MainFrame, obj->GetName (), obj->GetColumn ());
	  ret = dlg.ShowModal ();
	  if (ret == wxID_OK)
	    {
		srid = dlg.GetSrid ();
		oldSrid = dlg.GetOldSrid ();
		sql = wxT ("UPDATE ");
		sql += obj->GetName ();
		sql += wxT (" SET ");
		sql += obj->GetColumn ();
		sql += wxT (" = SetSrid(");
		sql += obj->GetColumn ();
		strSrid.Printf (wxT (", %d)"), srid);
		sql += strSrid;
		sql += wxT ("\nWHERE Srid(");
		sql += obj->GetColumn ();
		strSrid.Printf (wxT (") = %d"), oldSrid);
		sql += strSrid;
		MainFrame->SetSql (sql, true);
	    }
      }
}

void
MyTableTree::OnCmdDumpShp (wxCommandEvent & event)
{
//
// menu event - dumping as Shapefile
//
    int ret;
    wxString path;
    wxString lastDir;
    MyObject *obj = (MyObject *) GetItemData (CurrentItem);
    if (obj == NULL)
	return;
    if (obj->GetType () == MY_GEOMETRY || obj->GetType () == MY_GEOMETRY_INDEX)
      {
	  wxFileDialog *fileDialog =
	      new wxFileDialog (this, wxT ("Dump Shapefile"),
				wxT (""), wxT ("shapefile.shp"),
				wxT
				("Shapefile (*.shp)|*.shp|All files (*.*)|*.*"),
				wxFD_SAVE | wxFD_OVERWRITE_PROMPT,
				wxDefaultPosition, wxDefaultSize,
				wxT ("filedlg"));
	  lastDir = MainFrame->GetLastDirectory ();
	  if (lastDir.Len () >= 1)
	      fileDialog->SetDirectory (lastDir);
	  ret = fileDialog->ShowModal ();
	  if (ret == wxID_OK)
	    {

		wxFileName file (fileDialog->GetPath ());
		path = file.GetPath ();
		path += file.GetPathSeparator ();
		path += file.GetName ();
		lastDir = file.GetPath ();
		if (MainFrame->IsSetAskCharset () == false)
		  {
		      // using the default output charset
		      MainFrame->SetLastDirectory (lastDir);
		      ::wxBeginBusyCursor ();
		      MainFrame->DumpShapefile (path, obj->GetName (),
						obj->GetColumn (),
						MainFrame->GetDefaultCharset
						());
		      ::wxEndBusyCursor ();
		  }
		else
		  {
		      // asking the charset to be used
		      DumpShpDialog dlg;
		      dlg.Create (MainFrame, path, obj->GetName (),
				  obj->GetColumn (),
				  MainFrame->GetDefaultCharset ());
		      ret = dlg.ShowModal ();
		      if (ret == wxID_OK)
			{
			    MainFrame->SetLastDirectory (lastDir);
			    ::wxBeginBusyCursor ();
			    MainFrame->DumpShapefile (path, obj->GetName (),
						      obj->GetColumn (),
						      dlg.GetCharset ());
			    ::wxEndBusyCursor ();
			}
		  }
	    }
      }
}

void
MyTableTree::OnCmdDumpTxtTab (wxCommandEvent & event)
{
//
// menu event - dumping as TxtTab
//
    int ret;
    wxString path;
    wxString lastDir;
    wxString target;
    MyObject *obj = (MyObject *) GetItemData (CurrentItem);
    if (obj == NULL)
	return;
    wxFileDialog *fileDialog =
	new wxFileDialog (this, wxT ("Dump Txt/Tab file"),
			  wxT (""), wxT ("table.txt"),
			  wxT
			  ("File Txt/Tab (*.txt)|*.txt|All files (*.*)|*.*"),
			  wxFD_SAVE | wxFD_OVERWRITE_PROMPT, wxDefaultPosition,
			  wxDefaultSize, wxT ("filedlg"));
    lastDir = MainFrame->GetLastDirectory ();
    if (lastDir.Len () >= 1)
	fileDialog->SetDirectory (lastDir);
    ret = fileDialog->ShowModal ();
    if (ret == wxID_OK)
      {
	  wxFileName file (fileDialog->GetPath ());
	  path = file.GetPath ();
	  path += file.GetPathSeparator ();
	  path += file.GetName ();
	  path += wxT (".txt");
	  lastDir = file.GetPath ();
	  if (MainFrame->IsSetAskCharset () == false)
	    {
		// using the default output charset
		MainFrame->SetLastDirectory (lastDir);
		::wxBeginBusyCursor ();
		MainFrame->DumpTxtTab (path, obj->GetName (),
				       MainFrame->GetDefaultCharset ());
		::wxEndBusyCursor ();
	    }
	  else
	    {
		// asking the charset to be used
		DumpTxtDialog dlg;
		target = wxT ("TXT / TAB");
		dlg.Create (MainFrame, path, target,
			    MainFrame->GetDefaultCharset ());
		ret = dlg.ShowModal ();
		if (ret == wxID_OK)
		  {
		      MainFrame->SetLastDirectory (lastDir);
		      ::wxBeginBusyCursor ();
		      MainFrame->DumpTxtTab (path, obj->GetName (),
					     dlg.GetCharset ());
		      ::wxEndBusyCursor ();
		  }
	    }
      }
}

void
MyTableTree::OnCmdDumpCsv (wxCommandEvent & event)
{
//
// menu event - dumping as CSV
//
    int ret;
    wxString path;
    wxString lastDir;
    wxString target;
    MyObject *obj = (MyObject *) GetItemData (CurrentItem);
    if (obj == NULL)
	return;
    wxFileDialog *fileDialog = new wxFileDialog (this, wxT ("Dump CSV file"),
						 wxT (""), wxT ("table.csv"),
						 wxT
						 ("File CSV (*.csv)|*.csv|All files (*.*)|*.*"),
						 wxFD_SAVE |
						 wxFD_OVERWRITE_PROMPT,
						 wxDefaultPosition,
						 wxDefaultSize,
						 wxT ("filedlg"));
    lastDir = MainFrame->GetLastDirectory ();
    if (lastDir.Len () >= 1)
	fileDialog->SetDirectory (lastDir);
    ret = fileDialog->ShowModal ();
    if (ret == wxID_OK)
      {
	  wxFileName file (fileDialog->GetPath ());
	  path = file.GetPath ();
	  path += file.GetPathSeparator ();
	  path += file.GetName ();
	  path += wxT (".csv");
	  lastDir = file.GetPath ();
	  if (MainFrame->IsSetAskCharset () == false)
	    {
		// using the default output charset
		MainFrame->SetLastDirectory (lastDir);
		::wxBeginBusyCursor ();
		MainFrame->DumpCsv (path, obj->GetName (),
				    MainFrame->GetDefaultCharset ());
		::wxEndBusyCursor ();
	    }
	  else
	    {
		// asking the charset to be used
		DumpTxtDialog dlg;
		target = wxT ("CSV");
		dlg.Create (MainFrame, path, target,
			    MainFrame->GetDefaultCharset ());
		ret = dlg.ShowModal ();
		if (ret == wxID_OK)
		  {
		      MainFrame->SetLastDirectory (lastDir);
		      ::wxBeginBusyCursor ();
		      MainFrame->DumpCsv (path, obj->GetName (),
					  dlg.GetCharset ());
		      ::wxEndBusyCursor ();
		  }
	    }
      }
}

void
MyTableTree::OnCmdDumpHtml (wxCommandEvent & event)
{
//
// menu event - dumping as Html
//
    int ret;
    wxString path;
    wxString lastDir;
    wxString target;
    MyObject *obj = (MyObject *) GetItemData (CurrentItem);
    if (obj == NULL)
	return;
    wxFileDialog *fileDialog = new wxFileDialog (this, wxT ("Dump HTML file"),
						 wxT (""), wxT ("table.html"),
						 wxT
						 ("HTML web page (*.html)|*.html|All files (*.*)|*.*"),
						 wxFD_SAVE |
						 wxFD_OVERWRITE_PROMPT,
						 wxDefaultPosition,
						 wxDefaultSize,
						 wxT ("filedlg"));
    lastDir = MainFrame->GetLastDirectory ();
    if (lastDir.Len () >= 1)
	fileDialog->SetDirectory (lastDir);
    ret = fileDialog->ShowModal ();
    if (ret == wxID_OK)
      {
	  wxFileName file (fileDialog->GetPath ());
	  path = file.GetPath ();
	  path += file.GetPathSeparator ();
	  path += file.GetName ();
	  path += wxT (".html");
	  lastDir = file.GetPath ();
	  if (MainFrame->IsSetAskCharset () == false)
	    {
		// using the default output charset
		MainFrame->SetLastDirectory (lastDir);
		::wxBeginBusyCursor ();
		MainFrame->DumpHtml (path, obj->GetName (),
				     MainFrame->GetDefaultCharset ());
		::wxEndBusyCursor ();
	    }
	  else
	    {
		// asking the charset to be used
		DumpTxtDialog dlg;
		target = wxT ("HTML");
		dlg.Create (MainFrame, path, target,
			    MainFrame->GetDefaultCharset ());
		ret = dlg.ShowModal ();
		if (ret == wxID_OK)
		  {
		      MainFrame->SetLastDirectory (lastDir);
		      ::wxBeginBusyCursor ();
		      MainFrame->DumpHtml (path, obj->GetName (),
					   dlg.GetCharset ());
		      ::wxEndBusyCursor ();
		  }
	    }
      }
}

void
MyTableTree::OnCmdEdit (wxCommandEvent & event)
{
//
// menu event - editing row valuew
//
    char **results;
    int rows;
    int columns;
    int i;
    char *errMsg = NULL;
    wxString sql;
    char *column;
    char *type;
    int pk = 0;
    int pb = 0;
    int primaryKeys[1024];
    int blobCols[1024];
    for (i = 0; i < 1024; i++)
      {
	  primaryKeys[i] = -1;
	  blobCols[i] = -1;
      }
    primaryKeys[pk++] = 0;
    MyObject *obj = (MyObject *) GetItemData (CurrentItem);
    if (obj == NULL)
	return;
    sql = wxT ("PRAGMA table_info(");
    sql += obj->GetName ();
    sql += wxT (")");
    int ret =
	sqlite3_get_table (MainFrame->GetSqlite (), sql.ToUTF8 (), &results,
			   &rows, &columns, &errMsg);
    if (ret != SQLITE_OK)
      {
	  wxMessageBox (wxT ("SQLite SQL error: ") +
			wxString::FromUTF8 (errMsg), wxT ("spatialite-gui"),
			wxOK | wxICON_ERROR, this);
	  sqlite3_free (errMsg);
	  return;
      }
    sql = wxT ("");
    if (rows < 1)
	;
    else
      {
	  sql = wxT ("SELECT ROWID");
	  for (i = 1; i <= rows; i++)
	    {
		column = results[(i * columns) + 1];
		sql += wxT (", ") + wxString::FromUTF8 (column);
		type = results[(i * columns) + 2];
		if (strcasecmp (type, "BLOB") == 0)
		    blobCols[pb++] = i;
		if (atoi (results[(i * columns) + 5]) == 0)
		    ;
		else
		    primaryKeys[pk++] = i;
	    }
      }
    sqlite3_free_table (results);
    if (sql.Len () < 1)
	return;
    sql += wxT ("\nFROM ");
    sql += obj->GetName ();
    sql += wxT ("\nORDER BY ROWID");
    MainFrame->EditTable (sql, primaryKeys, blobCols, obj->GetName ());
}




|







 







>
>

|
<




|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




|
|
|
|


<
|




|
|
|
|
|
|
|
|
|
|
|


<
|




|
|
|
|
|
|
|
|
|
|
|
|


<
|




|
|
|
|
|
|
|
|
|
|
|


<
|




|
|
|
|
|
|
|


<
|




|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|


<
|




|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<
>
>
|
|
|
|
|
|
<
|
|
|
|
|
|
|
|
|
|
|
|
<
|
|
<
|
|
|
<
|
|
|
|
|
|
<
|
|
|
|
|
|
|
|
|
|
|
<
<
|
|
|
|
|
|
|
|
|
|
<
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<
|
|
|
|
|
|
|
|
|
<
|
|
|
|
|
|
|
<
|
|
|
|
|
|
|
|
|


<
|




|
|
|
|
|
|
|
|
|
|
|


<
|




|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
1
2
3
4
5
6
7
8
9
10
11
12
..
39
40
41
42
43
44
45
46
47
48
49

50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565






























566
567
568
569
570
571
572
573
574
575

576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593

594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612

613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630

631
632
633
634
635
636
637
638
639
640
641
642
643
644

645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689

690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719

720
721
722
723
724
725
726
727

728
729
730
731
732
733
734
735
736
737
738
739

740
741

742
743
744

745
746
747
748
749
750

751
752
753
754
755
756
757
758
759
760
761


762
763
764
765
766
767
768
769
770
771

772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819

820
821
822
823
824
825
826
827
828

829
830
831
832
833
834
835

836
837
838
839
840
841
842
843
844
845
846

847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864

865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747













































/*
/ TableTree.cpp
/ tree control to show tables, columns, indices and triggers
/
/ version 1.2, 2008 October 9
/
/ Author: Sandro Furieri a-furieri@lqt.it
/
/ Copyright (C) 2008  Alessandro Furieri
/
/    This program is free software: you can redistribute it and/or modify
/    it under the terms of the GNU General Public License as published by
................................................................................
#include "icons/pkey.xpm"
#include "icons/column.xpm"
#include "icons/index.xpm"
#include "icons/trigger.xpm"
#include "icons/geometry.xpm"
#include "icons/spatialidx.xpm"
#include "icons/mbrcache.xpm"
#include "icons/kill_spindex.xpm"
#include "icons/dumpshp.xpm"

MyTableTree::MyTableTree(MyFrame * parent, wxWindowID id):wxTreeCtrl(parent, id)

{
//
// constructor: TREE control to show DB objects
//
  MainFrame = parent;
  Root = AddRoot(wxT("no current DB"));
// setting up icons 
  Images = new wxImageList(16, 16, true);
  wxIcon icons[12];
  icons[0] = wxIcon(db_xpm);
  icons[1] = wxIcon(table_xpm);
  icons[2] = wxIcon(pkey_xpm);
  icons[3] = wxIcon(column_xpm);
  icons[4] = wxIcon(index_xpm);
  icons[5] = wxIcon(trigger_xpm);
  icons[6] = wxIcon(geometry_xpm);
  icons[7] = wxIcon(spatialidx_xpm);
  icons[8] = wxIcon(vtable_xpm);
  icons[9] = wxIcon(view_xpm);
  icons[10] = wxIcon(geotable_xpm);
  icons[11] = wxIcon(mbrcache_xpm);
  Images->Add(icons[0]);
  Images->Add(icons[1]);
  Images->Add(icons[2]);
  Images->Add(icons[3]);
  Images->Add(icons[4]);
  Images->Add(icons[5]);
  Images->Add(icons[6]);
  Images->Add(icons[7]);
  Images->Add(icons[8]);
  Images->Add(icons[9]);
  Images->Add(icons[10]);
  Images->Add(icons[11]);
  SetImageList(Images);
  SetItemImage(Root, 0);
// setting up event handlers 
  Connect(wxID_ANY, wxEVT_COMMAND_TREE_SEL_CHANGED,
          (wxObjectEventFunction) & MyTableTree::OnSelChanged);
  Connect(wxID_ANY, wxEVT_COMMAND_TREE_ITEM_RIGHT_CLICK,
          (wxObjectEventFunction) & MyTableTree::OnRightClick);
  Connect(Tree_NewTable, wxEVT_COMMAND_MENU_SELECTED,
          (wxObjectEventFunction) & MyTableTree::OnCmdNewTable);
  Connect(Tree_NewView, wxEVT_COMMAND_MENU_SELECTED,
          (wxObjectEventFunction) & MyTableTree::OnCmdNewView);
  Connect(Tree_NewIndex, wxEVT_COMMAND_MENU_SELECTED,
          (wxObjectEventFunction) & MyTableTree::OnCmdNewIndex);
  Connect(Tree_NewTrigger, wxEVT_COMMAND_MENU_SELECTED,
          (wxObjectEventFunction) & MyTableTree::OnCmdNewTrigger);
  Connect(Tree_NewColumn, wxEVT_COMMAND_MENU_SELECTED,
          (wxObjectEventFunction) & MyTableTree::OnCmdNewColumn);
  Connect(Tree_Show, wxEVT_COMMAND_MENU_SELECTED,
          (wxObjectEventFunction) & MyTableTree::OnCmdShow);
  Connect(Tree_Drop, wxEVT_COMMAND_MENU_SELECTED,
          (wxObjectEventFunction) & MyTableTree::OnCmdDrop);
  Connect(Tree_Rename, wxEVT_COMMAND_MENU_SELECTED,
          (wxObjectEventFunction) & MyTableTree::OnCmdRename);
  Connect(Tree_Select, wxEVT_COMMAND_MENU_SELECTED,
          (wxObjectEventFunction) & MyTableTree::OnCmdSelect);
  Connect(Tree_Refresh, wxEVT_COMMAND_MENU_SELECTED,
          (wxObjectEventFunction) & MyTableTree::OnCmdRefresh);
  Connect(Tree_Recover, wxEVT_COMMAND_MENU_SELECTED,
          (wxObjectEventFunction) & MyTableTree::OnCmdRecover);
  Connect(Tree_ShowSql, wxEVT_COMMAND_MENU_SELECTED,
          (wxObjectEventFunction) & MyTableTree::OnCmdShowSql);
  Connect(Tree_SpatialIndex, wxEVT_COMMAND_MENU_SELECTED,
          (wxObjectEventFunction) & MyTableTree::OnCmdSpatialIndex);
  Connect(Tree_MbrCache, wxEVT_COMMAND_MENU_SELECTED,
          (wxObjectEventFunction) & MyTableTree::OnCmdMbrCache);
  Connect(Tree_RebuildTriggers, wxEVT_COMMAND_MENU_SELECTED,
          (wxObjectEventFunction) & MyTableTree::OnCmdRebuildTriggers);
  Connect(Tree_CheckGeometry, wxEVT_COMMAND_MENU_SELECTED,
          (wxObjectEventFunction) & MyTableTree::OnCmdCheckGeometry);
  Connect(Tree_SetSrid, wxEVT_COMMAND_MENU_SELECTED,
          (wxObjectEventFunction) & MyTableTree::OnCmdSetSrid);
  Connect(Tree_DumpShp, wxEVT_COMMAND_MENU_SELECTED,
          (wxObjectEventFunction) & MyTableTree::OnCmdDumpShp);
  Connect(Tree_DumpTxtTab, wxEVT_COMMAND_MENU_SELECTED,
          (wxObjectEventFunction) & MyTableTree::OnCmdDumpTxtTab);
  Connect(Tree_DumpCsv, wxEVT_COMMAND_MENU_SELECTED,
          (wxObjectEventFunction) & MyTableTree::OnCmdDumpCsv);
  Connect(Tree_DumpHtml, wxEVT_COMMAND_MENU_SELECTED,
          (wxObjectEventFunction) & MyTableTree::OnCmdDumpHtml);
  Connect(Tree_Edit, wxEVT_COMMAND_MENU_SELECTED,
          (wxObjectEventFunction) & MyTableTree::OnCmdEdit);
}

void MyTableTree::AddTable(wxString & tableName, bool virtualTable)
{
//
// appends a table to the TREE list
  MyTableInfo list;
  MyColumnInfo *col;
  MyIndexInfo *idx;
  MyTriggerInfo *trgr;
  wxTreeItemId item;
  wxTreeItemId item2;
  wxString columnInfo;
  wxString indexInfo;
  wxString triggerInfo;
  int icon = 1;
  if (virtualTable == true)
    icon = 8;
  item = AppendItem(Root, tableName, icon);
  if (virtualTable == true)
    SetItemData(item, (wxTreeItemData *) (new MyObject(MY_VTABLE, tableName)));
  else
    SetItemData(item, (wxTreeItemData *) (new MyObject(MY_TABLE, tableName)));
  MainFrame->GetTableColumns(tableName, &list);
  MainFrame->GetTableIndices(tableName, &list);
  MainFrame->GetTableTriggers(tableName, &list);
  col = list.GetFirstColumn();
  while (col)
    {
      int icon;
      if (col->IsPrimaryKey() == true)
        icon = 2;
      else
        {
          if (col->IsGeometry() == true)
            {
              if (virtualTable == false)
                SetItemImage(item, 10);
              if (col->IsGeometryIndex() == true)
                icon = 7;
              else if (col->IsMbrCache() == true)
                icon = 11;
              else
                icon = 6;
          } else
            icon = 3;
        }
      columnInfo = col->GetName();
      item2 = AppendItem(item, columnInfo, icon);
      if (col->IsGeometry() == true)
        {
          if (col->IsGeometryIndex() == true)
            SetItemData(item2,
                        (wxTreeItemData *) (new
                                            MyObject(MY_GEOMETRY_INDEX,
                                                     tableName,
                                                     col->GetName())));
          else if (col->IsMbrCache() == true)
            SetItemData(item2,
                        (wxTreeItemData *) (new
                                            MyObject(MY_GEOMETRY_CACHED,
                                                     tableName,
                                                     col->GetName())));
          else
            SetItemData(item2,
                        (wxTreeItemData *) (new
                                            MyObject(MY_GEOMETRY, tableName,
                                                     col->GetName())));
      } else
        SetItemData(item2,
                    (wxTreeItemData *) (new
                                        MyObject(MY_COLUMN, tableName,
                                                 col->GetName())));
      col = col->GetNext();
    }
  idx = list.GetFirstIndex();
  while (idx)
    {
      indexInfo = idx->GetName();
      item2 = AppendItem(item, indexInfo, 4);
      SetItemData(item2,
                  (wxTreeItemData *) (new MyObject(MY_INDEX, idx->GetName())));
      idx = idx->GetNext();
    }
  trgr = list.GetFirstTrigger();
  while (trgr)
    {
      triggerInfo = trgr->GetName();
      item2 = AppendItem(item, triggerInfo, 5);
      SetItemData(item2,
                  (wxTreeItemData *) (new
                                      MyObject(MY_TRIGGER, trgr->GetName())));
      trgr = trgr->GetNext();
    }
}

void MyTableTree::AddView(wxString & viewName)
{
//
// appends a view to the TREE list
  MyViewInfo list;
  MyColumnInfo *col;
  wxTreeItemId item;
  wxTreeItemId item2;
  wxString columnInfo;
  item = AppendItem(Root, viewName, 9);
  SetItemData(item, (wxTreeItemData *) (new MyObject(MY_VIEW, viewName)));
  MainFrame->GetViewColumns(viewName, &list);
  col = list.GetFirst();
  while (col)
    {
      columnInfo = col->GetName();
      item2 = AppendItem(item, columnInfo, 3);
      SetItemData(item2,
                  (wxTreeItemData *) (new
                                      MyObject(MY_COLUMN, viewName,
                                               col->GetName())));
      col = col->GetNext();
    }
}

void MyTableTree::OnSelChanged(wxTreeEvent & event)
{
//
// selecting some node [mouse action]
//
  wxTreeItemId item = event.GetItem();
  if (item == Root)
    return;
  MyObject *obj = (MyObject *) GetItemData(item);
  if (obj == NULL)
    return;
  CurrentItem = item;
}

void MyTableTree::OnRightClick(wxTreeEvent & event)
{
//
// right click on some node [mouse action]
//
  wxMenu *menu = new wxMenu();
  wxMenuItem *menuItem;
  wxString title;
  bool table = false;
  bool canEdit = false;
  bool view = false;
  bool column = false;
  bool geometry = false;
  bool geometry_index = false;
  bool geometry_cached = false;
  bool index = false;
  bool trigger = false;
  bool metadata = MainFrame->CheckMetadata();
  if (MainFrame->IsConnected() == false)
    return;
  wxTreeItemId item = event.GetItem();
  SelectItem(item);
  wxPoint pt = event.GetPoint();
  if (item == Root)
    {
      CurrentItem = NULL;
      menuItem = new wxMenuItem(menu, Tree_Refresh, wxT("&Refresh"));
      menu->Append(menuItem);
      menu->AppendSeparator();
      menuItem = new wxMenuItem(menu, Tree_NewTable, wxT("Create New &Table"));
      menu->Append(menuItem);
      menuItem = new wxMenuItem(menu, Tree_NewView, wxT("Create New &View"));
      menu->Append(menuItem);
      PopupMenu(menu, pt);
      return;
    }
  MyObject *obj = (MyObject *) GetItemData(item);
  if (obj == NULL)
    {
      CurrentItem = NULL;
      menuItem = new wxMenuItem(menu, Tree_Refresh, wxT("&Refresh"));
      menu->Append(menuItem);
      menu->AppendSeparator();
      menuItem = new wxMenuItem(menu, Tree_NewTable, wxT("Create New &Table"));
      menu->Append(menuItem);
      menuItem = new wxMenuItem(menu, Tree_NewView, wxT("Create New &View"));
      menu->Append(menuItem);
      PopupMenu(menu, pt);
      return;
    }
  switch (obj->GetType())
    {
      case MY_VTABLE:
      case MY_TABLE:
        table = true;
        break;
      case MY_VIEW:
        view = true;
        break;
      case MY_COLUMN:
        column = true;
        break;
      case MY_GEOMETRY:
        geometry = true;
        break;
      case MY_GEOMETRY_INDEX:
        geometry_index = true;
        break;
      case MY_GEOMETRY_CACHED:
        geometry_cached = true;
        break;
      case MY_INDEX:
        index = true;
        break;
      case MY_TRIGGER:
        trigger = true;
        break;
    };
  if (obj->GetType() == MY_TABLE)
    canEdit = true;
  CurrentItem = item;
  menuItem = new wxMenuItem(menu, Tree_Refresh, wxT("&Refresh"));
  menu->Append(menuItem);
  if (table == true)
    {
      wxString title = wxT("Table: \"") + obj->GetName() + wxT("\"");
      menu->SetTitle(title);
      menu->AppendSeparator();
      menuItem = new wxMenuItem(menu, Tree_NewTable, wxT("Create New &Table"));
      menu->Append(menuItem);
      menuItem = new wxMenuItem(menu, Tree_NewView, wxT("Create New &View"));
      menu->Append(menuItem);
      menu->AppendSeparator();
      if (canEdit == true)
        {
          menuItem = new wxMenuItem(menu, Tree_Edit, wxT("&Edit table rows"));
          menu->Append(menuItem);
      } else
        {
          menuItem = new wxMenuItem(menu, Tree_Select, wxT("&Query table"));
          menu->Append(menuItem);
        }
      menuItem = new wxMenuItem(menu, Tree_Show, wxT("&Show columns"));
      menu->Append(menuItem);
      menuItem =
        new wxMenuItem(menu, Tree_ShowSql, wxT("&Show CREATE statement"));
      menu->Append(menuItem);
      menu->AppendSeparator();
      menuItem = new wxMenuItem(menu, Tree_NewColumn, wxT("Add New &Column"));
      menu->Append(menuItem);
      menuItem = new wxMenuItem(menu, Tree_Rename, wxT("&Rename table"));
      menu->Append(menuItem);
      menuItem = new wxMenuItem(menu, Tree_Drop, wxT("&Drop table"));
      menu->Append(menuItem);
      menu->AppendSeparator();
      menuItem = new wxMenuItem(menu, Tree_NewIndex, wxT("Create New &Index"));
      menu->Append(menuItem);
      menuItem =
        new wxMenuItem(menu, Tree_NewTrigger, wxT("Create New &Trigger"));
      menu->Append(menuItem);
      menu->AppendSeparator();
      menuItem =
        new wxMenuItem(menu, Tree_DumpTxtTab, wxT("Export as &Txt/Tab"));
      menu->Append(menuItem);
      menuItem = new wxMenuItem(menu, Tree_DumpCsv, wxT("Export as &CSV"));
      menu->Append(menuItem);
      menuItem = new wxMenuItem(menu, Tree_DumpHtml, wxT("Export as &HTML"));
      menu->Append(menuItem);
    }
  if (view == true)
    {
      wxString title = wxT("View: \"") + obj->GetName() + wxT("\"");
      menu->SetTitle(title);
      menu->AppendSeparator();
      menuItem = new wxMenuItem(menu, Tree_NewTable, wxT("Create New &Table"));
      menu->Append(menuItem);
      menuItem = new wxMenuItem(menu, Tree_NewView, wxT("Create New &View"));
      menu->Append(menuItem);
      menu->AppendSeparator();
      menuItem = new wxMenuItem(menu, Tree_Select, wxT("&Query view"));
      menu->Append(menuItem);
      menuItem = new wxMenuItem(menu, Tree_Show, wxT("&Show columns"));
      menu->Append(menuItem);
      menuItem =
        new wxMenuItem(menu, Tree_ShowSql, wxT("&Show CREATE statement"));
      menu->Append(menuItem);
      menu->AppendSeparator();
      menuItem = new wxMenuItem(menu, Tree_Drop, wxT("&Drop view"));
      menu->Append(menuItem);
      menu->AppendSeparator();
      menuItem =
        new wxMenuItem(menu, Tree_DumpTxtTab, wxT("Export as &Txt/Tab"));
      menu->Append(menuItem);
      menuItem = new wxMenuItem(menu, Tree_DumpCsv, wxT("Export as &CSV"));
      menu->Append(menuItem);
      menuItem = new wxMenuItem(menu, Tree_DumpHtml, wxT("Export as &HTML"));
      menu->Append(menuItem);
    }
  if (column == true)
    {
      wxString title =
        wxT("Column: \"") + obj->GetName() + wxT("\".\"") + obj->GetColumn() +
        wxT("\"");
      menu->SetTitle(title);
      menuItem =
        new wxMenuItem(menu, Tree_CheckGeometry, wxT("&Check geometries"));
      menu->Append(menuItem);
      menuItem = new wxMenuItem(menu, Tree_SetSrid, wxT("&Set SRID"));
      menu->Append(menuItem);
      if (metadata == true)
        {
          menu->AppendSeparator();
          menuItem =
            new wxMenuItem(menu, Tree_Recover, wxT("&Recover geometry column"));
          menu->Append(menuItem);
        }
    }
  if (geometry == true)
    {
      wxString title =
        wxT("Column: \"") + obj->GetName() + wxT("\".\"") + obj->GetColumn() +
        wxT("\"");
      menu->SetTitle(title);
      menuItem = new wxMenuItem(menu, Tree_Show, wxT("&Show Spatial Metadata"));
      menu->Append(menuItem);
      menuItem =
        new wxMenuItem(menu, Tree_CheckGeometry, wxT("&Check geometries"));
      menu->Append(menuItem);
      menu->AppendSeparator();
      menuItem =
        new wxMenuItem(menu, Tree_SpatialIndex, wxT("&Build Spatial Index"));
      menuItem->SetBitmap(wxBitmap(spatialidx_xpm));
      menu->Append(menuItem);
      menuItem = new wxMenuItem(menu, Tree_MbrCache, wxT("Build &MBR cache"));
      menuItem->SetBitmap(wxBitmap(mbrcache_xpm));
      menu->Append(menuItem);
      menu->AppendSeparator();
      menuItem =
        new wxMenuItem(menu, Tree_RebuildTriggers,
                       wxT("Rebuild Geometry &Triggers"));
      menu->Append(menuItem);
      menu->AppendSeparator();
      menuItem =
        new wxMenuItem(menu, Tree_DumpShp, wxT("Export as &Shapefile"));
      menuItem->SetBitmap(wxBitmap(dumpshp_xpm));
      menu->Append(menuItem);
    }
  if (geometry_index == true)
    {
      wxString title =
        wxT("Column: \"") + obj->GetName() + wxT("\".\"") + obj->GetColumn() +
        wxT("\"");
      menu->SetTitle(title);
      menuItem = new wxMenuItem(menu, Tree_Show, wxT("&Show Spatial Metadata"));
      menu->Append(menuItem);
      menuItem =
        new wxMenuItem(menu, Tree_CheckGeometry, wxT("&Check geometries"));
      menu->Append(menuItem);
      menu->AppendSeparator();
      menuItem =
        new wxMenuItem(menu, Tree_SpatialIndex, wxT("&Remove Spatial Index"));
      menuItem->SetBitmap(wxBitmap(kill_spindex_xpm));
      menu->Append(menuItem);
      menu->AppendSeparator();
      menuItem =
        new wxMenuItem(menu, Tree_RebuildTriggers,
                       wxT("Rebuild Geometry &Triggers"));
      menu->Append(menuItem);
      menu->AppendSeparator();
      menuItem =
        new wxMenuItem(menu, Tree_DumpShp, wxT("Export as &Shapefile"));
      menuItem->SetBitmap(wxBitmap(dumpshp_xpm));
      menu->Append(menuItem);
    }
  if (geometry_cached == true)
    {
      wxString title =
        wxT("Column: \"") + obj->GetName() + wxT("\".\"") + obj->GetColumn() +
        wxT("\"");
      menu->SetTitle(title);
      menuItem = new wxMenuItem(menu, Tree_Show, wxT("&Show Spatial Metadata"));
      menu->Append(menuItem);
      menuItem =
        new wxMenuItem(menu, Tree_CheckGeometry, wxT("&Check geometries"));
      menu->Append(menuItem);
      menu->AppendSeparator();
      menuItem = new wxMenuItem(menu, Tree_MbrCache, wxT("&Remove MBR cache"));
      menuItem->SetBitmap(wxBitmap(kill_spindex_xpm));
      menu->Append(menuItem);
      menu->AppendSeparator();
      menuItem =
        new wxMenuItem(menu, Tree_RebuildTriggers,
                       wxT("Rebuild Geometry &Triggers"));
      menu->Append(menuItem);
      menu->AppendSeparator();
      menuItem =
        new wxMenuItem(menu, Tree_DumpShp, wxT("Export as &Shapefile"));
      menuItem->SetBitmap(wxBitmap(dumpshp_xpm));
      menu->Append(menuItem);
    }
  if (index == true)
    {
      wxString title = wxT("Index: \"") + obj->GetName() + wxT("\"");
      menu->SetTitle(title);
      menu->AppendSeparator();
      menuItem = new wxMenuItem(menu, Tree_Show, wxT("&Show index"));
      menu->Append(menuItem);
      menu->AppendSeparator();
      menuItem = new wxMenuItem(menu, Tree_Drop, wxT("&Drop index"));
      menu->Append(menuItem);
    }
  if (trigger == true)
    {
      wxString title = wxT("Trigger: \"") + obj->GetName() + wxT("\"");
      menu->SetTitle(title);
      menu->AppendSeparator();
      menuItem = new wxMenuItem(menu, Tree_Show, wxT("&Show trigger"));
      menu->Append(menuItem);
      menu->AppendSeparator();
      menuItem = new wxMenuItem(menu, Tree_Drop, wxT("&Drop trigger"));
      menu->Append(menuItem);
    }
  PopupMenu(menu, pt);
}

void MyTableTree::OnCmdNewTable(wxCommandEvent & event)
{
//
// menu event - new table creation required
//
  wxString sql;
  sql = wxT("CREATE TABLE ...table-name... (\n");
  sql += wxT("...column1,\n...column2,\n...columnN)");
  MainFrame->SetSql(sql, false);
}

void MyTableTree::OnCmdNewView(wxCommandEvent & event)






























{
//
// menu event - new view creation required
//
  wxString sql;
  sql = wxT("CREATE VIEW ...view-name... AS\n");
  sql += wxT("SELECT ...sql-select-statement...");
  MainFrame->SetSql(sql, false);
}


void MyTableTree::OnCmdNewIndex(wxCommandEvent & event)
{
//
// menu event - new index creation required
//
  wxString sql;
  MyObject *obj = (MyObject *) GetItemData(CurrentItem);
  if (obj == NULL)
    return;
  if (obj->GetType() == MY_TABLE)
    {
      sql = wxT("CREATE [ UNIQUE ] INDEX ...index-name...\nON ");
      sql += obj->GetName();
      sql += wxT("\n(\n...column1, column2, columnN...\n)");
      MainFrame->SetSql(sql, false);
    }
}


void MyTableTree::OnCmdNewTrigger(wxCommandEvent & event)
{
//
// menu event - new trigger creation required
//
  wxString sql;
  MyObject *obj = (MyObject *) GetItemData(CurrentItem);
  if (obj == NULL)
    return;
  if (obj->GetType() == MY_TABLE)
    {
      sql = wxT("CREATE TRIGGER ...trigger-name...\n[ BEFORE | AFTER ]\n");
      sql += wxT("[ INSERT | UPDATE | DELETE ]\nON ");
      sql += obj->GetName();
      sql += wxT("\n...sql-statement...");
      MainFrame->SetSql(sql, false);
    }
}


void MyTableTree::OnCmdNewColumn(wxCommandEvent & event)
{
//
// menu event - new column creation required
//
  wxString sql;
  MyObject *obj = (MyObject *) GetItemData(CurrentItem);
  if (obj == NULL)
    return;
  if (obj->GetType() == MY_TABLE)
    {
      sql = wxT("ALTER TABLE \"");
      sql += obj->GetName();
      sql += wxT("\"\nADD COLUMN ...column-name column-type...");
      MainFrame->SetSql(sql, false);
    }
}


void MyTableTree::OnCmdSelect(wxCommandEvent & event)
{
//
// menu event - examining table rows required
//
  wxString sql;
  MyObject *obj = (MyObject *) GetItemData(CurrentItem);
  if (obj == NULL)
    return;
  sql = wxT("SELECT * FROM \"");
  sql += obj->GetName() + wxT("\"");
  MainFrame->SetSql(sql, true);
}


void MyTableTree::OnCmdShow(wxCommandEvent & event)
{
//
// menu event - examining full infos required
//
  wxString sql;
  MyObject *obj = (MyObject *) GetItemData(CurrentItem);
  if (obj == NULL)
    return;
  if (obj->GetType() == MY_TABLE || obj->GetType() == MY_VTABLE
      || obj->GetType() == MY_VIEW)
    {
      sql = wxT("PRAGMA table_info(\"");
      sql += obj->GetName();
      sql += wxT("\")");
    }
  if (obj->GetType() == MY_GEOMETRY || obj->GetType() == MY_GEOMETRY_INDEX
      || obj->GetType() == MY_GEOMETRY_CACHED)
    {
      sql = wxT("SELECT * FROM geom_cols_ref_sys\n");
      sql += wxT("WHERE f_table_name = '");
      sql += obj->GetName();
      sql += wxT("'\nAND f_geometry_column = '");
      sql += obj->GetColumn();
      sql += wxT("'");
    }
  if (obj->GetType() == MY_INDEX)
    {
      sql = wxT("PRAGMA index_info(\"");
      sql += obj->GetName();
      sql += wxT("\")");
    }
  if (obj->GetType() == MY_TRIGGER)
    {
      sql =
        wxT
        ("SELECT sql FROM sqlite_master\nWHERE type = 'trigger' AND name = '");
      sql += obj->GetName();
      sql += wxT("'");
    }
  if (sql.Len() < 1)
    return;
  MainFrame->SetSql(sql, true);
}


void MyTableTree::OnCmdDrop(wxCommandEvent & event)
{
//
// menu event - dropping some object required
//
  wxString sql;
  wxString msg;
  char *errMsg = NULL;
  int ret;
  sqlite3 *sqlite = MainFrame->GetSqlite();
  MyObject *obj = (MyObject *) GetItemData(CurrentItem);
  if (obj == NULL)
    return;
  if (obj->GetType() == MY_TABLE || obj->GetType() == MY_VTABLE)
    {
      bool metadata = MainFrame->CheckMetadata();
      if (metadata == true)
        {
          // SpatialMetadata exists; we must check for geometry_columns and SpatialIndices as well
          char *errMsg = NULL;
          int ret;
          int i;
          char **results;
          int rows;
          int columns;
          sqlite3 *sqlite = MainFrame->GetSqlite();
          sql = wxT("SELECT f_geometry_column, spatial_index_enabled ");
          sql += wxT("FROM geometry_columns WHERE f_table_name = '");
          sql += obj->GetName();
          sql += wxT("'");

          ret =
            sqlite3_get_table(sqlite, sql.ToUTF8(), &results, &rows, &columns,
                              &errMsg);
          if (ret != SQLITE_OK)
            {
              wxMessageBox(wxT("SQLite SQL error: ") +
                           wxString::FromUTF8(errMsg), wxT("spatialite-gui"),
                           wxOK | wxICON_ERROR, this);

              sqlite3_free(errMsg);
              return;
            }
          sql = wxT("BEGIN; ");
          if (rows < 1)
            ;
          else
            {
              for (i = 1; i <= rows; i++)
                {
                  if (results[(i * columns) + 0])
                    {

                      const char *column = results[(i * columns) + 0];
                      wxString geo_column = wxString::FromUTF8(column);

                      if (atoi(results[(i * columns) + 1]))
                        {
                          // dropping the SpatialIndex

                          sql += wxT("DROP TABLE IF EXISTS \"idx_");
                          sql += obj->GetName();
                          sql += wxT("_");
                          sql += geo_column;
                          sql += wxT("\"; ");
                          // dropping the MBR cache

                          sql += wxT("DROP TABLE IF EXISTS \"cache_");
                          sql += obj->GetName();
                          sql += wxT("_");
                          sql += geo_column;
                          sql += wxT("\"; ");
                        }
                      // deleting from geometry_columns
                      sql +=
                        wxT
                        ("DELETE FROM geometry_columns\n    WHERE f_table_name = '");
                      sql += obj->GetName();


                      sql += wxT("'\n        AND f_geometry_column = '");
                      sql += geo_column;
                      sql += wxT("'; ");
                    }
                }
            }
          sqlite3_free_table(results);
          sql += wxT("DROP TABLE IF EXISTS \"");
          sql += obj->GetName();
          sql += wxT("\"; COMMIT;");

      } else
        {
          // there are no SpatialMetadata at all; we'll simply try to drop the table
          sql = wxT("BEGIN; ");
          sql += wxT("DROP TABLE IF EXISTS \"");
          sql += obj->GetName();
          sql += wxT("\"; COMMIT;");
        }
      msg = wxT("Do you really intend to drop the Table named: \"");
      msg += obj->GetName();
      msg += wxT("\"\n[and any other related object] ?");
    }
  if (obj->GetType() == MY_VIEW)
    {
      msg = wxT("Do you really intend to drop the View named: \"");
      msg += obj->GetName();
      msg += wxT("\" ?");
      sql = wxT("BEGIN; DROP VIEW IF EXISTS \"");
      sql += obj->GetName();
      sql += wxT("\"; COMMIT;");
    }
  if (obj->GetType() == MY_INDEX)
    {
      sql = wxT("BEGIN; DROP INDEX IF EXISTS \"");
      sql += obj->GetName();
      sql += wxT("\"; COMMIT;");
    }
  if (obj->GetType() == MY_TRIGGER)
    {
      msg = wxT("Do you really intend to drop the Index named: \"");
      msg += obj->GetName();
      msg += wxT("\" ?");
      sql = wxT("BEGIN; DROP TRIGGER IF EXISTS \"");
      sql += obj->GetName();
      sql += wxT("\"; COMMIT;");
    }
  if (sql.Len() < 1)
    return;
  wxMessageDialog confirm(this, msg, wxT("Confirming DROP"),
                          wxOK | wxCANCEL | wxICON_QUESTION);
  ret = confirm.ShowModal();
  if (ret != wxID_OK)
    return;
  ::wxBeginBusyCursor();
  ret = sqlite3_exec(sqlite, sql.ToUTF8(), NULL, NULL, &errMsg);
  if (ret != SQLITE_OK)
    {
      wxMessageBox(wxT("SQLite SQL error: ") + wxString::FromUTF8(errMsg),

                   wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
      sqlite3_free(errMsg);
      ::wxEndBusyCursor();
      goto rollback;
    }
  ::wxEndBusyCursor();
  wxMessageBox(wxT("Selected object '") + obj->GetName() +
               wxT("' was successfully removed"), wxT("spatialite-gui"),
               wxOK | wxICON_INFORMATION, this);

  MainFrame->InitTableTree();
  return;
rollback:
  ret = sqlite3_exec(sqlite, "ROLLBACK", NULL, NULL, &errMsg);
  if (ret != SQLITE_OK)
    {
      wxMessageBox(wxT("SQLite SQL error: ") + wxString::FromUTF8(errMsg),

                   wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
      sqlite3_free(errMsg);
      ::wxEndBusyCursor();
      return;
    }
  ::wxEndBusyCursor();
  wxMessageBox(wxT
               ("An error occurred\n\na ROLLBACK was automatically performed"),
               wxT("spatialite-gui"), wxOK | wxICON_WARNING, this);
}


void MyTableTree::OnCmdRename(wxCommandEvent & event)
{
//
// menu event - table renaming required
//
  wxString sql;
  MyObject *obj = (MyObject *) GetItemData(CurrentItem);
  if (obj == NULL)
    return;
  if (obj->GetType() == MY_TABLE || obj->GetType() == MY_VTABLE)
    {
      sql = wxT("ALTER TABLE \"");
      sql += obj->GetName();
      sql += wxT("\"\nRENAME TO ...new-table-name...");
      MainFrame->SetSql(sql, false);
    }
}


void MyTableTree::OnCmdRefresh(wxCommandEvent & event)
{
//
// menu event - refreshing the Tree
//
  MainFrame->InitTableTree();
}

void MyTableTree::OnCmdRecover(wxCommandEvent & event)
{
//
// menu event - Recover Geometry
//
  char *errMsg = NULL;
  int ret;
  wxString sql;
  int i;
  char **results;
  int rows;
  int columns;
  int retval = 0;
  int srid = -1;
  char dummy[128];
  wxString type;
  RecoverDialog dlg;
  sqlite3 *sqlite = MainFrame->GetSqlite();
  MyObject *obj = (MyObject *) GetItemData(CurrentItem);
  if (obj == NULL)
    return;
  if (obj->GetType() == MY_COLUMN)
    {
      // trying to recover a geometry column
      if (MainFrame->CheckMetadata() == false)
        {
          wxMessageBox(wxT
                       ("Missing Spatial Metadata tables\n\ntry to run the 'init_spatialite.sql' script ..."),
                       wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
          return;
        }
      dlg.Create(MainFrame, obj->GetName(), obj->GetColumn());
      ret = dlg.ShowModal();
      if (ret == wxID_OK)
        {
          srid = dlg.GetSrid();
          type = dlg.GetType();
          ::wxBeginBusyCursor();
          ret = sqlite3_exec(sqlite, "BEGIN", NULL, NULL, &errMsg);
          if (ret != SQLITE_OK)
            {
              wxMessageBox(wxT("SQLite SQL error: ") +
                           wxString::FromUTF8(errMsg), wxT("spatialite-gui"),
                           wxOK | wxICON_ERROR, this);
              sqlite3_free(errMsg);
              ::wxEndBusyCursor();
              return;
            }
          sql = wxT("SELECT RecoverGeometryColumn('");
          sql += obj->GetName();
          sql += wxT("', '");
          sql += obj->GetColumn();
          sprintf(dummy, "', %d, '", srid);
          sql += wxString::FromUTF8(dummy);
          sql += type;
          sql += wxT("', 2)");
          ret =
            sqlite3_get_table(sqlite, sql.ToUTF8(), &results, &rows, &columns,
                              &errMsg);
          if (ret != SQLITE_OK)
            {
              wxMessageBox(wxT("SQLite SQL error: ") +
                           wxString::FromUTF8(errMsg), wxT("spatialite-gui"),
                           wxOK | wxICON_ERROR, this);
              sqlite3_free(errMsg);
              goto rollback;
            }
          if (rows < 1)
            ;
          else
            {
              for (i = 1; i <= rows; i++)
                {
                  if (results[(i * columns) + 0])
                    retval = atoi(results[(i * columns) + 0]);
                }
            }
          sqlite3_free_table(results);
          if (!retval)
            goto rollback;
          ret = sqlite3_exec(sqlite, "COMMIT", NULL, NULL, &errMsg);
          if (ret != SQLITE_OK)
            {
              wxMessageBox(wxT("SQLite SQL error: ") +
                           wxString::FromUTF8(errMsg), wxT("spatialite-gui"),
                           wxOK | wxICON_ERROR, this);
              sqlite3_free(errMsg);
              ::wxEndBusyCursor();
              return;
            }
          ::wxEndBusyCursor();
          wxMessageBox(wxT("Geometry column \"") + obj->GetName() +
                       wxT(".") + obj->GetColumn() +
                       wxT("\" was successfully recovered"),
                       wxT("spatialite-gui"), wxOK | wxICON_INFORMATION, this);
        }
    }
  return;
rollback:
  ret = sqlite3_exec(sqlite, "ROLLBACK", NULL, NULL, &errMsg);
  if (ret != SQLITE_OK)
    {
      wxMessageBox(wxT("SQLite SQL error: ") + wxString::FromUTF8(errMsg),
                   wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
      sqlite3_free(errMsg);
      ::wxEndBusyCursor();
      return;
    }
  ::wxEndBusyCursor();
  wxMessageBox(wxT
               ("Geometry column doesn't satisfies required constraints\n\na ROLLBACK was automatically performed"),
               wxT("spatialite-gui"), wxOK | wxICON_WARNING, this);
}

void MyTableTree::OnCmdShowSql(wxCommandEvent & event)
{
//
// menu event - Showing CREATE TABLE statement
//
  wxString sql;
  MyObject *obj = (MyObject *) GetItemData(CurrentItem);
  if (obj == NULL)
    return;
  if (obj->GetType() == MY_TABLE || obj->GetType() == MY_VTABLE)
    {
      sql =
        wxT("SELECT sql FROM sqlite_master\nWHERE type = 'table' AND name = '");
      sql += obj->GetName();
      sql += wxT("'");
      MainFrame->SetSql(sql, true);
    }
  if (obj->GetType() == MY_VIEW)
    {
      sql =
        wxT("SELECT sql FROM sqlite_master\nWHERE type = 'view' AND name = '");
      sql += obj->GetName();
      sql += wxT("'");
      MainFrame->SetSql(sql, true);
    }
}

void MyTableTree::OnCmdSpatialIndex(wxCommandEvent & event)
{
//
// menu event - Spatial Index creation-destruction
//
  char *errMsg = NULL;
  int ret;
  wxString sql;
  wxString msg;
  int i;
  char **results;
  int rows;
  int columns;
  int retval = 0;
  sqlite3 *sqlite = MainFrame->GetSqlite();
  MyObject *obj = (MyObject *) GetItemData(CurrentItem);
  if (obj == NULL)
    return;
  if (obj->GetType() == MY_GEOMETRY)
    {
      // creating the Spatial Index
      ::wxBeginBusyCursor();
      ret = sqlite3_exec(sqlite, "BEGIN", NULL, NULL, &errMsg);
      if (ret != SQLITE_OK)
        {
          wxMessageBox(wxT("SQLite SQL error: ") + wxString::FromUTF8(errMsg),
                       wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
          sqlite3_free(errMsg);
          ::wxEndBusyCursor();
          return;
        }
      sql = wxT("SELECT CreateSpatialIndex('");
      sql += obj->GetName();
      sql += wxT("', '");
      sql += obj->GetColumn();
      sql += wxT("')");
      ret =
        sqlite3_get_table(sqlite, sql.ToUTF8(), &results, &rows, &columns,
                          &errMsg);
      if (ret != SQLITE_OK)
        {
          wxMessageBox(wxT("SQLite SQL error: ") + wxString::FromUTF8(errMsg),
                       wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
          sqlite3_free(errMsg);
          goto rollback;
        }
      if (rows < 1)
        ;
      else
        {
          for (i = 1; i <= rows; i++)
            {
              if (results[(i * columns) + 0])
                retval = atoi(results[(i * columns) + 0]);
            }
        }
      sqlite3_free_table(results);
      if (!retval)
        goto rollback;
      ret = sqlite3_exec(sqlite, "COMMIT", NULL, NULL, &errMsg);
      if (ret != SQLITE_OK)
        {
          wxMessageBox(wxT("SQLite SQL error: ") + wxString::FromUTF8(errMsg),
                       wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
          sqlite3_free(errMsg);
          ::wxEndBusyCursor();
          return;
        }
      ::wxEndBusyCursor();
      wxMessageBox(wxT("Spatial Index \"idx_") + obj->GetName() +
                   wxT("_") + obj->GetColumn() +
                   wxT("\" was successfully created"), wxT("spatialite-gui"),
                   wxOK | wxICON_INFORMATION, this);
      MainFrame->InitTableTree();
  } else if (obj->GetType() == MY_GEOMETRY_INDEX)
    {
      // dropping the Spatial Index
      ::wxBeginBusyCursor();
      ret = sqlite3_exec(sqlite, "BEGIN", NULL, NULL, &errMsg);
      if (ret != SQLITE_OK)
        {
          wxMessageBox(wxT("SQLite SQL error: ") + wxString::FromUTF8(errMsg),
                       wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
          sqlite3_free(errMsg);
          ::wxEndBusyCursor();
          return;
        }
      sql = wxT("SELECT DisableSpatialIndex('");
      sql += obj->GetName();
      sql += wxT("', '");
      sql += obj->GetColumn();
      sql += wxT("')");
      msg = wxT("Do you really intend to delete the SpatialIndex\n");
      msg += wxT("on column \"");
      msg += obj->GetName();
      msg += wxT("\".\"");
      msg += obj->GetColumn();
      msg += wxT("\" ?");
      wxMessageDialog confirm(this, msg, wxT("Confirming Delete Spatial Index"),
                              wxOK | wxCANCEL | wxICON_QUESTION);
      ret = confirm.ShowModal();
      if (ret != wxID_OK)
        return;
      ret =
        sqlite3_get_table(sqlite, sql.ToUTF8(), &results, &rows, &columns,
                          &errMsg);
      if (ret != SQLITE_OK)
        {
          wxMessageBox(wxT("SQLite SQL error: ") + wxString::FromUTF8(errMsg),
                       wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
          sqlite3_free(errMsg);
          goto rollback;
        }
      if (rows < 1)
        ;
      else
        {
          for (i = 1; i <= rows; i++)
            {
              if (results[(i * columns) + 0])
                retval = atoi(results[(i * columns) + 0]);
            }
        }
      sqlite3_free_table(results);
      if (!retval)
        goto rollback;
      sql = wxT("DROP TABLE IF EXISTS \"idx_");
      sql += obj->GetName();
      sql += wxT("_");
      sql += obj->GetColumn();
      sql += wxT("\"");
      ret = sqlite3_exec(sqlite, sql.ToUTF8(), NULL, NULL, &errMsg);
      if (ret != SQLITE_OK)
        {
          wxMessageBox(wxT("SQLite SQL error: ") + wxString::FromUTF8(errMsg),
                       wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
          sqlite3_free(errMsg);
          ::wxEndBusyCursor();
          return;
        }
      ret = sqlite3_exec(sqlite, "COMMIT", NULL, NULL, &errMsg);
      if (ret != SQLITE_OK)
        {
          wxMessageBox(wxT("SQLite SQL error: ") + wxString::FromUTF8(errMsg),
                       wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
          sqlite3_free(errMsg);
          ::wxEndBusyCursor();
          return;
        }
      ::wxEndBusyCursor();
      wxMessageBox(wxT("Spatial Index idx_") + obj->GetName() +
                   wxT("_") + obj->GetColumn() +
                   wxT(" was successfully removed"), wxT("spatialite-gui"),
                   wxOK | wxICON_INFORMATION, this);
      MainFrame->InitTableTree();
    }
  return;
rollback:
  ret = sqlite3_exec(sqlite, "ROLLBACK", NULL, NULL, &errMsg);
  if (ret != SQLITE_OK)
    {
      wxMessageBox(wxT("SQLite SQL error: ") + wxString::FromUTF8(errMsg),
                   wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
      sqlite3_free(errMsg);
      ::wxEndBusyCursor();
      return;
    }
  ::wxEndBusyCursor();
  wxMessageBox(wxT
               ("An error occurred\n\na ROLLBACK was automatically performed"),
               wxT("spatialite-gui"), wxOK | wxICON_WARNING, this);
}

void MyTableTree::OnCmdMbrCache(wxCommandEvent & event)
{
//
// menu event - MBR cache creation-destruction
//
  char *errMsg = NULL;
  int ret;
  wxString sql;
  wxString msg;
  int i;
  char **results;
  int rows;
  int columns;
  int retval = 0;
  sqlite3 *sqlite = MainFrame->GetSqlite();
  MyObject *obj = (MyObject *) GetItemData(CurrentItem);
  if (obj == NULL)
    return;
  if (obj->GetType() == MY_GEOMETRY)
    {
      // creating the MBR cache
      ::wxBeginBusyCursor();
      ret = sqlite3_exec(sqlite, "BEGIN", NULL, NULL, &errMsg);
      if (ret != SQLITE_OK)
        {
          wxMessageBox(wxT("SQLite SQL error: ") + wxString::FromUTF8(errMsg),
                       wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
          sqlite3_free(errMsg);
          ::wxEndBusyCursor();
          return;
        }
      sql = wxT("SELECT CreateMbrCache('");
      sql += obj->GetName();
      sql += wxT("', '");
      sql += obj->GetColumn();
      sql += wxT("')");
      ret =
        sqlite3_get_table(sqlite, sql.ToUTF8(), &results, &rows, &columns,
                          &errMsg);
      if (ret != SQLITE_OK)
        {
          wxMessageBox(wxT("SQLite SQL error: ") + wxString::FromUTF8(errMsg),
                       wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
          sqlite3_free(errMsg);
          goto rollback;
        }
      if (rows < 1)
        ;
      else
        {
          for (i = 1; i <= rows; i++)
            {
              if (results[(i * columns) + 0])
                retval = atoi(results[(i * columns) + 0]);
            }
        }
      sqlite3_free_table(results);
      if (!retval)
        goto rollback;
      ret = sqlite3_exec(sqlite, "COMMIT", NULL, NULL, &errMsg);
      if (ret != SQLITE_OK)
        {
          wxMessageBox(wxT("SQLite SQL error: ") + wxString::FromUTF8(errMsg),
                       wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
          sqlite3_free(errMsg);
          ::wxEndBusyCursor();
          return;
        }
      ::wxEndBusyCursor();
      wxMessageBox(wxT("MBR cache \"cache_") + obj->GetName() +
                   wxT("_") + obj->GetColumn() +
                   wxT("\" was successfully created"), wxT("spatialite-gui"),
                   wxOK | wxICON_INFORMATION, this);
      MainFrame->InitTableTree();
  } else if (obj->GetType() == MY_GEOMETRY_CACHED)
    {
      // dropping the MBR cache
      ::wxBeginBusyCursor();
      ret = sqlite3_exec(sqlite, "BEGIN", NULL, NULL, &errMsg);
      if (ret != SQLITE_OK)
        {
          wxMessageBox(wxT("SQLite SQL error: ") + wxString::FromUTF8(errMsg),
                       wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
          sqlite3_free(errMsg);
          ::wxEndBusyCursor();
          return;
        }
      sql = wxT("SELECT DisableSpatialIndex('");
      sql += obj->GetName();
      sql += wxT("', '");
      sql += obj->GetColumn();
      sql += wxT("')");
      msg = wxT("Do you really intend to delete the MBR cache\n");
      msg += wxT("on column \"");
      msg += obj->GetName();
      msg += wxT("\".\"");
      msg += obj->GetColumn();
      msg += wxT("\" ?");
      wxMessageDialog confirm(this, msg, wxT("Confirming Delete MBR cache"),
                              wxOK | wxCANCEL | wxICON_QUESTION);
      ret = confirm.ShowModal();
      if (ret != wxID_OK)
        return;
      ret =
        sqlite3_get_table(sqlite, sql.ToUTF8(), &results, &rows, &columns,
                          &errMsg);
      if (ret != SQLITE_OK)
        {
          wxMessageBox(wxT("SQLite SQL error: ") + wxString::FromUTF8(errMsg),
                       wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
          sqlite3_free(errMsg);
          goto rollback;
        }
      if (rows < 1)
        ;
      else
        {
          for (i = 1; i <= rows; i++)
            {
              if (results[(i * columns) + 0])
                retval = atoi(results[(i * columns) + 0]);
            }
        }
      sqlite3_free_table(results);
      if (!retval)
        goto rollback;
      sql = wxT("DROP TABLE IF EXISTS \"cache_");
      sql += obj->GetName();
      sql += wxT("_");
      sql += obj->GetColumn();
      sql += wxT("\"");
      ret = sqlite3_exec(sqlite, sql.ToUTF8(), NULL, NULL, &errMsg);
      if (ret != SQLITE_OK)
        {
          wxMessageBox(wxT("SQLite SQL error: ") + wxString::FromUTF8(errMsg),
                       wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
          sqlite3_free(errMsg);
          ::wxEndBusyCursor();
          return;
        }
      ret = sqlite3_exec(sqlite, "COMMIT", NULL, NULL, &errMsg);
      if (ret != SQLITE_OK)
        {
          wxMessageBox(wxT("SQLite SQL error: ") + wxString::FromUTF8(errMsg),
                       wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
          sqlite3_free(errMsg);
          ::wxEndBusyCursor();
          return;
        }
      ::wxEndBusyCursor();
      wxMessageBox(wxT("MBR cache \"cache_") + obj->GetName() +
                   wxT("_") + obj->GetColumn() +
                   wxT("\" was successfully removed"), wxT("spatialite-gui"),
                   wxOK | wxICON_INFORMATION, this);
      MainFrame->InitTableTree();
    }
  return;
rollback:
  ret = sqlite3_exec(sqlite, "ROLLBACK", NULL, NULL, &errMsg);
  if (ret != SQLITE_OK)
    {
      wxMessageBox(wxT("SQLite SQL error: ") + wxString::FromUTF8(errMsg),
                   wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
      sqlite3_free(errMsg);
      ::wxEndBusyCursor();
      return;
    }
  ::wxEndBusyCursor();
  wxMessageBox(wxT
               ("An error occurred\n\na ROLLBACK was automatically performed"),
               wxT("spatialite-gui"), wxOK | wxICON_WARNING, this);
}

void MyTableTree::OnCmdRebuildTriggers(wxCommandEvent & event)
{
//
// menu event - rebuilding Geometry Triggers
//
  wxString sql;
  MyObject *obj = (MyObject *) GetItemData(CurrentItem);
  if (obj == NULL)
    return;
  if (obj->GetType() == MY_COLUMN || obj->GetType() == MY_GEOMETRY
      || obj->GetType() == MY_GEOMETRY_INDEX
      || obj->GetType() == MY_GEOMETRY_CACHED)
    {
      sql = wxT("SELECT RebuildGeometryTriggers('");
      sql += obj->GetName();
      sql += wxT("', '");
      sql += obj->GetColumn();
      sql += wxT("')");
      MainFrame->SetSql(sql, true);
    }
}

void MyTableTree::OnCmdCheckGeometry(wxCommandEvent & event)
{
//
// menu event - checking geometries
//
  wxString sql;
  MyObject *obj = (MyObject *) GetItemData(CurrentItem);
  if (obj == NULL)
    return;
  if (obj->GetType() == MY_COLUMN || obj->GetType() == MY_GEOMETRY
      || obj->GetType() == MY_GEOMETRY_INDEX
      || obj->GetType() == MY_GEOMETRY_CACHED)
    {
      sql = wxT("SELECT Count(*), GeometryType(\"");
      sql += obj->GetColumn();
      sql += wxT("\"), Srid(\"");
      sql += obj->GetColumn();
      sql += wxT("\")\nFROM \"");
      sql += obj->GetName();
      sql += wxT("\"\nGROUP BY 2, 3");
      MainFrame->SetSql(sql, true);
    }
}

void MyTableTree::OnCmdSetSrid(wxCommandEvent & event)
{
//
// menu event - setting SRID for geometries
//
  SetSridDialog dlg;
  wxString sql;
  int srid;
  int oldSrid;
  int ret;
  char dummy[128];
  MyObject *obj = (MyObject *) GetItemData(CurrentItem);
  if (obj == NULL)
    return;
  if (obj->GetType() == MY_COLUMN)
    {
      dlg.Create(MainFrame, obj->GetName(), obj->GetColumn());
      ret = dlg.ShowModal();
      if (ret == wxID_OK)
        {
          srid = dlg.GetSrid();
          oldSrid = dlg.GetOldSrid();
          sql = wxT("UPDATE ");
          sql += obj->GetName();
          sql += wxT(" SET ");
          sql += obj->GetColumn();
          sql += wxT(" = SetSrid(");
          sql += obj->GetColumn();
          sprintf(dummy, ", %d)", srid);
          sql += wxString::FromUTF8(dummy);
          sql += wxT("\nWHERE Srid(");
          sql += obj->GetColumn();
          sprintf(dummy, ") = %d", oldSrid);
          sql += wxString::FromUTF8(dummy);
          MainFrame->SetSql(sql, true);
        }
    }
}

void MyTableTree::OnCmdDumpShp(wxCommandEvent & event)
{
//
// menu event - dumping as Shapefile
//
  int ret;
  wxString path;
  wxString lastDir;
  MyObject *obj = (MyObject *) GetItemData(CurrentItem);
  if (obj == NULL)
    return;
  if (obj->GetType() == MY_GEOMETRY || obj->GetType() == MY_GEOMETRY_INDEX
      || obj->GetType() == MY_GEOMETRY_CACHED)
    {
      wxFileDialog *fileDialog = new wxFileDialog(this, wxT("Dump Shapefile"),
                                                  wxT(""), wxT("shapefile.shp"),
                                                  wxT
                                                  ("Shapefile (*.shp)|*.shp|All files (*.*)|*.*"),
                                                  wxFD_SAVE |
                                                  wxFD_OVERWRITE_PROMPT,
                                                  wxDefaultPosition,
                                                  wxDefaultSize,
                                                  wxT("filedlg"));
      lastDir = MainFrame->GetLastDirectory();
      if (lastDir.Len() >= 1)
        fileDialog->SetDirectory(lastDir);
      ret = fileDialog->ShowModal();
      if (ret == wxID_OK)
        {

          wxFileName file(fileDialog->GetPath());
          path = file.GetPath();
          path += file.GetPathSeparator();
          path += file.GetName();
          lastDir = file.GetPath();
          if (MainFrame->IsSetAskCharset() == false)
            {
              // using the default output charset
              MainFrame->SetLastDirectory(lastDir);
              ::wxBeginBusyCursor();
              MainFrame->DumpShapefile(path, obj->GetName(), obj->GetColumn(),
                                       MainFrame->GetDefaultCharset());
              ::wxEndBusyCursor();
          } else
            {
              // asking the charset to be used
              DumpShpDialog dlg;
              dlg.Create(MainFrame, path, obj->GetName(), obj->GetColumn(),
                         MainFrame->GetDefaultCharset());
              ret = dlg.ShowModal();
              if (ret == wxID_OK)
                {
                  MainFrame->SetLastDirectory(lastDir);
                  ::wxBeginBusyCursor();
                  MainFrame->DumpShapefile(path, obj->GetName(),
                                           obj->GetColumn(), dlg.GetCharset());
                  ::wxEndBusyCursor();
                }
            }
        }
    }
}

void MyTableTree::OnCmdDumpTxtTab(wxCommandEvent & event)
{
//
// menu event - dumping as TxtTab
//
  int ret;
  wxString path;
  wxString lastDir;
  wxString target;
  MyObject *obj = (MyObject *) GetItemData(CurrentItem);
  if (obj == NULL)
    return;
  wxFileDialog *fileDialog = new wxFileDialog(this, wxT("Dump Txt/Tab file"),
                                              wxT(""), wxT("table.txt"),
                                              wxT
                                              ("File Txt/Tab (*.txt)|*.txt|All files (*.*)|*.*"),
                                              wxFD_SAVE | wxFD_OVERWRITE_PROMPT,
                                              wxDefaultPosition,
                                              wxDefaultSize, wxT("filedlg"));
  lastDir = MainFrame->GetLastDirectory();
  if (lastDir.Len() >= 1)
    fileDialog->SetDirectory(lastDir);
  ret = fileDialog->ShowModal();
  if (ret == wxID_OK)
    {
      wxFileName file(fileDialog->GetPath());
      path = file.GetPath();
      path += file.GetPathSeparator();
      path += file.GetName();
      path += wxT(".txt");
      lastDir = file.GetPath();
      if (MainFrame->IsSetAskCharset() == false)
        {
          // using the default output charset
          MainFrame->SetLastDirectory(lastDir);
          ::wxBeginBusyCursor();
          MainFrame->DumpTxtTab(path, obj->GetName(),
                                MainFrame->GetDefaultCharset());
          ::wxEndBusyCursor();
      } else
        {
          // asking the charset to be used
          DumpTxtDialog dlg;
          target = wxT("TXT / TAB");
          dlg.Create(MainFrame, path, target, MainFrame->GetDefaultCharset());
          ret = dlg.ShowModal();
          if (ret == wxID_OK)
            {
              MainFrame->SetLastDirectory(lastDir);
              ::wxBeginBusyCursor();
              MainFrame->DumpTxtTab(path, obj->GetName(), dlg.GetCharset());
              ::wxEndBusyCursor();
            }
        }
    }
}

void MyTableTree::OnCmdDumpCsv(wxCommandEvent & event)
{
//
// menu event - dumping as CSV
//
  int ret;
  wxString path;
  wxString lastDir;
  wxString target;
  MyObject *obj = (MyObject *) GetItemData(CurrentItem);
  if (obj == NULL)
    return;
  wxFileDialog *fileDialog = new wxFileDialog(this, wxT("Dump CSV file"),
                                              wxT(""), wxT("table.csv"),
                                              wxT
                                              ("File CSV (*.csv)|*.csv|All files (*.*)|*.*"),
                                              wxFD_SAVE | wxFD_OVERWRITE_PROMPT,
                                              wxDefaultPosition,
                                              wxDefaultSize,
                                              wxT("filedlg"));
  lastDir = MainFrame->GetLastDirectory();
  if (lastDir.Len() >= 1)
    fileDialog->SetDirectory(lastDir);
  ret = fileDialog->ShowModal();
  if (ret == wxID_OK)
    {
      wxFileName file(fileDialog->GetPath());
      path = file.GetPath();
      path += file.GetPathSeparator();
      path += file.GetName();
      path += wxT(".csv");
      lastDir = file.GetPath();
      if (MainFrame->IsSetAskCharset() == false)
        {
          // using the default output charset
          MainFrame->SetLastDirectory(lastDir);
          ::wxBeginBusyCursor();
          MainFrame->DumpCsv(path, obj->GetName(),
                             MainFrame->GetDefaultCharset());
          ::wxEndBusyCursor();
      } else
        {
          // asking the charset to be used
          DumpTxtDialog dlg;
          target = wxT("CSV");
          dlg.Create(MainFrame, path, target, MainFrame->GetDefaultCharset());
          ret = dlg.ShowModal();
          if (ret == wxID_OK)
            {
              MainFrame->SetLastDirectory(lastDir);
              ::wxBeginBusyCursor();
              MainFrame->DumpCsv(path, obj->GetName(), dlg.GetCharset());
              ::wxEndBusyCursor();
            }
        }
    }
}

void MyTableTree::OnCmdDumpHtml(wxCommandEvent & event)
{
//
// menu event - dumping as Html
//
  int ret;
  wxString path;
  wxString lastDir;
  wxString target;
  MyObject *obj = (MyObject *) GetItemData(CurrentItem);
  if (obj == NULL)
    return;
  wxFileDialog *fileDialog = new wxFileDialog(this, wxT("Dump HTML file"),
                                              wxT(""), wxT("table.html"),
                                              wxT
                                              ("HTML web page (*.html)|*.html|All files (*.*)|*.*"),
                                              wxFD_SAVE | wxFD_OVERWRITE_PROMPT,
                                              wxDefaultPosition,
                                              wxDefaultSize,
                                              wxT("filedlg"));
  lastDir = MainFrame->GetLastDirectory();
  if (lastDir.Len() >= 1)
    fileDialog->SetDirectory(lastDir);
  ret = fileDialog->ShowModal();
  if (ret == wxID_OK)
    {
      wxFileName file(fileDialog->GetPath());
      path = file.GetPath();
      path += file.GetPathSeparator();
      path += file.GetName();
      path += wxT(".html");
      lastDir = file.GetPath();
      if (MainFrame->IsSetAskCharset() == false)
        {
          // using the default output charset
          MainFrame->SetLastDirectory(lastDir);
          ::wxBeginBusyCursor();
          MainFrame->DumpHtml(path, obj->GetName(),
                              MainFrame->GetDefaultCharset());
          ::wxEndBusyCursor();
      } else
        {
          // asking the charset to be used
          DumpTxtDialog dlg;
          target = wxT("HTML");
          dlg.Create(MainFrame, path, target, MainFrame->GetDefaultCharset());
          ret = dlg.ShowModal();
          if (ret == wxID_OK)
            {
              MainFrame->SetLastDirectory(lastDir);
              ::wxBeginBusyCursor();
              MainFrame->DumpHtml(path, obj->GetName(), dlg.GetCharset());
              ::wxEndBusyCursor();
            }
        }
    }
}

void MyTableTree::OnCmdEdit(wxCommandEvent & event)
{
//
// menu event - editing row valuew
//
  char **results;
  int rows;
  int columns;
  int i;
  char *errMsg = NULL;
  wxString sql;
  char *column;
  char *type;
  int pk = 0;
  int pb = 0;
  int primaryKeys[1024];
  int blobCols[1024];
  for (i = 0; i < 1024; i++)
    {
      primaryKeys[i] = -1;
      blobCols[i] = -1;
    }
  primaryKeys[pk++] = 0;
  MyObject *obj = (MyObject *) GetItemData(CurrentItem);
  if (obj == NULL)
    return;
  sql = wxT("PRAGMA table_info(\"");
  sql += obj->GetName();
  sql += wxT("\")");
  int ret = sqlite3_get_table(MainFrame->GetSqlite(), sql.ToUTF8(), &results,
                              &rows, &columns, &errMsg);
  if (ret != SQLITE_OK)
    {
      wxMessageBox(wxT("SQLite SQL error: ") + wxString::FromUTF8(errMsg),
                   wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
      sqlite3_free(errMsg);
      return;
    }
  sql = wxT("");
  if (rows < 1)
    ;
  else
    {
      sql = wxT("SELECT ROWID");
      for (i = 1; i <= rows; i++)
        {
          column = results[(i * columns) + 1];
          sql += wxT(", \"");
          sql += wxString::FromUTF8(column);
          sql += wxT("\"");
          type = results[(i * columns) + 2];
          if (strcasecmp(type, "BLOB") == 0)
            blobCols[pb++] = i;
          if (atoi(results[(i * columns) + 5]) == 0)
            ;
          else
            primaryKeys[pk++] = i;
        }
    }
  sqlite3_free_table(results);
  if (sql.Len() < 1)
    return;
  sql += wxT("\nFROM \"");
  sql += obj->GetName();
  sql += wxT("\"\nORDER BY ROWID");
  MainFrame->EditTable(sql, primaryKeys, blobCols, obj->GetName());
}













































Changes to TextCsv.cpp.

1
2
3
4
5
6
7
8
9
10
11
12
..
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
/*
/ TextCsv.cpp
/ methods related to CSV/TXT loading 
/
/ version 1.1, 2008 September 13
/
/ Author: Sandro Furieri a-furieri@lqt.it
/
/ Copyright (C) 2008  Alessandro Furieri
/
/    This program is free software: you can redistribute it and/or modify
/    it under the terms of the GNU General Public License as published by
................................................................................
#define VRTTXT_TEXT		1
#define VRTTXT_INTEGER	2
#define VRTTXT_DOUBLE	3

struct row_buffer
{
/* a complete row */
    int n_cells;		/* how many cells are stored into this line */
    char **cells;		/* the cells array */
    struct row_buffer *next;	/* pointer for linked list */
};

struct text_buffer
{
    int max_n_cells;		/* the maximun cell index */
    char **titles;		/* the column titles array */
    char *types;		/* the column types array */
    int n_rows;			/* the number of rows */
    struct row_buffer **rows;	/* the rows array */
    struct row_buffer *first;	/* pointers to build a linked list of rows */
    struct row_buffer *last;
};

static void
text_insert_row (struct text_buffer *text, char **fields, int max_cell)
{
/* inserting a row into the text buffer struct */
    int i;
    struct row_buffer *row =
	(struct row_buffer *) malloc (sizeof (struct row_buffer));
    row->n_cells = max_cell + 1;
    if (max_cell < 0)
	row->cells = NULL;
    else
      {
	  row->cells = (char **) malloc (sizeof (char *) * (max_cell + 1));
	  for (i = 0; i < row->n_cells; i++)
	    {
		/* setting cell values */
		*(row->cells + i) = *(fields + i);
	    }
      }
    row->next = NULL;
/* inserting the row into the linked list */
    if (!(text->first))
	text->first = row;
    if (text->last)
	text->last->next = row;
    text->last = row;
}

static struct text_buffer *
text_buffer_alloc ()
{
/* allocating and initializing the text buffer struct */
    struct text_buffer *text =
	(struct text_buffer *) malloc (sizeof (struct text_buffer));
    text->max_n_cells = 0;
    text->titles = NULL;
    text->types = NULL;
    text->n_rows = 0;
    text->rows = NULL;
    text->first = NULL;
    text->last = NULL;
    return text;
}

static void
text_buffer_free (struct text_buffer *text)
{
/* memory cleanup - freeing the text buffer */
    int i;
    struct row_buffer *row;
    if (!text)
	return;
    row = text->first;
    while (row)
      {
	  for (i = 0; i < row->n_cells; i++)
	    {
		if (*(row->cells + i))
		    free (*(row->cells + i));
	    }
	  row = row->next;
      }
    if (text->types)
	free (text->types);
    free (text);
}

static int
text_is_integer (char *value)
{
/* checking if this value can be an INTEGER */
    int invalids = 0;
    int digits = 0;
    int signs = 0;
    char last = '\0';
    char *p = value;
    while (*p != '\0')
      {
	  last = *p;
	  if (*p >= '0' && *p <= '9')
	      digits++;
	  else if (*p == '+' || *p == '-')
	      signs++;
	  else
	      signs++;
	  p++;
      }
    if (invalids)
	return 0;
    if (signs > 1)
	return 0;
    if (signs)
      {
	  if (*value == '+' || *value == '-' || last == '+' || last == '-')
	      ;
	  else
	      return 0;
      }
    return 1;
}

static int
text_is_double (char *value, char decimal_separator)
{
/* checking if this value can be a DOUBLE */
    int invalids = 0;
    int digits = 0;
    int signs = 0;
    int points = 0;
    char last = '\0';
    char *p = value;
    while (*p != '\0')
      {
	  last = *p;
	  if (*p >= '0' && *p <= '9')
	      digits++;
	  else if (*p == '+' || *p == '-')
	      points++;
	  else
	    {
		if (decimal_separator == ',')
		  {
		      if (*p == ',')
			  points++;
		      else
			  invalids++;
		  }
		else
		  {
		      if (*p == '.')
			  points++;
		      else
			  invalids++;
		  }
	    }
	  p++;
      }
    if (invalids)
	return 0;
    if (points > 1)
	return 0;
    if (signs > 1)
	return 0;
    if (signs)
      {
	  if (*value == '+' || *value == '-' || last == '+' || last == '-')
	      ;
	  else
	      return 0;
      }
    return 1;
}

static void
text_clean_integer (char *value)
{
/* cleaning an integer value */
    char last;
    char buffer[35536];
    int len = strlen (value);
    last = value[len - 1];
    if (last == '-' || last == '+')
      {
	  /* trailing sign; transforming into a leading sign */
	  *buffer = last;
	  strcpy (buffer + 1, value);
	  buffer[len - 1] = '\0';
	  strcpy (value, buffer);
      }
}

static void
text_clean_double (char *value)
{
/* cleaning an integer value */
    char *p;
    char last;
    char buffer[35536];
    int len = strlen (value);
    last = value[len - 1];
    if (last == '-' || last == '+')
      {
	  /* trailing sign; transforming into a leading sign */
	  *buffer = last;
	  strcpy (buffer + 1, value);
	  buffer[len - 1] = '\0';
	  strcpy (value, buffer);
      }
    p = value;
    while (*p != '\0')
      {
	  /* transforming COMMAs into POINTs */
	  if (*p == ',')
	      *p = '.';
	  p++;
      }
}

static int
text_clean_text (char **value, void *toUtf8)
{
/* cleaning a TEXT value and converting to UTF-8 */
    char *text = *value;
    char *utf8text;
    int err;
    int i;
    int oldlen = strlen (text);
    int newlen;
    for (i = oldlen - 1; i > 0; i++)
      {
	  /* cleaning up trailing spaces */
	  if (text[i] == ' ')
	      text[i] = '\0';
	  else
	      break;
      }
    utf8text = gaiaConvertToUTF8 (toUtf8, text, oldlen, &err);
    if (err)
	return 1;
    newlen = strlen (utf8text);
    if (newlen <= oldlen)
	strcpy (*value, utf8text);
    else
      {
	  free (*value);
	  *value = (char *) malloc (newlen + 1);
	  strcpy (*value, utf8text);
      }
    return 0;
}

static struct text_buffer *
text_parse (const char *path, const char *encoding, bool first_line_titles,
	    char field_separator, char text_separator, char decimal_separator)
{
/* trying to open and parse the text file */
    int c;
    int fld;
    int len;
    int max_cell;
    int is_string = 0;
    char last = '\0';
    char *fields[4096];
    char buffer[35536];
    char *p = buffer;
    struct text_buffer *text;
    int nrows;
    int ncols;
    int errs;
    struct row_buffer *row;
    void *toUtf8;
    int encoding_errors;
    int ir;
    char title[64];
    char *first_valid_row;
    int i;
    char *name;
    for (fld = 0; fld < 4096; fld++)
      {
	  /* preparing an empty row */
	  fields[fld] = NULL;
      }
/* trying to open the text file */
    FILE *in = fopen (path, "rb");
    if (!in)
	return NULL;
    text = text_buffer_alloc ();
    fld = 0;
    while ((c = getc (in)) != EOF)
      {
	  /* parsing the file, one char at each time */
	  if (c == '\r' && !is_string)
	    {
		last = c;
		continue;
	    }
	  if (c == field_separator && !is_string)
	    {
		/* insering a field into the fields tmp array */
		last = c;
		*p = '\0';
		len = strlen (buffer);
		if (len)
		  {
		      fields[fld] = (char *) malloc (len + 1);
		      strcpy (fields[fld], buffer);
		  }
		fld++;
		p = buffer;
		*p = '\0';
		continue;
	    }
	  if (c == text_separator)
	    {
		/* found a text separator */
		if (is_string)
		  {
		      is_string = 0;
		      last = c;
		  }
		else
		  {
		      if (last == text_separator)
			  *p++ = text_separator;
		      is_string = 1;
		  }
		continue;
	    }
	  last = c;
	  if (c == '\n' && !is_string)
	    {
		/* inserting the row into the text buffer */
		*p = '\0';
		len = strlen (buffer);
		if (len)
		  {
		      fields[fld] = (char *) malloc (len + 1);
		      strcpy (fields[fld], buffer);
		  }
		fld++;
		p = buffer;
		*p = '\0';
		max_cell = -1;
		for (fld = 0; fld < 4096; fld++)
		  {
		      if (fields[fld])
			  max_cell = fld;
		  }
		text_insert_row (text, fields, max_cell);
		for (fld = 0; fld < 4096; fld++)
		  {
		      /* resetting an empty row */
		      fields[fld] = NULL;
		  }
		fld = 0;
		continue;
	    }
	  *p++ = c;
      }
    fclose (in);
/* checking if the text file really seems to contain a table */
    nrows = 0;
    ncols = 0;
    errs = 0;
    row = text->first;
    while (row)
      {
	  if (first_line_titles == true && row == text->first)
	    {
		/* skipping first line */
		row = row->next;
		continue;
	    }
	  nrows++;
	  if (row->n_cells > ncols)
	      ncols = row->n_cells;
	  row = row->next;
      }
    if (nrows == 0 && ncols == 0)
      {
	  text_buffer_free (text);
	  return NULL;
      }
    text->n_rows = nrows;
/* going to check the column types */
    text->max_n_cells = ncols;
    text->types = (char *) malloc (sizeof (char) * text->max_n_cells);
    first_valid_row = (char *) malloc (sizeof (char) * text->max_n_cells);
    for (fld = 0; fld < text->max_n_cells; fld++)
      {
	  /* initally assuming any cell contains TEXT */
	  *(text->types + fld) = VRTTXT_TEXT;
	  *(first_valid_row + fld) = 1;
      }
    row = text->first;
    while (row)
      {
	  if (first_line_titles == true && row == text->first)
	    {
		/* skipping first line */
		row = row->next;
		continue;
	    }
	  for (fld = 0; fld < row->n_cells; fld++)
	    {
		if (*(row->cells + fld))
		  {
		      if (text_is_integer (*(row->cells + fld)))
			{
			    if (*(first_valid_row + fld))
			      {
				  *(text->types + fld) = VRTTXT_INTEGER;
				  *(first_valid_row + fld) = 0;
			      }
			}
		      else if (text_is_double
			       (*(row->cells + fld), decimal_separator))
			{
			    if (*(first_valid_row + fld))
			      {
				  *(text->types + fld) = VRTTXT_DOUBLE;
				  *(first_valid_row + fld) = 0;
			      }
			    else
			      {
				  /* promoting an INTEGER column to be of the DOUBLE type */
				  if (*(text->types + fld) == VRTTXT_INTEGER)
				      *(text->types + fld) = VRTTXT_DOUBLE;
			      }
			}
		      else
			{
			    /* this column is anyway of the TEXT type */
			    *(text->types + fld) = VRTTXT_TEXT;
			    if (*(first_valid_row + fld))
				*(first_valid_row + fld) = 0;
			}
		  }
	    }
	  row = row->next;
      }
    free (first_valid_row);
/* preparing the column names */
    text->titles = (char **) malloc (sizeof (char *) * text->max_n_cells);
    if (first_line_titles == true)
      {
	  for (fld = 0; fld < text->max_n_cells; fld++)
	    {
		if (fld >= text->first->n_cells)
		  {
		      /* this column name is NULL; setting a default name */
		      sprintf (title, "COL%03d", fld + 1);
		      len = strlen (title);
		      *(text->titles + fld) = (char *) malloc (len + 1);
		      strcpy (*(text->titles + fld), title);
		  }
		else
		  {
		      if (*(text->first->cells + fld))
			{
			    len = strlen (*(text->first->cells + fld));
			    *(text->titles + fld) = (char *) malloc (len + 1);
			    strcpy (*(text->titles + fld),
				    *(text->first->cells + fld));
			    name = *(text->titles + fld);
			    for (i = 0; i < len; i++)
			      {
				  /* masking any space in the column name */
				  if (*(name + i) == ' ')
				      *(name + i) = '_';
			      }
			}
		      else
			{
			    /* this column name is NULL; setting a default name */
			    sprintf (title, "COL%03d", fld + 1);
			    len = strlen (title);
			    *(text->titles + fld) = (char *) malloc (len + 1);
			    strcpy (*(text->titles + fld), title);
			}
		  }
	    }
      }
    else
      {
	  for (fld = 0; fld < text->max_n_cells; fld++)
	    {
		sprintf (title, "COL%03d", fld + 1);
		len = strlen (title);
		*(text->titles + fld) = (char *) malloc (len + 1);
		strcpy (*(text->titles + fld), title);
	    }
      }
/* cleaning cell values when needed */
    toUtf8 = gaiaCreateUTF8Converter (encoding);
    if (!toUtf8)
      {
	  text_buffer_free (text);
	  return NULL;
      }
    encoding_errors = 0;
    row = text->first;
    while (row)
      {
	  if (first_line_titles == true && row == text->first)
	    {
		/* skipping first line */
		row = row->next;
		continue;
	    }
	  for (fld = 0; fld < row->n_cells; fld++)
	    {
		if (*(row->cells + fld))
		  {
		      if (*(text->types + fld) == VRTTXT_INTEGER)
			  text_clean_integer (*(row->cells + fld));
		      else if (*(text->types + fld) == VRTTXT_DOUBLE)
			  text_clean_double (*(row->cells + fld));
		      else
			  encoding_errors +=
			      text_clean_text (row->cells + fld, toUtf8);
		  }
	    }
	  row = row->next;
      }
    gaiaFreeUTF8Converter (toUtf8);
    if (encoding_errors)
      {
	  text_buffer_free (text);
	  return NULL;
      }
/* ok, we can now go to prepare the rows array */
    text->rows =
	(struct row_buffer **) malloc (sizeof (struct text_row *) *
				       text->n_rows);
    ir = 0;
    row = text->first;
    while (row)
      {
	  if (first_line_titles == true && row == text->first)
	    {
		/* skipping first line */
		row = row->next;
		continue;
	    }
	  *(text->rows + ir++) = row;
	  row = row->next;
      }
    return text;
}

void
MyFrame::LoadText (wxString & path, wxString & table, wxString & charset,
		   bool first_titles, char decimal_separator, char separator,
		   char text_separator)
{
//
// loading a CSV/TXT as a new DB table
//
    struct text_buffer *text = NULL;
    struct row_buffer *row;
    int seed;
    int dup;
    int idup;
    char dummy[65536];
    char dummyName[4096];
    char **col_name = NULL;
    int i;
    char sql[65536];
    int len;
    int ret;
    int rows = 0;
    char *errMsg = NULL;
    bool sqlError = false;
    char xtable[1024];
    int current_row;
    wxString msg;
//
// performing some checks before starting
//
    if (TableAlreadyExists (table) == true)
      {
	  wxMessageBox (wxT ("a table name '") + table +
			wxT ("' already exists"), wxT ("spatialite-gui"),
			wxOK | wxICON_ERROR, this);
	  return;
      }
    if (gaiaIllegalSqlName (table.ToUTF8 ()) == 1
	|| gaiaIsReservedSqlName (table.ToUTF8 ()) == 1
	|| gaiaIsReservedSqliteName (table.ToUTF8 ()) == 1)
      {
	  wxMessageBox (wxT ("'") + table +
			wxT
			("' is an invalid TABLE NAME\n\nsame as SQL reserved keyword"),
			wxT ("spatialite-gui"), wxOK | wxICON_ERROR, this);
	  return;
      }
    text =
	text_parse (path.ToUTF8 (), charset.ToUTF8 (), first_titles, separator,
		    text_separator, decimal_separator);
    if (!text)
	return;
    ::wxBeginBusyCursor ();
//
// checking for duplicate / illegal column names and antialising them 
//
    col_name = (char **) malloc (sizeof (char *) * text->max_n_cells);
    seed = 0;
    for (i = 0; i < text->max_n_cells; i++)
      {
	  if (gaiaIllegalSqlName (*(text->titles + i))
	      || gaiaIsReservedSqlName (*(text->titles + i))
	      || gaiaIsReservedSqliteName (*(text->titles + i)))
	      sprintf (dummyName, "COL_%d", seed++);
	  else
	      strcpy (dummyName, *(text->titles + i));
	  dup = 0;
	  for (idup = 0; idup < i; idup++)
	    {
		if (strcasecmp (dummyName, *(col_name + idup)) == 0)
		    dup = 1;
	    }
	  if (strcasecmp (dummyName, "PKUID") == 0)
	      dup = 1;
	  if (strcasecmp (dummyName, "Geometry") == 0)
	      dup = 1;
	  if (dup)
	      sprintf (dummyName, "COL_%d", seed++);
	  len = strlen (dummyName);
	  *(col_name + i) = (char *) malloc (len + 1);
	  strcpy (*(col_name + i), dummyName);
      }
//
// starting a transaction
//
    ret = sqlite3_exec (SqliteHandle, "BEGIN", NULL, 0, &errMsg);
    if (ret != SQLITE_OK)
      {
	  wxMessageBox (wxT ("load CSV/TXT error:") +
			wxString::FromUTF8 (errMsg), wxT ("spatialite-gui"),
			wxOK | wxICON_ERROR, this);
	  sqlite3_free (errMsg);
	  sqlError = true;
	  goto clean_up;
      }
//
// creating the Table 
//
    strcpy (xtable, table.ToUTF8 ());
    sprintf (sql, "CREATE TABLE %s", xtable);
    strcat (sql, " (\nPK_UID INTEGER PRIMARY KEY AUTOINCREMENT");
    for (i = 0; i < text->max_n_cells; i++)
      {
	  strcat (sql, ",\n");
	  strcat (sql, *(col_name + i));
	  if (*(text->types + i) == VRTTXT_INTEGER)
	      strcat (sql, " INTEGER");
	  else if (*(text->types + i) == VRTTXT_DOUBLE)
	      strcat (sql, " DOUBLE");
	  else
	      strcat (sql, " TEXT");
      }
    strcat (sql, ")");
    ret = sqlite3_exec (SqliteHandle, sql, NULL, 0, &errMsg);
    if (ret != SQLITE_OK)
      {
	  wxMessageBox (wxT ("load text error:") +
			wxString::FromUTF8 (errMsg), wxT ("spatialite-gui"),
			wxOK | wxICON_ERROR, this);
	  sqlite3_free (errMsg);
	  sqlError = true;
	  goto clean_up;
      }
    current_row = 0;
    while (current_row < text->n_rows)
      {
	  //
	  // inserting rows from CSV/TXT
	  //
	  sprintf (sql, "INSERT INTO %s (\nPK_UID", xtable);
	  for (i = 0; i < text->max_n_cells; i++)
	    {
		// columns corresponding to some CSV/TXT column
		strcat (sql, ",");
		strcat (sql, *(col_name + i));
	    }
	  strcat (sql, ")\nVALUES (");
	  sprintf (dummy, "%d", current_row);
	  strcat (sql, dummy);
	  for (i = 0; i < text->max_n_cells; i++)
	    {
		// column values
		row = *(text->rows + current_row);
		strcat (sql, ",");
		if (i >= row->n_cells)
		    strcat (sql, "NULL");
		else
		  {
		      if (*(row->cells + i))
			{
			    if (*(text->types + i) == VRTTXT_INTEGER)
			      {
				  sprintf (dummy, "%d",
					   atoi (*(row->cells + i)));
				  strcat (sql, dummy);
			      }
			    else if (*(text->types + i) == VRTTXT_DOUBLE)
			      {
				  sprintf (dummy, "%1.6lf",
					   atof (*(row->cells + i)));
				  strcat (sql, dummy);
			      }
			    else
			      {
				  strcpy (dummy, *(row->cells + i));
				  CleanSqlString (dummy);
				  strcat (sql, "'");
				  strcat (sql, dummy);
				  strcat (sql, "'");
			      }
			}
		      else
			  strcat (sql, "NULL");
		  }
	    }
	  strcat (sql, ")");
	  ret = sqlite3_exec (SqliteHandle, sql, NULL, 0, &errMsg);
	  if (ret != SQLITE_OK)
	    {
		wxMessageBox (wxT ("load text error:") +
			      wxString::FromUTF8 (errMsg),
			      wxT ("spatialite-gui"), wxOK | wxICON_ERROR,
			      this);
		sqlite3_free (errMsg);
		sqlError = true;
		goto clean_up;
	    }
	  rows++;
	  current_row++;
      }
  clean_up:
    if (col_name)
      {
	  // releasing memory allocation for column names 
	  for (i = 0; i < text->max_n_cells; i++)
	      free (*(col_name + i));
	  free (col_name);
      }
    free (text);
    if (sqlError == true)
      {
	  // some error occurred - ROLLBACK 
	  ret = sqlite3_exec (SqliteHandle, "ROLLBACK", NULL, 0, &errMsg);
	  if (ret != SQLITE_OK)
	    {
		wxMessageBox (wxT ("load text error:") +
			      wxString::FromUTF8 (errMsg),
			      wxT ("spatialite-gui"), wxOK | wxICON_ERROR,
			      this);
		sqlite3_free (errMsg);
	    }
	  ::wxEndBusyCursor ();
	  msg.Printf (wxT
		      ("CSV/TXT not loaded\n\n\na ROLLBACK was automatically performed"));
	  wxMessageBox (msg, wxT ("spatialite-gui"), wxOK | wxICON_WARNING,
			this);
      }
    else
      {
	  // ok - confirming pending transaction - COMMIT 
	  ret = sqlite3_exec (SqliteHandle, "COMMIT", NULL, 0, &errMsg);
	  if (ret != SQLITE_OK)
	    {
		wxMessageBox (wxT ("load text error:") +
			      wxString::FromUTF8 (errMsg),
			      wxT ("spatialite-gui"), wxOK | wxICON_ERROR,
			      this);
		sqlite3_free (errMsg);
		return;
	    }
	  ::wxEndBusyCursor ();
	  msg.Printf (wxT ("CSV/TXT loaded\n\n%d inserted rows"), rows);
	  wxMessageBox (msg, wxT ("spatialite-gui"),
			wxOK | wxICON_INFORMATION, this);
	  ClearTableTree ();
	  InitTableTree ();
      }
}




|







 







|
|
|




|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
1
2
3
4
5
6
7
8
9
10
11
12
..
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769

















































/*
/ TextCsv.cpp
/ methods related to CSV/TXT loading 
/
/ version 1.2, 2008 October 9
/
/ Author: Sandro Furieri a-furieri@lqt.it
/
/ Copyright (C) 2008  Alessandro Furieri
/
/    This program is free software: you can redistribute it and/or modify
/    it under the terms of the GNU General Public License as published by
................................................................................
#define VRTTXT_TEXT		1
#define VRTTXT_INTEGER	2
#define VRTTXT_DOUBLE	3

struct row_buffer
{
/* a complete row */
  int n_cells;                  /* how many cells are stored into this line */
  char **cells;                 /* the cells array */
  struct row_buffer *next;      /* pointer for linked list */
};

struct text_buffer
{
  int max_n_cells;              /* the maximun cell index */
  char **titles;                /* the column titles array */
  char *types;                  /* the column types array */
  int n_rows;                   /* the number of rows */
  struct row_buffer **rows;     /* the rows array */
  struct row_buffer *first;     /* pointers to build a linked list of rows */
  struct row_buffer *last;
};

static void text_insert_row(struct text_buffer *text, char **fields,
                            int max_cell)
{
/* inserting a row into the text buffer struct */
  int i;
  struct row_buffer *row =
    (struct row_buffer *) malloc(sizeof(struct row_buffer));
  row->n_cells = max_cell + 1;
  if (max_cell < 0)
    row->cells = NULL;
  else
    {
      row->cells = (char **) malloc(sizeof(char *) * (max_cell + 1));
      for (i = 0; i < row->n_cells; i++)
        {
          /* setting cell values */
          *(row->cells + i) = *(fields + i);
        }
    }
  row->next = NULL;
/* inserting the row into the linked list */
  if (!(text->first))
    text->first = row;
  if (text->last)
    text->last->next = row;
  text->last = row;
}

static struct text_buffer *text_buffer_alloc()
{
/* allocating and initializing the text buffer struct */
  struct text_buffer *text =
    (struct text_buffer *) malloc(sizeof(struct text_buffer));
  text->max_n_cells = 0;
  text->titles = NULL;
  text->types = NULL;
  text->n_rows = 0;
  text->rows = NULL;
  text->first = NULL;
  text->last = NULL;
  return text;
}

static void text_buffer_free(struct text_buffer *text)
{
/* memory cleanup - freeing the text buffer */
  int i;
  struct row_buffer *row;
  if (!text)
    return;
  row = text->first;
  while (row)
    {
      for (i = 0; i < row->n_cells; i++)
        {
          if (*(row->cells + i))
            free(*(row->cells + i));
        }
      row = row->next;
    }
  if (text->types)
    free(text->types);
  free(text);
}

static int text_is_integer(char *value)
{
/* checking if this value can be an INTEGER */
  int invalids = 0;
  int digits = 0;
  int signs = 0;
  char last = '\0';
  char *p = value;
  while (*p != '\0')
    {
      last = *p;
      if (*p >= '0' && *p <= '9')
        digits++;
      else if (*p == '+' || *p == '-')
        signs++;
      else
        signs++;
      p++;
    }
  if (invalids)
    return 0;
  if (signs > 1)
    return 0;
  if (signs)
    {
      if (*value == '+' || *value == '-' || last == '+' || last == '-')
        ;
      else
        return 0;
    }
  return 1;
}

static int text_is_double(char *value, char decimal_separator)
{
/* checking if this value can be a DOUBLE */
  int invalids = 0;
  int digits = 0;
  int signs = 0;
  int points = 0;
  char last = '\0';
  char *p = value;
  while (*p != '\0')
    {
      last = *p;
      if (*p >= '0' && *p <= '9')
        digits++;
      else if (*p == '+' || *p == '-')
        points++;
      else
        {
          if (decimal_separator == ',')
            {
              if (*p == ',')
                points++;
              else
                invalids++;
          } else
            {
              if (*p == '.')
                points++;
              else
                invalids++;
            }
        }
      p++;
    }
  if (invalids)
    return 0;
  if (points > 1)
    return 0;
  if (signs > 1)
    return 0;
  if (signs)
    {
      if (*value == '+' || *value == '-' || last == '+' || last == '-')
        ;
      else
        return 0;
    }
  return 1;
}

static void text_clean_integer(char *value)
{
/* cleaning an integer value */
  char last;
  char buffer[35536];
  int len = strlen(value);
  last = value[len - 1];
  if (last == '-' || last == '+')
    {
      /* trailing sign; transforming into a leading sign */
      *buffer = last;
      strcpy(buffer + 1, value);
      buffer[len - 1] = '\0';
      strcpy(value, buffer);
    }
}

static void text_clean_double(char *value)
{
/* cleaning an integer value */
  char *p;
  char last;
  char buffer[35536];
  int len = strlen(value);
  last = value[len - 1];
  if (last == '-' || last == '+')
    {
      /* trailing sign; transforming into a leading sign */
      *buffer = last;
      strcpy(buffer + 1, value);
      buffer[len - 1] = '\0';
      strcpy(value, buffer);
    }
  p = value;
  while (*p != '\0')
    {
      /* transforming COMMAs into POINTs */
      if (*p == ',')
        *p = '.';
      p++;
    }
}

static int text_clean_text(char **value, void *toUtf8)
{
/* cleaning a TEXT value and converting to UTF-8 */
  char *text = *value;
  char *utf8text;
  int err;
  int i;
  int oldlen = strlen(text);
  int newlen;
  for (i = oldlen - 1; i > 0; i++)
    {
      /* cleaning up trailing spaces */
      if (text[i] == ' ')
        text[i] = '\0';
      else
        break;
    }
  utf8text = gaiaConvertToUTF8(toUtf8, text, oldlen, &err);
  if (err)
    return 1;
  newlen = strlen(utf8text);
  if (newlen <= oldlen)
    strcpy(*value, utf8text);
  else
    {
      free(*value);
      *value = (char *) malloc(newlen + 1);
      strcpy(*value, utf8text);
    }
  return 0;
}

static struct text_buffer *text_parse(const char *path, const char *encoding,
                                      bool first_line_titles,
                                      char field_separator, char text_separator,
                                      char decimal_separator)
{
/* trying to open and parse the text file */
  int c;
  int fld;
  int len;
  int max_cell;
  int is_string = 0;
  char last = '\0';
  char *fields[4096];
  char buffer[35536];
  char *p = buffer;
  struct text_buffer *text;
  int nrows;
  int ncols;
  int errs;
  struct row_buffer *row;
  void *toUtf8;
  int encoding_errors;
  int ir;
  char title[64];
  char *first_valid_row;
  int i;
  char *name;
  for (fld = 0; fld < 4096; fld++)
    {
      /* preparing an empty row */
      fields[fld] = NULL;
    }
/* trying to open the text file */
  FILE *in = fopen(path, "rb");
  if (!in)
    return NULL;
  text = text_buffer_alloc();
  fld = 0;
  while ((c = getc(in)) != EOF)
    {
      /* parsing the file, one char at each time */
      if (c == '\r' && !is_string)
        {
          last = c;
          continue;
        }
      if (c == field_separator && !is_string)
        {
          /* insering a field into the fields tmp array */
          last = c;
          *p = '\0';
          len = strlen(buffer);
          if (len)
            {
              fields[fld] = (char *) malloc(len + 1);
              strcpy(fields[fld], buffer);
            }
          fld++;
          p = buffer;
          *p = '\0';
          continue;
        }
      if (c == text_separator)
        {
          /* found a text separator */
          if (is_string)
            {
              is_string = 0;
              last = c;
          } else
            {
              if (last == text_separator)
                *p++ = text_separator;
              is_string = 1;
            }
          continue;
        }
      last = c;
      if (c == '\n' && !is_string)
        {
          /* inserting the row into the text buffer */
          *p = '\0';
          len = strlen(buffer);
          if (len)
            {
              fields[fld] = (char *) malloc(len + 1);
              strcpy(fields[fld], buffer);
            }
          fld++;
          p = buffer;
          *p = '\0';
          max_cell = -1;
          for (fld = 0; fld < 4096; fld++)
            {
              if (fields[fld])
                max_cell = fld;
            }
          text_insert_row(text, fields, max_cell);
          for (fld = 0; fld < 4096; fld++)
            {
              /* resetting an empty row */
              fields[fld] = NULL;
            }
          fld = 0;
          continue;
        }
      *p++ = c;
    }
  fclose(in);
/* checking if the text file really seems to contain a table */
  nrows = 0;
  ncols = 0;
  errs = 0;
  row = text->first;
  while (row)
    {
      if (first_line_titles == true && row == text->first)
        {
          /* skipping first line */
          row = row->next;
          continue;
        }
      nrows++;
      if (row->n_cells > ncols)
        ncols = row->n_cells;
      row = row->next;
    }
  if (nrows == 0 && ncols == 0)
    {
      text_buffer_free(text);
      return NULL;
    }
  text->n_rows = nrows;
/* going to check the column types */
  text->max_n_cells = ncols;
  text->types = (char *) malloc(sizeof(char) * text->max_n_cells);
  first_valid_row = (char *) malloc(sizeof(char) * text->max_n_cells);
  for (fld = 0; fld < text->max_n_cells; fld++)
    {
      /* initally assuming any cell contains TEXT */
      *(text->types + fld) = VRTTXT_TEXT;
      *(first_valid_row + fld) = 1;
    }
  row = text->first;
  while (row)
    {
      if (first_line_titles == true && row == text->first)
        {
          /* skipping first line */
          row = row->next;
          continue;
        }
      for (fld = 0; fld < row->n_cells; fld++)
        {
          if (*(row->cells + fld))
            {
              if (text_is_integer(*(row->cells + fld)))
                {
                  if (*(first_valid_row + fld))
                    {
                      *(text->types + fld) = VRTTXT_INTEGER;
                      *(first_valid_row + fld) = 0;
                    }
              } else if (text_is_double(*(row->cells + fld), decimal_separator))
                {
                  if (*(first_valid_row + fld))
                    {
                      *(text->types + fld) = VRTTXT_DOUBLE;
                      *(first_valid_row + fld) = 0;
                  } else
                    {
                      /* promoting an INTEGER column to be of the DOUBLE type */
                      if (*(text->types + fld) == VRTTXT_INTEGER)
                        *(text->types + fld) = VRTTXT_DOUBLE;
                    }
              } else
                {
                  /* this column is anyway of the TEXT type */
                  *(text->types + fld) = VRTTXT_TEXT;
                  if (*(first_valid_row + fld))
                    *(first_valid_row + fld) = 0;
                }
            }
        }
      row = row->next;
    }
  free(first_valid_row);
/* preparing the column names */
  text->titles = (char **) malloc(sizeof(char *) * text->max_n_cells);
  if (first_line_titles == true)
    {
      for (fld = 0; fld < text->max_n_cells; fld++)
        {
          if (fld >= text->first->n_cells)
            {
              /* this column name is NULL; setting a default name */
              sprintf(title, "COL%03d", fld + 1);
              len = strlen(title);
              *(text->titles + fld) = (char *) malloc(len + 1);
              strcpy(*(text->titles + fld), title);
          } else
            {
              if (*(text->first->cells + fld))
                {
                  len = strlen(*(text->first->cells + fld));
                  *(text->titles + fld) = (char *) malloc(len + 1);
                  strcpy(*(text->titles + fld), *(text->first->cells + fld));
                  name = *(text->titles + fld);
                  for (i = 0; i < len; i++)
                    {
                      /* masking any space in the column name */
                      if (*(name + i) == ' ')
                        *(name + i) = '_';
                    }
              } else
                {
                  /* this column name is NULL; setting a default name */
                  sprintf(title, "COL%03d", fld + 1);
                  len = strlen(title);
                  *(text->titles + fld) = (char *) malloc(len + 1);
                  strcpy(*(text->titles + fld), title);
                }
            }
        }
  } else
    {
      for (fld = 0; fld < text->max_n_cells; fld++)
        {
          sprintf(title, "COL%03d", fld + 1);
          len = strlen(title);
          *(text->titles + fld) = (char *) malloc(len + 1);
          strcpy(*(text->titles + fld), title);
        }
    }
/* cleaning cell values when needed */
  toUtf8 = gaiaCreateUTF8Converter(encoding);
  if (!toUtf8)
    {
      text_buffer_free(text);
      return NULL;
    }
  encoding_errors = 0;
  row = text->first;
  while (row)
    {
      if (first_line_titles == true && row == text->first)
        {
          /* skipping first line */
          row = row->next;
          continue;
        }
      for (fld = 0; fld < row->n_cells; fld++)
        {
          if (*(row->cells + fld))
            {
              if (*(text->types + fld) == VRTTXT_INTEGER)
                text_clean_integer(*(row->cells + fld));
              else if (*(text->types + fld) == VRTTXT_DOUBLE)
                text_clean_double(*(row->cells + fld));
              else
                encoding_errors += text_clean_text(row->cells + fld, toUtf8);
            }
        }
      row = row->next;
    }
  gaiaFreeUTF8Converter(toUtf8);
  if (encoding_errors)
    {
      text_buffer_free(text);
      return NULL;
    }
/* ok, we can now go to prepare the rows array */
  text->rows =
    (struct row_buffer **) malloc(sizeof(struct text_row *) * text->n_rows);
  ir = 0;
  row = text->first;
  while (row)
    {
      if (first_line_titles == true && row == text->first)
        {
          /* skipping first line */
          row = row->next;
          continue;
        }
      *(text->rows + ir++) = row;
      row = row->next;
    }
  return text;
}

void
  MyFrame::LoadText(wxString & path, wxString & table, wxString & charset,
                    bool first_titles, char decimal_separator, char separator,
                    char text_separator)
{
//
// loading a CSV/TXT as a new DB table
//
  struct text_buffer *text = NULL;
  struct row_buffer *row;
  int seed;
  int dup;
  int idup;
  char dummy[65536];
  char dummyName[4096];
  char **col_name = NULL;
  int i;
  char sql[65536];
  int len;
  int ret;
  int rows = 0;
  char *errMsg = NULL;
  bool sqlError = false;
  char xtable[1024];
  int current_row;
  wxString msg;
//
// performing some checks before starting
//
  if (TableAlreadyExists(table) == true)
    {
      wxMessageBox(wxT("a table name '") + table + wxT("' already exists"),
                   wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
      return;
    }
  text =
    text_parse(path.ToUTF8(), charset.ToUTF8(), first_titles, separator,
               text_separator, decimal_separator);
  if (!text)
    return;
  ::wxBeginBusyCursor();
//
// checking for duplicate / illegal column names and antialising them 
//
  col_name = (char **) malloc(sizeof(char *) * text->max_n_cells);
  seed = 0;
  for (i = 0; i < text->max_n_cells; i++)
    {
      strcpy(dummyName, *(text->titles + i));
      dup = 0;
      for (idup = 0; idup < i; idup++)
        {
          if (strcasecmp(dummyName, *(col_name + idup)) == 0)
            dup = 1;
        }
      if (strcasecmp(dummyName, "PKUID") == 0)
        dup = 1;
      if (strcasecmp(dummyName, "Geometry") == 0)
        dup = 1;
      if (dup)
        sprintf(dummyName, "COL_%d", seed++);
      len = strlen(dummyName);
      *(col_name + i) = (char *) malloc(len + 1);
      strcpy(*(col_name + i), dummyName);
    }
//
// starting a transaction
//
  ret = sqlite3_exec(SqliteHandle, "BEGIN", NULL, 0, &errMsg);
  if (ret != SQLITE_OK)
    {
      wxMessageBox(wxT("load CSV/TXT error:") + wxString::FromUTF8(errMsg),
                   wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
      sqlite3_free(errMsg);
      sqlError = true;
      goto clean_up;
    }
//
// creating the Table 
//
  strcpy(xtable, table.ToUTF8());
  sprintf(sql, "CREATE TABLE \"%s\"", xtable);
  strcat(sql, " (\n\"PK_UID\" INTEGER PRIMARY KEY AUTOINCREMENT");
  for (i = 0; i < text->max_n_cells; i++)
    {
      strcat(sql, ",\n\"");
      strcat(sql, *(col_name + i));
      if (*(text->types + i) == VRTTXT_INTEGER)
        strcat(sql, "\" INTEGER");
      else if (*(text->types + i) == VRTTXT_DOUBLE)
        strcat(sql, "\" DOUBLE");
      else
        strcat(sql, "\" TEXT");
    }
  strcat(sql, ")");
  ret = sqlite3_exec(SqliteHandle, sql, NULL, 0, &errMsg);
  if (ret != SQLITE_OK)
    {
      wxMessageBox(wxT("load text error:") + wxString::FromUTF8(errMsg),
                   wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
      sqlite3_free(errMsg);
      sqlError = true;
      goto clean_up;
    }
  current_row = 0;
  while (current_row < text->n_rows)
    {
      //
      // inserting rows from CSV/TXT
      //
      sprintf(sql, "INSERT INTO \"%s\" (\n\"PK_UID\"", xtable);
      for (i = 0; i < text->max_n_cells; i++)
        {
          // columns corresponding to some CSV/TXT column
          strcat(sql, ",\"");
          strcat(sql, *(col_name + i));
          strcat(sql, "\"");
        }
      strcat(sql, ")\nVALUES (");
      sprintf(dummy, "%d", current_row);
      strcat(sql, dummy);
      for (i = 0; i < text->max_n_cells; i++)
        {
          // column values
          row = *(text->rows + current_row);
          strcat(sql, ",");
          if (i >= row->n_cells)
            strcat(sql, "NULL");
          else
            {
              if (*(row->cells + i))
                {
                  if (*(text->types + i) == VRTTXT_INTEGER)
                    {
                      sprintf(dummy, "%d", atoi(*(row->cells + i)));
                      strcat(sql, dummy);
                  } else if (*(text->types + i) == VRTTXT_DOUBLE)
                    {
                      sprintf(dummy, "%1.6lf", atof(*(row->cells + i)));
                      strcat(sql, dummy);
                  } else
                    {
                      strcpy(dummy, *(row->cells + i));
                      CleanSqlString(dummy);
                      strcat(sql, "'");
                      strcat(sql, dummy);
                      strcat(sql, "'");
                    }
              } else
                strcat(sql, "NULL");
            }
        }
      strcat(sql, ")");
      ret = sqlite3_exec(SqliteHandle, sql, NULL, 0, &errMsg);
      if (ret != SQLITE_OK)
        {
          wxMessageBox(wxT("load text error:") + wxString::FromUTF8(errMsg),
                       wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
          sqlite3_free(errMsg);
          sqlError = true;
          goto clean_up;
        }
      rows++;
      current_row++;
    }
clean_up:
  if (col_name)
    {
      // releasing memory allocation for column names 
      for (i = 0; i < text->max_n_cells; i++)
        free(*(col_name + i));
      free(col_name);
    }
  free(text);
  if (sqlError == true)
    {
      // some error occurred - ROLLBACK 
      ret = sqlite3_exec(SqliteHandle, "ROLLBACK", NULL, 0, &errMsg);
      if (ret != SQLITE_OK)
        {
          wxMessageBox(wxT("load text error:") + wxString::FromUTF8(errMsg),
                       wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
          sqlite3_free(errMsg);
        }
      ::wxEndBusyCursor();
      msg =
        wxT("CSV/TXT not loaded\n\n\na ROLLBACK was automatically performed");
      wxMessageBox(msg, wxT("spatialite-gui"), wxOK | wxICON_WARNING, this);
  } else
    {
      // ok - confirming pending transaction - COMMIT 
      ret = sqlite3_exec(SqliteHandle, "COMMIT", NULL, 0, &errMsg);
      if (ret != SQLITE_OK)
        {
          wxMessageBox(wxT("load text error:") + wxString::FromUTF8(errMsg),
                       wxT("spatialite-gui"), wxOK | wxICON_ERROR, this);
          sqlite3_free(errMsg);
          return;
        }
      ::wxEndBusyCursor();
      sprintf(dummy, "CSV/TXT loaded\n\n%d inserted rows", rows);
      msg = wxString::FromUTF8(dummy);
      wxMessageBox(msg, wxT("spatialite-gui"), wxOK | wxICON_INFORMATION, this);
      InitTableTree();
    }
}

















































Added icons/dumpshp.xpm.







































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/* XPM */
static const char * dumpshp_xpm[] = {
"16 16 16 1",
" 	c None",
".	c #5AB24A",
"+	c #41A0E9",
"@	c #8BCC5C",
"#	c #ECF7E6",
"$	c #D3EDBC",
"%	c #D0EBFA",
"&	c #0A5EC5",
"*	c #9BD48C",
"=	c #BCE7B1",
"-	c #94B7E3",
";	c #A7D6A3",
">	c #209910",
",	c #638F45",
"'	c #106CD2",
")	c #FFFFFF",
"     ))))))     ",
"     ),@.,)     ",
"    )),@@,))    ",
"   ),,,@@,,,)   ",
"   )),@@@@,))   ",
"  )>#),@.,#=>)  ",
"  )'#$#,,#.=>)  ",
" )'%$$*%%.@@=>) ",
" )'%+*+++@@.;>) ",
" )'%+-+++...;>) ",
" )>$*.+++''>;') ",
"  )>$@..'&&-')  ",
"  )>==>.'&--')  ",
"   )>>;;--'')   ",
"    ))>'''))    ",
"      ))))      "};

Added icons/exif.xpm.











































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
/* XPM */
static const char * exif_xpm[] = {
"16 16 114 2",
"  	c None",
". 	c #AA7128",
"+ 	c #A96F27",
"@ 	c #A76E26",
"# 	c #A56C25",
"$ 	c #A36A23",
"% 	c #A06822",
"& 	c #9D6620",
"* 	c #9B641F",
"= 	c #98611D",
"- 	c #955F1C",
"; 	c #A86F26",
"> 	c #DDA252",
", 	c #DA934D",
"' 	c #D59243",
") 	c #D1913C",
"! 	c #CD8E3C",
"~ 	c #CB8B3A",
"{ 	c #BE843E",
"] 	c #CA924B",
"^ 	c #905B19",
"/ 	c #D8903F",
"( 	c #61BCF3",
"_ 	c #62BDF3",
": 	c #5DB8F1",
"< 	c #4DA6E9",
"[ 	c #368EDE",
"} 	c #CA9249",
"| 	c #8C5817",
"1 	c #A26A23",
"2 	c #DD9148",
"3 	c #5CB6F0",
"4 	c #5EB8F1",
"5 	c #5CB7F0",
"6 	c #A47536",
"7 	c #A27234",
"8 	c #9F7032",
"9 	c #A86E26",
"0 	c #A16922",
"a 	c #9E6721",
"b 	c #D98F46",
"c 	c #4BA4E8",
"d 	c #4FA8EA",
"e 	c #4CA5E8",
"f 	c #A17233",
"g 	c #D2A15B",
"h 	c #CE9256",
"i 	c #D49244",
"j 	c #CC8D39",
"k 	c #9A631F",
"l 	c #D48A43",
"m 	c #368DDE",
"n 	c #3890DF",
"o 	c #9B6F35",
"p 	c #CC8F49",
"q 	c #35C62D",
"r 	c #40C723",
"s 	c #3CC321",
"t 	c #3BCD27",
"u 	c #43D12E",
"v 	c #57DA3F",
"w 	c #96601C",
"x 	c #CC8A43",
"y 	c #6EE454",
"z 	c #CF9037",
"A 	c #885514",
"B 	c #925D1A",
"C 	c #8F5A18",
"D 	c #6EE46E",
"E 	c #CA8B51",
"F 	c #845112",
"G 	c #38BAED",
"H 	c #58BFFF",
"I 	c #62BBFF",
"J 	c #44B6FF",
"K 	c #DBEB8C",
"L 	c #FFFF6D",
"M 	c #78EF69",
"N 	c #CE8F45",
"O 	c #804E10",
"P 	c #3BCE45",
"Q 	c #07BE31",
"R 	c #5AB7FF",
"S 	c #58B6FF",
"T 	c #97D1CC",
"U 	c #F3FA8A",
"V 	c #C99A40",
"W 	c #C7883D",
"X 	c #7D4C0E",
"Y 	c #4BC84F",
"Z 	c #36CB21",
"` 	c #42C825",
" .	c #54B8AC",
"..	c #42A6FF",
"+.	c #00A2FF",
"@.	c #7E4D0F",
"#.	c #7C4B0E",
"$.	c #7A490D",
"%.	c #77F35E",
"&.	c #A4FF8C",
"*.	c #ACFF77",
"=.	c #7CF634",
"-.	c #75EF55",
";.	c #64FF79",
">.	c #C59046",
",.	c #C6954A",
"'.	c #E8D462",
").	c #E9D461",
"!.	c #C99644",
"~.	c #8C5816",
"{.	c #895515",
"].	c #865313",
"^.	c #835112",
"/.	c #804F10",
"                                ",
". + @ # $ % & * = -             ",
"; > , ' ) ! ~ { ] ^             ",
"# / ( _ ( : < [ } |             ",
"1 2 3 4 5 6 7 8 9 0 % & * = -   ",
"a b c d e f g h i j ! ~ { ] ^   ",
"k l m n [ o p q r s t u v } |   ",
"w x . + @ # $ % & * = - y z A   ",
"B C ; > , ' ) ! ~ { ] ^ D E F   ",
"    # / G H I J K L } | M N O   ",
"    1 2 P Q R S T U z A V W X   ",
"    a b Y Z `  ...+.E F @.#.$.  ",
"    k l %.&.*.=.-.;.N O         ",
"    w x >.,.'.).!.V W X         ",
"    B C ~.{.].^./.@.#.$.        ",
"                                "};

Changes to icons/icon.xpm.

1
2
3
4
5
6
7
8
9
10
11

12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43

/* XPM */
static const char * icon_xpm[] = {
"32 32 8 1",
" 	c None",
".	c #F0C080",
"+	c #D0E0D0",
"@	c #D0FFD0",
"#	c #E0F0E0",
"$	c #D0D0FF",
"%	c #F0F0F0",
"&	c #E0E0FF",

"                                ",
"                                ",
"                                ",
"            ........            ",
"        ....++++++++....        ",
"    ....++++++##@##+++++....    ",
"  ..++++++##+++#@#+++@++++++..  ",
" .+++@@@##@@@@@##+#@@@##@@@+++. ",
" .++++++@#@@@#+##@@@@@#@++++++. ",
"  ..++++++@+++#@#+++##++++++..  ",
"   $....++++++#@##++++++....$   ",
"   $$$$$....++++++++....$$$$$   ",
"   $$$$$&&&&........&&&&$$$$$   ",
"   $$$$$&&&&%%%%%%%%&&&&$$$$$   ",
"   $$$$$&&&&%%%%%%%%&&&&$$$$$   ",
"  .$$$$$&&&&%%%%%%%%&&&&$$$$$.  ",
" .+$$$$$&&&&%%%%%%%%&&&&$$$$$+. ",
" .++$$$$&&&&%%%%%%%%&&&&$$$$++. ",
"  ..++++&&&&%%%%%%%%&&&&++++..  ",
"   $....++++%%%%%%%%++++....$   ",
"   $$$$$....++++++++....$$$$$   ",
"   $$$$$&&&&........&&&&$$$$$   ",
"   $$$$$&&&&%%%%%%%%&&&&$$$$$   ",
"   $$$$$&&&&%%%%%%%%&&&&$$$$$   ",
"  .$$$$$&&&&%%%%%%%%&&&&$$$$$.  ",
" .+$$$$$&&&&%%%%%%%%&&&&$$$$$+. ",
" .++$$$$&&&&%%%%%%%%&&&&$$$$++. ",
"  ..++++&&&&%%%%%%%%&&&&++++..  ",
"    ....++++%%%%%%%%++++....    ",
"        ....++++++++....        ",
"            ........            ",
"                                "};



|

|
|
|
|
|
|
|
>
|
|
|
|
<
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/* XPM */
static const char * icon_xpm[] = {
"32 32 9 1",
" 	c None",
".	c #5F6431",
"+	c #496E14",
"@	c #AF5C57",
"#	c #916864",
"$	c #5F8B22",
"%	c #878882",
"&	c #9C9D9A",
"*	c #C1C2BF",
"                             *  ",
"                            *** ",
"                          &**** ",
"                         &&**** ",

"                        &&***** ",
"                       &&&***** ",
"                       &&&***** ",
"                      &&&&******",
"                      &&&&******",
"                #####&&&&&&*****",
"              #######&&&&&***** ",
"             #####@#&&&&&&***** ",
"            ####@@@##@@##*****  ",
"            ##@@@@@@@@@@@&****  ",
"           ###@@@@@@@@@@@#***   ",
"           #@@@@@@@@@@@@@@&**   ",
"          .#@@@@@@@@@@@@@@#*    ",
"        .+.#@@@@@@@@@@@@@@#.+.  ",
"       +++##@@@@@@@@@@@@@@@#+++ ",
"      +++ ###@@@@@@@@@@@@@@# ++ ",
"      +++ ###@@@@@@@@@@@@@## +++",
"      +++ ###@@@@@@@@@@@@@#  ++$",
"      ++++##@@@@@@@@@@@@@@# ++$$",
"       $++.##@@@@@@@@@@@@##++$$ ",
"        $$++.#@@@@@@@@@##.++$$  ",
"         $$$++++......+++$$$$   ",
"        %%%+$$$$$$$$+$$$$$$     ",
"       %&%%&&%..+$$$$+..        ",
"      %%%&&****########         ",
"     %%%&&&&*&*                 ",
"  &&  %&&*&&                    ",
"        &                       "};

Added icons/icon_info.xpm.









































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
/* XPM */
static const char * icon_info_xpm[] = {
"128 113 256 2",
"  	c None",
". 	c #583F32",
"+ 	c #653D22",
"@ 	c #4A4625",
"# 	c #643E2B",
"$ 	c #4F452E",
"% 	c #6E3C2D",
"& 	c #3A5016",
"* 	c #5E432D",
"= 	c #3C4F1C",
"- 	c #3A5211",
"; 	c #404F23",
"> 	c #784129",
", 	c #92392C",
"' 	c #495025",
") 	c #873D2C",
"! 	c #77413D",
"~ 	c #3F590F",
"{ 	c #3F5917",
"] 	c #6D4745",
"^ 	c #973D30",
"/ 	c #42591F",
"( 	c #8D4226",
"_ 	c #944028",
": 	c #864521",
"< 	c #84452E",
"[ 	c #844626",
"} 	c #475829",
"| 	c #4F5536",
"1 	c #3E5F14",
"2 	c #3F600B",
"3 	c #824743",
"4 	c #7B4947",
"5 	c #9E4228",
"6 	c #8E453B",
"7 	c #6A5040",
"8 	c #6F4E4D",
"9 	c #535843",
"0 	c #3F6505",
"a 	c #8B4846",
"b 	c #4E5E24",
"c 	c #894B3F",
"d 	c #476221",
"e 	c #9B4925",
"f 	c #9C492C",
"g 	c #964A38",
"h 	c #944A45",
"i 	c #6B5554",
"j 	c #76534A",
"k 	c #426815",
"l 	c #4B651C",
"m 	c #9B4946",
"n 	c #655A43",
"o 	c #47671C",
"p 	c #A9473B",
"q 	c #85504E",
"r 	c #486815",
"s 	c #8C4F4A",
"t 	c #8B4F4F",
"u 	c #466B0E",
"v 	c #AA4844",
"w 	c #536339",
"x 	c #536430",
"y 	c #924F4C",
"z 	c #A54B47",
"A 	c #7C5749",
"B 	c #446F04",
"C 	c #994F4F",
"D 	c #476D19",
"E 	c #436F11",
"F 	c #586443",
"G 	c #A14E4B",
"H 	c #795A4A",
"I 	c #496E12",
"J 	c #9C504B",
"K 	c #5C644D",
"L 	c #417309",
"M 	c #6B6140",
"N 	c #506C2B",
"O 	c #6F5E5C",
"P 	c #985351",
"Q 	c #B04D46",
"R 	c #48720A",
"S 	c #AF4D4C",
"T 	c #9D5347",
"U 	c #66625B",
"V 	c #825A58",
"W 	c #785E5C",
"X 	c #6B6352",
"Y 	c #4D7217",
"Z 	c #AB514C",
"` 	c #746153",
" .	c #965752",
"..	c #A65350",
"+.	c #45770E",
"@.	c #497518",
"#.	c #77624E",
"$.	c #487802",
"%.	c #B4514A",
"&.	c #965958",
"*.	c #B4514F",
"=.	c #8B5C5D",
"-.	c #4C7710",
";.	c #507424",
">.	c #A35751",
",.	c #AE5454",
"'.	c #B0544F",
").	c #B75346",
"!.	c #915D59",
"~.	c #A35857",
"{.	c #A5594D",
"].	c #A75A48",
"^.	c #836263",
"/.	c #A05B58",
"(.	c #AC5854",
"_.	c #7F6463",
":.	c #B9554E",
"<.	c #85635E",
"[.	c #786766",
"}.	c #8B6260",
"|.	c #6B6C5E",
"1.	c #B95654",
"2.	c #4D7E08",
"3.	c #8E635C",
"4.	c #4F7D17",
"5.	c #B55954",
"6.	c #AF5B58",
"7.	c #68705A",
"8.	c #9E605E",
"9.	c #9C6254",
"0.	c #6E6E6B",
"a.	c #B65B5A",
"b.	c #8F6664",
"c.	c #A6605D",
"d.	c #63764B",
"e.	c #B95C50",
"f.	c #AB5F5E",
"g.	c #BE5A58",
"h.	c #956565",
"i.	c #976661",
"j.	c #8A696A",
"k.	c #B95D57",
"l.	c #AE605A",
"m.	c #8C6965",
"n.	c #677654",
"o.	c #9D6562",
"p.	c #538314",
"q.	c #C15C54",
"r.	c #777254",
"s.	c #627A44",
"t.	c #816D6C",
"u.	c #B4605C",
"v.	c #627C3B",
"w.	c #7C7071",
"x.	c #C25E5B",
"y.	c #508717",
"z.	c #51880B",
"A.	c #886E6D",
"B.	c #558520",
"C.	c #986B5E",
"D.	c #AA6752",
"E.	c #956B69",
"F.	c #AC6562",
"G.	c #A56766",
"H.	c #BE615B",
"I.	c #A16966",
"J.	c #B86360",
"K.	c #B3655F",
"L.	c #9B6B6B",
"M.	c #C16257",
"N.	c #BE6261",
"O.	c #568B00",
"P.	c #7A7572",
"Q.	c #767A51",
"R.	c #757774",
"S.	c #AA6963",
"T.	c #5F8530",
"U.	c #AF6865",
"V.	c #C7625F",
"W.	c #967067",
"X.	c #538F04",
"Y.	c #AA6B6B",
"Z.	c #B9685D",
"`.	c #C3655F",
" +	c #A56D6A",
".+	c #847676",
"++	c #B96B4D",
"@+	c #588E15",
"#+	c #B36D51",
"$+	c #728246",
"%+	c #B86A69",
"&+	c #B46C69",
"*+	c #C56867",
"=+	c #8F795F",
"-+	c #C8695D",
";+	c #7B7D7A",
">+	c #C16C5A",
",+	c #817C7B",
"'+	c #B66E6B",
")+	c #738460",
"!+	c #BC6E6C",
"~+	c #BE6E68",
"{+	c #BF7052",
"]+	c #5F9226",
"^+	c #AB7470",
"/+	c #B27270",
"(+	c #5A9611",
"_+	c #6E8B49",
":+	c #C56E6A",
"<+	c #599902",
"[+	c #977B78",
"}+	c #659134",
"|+	c #5D961E",
"1+	c #6A8F3F",
"2+	c #A37974",
"3+	c #7E856F",
"4+	c #818380",
"5+	c #738C56",
"6+	c #90807F",
"7+	c #5C9E0C",
"8+	c #858784",
"9+	c #639F1F",
"0+	c #8A8C89",
"a+	c #63A518",
"b+	c #AC8582",
"c+	c #7E975E",
"d+	c #9E8A89",
"e+	c #8E8F8D",
"f+	c #919390",
"g+	c #6AAC21",
"h+	c #949693",
"i+	c #7AA648",
"j+	c #8C9B83",
"k+	c #71AC32",
"l+	c #6FB019",
"m+	c #76AA40",
"n+	c #999B98",
"o+	c #9C9E9B",
"p+	c #9FA19E",
"q+	c #7BB938",
"r+	c #AFA1A2",
"s+	c #A4A6A3",
"t+	c #AAACA8",
"u+	c #ADAFAC",
"v+	c #B0B2AF",
"w+	c #B3B5B2",
"x+	c #C7B5B4",
"y+	c #B8BAB7",
"z+	c #BBBDBA",
"A+	c #C0C2BF",
"B+	c #C7C9C6",
"C+	c #CED0CC",
"D+	c #D0D2CF",
"E+	c #D3D5D2",
"F+	c #D7D9D6",
"G+	c #DEE0DC",
"                                                                                                                                                                                                                                                                ",
"                                                                                                                                                                                                                                              s+                ",
"                                                                                                                                                                                                                                        t+w+A+s+                ",
"                                                                                                                                                                                                                                  p+t+z+A+A+z+s+z+              ",
"                                                                                                                                                                                                                                y+w+A+A+A+A+p+C+E+z+4+          ",
"                                                                                                                                                                                                                              A+C+u+A+A+A+z+s+E+E+z+t+;+        ",
"                                                                                                                                                                                                                          p+B+C+y+z+A+A+A+p+C+E+C+A+w+A+0+      ",
"                                                                                                                                                                                                                        p+C+C+C+v+A+A+A+z+s+E+E+y+F+E+y+        ",
"                                                                                                                                                                                                                    h+n+A+C+C+B+v+A+A+A+p+C+E+B+C+E+B+e+        ",
"                                                                                                                                                                                                                  h+p+p+C+C+C+w+A+A+A+z+t+E+D+z+F+E+s+f+        ",
"                                                                                                                                                                                                              f+n+p+p+t+C+C+C+u+A+A+A+p+C+E+z+E+E+w+p+t+        ",
"                                                                                                                                                                                                            f+8+p+p+p+w+C+C+A+y+A+A+z+t+E+C+A+E+B+p+E+A+f+      ",
"                                                                                                                                                                                                      f+e+h+f+f+p+p+n+B+C+C+w+A+A+A+p+C+E+y+F+D+p+B+F+A+        ",
"                                                                                                                                                                                                      o+f+p+8+o+p+p+h+C+C+C+u+A+A+z+t+E+B+B+E+u+w+F+B+s+        ",
"                                                                                                                                                                                                    e+p+n+p+4+p+p+p+p+C+C+y+z+A+A+p+C+E+z+F+B+p+F+E+A+z+        ",
"                                                                                                                                                                                                  e+u+n+p+p+4+p+p+o+u+C+C+v+A+A+z+t+E+z+E+D+n+C+F+z+F+A+t+      ",
"                                                                                                                                                                                                8+t+u+h+p+n+8+p+p+f+B+C+B+v+A+A+p+C+C+A+E+t+z+F+z+F+F+C+y+      ",
"                                                                                                                                                                                            ;+e+p+u+u+f+p+0+f+p+p+n+C+C+w+A+A+y+t+E+z+F+A+s+F+B+C+F+C+C+A+      ",
"                                                                                                                                                                                            4+h+u+u+t+f+p+4+o+p+p+s+C+C+u+A+A+p+C+B+B+D+h+D+C+B+F+C+C+C+A+      ",
"                                                                                                                                                                                          8+o+u+u+u+p+o+p+4+p+p+p+y+C+A+y+A+y+t+E+z+E+s+A+E+A+F+B+C+C+C+B+      ",
"                                                                                                                                                                                        ;+h+t+u+u+u+n+p+p+4+p+p+h+B+C+w+A+A+p+C+A+D+z+s+F+z+F+C+C+C+C+C+C+      ",
"                                                                                                                                                                                        0+s+u+u+u+u+h+p+f+e+p+p+p+C+C+u+A+y+u+C+A+C+n+E+A+E+D+B+C+C+C+C+C+n+    ",
"                                                                                                                                                                                      4+o+t+u+u+u+u+f+p+e+f+p+p+v+C+y+z+A+s+C+y+E+p+B+B+C+E+B+C+C+C+C+C+C+o+    ",
"                                                                                                                                                                                      s+h+t+u+u+u+t+h+p+4+o+p+s+y+C+v+A+y+u+B+B+y+t+C+B+E+B+C+C+C+C+C+C+w+y+    ",
"                                                                                                                                                                                    e+z+f+u+u+u+u+p+n+o+4+p+p+n+C+B+w+A+s+D+y+C+n+F+z+E+B+C+C+C+C+C+C+u+C+F+    ",
"                                                                                                                                                                                  4+w+z+e+u+u+u+u+n+p+e+e+p+n+t+C+w+A+y+v+A+C+p+C+z+F+A+C+C+C+C+C+C+t+D+F+F+w+  ",
"                                                                                                                                                                                  h+z+z+8+u+u+u+u+h+p+0+f+p+s+v+C+u+A+s+C+z+w+w+A+D+A+C+C+C+C+C+B+t+E+F+F+F+y+  ",
"                                                                                                                                                                                ;+w+s+z+8+u+u+u+u+f+p+0+f+p+s+A+A+y+y+w+z+C+n+B+B+z+B+C+C+C+C+A+t+F+F+F+F+A+z+  ",
"                                                                                                                                                                                4+p+v+y+0+u+u+u+t+f+p+4+o+n+t+C+w+A+s+B+B+p+B+A+A+B+C+C+C+C+z+v+F+F+F+F+y+C+A+  ",
"                                                                                                                                                                                ;+u+w+u+h+u+u+u+o+o+f+0+p+p+w+C+u+y+w+y+y+z+z+B+z+C+C+C+C+v+y+F+F+F+C+z+F+F+z+  ",
"                                                                                                                                                                              ;+s+s+z+t+p+u+u+u+n+p+0+h+p+t+w+y+z+s+A+A+t+z+C+w+C+C+C+C+t+A+F+F+F+B+A+F+F+F+w+  ",
"                                                                                                                                                                              f+v+s+z+s+o+u+u+u+h+p+f+f+n+t+B+v+y+w+z+n+A+B+u+C+C+C+C+s+B+F+F+F+z+B+F+F+F+F+    ",
"                                                                                                                                            w.w.[..+.+[.0.U O w..+          8+v+v+s+z+s+h+u+u+u+f+p+h+f+n+u+B+w+o+h+o+w+B+t+C+C+C+B+o+B+F+F+E+y+E+F+F+F+F+B+    ",
"                                                                                                                                    w.t.W W W W O W W ^.i i i i i W O [.P.4+t+v+v+s+z+s+h+u+u+t+h+n+e+o+s+v+w+y+;+0+s+z+t+C+C+C+B+p+D+F+F+B+z+F+F+F+F+F+F+A+    ",
"                                                                                                                            P.[.O W O <.<.<.}.}.}.h.b.h.L.}.}.}.^.}.}.^.w.p+v+v+u+t+z+s+h+u+u+o+o+e+n+o+w+v+u+f+4+h+y+u+B+C+C+z+p+E+F+F+A+B+F+F+F+F+F+F+F+w+h+  ",
"                                                                                                                          [.W W W <.^.W b.h.b.h. +}. + +h. +h.h.I.}.<.A.e+v+v+v+h+w+z+s+n+u+u+h+p+e+n+h+w+y+u+;+0+u+v+A+C+C+w+s+F+F+F+y+C+F+F+F+F+F+F+F+F+u+    ",
"                                                                                                                      w.O ^.W b.}.}.}.h.h.}.}.h.h.h.i.i.}.i.h.h.=.o.h.w.p+v+v+v+f+z+y+s+o+u+u+h+p+f+f+s+v+v+e+4+p+t+y+C+C+u+u+F+F+C+z+E+F+F+F+F+F+F+F+F+E+f+    ",
"                                                                                                                  [.W ^.W ^.h.}.h.h.I.i.h.I.o.&+o.&+o.&+I.&+Y.o.Y.o.[+;+p+v+v+v+n+z+u+u+n+u+u+f+n+h+f+v+t+e+;+e+t+v+C+C+s+y+F+F+B+A+F+F+F+F+F+F+F+F+F+F+A+      ",
"                                                                                                              ,+_.^.^.^.L.}.}.}.h.Y.h.I.Y.o.&+G.G.&+o.&+S.G.&+i.&+L.4+e+p+v+v+v+p+z+t+w+h+u+s+h+0+o+f+A+n+;+8+p+o+C+C+p+A+F+F+z+B+F+F+F+F+F+F+F+F+F+G+G+s+      ",
"                                                                                                            w._.^.^.h.L.h. +h.I.I.}.h.i.}.o.G.o.&+&+o.&+&+o.&+S.E.,+s+e+p+v+v+v+h+z+s+w+h+u+o+p+0+p+o+w+e+4+e+h+C+B+s+B+F+E+y+E+F+F+F+F+F+F+F+F+G+G+G+y+0+      ",
"                                                                                                          .+W m.^.L.h.h. +h.G.&+o.&+&+o.&+%+G.o.G.G.!.G.G.!.S.G.P.h+s+f+p+v+v+t+n+z+s+w+h+u+h+n+n+n+t+s+4+4+f+B+A+s+B+F+C+z+F+F+F+F+F+F+F+F+G+G+G+G+G+          ",
"                                                                                                        t.^.^.^.I.b.I. +h.G.&+G.G.&+&+o.!+!+G.!+!+!+G.~+~+G.~+W.f+o+s+f+p+v+v+s+s+z+s+w+n+u+h+h+t+e+A+8+4+8+A+z+s+C+F+A+B+F+F+F+F+F+F+F+G+G+G+G+G+G+A+          ",
"                                                                                                      t.^.m.h.h.<.i. +h.Y.&+Y.G.&+&+o.%+!+!+G.!+!+!+G.~+~+G.^+,+p+s+r+e+d+[+^+8.o.b+d+v+e+r+[+6+t+0+s+4+;+y+w+u+E+E+v+C+F+F+F+F+F+F+G+G+G+G+G+G+G+G+            ",
"                                                                                                    [.j.m.h.L.h.Y.h.V h.Y.Y.o.&+&+&+G.!+!+&+G.!+!+&+F.~+~+/+P.t+n+2+~.G G P J G .. .y t t q C  .6+e+0+R.u+v+u+F+y+t+E+F+F+F+F+C+F+G+G+G+G+G+G+G+G+A+            ",
"                                                                                                  O m.<.h.L.}.Y.Y.o.S.&+o.h.o.o.S.o.!+!+!+G.!+!+!+U.%+~+~+<.o+r+L.Z y G G ..q s y  .q ..G J a C y ^.,+t+t+y+D+p+y+C+F+F+F+C+A+G+G+G+G+G+G+G+G+G+F+              ",
"                                                                                                [.^.^.h.L.h. +Y.I.G.&+&+G.&+!+!+G.8.F.G.G.!.S.S.G.o.G.F./.O V P J y t y C >...C Z ,...P G G y y h a q r+z+A+p+y+D+F+F+E+z+C+G+G+G+G+G+G+G+G+G+G+u+              ",
"                                                                                              w._.W h.L.h.I.Y.Y.o.&+&+&+G.!+!+!+G.:+:+:+~+F.:+:+:+U.:+*+v Q h '.S *.Z C Z '.'.P Z Z ,.C J m ..s C h y !.r+s+y+E+F+F+B+A+G+G+G+G+G+G+G+G+G+G+G+F+n+              ",
"                                                                                            ,+_.^.}.}.h.I.Y.Y.i.&+&+&+o.!+!+!+%+U.:+:+:+F.:+:+:+:+U.*+Q S S h '.S *.S P Z '.Z (.P Z ,.'.a m (.G 3 C ~.s V z+F+F+D+z+E+G+G+G+G+G+G+G+G+G+G+G+G+t+                ",
"                                                                                            [.m.<.L.b.h.I.Y.o.&+&+&+S.U.!+!+!+G.:+:+:+:+G.:+:+:+:+U.k.S *.S h '.S *.S P Z '.Z 5.y Z ,.,.G y G m ..q  .s &.b+E+z+B+G+G+G+G+G+G+G+G+G+G+G+G+E+z+                  ",
"                                                                                          w.j.^.L.L.h.Y.I.h.o.&+&+&+G.!+!+!+!+F.:+:+:+:+F.:+:+:+:+U.S S '.Q h '.S *.S '.J '.Z 5.(.C ,.'.z h h m y y t f.f.q [+F+G+G+G+G+G+G+G+G+G+G+E+y+t+z+w+                  ",
"                                                                                          _.^.E.L.b.Y.Y.Y.o.&+I.o.o.&+!+!+!+U.~+:+:+:+~+F.:+:+:+:+>.v S '.Q G G *.*.*.'.C '.'.5.'.y ,.Z m y 3 /...6. .~.J /.i.C+G+G+G+G+G+G+G+C+A+u+t+A+C+B+                    ",
"                                                                                        .+j.}.L.h.o.Y.Y.i.&+&+&+&+G.G.G.G.G.G.:+:+:+:+F.:+*+N.N.k.m S S '.Q S J *.*.*.'.C '.'.6.J y q y m Z 6.J (.(.6.t f.F.8.b+G+G+G+G+C+A+A+w+y+B+C+C+C+t+                    ",
"                                                                                        _.W L.L.h.Y.Y.Y.o.&+&+&+G.%+:+J.u.>.h 6 6 6 6 c 6 ) ) 6 m y G G ..m G s J J J J y y >...*.%.>.Z '.S S P u.6.u.c.c.F.F.!.x+C+A+A+B+z+y+C+C+C+C+C+z+                      ",
"                                                                                      .+_.<.L.b. +Y.Y.i.&+&+f.>.h g ^ , _ ) 5 ^ 5 5 5 ) 5 5 5 v '.h Z Z 5.Q %.J :.%.:.1.%.G 1.1.%.*...'.v '.N.6.>.J.J.J.&.F.f./.=.B+B+z+A+C+C+C+C+C+C+B+                        ",
"                                                                                      A.^.E.}.h.Y.G. .3 ) ) ) ) ) , _ ( ( < f e f e f < 5 f p Q 1.J %.%.:.%.%.J :.%.1.1.%.G 1.1.Q 1.*.C N.N.5.a.c.J.J.u.~. .f.8.q [+B+C+C+C+C+C+B+v+C+v+                        ",
"                                                                                    .+_.b.h.V 3 % ) % ( ( ( ( > ( ( ( ( ( [ e e f f f g f p %.Q 1.J %.%.:.%.:.J :.%.g.1.%.G 1.1.Q *.1./.k.5.N.N.l.>.6.u.J.&.&.P /.!.A+C+C+C+z+y+z+u+v+                          ",
"                                                                                    t.8 4 % % > > % % ( ( : [ < ( ( ( f < ].%.e.H.*+F.*+%.Q 1.Q 1.G %.%.:.%.:.J :.%.g.1.%.z 5.1.Q 1.1...6.k.k.k.N.c.J.6.P P &.f.f.!.b+B+y+y+B+C+w+4+                            ",
"                                                                                  9 . # % # > > > > < > > [ > f g (.J.~+F.:+:+:+:+:+F.H.Q 1.1.%.*.>.%.:.:.%.:.J :.%.g.1.%.1...1.*.*.1.g.~.N.N.N.N.~.P /.u.u.&.f.f.P E.A+C+C+C+B+                                ",
"                                                                              F / ' . + + # > > > > [ ( g  .!.F.&+~+~+!+F.:+:+:+:+:+c.v %.1.1.%.S >.%.:.%.%.:.J :.%.g.1.Q g.(.*.g.g.`.`.c.N.f.~.~.6./.u.u.u./.P ~.c.!.x+C+C+C+f+                                ",
"                                                                        |.F / o r @ . + + > [ > > c >.U.&+S.&+~+%+F.F.o.U.~+:+:+:+*+h *.1.1.1.%.S >.%.:.%.%.:.G '.%.g.1.Q g...1.5.u.l.l./.P a.N.N.k.P (.z ,.6.!.c.c.&.b+C+C+u+N / w                             ",
"                                                                      w / k d o d $ * + * > > c !.&+&+&+&+G.~+~+~+~+~+F.:+~+%+%+f.h y J C >...Z Z ..%.1.%.Z '.G C G >.>.J >. .>.u.N.g.g.x.~.5.5.5.*.J (.u.u.u.&.c.c.c.V B+B+s.I r k d w                         ",
"                                                                  K / r D D E D I $ # * # s G. +o.&+&+&+&+S.~+~+~+~+~+U.:+:+:+*+S Z (.:.:.k.5.Z J D.D.D.D.D.#+#+>.e.M.q.).M.e.6.g.g.g.1.1.>.k.5.5.k.N./.u.u.u.f.&.c. .=.r+0+R D I D k o } K                     ",
"                                                                w / u r R D +.@.b * # 8 h.I. +h.&+&+&+&+&+F.~+~+~+~+!+%+:+:+:+k.S J 5.:.:.q.:.:.Z #+{+{+{+{+{+{+{.q.M.:.q.).e.G :.g.g.V.g.>.5.N.N.N.N./.u.u.u.u.&.8.8.!.[+* l D o d u d E d x n.                ",
"                                                            n.d d u o r d D o 2.' . }.<.I.h.h.o.&+&+&+&+G.!+~+~+~+~+%+~+:+:+:+Q S J :.:.%.q.:.:.'.#+{+{+{+{+{+{+T M.q.M.).e.M.l.V.x.g.g.x.6.u.N.N.N.N./.l.u.J.K.!.8.c.8.=.! | D o R o L o B o l d.              ",
"                                                          w 1 o B r L D $.D D N U ^.E.}.I.I.I.h.G.&+&+&+G.~+~+~+~+~+F.:+:+:+S Q S J :.:.%.q.:.:.(.{+{+{+{+{+{+{+T :.e.q.-+-+-+>.g.g.x.x.x.x.~.N.N.N.N.J.c.K.c.c.c.8.c./.h.I.U } u o R o R r B o o w             ",
"                                                        w 1 o B r L r $.D +.N   P.b.E.b.I.I.L.I.S.o.o.&+G.~+~+~+~+~+F.:+:+S Q S Q J :.:.%.:.:.:.(.++{+{+{+++{+{+T q.q.-+-+M.M.l.x.x.x.x.x.V.c.N.N.N.N.J.!.c.K.K.K.!.c.F.h.I.d+  } u o D d u d o d o w           ",
"                                                      F d d u d D d I r $.d     .+E.b.h.I.I.h.S.&+&+&+o.G.F.%+~+~+~+U.:+S v *.Q S J :.:.:.:.:.:.>.{+{+{+{+++{+{+{.).M.M.M.M.M.{.1.1.g.g.V.`.f.N.u.f.f.u.c.K.K.K.K.!./.&+o.h.[+    ; r o B r L r $.r D v.        ",
"                                                    s.o k B u R E E u u /       .+^.<.I.I.I.h.&+&+&+&+I.!+!+&+S.F.U.U.Q S Q *.S S >.:.:.:.:.:.:.>.{+{+{+{+++{+{+{.:.M.M.M.M.-+Z.J.`.`.`.J.l./.c.J.N.N.N.f.K.K.K.K.&.F.&+I.}.[+      & 0 u u E E u E u o s.      ",
"                                                    o E r L r $.r $.r u w       w._.^.I.I.I.h.&+&+&+&+I.!+!+!+!+!+F.h m J m J G Z >.:.:.1.:.:.:.{.{+++{+{+++{+++D.-+M.M.-+:+`.K./.l.l.l.N.`.N.f.N.N.N.N.l.f.K.K.K.&.&+&+o.b.[+      K k o B d u d I o E o       ",
"                                                  N o k B u B R u E E l         w.j.^.h.I.I.i.&+&+&+&+G.!+!+!+!+!+G.v Z Z S S z J C ....>.G ....>.D.].D.D.].].D.9.l.l.K.K.J.J.`.l.`.`.`.x.x.k.~.a.k.k.k.5.P ..(.l.S.Y.o.I.}.[+        ' ~ d 1 B B D R d o N     ",
"                                                  d k o u o u o r d o w         w.j.^.b.h.I.o.&+&+&+&+G.!+!+!+!+~+y v '.Z Z S S ..Z 1.*.1.%.%.*.C :.).M.e.).e.M.>.q.q.q.q.q.q.q.(.g.g.x.x.x.g.P 5.5.a.k.k./.l.!+!+!+=.I.Y.}.[+        9 0 1 0 u L D $.D +.-.    ",
"                                                s.r $.r $.r L k B k u 7.        [.j.<.L.h.<.G.&+&+&+&+G.!+!+!+!+..a S Z '.Z S S J Q 1.1.1.%.%.%.J :.).e.:.M.-+-+l.V.V.V.V.V.V.q.>.g.g.g.g.x.`.c.N.N.k.k.k.P K.!+U.G.h.Y.Y.}.A.        9 0 1 u k L D $.D $.I s.  ",
"                                                o D $.D $.r L k B k u 7.        6+j.<.L.L.}.o.o.S.&+S.F.!+!+!+(.z C S '.'.Z S S J %.1.%.1.%.%.:.J e.).).M.-+-+-+c.q.q.q.x.q.x.V.l.`.`.`.`.`.`.f.k.N.N.N.N.c.&+G.U.&+i.Y.Y.}.A.        9 { / 2 d u d u r $.I ;.  ",
"                                                D D $.D $.r B d u r 0 K         .+j.^.L.L.b.Y.Y.o.o.o.!+!+!+(.z ..h S '.'.Z S S J %.1.1.1.%.Q 1.>.e.).e.M.M.M.M.>.V.V.V.V.V.x.x.6.x.g.g.g.g.g.~.k.5.5.5.6.8.G.&+&+&+h.Y.Y.^.          |.~ 1 0 u L u L o Y N D   ",
"                                                I D I d D o u u 2 k { F           _.^.L.L.b.Y.Y.Y.Y.i.G.F.G z z ..h *.'.'.S S S J %.1.%.1.%.Q 1.>.%.M.M.M.M.M.M.l.x.x.x.x.V.V.V.l.H.H.g.g.g.g.>.a.6./.c.%+G.&+&+&+&+i.Y.Y.W           w ~ 0 2 L B I $.E 2.-.-.  ",
"                                                o D $.I $.L u L k 0 1 d           [.^.L.L.b.Y.Y.Y.Y.o.%+f.a a a J h *.Z '.S S S J :.%.%.1.%.Q 1.G M.-+-+-+-+-+-+l.V.V.x.x.g.x.x.6.g.x.V.H.k.6.P /.>.u.:+:+F.&+&+&+&+o.Y.h._.          - ~ 0 r L u L $.R 2.-.-.  ",
"                                                I -.$.+.R $.u L B k 0 2 n.        t.W h.L.b.Y.Y.Y.Y.o.f.m m ..m P s C J >.,.'.S J :.%.%.1.:.%.Q >.-+-+M.M.M.M.M.l.g.q.x.V.V.V.V.6.a.(.>.>.f.N.l.(.u.:+:+:+S.&+&+&+&+o.o.}.[+        7.& { { o u r L L +.2.2.;.  ",
"                                                x 2.@.$.E $.R u E d 1 { /         .+_.<.b.b.Y.Y.Y.Y.!.m G ..G m J h '.z ..G C h y ..G G ..(.S Q J e.M.M.-+-+>+>+l.u.u.l.l.l.l.l. .u.N.N.N.N.N.l.6.:+:+:+:+S.&+&+&+&+=.h.b.A.        & { 2 k B u R E r Y @.z.v.  ",
"                                                d.-.R $.R u I o k B 1 0 { b         [.b.m.^.Y.Y.Y.Y.t m ....G m G J '.z ,.z '.z J 5.S Q 5.z ..l./.6.6.6.6.6.6.(.~.(.g.g.g.g.k.k.~.5.5.5.5.5.5.6.~+:+:+:+:+F.&+&+&+o.}.I.}.        / - 2 1 B B I $.R 2.z.@.-.d.  ",
"                                                  o $.D -.@.L $.u B B 1 0 { {       [.j.E.^.h.I.Y.y 3 G ....m G m J '.Z Z Z '.z J 5.S 5.S *.H.k.>.x.H.x.g.g.g.g.6.5.g.g.g.1.*.*.J '.5.k.k.k.k.%+!+:+:+:+:+F.&+G.o.Y.h.I.t.      / - 2 1 B B u $.L 4.z.4.X.4.)+  ",
"                                                  s.-.p.$.2.E L $.u B L r 0 ~ {     .+^.E.b.h.h.4 a t G ....m G m J Z Z Z z '.z J *.5.S Q *.*.5.>.g.g.g.x.`.`.`.u.N.H.H.g.H.H.H./.N.N.N.N.k.:+%+%+:+:+:+:+G.o.Y.Y.o.I.L.      ' = { { k k r $.$.@.z.2.z.p.1+    ",
"                                                    ;.z.p.$.2.I L $.u B u d { { ' F   W E.E.V a 3 q 4 P ....m G J J Z '.z z '.z J '.Q *.k.k.k.5.>.g.g.g.g.g.g.g.6.k.H.H.H.H.H.H./.N.N.N.k.*+:+%+%+:+!+F.G.o.Y.Y.Y.i.I.E.  w = ~ 1 k B u u E D o z.y.p.z.T.      ",
"                                                      ;.z.2.$.2.I R D o k B u 1 2 - } |.E.j.] 3 t t q y t s C G J J Z '.z z '.'.J S S k.k.k.k.k.f.H.H.H.H.H.H.H.6.5.1.1.1.1.1.1.J 5.5.k.H.:+:+%+S.G.G.%+!+G.Y.Y.Y.h.h.P.; - 2 1 E B u R $.L -.z.Y @.X.T.        ",
"                                                      c+;.z.4.$.-.Y R $.L D E B u 1 1 - w U ] 3 t t q a C h y t a y Z '.z z ,.z C *.*.S S *.S S G *.*.1.1.1.1.1.,.'.1.1.1.1.1.k.~.5.*+*+~+U.U.o.U.!+!+!+!+o.Y.Y./+<.9 ; = { r B B D $.$.R p.z.y.y.@+;._+        ",
"                                                        _+Y 4.@.2.z.p.@.L $.R u B B k 1 / = | 7 q t t t C h h C C 3 y P y C h ,./.k.k.k.5.1.5.5.>.1.1.1.g.k.H.H.u.N.`.`.`.`.`.H.P c.U.F.%+!+~+G.%+!+!+!+!+o.^+#.| & - ~ 2 u k o I $.$.@.z.z.p.X.X.@+1+          ",
"                                                          5+B.z.X.4.p.z.2.E $.$.E D o k k 1 ~ - = $ j q C h h C C 3 ....m m m P &.~.~.~.f.f.f.l./.u.u.u.u.u.u.l.f.c.f.f.f.f.f.>.F.!+~+~+~+~+~+G.!+!+!+'+ +n ; - ~ 1 k B E u I $.I D 4.z.z.p.(+@+@+c+            ",
"                                                            s.B.p.X.z.4.z.z.-.E I R E u u B E 2 ~ ~ - ; n 4 y C C 3 G m G l.l.l.&.6.6.6.6.6.6.u.8.l.u.u.u.u.J.J.c.u.J.J.J.J.a.:+F.~+~+~+~+~+~+G./+W.#.| = = ~ 1 E B u u R $.$.@.-.z.@.p.@+(+@+}+                ",
"                                                                T.p.z.X.p.2.z.-.-.@.L $.$.I u u B u 2 { = & = | 7 7 s ~.l.l.l.l.&.u.u.u.u.u.u.6.P 5.a.a.5.a.a.J./.u.J.J.J.a.:+:+F.~+~+!+/+C.#.| = & - ~ 2 u k k k I $.$.R -.p.X.O.p.y.@+@+@+1+                  ",
"                                                                  )+T.y.z.z.4.p.z.z.p.-.E $.$.R u u r u u k 2 1 { & & ; | 7 A q 3./.F.6.6.6.6.6./.a.a.a.a.,.'.'.P Z '.5.!+'+^+C.H #.n | ; - - ~ 2 u B B u u u E D $.R -.p.X.z.p.@+<+(+(+B._+                    ",
"                                                                      v.p.B.@+(+@+p.p.z.z.2.-.R $.D E I u u u B B E k 2 1 & = & & = ; ; F n #.H ` H H H 7 ` ` X n n n | ; = & & & { ~ 1 2 l B B u u u E $.$.$.R -.o z.X.z.p.@+<+(+9+|+1+                        ",
"                                                                          1+]+(+@+(+(+p.p.z.z.z.Y @.R R $.$.$.R I u u u u B B u u k 2 2 1 1 ~ - & - { ~ ~ ~ ~ ~ ~ ~ { 1 2 k u B B B u u k r r E $.$.$.R -.4.p.X.X.z.;.p.(+<+(+9+|+_+                            ",
"                                                                          R.0.n.B.|+|+@+<+@+p.@.p.X.X.z.p.4.-.@.R $.$.R r E I I u u u u k u B r B B B B B B E u u u r o u u u I E R +.$.$.$.R R R 4.p.X.X.X.p.y.@+(+7+B.(+9+]+s.                                ",
"                                                                    0+R.R.4+4+f+4+3+v.]+|+@+@+@+(+@+y.p.p.z.X.X.z.p.-.o R R R +.$.$.$.$.$.$.R r E R R R R R R +.$.$.$.I $.$.$.+.R R -.-.4.p.p.4.X.X.z.p.@+@+7+7+(+9+a+]+}+d.                                    ",
"                                                                    R.4+n+0+8+f+h+0+n+4+n.T.]+a+9+(+(+7+<+X.@+y.p.p.z.p.X.X.z.z.y.p.2.4.4.-.-.o R -.-.-.-.-.-.-.-.-.-.;.4.p.p.z.X.X.X.X.@+p.p.p.4.@+<+7+(+(+a+9+9+}+5+                                          ",
"                                                                e+;+h+h+f+8+e+n+n+e+n+e+0+p+R.)+_+]+9+9+7+(+@+(+7+<+4.@+@+@+y.y.p.p.z.@+X.X.X.p.X.X.X.X.X.X.X.X.X.X.X.p.z.z.p.p.@+@+@+@+(+7+7+7+y.(+7+a+9+]+_+                                                  ",
"                                                                0+n+h+h+8+e+e+e+f+e+e+e+f+p+o+p+p+A+u+j+5+1+|+9+a+9+p.(+(+(+<+7+7+7+<+(+@+@+@+4.@+@+@+@+@+@+@+@+@+@+|+|+p.7+7+7+<+(+(+9+a+g+l+g+9+]+1+s.                                                        ",
"                                                            0+R.n+o+0+h+8+f+f+8+f+e+f+f+e+w+s+t+p+f+e+f+p+s+P.X M v.T.|+9+a+a+a+g+a+a+7+9+(+@+B.(+(+9+9+9+9+9+9+9+k+g+g+]+g+l+g+g+g+9+]+1+$+Q.r.3+                                                              ",
"                                                          R.R.R.f+o+f+f+8+0+n+4+h+0+0+n+n+8+0+f+p+p+n+n+e+4+8+P.8 4 q V W H #.M M x $+T.}+|+9+q+q+q+q+q+k+k+k+m+m+m+m+i+1+_+Q.r.=+W.L.L.h.h._..+                                                                ",
"                                                      ;+0.;+R.0+e+n+f+0+8+4+s+4+n+e+o+f+v+y+w+s+h+f+h+p+s+t+s+o+n+w.] ] ] 4 3 3 ! ! 4 s 8. +2+W.W.W.2+2+b+^+I.I.h. +^+^+^+Y.h. + + + +^.^.t.                                                                    ",
"                                                    0.4+4+e+4+0+e+f+e+;+f+e+o+e+h+w+A+z+w+y+B+G+G+G+G+C+B+F+E+C+B+A+n+i i 8 q q q t V  + + + + + +h.Y.Y.Y.Y.Y.i.I.Y.Y.Y.Y.I.h.I.h.}.W A..+                                                                      ",
"                                                  R.0.0+8+0+0+8+f+8+o+4+n+R.p+A+z+t+n+n+s+w+z+w+y+A+G+G+G+G+G+G+G+G+G+B+d+W i ] V }.<.h.I. + + + +h.Y.Y.Y.Y.Y.h.Y.Y.o.h.h.<.}.b.b.[..+                                                                          ",
"                                                0.R.;+;+8+8+f+4+h+4+p+;+s+y+p+h+s+u+t+t+p+s+p+t+w+u+t+y+A+F+G+G+G+G+G+G+G+B+w.t.j.m.E._.b.}.}.}.b.<.h.h.h.b.b.<.}.b.E.L.<.b.j.[+                                                                                ",
"                                            R.0.R.;+8+;+8+;+n+8+h+;+o+w+p+h+h+o+o+p+t+A+B+z+w+t+p+v+t+s+s+f+s+A+F+G+G+G+C+          .+A.W b.E.E.E.<.L.L.L.L.L.<.L.b.m.[+.+                                                                                      ",
"                                        p+8+R.;+R.;+;+;+0+R.f+e+e+p+p+e+0+h+n+o+n+t+t+n+t+v+z+A+B+B+B+B+A+v+s+h+4+p+A+B+                    [.w.t.[.W [.t.t.[.w.w.                                                                                              ",
"                                  p+p+e+8+;+;+;+;+8+R.;+8+f+o+s+w+o+8+e+h+f+f+p+s+n+t+u+u+s+h+p+t+w+w+w+w+v+A+o+0.                                                                                                                                              ",
"                            p+s+h+8+e+n+h+;+R.R.8+8+8+0+f+8+0+0+0+h+p+s+o+n+u+s+h+f+h+e+8+p+v+u+p+f+n+v+w+n+                                                                                                                                                    ",
"                      n+s+o+e+e+p+n+4+;+  ;+;+;+e+n+f+o+t+z+B+y+s+f+f+8+4+e+h+s+s+t+n+s+v+s+h+f+s+A+t+p+                                                                                                                                                        ",
"                o+s+s+n+h+s+o+8+0.        0+0+8+4+R.8+4+8+p+n+w+C+F+F+F+D+z+s+h+8+f+t+w+s+p+u+t+t+                                                                                                                                                              ",
"          h+s+t+p+p+s+s+0+R.                    8+8+8+f+4+;+o+h+h+s+A+F+F+F+F+F+y+0.0.h+u+v+                                                                                                                                                                    ",
"      h+e+n+s+t+v+f+4+                              8+e+p+f+8+8+;+e+8+8+w+E+E+v+                                                                                                                                                                                ",
"  0+4+e+f+o+n+8+                                          o+s+u+u+o+8+o+e+h+                                                                                                                                                                                    ",
"  f+n+                                                        s+t+p+o+                                                                                                                                                                                          ",
"                                                                                                                                                                                                                                                                "};

Added icons/kill_spindex.xpm.































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
/* XPM */
static const char * kill_spindex_xpm[] = {
"16 16 124 2",
"  	c None",
". 	c #ECCE40",
"+ 	c #EBCC3F",
"@ 	c #EACB3E",
"# 	c #E9C93C",
"$ 	c #E9C73B",
"% 	c #E8C43A",
"& 	c #E7C238",
"* 	c #E6C036",
"= 	c #E5BD35",
"- 	c #E4BB33",
"; 	c #E3B831",
"> 	c #FAED9A",
", 	c #F9EB99",
"' 	c #F9E897",
") 	c #F8E594",
"! 	c #F7E291",
"~ 	c #F6DF8E",
"{ 	c #F5DB8B",
"] 	c #EBC756",
"^ 	c #F1D964",
"/ 	c #FAEB9A",
"( 	c #F4D848",
"_ 	c #F3D344",
": 	c #F1CE3F",
"< 	c #F0C83A",
"[ 	c #F5DC8C",
"} 	c #EDCB62",
"| 	c #EACA3D",
"1 	c #F9E993",
"2 	c #F7E172",
"3 	c #F3D445",
"4 	c #F2CE41",
"5 	c #F0C93C",
"6 	c #F5DC8A",
"7 	c #EFD070",
"8 	c #E4BB3D",
"9 	c #EFD45B",
"0 	c #F9EA99",
"a 	c #F4D647",
"b 	c #F2D042",
"c 	c #F0CB3D",
"d 	c #F3D56E",
"e 	c #F3D77F",
"f 	c #E7C04A",
"g 	c #F5E180",
"h 	c #F8E68E",
"i 	c #F3D243",
"j 	c #F1CD3F",
"k 	c #EFC739",
"l 	c #EAC658",
"m 	c #ECCD4F",
"n 	c #F9E998",
"o 	c #F3D54A",
"p 	c #F1CF45",
"q 	c #F0CA40",
"r 	c #EEC238",
"s 	c #F4D989",
"t 	c #E1B42E",
"u 	c #E0B12C",
"v 	c #DFAE2B",
"w 	c #DEAC29",
"x 	c #DCA927",
"y 	c #DBA625",
"z 	c #DAA323",
"A 	c #F2DA75",
"B 	c #F8E693",
"C 	c #F7E391",
"D 	c #F6E08D",
"E 	c #F5DB8A",
"F 	c #F4D788",
"G 	c #F2D384",
"H 	c #F1CF7F",
"I 	c #F0CC7C",
"J 	c #EFC97A",
"K 	c #E3B448",
"L 	c #E2B62F",
"M 	c #F3D786",
"N 	c #EBB62F",
"O 	c #ECBC4A",
"P 	c #F1CE80",
"Q 	c #D68B39",
"R 	c #C35812",
"S 	c #BC4204",
"T 	c #B94503",
"U 	c #E0B22D",
"V 	c #EECC70",
"W 	c #F2D283",
"X 	c #F1CE7E",
"Y 	c #D58A35",
"Z 	c #D17438",
"` 	c #F7B58D",
" .	c #FED6B8",
"..	c #F5A872",
"+.	c #CB6B2D",
"@.	c #DFAF2B",
"#.	c #E7BD55",
"$.	c #DEAA2E",
"%.	c #BC4C06",
"&.	c #F6B58D",
"*.	c #FF924D",
"=.	c #FF7711",
"-.	c #FF8621",
";.	c #EB8A40",
">.	c #B94403",
",.	c #E7BC4F",
"'.	c #E6BA4C",
").	c #DCA726",
"!.	c #FECDAE",
"~.	c #FFFFFF",
"{.	c #EF7F18",
"].	c #DFAE2D",
"^.	c #DEAB2B",
"/.	c #F49D63",
"(.	c #FF7F18",
"_.	c #F87600",
":.	c #EE7600",
"<.	c #E16803",
"[.	c #C3571A",
"}.	c #C96425",
"|.	c #E67721",
"1.	c #EA7905",
"2.	c #DD6401",
"3.	c #BD4D04",
"                                ",
"      . + @ # $ % & * = - ;     ",
"      + > , ' ) ! ~ { ] ;       ",
"    + ^ / ( _ : < [ } ;         ",
"    | 1 2 3 4 5 6 7 8           ",
"    9 0 a b c d e f             ",
"  $ g h i j k [ l               ",
"  m n o p q r s t u v w x y z   ",
"% A B C D 6 E F G H I J K z     ",
"& * = - ; L M N O P Q R S T     ",
"          U V W X Y Z `  ...+.  ",
"          @.G #.$.%.&.*.=.-.;.>.",
"        @.,.'.).  S !.~.~.~.{.S ",
"        ].^.y     T /.(._.:.<.T ",
"      w x         [.}.|.1.2.3.  ",
"                      T S T     "};

Added icons/memdb_clock.xpm.



































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
/* XPM */
static const char * memdb_clock_xpm[] = {
"16 16 158 2",
"  	c None",
". 	c #C6AB7E",
"+ 	c #CDB378",
"@ 	c #D0B87B",
"# 	c #CDB47A",
"$ 	c #C4A971",
"% 	c #B99D71",
"& 	c #C2AA86",
"* 	c #D2BA78",
"= 	c #E3D9C8",
"- 	c #EAE7DD",
"; 	c #F1F1EE",
"> 	c #F0F0EC",
", 	c #E4E0D2",
"' 	c #D2C4A8",
") 	c #B89C67",
"! 	c #C0A885",
"~ 	c #DCCC97",
"{ 	c #EEEBE1",
"] 	c #D9E1EE",
"^ 	c #ACBEDF",
"/ 	c #96ADD5",
"( 	c #92AAD4",
"_ 	c #A3B7DC",
": 	c #CEDAE8",
"< 	c #DFD9C6",
"[ 	c #B69B68",
"} 	c #CCB374",
"| 	c #ECE9DF",
"1 	c #C2CFE6",
"2 	c #AEBFDF",
"3 	c #DCE3F1",
"4 	c #ECF1F3",
"5 	c #EBF1F4",
"6 	c #D9E2F1",
"7 	c #A3BADC",
"8 	c #AFC1DE",
"9 	c #D8CFB7",
"0 	c #A48358",
"a 	c #BCA177",
"b 	c #DBCFB7",
"c 	c #D7E0ED",
"d 	c #AABDDE",
"e 	c #FFFFFF",
"f 	c #EEF0F0",
"g 	c #DAE5E7",
"h 	c #F7FFFF",
"i 	c #F3FEFF",
"j 	c #98B4DC",
"k 	c #C4D1E1",
"l 	c #BBA473",
"m 	c #987C59",
"n 	c #BEA26D",
"o 	c #E6E1D3",
"p 	c #A4B9DB",
"q 	c #D6E3F1",
"r 	c #F5FBFE",
"s 	c #F3F5F5",
"t 	c #959E9F",
"u 	c #E9F0F0",
"v 	c #F2F8F8",
"w 	c #ADB9BE",
"x 	c #C2DAF0",
"y 	c #8BA7D1",
"z 	c #D3CAA9",
"A 	c #9B7B53",
"B 	c #BDA16C",
"C 	c #EEECE4",
"D 	c #8AA5D1",
"E 	c #E9F6FA",
"F 	c #EEF8FD",
"G 	c #F9FFFF",
"H 	c #798081",
"I 	c #A4AEB1",
"J 	c #777F81",
"K 	c #BAC6C9",
"L 	c #D3F0FA",
"M 	c #7295C9",
"N 	c #E2DFC9",
"O 	c #9E7B54",
"P 	c #B89A67",
"Q 	c #ECEADD",
"R 	c #819FCF",
"S 	c #E2F3FA",
"T 	c #E9F6FD",
"U 	c #E3F0F2",
"V 	c #848C8D",
"W 	c #C2CFD2",
"X 	c #EBFBFF",
"Y 	c #CCECFA",
"Z 	c #6D90C7",
"` 	c #E1DDC1",
" .	c #9D7953",
"..	c #AD8E5E",
"+.	c #DDD3B7",
"@.	c #90AAD1",
"#.	c #C1DBF0",
"$.	c #E6F7FF",
"%.	c #E3F2FA",
"&.	c #B6C0C5",
"*.	c #DEEDF1",
"=.	c #E8FCFF",
"-.	c #A9C6AE",
";.	c #719760",
">.	c #668E4F",
",.	c #5F8744",
"'.	c #6E773E",
").	c #A0855E",
"!.	c #C0A978",
"~.	c #C6D1DA",
"{.	c #88AAD9",
"].	c #EBFEFF",
"^.	c #EEFAFF",
"/.	c #F2FDFF",
"(.	c #F2FEFF",
"_.	c #ABC5A8",
":.	c #81AB61",
"<.	c #B4D495",
"[.	c #D0E6BA",
"}.	c #8FBB6A",
"|.	c #578F2D",
"1.	c #376B19",
"2.	c #A28257",
"3.	c #D8CCA2",
"4.	c #A5B7CD",
"5.	c #89AAD8",
"6.	c #CFDFEF",
"7.	c #F3F6FA",
"8.	c #F3F5FA",
"9.	c #618A49",
"0.	c #B1D390",
"a.	c #B1D692",
"b.	c #8CBC65",
"c.	c #8FBC67",
"d.	c #A68855",
"e.	c #D6C896",
"f.	c #BFCACC",
"g.	c #869FC8",
"h.	c #7692C5",
"i.	c #7390C4",
"j.	c #4C7B31",
"k.	c #B6D49C",
"l.	c #B2D295",
"m.	c #9A7850",
"n.	c #B1975A",
"o.	c #CEBD85",
"p.	c #DED6A4",
"q.	c #DED5A0",
"r.	c #3E6E1E",
"s.	c #8BBA62",
"t.	c #87BA60",
"u.	c #87B960",
"v.	c #917553",
"w.	c #93724E",
"x.	c #97744D",
"y.	c #606E31",
"z.	c #538C28",
"A.	c #8DBA64",
"                                ",
"          . + @ # $ %           ",
"      & * = - ; > , ' )         ",
"    ! ~ { ] ^ / ( _ : < [       ",
"    } | 1 2 3 4 5 6 7 8 9 0     ",
"  a b c d e f g h h i j k l m   ",
"  n o p q r s t u v w x y z A   ",
"  B C D E F G H I J K L M N O   ",
"  P Q R S T U V J W X Y Z `  .  ",
"  ..+.@.#.$.%.&.*.=.-.;.>.,.'.  ",
"  ).!.~.{.].^./.(._.:.<.[.}.|.1.",
"    2.3.4.5.6.7.8.9.0.a.e b.c.1.",
"      d.e.f.g.h.i.j.k.e e e l.1.",
"        m.n.o.p.q.r.s.t.e u.c.1.",
"          v.w.x.x.y.z.A.l.A.z.1.",
"                    1.1.1.1.1.  "};

Added icons/memdb_load.xpm.

























































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
/* XPM */
static const char * memdb_load_xpm[] = {
"16 16 121 2",
"  	c None",
". 	c #BABABA",
"+ 	c #B8B8B8",
"@ 	c #B7B7B7",
"# 	c #B6B6B6",
"$ 	c #B4B4B4",
"% 	c #B3B3B3",
"& 	c #BBBBBB",
"* 	c #D0D0D0",
"= 	c #E8E8E8",
"- 	c #F3F3F3",
"; 	c #FDFDFD",
"> 	c #FCFCFC",
", 	c #EDEDED",
"' 	c #E0E0E0",
") 	c #C2C2C2",
"! 	c #ADADAD",
"~ 	c #E1E1E1",
"{ 	c #FEFEFE",
"] 	c #FFFFFF",
"^ 	c #FBFBFB",
"/ 	c #CFCFCF",
"( 	c #A9A9A9",
"_ 	c #B9B9B9",
": 	c #F8F8F8",
"< 	c #EAEAEA",
"[ 	c #A7A7A7",
"} 	c #F7F7F7",
"| 	c #E7E7E7",
"1 	c #EFEFEF",
"2 	c #F6F6F6",
"3 	c #FAFAFA",
"4 	c #F0F0F0",
"5 	c #DEDEDE",
"6 	c #C3C3C3",
"7 	c #E6E6E6",
"8 	c #A5A5A5",
"9 	c #B5B5B5",
"0 	c #EBEBEB",
"a 	c #D6D6D6",
"b 	c #D5D5D5",
"c 	c #D1D1D1",
"d 	c #BCBCBC",
"e 	c #C0C0C0",
"f 	c #E5E5E5",
"g 	c #A3A3A3",
"h 	c #F5F5F5",
"i 	c #EEEEEE",
"j 	c #E2E2E2",
"k 	c #CDCDCD",
"l 	c #6EA43C",
"m 	c #659F31",
"n 	c #DEE1DD",
"o 	c #A0A0A0",
"p 	c #B2B2B2",
"q 	c #F4F4F4",
"r 	c #DDDDDD",
"s 	c #E3E3E3",
"t 	c #C9C9C9",
"u 	c #67A036",
"v 	c #81B35A",
"w 	c #579828",
"x 	c #9B9E99",
"y 	c #B0B0B0",
"z 	c #6FA53D",
"A 	c #6EA338",
"B 	c #68A134",
"C 	c #629D30",
"D 	c #7CAF55",
"E 	c #AACB91",
"F 	c #74AB4F",
"G 	c #468F18",
"H 	c #AEAEAE",
"I 	c #F2F2F2",
"J 	c #D8D8D8",
"K 	c #6BA337",
"L 	c #B0CE96",
"M 	c #ADCD94",
"N 	c #A8CB90",
"O 	c #90BC74",
"P 	c #A1C78A",
"Q 	c #68A546",
"R 	c #358707",
"S 	c #ACACAC",
"T 	c #D4D4D4",
"U 	c #639F31",
"V 	c #8EBA6F",
"W 	c #89B86B",
"X 	c #85B666",
"Y 	c #80B361",
"Z 	c #82B567",
"` 	c #98C283",
" .	c #5CA03C",
"..	c #257F00",
"+.	c #DBDBDB",
"@.	c #5B9B29",
"#.	c #A9CA90",
"$.	c #A5C88D",
"%.	c #A1C68A",
"&.	c #9EC588",
"*.	c #85B66A",
"=.	c #97C282",
"-.	c #66A548",
";.	c #217D00",
">.	c #CECECE",
",.	c #529722",
"'.	c #4A911C",
").	c #448F16",
"!.	c #3C8B10",
"~.	c #5E9F3A",
"{.	c #96C180",
"].	c #62A346",
"^.	c #217D03",
"/.	c #A1A1A1",
"(.	c #9F9F9F",
"_.	c #ABABAB",
":.	c #959595",
"<.	c #2E8306",
"[.	c #5FA143",
"}.	c #207B01",
"|.	c #1E7B03",
"                                ",
"          . + @ # $ %           ",
"      & * = - ; > , ' ) !       ",
"    . ~ { ] ] ] ] ] ] ^ / (     ",
"    _ : { ] ] ] ] ] ] ^ < [     ",
"    @ } | 1 2 ^ 3 4 5 6 7 8     ",
"    9 2 0 5 a b c 6 d e f g     ",
"    $ h i 7 j 7 ~ k l m n o     ",
"    p q < ~ r s 5 t u v w x     ",
"    y - | r z A B C D E F G     ",
"    H I j J K L M E N O P Q R   ",
"    S 4 5 T U M V W X Y Z `  ...",
"    ( 5 - +.@.#.$.%.&.*.=.-.;.  ",
"      8 >., ,.'.).!.~.{.].^.    ",
"        /.(./._.[ :.<.[.}.      ",
"                    ;.|.        "};

Added icons/memdb_new.xpm.

























































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
/* XPM */
static const char * memdb_new_xpm[] = {
"16 16 137 2",
"  	c None",
". 	c #BABABA",
"+ 	c #B8B8B8",
"@ 	c #B7B7B7",
"# 	c #B6B6B6",
"$ 	c #B4B4B4",
"% 	c #B3B3B3",
"& 	c #BBBBBB",
"* 	c #D0D0D0",
"= 	c #E8E8E8",
"- 	c #F3F3F3",
"; 	c #FDFDFD",
"> 	c #FCFCFC",
", 	c #EDEDED",
"' 	c #E0E0E0",
") 	c #C2C2C2",
"! 	c #ADADAD",
"~ 	c #E1E1E1",
"{ 	c #FEFEFE",
"] 	c #FFFFFF",
"^ 	c #FBFBFB",
"/ 	c #CFCFCF",
"( 	c #A9A9A9",
"_ 	c #EAC93D",
": 	c #E2C54C",
"< 	c #EACC55",
"[ 	c #EACA55",
"} 	c #E9C753",
"| 	c #E7C34E",
"1 	c #E8C559",
"2 	c #FCF7E8",
"3 	c #EAEAEA",
"4 	c #A7A7A7",
"5 	c #F3DC73",
"6 	c #F6E289",
"7 	c #F4DE84",
"8 	c #F3D981",
"9 	c #F1D378",
"0 	c #E8C14F",
"a 	c #F0DFAF",
"b 	c #F8F7F6",
"c 	c #E7E7E7",
"d 	c #D8D8D8",
"e 	c #C7C7C7",
"f 	c #E6E6E6",
"g 	c #A5A5A5",
"h 	c #E8C63B",
"i 	c #F8E793",
"j 	c #F4D85F",
"k 	c #F6E090",
"l 	c #F2D57C",
"m 	c #E9C352",
"n 	c #CFBD89",
"o 	c #CCCCCC",
"p 	c #C9C9C9",
"q 	c #B5B5B5",
"r 	c #C1C1C1",
"s 	c #E5E5E5",
"t 	c #A3A3A3",
"u 	c #E8C63A",
"v 	c #F1D86A",
"w 	c #F8E796",
"x 	c #F2CF47",
"y 	c #F4DC89",
"z 	c #E2B837",
"A 	c #E3D098",
"B 	c #E2E2E2",
"C 	c #CDCDCD",
"D 	c #E3E3E3",
"E 	c #A0A0A0",
"F 	c #E7C338",
"G 	c #F8E68F",
"H 	c #F7E38D",
"I 	c #F2D260",
"J 	c #F4D784",
"K 	c #E1B63A",
"L 	c #E0C47B",
"M 	c #DDC27D",
"N 	c #DFC179",
"O 	c #DCC183",
"P 	c #CBC4B6",
"Q 	c #BDBDBD",
"R 	c #BFBFBF",
"S 	c #9E9E9E",
"T 	c #E7C238",
"U 	c #F0D76D",
"V 	c #EFD267",
"W 	c #EDCF66",
"X 	c #F3D984",
"Y 	c #F4D788",
"Z 	c #F1CF7D",
"` 	c #E8BD58",
" .	c #E6B852",
"..	c #DAA425",
"+.	c #D9C393",
"@.	c #C5C2BD",
"#.	c #9B9B9B",
"$.	c #E4BC34",
"%.	c #E3B831",
"&.	c #E1B52F",
"*.	c #DCB137",
"=.	c #F0D07D",
"-.	c #EDC76D",
";.	c #E3B345",
">.	c #D8B567",
",.	c #DBD3C3",
"'.	c #C0C0C0",
").	c #969696",
"!.	c #DCAD2F",
"~.	c #E7BC52",
"{.	c #DBAC39",
"].	c #D6C192",
"^.	c #D2D2D2",
"/.	c #DBDBDB",
"(.	c #D6D6D6",
"_.	c #B0B0B0",
":.	c #DEDEDE",
"<.	c #909090",
"[.	c #DEAD2A",
"}.	c #E4B644",
"|.	c #DCB863",
"1.	c #F1EEE6",
"2.	c #C4C4C4",
"3.	c #8B8B8B",
"4.	c #DCA927",
"5.	c #C7A657",
"6.	c #CECECE",
"7.	c #F4F4F4",
"8.	c #F5F5F5",
"9.	c #EFEFEF",
"0.	c #8A8A8A",
"a.	c #A1A1A1",
"b.	c #9F9F9F",
"c.	c #ABABAB",
"d.	c #959595",
"e.	c #8D8D8D",
"f.	c #898989",
"                                ",
"              . + @ # $ %       ",
"          & * = - ; > , ' ) !   ",
"        . ~ { ] ] ] ] ] ] ^ / ( ",
"      _ : < [ } | 1 2 ] ] ^ 3 4 ",
"    _ 5 6 7 8 9 0 a b c d e f g ",
"    h i j k l m n o p q @ r s t ",
"  u v w x y z A B f ~ C ) ) D E ",
"  F G H I J K L M N O P Q R B S ",
"T U V W X Y Z `  ...+.@.+ & ~ #.",
"  $.%.&.*.=.-.;.>.,.d '.% @ ' ).",
"        !.~.{.].^./.(.R _.% :.<.",
"      [.}.|.1./.^./.(.'.p f 2.3.",
"      4.5.g 6., 7.8.7.9.B . 0.  ",
"            a.b.a.c.4 d.e.f.    ",
"                                "};

Added icons/memdb_save.xpm.



































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
/* XPM */
static const char * memdb_save_xpm[] = {
"16 16 158 2",
"  	c None",
". 	c #BABABA",
"+ 	c #B8B8B8",
"@ 	c #B7B7B7",
"# 	c #B6B6B6",
"$ 	c #B4B4B4",
"% 	c #B3B3B3",
"& 	c #BBBBBB",
"* 	c #D0D0D0",
"= 	c #E8E8E8",
"- 	c #F3F3F3",
"; 	c #FDFDFD",
"> 	c #FCFCFC",
", 	c #EDEDED",
"' 	c #E0E0E0",
") 	c #C2C2C2",
"! 	c #ADADAD",
"~ 	c #E1E1E1",
"{ 	c #FEFEFE",
"] 	c #FFFFFF",
"^ 	c #FBFBFB",
"/ 	c #CFCFCF",
"( 	c #A9A9A9",
"_ 	c #B9B9B9",
": 	c #F8F8F8",
"< 	c #EAEAEA",
"[ 	c #A7A7A7",
"} 	c #F7F7F7",
"| 	c #E7E7E7",
"1 	c #EFEFEF",
"2 	c #F6F6F6",
"3 	c #FAFAFA",
"4 	c #F0F0F0",
"5 	c #DEDEDE",
"6 	c #C3C3C3",
"7 	c #E6E6E6",
"8 	c #A5A5A5",
"9 	c #B5B5B5",
"0 	c #EBEBEB",
"a 	c #D6D6D6",
"b 	c #D5D5D5",
"c 	c #D1D1D1",
"d 	c #BCBCBC",
"e 	c #C0C0C0",
"f 	c #E5E5E5",
"g 	c #A3A3A3",
"h 	c #F5F5F5",
"i 	c #EEEEEE",
"j 	c #E2E2E2",
"k 	c #6E97D4",
"l 	c #7B9ED4",
"m 	c #7198D0",
"n 	c #82A4D6",
"o 	c #688ECD",
"p 	c #6990CD",
"q 	c #759AD0",
"r 	c #7399D1",
"s 	c #628BC8",
"t 	c #B2B2B2",
"u 	c #F4F4F4",
"v 	c #DDDDDD",
"w 	c #E3E3E3",
"x 	c #658DCC",
"y 	c #B0CDF3",
"z 	c #B3C7E3",
"A 	c #A1BFEA",
"B 	c #6089C9",
"C 	c #B0B0B0",
"D 	c #D9D9D9",
"E 	c #5B86C7",
"F 	c #9EC0EF",
"G 	c #6E93CC",
"H 	c #F7FBFF",
"I 	c #F1F8FF",
"J 	c #8CAFE4",
"K 	c #618AC7",
"L 	c #AEAEAE",
"M 	c #F2F2F2",
"N 	c #D8D8D8",
"O 	c #DCDCDC",
"P 	c #5D88C8",
"Q 	c #A1BFEF",
"R 	c #FAFCFD",
"S 	c #FBFCFE",
"T 	c #FDFDFE",
"U 	c #FCFDFE",
"V 	c #FAFBFD",
"W 	c #FBFCFD",
"X 	c #85A8DD",
"Y 	c #537FC1",
"Z 	c #ACACAC",
"` 	c #D4D4D4",
" .	c #D2D2D2",
"..	c #DBDBDB",
"+.	c #658DCA",
"@.	c #99B8EA",
"#.	c #7EA5DD",
"$.	c #80A6DD",
"%.	c #7CA3DB",
"&.	c #7AA0D9",
"*.	c #79A0D9",
"=.	c #789FD8",
"-.	c #789ED8",
";.	c #5D84BF",
">.	c #618BC9",
",.	c #92B5E6",
"'.	c #81A7E2",
").	c #81A7E1",
"!.	c #7DA3DE",
"~.	c #7BA1DC",
"{.	c #799FDB",
"].	c #779ED9",
"^.	c #739AD4",
"/.	c #577EBB",
"(.	c #CECECE",
"_.	c #5481C4",
":.	c #97B6EA",
"<.	c #EAF3F3",
"[.	c #E6F1ED",
"}.	c #E6F1EF",
"|.	c #E6F0EF",
"1.	c #E5F1ED",
"2.	c #EDF5F3",
"3.	c #799CD5",
"4.	c #4470B0",
"5.	c #A1A1A1",
"6.	c #9F9F9F",
"7.	c #ABABAB",
"8.	c #517FC3",
"9.	c #9AB6EF",
"0.	c #E8F3EA",
"a.	c #84BF51",
"b.	c #98C96F",
"c.	c #99C971",
"d.	c #84BF54",
"e.	c #E9F4E4",
"f.	c #7B9CDD",
"g.	c #3A69AA",
"h.	c #5583C6",
"i.	c #BACEEF",
"j.	c #FFFFDD",
"k.	c #C7EE87",
"l.	c #D7F4A2",
"m.	c #D7F6A2",
"n.	c #C7EE8C",
"o.	c #FFFFE0",
"p.	c #85A2DD",
"q.	c #3E6AAB",
"r.	c #3368BA",
"s.	c #5884C3",
"t.	c #688BD3",
"u.	c #708FE1",
"v.	c #6C8DDC",
"w.	c #6D8BDA",
"x.	c #6E8AD7",
"y.	c #6C8BCD",
"z.	c #446DAB",
"A.	c #2E5FA6",
"      . + @ # $ %               ",
"  & * = - ; > , ' ) !           ",
". ~ { ] ] ] ] ] ] ^ / (         ",
"_ : { ] ] ] ] ] ] ^ < [         ",
"@ } | 1 2 ^ 3 4 5 6 7 8         ",
"9 2 0 5 a b c 6 d e f g         ",
"$ h i 7 j 7 k l m n o p q r s   ",
"t u < ~ v w x y ] z ] ] ] ] A B ",
"C - | v D ' E F ] G ] ] H I J K ",
"L M j N b O P Q R S T U V W X Y ",
"Z 4 5 `  ...+.@.#.$.%.&.*.=.-.;.",
"( 5 - .. ...>.,.'.).!.~.{.].^./.",
"  8 (., u h _.:.<.[.}.|.1.2.3.4.",
"    5.6.5.7.8.9.0.a.b.c.d.e.f.g.",
"            h.i.j.k.l.m.n.o.p.q.",
"            r.s.t.u.v.w.x.y.z.A."};

Added icons/network.xpm.

















































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/* XPM */
static const char * network_xpm[] = {
"16 16 37 1",
" 	c None",
".	c #707070",
"+	c #C5C5C5",
"@	c #A8A8A8",
"#	c #9A9A9A",
"$	c #D1D1D1",
"%	c #737373",
"&	c #A4A4A4",
"*	c #979797",
"=	c #A0A0A0",
"-	c #D5D5D5",
";	c #989898",
">	c #777777",
",	c #C7C7C7",
"'	c #A2A2A2",
")	c #8D8D8D",
"!	c #9B9B9B",
"~	c #A1A1A1",
"{	c #7F7F7F",
"]	c #8A8A8A",
"^	c #949494",
"/	c #A7A7A7",
"(	c #909090",
"_	c #939393",
":	c #A3A3A3",
"<	c #7B7B7B",
"[	c #A5A5A5",
"}	c #9D9D9D",
"|	c #7D7D7D",
"1	c #9F9F9F",
"2	c #848484",
"3	c #727272",
"4	c #7E7E7E",
"5	c #858585",
"6	c #9E9E9E",
"7	c #DADADA",
"8	c #FFFFFF",
"                ",
"                ",
"     888888     ",
"    8@/[&~=8    ",
"   8@87-$,+!8   ",
"888@8&=1#;;+^888",
"866666:88*666668",
"8777775  {777778",
"855555#88%.....8",
"888'8*(]24<+>888",
"   8}87-$,+38   ",
"    8_)5|>%8    ",
"     888888     ",
"                ",
"                ",
"                "};

Added indent_me.





>
>
1
2
indent -npsl -nbfda -l80 -i2 -ci2 -cbi2 -cp2 -ts2 -cli2 -bl -ce -lp -npcs -nut *.h *.cpp

Added mac_resource/wxmac.icns.

cannot compute difference between binary files

Changes to win_resource/icon.ico.

cannot compute difference between binary files

Added win_resource/spatialite-icon.png.

cannot compute difference between binary files