[saga] 01/01: Imported Upstream version 2.2.3+dfsg

Johan Van de Wauw johanvdw-guest at moszumanska.debian.org
Thu Dec 17 22:55:08 UTC 2015


This is an automated email from the git hooks/post-receive script.

johanvdw-guest pushed a commit to annotated tag upstream/2.2.3+dfsg
in repository saga.

commit af272ed47d2335f459fb6f56d2898a88ee1bc7e8
Author: Johan Van de Wauw <johan at vandewauw.be>
Date:   Thu Dec 17 19:19:33 2015 +0100

    Imported Upstream version 2.2.3+dfsg
---
 README                                             |     2 +-
 configure                                          |    23 +-
 configure.ac                                       |     5 +-
 src/modules/db/db_pgsql/db_pgsql.cpp               |    55 +-
 src/modules/db/db_pgsql/pgis_raster.cpp            |    11 +-
 .../garden_3d_viewer/3d_viewer_pointcloud.cpp      |    73 +-
 .../grid/grid_analysis/diversity_analysis.cpp      |    25 +-
 .../grid/grid_analysis/diversity_analysis.h        |     2 +-
 src/modules/grid/grid_gridding/nn/triangle.c       | 16012 -------------------
 src/modules/grid/grid_gridding/nn/triangle.h       |   296 -
 src/modules/grid/grid_tools/Grid_Cut.cpp           |   137 +-
 src/modules/grid/grid_tools/Grid_Cut.h             |     5 +-
 src/modules/grid/grid_tools/Grid_Merge.cpp         |   109 +-
 src/modules/imagery/imagery_opencv/opencv.cpp      |     4 +-
 src/modules/imagery/imagery_svm/svm.cpp            |  3089 ----
 src/modules/imagery/imagery_svm/svm.h              |   101 -
 src/modules/imagery/imagery_tools/landsat_toar.cpp |    76 +-
 src/modules/io/io_gdal/MLB_Interface.cpp           |     6 +-
 src/modules/io/io_gdal/Makefile.am                 |     2 +
 src/modules/io/io_gdal/Makefile.in                 |    11 +-
 src/modules/io/io_gdal/gdal_catalogue.cpp          |   587 +
 .../Grid_Cut.h => io/io_gdal/gdal_catalogue.h}     |    72 +-
 src/modules/io/io_gdal/gdal_driver.cpp             |    34 +
 src/modules/io/io_gdal/gdal_driver.h               |     3 +
 src/modules/io/io_gdal/gdal_export.cpp             |     4 +-
 src/modules/io/io_gdal/gdal_export.h               |     4 +-
 src/modules/io/io_gdal/gdal_export_geotiff.cpp     |     4 +-
 src/modules/io/io_gdal/gdal_export_geotiff.h       |     6 +-
 src/modules/io/io_gdal/gdal_import.cpp             |     2 +-
 src/modules/io/io_gdal/gdal_import.h               |     2 +
 src/modules/io/io_gdal/gdal_import_netcdf.cpp      |     2 +-
 src/modules/io/io_gdal/gdal_import_netcdf.h        |     2 +
 src/modules/io/io_gdal/ogr_export.cpp              |     6 +-
 src/modules/io/io_gdal/ogr_export.h                |     4 +-
 src/modules/io/io_gdal/ogr_export_kml.cpp          |    10 +-
 src/modules/io/io_gdal/ogr_export_kml.h            |     4 +-
 src/modules/io/io_gdal/ogr_import.cpp              |     6 +-
 src/modules/io/io_gdal/ogr_import.h                |     4 +-
 .../io/io_grid_grib2/g2clib-1.0.4/cmplxpack.c      |    78 -
 .../io/io_grid_grib2/g2clib-1.0.4/compack.c        |   419 -
 .../io/io_grid_grib2/g2clib-1.0.4/comunpack.c      |   333 -
 .../io/io_grid_grib2/g2clib-1.0.4/dec_jpeg2000.c   |   147 -
 .../io/io_grid_grib2/g2clib-1.0.4/dec_png.c        |   144 -
 .../io/io_grid_grib2/g2clib-1.0.4/drstemplates.c   |   157 -
 .../io/io_grid_grib2/g2clib-1.0.4/drstemplates.h   |    72 -
 .../io/io_grid_grib2/g2clib-1.0.4/enc_jpeg2000.c   |   190 -
 .../io/io_grid_grib2/g2clib-1.0.4/enc_png.c        |   138 -
 .../io/io_grid_grib2/g2clib-1.0.4/g2_addfield.c    |   513 -
 .../io/io_grid_grib2/g2clib-1.0.4/g2_addgrid.c     |   246 -
 .../io/io_grid_grib2/g2clib-1.0.4/g2_addlocal.c    |   150 -
 .../io/io_grid_grib2/g2clib-1.0.4/g2_create.c      |   130 -
 .../io/io_grid_grib2/g2clib-1.0.4/g2_free.c        |    47 -
 .../io/io_grid_grib2/g2clib-1.0.4/g2_getfld.c      |   553 -
 .../io/io_grid_grib2/g2clib-1.0.4/g2_gribend.c     |   125 -
 .../io/io_grid_grib2/g2clib-1.0.4/g2_info.c        |   193 -
 .../io/io_grid_grib2/g2clib-1.0.4/g2_miss.c        |    72 -
 .../io/io_grid_grib2/g2clib-1.0.4/g2_unpack1.c     |   102 -
 .../io/io_grid_grib2/g2clib-1.0.4/g2_unpack2.c     |    82 -
 .../io/io_grid_grib2/g2clib-1.0.4/g2_unpack3.c     |   216 -
 .../io/io_grid_grib2/g2clib-1.0.4/g2_unpack4.c     |   187 -
 .../io/io_grid_grib2/g2clib-1.0.4/g2_unpack5.c     |   154 -
 .../io/io_grid_grib2/g2clib-1.0.4/g2_unpack6.c     |   100 -
 .../io/io_grid_grib2/g2clib-1.0.4/g2_unpack7.c     |   154 -
 src/modules/io/io_grid_grib2/g2clib-1.0.4/gbits.c  |   127 -
 src/modules/io/io_grid_grib2/g2clib-1.0.4/getdim.c |   130 -
 .../io/io_grid_grib2/g2clib-1.0.4/getpoly.c        |    83 -
 src/modules/io/io_grid_grib2/g2clib-1.0.4/grib2.h  |   254 -
 .../io/io_grid_grib2/g2clib-1.0.4/gridtemplates.c  |   176 -
 .../io/io_grid_grib2/g2clib-1.0.4/gridtemplates.h  |    99 -
 .../io/io_grid_grib2/g2clib-1.0.4/int_power.c      |    33 -
 .../io/io_grid_grib2/g2clib-1.0.4/jpcpack.c        |   178 -
 .../io/io_grid_grib2/g2clib-1.0.4/jpcunpack.c      |    75 -
 .../io/io_grid_grib2/g2clib-1.0.4/misspack.c       |   535 -
 src/modules/io/io_grid_grib2/g2clib-1.0.4/mkieee.c |   126 -
 .../io/io_grid_grib2/g2clib-1.0.4/pack_gp.c        |  1450 --
 .../io/io_grid_grib2/g2clib-1.0.4/pdstemplates.c   |   271 -
 .../io/io_grid_grib2/g2clib-1.0.4/pdstemplates.h   |   121 -
 .../io/io_grid_grib2/g2clib-1.0.4/pngpack.c        |   165 -
 .../io/io_grid_grib2/g2clib-1.0.4/pngunpack.c      |    79 -
 src/modules/io/io_grid_grib2/g2clib-1.0.4/rdieee.c |    81 -
 src/modules/io/io_grid_grib2/g2clib-1.0.4/reduce.c |   413 -
 src/modules/io/io_grid_grib2/g2clib-1.0.4/seekgb.c |    83 -
 .../io/io_grid_grib2/g2clib-1.0.4/simpack.c        |   184 -
 .../io/io_grid_grib2/g2clib-1.0.4/simunpack.c      |    79 -
 .../io/io_grid_grib2/g2clib-1.0.4/specpack.c       |   131 -
 .../io/io_grid_grib2/g2clib-1.0.4/specunpack.c     |   118 -
 src/modules/io/io_table/io_table_txt.cpp           |    42 +-
 src/modules/io/io_table/io_table_txt.h             |    29 +-
 .../Polygon_StatisticsFromPoints.cpp               |    36 +-
 .../shapes/shapes_tools/GraticuleBuilder.cpp       |   217 +-
 src/modules/shapes/shapes_tools/GraticuleBuilder.h |    38 +-
 src/modules/simulation/Makefile.am                 |     2 +-
 src/modules/simulation/Makefile.in                 |     2 +-
 .../simulation/sim_fire_spreading/Forecasting.cpp  |   666 -
 .../simulation/sim_fire_spreading/Forecasting.h    |    84 -
 .../sim_fire_spreading/MLB_Interface.cpp           |   130 -
 .../simulation/sim_fire_spreading/MLB_Interface.h  |    72 -
 .../simulation/sim_fire_spreading/Makefile.am      |    26 -
 .../simulation/sim_fire_spreading/Simulate.cpp     |   363 -
 .../simulation/sim_fire_spreading/Simulate.h       |    81 -
 .../simulation/sim_fire_spreading/fireLib.c        |  1817 ---
 .../simulation/sim_fire_spreading/fireLib.h        |   551 -
 .../sim_qm_of_esp}/MLB_Interface.cpp               |    73 +-
 .../sim_qm_of_esp/MLB_Interface.h}                 |   177 +-
 src/modules/simulation/sim_qm_of_esp/Makefile.am   |    30 +
 .../Makefile.in                                    |   120 +-
 .../simulation/sim_qm_of_esp/fill_sinks.cpp}       |   383 +-
 .../sim_qm_of_esp/fill_sinks.h}                    |    54 +-
 .../simulation/sim_qm_of_esp/flow_routing.cpp}     |   249 +-
 .../sim_qm_of_esp/flow_routing.h}                  |    55 +-
 .../sim_qm_of_esp/hillslope_evolution_adi.cpp      |   541 +
 .../sim_qm_of_esp/hillslope_evolution_adi.h}       |    53 +-
 .../sim_qm_of_esp/hillslope_evolution_ftcs.cpp     |   348 +
 .../sim_qm_of_esp/hillslope_evolution_ftcs.h}      |    52 +-
 .../sim_qm_of_esp/successive_flow_routing.cpp      |   313 +
 .../sim_qm_of_esp/successive_flow_routing.h}       |    55 +-
 .../statistics_grid/GSGrid_Residuals.cpp           |    11 +-
 .../table_calculus/table_field_statistics.cpp      |    24 +-
 src/saga_core/saga_api/api_callback.cpp            |     4 +-
 src/saga_core/saga_api/api_core.h                  |     4 +-
 src/saga_core/saga_api/api_file.cpp                |    58 +-
 src/saga_core/saga_api/data_manager.cpp            |    10 +
 src/saga_core/saga_api/grid_io.cpp                 |     6 +-
 src/saga_core/saga_api/grid_operation.cpp          |    17 +-
 src/saga_core/saga_api/grid_system.cpp             |    24 +-
 src/saga_core/saga_api/module.cpp                  |     4 +-
 src/saga_core/saga_api/module_library.h            |    10 +-
 src/saga_core/saga_api/parameter_data.cpp          |    29 +-
 src/saga_core/saga_api/parameters.cpp              |    19 +-
 src/saga_core/saga_api/parameters.h                |     3 +-
 src/saga_core/saga_api/pointcloud.cpp              |   130 +-
 src/saga_core/saga_api/pointcloud.h                |     8 +-
 src/saga_core/saga_api/projections.cpp             |    51 +-
 src/saga_core/saga_api/saga_api.h                  |     4 +-
 src/saga_core/saga_api/shapes.cpp                  |     6 +-
 src/saga_core/saga_api/shapes_io.cpp               |     6 +-
 src/saga_core/saga_api/table.cpp                   |    34 +-
 src/saga_core/saga_api/table.h                     |    33 +-
 src/saga_core/saga_api/table_io.cpp                |   153 +-
 src/saga_core/saga_api/table_selection.cpp         |   127 +-
 src/saga_core/saga_cmd/module_library.cpp          |    25 +-
 src/saga_core/saga_cmd/module_library.h            |     5 +-
 src/saga_core/saga_cmd/saga_cmd.cpp                |    38 +-
 src/saga_core/saga_gui/Makefile.am                 |     6 +-
 src/saga_core/saga_gui/Makefile.in                 |    79 +-
 src/saga_core/saga_gui/active_attributes.cpp       |    74 +-
 src/saga_core/saga_gui/active_attributes.h         |    36 +-
 .../saga_gui/active_attributes_control.cpp         |   560 +
 ...ve_attributes.h => active_attributes_control.h} |    67 +-
 src/saga_core/saga_gui/data_source.cpp             |    80 +-
 src/saga_core/saga_gui/data_source_pgsql.cpp       |    32 +
 src/saga_core/saga_gui/data_source_pgsql.h         |    10 +-
 src/saga_core/saga_gui/dlg_about.cpp               |    91 +-
 src/saga_core/saga_gui/dlg_about.h                 |     6 +-
 src/saga_core/saga_gui/dlg_table.cpp               |    96 +-
 src/saga_core/saga_gui/dlg_table.h                 |     9 +-
 src/saga_core/saga_gui/dlg_table_control.cpp       |   772 +
 .../{view_table_control.h => dlg_table_control.h}  |    69 +-
 src/saga_core/saga_gui/project.cpp                 |   196 +-
 src/saga_core/saga_gui/project.h                   |     9 +-
 src/saga_core/saga_gui/res/saga.ger.txt            |   594 +-
 src/saga_core/saga_gui/res/saga.lng.txt            |   562 +-
 src/saga_core/saga_gui/res/saga_icon_128.png       |   Bin 0 -> 5557 bytes
 src/saga_core/saga_gui/res/saga_icon_64.png        |   Bin 0 -> 5519 bytes
 src/saga_core/saga_gui/res_commands.cpp            |    61 +-
 src/saga_core/saga_gui/res_commands.h              |    21 +-
 src/saga_core/saga_gui/res_controls.cpp            |    51 +-
 src/saga_core/saga_gui/res_controls.h              |     5 +-
 src/saga_core/saga_gui/saga.cpp                    |    14 +-
 src/saga_core/saga_gui/saga_frame.cpp              |    94 +-
 src/saga_core/saga_gui/view_map.cpp                |    11 +-
 src/saga_core/saga_gui/view_map.h                  |     3 +-
 src/saga_core/saga_gui/view_map_3d.cpp             |    15 +-
 src/saga_core/saga_gui/view_map_3d_panel.cpp       |     7 +-
 src/saga_core/saga_gui/view_map_control.cpp        |   107 +-
 src/saga_core/saga_gui/view_table.cpp              |   149 +-
 src/saga_core/saga_gui/view_table.h                |    27 +-
 src/saga_core/saga_gui/view_table_control.cpp      |  1120 +-
 src/saga_core/saga_gui/view_table_control.h        |   134 +-
 src/saga_core/saga_gui/wksp.cpp                    |    19 +-
 src/saga_core/saga_gui/wksp_base_item.h            |     3 +-
 src/saga_core/saga_gui/wksp_data_item.cpp          |     6 +-
 src/saga_core/saga_gui/wksp_data_item.h            |     2 +
 src/saga_core/saga_gui/wksp_data_manager.cpp       |    24 +-
 src/saga_core/saga_gui/wksp_data_menu_file.cpp     |    12 +-
 src/saga_core/saga_gui/wksp_data_menu_files.cpp    |     6 +-
 src/saga_core/saga_gui/wksp_grid.cpp               |    29 +-
 src/saga_core/saga_gui/wksp_grid.h                 |     5 +-
 src/saga_core/saga_gui/wksp_layer.cpp              |     4 +-
 src/saga_core/saga_gui/wksp_map.cpp                |    77 +-
 src/saga_core/saga_gui/wksp_map.h                  |     3 +-
 src/saga_core/saga_gui/wksp_module.cpp             |     4 +-
 src/saga_core/saga_gui/wksp_module_manager.cpp     |     4 +-
 src/saga_core/saga_gui/wksp_module_menu.cpp        |    24 +-
 src/saga_core/saga_gui/wksp_pointcloud.cpp         |   159 +-
 src/saga_core/saga_gui/wksp_pointcloud.h           |    25 +-
 src/saga_core/saga_gui/wksp_shapes.cpp             |   123 +-
 src/saga_core/saga_gui/wksp_shapes_point.cpp       |    98 +-
 src/saga_core/saga_gui/wksp_shapes_polygon.cpp     |    21 +-
 src/scripting/helper/make_arcsaga_toolboxes.bat    |    43 +
 src/scripting/helper/make_saga_release.bat         |   171 +
 src/scripting/helper/make_saga_snapshot.bat        |    42 +
 src/scripting/helper/make_tools_interface.bat      |    12 +
 src/scripting/helper/make_translation_files.bat    |    29 +
 .../python/examples/02_grid_morphometry.py         |     8 +-
 src/scripting/python/examples/04_grid_contour.py   |     7 +-
 .../helpers/saga_cmd_param_interface/tools.py      |    29 +-
 src/scripting/python/saga_python_api.txt           |     8 +
 208 files changed, 7601 insertions(+), 36558 deletions(-)

diff --git a/README b/README
index 2b38889..13b9488 100644
--- a/README
+++ b/README
@@ -1,6 +1,6 @@
 _______________________________________________________________________________
 
-         SAGA 2.2.2 - System for Automated Geoscientific Analyses
+         SAGA 2.2.3 - System for Automated Geoscientific Analyses
 _______________________________________________________________________________
 
 * Introduction
diff --git a/configure b/configure
index 174542e..e447e1c 100755
--- a/configure
+++ b/configure
@@ -1,6 +1,6 @@
 #! /bin/sh
 # Guess values for system-dependent variables and create Makefiles.
-# Generated by GNU Autoconf 2.69 for saga 2.2.2.
+# Generated by GNU Autoconf 2.69 for saga 2.2.3.
 #
 # Report bugs to <BUG-REPORT-ADDRESS>.
 #
@@ -590,8 +590,8 @@ MAKEFLAGS=
 # Identity of this package.
 PACKAGE_NAME='saga'
 PACKAGE_TARNAME='saga'
-PACKAGE_VERSION='2.2.2'
-PACKAGE_STRING='saga 2.2.2'
+PACKAGE_VERSION='2.2.3'
+PACKAGE_STRING='saga 2.2.3'
 PACKAGE_BUGREPORT='BUG-REPORT-ADDRESS'
 PACKAGE_URL=''
 
@@ -1380,7 +1380,7 @@ if test "$ac_init_help" = "long"; then
   # Omit some internal or obsolete options to make the list less imposing.
   # This message is too long to be a string in the A/UX 3.1 sh.
   cat <<_ACEOF
-\`configure' configures saga 2.2.2 to adapt to many kinds of systems.
+\`configure' configures saga 2.2.3 to adapt to many kinds of systems.
 
 Usage: $0 [OPTION]... [VAR=VALUE]...
 
@@ -1450,7 +1450,7 @@ fi
 
 if test -n "$ac_init_help"; then
   case $ac_init_help in
-     short | recursive ) echo "Configuration of saga 2.2.2:";;
+     short | recursive ) echo "Configuration of saga 2.2.3:";;
    esac
   cat <<\_ACEOF
 
@@ -1571,7 +1571,7 @@ fi
 test -n "$ac_init_help" && exit $ac_status
 if $ac_init_version; then
   cat <<\_ACEOF
-saga configure 2.2.2
+saga configure 2.2.3
 generated by GNU Autoconf 2.69
 
 Copyright (C) 2012 Free Software Foundation, Inc.
@@ -2115,7 +2115,7 @@ cat >config.log <<_ACEOF
 This file contains any messages produced by compilers while
 running configure, to aid debugging if configure makes a mistake.
 
-It was created by saga $as_me 2.2.2, which was
+It was created by saga $as_me 2.2.3, which was
 generated by GNU Autoconf 2.69.  Invocation command line was
 
   $ $0 $@
@@ -2982,7 +2982,7 @@ fi
 
 # Define the identity of the package.
  PACKAGE='saga'
- VERSION='2.2.2'
+ VERSION='2.2.3'
 
 
 cat >>confdefs.h <<_ACEOF
@@ -18009,7 +18009,7 @@ $as_echo "$as_me: WARNING: cannot determine SWIG version" >&2;}
 
 fi
 #AC_CONFIG_FILES([Makefile])
-ac_config_files="$ac_config_files Makefile src/Makefile src/saga_core/Makefile src/saga_core/saga_api/Makefile src/saga_core/saga_gdi/Makefile src/saga_core/saga_gui/Makefile src/saga_core/saga_gui/man/Makefile src/saga_core/saga_cmd/Makefile src/saga_core/saga_cmd/man/Makefile src/modules/Makefile src/modules/climate/Makefile src/modules/climate/climate_tools/Makefile src/modules/contrib/Makefile src/modules/contrib/contrib_peregro/Makefile src/modules/db/Makefile src/modules/db/db_odbc [...]
+ac_config_files="$ac_config_files Makefile src/Makefile src/saga_core/Makefile src/saga_core/saga_api/Makefile src/saga_core/saga_gdi/Makefile src/saga_core/saga_gui/Makefile src/saga_core/saga_gui/man/Makefile src/saga_core/saga_cmd/Makefile src/saga_core/saga_cmd/man/Makefile src/modules/Makefile src/modules/climate/Makefile src/modules/climate/climate_tools/Makefile src/modules/contrib/Makefile src/modules/contrib/contrib_peregro/Makefile src/modules/db/Makefile src/modules/db/db_odbc [...]
 
 cat >confcache <<\_ACEOF
 # This file is a shell script that caches the results of configure
@@ -18590,7 +18590,7 @@ cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
 # report actual input values of CONFIG_FILES etc. instead of their
 # values after options handling.
 ac_log="
-This file was extended by saga $as_me 2.2.2, which was
+This file was extended by saga $as_me 2.2.3, which was
 generated by GNU Autoconf 2.69.  Invocation command line was
 
   CONFIG_FILES    = $CONFIG_FILES
@@ -18656,7 +18656,7 @@ _ACEOF
 cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
 ac_cs_config="`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`"
 ac_cs_version="\\
-saga config.status 2.2.2
+saga config.status 2.2.3
 configured by $0, generated by GNU Autoconf 2.69,
   with options \\"\$ac_cs_config\\"
 
@@ -19239,6 +19239,7 @@ do
     "src/modules/simulation/sim_fire_spreading/Makefile") CONFIG_FILES="$CONFIG_FILES src/modules/simulation/sim_fire_spreading/Makefile" ;;
     "src/modules/simulation/sim_hydrology/Makefile") CONFIG_FILES="$CONFIG_FILES src/modules/simulation/sim_hydrology/Makefile" ;;
     "src/modules/simulation/sim_ihacres/Makefile") CONFIG_FILES="$CONFIG_FILES src/modules/simulation/sim_ihacres/Makefile" ;;
+    "src/modules/simulation/sim_qm_of_esp/Makefile") CONFIG_FILES="$CONFIG_FILES src/modules/simulation/sim_qm_of_esp/Makefile" ;;
     "src/modules/simulation/sim_rivflow/Makefile") CONFIG_FILES="$CONFIG_FILES src/modules/simulation/sim_rivflow/Makefile" ;;
     "src/modules/statistics/Makefile") CONFIG_FILES="$CONFIG_FILES src/modules/statistics/Makefile" ;;
     "src/modules/statistics/statistics_grid/Makefile") CONFIG_FILES="$CONFIG_FILES src/modules/statistics/statistics_grid/Makefile" ;;
diff --git a/configure.ac b/configure.ac
index 5a7a618..04241af 100755
--- a/configure.ac
+++ b/configure.ac
@@ -1,9 +1,9 @@
-# $Id: configure.ac 2601 2015-09-23 15:11:23Z oconrad $
+# $Id: configure.ac 2692 2015-11-17 16:13:05Z oconrad $
 #                                               -*- Autoconf -*-
 # Process this file with autoconf to produce a configure script.
 
 AC_PREREQ(2.59)
-AC_INIT(saga, 2.2.2, BUG-REPORT-ADDRESS)
+AC_INIT(saga, 2.2.3, BUG-REPORT-ADDRESS)
 AC_CONFIG_SRCDIR([src/saga_core/saga_gui/wksp_data_menu_files.cpp])
 AC_CONFIG_HEADER([config.h])
 AC_CONFIG_MACRO_DIR([m4])
@@ -279,6 +279,7 @@ AC_OUTPUT(Makefile \
 	src/modules/simulation/sim_fire_spreading/Makefile \
 	src/modules/simulation/sim_hydrology/Makefile \
 	src/modules/simulation/sim_ihacres/Makefile \
+	src/modules/simulation/sim_qm_of_esp/Makefile \
 	src/modules/simulation/sim_rivflow/Makefile \
 	src/modules/statistics/Makefile \
 	src/modules/statistics/statistics_grid/Makefile \
diff --git a/src/modules/db/db_pgsql/db_pgsql.cpp b/src/modules/db/db_pgsql/db_pgsql.cpp
index d805574..869edfd 100644
--- a/src/modules/db/db_pgsql/db_pgsql.cpp
+++ b/src/modules/db/db_pgsql/db_pgsql.cpp
@@ -229,19 +229,16 @@ TSG_Data_Type CSG_PG_Connection::Get_Type_From_SQL(int Type)
 	switch( Type )
 	{
 	case SG_PG_VARCHAR:	return( SG_DATATYPE_String );
-	case SG_PG_NAME:	return( SG_DATATYPE_String );
-	case SG_PG_TEXT:	return( SG_DATATYPE_String );
-
-	case SG_PG_INT2:	return( SG_DATATYPE_Short  );	// 2 bytes integer
-	case SG_PG_INT4:	return( SG_DATATYPE_Int    );	// 4 bytes integer
-	case SG_PG_INT8:	return( SG_DATATYPE_Long   );	// 8 bytes integer
-	case SG_PG_FLOAT4:	return( SG_DATATYPE_Float  );	// 4 bytes floating point, inexact
-	case SG_PG_FLOAT8:	return( SG_DATATYPE_Double );	// 8 bytes floating point, inexact
-
-	case SG_PG_BYTEA:	return( SG_DATATYPE_Binary );
+	case SG_PG_NAME   :	return( SG_DATATYPE_String );
+	case SG_PG_TEXT   :	return( SG_DATATYPE_String );
+	case SG_PG_INT2   :	return( SG_DATATYPE_Short  );	// 2 bytes integer
+	case SG_PG_INT4   :	return( SG_DATATYPE_Int    );	// 4 bytes integer
+	case SG_PG_INT8   :	return( SG_DATATYPE_Long   );	// 8 bytes integer
+	case SG_PG_FLOAT4 :	return( SG_DATATYPE_Float  );	// 4 bytes floating point, inexact
+	case SG_PG_FLOAT8 :	return( SG_DATATYPE_Double );	// 8 bytes floating point, inexact
+	case SG_PG_BYTEA  :	return( SG_DATATYPE_Binary );
+	default           :	return( SG_DATATYPE_String );
 	}
-
-	return( SG_DATATYPE_String );
 }
 
 //---------------------------------------------------------
@@ -249,19 +246,18 @@ CSG_String CSG_PG_Connection::Get_Raster_Type_To_SQL(TSG_Data_Type Type)
 {
 	switch( Type )
 	{
-	case SG_DATATYPE_Bit:		return( "1BB"   );
-	case SG_DATATYPE_Char:		return( "8BSI"  );
-	case SG_DATATYPE_Byte:		return( "8BUI"  );
-	case SG_DATATYPE_Short:		return( "16BSI" );
-	case SG_DATATYPE_Word:		return( "16BUI" );
-	case SG_DATATYPE_Int:		return( "32BSI" );
-	case SG_DATATYPE_DWord:		return( "32BUI" );
-	case SG_DATATYPE_Long:		return( "32BSI" );
-	case SG_DATATYPE_Float:		return( "32BF"  );
+	case SG_DATATYPE_Bit   :	return( "1BB"   );
+	case SG_DATATYPE_Char  :	return( "8BSI"  );
+	case SG_DATATYPE_Byte  :	return( "8BUI"  );
+	case SG_DATATYPE_Short :	return( "16BSI" );
+	case SG_DATATYPE_Word  :	return( "16BUI" );
+	case SG_DATATYPE_Int   :	return( "32BSI" );
+	case SG_DATATYPE_DWord :	return( "32BUI" );
+	case SG_DATATYPE_Long  :	return( "32BSI" );
+	case SG_DATATYPE_Float :	return( "32BF"  );
 	case SG_DATATYPE_Double:	return( "64BF"  );
+	default                :	return( "64BF"  );
 	}
-
-	return( "64BF" );
 }
 
 
@@ -853,9 +849,16 @@ bool CSG_PG_Connection::Table_Insert(const CSG_String &Table_Name, const CSG_Tab
 
 				if( 0 && Table.Get_Field_Type(iField) == SG_DATATYPE_String )
 				{
-					char	*s	= NULL; Value.to_ASCII(&s);
-
-					sprintf(Values[iField], "%s", s ? s : '\0');
+					char	*s	= NULL;
+
+					if( Value.to_ASCII(&s) && s && *s )
+					{
+						sprintf(Values[iField], "%s", s);
+					}
+					else
+					{
+						Values[iField][0]	= '\0';
+					}
 
 					SG_FREE_SAFE(s);
 				}
diff --git a/src/modules/db/db_pgsql/pgis_raster.cpp b/src/modules/db/db_pgsql/pgis_raster.cpp
index 127caba..3f6f229 100644
--- a/src/modules/db/db_pgsql/pgis_raster.cpp
+++ b/src/modules/db/db_pgsql/pgis_raster.cpp
@@ -286,20 +286,20 @@ CRaster_Save::CRaster_Save(void)
 		PARAMETER_INPUT
 	);
 
-	Parameters.Add_Choice(
-		NULL	, "TABLE"		, _TL("Table"),
+	pNode	= Parameters.Add_Choice(
+		NULL	, "TABLE"		, _TL("Add to Table"),
 		_TL(""),
 		""
 	);
 
 	Parameters.Add_String(
-		NULL	, "NAME"		, _TL("Table Name"),
+		pNode	, "NAME"		, _TL("Table Name"),
 		_TL(""),
 		""
 	);
 
 	Parameters.Add_Value(
-		NULL	, "GRID_NAME"	, _TL("Add Grid Name Field"),
+		pNode	, "GRID_NAME"	, _TL("Band Name Field"),
 		_TL(""),
 		PARAMETER_TYPE_Bool, true
 	);
@@ -325,6 +325,9 @@ void CRaster_Save::On_Connection_Changed(CSG_Parameters *pParameters)
 
 	pParameters->Get_Parameter("TABLE")->asChoice()->Set_Items(s);
 	pParameters->Get_Parameter("TABLE")->Set_Value(t.Get_Count());
+
+	On_Parameter_Changed(pParameters, pParameters->Get_Parameter("TABLE"));
+	On_Parameter_Changed(pParameters, pParameters->Get_Parameter("GRIDS"));
 }
 
 //---------------------------------------------------------
diff --git a/src/modules/garden/garden_3d_viewer/3d_viewer_pointcloud.cpp b/src/modules/garden/garden_3d_viewer/3d_viewer_pointcloud.cpp
index 2f73c8a..7c01d6b 100644
--- a/src/modules/garden/garden_3d_viewer/3d_viewer_pointcloud.cpp
+++ b/src/modules/garden/garden_3d_viewer/3d_viewer_pointcloud.cpp
@@ -223,6 +223,16 @@ C3D_Viewer_PointCloud_Panel::C3D_Viewer_PointCloud_Panel(wxWindow *pParent, CSG_
 	);
 
 	//-----------------------------------------------------
+	m_Parameters.Add_Choice(
+		pNode	, "OVERVIEW_ATTR"	, _TL("Overview Content"),
+		_TL(""),
+		CSG_String::Format("%s|%s|",
+			_TL("average value"),
+			_TL("number of points")
+		), 0
+	);
+
+	//-----------------------------------------------------
 	m_Extent	= pPoints->Get_Extent();
 
 	m_Selection.Create(sizeof(int), 0, SG_ARRAY_GROWTH_2);
@@ -500,20 +510,26 @@ public:
 		//-------------------------------------------------
 		m_Ratio	= pPoints->Get_Extent().Get_XRange() / pPoints->Get_Extent().Get_YRange();
 
-		m_Count.Create(CSG_Grid_System(m_Ratio > 1.0
+		CSG_Grid_System	System(m_Ratio > 1.0
 			? pPoints->Get_Extent().Get_XRange() / 100.0
 			: pPoints->Get_Extent().Get_YRange() / 100.0,
-			pPoints->Get_Extent()), SG_DATATYPE_Int
+			pPoints->Get_Extent()
 		);
 
+		m_Count.Create(System, SG_DATATYPE_Int);
+		m_Value.Create(System, SG_DATATYPE_Double);
+
 		for(int i=0, x, y; i<pPoints->Get_Count(); i++)
 		{
 			if( m_Count.Get_System().Get_World_to_Grid(x, y, pPoints->Get_X(i), pPoints->Get_Y(i)) ) // && m_Count.is_InGrid(x, y, false) )
 			{
 				m_Count.Add_Value(x, y, 1);
+				m_Value.Add_Value(x, y, pPoints->Get_Z(i));
 			}
 		}
 
+		m_Value.Divide(m_Count);
+
 		int	Size	= GetClientSize().GetWidth();
 
 		if( m_Ratio > 1.0 )
@@ -525,6 +541,8 @@ public:
 
 private:
 
+	bool						m_bCount;
+
 	double						m_Ratio;
 
 	wxPoint						m_Mouse_Down, m_Mouse_Move;
@@ -533,7 +551,7 @@ private:
 
 	wxImage						m_Image;
 
-	CSG_Grid					m_Count;
+	CSG_Grid					m_Count, m_Value;
 
 	C3D_Viewer_PointCloud_Panel	*m_pPanel;
 
@@ -608,6 +626,11 @@ private:
 		case WXK_PAGEDOWN:
 			Set_Size(GetClientSize().GetWidth() / 1.25, GetClientSize().GetHeight() / 1.25, true);
 			break;
+
+		case WXK_SPACE:
+			m_pPanel->m_Parameters("OVERVIEW_ATTR")->Set_Value(m_pPanel->m_Parameters("OVERVIEW_ATTR")->asInt() ? 0 : 1);
+			Set_Image(true);
+			break;
 		}
 	}
 
@@ -668,26 +691,48 @@ private:
 
 		if( !m_Image.IsOk() || m_Image.GetWidth() != Width )
 		{
-			CSG_Colors	Colors(7, SG_COLORS_RAINBOW);
-			Colors.Set_Color(0, m_pPanel->m_Parameters("BGCOLOR")->asColor());
-			Colors.Set_Count(100);
+			m_Image.Create(Width, Height, false);
 
-			double	dCount	= (Colors.Get_Count() - 2.0) / log(1.0 + m_Count.Get_ZMax());
-			double	dx		= m_Count.Get_XRange() / (double)Width ;
-			double	dy		= m_Count.Get_YRange() / (double)Height;
+			Set_Image(bRefresh);
+		}
+	}
 
-			m_Image.Create(Width, Height, false);
+	//---------------------------------------------------------
+	void						Set_Image		(bool bRefresh)
+	{
+		if( m_Image.IsOk() && m_Count.is_Valid() )
+		{
+			bool	bCount	= m_pPanel->m_Parameters("OVERVIEW_ATTR")->asInt() == 1;
+
+			CSG_Colors	Colors(11, SG_COLORS_RAINBOW);	Colors.Set_Color(0, m_pPanel->m_Parameters("BGCOLOR")->asColor());
+
+			double	dx	= m_Count.Get_XRange() / (double)m_Image.GetWidth ();
+			double	dy	= m_Count.Get_YRange() / (double)m_Image.GetHeight();
+			double	dz	= (Colors.Get_Count() - 2.0) / (bCount ? log(1.0 + m_Count.Get_ZMax()) : 4.0 * m_Value.Get_StdDev());
 
 			#pragma omp parallel for
 			for(int y=0; y<m_Image.GetHeight(); y++)
 			{
-				double	Count, ix = m_Count.Get_XMin(), iy = m_Count.Get_YMax() - y * dy;
+				double	iz, ix = m_Count.Get_XMin(), iy = m_Count.Get_YMax() - y * dy;
 
 				for(int x=0; x<m_Image.GetWidth(); x++, ix+=dx)
 				{
-					int	i	= m_Count.Get_Value(ix, iy, Count) && Count > 0.0 ? (int)(log(1.0 + Count) * dCount) : 0;
-
-					m_Image.SetRGB(x, y, Colors.Get_Red(i), Colors.Get_Green(i), Colors.Get_Blue(i));
+					if( bCount )
+					{
+						iz	= dz * (m_Count.Get_Value(ix, iy, iz) && iz > 0.0 ? log(1.0 + iz) : 0.0);
+					}
+					else if( m_Value.Get_Value(ix, iy, iz) )
+					{
+						iz	= dz * (iz - (m_Value.Get_Mean() - 2.0 * m_Value.Get_StdDev()));
+					}
+					else
+					{
+						iz	= 0.0;
+					}
+
+					int	ic	= Colors.Get_Interpolated(iz);
+
+					m_Image.SetRGB(x, y, SG_GET_R(ic), SG_GET_G(ic), SG_GET_B(ic));
 				}
 			}
 		}
diff --git a/src/modules/grid/grid_analysis/diversity_analysis.cpp b/src/modules/grid/grid_analysis/diversity_analysis.cpp
index 66c46a9..9b565ec 100644
--- a/src/modules/grid/grid_analysis/diversity_analysis.cpp
+++ b/src/modules/grid/grid_analysis/diversity_analysis.cpp
@@ -91,12 +91,18 @@ CDiversity_Analysis::CDiversity_Analysis(void)
 	);
 
 	Parameters.Add_Grid(
-		NULL	, "DIVERSITY"		, _TL("Number of Categories"),
+		NULL	, "COUNT"			, _TL("Number of Categories"),
 		_TL("number of different categories (unique values) within search area"),
 		PARAMETER_OUTPUT
 	);
 
 	Parameters.Add_Grid(
+		NULL	, "DIVERSITY"		, _TL("Diversity"),
+		_TL("number of different categories (unique values) per area"),
+		PARAMETER_OUTPUT
+	);
+
+	Parameters.Add_Grid(
 		NULL	, "SIZE_MEAN"		, _TL("Average Size"),
 		_TL("average size of the area covered by each category that occurs within search area"),
 		PARAMETER_OUTPUT
@@ -166,16 +172,19 @@ bool CDiversity_Analysis::On_Execute(void)
 {
 	//-----------------------------------------------------
 	m_pClasses		= Parameters("CATEGORIES"  )->asGrid();
+	m_pCount		= Parameters("COUNT"       )->asGrid();
 	m_pDiversity	= Parameters("DIVERSITY"   )->asGrid();
 	m_pSize_Mean	= Parameters("SIZE_MEAN"   )->asGrid();
 	m_pSize_Skew	= Parameters("SIZE_SKEW"   )->asGrid();
 	m_pConnectivity	= Parameters("CONNECTIVITY")->asGrid();
 
-	m_pDiversity	->Set_Name(CSG_String::Format("%s [%s]", m_pClasses->Get_Name(), _TL("Count"       )));
+	m_pCount		->Set_Name(CSG_String::Format("%s [%s]", m_pClasses->Get_Name(), _TL("Count"       )));
+	m_pDiversity	->Set_Name(CSG_String::Format("%s [%s]", m_pClasses->Get_Name(), _TL("Diversity"   )));
 	m_pSize_Mean	->Set_Name(CSG_String::Format("%s [%s]", m_pClasses->Get_Name(), _TL("Average"     )));
 	m_pSize_Skew	->Set_Name(CSG_String::Format("%s [%s]", m_pClasses->Get_Name(), _TL("Skewness"    )));
 	m_pConnectivity	->Set_Name(CSG_String::Format("%s [%s]", m_pClasses->Get_Name(), _TL("Connectivity")));
 
+	DataObject_Set_Colors(m_pCount       , 11, SG_COLORS_DEFAULT, false);
 	DataObject_Set_Colors(m_pDiversity   , 11, SG_COLORS_DEFAULT, false);
 	DataObject_Set_Colors(m_pSize_Mean   , 11, SG_COLORS_DEFAULT,  true);
 	DataObject_Set_Colors(m_pSize_Skew   , 11, SG_COLORS_DEFAULT,  true);
@@ -198,6 +207,7 @@ bool CDiversity_Analysis::On_Execute(void)
 		{
 			if( m_pClasses->is_NoData(x, y) || !Get_Diversity(x, y) )
 			{
+				m_pCount       ->Set_NoData(x, y);
 				m_pDiversity   ->Set_NoData(x, y);
 				m_pSize_Mean   ->Set_NoData(x, y);
 				m_pSize_Skew   ->Set_NoData(x, y);
@@ -258,19 +268,24 @@ bool CDiversity_Analysis::Get_Diversity(int x, int y)
 	//-----------------------------------------------------
 	if( Classes.Get_Count() > 1 )
 	{
-		CSG_Simple_Statistics	s(true);
+		CSG_Simple_Statistics	c, s(true);
 
 		for(i=0; i<Classes.Get_Count(); i++)
 		{
-			s.Add_Value(Classes.Get_Class_Count(i), m_bWeighted ? Classes.Get_Class_Weight(i) / Classes.Get_Class_Count(i) : 1.0);
+			double	w	= m_bWeighted ? Classes.Get_Class_Weight(i) / Classes.Get_Class_Count(i) : 1.0;
+
+			c.Add_Value(w);
+			s.Add_Value(Classes.Get_Class_Count(i), w);
 		}
 
-		m_pDiversity->Set_Value(x, y, s.Get_Sum() * s.Get_Weights());
+		m_pCount    ->Set_Value(x, y, c.Get_Sum ());
+		m_pDiversity->Set_Value(x, y, s.Get_Mean());
 		m_pSize_Mean->Set_Value(x, y, s.Get_Mean() / (double)nCells);	// relative size !!!
 		m_pSize_Skew->Set_Value(x, y, s.Get_Skewness());	//	m_pSize_Skew->Set_Value(x, y, s.Get_SkewnessPearson());
 	}
 	else
 	{
+		m_pCount    ->Set_Value(x, y, 1.0);
 		m_pDiversity->Set_Value(x, y, 1.0);
 		m_pSize_Mean->Set_Value(x, y, 1.0);
 		m_pSize_Skew->Set_Value(x, y, 0.0);
diff --git a/src/modules/grid/grid_analysis/diversity_analysis.h b/src/modules/grid/grid_analysis/diversity_analysis.h
index c03ea9e..2564f8d 100644
--- a/src/modules/grid/grid_analysis/diversity_analysis.h
+++ b/src/modules/grid/grid_analysis/diversity_analysis.h
@@ -99,7 +99,7 @@ private:
 
 	int							m_NB_Step;
 
-	CSG_Grid					*m_pClasses, *m_pDiversity, *m_pSize_Mean, *m_pSize_Skew, *m_pConnectivity;
+	CSG_Grid					*m_pClasses, *m_pCount, *m_pDiversity, *m_pSize_Mean, *m_pSize_Skew, *m_pConnectivity;
 
 	CSG_Grid_Cell_Addressor		m_Search;
 
diff --git a/src/modules/grid/grid_gridding/nn/triangle.c b/src/modules/grid/grid_gridding/nn/triangle.c
deleted file mode 100644
index 5676f82..0000000
--- a/src/modules/grid/grid_gridding/nn/triangle.c
+++ /dev/null
@@ -1,16012 +0,0 @@
-/**********************************************************
- * Version $Id: triangle.c 911 2011-02-14 16:38:15Z reklov_w $
- *********************************************************/
-/*****************************************************************************/
-/*                                                                           */
-/*      888888888        ,o,                          / 888                  */
-/*         888    88o88o  "    o8888o  88o8888o o88888o 888  o88888o         */
-/*         888    888    888       88b 888  888 888 888 888 d888  88b        */
-/*         888    888    888  o88^o888 888  888 "88888" 888 8888oo888        */
-/*         888    888    888 C888  888 888  888  /      888 q888             */
-/*         888    888    888  "88o^888 888  888 Cb      888  "88oooo"        */
-/*                                              "8oo8D                       */
-/*                                                                           */
-/*  A Two-Dimensional Quality Mesh Generator and Delaunay Triangulator.      */
-/*  (triangle.c)                                                             */
-/*                                                                           */
-/*  Version 1.6                                                              */
-/*  July 28, 2005                                                            */
-/*                                                                           */
-/*  Copyright 1993, 1995, 1997, 1998, 2002, 2005                             */
-/*  Jonathan Richard Shewchuk                                                */
-/*  2360 Woolsey #H                                                          */
-/*  Berkeley, California  94705-1927                                         */
-/*  jrs at cs.berkeley.edu                                                      */
-/*                                                                           */
-/*  This program may be freely redistributed under the condition that the    */
-/*    copyright notices (including this entire header and the copyright      */
-/*    notice printed when the `-h' switch is selected) are not removed, and  */
-/*    no compensation is received.  Private, research, and institutional     */
-/*    use is free.  You may distribute modified versions of this code UNDER  */
-/*    THE CONDITION THAT THIS CODE AND ANY MODIFICATIONS MADE TO IT IN THE   */
-/*    SAME FILE REMAIN UNDER COPYRIGHT OF THE ORIGINAL AUTHOR, BOTH SOURCE   */
-/*    AND OBJECT CODE ARE MADE FREELY AVAILABLE WITHOUT CHARGE, AND CLEAR    */
-/*    NOTICE IS GIVEN OF THE MODIFICATIONS.  Distribution of this code as    */
-/*    part of a commercial system is permissible ONLY BY DIRECT ARRANGEMENT  */
-/*    WITH THE AUTHOR.  (If you are not directly supplying this code to a    */
-/*    customer, and you are instead telling them how they can obtain it for  */
-/*    free, then you are not required to make any arrangement with me.)      */
-/*                                                                           */
-/*  Hypertext instructions for Triangle are available on the Web at          */
-/*                                                                           */
-/*      http://www.cs.cmu.edu/~quake/triangle.html                           */
-/*                                                                           */
-/*  Disclaimer:  Neither I nor Carnegie Mellon warrant this code in any way  */
-/*    whatsoever.  This code is provided "as-is".  Use at your own risk.     */
-/*                                                                           */
-/*  Some of the references listed below are marked with an asterisk.  [*]    */
-/*    These references are available for downloading from the Web page       */
-/*                                                                           */
-/*      http://www.cs.cmu.edu/~quake/triangle.research.html                  */
-/*                                                                           */
-/*  Three papers discussing aspects of Triangle are available.  A short      */
-/*    overview appears in "Triangle:  Engineering a 2D Quality Mesh          */
-/*    Generator and Delaunay Triangulator," in Applied Computational         */
-/*    Geometry:  Towards Geometric Engineering, Ming C. Lin and Dinesh       */
-/*    Manocha, editors, Lecture Notes in Computer Science volume 1148,       */
-/*    pages 203-222, Springer-Verlag, Berlin, May 1996 (from the First ACM   */
-/*    Workshop on Applied Computational Geometry).  [*]                      */
-/*                                                                           */
-/*    The algorithms are discussed in the greatest detail in "Delaunay       */
-/*    Refinement Algorithms for Triangular Mesh Generation," Computational   */
-/*    Geometry:  Theory and Applications 22(1-3):21-74, May 2002.  [*]       */
-/*                                                                           */
-/*    More detail about the data structures may be found in my dissertation: */
-/*    "Delaunay Refinement Mesh Generation," Ph.D. thesis, Technical Report  */
-/*    CMU-CS-97-137, School of Computer Science, Carnegie Mellon University, */
-/*    Pittsburgh, Pennsylvania, 18 May 1997.  [*]                            */
-/*                                                                           */
-/*  Triangle was created as part of the Quake Project in the School of       */
-/*    Computer Science at Carnegie Mellon University.  For further           */
-/*    information, see Hesheng Bao, Jacobo Bielak, Omar Ghattas, Loukas F.   */
-/*    Kallivokas, David R. O'Hallaron, Jonathan R. Shewchuk, and Jifeng Xu,  */
-/*    "Large-scale Simulation of Elastic Wave Propagation in Heterogeneous   */
-/*    Media on Parallel Computers," Computer Methods in Applied Mechanics    */
-/*    and Engineering 152(1-2):85-102, 22 January 1998.                      */
-/*                                                                           */
-/*  Triangle's Delaunay refinement algorithm for quality mesh generation is  */
-/*    a hybrid of one due to Jim Ruppert, "A Delaunay Refinement Algorithm   */
-/*    for Quality 2-Dimensional Mesh Generation," Journal of Algorithms      */
-/*    18(3):548-585, May 1995 [*], and one due to L. Paul Chew, "Guaranteed- */
-/*    Quality Mesh Generation for Curved Surfaces," Proceedings of the Ninth */
-/*    Annual Symposium on Computational Geometry (San Diego, California),    */
-/*    pages 274-280, Association for Computing Machinery, May 1993,          */
-/*    http://portal.acm.org/citation.cfm?id=161150 .                         */
-/*                                                                           */
-/*  The Delaunay refinement algorithm has been modified so that it meshes    */
-/*    domains with small input angles well, as described in Gary L. Miller,  */
-/*    Steven E. Pav, and Noel J. Walkington, "When and Why Ruppert's         */
-/*    Algorithm Works," Twelfth International Meshing Roundtable, pages      */
-/*    91-102, Sandia National Laboratories, September 2003.  [*]             */
-/*                                                                           */
-/*  My implementation of the divide-and-conquer and incremental Delaunay     */
-/*    triangulation algorithms follows closely the presentation of Guibas    */
-/*    and Stolfi, even though I use a triangle-based data structure instead  */
-/*    of their quad-edge data structure.  (In fact, I originally implemented */
-/*    Triangle using the quad-edge data structure, but the switch to a       */
-/*    triangle-based data structure sped Triangle by a factor of two.)  The  */
-/*    mesh manipulation primitives and the two aforementioned Delaunay       */
-/*    triangulation algorithms are described by Leonidas J. Guibas and Jorge */
-/*    Stolfi, "Primitives for the Manipulation of General Subdivisions and   */
-/*    the Computation of Voronoi Diagrams," ACM Transactions on Graphics     */
-/*    4(2):74-123, April 1985, http://portal.acm.org/citation.cfm?id=282923 .*/
-/*                                                                           */
-/*  Their O(n log n) divide-and-conquer algorithm is adapted from Der-Tsai   */
-/*    Lee and Bruce J. Schachter, "Two Algorithms for Constructing the       */
-/*    Delaunay Triangulation," International Journal of Computer and         */
-/*    Information Science 9(3):219-242, 1980.  Triangle's improvement of the */
-/*    divide-and-conquer algorithm by alternating between vertical and       */
-/*    horizontal cuts was introduced by Rex A. Dwyer, "A Faster Divide-and-  */
-/*    Conquer Algorithm for Constructing Delaunay Triangulations,"           */
-/*    Algorithmica 2(2):137-151, 1987.                                       */
-/*                                                                           */
-/*  The incremental insertion algorithm was first proposed by C. L. Lawson,  */
-/*    "Software for C1 Surface Interpolation," in Mathematical Software III, */
-/*    John R. Rice, editor, Academic Press, New York, pp. 161-194, 1977.     */
-/*    For point location, I use the algorithm of Ernst P. Mucke, Isaac       */
-/*    Saias, and Binhai Zhu, "Fast Randomized Point Location Without         */
-/*    Preprocessing in Two- and Three-Dimensional Delaunay Triangulations,"  */
-/*    Proceedings of the Twelfth Annual Symposium on Computational Geometry, */
-/*    ACM, May 1996.  [*]  If I were to randomize the order of vertex        */
-/*    insertion (I currently don't bother), their result combined with the   */
-/*    result of Kenneth L. Clarkson and Peter W. Shor, "Applications of      */
-/*    Random Sampling in Computational Geometry II," Discrete &              */
-/*    Computational Geometry 4(1):387-421, 1989, would yield an expected     */
-/*    O(n^{4/3}) bound on running time.                                      */
-/*                                                                           */
-/*  The O(n log n) sweepline Delaunay triangulation algorithm is taken from  */
-/*    Steven Fortune, "A Sweepline Algorithm for Voronoi Diagrams",          */
-/*    Algorithmica 2(2):153-174, 1987.  A random sample of edges on the      */
-/*    boundary of the triangulation are maintained in a splay tree for the   */
-/*    purpose of point location.  Splay trees are described by Daniel        */
-/*    Dominic Sleator and Robert Endre Tarjan, "Self-Adjusting Binary Search */
-/*    Trees," Journal of the ACM 32(3):652-686, July 1985,                   */
-/*    http://portal.acm.org/citation.cfm?id=3835 .                           */
-/*                                                                           */
-/*  The algorithms for exact computation of the signs of determinants are    */
-/*    described in Jonathan Richard Shewchuk, "Adaptive Precision Floating-  */
-/*    Point Arithmetic and Fast Robust Geometric Predicates," Discrete &     */
-/*    Computational Geometry 18(3):305-363, October 1997.  (Also available   */
-/*    as Technical Report CMU-CS-96-140, School of Computer Science,         */
-/*    Carnegie Mellon University, Pittsburgh, Pennsylvania, May 1996.)  [*]  */
-/*    An abbreviated version appears as Jonathan Richard Shewchuk, "Robust   */
-/*    Adaptive Floating-Point Geometric Predicates," Proceedings of the      */
-/*    Twelfth Annual Symposium on Computational Geometry, ACM, May 1996. [*] */
-/*    Many of the ideas for my exact arithmetic routines originate with      */
-/*    Douglas M. Priest, "Algorithms for Arbitrary Precision Floating Point  */
-/*    Arithmetic," Tenth Symposium on Computer Arithmetic, pp. 132-143, IEEE */
-/*    Computer Society Press, 1991.  [*]  Many of the ideas for the correct  */
-/*    evaluation of the signs of determinants are taken from Steven Fortune  */
-/*    and Christopher J. Van Wyk, "Efficient Exact Arithmetic for Computa-   */
-/*    tional Geometry," Proceedings of the Ninth Annual Symposium on         */
-/*    Computational Geometry, ACM, pp. 163-172, May 1993, and from Steven    */
-/*    Fortune, "Numerical Stability of Algorithms for 2D Delaunay Triangu-   */
-/*    lations," International Journal of Computational Geometry & Applica-   */
-/*    tions 5(1-2):193-213, March-June 1995.                                 */
-/*                                                                           */
-/*  The method of inserting new vertices off-center (not precisely at the    */
-/*    circumcenter of every poor-quality triangle) is from Alper Ungor,      */
-/*    "Off-centers:  A New Type of Steiner Points for Computing Size-Optimal */
-/*    Quality-Guaranteed Delaunay Triangulations," Proceedings of LATIN      */
-/*    2004 (Buenos Aires, Argentina), April 2004.                            */
-/*                                                                           */
-/*  For definitions of and results involving Delaunay triangulations,        */
-/*    constrained and conforming versions thereof, and other aspects of      */
-/*    triangular mesh generation, see the excellent survey by Marshall Bern  */
-/*    and David Eppstein, "Mesh Generation and Optimal Triangulation," in    */
-/*    Computing and Euclidean Geometry, Ding-Zhu Du and Frank Hwang,         */
-/*    editors, World Scientific, Singapore, pp. 23-90, 1992.  [*]            */
-/*                                                                           */
-/*  The time for incrementally adding PSLG (planar straight line graph)      */
-/*    segments to create a constrained Delaunay triangulation is probably    */
-/*    O(t^2) per segment in the worst case and O(t) per segment in the       */
-/*    common case, where t is the number of triangles that intersect the     */
-/*    segment before it is inserted.  This doesn't count point location,     */
-/*    which can be much more expensive.  I could improve this to O(d log d)  */
-/*    time, but d is usually quite small, so it's not worth the bother.      */
-/*    (This note does not apply when the -s switch is used, invoking a       */
-/*    different method is used to insert segments.)                          */
-/*                                                                           */
-/*  The time for deleting a vertex from a Delaunay triangulation is O(d^2)   */
-/*    in the worst case and O(d) in the common case, where d is the degree   */
-/*    of the vertex being deleted.  I could improve this to O(d log d) time, */
-/*    but d is usually quite small, so it's not worth the bother.            */
-/*                                                                           */
-/*  Ruppert's Delaunay refinement algorithm typically generates triangles    */
-/*    at a linear rate (constant time per triangle) after the initial        */
-/*    triangulation is formed.  There may be pathological cases where        */
-/*    quadratic time is required, but these never arise in practice.         */
-/*                                                                           */
-/*  The geometric predicates (circumcenter calculations, segment             */
-/*    intersection formulae, etc.) appear in my "Lecture Notes on Geometric  */
-/*    Robustness" at http://www.cs.berkeley.edu/~jrs/mesh .                  */
-/*                                                                           */
-/*  If you make any improvements to this code, please please please let me   */
-/*    know, so that I may obtain the improvements.  Even if you don't change */
-/*    the code, I'd still love to hear what it's being used for.             */
-/*                                                                           */
-/*****************************************************************************/
-
-/* For single precision (which will save some memory and reduce paging),     */
-/*   define the symbol SINGLE by using the -DSINGLE compiler switch or by    */
-/*   writing "#define SINGLE" below.                                         */
-/*                                                                           */
-/* For double precision (which will allow you to refine meshes to a smaller  */
-/*   edge length), leave SINGLE undefined.                                   */
-/*                                                                           */
-/* Double precision uses more memory, but improves the resolution of the     */
-/*   meshes you can generate with Triangle.  It also reduces the likelihood  */
-/*   of a floating exception due to overflow.  Finally, it is much faster    */
-/*   than single precision on 64-bit architectures like the DEC Alpha.  I    */
-/*   recommend double precision unless you want to generate a mesh for which */
-/*   you do not have enough memory.                                          */
-
-/* #define SINGLE */
-
-#ifdef SINGLE
-#define REAL float
-#else /* not SINGLE */
-#define REAL double
-#endif /* not SINGLE */
-
-/* If yours is not a Unix system, define the NO_TIMER compiler switch to     */
-/*   remove the Unix-specific timing code.                                   */
-
-#define NO_TIMER
-
-/* To insert lots of self-checks for internal errors, define the SELF_CHECK  */
-/*   symbol.  This will slow down the program significantly.  It is best to  */
-/*   define the symbol using the -DSELF_CHECK compiler switch, but you could */
-/*   write "#define SELF_CHECK" below.  If you are modifying this code, I    */
-/*   recommend you turn self-checks on until your work is debugged.          */
-
-/* #define SELF_CHECK */
-
-/* To compile Triangle as a callable object library (triangle.o), define the */
-/*   TRILIBRARY symbol.  Read the file triangle.h for details on how to call */
-/*   the procedure triangulate() that results.                               */
-
-#define TRILIBRARY
-
-/* It is possible to generate a smaller version of Triangle using one or     */
-/*   both of the following symbols.  Define the REDUCED symbol to eliminate  */
-/*   all features that are primarily of research interest; specifically, the */
-/*   -i, -F, -s, and -C switches.  Define the CDT_ONLY symbol to eliminate   */
-/*   all meshing algorithms above and beyond constrained Delaunay            */
-/*   triangulation; specifically, the -r, -q, -a, -u, -D, -S, and -s         */
-/*   switches.  These reductions are most likely to be useful when           */
-/*   generating an object library (triangle.o) by defining the TRILIBRARY    */
-/*   symbol.                                                                 */
-
-/* #define REDUCED */
-/* #define CDT_ONLY */
-
-/* On some machines, my exact arithmetic routines might be defeated by the   */
-/*   use of internal extended precision floating-point registers.  The best  */
-/*   way to solve this problem is to set the floating-point registers to use */
-/*   single or double precision internally.  On 80x86 processors, this may   */
-/*   be accomplished by setting the CPU86 symbol for the Microsoft C         */
-/*   compiler, or the LINUX symbol for the gcc compiler running on Linux.    */
-/*                                                                           */
-/* An inferior solution is to declare certain values as `volatile', thus     */
-/*   forcing them to be stored to memory and rounded off.  Unfortunately,    */
-/*   this solution might slow Triangle down quite a bit.  To use volatile    */
-/*   values, write "#define INEXACT volatile" below.  Normally, however,     */
-/*   INEXACT should be defined to be nothing.  ("#define INEXACT".)          */
-/*                                                                           */
-/* For more discussion, see http://www.cs.cmu.edu/~quake/robust.pc.html .    */
-/*   For yet more discussion, see Section 5 of my paper, "Adaptive Precision */
-/*   Floating-Point Arithmetic and Fast Robust Geometric Predicates" (also   */
-/*   available as Section 6.6 of my dissertation).                           */
-
-/* #define CPU86 */
-/* #define LINUX */
-
-#define INEXACT /* Nothing */
-/* #define INEXACT volatile */
-
-/* Maximum number of characters in a file name (including the null).         */
-
-#define FILENAMESIZE 2048
-
-/* Maximum number of characters in a line read from a file (including the    */
-/*   null).                                                                  */
-
-#define INPUTLINESIZE 1024
-
-/* For efficiency, a variety of data structures are allocated in bulk.  The  */
-/*   following constants determine how many of each structure is allocated   */
-/*   at once.                                                                */
-
-#define TRIPERBLOCK 4092           /* Number of triangles allocated at once. */
-#define SUBSEGPERBLOCK 508       /* Number of subsegments allocated at once. */
-#define VERTEXPERBLOCK 4092         /* Number of vertices allocated at once. */
-#define VIRUSPERBLOCK 1020   /* Number of virus triangles allocated at once. */
-/* Number of encroached subsegments allocated at once. */
-#define BADSUBSEGPERBLOCK 252
-/* Number of skinny triangles allocated at once. */
-#define BADTRIPERBLOCK 4092
-/* Number of flipped triangles allocated at once. */
-#define FLIPSTACKERPERBLOCK 252
-/* Number of splay tree nodes allocated at once. */
-#define SPLAYNODEPERBLOCK 508
-
-/* The vertex types.   A DEADVERTEX has been deleted entirely.  An           */
-/*   UNDEADVERTEX is not part of the mesh, but is written to the output      */
-/*   .node file and affects the node indexing in the other output files.     */
-
-#define INPUTVERTEX 0
-#define SEGMENTVERTEX 1
-#define FREEVERTEX 2
-#define DEADVERTEX -32768
-#define UNDEADVERTEX -32767
-
-/* The next line is used to outsmart some very stupid compilers.  If your    */
-/*   compiler is smarter, feel free to replace the "int" with "void".        */
-/*   Not that it matters.                                                    */
-
-#define VOID void
-
-/* Two constants for algorithms based on random sampling.  Both constants    */
-/*   have been chosen empirically to optimize their respective algorithms.   */
-
-/* Used for the point location scheme of Mucke, Saias, and Zhu, to decide    */
-/*   how large a random sample of triangles to inspect.                      */
-
-#define SAMPLEFACTOR 11
-
-/* Used in Fortune's sweepline Delaunay algorithm to determine what fraction */
-/*   of boundary edges should be maintained in the splay tree for point      */
-/*   location on the front.                                                  */
-
-#define SAMPLERATE 10
-
-/* A number that speaks for itself, every kissable digit.                    */
-
-#define PI 3.141592653589793238462643383279502884197169399375105820974944592308
-
-/* Another fave.                                                             */
-
-#define SQUAREROOTTWO 1.4142135623730950488016887242096980785696718753769480732
-
-/* And here's one for those of you who are intimidated by math.              */
-
-#define ONETHIRD 0.333333333333333333333333333333333333333333333333333333333333
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <math.h>
-#ifndef NO_TIMER
-#include <sys/time.h>
-#endif /* not NO_TIMER */
-#ifdef CPU86
-#include <float.h>
-#endif /* CPU86 */
-#ifdef LINUX
-#include <fpu_control.h>
-#endif /* LINUX */
-#ifdef TRILIBRARY
-#include "triangle.h"
-#endif /* TRILIBRARY */
-
-/* A few forward declarations.                                               */
-
-#ifndef TRILIBRARY
-char *readline();
-char *findfield();
-#endif /* not TRILIBRARY */
-
-/* Labels that signify the result of point location.  The result of a        */
-/*   search indicates that the point falls in the interior of a triangle, on */
-/*   an edge, on a vertex, or outside the mesh.                              */
-
-enum locateresult {INTRIANGLE, ONEDGE, ONVERTEX, OUTSIDE};
-
-/* Labels that signify the result of vertex insertion.  The result indicates */
-/*   that the vertex was inserted with complete success, was inserted but    */
-/*   encroaches upon a subsegment, was not inserted because it lies on a     */
-/*   segment, or was not inserted because another vertex occupies the same   */
-/*   location.                                                               */
-
-enum insertvertexresult {SUCCESSFULVERTEX, ENCROACHINGVERTEX, VIOLATINGVERTEX,
-                         DUPLICATEVERTEX};
-
-/* Labels that signify the result of direction finding.  The result          */
-/*   indicates that a segment connecting the two query points falls within   */
-/*   the direction triangle, along the left edge of the direction triangle,  */
-/*   or along the right edge of the direction triangle.                      */
-
-enum finddirectionresult {WITHIN, LEFTCOLLINEAR, RIGHTCOLLINEAR};
-
-/*****************************************************************************/
-/*                                                                           */
-/*  The basic mesh data structures                                           */
-/*                                                                           */
-/*  There are three:  vertices, triangles, and subsegments (abbreviated      */
-/*  `subseg').  These three data structures, linked by pointers, comprise    */
-/*  the mesh.  A vertex simply represents a mesh vertex and its properties.  */
-/*  A triangle is a triangle.  A subsegment is a special data structure used */
-/*  to represent an impenetrable edge of the mesh (perhaps on the outer      */
-/*  boundary, on the boundary of a hole, or part of an internal boundary     */
-/*  separating two triangulated regions).  Subsegments represent boundaries, */
-/*  defined by the user, that triangles may not lie across.                  */
-/*                                                                           */
-/*  A triangle consists of a list of three vertices, a list of three         */
-/*  adjoining triangles, a list of three adjoining subsegments (when         */
-/*  segments exist), an arbitrary number of optional user-defined            */
-/*  floating-point attributes, and an optional area constraint.  The latter  */
-/*  is an upper bound on the permissible area of each triangle in a region,  */
-/*  used for mesh refinement.                                                */
-/*                                                                           */
-/*  For a triangle on a boundary of the mesh, some or all of the neighboring */
-/*  triangles may not be present.  For a triangle in the interior of the     */
-/*  mesh, often no neighboring subsegments are present.  Such absent         */
-/*  triangles and subsegments are never represented by NULL pointers; they   */
-/*  are represented by two special records:  `dummytri', the triangle that   */
-/*  fills "outer space", and `dummysub', the omnipresent subsegment.         */
-/*  `dummytri' and `dummysub' are used for several reasons; for instance,    */
-/*  they can be dereferenced and their contents examined without violating   */
-/*  protected memory.                                                        */
-/*                                                                           */
-/*  However, it is important to understand that a triangle includes other    */
-/*  information as well.  The pointers to adjoining vertices, triangles, and */
-/*  subsegments are ordered in a way that indicates their geometric relation */
-/*  to each other.  Furthermore, each of these pointers contains orientation */
-/*  information.  Each pointer to an adjoining triangle indicates which face */
-/*  of that triangle is contacted.  Similarly, each pointer to an adjoining  */
-/*  subsegment indicates which side of that subsegment is contacted, and how */
-/*  the subsegment is oriented relative to the triangle.                     */
-/*                                                                           */
-/*  The data structure representing a subsegment may be thought to be        */
-/*  abutting the edge of one or two triangle data structures:  either        */
-/*  sandwiched between two triangles, or resting against one triangle on an  */
-/*  exterior boundary or hole boundary.                                      */
-/*                                                                           */
-/*  A subsegment consists of a list of four vertices--the vertices of the    */
-/*  subsegment, and the vertices of the segment it is a part of--a list of   */
-/*  two adjoining subsegments, and a list of two adjoining triangles.  One   */
-/*  of the two adjoining triangles may not be present (though there should   */
-/*  always be one), and neighboring subsegments might not be present.        */
-/*  Subsegments also store a user-defined integer "boundary marker".         */
-/*  Typically, this integer is used to indicate what boundary conditions are */
-/*  to be applied at that location in a finite element simulation.           */
-/*                                                                           */
-/*  Like triangles, subsegments maintain information about the relative      */
-/*  orientation of neighboring objects.                                      */
-/*                                                                           */
-/*  Vertices are relatively simple.  A vertex is a list of floating-point    */
-/*  numbers, starting with the x, and y coordinates, followed by an          */
-/*  arbitrary number of optional user-defined floating-point attributes,     */
-/*  followed by an integer boundary marker.  During the segment insertion    */
-/*  phase, there is also a pointer from each vertex to a triangle that may   */
-/*  contain it.  Each pointer is not always correct, but when one is, it     */
-/*  speeds up segment insertion.  These pointers are assigned values once    */
-/*  at the beginning of the segment insertion phase, and are not used or     */
-/*  updated except during this phase.  Edge flipping during segment          */
-/*  insertion will render some of them incorrect.  Hence, don't rely upon    */
-/*  them for anything.                                                       */
-/*                                                                           */
-/*  Other than the exception mentioned above, vertices have no information   */
-/*  about what triangles, subfacets, or subsegments they are linked to.      */
-/*                                                                           */
-/*****************************************************************************/
-
-/*****************************************************************************/
-/*                                                                           */
-/*  Handles                                                                  */
-/*                                                                           */
-/*  The oriented triangle (`otri') and oriented subsegment (`osub') data     */
-/*  structures defined below do not themselves store any part of the mesh.   */
-/*  The mesh itself is made of `triangle's, `subseg's, and `vertex's.        */
-/*                                                                           */
-/*  Oriented triangles and oriented subsegments will usually be referred to  */
-/*  as "handles."  A handle is essentially a pointer into the mesh; it       */
-/*  allows you to "hold" one particular part of the mesh.  Handles are used  */
-/*  to specify the regions in which one is traversing and modifying the mesh.*/
-/*  A single `triangle' may be held by many handles, or none at all.  (The   */
-/*  latter case is not a memory leak, because the triangle is still          */
-/*  connected to other triangles in the mesh.)                               */
-/*                                                                           */
-/*  An `otri' is a handle that holds a triangle.  It holds a specific edge   */
-/*  of the triangle.  An `osub' is a handle that holds a subsegment.  It     */
-/*  holds either the left or right side of the subsegment.                   */
-/*                                                                           */
-/*  Navigation about the mesh is accomplished through a set of mesh          */
-/*  manipulation primitives, further below.  Many of these primitives take   */
-/*  a handle and produce a new handle that holds the mesh near the first     */
-/*  handle.  Other primitives take two handles and glue the corresponding    */
-/*  parts of the mesh together.  The orientation of the handles is           */
-/*  important.  For instance, when two triangles are glued together by the   */
-/*  bond() primitive, they are glued at the edges on which the handles lie.  */
-/*                                                                           */
-/*  Because vertices have no information about which triangles they are      */
-/*  attached to, I commonly represent a vertex by use of a handle whose      */
-/*  origin is the vertex.  A single handle can simultaneously represent a    */
-/*  triangle, an edge, and a vertex.                                         */
-/*                                                                           */
-/*****************************************************************************/
-
-/* The triangle data structure.  Each triangle contains three pointers to    */
-/*   adjoining triangles, plus three pointers to vertices, plus three        */
-/*   pointers to subsegments (declared below; these pointers are usually     */
-/*   `dummysub').  It may or may not also contain user-defined attributes    */
-/*   and/or a floating-point "area constraint."  It may also contain extra   */
-/*   pointers for nodes, when the user asks for high-order elements.         */
-/*   Because the size and structure of a `triangle' is not decided until     */
-/*   runtime, I haven't simply declared the type `triangle' as a struct.     */
-
-typedef REAL **triangle;            /* Really:  typedef triangle *triangle   */
-
-/* An oriented triangle:  includes a pointer to a triangle and orientation.  */
-/*   The orientation denotes an edge of the triangle.  Hence, there are      */
-/*   three possible orientations.  By convention, each edge always points    */
-/*   counterclockwise about the corresponding triangle.                      */
-
-struct otri {
-  triangle *tri;
-  int orient;                                         /* Ranges from 0 to 2. */
-};
-
-/* The subsegment data structure.  Each subsegment contains two pointers to  */
-/*   adjoining subsegments, plus four pointers to vertices, plus two         */
-/*   pointers to adjoining triangles, plus one boundary marker, plus one     */
-/*   segment number.                                                         */
-
-typedef REAL **subseg;                  /* Really:  typedef subseg *subseg   */
-
-/* An oriented subsegment:  includes a pointer to a subsegment and an        */
-/*   orientation.  The orientation denotes a side of the edge.  Hence, there */
-/*   are two possible orientations.  By convention, the edge is always       */
-/*   directed so that the "side" denoted is the right side of the edge.      */
-
-struct osub {
-  subseg *ss;
-  int ssorient;                                       /* Ranges from 0 to 1. */
-};
-
-/* The vertex data structure.  Each vertex is actually an array of REALs.    */
-/*   The number of REALs is unknown until runtime.  An integer boundary      */
-/*   marker, and sometimes a pointer to a triangle, is appended after the    */
-/*   REALs.                                                                  */
-
-typedef REAL *vertex;
-
-/* A queue used to store encroached subsegments.  Each subsegment's vertices */
-/*   are stored so that we can check whether a subsegment is still the same. */
-
-struct badsubseg {
-  subseg encsubseg;                             /* An encroached subsegment. */
-  vertex subsegorg, subsegdest;                         /* Its two vertices. */
-};
-
-/* A queue used to store bad triangles.  The key is the square of the cosine */
-/*   of the smallest angle of the triangle.  Each triangle's vertices are    */
-/*   stored so that one can check whether a triangle is still the same.      */
-
-struct badtriang {
-  triangle poortri;                       /* A skinny or too-large triangle. */
-  REAL key;                             /* cos^2 of smallest (apical) angle. */
-  vertex triangorg, triangdest, triangapex;           /* Its three vertices. */
-  struct badtriang *nexttriang;             /* Pointer to next bad triangle. */
-};
-
-/* A stack of triangles flipped during the most recent vertex insertion.     */
-/*   The stack is used to undo the vertex insertion if the vertex encroaches */
-/*   upon a subsegment.                                                      */
-
-struct flipstacker {
-  triangle flippedtri;                       /* A recently flipped triangle. */
-  struct flipstacker *prevflip;               /* Previous flip in the stack. */
-};
-
-/* A node in a heap used to store events for the sweepline Delaunay          */
-/*   algorithm.  Nodes do not point directly to their parents or children in */
-/*   the heap.  Instead, each node knows its position in the heap, and can   */
-/*   look up its parent and children in a separate array.  The `eventptr'    */
-/*   points either to a `vertex' or to a triangle (in encoded format, so     */
-/*   that an orientation is included).  In the latter case, the origin of    */
-/*   the oriented triangle is the apex of a "circle event" of the sweepline  */
-/*   algorithm.  To distinguish site events from circle events, all circle   */
-/*   events are given an invalid (smaller than `xmin') x-coordinate `xkey'.  */
-
-struct event {
-  REAL xkey, ykey;                              /* Coordinates of the event. */
-  VOID *eventptr;      /* Can be a vertex or the location of a circle event. */
-  int heapposition;              /* Marks this event's position in the heap. */
-};
-
-/* A node in the splay tree.  Each node holds an oriented ghost triangle     */
-/*   that represents a boundary edge of the growing triangulation.  When a   */
-/*   circle event covers two boundary edges with a triangle, so that they    */
-/*   are no longer boundary edges, those edges are not immediately deleted   */
-/*   from the tree; rather, they are lazily deleted when they are next       */
-/*   encountered.  (Since only a random sample of boundary edges are kept    */
-/*   in the tree, lazy deletion is faster.)  `keydest' is used to verify     */
-/*   that a triangle is still the same as when it entered the splay tree; if */
-/*   it has been rotated (due to a circle event), it no longer represents a  */
-/*   boundary edge and should be deleted.                                    */
-
-struct splaynode {
-  struct otri keyedge;                     /* Lprev of an edge on the front. */
-  vertex keydest;           /* Used to verify that splay node is still live. */
-  struct splaynode *lchild, *rchild;              /* Children in splay tree. */
-};
-
-/* A type used to allocate memory.  firstblock is the first block of items.  */
-/*   nowblock is the block from which items are currently being allocated.   */
-/*   nextitem points to the next slab of free memory for an item.            */
-/*   deaditemstack is the head of a linked list (stack) of deallocated items */
-/*   that can be recycled.  unallocateditems is the number of items that     */
-/*   remain to be allocated from nowblock.                                   */
-/*                                                                           */
-/* Traversal is the process of walking through the entire list of items, and */
-/*   is separate from allocation.  Note that a traversal will visit items on */
-/*   the "deaditemstack" stack as well as live items.  pathblock points to   */
-/*   the block currently being traversed.  pathitem points to the next item  */
-/*   to be traversed.  pathitemsleft is the number of items that remain to   */
-/*   be traversed in pathblock.                                              */
-/*                                                                           */
-/* alignbytes determines how new records should be aligned in memory.        */
-/*   itembytes is the length of a record in bytes (after rounding up).       */
-/*   itemsperblock is the number of items allocated at once in a single      */
-/*   block.  itemsfirstblock is the number of items in the first block,      */
-/*   which can vary from the others.  items is the number of currently       */
-/*   allocated items.  maxitems is the maximum number of items that have     */
-/*   been allocated at once; it is the current number of items plus the      */
-/*   number of records kept on deaditemstack.                                */
-
-struct memorypool {
-  VOID **firstblock, **nowblock;
-  VOID *nextitem;
-  VOID *deaditemstack;
-  VOID **pathblock;
-  VOID *pathitem;
-  int alignbytes;
-  int itembytes;
-  int itemsperblock;
-  int itemsfirstblock;
-  long items, maxitems;
-  int unallocateditems;
-  int pathitemsleft;
-};
-
-
-/* Global constants.                                                         */
-
-REAL splitter;       /* Used to split REAL factors for exact multiplication. */
-REAL epsilon;                             /* Floating-point machine epsilon. */
-REAL resulterrbound;
-REAL ccwerrboundA, ccwerrboundB, ccwerrboundC;
-REAL iccerrboundA, iccerrboundB, iccerrboundC;
-REAL o3derrboundA, o3derrboundB, o3derrboundC;
-
-/* Random number seed is not constant, but I've made it global anyway.       */
-
-unsigned long randomseed;                     /* Current random number seed. */
-
-
-/* Mesh data structure.  Triangle operates on only one mesh, but the mesh    */
-/*   structure is used (instead of global variables) to allow reentrancy.    */
-
-struct mesh {
-
-/* Variables used to allocate memory for triangles, subsegments, vertices,   */
-/*   viri (triangles being eaten), encroached segments, bad (skinny or too   */
-/*   large) triangles, and splay tree nodes.                                 */
-
-  struct memorypool triangles;
-  struct memorypool subsegs;
-  struct memorypool vertices;
-  struct memorypool viri;
-  struct memorypool badsubsegs;
-  struct memorypool badtriangles;
-  struct memorypool flipstackers;
-  struct memorypool splaynodes;
-
-/* Variables that maintain the bad triangle queues.  The queues are          */
-/*   ordered from 4095 (highest priority) to 0 (lowest priority).            */
-
-  struct badtriang *queuefront[4096];
-  struct badtriang *queuetail[4096];
-  int nextnonemptyq[4096];
-  int firstnonemptyq;
-
-/* Variable that maintains the stack of recently flipped triangles.          */
-
-  struct flipstacker *lastflip;
-
-/* Other variables. */
-
-  REAL xmin, xmax, ymin, ymax;                            /* x and y bounds. */
-  REAL xminextreme;      /* Nonexistent x value used as a flag in sweepline. */
-  int invertices;                               /* Number of input vertices. */
-  int inelements;                              /* Number of input triangles. */
-  int insegments;                               /* Number of input segments. */
-  int holes;                                       /* Number of input holes. */
-  int regions;                                   /* Number of input regions. */
-  int undeads;    /* Number of input vertices that don't appear in the mesh. */
-  long edges;                                     /* Number of output edges. */
-  int mesh_dim;                                /* Dimension (ought to be 2). */
-  int nextras;                           /* Number of attributes per vertex. */
-  int eextras;                         /* Number of attributes per triangle. */
-  long hullsize;                          /* Number of edges in convex hull. */
-  int steinerleft;                 /* Number of Steiner points not yet used. */
-  int vertexmarkindex;         /* Index to find boundary marker of a vertex. */
-  int vertex2triindex;     /* Index to find a triangle adjacent to a vertex. */
-  int highorderindex;  /* Index to find extra nodes for high-order elements. */
-  int elemattribindex;            /* Index to find attributes of a triangle. */
-  int areaboundindex;             /* Index to find area bound of a triangle. */
-  int checksegments;         /* Are there segments in the triangulation yet? */
-  int checkquality;                  /* Has quality triangulation begun yet? */
-  int readnodefile;                           /* Has a .node file been read? */
-  long samples;              /* Number of random samples for point location. */
-
-  long incirclecount;                 /* Number of incircle tests performed. */
-  long counterclockcount;     /* Number of counterclockwise tests performed. */
-  long orient3dcount;           /* Number of 3D orientation tests performed. */
-  long hyperbolacount;      /* Number of right-of-hyperbola tests performed. */
-  long circumcentercount;  /* Number of circumcenter calculations performed. */
-  long circletopcount;       /* Number of circle top calculations performed. */
-
-/* Triangular bounding box vertices.                                         */
-
-  vertex infvertex1, infvertex2, infvertex3;
-
-/* Pointer to the `triangle' that occupies all of "outer space."             */
-
-  triangle *dummytri;
-  triangle *dummytribase;    /* Keep base address so we can free() it later. */
-
-/* Pointer to the omnipresent subsegment.  Referenced by any triangle or     */
-/*   subsegment that isn't really connected to a subsegment at that          */
-/*   location.                                                               */
-
-  subseg *dummysub;
-  subseg *dummysubbase;      /* Keep base address so we can free() it later. */
-
-/* Pointer to a recently visited triangle.  Improves point location if       */
-/*   proximate vertices are inserted sequentially.                           */
-
-  struct otri recenttri;
-
-};                                                  /* End of `struct mesh'. */
-
-
-/* Data structure for command line switches and file names.  This structure  */
-/*   is used (instead of global variables) to allow reentrancy.              */
-
-struct behavior {
-
-/* Switches for the triangulator.                                            */
-/*   poly: -p switch.  refine: -r switch.                                    */
-/*   quality: -q switch.                                                     */
-/*     minangle: minimum angle bound, specified after -q switch.             */
-/*     goodangle: cosine squared of minangle.                                */
-/*     offconstant: constant used to place off-center Steiner points.        */
-/*   vararea: -a switch without number.                                      */
-/*   fixedarea: -a switch with number.                                       */
-/*     maxarea: maximum area bound, specified after -a switch.               */
-/*   usertest: -u switch.                                                    */
-/*   regionattrib: -A switch.  convex: -c switch.                            */
-/*   weighted: 1 for -w switch, 2 for -W switch.  jettison: -j switch        */
-/*   firstnumber: inverse of -z switch.  All items are numbered starting     */
-/*     from `firstnumber'.                                                   */
-/*   edgesout: -e switch.  voronoi: -v switch.                               */
-/*   neighbors: -n switch.  geomview: -g switch.                             */
-/*   nobound: -B switch.  nopolywritten: -P switch.                          */
-/*   nonodewritten: -N switch.  noelewritten: -E switch.                     */
-/*   noiterationnum: -I switch.  noholes: -O switch.                         */
-/*   noexact: -X switch.                                                     */
-/*   order: element order, specified after -o switch.                        */
-/*   nobisect: count of how often -Y switch is selected.                     */
-/*   steiner: maximum number of Steiner points, specified after -S switch.   */
-/*   incremental: -i switch.  sweepline: -F switch.                          */
-/*   dwyer: inverse of -l switch.                                            */
-/*   splitseg: -s switch.                                                    */
-/*   conformdel: -D switch.  docheck: -C switch.                             */
-/*   quiet: -Q switch.  verbose: count of how often -V switch is selected.   */
-/*   usesegments: -p, -r, -q, or -c switch; determines whether segments are  */
-/*     used at all.                                                          */
-/*                                                                           */
-/* Read the instructions to find out the meaning of these switches.          */
-
-  int poly, refine, quality, vararea, fixedarea, usertest;
-  int regionattrib, convex, weighted, jettison;
-  int firstnumber;
-  int edgesout, voronoi, neighbors, geomview;
-  int nobound, nopolywritten, nonodewritten, noelewritten, noiterationnum;
-  int noholes, noexact, conformdel;
-  int incremental, sweepline, dwyer;
-  int splitseg;
-  int docheck;
-  int quiet, verbose;
-  int usesegments;
-  int order;
-  int nobisect;
-  int steiner;
-  REAL minangle, goodangle, offconstant;
-  REAL maxarea;
-
-/* Variables for file names.                                                 */
-
-#ifndef TRILIBRARY
-  char innodefilename[FILENAMESIZE];
-  char inelefilename[FILENAMESIZE];
-  char inpolyfilename[FILENAMESIZE];
-  char areafilename[FILENAMESIZE];
-  char outnodefilename[FILENAMESIZE];
-  char outelefilename[FILENAMESIZE];
-  char outpolyfilename[FILENAMESIZE];
-  char edgefilename[FILENAMESIZE];
-  char vnodefilename[FILENAMESIZE];
-  char vedgefilename[FILENAMESIZE];
-  char neighborfilename[FILENAMESIZE];
-  char offfilename[FILENAMESIZE];
-#endif /* not TRILIBRARY */
-
-};                                              /* End of `struct behavior'. */
-
-
-/*****************************************************************************/
-/*                                                                           */
-/*  Mesh manipulation primitives.  Each triangle contains three pointers to  */
-/*  other triangles, with orientations.  Each pointer points not to the      */
-/*  first byte of a triangle, but to one of the first three bytes of a       */
-/*  triangle.  It is necessary to extract both the triangle itself and the   */
-/*  orientation.  To save memory, I keep both pieces of information in one   */
-/*  pointer.  To make this possible, I assume that all triangles are aligned */
-/*  to four-byte boundaries.  The decode() routine below decodes a pointer,  */
-/*  extracting an orientation (in the range 0 to 2) and a pointer to the     */
-/*  beginning of a triangle.  The encode() routine compresses a pointer to a */
-/*  triangle and an orientation into a single pointer.  My assumptions that  */
-/*  triangles are four-byte-aligned and that the `unsigned long' type is     */
-/*  long enough to hold a pointer are two of the few kludges in this program.*/
-/*                                                                           */
-/*  Subsegments are manipulated similarly.  A pointer to a subsegment        */
-/*  carries both an address and an orientation in the range 0 to 1.          */
-/*                                                                           */
-/*  The other primitives take an oriented triangle or oriented subsegment,   */
-/*  and return an oriented triangle or oriented subsegment or vertex; or     */
-/*  they change the connections in the data structure.                       */
-/*                                                                           */
-/*  Below, triangles and subsegments are denoted by their vertices.  The     */
-/*  triangle abc has origin (org) a, destination (dest) b, and apex (apex)   */
-/*  c.  These vertices occur in counterclockwise order about the triangle.   */
-/*  The handle abc may simultaneously denote vertex a, edge ab, and triangle */
-/*  abc.                                                                     */
-/*                                                                           */
-/*  Similarly, the subsegment ab has origin (sorg) a and destination (sdest) */
-/*  b.  If ab is thought to be directed upward (with b directly above a),    */
-/*  then the handle ab is thought to grasp the right side of ab, and may     */
-/*  simultaneously denote vertex a and edge ab.                              */
-/*                                                                           */
-/*  An asterisk (*) denotes a vertex whose identity is unknown.              */
-/*                                                                           */
-/*  Given this notation, a partial list of mesh manipulation primitives      */
-/*  follows.                                                                 */
-/*                                                                           */
-/*                                                                           */
-/*  For triangles:                                                           */
-/*                                                                           */
-/*  sym:  Find the abutting triangle; same edge.                             */
-/*  sym(abc) -> ba*                                                          */
-/*                                                                           */
-/*  lnext:  Find the next edge (counterclockwise) of a triangle.             */
-/*  lnext(abc) -> bca                                                        */
-/*                                                                           */
-/*  lprev:  Find the previous edge (clockwise) of a triangle.                */
-/*  lprev(abc) -> cab                                                        */
-/*                                                                           */
-/*  onext:  Find the next edge counterclockwise with the same origin.        */
-/*  onext(abc) -> ac*                                                        */
-/*                                                                           */
-/*  oprev:  Find the next edge clockwise with the same origin.               */
-/*  oprev(abc) -> a*b                                                        */
-/*                                                                           */
-/*  dnext:  Find the next edge counterclockwise with the same destination.   */
-/*  dnext(abc) -> *ba                                                        */
-/*                                                                           */
-/*  dprev:  Find the next edge clockwise with the same destination.          */
-/*  dprev(abc) -> cb*                                                        */
-/*                                                                           */
-/*  rnext:  Find the next edge (counterclockwise) of the adjacent triangle.  */
-/*  rnext(abc) -> *a*                                                        */
-/*                                                                           */
-/*  rprev:  Find the previous edge (clockwise) of the adjacent triangle.     */
-/*  rprev(abc) -> b**                                                        */
-/*                                                                           */
-/*  org:  Origin          dest:  Destination          apex:  Apex            */
-/*  org(abc) -> a         dest(abc) -> b              apex(abc) -> c         */
-/*                                                                           */
-/*  bond:  Bond two triangles together at the resepective handles.           */
-/*  bond(abc, bad)                                                           */
-/*                                                                           */
-/*                                                                           */
-/*  For subsegments:                                                         */
-/*                                                                           */
-/*  ssym:  Reverse the orientation of a subsegment.                          */
-/*  ssym(ab) -> ba                                                           */
-/*                                                                           */
-/*  spivot:  Find adjoining subsegment with the same origin.                 */
-/*  spivot(ab) -> a*                                                         */
-/*                                                                           */
-/*  snext:  Find next subsegment in sequence.                                */
-/*  snext(ab) -> b*                                                          */
-/*                                                                           */
-/*  sorg:  Origin                      sdest:  Destination                   */
-/*  sorg(ab) -> a                      sdest(ab) -> b                        */
-/*                                                                           */
-/*  sbond:  Bond two subsegments together at the respective origins.         */
-/*  sbond(ab, ac)                                                            */
-/*                                                                           */
-/*                                                                           */
-/*  For interacting tetrahedra and subfacets:                                */
-/*                                                                           */
-/*  tspivot:  Find a subsegment abutting a triangle.                         */
-/*  tspivot(abc) -> ba                                                       */
-/*                                                                           */
-/*  stpivot:  Find a triangle abutting a subsegment.                         */
-/*  stpivot(ab) -> ba*                                                       */
-/*                                                                           */
-/*  tsbond:  Bond a triangle to a subsegment.                                */
-/*  tsbond(abc, ba)                                                          */
-/*                                                                           */
-/*****************************************************************************/
-
-/********* Mesh manipulation primitives begin here                   *********/
-/**                                                                         **/
-/**                                                                         **/
-
-/* Fast lookup arrays to speed some of the mesh manipulation primitives.     */
-
-int plus1mod3[3] = {1, 2, 0};
-int minus1mod3[3] = {2, 0, 1};
-
-/********* Primitives for triangles                                  *********/
-/*                                                                           */
-/*                                                                           */
-
-/* decode() converts a pointer to an oriented triangle.  The orientation is  */
-/*   extracted from the two least significant bits of the pointer.           */
-
-#define decode(ptr, otri)                                                     \
-  (otri).orient = (int) ((unsigned long) (ptr) & (unsigned long) 3l);         \
-  (otri).tri = (triangle *)                                                   \
-                  ((unsigned long) (ptr) ^ (unsigned long) (otri).orient)
-
-/* encode() compresses an oriented triangle into a single pointer.  It       */
-/*   relies on the assumption that all triangles are aligned to four-byte    */
-/*   boundaries, so the two least significant bits of (otri).tri are zero.   */
-
-#define encode(otri)                                                          \
-  (triangle) ((unsigned long) (otri).tri | (unsigned long) (otri).orient)
-
-/* The following handle manipulation primitives are all described by Guibas  */
-/*   and Stolfi.  However, Guibas and Stolfi use an edge-based data          */
-/*   structure, whereas I use a triangle-based data structure.               */
-
-/* sym() finds the abutting triangle, on the same edge.  Note that the edge  */
-/*   direction is necessarily reversed, because the handle specified by an   */
-/*   oriented triangle is directed counterclockwise around the triangle.     */
-
-#define sym(otri1, otri2)                                                     \
-  ptr = (otri1).tri[(otri1).orient];                                          \
-  decode(ptr, otri2);
-
-#define symself(otri)                                                         \
-  ptr = (otri).tri[(otri).orient];                                            \
-  decode(ptr, otri);
-
-/* lnext() finds the next edge (counterclockwise) of a triangle.             */
-
-#define lnext(otri1, otri2)                                                   \
-  (otri2).tri = (otri1).tri;                                                  \
-  (otri2).orient = plus1mod3[(otri1).orient]
-
-#define lnextself(otri)                                                       \
-  (otri).orient = plus1mod3[(otri).orient]
-
-/* lprev() finds the previous edge (clockwise) of a triangle.                */
-
-#define lprev(otri1, otri2)                                                   \
-  (otri2).tri = (otri1).tri;                                                  \
-  (otri2).orient = minus1mod3[(otri1).orient]
-
-#define lprevself(otri)                                                       \
-  (otri).orient = minus1mod3[(otri).orient]
-
-/* onext() spins counterclockwise around a vertex; that is, it finds the     */
-/*   next edge with the same origin in the counterclockwise direction.  This */
-/*   edge is part of a different triangle.                                   */
-
-#define onext(otri1, otri2)                                                   \
-  lprev(otri1, otri2);                                                        \
-  symself(otri2);
-
-#define onextself(otri)                                                       \
-  lprevself(otri);                                                            \
-  symself(otri);
-
-/* oprev() spins clockwise around a vertex; that is, it finds the next edge  */
-/*   with the same origin in the clockwise direction.  This edge is part of  */
-/*   a different triangle.                                                   */
-
-#define oprev(otri1, otri2)                                                   \
-  sym(otri1, otri2);                                                          \
-  lnextself(otri2);
-
-#define oprevself(otri)                                                       \
-  symself(otri);                                                              \
-  lnextself(otri);
-
-/* dnext() spins counterclockwise around a vertex; that is, it finds the     */
-/*   next edge with the same destination in the counterclockwise direction.  */
-/*   This edge is part of a different triangle.                              */
-
-#define dnext(otri1, otri2)                                                   \
-  sym(otri1, otri2);                                                          \
-  lprevself(otri2);
-
-#define dnextself(otri)                                                       \
-  symself(otri);                                                              \
-  lprevself(otri);
-
-/* dprev() spins clockwise around a vertex; that is, it finds the next edge  */
-/*   with the same destination in the clockwise direction.  This edge is     */
-/*   part of a different triangle.                                           */
-
-#define dprev(otri1, otri2)                                                   \
-  lnext(otri1, otri2);                                                        \
-  symself(otri2);
-
-#define dprevself(otri)                                                       \
-  lnextself(otri);                                                            \
-  symself(otri);
-
-/* rnext() moves one edge counterclockwise about the adjacent triangle.      */
-/*   (It's best understood by reading Guibas and Stolfi.  It involves        */
-/*   changing triangles twice.)                                              */
-
-#define rnext(otri1, otri2)                                                   \
-  sym(otri1, otri2);                                                          \
-  lnextself(otri2);                                                           \
-  symself(otri2);
-
-#define rnextself(otri)                                                       \
-  symself(otri);                                                              \
-  lnextself(otri);                                                            \
-  symself(otri);
-
-/* rprev() moves one edge clockwise about the adjacent triangle.             */
-/*   (It's best understood by reading Guibas and Stolfi.  It involves        */
-/*   changing triangles twice.)                                              */
-
-#define rprev(otri1, otri2)                                                   \
-  sym(otri1, otri2);                                                          \
-  lprevself(otri2);                                                           \
-  symself(otri2);
-
-#define rprevself(otri)                                                       \
-  symself(otri);                                                              \
-  lprevself(otri);                                                            \
-  symself(otri);
-
-/* These primitives determine or set the origin, destination, or apex of a   */
-/* triangle.                                                                 */
-
-#define org(otri, vertexptr)                                                  \
-  vertexptr = (vertex) (otri).tri[plus1mod3[(otri).orient] + 3]
-
-#define dest(otri, vertexptr)                                                 \
-  vertexptr = (vertex) (otri).tri[minus1mod3[(otri).orient] + 3]
-
-#define apex(otri, vertexptr)                                                 \
-  vertexptr = (vertex) (otri).tri[(otri).orient + 3]
-
-#define setorg(otri, vertexptr)                                               \
-  (otri).tri[plus1mod3[(otri).orient] + 3] = (triangle) vertexptr
-
-#define setdest(otri, vertexptr)                                              \
-  (otri).tri[minus1mod3[(otri).orient] + 3] = (triangle) vertexptr
-
-#define setapex(otri, vertexptr)                                              \
-  (otri).tri[(otri).orient + 3] = (triangle) vertexptr
-
-/* Bond two triangles together.                                              */
-
-#define bond(otri1, otri2)                                                    \
-  (otri1).tri[(otri1).orient] = encode(otri2);                                \
-  (otri2).tri[(otri2).orient] = encode(otri1)
-
-/* Dissolve a bond (from one side).  Note that the other triangle will still */
-/*   think it's connected to this triangle.  Usually, however, the other     */
-/*   triangle is being deleted entirely, or bonded to another triangle, so   */
-/*   it doesn't matter.                                                      */
-
-#define dissolve(otri)                                                        \
-  (otri).tri[(otri).orient] = (triangle) m->dummytri
-
-/* Copy an oriented triangle.                                                */
-
-#define otricopy(otri1, otri2)                                                \
-  (otri2).tri = (otri1).tri;                                                  \
-  (otri2).orient = (otri1).orient
-
-/* Test for equality of oriented triangles.                                  */
-
-#define otriequal(otri1, otri2)                                               \
-  (((otri1).tri == (otri2).tri) &&                                            \
-   ((otri1).orient == (otri2).orient))
-
-/* Primitives to infect or cure a triangle with the virus.  These rely on    */
-/*   the assumption that all subsegments are aligned to four-byte boundaries.*/
-
-#define infect(otri)                                                          \
-  (otri).tri[6] = (triangle)                                                  \
-                    ((unsigned long) (otri).tri[6] | (unsigned long) 2l)
-
-#define uninfect(otri)                                                        \
-  (otri).tri[6] = (triangle)                                                  \
-                    ((unsigned long) (otri).tri[6] & ~ (unsigned long) 2l)
-
-/* Test a triangle for viral infection.                                      */
-
-#define infected(otri)                                                        \
-  (((unsigned long) (otri).tri[6] & (unsigned long) 2l) != 0l)
-
-/* Check or set a triangle's attributes.                                     */
-
-#define elemattribute(otri, attnum)                                           \
-  ((REAL *) (otri).tri)[m->elemattribindex + (attnum)]
-
-#define setelemattribute(otri, attnum, value)                                 \
-  ((REAL *) (otri).tri)[m->elemattribindex + (attnum)] = value
-
-/* Check or set a triangle's maximum area bound.                             */
-
-#define areabound(otri)  ((REAL *) (otri).tri)[m->areaboundindex]
-
-#define setareabound(otri, value)                                             \
-  ((REAL *) (otri).tri)[m->areaboundindex] = value
-
-/* Check or set a triangle's deallocation.  Its second pointer is set to     */
-/*   NULL to indicate that it is not allocated.  (Its first pointer is used  */
-/*   for the stack of dead items.)  Its fourth pointer (its first vertex)    */
-/*   is set to NULL in case a `badtriang' structure points to it.            */
-
-#define deadtri(tria)  ((tria)[1] == (triangle) NULL)
-
-#define killtri(tria)                                                         \
-  (tria)[1] = (triangle) NULL;                                                \
-  (tria)[3] = (triangle) NULL
-
-/********* Primitives for subsegments                                *********/
-/*                                                                           */
-/*                                                                           */
-
-/* sdecode() converts a pointer to an oriented subsegment.  The orientation  */
-/*   is extracted from the least significant bit of the pointer.  The two    */
-/*   least significant bits (one for orientation, one for viral infection)   */
-/*   are masked out to produce the real pointer.                             */
-
-#define sdecode(sptr, osub)                                                   \
-  (osub).ssorient = (int) ((unsigned long) (sptr) & (unsigned long) 1l);      \
-  (osub).ss = (subseg *)                                                      \
-              ((unsigned long) (sptr) & ~ (unsigned long) 3l)
-
-/* sencode() compresses an oriented subsegment into a single pointer.  It    */
-/*   relies on the assumption that all subsegments are aligned to two-byte   */
-/*   boundaries, so the least significant bit of (osub).ss is zero.          */
-
-#define sencode(osub)                                                         \
-  (subseg) ((unsigned long) (osub).ss | (unsigned long) (osub).ssorient)
-
-/* ssym() toggles the orientation of a subsegment.                           */
-
-#define ssym(osub1, osub2)                                                    \
-  (osub2).ss = (osub1).ss;                                                    \
-  (osub2).ssorient = 1 - (osub1).ssorient
-
-#define ssymself(osub)                                                        \
-  (osub).ssorient = 1 - (osub).ssorient
-
-/* spivot() finds the other subsegment (from the same segment) that shares   */
-/*   the same origin.                                                        */
-
-#define spivot(osub1, osub2)                                                  \
-  sptr = (osub1).ss[(osub1).ssorient];                                        \
-  sdecode(sptr, osub2)
-
-#define spivotself(osub)                                                      \
-  sptr = (osub).ss[(osub).ssorient];                                          \
-  sdecode(sptr, osub)
-
-/* snext() finds the next subsegment (from the same segment) in sequence;    */
-/*   one whose origin is the input subsegment's destination.                 */
-
-#define snext(osub1, osub2)                                                   \
-  sptr = (osub1).ss[1 - (osub1).ssorient];                                    \
-  sdecode(sptr, osub2)
-
-#define snextself(osub)                                                       \
-  sptr = (osub).ss[1 - (osub).ssorient];                                      \
-  sdecode(sptr, osub)
-
-/* These primitives determine or set the origin or destination of a          */
-/*   subsegment or the segment that includes it.                             */
-
-#define sorg(osub, vertexptr)                                                 \
-  vertexptr = (vertex) (osub).ss[2 + (osub).ssorient]
-
-#define sdest(osub, vertexptr)                                                \
-  vertexptr = (vertex) (osub).ss[3 - (osub).ssorient]
-
-#define setsorg(osub, vertexptr)                                              \
-  (osub).ss[2 + (osub).ssorient] = (subseg) vertexptr
-
-#define setsdest(osub, vertexptr)                                             \
-  (osub).ss[3 - (osub).ssorient] = (subseg) vertexptr
-
-#define segorg(osub, vertexptr)                                               \
-  vertexptr = (vertex) (osub).ss[4 + (osub).ssorient]
-
-#define segdest(osub, vertexptr)                                              \
-  vertexptr = (vertex) (osub).ss[5 - (osub).ssorient]
-
-#define setsegorg(osub, vertexptr)                                            \
-  (osub).ss[4 + (osub).ssorient] = (subseg) vertexptr
-
-#define setsegdest(osub, vertexptr)                                           \
-  (osub).ss[5 - (osub).ssorient] = (subseg) vertexptr
-
-/* These primitives read or set a boundary marker.  Boundary markers are     */
-/*   used to hold user-defined tags for setting boundary conditions in       */
-/*   finite element solvers.                                                 */
-
-#define mark(osub)  (* (int *) ((osub).ss + 8))
-
-#define setmark(osub, value)                                                  \
-  * (int *) ((osub).ss + 8) = value
-
-/* Bond two subsegments together.                                            */
-
-#define sbond(osub1, osub2)                                                   \
-  (osub1).ss[(osub1).ssorient] = sencode(osub2);                              \
-  (osub2).ss[(osub2).ssorient] = sencode(osub1)
-
-/* Dissolve a subsegment bond (from one side).  Note that the other          */
-/*   subsegment will still think it's connected to this subsegment.          */
-
-#define sdissolve(osub)                                                       \
-  (osub).ss[(osub).ssorient] = (subseg) m->dummysub
-
-/* Copy a subsegment.                                                        */
-
-#define subsegcopy(osub1, osub2)                                              \
-  (osub2).ss = (osub1).ss;                                                    \
-  (osub2).ssorient = (osub1).ssorient
-
-/* Test for equality of subsegments.                                         */
-
-#define subsegequal(osub1, osub2)                                             \
-  (((osub1).ss == (osub2).ss) &&                                              \
-   ((osub1).ssorient == (osub2).ssorient))
-
-/* Check or set a subsegment's deallocation.  Its second pointer is set to   */
-/*   NULL to indicate that it is not allocated.  (Its first pointer is used  */
-/*   for the stack of dead items.)  Its third pointer (its first vertex)     */
-/*   is set to NULL in case a `badsubseg' structure points to it.            */
-
-#define deadsubseg(sub)  ((sub)[1] == (subseg) NULL)
-
-#define killsubseg(sub)                                                       \
-  (sub)[1] = (subseg) NULL;                                                   \
-  (sub)[2] = (subseg) NULL
-
-/********* Primitives for interacting triangles and subsegments      *********/
-/*                                                                           */
-/*                                                                           */
-
-/* tspivot() finds a subsegment abutting a triangle.                         */
-
-#define tspivot(otri, osub)                                                   \
-  sptr = (subseg) (otri).tri[6 + (otri).orient];                              \
-  sdecode(sptr, osub)
-
-/* stpivot() finds a triangle abutting a subsegment.  It requires that the   */
-/*   variable `ptr' of type `triangle' be defined.                           */
-
-#define stpivot(osub, otri)                                                   \
-  ptr = (triangle) (osub).ss[6 + (osub).ssorient];                            \
-  decode(ptr, otri)
-
-/* Bond a triangle to a subsegment.                                          */
-
-#define tsbond(otri, osub)                                                    \
-  (otri).tri[6 + (otri).orient] = (triangle) sencode(osub);                   \
-  (osub).ss[6 + (osub).ssorient] = (subseg) encode(otri)
-
-/* Dissolve a bond (from the triangle side).                                 */
-
-#define tsdissolve(otri)                                                      \
-  (otri).tri[6 + (otri).orient] = (triangle) m->dummysub
-
-/* Dissolve a bond (from the subsegment side).                               */
-
-#define stdissolve(osub)                                                      \
-  (osub).ss[6 + (osub).ssorient] = (subseg) m->dummytri
-
-/********* Primitives for vertices                                   *********/
-/*                                                                           */
-/*                                                                           */
-
-#define vertexmark(vx)  ((int *) (vx))[m->vertexmarkindex]
-
-#define setvertexmark(vx, value)                                              \
-  ((int *) (vx))[m->vertexmarkindex] = value
-
-#define vertextype(vx)  ((int *) (vx))[m->vertexmarkindex + 1]
-
-#define setvertextype(vx, value)                                              \
-  ((int *) (vx))[m->vertexmarkindex + 1] = value
-
-#define vertex2tri(vx)  ((triangle *) (vx))[m->vertex2triindex]
-
-#define setvertex2tri(vx, value)                                              \
-  ((triangle *) (vx))[m->vertex2triindex] = value
-
-/**                                                                         **/
-/**                                                                         **/
-/********* Mesh manipulation primitives end here                     *********/
-
-/********* User-defined triangle evaluation routine begins here      *********/
-/**                                                                         **/
-/**                                                                         **/
-
-/*****************************************************************************/
-/*                                                                           */
-/*  triunsuitable()   Determine if a triangle is unsuitable, and thus must   */
-/*                    be further refined.                                    */
-/*                                                                           */
-/*  You may write your own procedure that decides whether or not a selected  */
-/*  triangle is too big (and needs to be refined).  There are two ways to do */
-/*  this.                                                                    */
-/*                                                                           */
-/*  (1)  Modify the procedure `triunsuitable' below, then recompile          */
-/*  Triangle.                                                                */
-/*                                                                           */
-/*  (2)  Define the symbol EXTERNAL_TEST (either by adding the definition    */
-/*  to this file, or by using the appropriate compiler switch).  This way,   */
-/*  you can compile triangle.c separately from your test.  Write your own    */
-/*  `triunsuitable' procedure in a separate C file (using the same prototype */
-/*  as below).  Compile it and link the object code with triangle.o.         */
-/*                                                                           */
-/*  This procedure returns 1 if the triangle is too large and should be      */
-/*  refined; 0 otherwise.                                                    */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef EXTERNAL_TEST
-
-int triunsuitable();
-
-#else /* not EXTERNAL_TEST */
-
-#ifdef ANSI_DECLARATORS
-int triunsuitable(vertex triorg, vertex tridest, vertex triapex, REAL area)
-#else /* not ANSI_DECLARATORS */
-int triunsuitable(triorg, tridest, triapex, area)
-vertex triorg;                              /* The triangle's origin vertex. */
-vertex tridest;                        /* The triangle's destination vertex. */
-vertex triapex;                               /* The triangle's apex vertex. */
-REAL area;                                      /* The area of the triangle. */
-#endif /* not ANSI_DECLARATORS */
-
-{
-  REAL dxoa, dxda, dxod;
-  REAL dyoa, dyda, dyod;
-  REAL oalen, dalen, odlen;
-  REAL maxlen;
-
-  dxoa = triorg[0] - triapex[0];
-  dyoa = triorg[1] - triapex[1];
-  dxda = tridest[0] - triapex[0];
-  dyda = tridest[1] - triapex[1];
-  dxod = triorg[0] - tridest[0];
-  dyod = triorg[1] - tridest[1];
-  /* Find the squares of the lengths of the triangle's three edges. */
-  oalen = dxoa * dxoa + dyoa * dyoa;
-  dalen = dxda * dxda + dyda * dyda;
-  odlen = dxod * dxod + dyod * dyod;
-  /* Find the square of the length of the longest edge. */
-  maxlen = (dalen > oalen) ? dalen : oalen;
-  maxlen = (odlen > maxlen) ? odlen : maxlen;
-
-  if (maxlen > 0.05 * (triorg[0] * triorg[0] + triorg[1] * triorg[1]) + 0.02) {
-    return 1;
-  } else {
-    return 0;
-  }
-}
-
-#endif /* not EXTERNAL_TEST */
-
-/**                                                                         **/
-/**                                                                         **/
-/********* User-defined triangle evaluation routine ends here        *********/
-
-/********* Memory allocation and program exit wrappers begin here    *********/
-/**                                                                         **/
-/**                                                                         **/
-
-#ifdef ANSI_DECLARATORS
-void triexit(int status)
-#else /* not ANSI_DECLARATORS */
-void triexit(status)
-int status;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  exit(status);
-}
-
-#ifdef ANSI_DECLARATORS
-VOID *trimalloc(int size)
-#else /* not ANSI_DECLARATORS */
-VOID *trimalloc(size)
-int size;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  VOID *memptr;
-
-  memptr = (VOID *) malloc((unsigned int) size);
-  if (memptr == (VOID *) NULL) {
-    printf("Error:  Out of memory.\n");
-    triexit(1);
-  }
-  return(memptr);
-}
-
-#ifdef ANSI_DECLARATORS
-void trifree(VOID *memptr)
-#else /* not ANSI_DECLARATORS */
-void trifree(memptr)
-VOID *memptr;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  free(memptr);
-}
-
-/**                                                                         **/
-/**                                                                         **/
-/********* Memory allocation and program exit wrappers end here      *********/
-
-/********* User interaction routines begin here                      *********/
-/**                                                                         **/
-/**                                                                         **/
-
-/*****************************************************************************/
-/*                                                                           */
-/*  syntax()   Print list of command line switches.                          */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifndef TRILIBRARY
-
-void syntax()
-{
-#ifdef CDT_ONLY
-#ifdef REDUCED
-  printf("triangle [-pAcjevngBPNEIOXzo_lQVh] input_file\n");
-#else /* not REDUCED */
-  printf("triangle [-pAcjevngBPNEIOXzo_iFlCQVh] input_file\n");
-#endif /* not REDUCED */
-#else /* not CDT_ONLY */
-#ifdef REDUCED
-  printf("triangle [-prq__a__uAcDjevngBPNEIOXzo_YS__lQVh] input_file\n");
-#else /* not REDUCED */
-  printf("triangle [-prq__a__uAcDjevngBPNEIOXzo_YS__iFlsCQVh] input_file\n");
-#endif /* not REDUCED */
-#endif /* not CDT_ONLY */
-
-  printf("    -p  Triangulates a Planar Straight Line Graph (.poly file).\n");
-#ifndef CDT_ONLY
-  printf("    -r  Refines a previously generated mesh.\n");
-  printf(
-    "    -q  Quality mesh generation.  A minimum angle may be specified.\n");
-  printf("    -a  Applies a maximum triangle area constraint.\n");
-  printf("    -u  Applies a user-defined triangle constraint.\n");
-#endif /* not CDT_ONLY */
-  printf(
-    "    -A  Applies attributes to identify triangles in certain regions.\n");
-  printf("    -c  Encloses the convex hull with segments.\n");
-#ifndef CDT_ONLY
-  printf("    -D  Conforming Delaunay:  all triangles are truly Delaunay.\n");
-#endif /* not CDT_ONLY */
-/*
-  printf("    -w  Weighted Delaunay triangulation.\n");
-  printf("    -W  Regular triangulation (lower hull of a height field).\n");
-*/
-  printf("    -j  Jettison unused vertices from output .node file.\n");
-  printf("    -e  Generates an edge list.\n");
-  printf("    -v  Generates a Voronoi diagram.\n");
-  printf("    -n  Generates a list of triangle neighbors.\n");
-  printf("    -g  Generates an .off file for Geomview.\n");
-  printf("    -B  Suppresses output of boundary information.\n");
-  printf("    -P  Suppresses output of .poly file.\n");
-  printf("    -N  Suppresses output of .node file.\n");
-  printf("    -E  Suppresses output of .ele file.\n");
-  printf("    -I  Suppresses mesh iteration numbers.\n");
-  printf("    -O  Ignores holes in .poly file.\n");
-  printf("    -X  Suppresses use of exact arithmetic.\n");
-  printf("    -z  Numbers all items starting from zero (rather than one).\n");
-  printf("    -o2 Generates second-order subparametric elements.\n");
-#ifndef CDT_ONLY
-  printf("    -Y  Suppresses boundary segment splitting.\n");
-  printf("    -S  Specifies maximum number of added Steiner points.\n");
-#endif /* not CDT_ONLY */
-#ifndef REDUCED
-  printf("    -i  Uses incremental method, rather than divide-and-conquer.\n");
-  printf("    -F  Uses Fortune's sweepline algorithm, rather than d-and-c.\n");
-#endif /* not REDUCED */
-  printf("    -l  Uses vertical cuts only, rather than alternating cuts.\n");
-#ifndef REDUCED
-#ifndef CDT_ONLY
-  printf(
-    "    -s  Force segments into mesh by splitting (instead of using CDT).\n");
-#endif /* not CDT_ONLY */
-  printf("    -C  Check consistency of final mesh.\n");
-#endif /* not REDUCED */
-  printf("    -Q  Quiet:  No terminal output except errors.\n");
-  printf("    -V  Verbose:  Detailed information on what I'm doing.\n");
-  printf("    -h  Help:  Detailed instructions for Triangle.\n");
-  triexit(0);
-}
-
-#endif /* not TRILIBRARY */
-
-/*****************************************************************************/
-/*                                                                           */
-/*  info()   Print out complete instructions.                                */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifndef TRILIBRARY
-
-void info()
-{
-  printf("Triangle\n");
-  printf(
-"A Two-Dimensional Quality Mesh Generator and Delaunay Triangulator.\n");
-  printf("Version 1.6\n\n");
-  printf(
-"Copyright 1993, 1995, 1997, 1998, 2002, 2005 Jonathan Richard Shewchuk\n");
-  printf("2360 Woolsey #H / Berkeley, California 94705-1927\n");
-  printf("Bugs/comments to jrs at cs.berkeley.edu\n");
-  printf(
-"Created as part of the Quake project (tools for earthquake simulation).\n");
-  printf(
-"Supported in part by NSF Grant CMS-9318163 and an NSERC 1967 Scholarship.\n");
-  printf("There is no warranty whatsoever.  Use at your own risk.\n");
-#ifdef SINGLE
-  printf("This executable is compiled for single precision arithmetic.\n\n\n");
-#else /* not SINGLE */
-  printf("This executable is compiled for double precision arithmetic.\n\n\n");
-#endif /* not SINGLE */
-  printf(
-"Triangle generates exact Delaunay triangulations, constrained Delaunay\n");
-  printf(
-"triangulations, conforming Delaunay triangulations, Voronoi diagrams, and\n");
-  printf(
-"high-quality triangular meshes.  The latter can be generated with no small\n"
-);
-  printf(
-"or large angles, and are thus suitable for finite element analysis.  If no\n"
-);
-  printf(
-"command line switch is specified, your .node input file is read, and the\n");
-  printf(
-"Delaunay triangulation is returned in .node and .ele output files.  The\n");
-  printf("command syntax is:\n\n");
-  printf("triangle [-prq__a__uAcDjevngBPNEIOXzo_YS__iFlsCQVh] input_file\n\n");
-  printf(
-"Underscores indicate that numbers may optionally follow certain switches.\n");
-  printf(
-"Do not leave any space between a switch and its numeric parameter.\n");
-  printf(
-"input_file must be a file with extension .node, or extension .poly if the\n");
-  printf(
-"-p switch is used.  If -r is used, you must supply .node and .ele files,\n");
-  printf(
-"and possibly a .poly file and an .area file as well.  The formats of these\n"
-);
-  printf("files are described below.\n\n");
-  printf("Command Line Switches:\n\n");
-  printf(
-"    -p  Reads a Planar Straight Line Graph (.poly file), which can specify\n"
-);
-  printf(
-"        vertices, segments, holes, regional attributes, and regional area\n");
-  printf(
-"        constraints.  Generates a constrained Delaunay triangulation (CDT)\n"
-);
-  printf(
-"        fitting the input; or, if -s, -q, -a, or -u is used, a conforming\n");
-  printf(
-"        constrained Delaunay triangulation (CCDT).  If you want a truly\n");
-  printf(
-"        Delaunay (not just constrained Delaunay) triangulation, use -D as\n");
-  printf(
-"        well.  When -p is not used, Triangle reads a .node file by default.\n"
-);
-  printf(
-"    -r  Refines a previously generated mesh.  The mesh is read from a .node\n"
-);
-  printf(
-"        file and an .ele file.  If -p is also used, a .poly file is read\n");
-  printf(
-"        and used to constrain segments in the mesh.  If -a is also used\n");
-  printf(
-"        (with no number following), an .area file is read and used to\n");
-  printf(
-"        impose area constraints on the mesh.  Further details on refinement\n"
-);
-  printf("        appear below.\n");
-  printf(
-"    -q  Quality mesh generation by Delaunay refinement (a hybrid of Paul\n");
-  printf(
-"        Chew's and Jim Ruppert's algorithms).  Adds vertices to the mesh to\n"
-);
-  printf(
-"        ensure that all angles are between 20 and 140 degrees.  An\n");
-  printf(
-"        alternative bound on the minimum angle, replacing 20 degrees, may\n");
-  printf(
-"        be specified after the `q'.  The specified angle may include a\n");
-  printf(
-"        decimal point, but not exponential notation.  Note that a bound of\n"
-);
-  printf(
-"        theta degrees on the smallest angle also implies a bound of\n");
-  printf(
-"        (180 - 2 theta) on the largest angle.  If the minimum angle is 28.6\n"
-);
-  printf(
-"        degrees or smaller, Triangle is mathematically guaranteed to\n");
-  printf(
-"        terminate (assuming infinite precision arithmetic--Triangle may\n");
-  printf(
-"        fail to terminate if you run out of precision).  In practice,\n");
-  printf(
-"        Triangle often succeeds for minimum angles up to 34 degrees.  For\n");
-  printf(
-"        some meshes, however, you might need to reduce the minimum angle to\n"
-);
-  printf(
-"        avoid problems associated with insufficient floating-point\n");
-  printf("        precision.\n");
-  printf(
-"    -a  Imposes a maximum triangle area.  If a number follows the `a', no\n");
-  printf(
-"        triangle is generated whose area is larger than that number.  If no\n"
-);
-  printf(
-"        number is specified, an .area file (if -r is used) or .poly file\n");
-  printf(
-"        (if -r is not used) specifies a set of maximum area constraints.\n");
-  printf(
-"        An .area file contains a separate area constraint for each\n");
-  printf(
-"        triangle, and is useful for refining a finite element mesh based on\n"
-);
-  printf(
-"        a posteriori error estimates.  A .poly file can optionally contain\n"
-);
-  printf(
-"        an area constraint for each segment-bounded region, thereby\n");
-  printf(
-"        controlling triangle densities in a first triangulation of a PSLG.\n"
-);
-  printf(
-"        You can impose both a fixed area constraint and a varying area\n");
-  printf(
-"        constraint by invoking the -a switch twice, once with and once\n");
-  printf(
-"        without a number following.  Each area specified may include a\n");
-  printf("        decimal point.\n");
-  printf(
-"    -u  Imposes a user-defined constraint on triangle size.  There are two\n"
-);
-  printf(
-"        ways to use this feature.  One is to edit the triunsuitable()\n");
-  printf(
-"        procedure in triangle.c to encode any constraint you like, then\n");
-  printf(
-"        recompile Triangle.  The other is to compile triangle.c with the\n");
-  printf(
-"        EXTERNAL_TEST symbol set (compiler switch -DEXTERNAL_TEST), then\n");
-  printf(
-"        link Triangle with a separate object file that implements\n");
-  printf(
-"        triunsuitable().  In either case, the -u switch causes the user-\n");
-  printf("        defined test to be applied to every triangle.\n");
-  printf(
-"    -A  Assigns an additional floating-point attribute to each triangle\n");
-  printf(
-"        that identifies what segment-bounded region each triangle belongs\n");
-  printf(
-"        to.  Attributes are assigned to regions by the .poly file.  If a\n");
-  printf(
-"        region is not explicitly marked by the .poly file, triangles in\n");
-  printf(
-"        that region are assigned an attribute of zero.  The -A switch has\n");
-  printf(
-"        an effect only when the -p switch is used and the -r switch is not.\n"
-);
-  printf(
-"    -c  Creates segments on the convex hull of the triangulation.  If you\n");
-  printf(
-"        are triangulating a vertex set, this switch causes a .poly file to\n"
-);
-  printf(
-"        be written, containing all edges of the convex hull.  If you are\n");
-  printf(
-"        triangulating a PSLG, this switch specifies that the whole convex\n");
-  printf(
-"        hull of the PSLG should be triangulated, regardless of what\n");
-  printf(
-"        segments the PSLG has.  If you do not use this switch when\n");
-  printf(
-"        triangulating a PSLG, Triangle assumes that you have identified the\n"
-);
-  printf(
-"        region to be triangulated by surrounding it with segments of the\n");
-  printf(
-"        input PSLG.  Beware:  if you are not careful, this switch can cause\n"
-);
-  printf(
-"        the introduction of an extremely thin angle between a PSLG segment\n"
-);
-  printf(
-"        and a convex hull segment, which can cause overrefinement (and\n");
-  printf(
-"        possibly failure if Triangle runs out of precision).  If you are\n");
-  printf(
-"        refining a mesh, the -c switch works differently:  it causes a\n");
-  printf(
-"        .poly file to be written containing the boundary edges of the mesh\n"
-);
-  printf("        (useful if no .poly file was read).\n");
-  printf(
-"    -D  Conforming Delaunay triangulation:  use this switch if you want to\n"
-);
-  printf(
-"        ensure that all the triangles in the mesh are Delaunay, and not\n");
-  printf(
-"        merely constrained Delaunay; or if you want to ensure that all the\n"
-);
-  printf(
-"        Voronoi vertices lie within the triangulation.  (Some finite volume\n"
-);
-  printf(
-"        methods have this requirement.)  This switch invokes Ruppert's\n");
-  printf(
-"        original algorithm, which splits every subsegment whose diametral\n");
-  printf(
-"        circle is encroached.  It usually increases the number of vertices\n"
-);
-  printf("        and triangles.\n");
-  printf(
-"    -j  Jettisons vertices that are not part of the final triangulation\n");
-  printf(
-"        from the output .node file.  By default, Triangle copies all\n");
-  printf(
-"        vertices in the input .node file to the output .node file, in the\n");
-  printf(
-"        same order, so their indices do not change.  The -j switch prevents\n"
-);
-  printf(
-"        duplicated input vertices, or vertices `eaten' by holes, from\n");
-  printf(
-"        appearing in the output .node file.  Thus, if two input vertices\n");
-  printf(
-"        have exactly the same coordinates, only the first appears in the\n");
-  printf(
-"        output.  If any vertices are jettisoned, the vertex numbering in\n");
-  printf(
-"        the output .node file differs from that of the input .node file.\n");
-  printf(
-"    -e  Outputs (to an .edge file) a list of edges of the triangulation.\n");
-  printf(
-"    -v  Outputs the Voronoi diagram associated with the triangulation.\n");
-  printf(
-"        Does not attempt to detect degeneracies, so some Voronoi vertices\n");
-  printf(
-"        may be duplicated.  See the discussion of Voronoi diagrams below.\n");
-  printf(
-"    -n  Outputs (to a .neigh file) a list of triangles neighboring each\n");
-  printf("        triangle.\n");
-  printf(
-"    -g  Outputs the mesh to an Object File Format (.off) file, suitable for\n"
-);
-  printf("        viewing with the Geometry Center's Geomview package.\n");
-  printf(
-"    -B  No boundary markers in the output .node, .poly, and .edge output\n");
-  printf(
-"        files.  See the detailed discussion of boundary markers below.\n");
-  printf(
-"    -P  No output .poly file.  Saves disk space, but you lose the ability\n");
-  printf(
-"        to maintain constraining segments on later refinements of the mesh.\n"
-);
-  printf("    -N  No output .node file.\n");
-  printf("    -E  No output .ele file.\n");
-  printf(
-"    -I  No iteration numbers.  Suppresses the output of .node and .poly\n");
-  printf(
-"        files, so your input files won't be overwritten.  (If your input is\n"
-);
-  printf(
-"        a .poly file only, a .node file is written.)  Cannot be used with\n");
-  printf(
-"        the -r switch, because that would overwrite your input .ele file.\n");
-  printf(
-"        Shouldn't be used with the -q, -a, -u, or -s switch if you are\n");
-  printf(
-"        using a .node file for input, because no .node file is written, so\n"
-);
-  printf("        there is no record of any added Steiner points.\n");
-  printf("    -O  No holes.  Ignores the holes in the .poly file.\n");
-  printf(
-"    -X  No exact arithmetic.  Normally, Triangle uses exact floating-point\n"
-);
-  printf(
-"        arithmetic for certain tests if it thinks the inexact tests are not\n"
-);
-  printf(
-"        accurate enough.  Exact arithmetic ensures the robustness of the\n");
-  printf(
-"        triangulation algorithms, despite floating-point roundoff error.\n");
-  printf(
-"        Disabling exact arithmetic with the -X switch causes a small\n");
-  printf(
-"        improvement in speed and creates the possibility that Triangle will\n"
-);
-  printf("        fail to produce a valid mesh.  Not recommended.\n");
-  printf(
-"    -z  Numbers all items starting from zero (rather than one).  Note that\n"
-);
-  printf(
-"        this switch is normally overridden by the value used to number the\n"
-);
-  printf(
-"        first vertex of the input .node or .poly file.  However, this\n");
-  printf(
-"        switch is useful when calling Triangle from another program.\n");
-  printf(
-"    -o2 Generates second-order subparametric elements with six nodes each.\n"
-);
-  printf(
-"    -Y  No new vertices on the boundary.  This switch is useful when the\n");
-  printf(
-"        mesh boundary must be preserved so that it conforms to some\n");
-  printf(
-"        adjacent mesh.  Be forewarned that you will probably sacrifice much\n"
-);
-  printf(
-"        of the quality of the mesh; Triangle will try, but the resulting\n");
-  printf(
-"        mesh may contain poorly shaped triangles.  Works well if all the\n");
-  printf(
-"        boundary vertices are closely spaced.  Specify this switch twice\n");
-  printf(
-"        (`-YY') to prevent all segment splitting, including internal\n");
-  printf("        boundaries.\n");
-  printf(
-"    -S  Specifies the maximum number of Steiner points (vertices that are\n");
-  printf(
-"        not in the input, but are added to meet the constraints on minimum\n"
-);
-  printf(
-"        angle and maximum area).  The default is to allow an unlimited\n");
-  printf(
-"        number.  If you specify this switch with no number after it,\n");
-  printf(
-"        the limit is set to zero.  Triangle always adds vertices at segment\n"
-);
-  printf(
-"        intersections, even if it needs to use more vertices than the limit\n"
-);
-  printf(
-"        you set.  When Triangle inserts segments by splitting (-s), it\n");
-  printf(
-"        always adds enough vertices to ensure that all the segments of the\n"
-);
-  printf("        PLSG are recovered, ignoring the limit if necessary.\n");
-  printf(
-"    -i  Uses an incremental rather than a divide-and-conquer algorithm to\n");
-  printf(
-"        construct a Delaunay triangulation.  Try it if the divide-and-\n");
-  printf("        conquer algorithm fails.\n");
-  printf(
-"    -F  Uses Steven Fortune's sweepline algorithm to construct a Delaunay\n");
-  printf(
-"        triangulation.  Warning:  does not use exact arithmetic for all\n");
-  printf("        calculations.  An exact result is not guaranteed.\n");
-  printf(
-"    -l  Uses only vertical cuts in the divide-and-conquer algorithm.  By\n");
-  printf(
-"        default, Triangle alternates between vertical and horizontal cuts,\n"
-);
-  printf(
-"        which usually improve the speed except with vertex sets that are\n");
-  printf(
-"        small or short and wide.  This switch is primarily of theoretical\n");
-  printf("        interest.\n");
-  printf(
-"    -s  Specifies that segments should be forced into the triangulation by\n"
-);
-  printf(
-"        recursively splitting them at their midpoints, rather than by\n");
-  printf(
-"        generating a constrained Delaunay triangulation.  Segment splitting\n"
-);
-  printf(
-"        is true to Ruppert's original algorithm, but can create needlessly\n"
-);
-  printf(
-"        small triangles.  This switch is primarily of theoretical interest.\n"
-);
-  printf(
-"    -C  Check the consistency of the final mesh.  Uses exact arithmetic for\n"
-);
-  printf(
-"        checking, even if the -X switch is used.  Useful if you suspect\n");
-  printf("        Triangle is buggy.\n");
-  printf(
-"    -Q  Quiet:  Suppresses all explanation of what Triangle is doing,\n");
-  printf("        unless an error occurs.\n");
-  printf(
-"    -V  Verbose:  Gives detailed information about what Triangle is doing.\n"
-);
-  printf(
-"        Add more `V's for increasing amount of detail.  `-V' is most\n");
-  printf(
-"        useful; itgives information on algorithmic progress and much more\n");
-  printf(
-"        detailed statistics.  `-VV' gives vertex-by-vertex details, and\n");
-  printf(
-"        prints so much that Triangle runs much more slowly.  `-VVVV' gives\n"
-);
-  printf("        information only a debugger could love.\n");
-  printf("    -h  Help:  Displays these instructions.\n");
-  printf("\n");
-  printf("Definitions:\n");
-  printf("\n");
-  printf(
-"  A Delaunay triangulation of a vertex set is a triangulation whose\n");
-  printf(
-"  vertices are the vertex set, that covers the convex hull of the vertex\n");
-  printf(
-"  set.  A Delaunay triangulation has the property that no vertex lies\n");
-  printf(
-"  inside the circumscribing circle (circle that passes through all three\n");
-  printf("  vertices) of any triangle in the triangulation.\n\n");
-  printf(
-"  A Voronoi diagram of a vertex set is a subdivision of the plane into\n");
-  printf(
-"  polygonal cells (some of which may be unbounded, meaning infinitely\n");
-  printf(
-"  large), where each cell is the set of points in the plane that are closer\n"
-);
-  printf(
-"  to some input vertex than to any other input vertex.  The Voronoi diagram\n"
-);
-  printf("  is a geometric dual of the Delaunay triangulation.\n\n");
-  printf(
-"  A Planar Straight Line Graph (PSLG) is a set of vertices and segments.\n");
-  printf(
-"  Segments are simply edges, whose endpoints are all vertices in the PSLG.\n"
-);
-  printf(
-"  Segments may intersect each other only at their endpoints.  The file\n");
-  printf("  format for PSLGs (.poly files) is described below.\n\n");
-  printf(
-"  A constrained Delaunay triangulation (CDT) of a PSLG is similar to a\n");
-  printf(
-"  Delaunay triangulation, but each PSLG segment is present as a single edge\n"
-);
-  printf(
-"  of the CDT.  (A constrained Delaunay triangulation is not truly a\n");
-  printf(
-"  Delaunay triangulation, because some of its triangles might not be\n");
-  printf(
-"  Delaunay.)  By definition, a CDT does not have any vertices other than\n");
-  printf(
-"  those specified in the input PSLG.  Depending on context, a CDT might\n");
-  printf(
-"  cover the convex hull of the PSLG, or it might cover only a segment-\n");
-  printf("  bounded region (e.g. a polygon).\n\n");
-  printf(
-"  A conforming Delaunay triangulation of a PSLG is a triangulation in which\n"
-);
-  printf(
-"  each triangle is truly Delaunay, and each PSLG segment is represented by\n"
-);
-  printf(
-"  a linear contiguous sequence of edges of the triangulation.  New vertices\n"
-);
-  printf(
-"  (not part of the PSLG) may appear, and each input segment may have been\n");
-  printf(
-"  subdivided into shorter edges (subsegments) by these additional vertices.\n"
-);
-  printf(
-"  The new vertices are frequently necessary to maintain the Delaunay\n");
-  printf("  property while ensuring that every segment is represented.\n\n");
-  printf(
-"  A conforming constrained Delaunay triangulation (CCDT) of a PSLG is a\n");
-  printf(
-"  triangulation of a PSLG whose triangles are constrained Delaunay.  New\n");
-  printf("  vertices may appear, and input segments may be subdivided into\n");
-  printf(
-"  subsegments, but not to guarantee that segments are respected; rather, to\n"
-);
-  printf(
-"  improve the quality of the triangles.  The high-quality meshes produced\n");
-  printf(
-"  by the -q switch are usually CCDTs, but can be made conforming Delaunay\n");
-  printf("  with the -D switch.\n\n");
-  printf("File Formats:\n\n");
-  printf(
-"  All files may contain comments prefixed by the character '#'.  Vertices,\n"
-);
-  printf(
-"  triangles, edges, holes, and maximum area constraints must be numbered\n");
-  printf(
-"  consecutively, starting from either 1 or 0.  Whichever you choose, all\n");
-  printf(
-"  input files must be consistent; if the vertices are numbered from 1, so\n");
-  printf(
-"  must be all other objects.  Triangle automatically detects your choice\n");
-  printf(
-"  while reading the .node (or .poly) file.  (When calling Triangle from\n");
-  printf(
-"  another program, use the -z switch if you wish to number objects from\n");
-  printf("  zero.)  Examples of these file formats are given below.\n\n");
-  printf("  .node files:\n");
-  printf(
-"    First line:  <# of vertices> <dimension (must be 2)> <# of attributes>\n"
-);
-  printf(
-"                                           <# of boundary markers (0 or 1)>\n"
-);
-  printf(
-"    Remaining lines:  <vertex #> <x> <y> [attributes] [boundary marker]\n");
-  printf("\n");
-  printf(
-"    The attributes, which are typically floating-point values of physical\n");
-  printf(
-"    quantities (such as mass or conductivity) associated with the nodes of\n"
-);
-  printf(
-"    a finite element mesh, are copied unchanged to the output mesh.  If -q,\n"
-);
-  printf(
-"    -a, -u, -D, or -s is selected, each new Steiner point added to the mesh\n"
-);
-  printf("    has attributes assigned to it by linear interpolation.\n\n");
-  printf(
-"    If the fourth entry of the first line is `1', the last column of the\n");
-  printf(
-"    remainder of the file is assumed to contain boundary markers.  Boundary\n"
-);
-  printf(
-"    markers are used to identify boundary vertices and vertices resting on\n"
-);
-  printf(
-"    PSLG segments; a complete description appears in a section below.  The\n"
-);
-  printf(
-"    .node file produced by Triangle contains boundary markers in the last\n");
-  printf("    column unless they are suppressed by the -B switch.\n\n");
-  printf("  .ele files:\n");
-  printf(
-"    First line:  <# of triangles> <nodes per triangle> <# of attributes>\n");
-  printf(
-"    Remaining lines:  <triangle #> <node> <node> <node> ... [attributes]\n");
-  printf("\n");
-  printf(
-"    Nodes are indices into the corresponding .node file.  The first three\n");
-  printf(
-"    nodes are the corner vertices, and are listed in counterclockwise order\n"
-);
-  printf(
-"    around each triangle.  (The remaining nodes, if any, depend on the type\n"
-);
-  printf("    of finite element used.)\n\n");
-  printf(
-"    The attributes are just like those of .node files.  Because there is no\n"
-);
-  printf(
-"    simple mapping from input to output triangles, Triangle attempts to\n");
-  printf(
-"    interpolate attributes, and may cause a lot of diffusion of attributes\n"
-);
-  printf(
-"    among nearby triangles as the triangulation is refined.  Attributes do\n"
-);
-  printf("    not diffuse across segments, so attributes used to identify\n");
-  printf("    segment-bounded regions remain intact.\n\n");
-  printf(
-"    In .ele files produced by Triangle, each triangular element has three\n");
-  printf(
-"    nodes (vertices) unless the -o2 switch is used, in which case\n");
-  printf(
-"    subparametric quadratic elements with six nodes each are generated.\n");
-  printf(
-"    The first three nodes are the corners in counterclockwise order, and\n");
-  printf(
-"    the fourth, fifth, and sixth nodes lie on the midpoints of the edges\n");
-  printf(
-"    opposite the first, second, and third vertices, respectively.\n");
-  printf("\n");
-  printf("  .poly files:\n");
-  printf(
-"    First line:  <# of vertices> <dimension (must be 2)> <# of attributes>\n"
-);
-  printf(
-"                                           <# of boundary markers (0 or 1)>\n"
-);
-  printf(
-"    Following lines:  <vertex #> <x> <y> [attributes] [boundary marker]\n");
-  printf("    One line:  <# of segments> <# of boundary markers (0 or 1)>\n");
-  printf(
-"    Following lines:  <segment #> <endpoint> <endpoint> [boundary marker]\n");
-  printf("    One line:  <# of holes>\n");
-  printf("    Following lines:  <hole #> <x> <y>\n");
-  printf(
-"    Optional line:  <# of regional attributes and/or area constraints>\n");
-  printf(
-"    Optional following lines:  <region #> <x> <y> <attribute> <max area>\n");
-  printf("\n");
-  printf(
-"    A .poly file represents a PSLG, as well as some additional information.\n"
-);
-  printf(
-"    The first section lists all the vertices, and is identical to the\n");
-  printf(
-"    format of .node files.  <# of vertices> may be set to zero to indicate\n"
-);
-  printf(
-"    that the vertices are listed in a separate .node file; .poly files\n");
-  printf(
-"    produced by Triangle always have this format.  A vertex set represented\n"
-);
-  printf(
-"    this way has the advantage that it may easily be triangulated with or\n");
-  printf(
-"    without segments (depending on whether the -p switch is invoked).\n");
-  printf("\n");
-  printf(
-"    The second section lists the segments.  Segments are edges whose\n");
-  printf(
-"    presence in the triangulation is enforced.  (Depending on the choice of\n"
-);
-  printf(
-"    switches, segment might be subdivided into smaller edges).  Each\n");
-  printf(
-"    segment is specified by listing the indices of its two endpoints.  This\n"
-);
-  printf(
-"    means that you must include its endpoints in the vertex list.  Each\n");
-  printf("    segment, like each point, may have a boundary marker.\n\n");
-  printf(
-"    If -q, -a, -u, and -s are not selected, Triangle produces a constrained\n"
-);
-  printf(
-"    Delaunay triangulation (CDT), in which each segment appears as a single\n"
-);
-  printf(
-"    edge in the triangulation.  If -q, -a, -u, or -s is selected, Triangle\n"
-);
-  printf(
-"    produces a conforming constrained Delaunay triangulation (CCDT), in\n");
-  printf(
-"    which segments may be subdivided into smaller edges.  If -D is\n");
-  printf(
-"    selected, Triangle produces a conforming Delaunay triangulation, so\n");
-  printf(
-"    that every triangle is Delaunay, and not just constrained Delaunay.\n");
-  printf("\n");
-  printf(
-"    The third section lists holes (and concavities, if -c is selected) in\n");
-  printf(
-"    the triangulation.  Holes are specified by identifying a point inside\n");
-  printf(
-"    each hole.  After the triangulation is formed, Triangle creates holes\n");
-  printf(
-"    by eating triangles, spreading out from each hole point until its\n");
-  printf(
-"    progress is blocked by segments in the PSLG.  You must be careful to\n");
-  printf(
-"    enclose each hole in segments, or your whole triangulation might be\n");
-  printf(
-"    eaten away.  If the two triangles abutting a segment are eaten, the\n");
-  printf(
-"    segment itself is also eaten.  Do not place a hole directly on a\n");
-  printf("    segment; if you do, Triangle chooses one side of the segment\n");
-  printf("    arbitrarily.\n\n");
-  printf(
-"    The optional fourth section lists regional attributes (to be assigned\n");
-  printf(
-"    to all triangles in a region) and regional constraints on the maximum\n");
-  printf(
-"    triangle area.  Triangle reads this section only if the -A switch is\n");
-  printf(
-"    used or the -a switch is used without a number following it, and the -r\n"
-);
-  printf(
-"    switch is not used.  Regional attributes and area constraints are\n");
-  printf(
-"    propagated in the same manner as holes:  you specify a point for each\n");
-  printf(
-"    attribute and/or constraint, and the attribute and/or constraint\n");
-  printf(
-"    affects the whole region (bounded by segments) containing the point.\n");
-  printf(
-"    If two values are written on a line after the x and y coordinate, the\n");
-  printf(
-"    first such value is assumed to be a regional attribute (but is only\n");
-  printf(
-"    applied if the -A switch is selected), and the second value is assumed\n"
-);
-  printf(
-"    to be a regional area constraint (but is only applied if the -a switch\n"
-);
-  printf(
-"    is selected).  You may specify just one value after the coordinates,\n");
-  printf(
-"    which can serve as both an attribute and an area constraint, depending\n"
-);
-  printf(
-"    on the choice of switches.  If you are using the -A and -a switches\n");
-  printf(
-"    simultaneously and wish to assign an attribute to some region without\n");
-  printf("    imposing an area constraint, use a negative maximum area.\n\n");
-  printf(
-"    When a triangulation is created from a .poly file, you must either\n");
-  printf(
-"    enclose the entire region to be triangulated in PSLG segments, or\n");
-  printf(
-"    use the -c switch, which automatically creates extra segments that\n");
-  printf(
-"    enclose the convex hull of the PSLG.  If you do not use the -c switch,\n"
-);
-  printf(
-"    Triangle eats all triangles that are not enclosed by segments; if you\n");
-  printf(
-"    are not careful, your whole triangulation may be eaten away.  If you do\n"
-);
-  printf(
-"    use the -c switch, you can still produce concavities by the appropriate\n"
-);
-  printf(
-"    placement of holes just inside the boundary of the convex hull.\n");
-  printf("\n");
-  printf(
-"    An ideal PSLG has no intersecting segments, nor any vertices that lie\n");
-  printf(
-"    upon segments (except, of course, the endpoints of each segment).  You\n"
-);
-  printf(
-"    aren't required to make your .poly files ideal, but you should be aware\n"
-);
-  printf(
-"    of what can go wrong.  Segment intersections are relatively safe--\n");
-  printf(
-"    Triangle calculates the intersection points for you and adds them to\n");
-  printf(
-"    the triangulation--as long as your machine's floating-point precision\n");
-  printf(
-"    doesn't become a problem.  You are tempting the fates if you have three\n"
-);
-  printf(
-"    segments that cross at the same location, and expect Triangle to figure\n"
-);
-  printf(
-"    out where the intersection point is.  Thanks to floating-point roundoff\n"
-);
-  printf(
-"    error, Triangle will probably decide that the three segments intersect\n"
-);
-  printf(
-"    at three different points, and you will find a minuscule triangle in\n");
-  printf(
-"    your output--unless Triangle tries to refine the tiny triangle, uses\n");
-  printf(
-"    up the last bit of machine precision, and fails to terminate at all.\n");
-  printf(
-"    You're better off putting the intersection point in the input files,\n");
-  printf(
-"    and manually breaking up each segment into two.  Similarly, if you\n");
-  printf(
-"    place a vertex at the middle of a segment, and hope that Triangle will\n"
-);
-  printf(
-"    break up the segment at that vertex, you might get lucky.  On the other\n"
-);
-  printf(
-"    hand, Triangle might decide that the vertex doesn't lie precisely on\n");
-  printf(
-"    the segment, and you'll have a needle-sharp triangle in your output--or\n"
-);
-  printf("    a lot of tiny triangles if you're generating a quality mesh.\n");
-  printf("\n");
-  printf(
-"    When Triangle reads a .poly file, it also writes a .poly file, which\n");
-  printf(
-"    includes all the subsegments--the edges that are parts of input\n");
-  printf(
-"    segments.  If the -c switch is used, the output .poly file also\n");
-  printf(
-"    includes all of the edges on the convex hull.  Hence, the output .poly\n"
-);
-  printf(
-"    file is useful for finding edges associated with input segments and for\n"
-);
-  printf(
-"    setting boundary conditions in finite element simulations.  Moreover,\n");
-  printf(
-"    you will need the output .poly file if you plan to refine the output\n");
-  printf(
-"    mesh, and don't want segments to be missing in later triangulations.\n");
-  printf("\n");
-  printf("  .area files:\n");
-  printf("    First line:  <# of triangles>\n");
-  printf("    Following lines:  <triangle #> <maximum area>\n");
-  printf("\n");
-  printf(
-"    An .area file associates with each triangle a maximum area that is used\n"
-);
-  printf(
-"    for mesh refinement.  As with other file formats, every triangle must\n");
-  printf(
-"    be represented, and the triangles must be numbered consecutively.  A\n");
-  printf(
-"    triangle may be left unconstrained by assigning it a negative maximum\n");
-  printf("    area.\n\n");
-  printf("  .edge files:\n");
-  printf("    First line:  <# of edges> <# of boundary markers (0 or 1)>\n");
-  printf(
-"    Following lines:  <edge #> <endpoint> <endpoint> [boundary marker]\n");
-  printf("\n");
-  printf(
-"    Endpoints are indices into the corresponding .node file.  Triangle can\n"
-);
-  printf(
-"    produce .edge files (use the -e switch), but cannot read them.  The\n");
-  printf(
-"    optional column of boundary markers is suppressed by the -B switch.\n");
-  printf("\n");
-  printf(
-"    In Voronoi diagrams, one also finds a special kind of edge that is an\n");
-  printf(
-"    infinite ray with only one endpoint.  For these edges, a different\n");
-  printf("    format is used:\n\n");
-  printf("        <edge #> <endpoint> -1 <direction x> <direction y>\n\n");
-  printf(
-"    The `direction' is a floating-point vector that indicates the direction\n"
-);
-  printf("    of the infinite ray.\n\n");
-  printf("  .neigh files:\n");
-  printf(
-"    First line:  <# of triangles> <# of neighbors per triangle (always 3)>\n"
-);
-  printf(
-"    Following lines:  <triangle #> <neighbor> <neighbor> <neighbor>\n");
-  printf("\n");
-  printf(
-"    Neighbors are indices into the corresponding .ele file.  An index of -1\n"
-);
-  printf(
-"    indicates no neighbor (because the triangle is on an exterior\n");
-  printf(
-"    boundary).  The first neighbor of triangle i is opposite the first\n");
-  printf("    corner of triangle i, and so on.\n\n");
-  printf(
-"    Triangle can produce .neigh files (use the -n switch), but cannot read\n"
-);
-  printf("    them.\n\n");
-  printf("Boundary Markers:\n\n");
-  printf(
-"  Boundary markers are tags used mainly to identify which output vertices\n");
-  printf(
-"  and edges are associated with which PSLG segment, and to identify which\n");
-  printf(
-"  vertices and edges occur on a boundary of the triangulation.  A common\n");
-  printf(
-"  use is to determine where boundary conditions should be applied to a\n");
-  printf(
-"  finite element mesh.  You can prevent boundary markers from being written\n"
-);
-  printf("  into files produced by Triangle by using the -B switch.\n\n");
-  printf(
-"  The boundary marker associated with each segment in an output .poly file\n"
-);
-  printf("  and each edge in an output .edge file is chosen as follows:\n");
-  printf(
-"    - If an output edge is part or all of a PSLG segment with a nonzero\n");
-  printf(
-"      boundary marker, then the edge is assigned the same marker.\n");
-  printf(
-"    - Otherwise, if the edge lies on a boundary of the triangulation\n");
-  printf(
-"      (even the boundary of a hole), then the edge is assigned the marker\n");
-  printf("      one (1).\n");
-  printf("    - Otherwise, the edge is assigned the marker zero (0).\n");
-  printf(
-"  The boundary marker associated with each vertex in an output .node file\n");
-  printf("  is chosen as follows:\n");
-  printf(
-"    - If a vertex is assigned a nonzero boundary marker in the input file,\n"
-);
-  printf(
-"      then it is assigned the same marker in the output .node file.\n");
-  printf(
-"    - Otherwise, if the vertex lies on a PSLG segment (even if it is an\n");
-  printf(
-"      endpoint of the segment) with a nonzero boundary marker, then the\n");
-  printf(
-"      vertex is assigned the same marker.  If the vertex lies on several\n");
-  printf("      such segments, one of the markers is chosen arbitrarily.\n");
-  printf(
-"    - Otherwise, if the vertex occurs on a boundary of the triangulation,\n");
-  printf("      then the vertex is assigned the marker one (1).\n");
-  printf("    - Otherwise, the vertex is assigned the marker zero (0).\n");
-  printf("\n");
-  printf(
-"  If you want Triangle to determine for you which vertices and edges are on\n"
-);
-  printf(
-"  the boundary, assign them the boundary marker zero (or use no markers at\n"
-);
-  printf(
-"  all) in your input files.  In the output files, all boundary vertices,\n");
-  printf("  edges, and segments will be assigned the value one.\n\n");
-  printf("Triangulation Iteration Numbers:\n\n");
-  printf(
-"  Because Triangle can read and refine its own triangulations, input\n");
-  printf(
-"  and output files have iteration numbers.  For instance, Triangle might\n");
-  printf(
-"  read the files mesh.3.node, mesh.3.ele, and mesh.3.poly, refine the\n");
-  printf(
-"  triangulation, and output the files mesh.4.node, mesh.4.ele, and\n");
-  printf("  mesh.4.poly.  Files with no iteration number are treated as if\n");
-  printf(
-"  their iteration number is zero; hence, Triangle might read the file\n");
-  printf(
-"  points.node, triangulate it, and produce the files points.1.node and\n");
-  printf("  points.1.ele.\n\n");
-  printf(
-"  Iteration numbers allow you to create a sequence of successively finer\n");
-  printf(
-"  meshes suitable for multigrid methods.  They also allow you to produce a\n"
-);
-  printf(
-"  sequence of meshes using error estimate-driven mesh refinement.\n");
-  printf("\n");
-  printf(
-"  If you're not using refinement or quality meshing, and you don't like\n");
-  printf(
-"  iteration numbers, use the -I switch to disable them.  This switch also\n");
-  printf(
-"  disables output of .node and .poly files to prevent your input files from\n"
-);
-  printf(
-"  being overwritten.  (If the input is a .poly file that contains its own\n");
-  printf(
-"  points, a .node file is written.  This can be quite convenient for\n");
-  printf("  computing CDTs or quality meshes.)\n\n");
-  printf("Examples of How to Use Triangle:\n\n");
-  printf(
-"  `triangle dots' reads vertices from dots.node, and writes their Delaunay\n"
-);
-  printf(
-"  triangulation to dots.1.node and dots.1.ele.  (dots.1.node is identical\n");
-  printf(
-"  to dots.node.)  `triangle -I dots' writes the triangulation to dots.ele\n");
-  printf(
-"  instead.  (No additional .node file is needed, so none is written.)\n");
-  printf("\n");
-  printf(
-"  `triangle -pe object.1' reads a PSLG from object.1.poly (and possibly\n");
-  printf(
-"  object.1.node, if the vertices are omitted from object.1.poly) and writes\n"
-);
-  printf(
-"  its constrained Delaunay triangulation to object.2.node and object.2.ele.\n"
-);
-  printf(
-"  The segments are copied to object.2.poly, and all edges are written to\n");
-  printf("  object.2.edge.\n\n");
-  printf(
-"  `triangle -pq31.5a.1 object' reads a PSLG from object.poly (and possibly\n"
-);
-  printf(
-"  object.node), generates a mesh whose angles are all between 31.5 and 117\n"
-);
-  printf(
-"  degrees and whose triangles all have areas of 0.1 or less, and writes the\n"
-);
-  printf(
-"  mesh to object.1.node and object.1.ele.  Each segment may be broken up\n");
-  printf("  into multiple subsegments; these are written to object.1.poly.\n");
-  printf("\n");
-  printf(
-"  Here is a sample file `box.poly' describing a square with a square hole:\n"
-);
-  printf("\n");
-  printf(
-"    # A box with eight vertices in 2D, no attributes, one boundary marker.\n"
-);
-  printf("    8 2 0 1\n");
-  printf("     # Outer box has these vertices:\n");
-  printf("     1   0 0   0\n");
-  printf("     2   0 3   0\n");
-  printf("     3   3 0   0\n");
-  printf("     4   3 3   33     # A special marker for this vertex.\n");
-  printf("     # Inner square has these vertices:\n");
-  printf("     5   1 1   0\n");
-  printf("     6   1 2   0\n");
-  printf("     7   2 1   0\n");
-  printf("     8   2 2   0\n");
-  printf("    # Five segments with boundary markers.\n");
-  printf("    5 1\n");
-  printf("     1   1 2   5      # Left side of outer box.\n");
-  printf("     # Square hole has these segments:\n");
-  printf("     2   5 7   0\n");
-  printf("     3   7 8   0\n");
-  printf("     4   8 6   10\n");
-  printf("     5   6 5   0\n");
-  printf("    # One hole in the middle of the inner square.\n");
-  printf("    1\n");
-  printf("     1   1.5 1.5\n");
-  printf("\n");
-  printf(
-"  Note that some segments are missing from the outer square, so you must\n");
-  printf(
-"  use the `-c' switch.  After `triangle -pqc box.poly', here is the output\n"
-);
-  printf(
-"  file `box.1.node', with twelve vertices.  The last four vertices were\n");
-  printf(
-"  added to meet the angle constraint.  Vertices 1, 2, and 9 have markers\n");
-  printf(
-"  from segment 1.  Vertices 6 and 8 have markers from segment 4.  All the\n");
-  printf(
-"  other vertices but 4 have been marked to indicate that they lie on a\n");
-  printf("  boundary.\n\n");
-  printf("    12  2  0  1\n");
-  printf("       1    0   0      5\n");
-  printf("       2    0   3      5\n");
-  printf("       3    3   0      1\n");
-  printf("       4    3   3     33\n");
-  printf("       5    1   1      1\n");
-  printf("       6    1   2     10\n");
-  printf("       7    2   1      1\n");
-  printf("       8    2   2     10\n");
-  printf("       9    0   1.5    5\n");
-  printf("      10    1.5   0    1\n");
-  printf("      11    3   1.5    1\n");
-  printf("      12    1.5   3    1\n");
-  printf("    # Generated by triangle -pqc box.poly\n");
-  printf("\n");
-  printf("  Here is the output file `box.1.ele', with twelve triangles.\n");
-  printf("\n");
-  printf("    12  3  0\n");
-  printf("       1     5   6   9\n");
-  printf("       2    10   3   7\n");
-  printf("       3     6   8  12\n");
-  printf("       4     9   1   5\n");
-  printf("       5     6   2   9\n");
-  printf("       6     7   3  11\n");
-  printf("       7    11   4   8\n");
-  printf("       8     7   5  10\n");
-  printf("       9    12   2   6\n");
-  printf("      10     8   7  11\n");
-  printf("      11     5   1  10\n");
-  printf("      12     8   4  12\n");
-  printf("    # Generated by triangle -pqc box.poly\n\n");
-  printf(
-"  Here is the output file `box.1.poly'.  Note that segments have been added\n"
-);
-  printf(
-"  to represent the convex hull, and some segments have been subdivided by\n");
-  printf(
-"  newly added vertices.  Note also that <# of vertices> is set to zero to\n");
-  printf("  indicate that the vertices should be read from the .node file.\n");
-  printf("\n");
-  printf("    0  2  0  1\n");
-  printf("    12  1\n");
-  printf("       1     1   9     5\n");
-  printf("       2     5   7     1\n");
-  printf("       3     8   7     1\n");
-  printf("       4     6   8    10\n");
-  printf("       5     5   6     1\n");
-  printf("       6     3  10     1\n");
-  printf("       7     4  11     1\n");
-  printf("       8     2  12     1\n");
-  printf("       9     9   2     5\n");
-  printf("      10    10   1     1\n");
-  printf("      11    11   3     1\n");
-  printf("      12    12   4     1\n");
-  printf("    1\n");
-  printf("       1   1.5 1.5\n");
-  printf("    # Generated by triangle -pqc box.poly\n");
-  printf("\n");
-  printf("Refinement and Area Constraints:\n");
-  printf("\n");
-  printf(
-"  The -r switch causes a mesh (.node and .ele files) to be read and\n");
-  printf(
-"  refined.  If the -p switch is also used, a .poly file is read and used to\n"
-);
-  printf(
-"  specify edges that are constrained and cannot be eliminated (although\n");
-  printf(
-"  they can be subdivided into smaller edges) by the refinement process.\n");
-  printf("\n");
-  printf(
-"  When you refine a mesh, you generally want to impose tighter constraints.\n"
-);
-  printf(
-"  One way to accomplish this is to use -q with a larger angle, or -a\n");
-  printf(
-"  followed by a smaller area than you used to generate the mesh you are\n");
-  printf(
-"  refining.  Another way to do this is to create an .area file, which\n");
-  printf(
-"  specifies a maximum area for each triangle, and use the -a switch\n");
-  printf(
-"  (without a number following).  Each triangle's area constraint is applied\n"
-);
-  printf(
-"  to that triangle.  Area constraints tend to diffuse as the mesh is\n");
-  printf(
-"  refined, so if there are large variations in area constraint between\n");
-  printf(
-"  adjacent triangles, you may not get the results you want.  In that case,\n"
-);
-  printf(
-"  consider instead using the -u switch and writing a C procedure that\n");
-  printf("  determines which triangles are too large.\n\n");
-  printf(
-"  If you are refining a mesh composed of linear (three-node) elements, the\n"
-);
-  printf(
-"  output mesh contains all the nodes present in the input mesh, in the same\n"
-);
-  printf(
-"  order, with new nodes added at the end of the .node file.  However, the\n");
-  printf(
-"  refinement is not hierarchical: there is no guarantee that each output\n");
-  printf(
-"  element is contained in a single input element.  Often, an output element\n"
-);
-  printf(
-"  can overlap two or three input elements, and some input edges are not\n");
-  printf(
-"  present in the output mesh.  Hence, a sequence of refined meshes forms a\n"
-);
-  printf(
-"  hierarchy of nodes, but not a hierarchy of elements.  If you refine a\n");
-  printf(
-"  mesh of higher-order elements, the hierarchical property applies only to\n"
-);
-  printf(
-"  the nodes at the corners of an element; the midpoint nodes on each edge\n");
-  printf("  are discarded before the mesh is refined.\n\n");
-  printf(
-"  Maximum area constraints in .poly files operate differently from those in\n"
-);
-  printf(
-"  .area files.  A maximum area in a .poly file applies to the whole\n");
-  printf(
-"  (segment-bounded) region in which a point falls, whereas a maximum area\n");
-  printf(
-"  in an .area file applies to only one triangle.  Area constraints in .poly\n"
-);
-  printf(
-"  files are used only when a mesh is first generated, whereas area\n");
-  printf(
-"  constraints in .area files are used only to refine an existing mesh, and\n"
-);
-  printf(
-"  are typically based on a posteriori error estimates resulting from a\n");
-  printf("  finite element simulation on that mesh.\n\n");
-  printf(
-"  `triangle -rq25 object.1' reads object.1.node and object.1.ele, then\n");
-  printf(
-"  refines the triangulation to enforce a 25 degree minimum angle, and then\n"
-);
-  printf(
-"  writes the refined triangulation to object.2.node and object.2.ele.\n");
-  printf("\n");
-  printf(
-"  `triangle -rpaa6.2 z.3' reads z.3.node, z.3.ele, z.3.poly, and z.3.area.\n"
-);
-  printf(
-"  After reconstructing the mesh and its subsegments, Triangle refines the\n");
-  printf(
-"  mesh so that no triangle has area greater than 6.2, and furthermore the\n");
-  printf(
-"  triangles satisfy the maximum area constraints in z.3.area.  No angle\n");
-  printf(
-"  bound is imposed at all.  The output is written to z.4.node, z.4.ele, and\n"
-);
-  printf("  z.4.poly.\n\n");
-  printf(
-"  The sequence `triangle -qa1 x', `triangle -rqa.3 x.1', `triangle -rqa.1\n");
-  printf(
-"  x.2' creates a sequence of successively finer meshes x.1, x.2, and x.3,\n");
-  printf("  suitable for multigrid.\n\n");
-  printf("Convex Hulls and Mesh Boundaries:\n\n");
-  printf(
-"  If the input is a vertex set (not a PSLG), Triangle produces its convex\n");
-  printf(
-"  hull as a by-product in the output .poly file if you use the -c switch.\n");
-  printf(
-"  There are faster algorithms for finding a two-dimensional convex hull\n");
-  printf("  than triangulation, of course, but this one comes for free.\n\n");
-  printf(
-"  If the input is an unconstrained mesh (you are using the -r switch but\n");
-  printf(
-"  not the -p switch), Triangle produces a list of its boundary edges\n");
-  printf(
-"  (including hole boundaries) as a by-product when you use the -c switch.\n");
-  printf(
-"  If you also use the -p switch, the output .poly file contains all the\n");
-  printf("  segments from the input .poly file as well.\n\n");
-  printf("Voronoi Diagrams:\n\n");
-  printf(
-"  The -v switch produces a Voronoi diagram, in files suffixed .v.node and\n");
-  printf(
-"  .v.edge.  For example, `triangle -v points' reads points.node, produces\n");
-  printf(
-"  its Delaunay triangulation in points.1.node and points.1.ele, and\n");
-  printf(
-"  produces its Voronoi diagram in points.1.v.node and points.1.v.edge.  The\n"
-);
-  printf(
-"  .v.node file contains a list of all Voronoi vertices, and the .v.edge\n");
-  printf(
-"  file contains a list of all Voronoi edges, some of which may be infinite\n"
-);
-  printf(
-"  rays.  (The choice of filenames makes it easy to run the set of Voronoi\n");
-  printf("  vertices through Triangle, if so desired.)\n\n");
-  printf(
-"  This implementation does not use exact arithmetic to compute the Voronoi\n"
-);
-  printf(
-"  vertices, and does not check whether neighboring vertices are identical.\n"
-);
-  printf(
-"  Be forewarned that if the Delaunay triangulation is degenerate or\n");
-  printf(
-"  near-degenerate, the Voronoi diagram may have duplicate vertices or\n");
-  printf("  crossing edges.\n\n");
-  printf(
-"  The result is a valid Voronoi diagram only if Triangle's output is a true\n"
-);
-  printf(
-"  Delaunay triangulation.  The Voronoi output is usually meaningless (and\n");
-  printf(
-"  may contain crossing edges and other pathology) if the output is a CDT or\n"
-);
-  printf(
-"  CCDT, or if it has holes or concavities.  If the triangulated domain is\n");
-  printf(
-"  convex and has no holes, you can use -D switch to force Triangle to\n");
-  printf(
-"  construct a conforming Delaunay triangulation instead of a CCDT, so the\n");
-  printf("  Voronoi diagram will be valid.\n\n");
-  printf("Mesh Topology:\n\n");
-  printf(
-"  You may wish to know which triangles are adjacent to a certain Delaunay\n");
-  printf(
-"  edge in an .edge file, which Voronoi cells are adjacent to a certain\n");
-  printf(
-"  Voronoi edge in a .v.edge file, or which Voronoi cells are adjacent to\n");
-  printf(
-"  each other.  All of this information can be found by cross-referencing\n");
-  printf(
-"  output files with the recollection that the Delaunay triangulation and\n");
-  printf("  the Voronoi diagram are planar duals.\n\n");
-  printf(
-"  Specifically, edge i of an .edge file is the dual of Voronoi edge i of\n");
-  printf(
-"  the corresponding .v.edge file, and is rotated 90 degrees counterclock-\n");
-  printf(
-"  wise from the Voronoi edge.  Triangle j of an .ele file is the dual of\n");
-  printf(
-"  vertex j of the corresponding .v.node file.  Voronoi cell k is the dual\n");
-  printf("  of vertex k of the corresponding .node file.\n\n");
-  printf(
-"  Hence, to find the triangles adjacent to a Delaunay edge, look at the\n");
-  printf(
-"  vertices of the corresponding Voronoi edge.  If the endpoints of a\n");
-  printf(
-"  Voronoi edge are Voronoi vertices 2 and 6 respectively, then triangles 2\n"
-);
-  printf(
-"  and 6 adjoin the left and right sides of the corresponding Delaunay edge,\n"
-);
-  printf(
-"  respectively.  To find the Voronoi cells adjacent to a Voronoi edge, look\n"
-);
-  printf(
-"  at the endpoints of the corresponding Delaunay edge.  If the endpoints of\n"
-);
-  printf(
-"  a Delaunay edge are input vertices 7 and 12, then Voronoi cells 7 and 12\n"
-);
-  printf(
-"  adjoin the right and left sides of the corresponding Voronoi edge,\n");
-  printf(
-"  respectively.  To find which Voronoi cells are adjacent to each other,\n");
-  printf("  just read the list of Delaunay edges.\n\n");
-  printf(
-"  Triangle does not write a list of the edges adjoining each Voronoi cell,\n"
-);
-  printf(
-"  but you can reconstructed it straightforwardly.  For instance, to find\n");
-  printf(
-"  all the edges of Voronoi cell 1, search the output .edge file for every\n");
-  printf(
-"  edge that has input vertex 1 as an endpoint.  The corresponding dual\n");
-  printf(
-"  edges in the output .v.edge file form the boundary of Voronoi cell 1.\n");
-  printf("\n");
-  printf(
-"  For each Voronoi vertex, the .neigh file gives a list of the three\n");
-  printf(
-"  Voronoi vertices attached to it.  You might find this more convenient\n");
-  printf("  than the .v.edge file.\n\n");
-  printf("Quadratic Elements:\n\n");
-  printf(
-"  Triangle generates meshes with subparametric quadratic elements if the\n");
-  printf(
-"  -o2 switch is specified.  Quadratic elements have six nodes per element,\n"
-);
-  printf(
-"  rather than three.  `Subparametric' means that the edges of the triangles\n"
-);
-  printf(
-"  are always straight, so that subparametric quadratic elements are\n");
-  printf(
-"  geometrically identical to linear elements, even though they can be used\n"
-);
-  printf(
-"  with quadratic interpolating functions.  The three extra nodes of an\n");
-  printf(
-"  element fall at the midpoints of the three edges, with the fourth, fifth,\n"
-);
-  printf(
-"  and sixth nodes appearing opposite the first, second, and third corners\n");
-  printf("  respectively.\n\n");
-  printf("Domains with Small Angles:\n\n");
-  printf(
-"  If two input segments adjoin each other at a small angle, clearly the -q\n"
-);
-  printf(
-"  switch cannot remove the small angle.  Moreover, Triangle may have no\n");
-  printf(
-"  choice but to generate additional triangles whose smallest angles are\n");
-  printf(
-"  smaller than the specified bound.  However, these triangles only appear\n");
-  printf(
-"  between input segments separated by small angles.  Moreover, if you\n");
-  printf(
-"  request a minimum angle of theta degrees, Triangle will generally produce\n"
-);
-  printf(
-"  no angle larger than 180 - 2 theta, even if it is forced to compromise on\n"
-);
-  printf("  the minimum angle.\n\n");
-  printf("Statistics:\n\n");
-  printf(
-"  After generating a mesh, Triangle prints a count of entities in the\n");
-  printf(
-"  output mesh, including the number of vertices, triangles, edges, exterior\n"
-);
-  printf(
-"  boundary edges (i.e. subsegments on the boundary of the triangulation,\n");
-  printf(
-"  including hole boundaries), interior boundary edges (i.e. subsegments of\n"
-);
-  printf(
-"  input segments not on the boundary), and total subsegments.  If you've\n");
-  printf(
-"  forgotten the statistics for an existing mesh, run Triangle on that mesh\n"
-);
-  printf(
-"  with the -rNEP switches to read the mesh and print the statistics without\n"
-);
-  printf(
-"  writing any files.  Use -rpNEP if you've got a .poly file for the mesh.\n");
-  printf("\n");
-  printf(
-"  The -V switch produces extended statistics, including a rough estimate\n");
-  printf(
-"  of memory use, the number of calls to geometric predicates, and\n");
-  printf(
-"  histograms of the angles and the aspect ratios of the triangles in the\n");
-  printf("  mesh.\n\n");
-  printf("Exact Arithmetic:\n\n");
-  printf(
-"  Triangle uses adaptive exact arithmetic to perform what computational\n");
-  printf(
-"  geometers call the `orientation' and `incircle' tests.  If the floating-\n"
-);
-  printf(
-"  point arithmetic of your machine conforms to the IEEE 754 standard (as\n");
-  printf(
-"  most workstations do), and does not use extended precision internal\n");
-  printf(
-"  floating-point registers, then your output is guaranteed to be an\n");
-  printf(
-"  absolutely true Delaunay or constrained Delaunay triangulation, roundoff\n"
-);
-  printf(
-"  error notwithstanding.  The word `adaptive' implies that these arithmetic\n"
-);
-  printf(
-"  routines compute the result only to the precision necessary to guarantee\n"
-);
-  printf(
-"  correctness, so they are usually nearly as fast as their approximate\n");
-  printf("  counterparts.\n\n");
-  printf(
-"  May CPUs, including Intel x86 processors, have extended precision\n");
-  printf(
-"  floating-point registers.  These must be reconfigured so their precision\n"
-);
-  printf(
-"  is reduced to memory precision.  Triangle does this if it is compiled\n");
-  printf("  correctly.  See the makefile for details.\n\n");
-  printf(
-"  The exact tests can be disabled with the -X switch.  On most inputs, this\n"
-);
-  printf(
-"  switch reduces the computation time by about eight percent--it's not\n");
-  printf(
-"  worth the risk.  There are rare difficult inputs (having many collinear\n");
-  printf(
-"  and cocircular vertices), however, for which the difference in speed\n");
-  printf(
-"  could be a factor of two.  Be forewarned that these are precisely the\n");
-  printf(
-"  inputs most likely to cause errors if you use the -X switch.  Hence, the\n"
-);
-  printf("  -X switch is not recommended.\n\n");
-  printf(
-"  Unfortunately, the exact tests don't solve every numerical problem.\n");
-  printf(
-"  Exact arithmetic is not used to compute the positions of new vertices,\n");
-  printf(
-"  because the bit complexity of vertex coordinates would grow without\n");
-  printf(
-"  bound.  Hence, segment intersections aren't computed exactly; in very\n");
-  printf(
-"  unusual cases, roundoff error in computing an intersection point might\n");
-  printf(
-"  actually lead to an inverted triangle and an invalid triangulation.\n");
-  printf(
-"  (This is one reason to specify your own intersection points in your .poly\n"
-);
-  printf(
-"  files.)  Similarly, exact arithmetic is not used to compute the vertices\n"
-);
-  printf("  of the Voronoi diagram.\n\n");
-  printf(
-"  Another pair of problems not solved by the exact arithmetic routines is\n");
-  printf(
-"  underflow and overflow.  If Triangle is compiled for double precision\n");
-  printf(
-"  arithmetic, I believe that Triangle's geometric predicates work correctly\n"
-);
-  printf(
-"  if the exponent of every input coordinate falls in the range [-148, 201].\n"
-);
-  printf(
-"  Underflow can silently prevent the orientation and incircle tests from\n");
-  printf(
-"  being performed exactly, while overflow typically causes a floating\n");
-  printf("  exception.\n\n");
-  printf("Calling Triangle from Another Program:\n\n");
-  printf("  Read the file triangle.h for details.\n\n");
-  printf("Troubleshooting:\n\n");
-  printf("  Please read this section before mailing me bugs.\n\n");
-  printf("  `My output mesh has no triangles!'\n\n");
-  printf(
-"    If you're using a PSLG, you've probably failed to specify a proper set\n"
-);
-  printf(
-"    of bounding segments, or forgotten to use the -c switch.  Or you may\n");
-  printf(
-"    have placed a hole badly, thereby eating all your triangles.  To test\n");
-  printf("    these possibilities, try again with the -c and -O switches.\n");
-  printf(
-"    Alternatively, all your input vertices may be collinear, in which case\n"
-);
-  printf("    you can hardly expect to triangulate them.\n\n");
-  printf("  `Triangle doesn't terminate, or just crashes.'\n\n");
-  printf(
-"    Bad things can happen when triangles get so small that the distance\n");
-  printf(
-"    between their vertices isn't much larger than the precision of your\n");
-  printf(
-"    machine's arithmetic.  If you've compiled Triangle for single-precision\n"
-);
-  printf(
-"    arithmetic, you might do better by recompiling it for double-precision.\n"
-);
-  printf(
-"    Then again, you might just have to settle for more lenient constraints\n"
-);
-  printf(
-"    on the minimum angle and the maximum area than you had planned.\n");
-  printf("\n");
-  printf(
-"    You can minimize precision problems by ensuring that the origin lies\n");
-  printf(
-"    inside your vertex set, or even inside the densest part of your\n");
-  printf(
-"    mesh.  If you're triangulating an object whose x-coordinates all fall\n");
-  printf(
-"    between 6247133 and 6247134, you're not leaving much floating-point\n");
-  printf("    precision for Triangle to work with.\n\n");
-  printf(
-"    Precision problems can occur covertly if the input PSLG contains two\n");
-  printf(
-"    segments that meet (or intersect) at an extremely small angle, or if\n");
-  printf(
-"    such an angle is introduced by the -c switch.  If you don't realize\n");
-  printf(
-"    that a tiny angle is being formed, you might never discover why\n");
-  printf(
-"    Triangle is crashing.  To check for this possibility, use the -S switch\n"
-);
-  printf(
-"    (with an appropriate limit on the number of Steiner points, found by\n");
-  printf(
-"    trial-and-error) to stop Triangle early, and view the output .poly file\n"
-);
-  printf(
-"    with Show Me (described below).  Look carefully for regions where dense\n"
-);
-  printf(
-"    clusters of vertices are forming and for small angles between segments.\n"
-);
-  printf(
-"    Zoom in closely, as such segments might look like a single segment from\n"
-);
-  printf("    a distance.\n\n");
-  printf(
-"    If some of the input values are too large, Triangle may suffer a\n");
-  printf(
-"    floating exception due to overflow when attempting to perform an\n");
-  printf(
-"    orientation or incircle test.  (Read the section on exact arithmetic\n");
-  printf(
-"    above.)  Again, I recommend compiling Triangle for double (rather\n");
-  printf("    than single) precision arithmetic.\n\n");
-  printf(
-"    Unexpected problems can arise if you use quality meshing (-q, -a, or\n");
-  printf(
-"    -u) with an input that is not segment-bounded--that is, if your input\n");
-  printf(
-"    is a vertex set, or you're using the -c switch.  If the convex hull of\n"
-);
-  printf(
-"    your input vertices has collinear vertices on its boundary, an input\n");
-  printf(
-"    vertex that you think lies on the convex hull might actually lie just\n");
-  printf(
-"    inside the convex hull.  If so, the vertex and the nearby convex hull\n");
-  printf(
-"    edge form an extremely thin triangle.  When Triangle tries to refine\n");
-  printf(
-"    the mesh to enforce angle and area constraints, Triangle might generate\n"
-);
-  printf(
-"    extremely tiny triangles, or it might fail because of insufficient\n");
-  printf("    floating-point precision.\n\n");
-  printf(
-"  `The numbering of the output vertices doesn't match the input vertices.'\n"
-);
-  printf("\n");
-  printf(
-"    You may have had duplicate input vertices, or you may have eaten some\n");
-  printf(
-"    of your input vertices with a hole, or by placing them outside the area\n"
-);
-  printf(
-"    enclosed by segments.  In any case, you can solve the problem by not\n");
-  printf("    using the -j switch.\n\n");
-  printf(
-"  `Triangle executes without incident, but when I look at the resulting\n");
-  printf(
-"  mesh, it has overlapping triangles or other geometric inconsistencies.'\n");
-  printf("\n");
-  printf(
-"    If you select the -X switch, Triangle occasionally makes mistakes due\n");
-  printf(
-"    to floating-point roundoff error.  Although these errors are rare,\n");
-  printf(
-"    don't use the -X switch.  If you still have problems, please report the\n"
-);
-  printf("    bug.\n\n");
-  printf(
-"  `Triangle executes without incident, but when I look at the resulting\n");
-  printf("  Voronoi diagram, it has overlapping edges or other geometric\n");
-  printf("  inconsistencies.'\n");
-  printf("\n");
-  printf(
-"    If your input is a PSLG (-p), you can only expect a meaningful Voronoi\n"
-);
-  printf(
-"    diagram if the domain you are triangulating is convex and free of\n");
-  printf(
-"    holes, and you use the -D switch to construct a conforming Delaunay\n");
-  printf("    triangulation (instead of a CDT or CCDT).\n\n");
-  printf(
-"  Strange things can happen if you've taken liberties with your PSLG.  Do\n");
-  printf(
-"  you have a vertex lying in the middle of a segment?  Triangle sometimes\n");
-  printf(
-"  copes poorly with that sort of thing.  Do you want to lay out a collinear\n"
-);
-  printf(
-"  row of evenly spaced, segment-connected vertices?  Have you simply\n");
-  printf(
-"  defined one long segment connecting the leftmost vertex to the rightmost\n"
-);
-  printf(
-"  vertex, and a bunch of vertices lying along it?  This method occasionally\n"
-);
-  printf(
-"  works, especially with horizontal and vertical lines, but often it\n");
-  printf(
-"  doesn't, and you'll have to connect each adjacent pair of vertices with a\n"
-);
-  printf("  separate segment.  If you don't like it, tough.\n\n");
-  printf(
-"  Furthermore, if you have segments that intersect other than at their\n");
-  printf(
-"  endpoints, try not to let the intersections fall extremely close to PSLG\n"
-);
-  printf("  vertices or each other.\n\n");
-  printf(
-"  If you have problems refining a triangulation not produced by Triangle:\n");
-  printf(
-"  Are you sure the triangulation is geometrically valid?  Is it formatted\n");
-  printf(
-"  correctly for Triangle?  Are the triangles all listed so the first three\n"
-);
-  printf(
-"  vertices are their corners in counterclockwise order?  Are all of the\n");
-  printf(
-"  triangles constrained Delaunay?  Triangle's Delaunay refinement algorithm\n"
-);
-  printf("  assumes that it starts with a CDT.\n\n");
-  printf("Show Me:\n\n");
-  printf(
-"  Triangle comes with a separate program named `Show Me', whose primary\n");
-  printf(
-"  purpose is to draw meshes on your screen or in PostScript.  Its secondary\n"
-);
-  printf(
-"  purpose is to check the validity of your input files, and do so more\n");
-  printf(
-"  thoroughly than Triangle does.  Unlike Triangle, Show Me requires that\n");
-  printf(
-"  you have the X Windows system.  Sorry, Microsoft Windows users.\n");
-  printf("\n");
-  printf("Triangle on the Web:\n");
-  printf("\n");
-  printf("  To see an illustrated version of these instructions, check out\n");
-  printf("\n");
-  printf("    http://www.cs.cmu.edu/~quake/triangle.html\n");
-  printf("\n");
-  printf("A Brief Plea:\n");
-  printf("\n");
-  printf(
-"  If you use Triangle, and especially if you use it to accomplish real\n");
-  printf(
-"  work, I would like very much to hear from you.  A short letter or email\n");
-  printf(
-"  (to jrs at cs.berkeley.edu) describing how you use Triangle will mean a lot\n"
-);
-  printf(
-"  to me.  The more people I know are using this program, the more easily I\n"
-);
-  printf(
-"  can justify spending time on improvements, which in turn will benefit\n");
-  printf(
-"  you.  Also, I can put you on a list to receive email whenever a new\n");
-  printf("  version of Triangle is available.\n\n");
-  printf(
-"  If you use a mesh generated by Triangle in a publication, please include\n"
-);
-  printf(
-"  an acknowledgment as well.  And please spell Triangle with a capital `T'!\n"
-);
-  printf(
-"  If you want to include a citation, use `Jonathan Richard Shewchuk,\n");
-  printf(
-"  ``Triangle: Engineering a 2D Quality Mesh Generator and Delaunay\n");
-  printf(
-"  Triangulator,'' in Applied Computational Geometry:  Towards Geometric\n");
-  printf(
-"  Engineering (Ming C. Lin and Dinesh Manocha, editors), volume 1148 of\n");
-  printf(
-"  Lecture Notes in Computer Science, pages 203-222, Springer-Verlag,\n");
-  printf(
-"  Berlin, May 1996.  (From the First ACM Workshop on Applied Computational\n"
-);
-  printf("  Geometry.)'\n\n");
-  printf("Research credit:\n\n");
-  printf(
-"  Of course, I can take credit for only a fraction of the ideas that made\n");
-  printf(
-"  this mesh generator possible.  Triangle owes its existence to the efforts\n"
-);
-  printf(
-"  of many fine computational geometers and other researchers, including\n");
-  printf(
-"  Marshall Bern, L. Paul Chew, Kenneth L. Clarkson, Boris Delaunay, Rex A.\n"
-);
-  printf(
-"  Dwyer, David Eppstein, Steven Fortune, Leonidas J. Guibas, Donald E.\n");
-  printf(
-"  Knuth, Charles L. Lawson, Der-Tsai Lee, Gary L. Miller, Ernst P. Mucke,\n");
-  printf(
-"  Steven E. Pav, Douglas M. Priest, Jim Ruppert, Isaac Saias, Bruce J.\n");
-  printf(
-"  Schachter, Micha Sharir, Peter W. Shor, Daniel D. Sleator, Jorge Stolfi,\n"
-);
-  printf("  Robert E. Tarjan, Alper Ungor, Christopher J. Van Wyk, Noel J.\n");
-  printf(
-"  Walkington, and Binhai Zhu.  See the comments at the beginning of the\n");
-  printf("  source code for references.\n\n");
-  triexit(0);
-}
-
-#endif /* not TRILIBRARY */
-
-/*****************************************************************************/
-/*                                                                           */
-/*  internalerror()   Ask the user to send me the defective product.  Exit.  */
-/*                                                                           */
-/*****************************************************************************/
-
-void internalerror()
-{
-  printf("  Please report this bug to jrs at cs.berkeley.edu\n");
-  printf("  Include the message above, your input data set, and the exact\n");
-  printf("    command line you used to run Triangle.\n");
-  triexit(1);
-}
-
-/*****************************************************************************/
-/*                                                                           */
-/*  parsecommandline()   Read the command line, identify switches, and set   */
-/*                       up options and file names.                          */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef ANSI_DECLARATORS
-void parsecommandline(int argc, char **argv, struct behavior *b)
-#else /* not ANSI_DECLARATORS */
-void parsecommandline(argc, argv, b)
-int argc;
-char **argv;
-struct behavior *b;
-#endif /* not ANSI_DECLARATORS */
-
-{
-#ifdef TRILIBRARY
-#define STARTINDEX 0
-#else /* not TRILIBRARY */
-#define STARTINDEX 1
-  int increment;
-  int meshnumber;
-#endif /* not TRILIBRARY */
-#ifndef CDT_ONLY
-  int k;
-  char workstring[FILENAMESIZE];
-#endif
-  int i, j;
-
-  b->poly = b->refine = b->quality = 0;
-  b->vararea = b->fixedarea = b->usertest = 0;
-  b->regionattrib = b->convex = b->weighted = b->jettison = 0;
-  b->firstnumber = 1;
-  b->edgesout = b->voronoi = b->neighbors = b->geomview = 0;
-  b->nobound = b->nopolywritten = b->nonodewritten = b->noelewritten = 0;
-  b->noiterationnum = 0;
-  b->noholes = b->noexact = 0;
-  b->incremental = b->sweepline = 0;
-  b->dwyer = 1;
-  b->splitseg = 0;
-  b->docheck = 0;
-  b->nobisect = 0;
-  b->conformdel = 0;
-  b->steiner = -1;
-  b->order = 1;
-  b->minangle = 0.0;
-  b->maxarea = -1.0;
-  b->quiet = b->verbose = 0;
-#ifndef TRILIBRARY
-  b->innodefilename[0] = '\0';
-#endif /* not TRILIBRARY */
-
-  for (i = STARTINDEX; i < argc; i++) {
-#ifndef TRILIBRARY
-    if (argv[i][0] == '-') {
-#endif /* not TRILIBRARY */
-      for (j = STARTINDEX; argv[i][j] != '\0'; j++) {
-        if (argv[i][j] == 'p') {
-          b->poly = 1;
-	}
-#ifndef CDT_ONLY
-        if (argv[i][j] == 'r') {
-          b->refine = 1;
-	}
-        if (argv[i][j] == 'q') {
-          b->quality = 1;
-          if (((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) ||
-              (argv[i][j + 1] == '.')) {
-            k = 0;
-            while (((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) ||
-                   (argv[i][j + 1] == '.')) {
-              j++;
-              workstring[k] = argv[i][j];
-              k++;
-            }
-            workstring[k] = '\0';
-            b->minangle = (REAL) strtod(workstring, (char **) NULL);
-	  } else {
-            b->minangle = 20.0;
-	  }
-	}
-        if (argv[i][j] == 'a') {
-          b->quality = 1;
-          if (((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) ||
-              (argv[i][j + 1] == '.')) {
-            b->fixedarea = 1;
-            k = 0;
-            while (((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) ||
-                   (argv[i][j + 1] == '.')) {
-              j++;
-              workstring[k] = argv[i][j];
-              k++;
-            }
-            workstring[k] = '\0';
-            b->maxarea = (REAL) strtod(workstring, (char **) NULL);
-            if (b->maxarea <= 0.0) {
-              printf("Error:  Maximum area must be greater than zero.\n");
-              triexit(1);
-	    }
-	  } else {
-            b->vararea = 1;
-	  }
-	}
-        if (argv[i][j] == 'u') {
-          b->quality = 1;
-          b->usertest = 1;
-        }
-#endif /* not CDT_ONLY */
-        if (argv[i][j] == 'A') {
-          b->regionattrib = 1;
-        }
-        if (argv[i][j] == 'c') {
-          b->convex = 1;
-        }
-        if (argv[i][j] == 'w') {
-          b->weighted = 1;
-        }
-        if (argv[i][j] == 'W') {
-          b->weighted = 2;
-        }
-        if (argv[i][j] == 'j') {
-          b->jettison = 1;
-        }
-        if (argv[i][j] == 'z') {
-          b->firstnumber = 0;
-        }
-        if (argv[i][j] == 'e') {
-          b->edgesout = 1;
-	}
-        if (argv[i][j] == 'v') {
-          b->voronoi = 1;
-	}
-        if (argv[i][j] == 'n') {
-          b->neighbors = 1;
-	}
-        if (argv[i][j] == 'g') {
-          b->geomview = 1;
-	}
-        if (argv[i][j] == 'B') {
-          b->nobound = 1;
-	}
-        if (argv[i][j] == 'P') {
-          b->nopolywritten = 1;
-	}
-        if (argv[i][j] == 'N') {
-          b->nonodewritten = 1;
-	}
-        if (argv[i][j] == 'E') {
-          b->noelewritten = 1;
-	}
-#ifndef TRILIBRARY
-        if (argv[i][j] == 'I') {
-          b->noiterationnum = 1;
-	}
-#endif /* not TRILIBRARY */
-        if (argv[i][j] == 'O') {
-          b->noholes = 1;
-	}
-        if (argv[i][j] == 'X') {
-          b->noexact = 1;
-	}
-        if (argv[i][j] == 'o') {
-          if (argv[i][j + 1] == '2') {
-            j++;
-            b->order = 2;
-          }
-	}
-#ifndef CDT_ONLY
-        if (argv[i][j] == 'Y') {
-          b->nobisect++;
-	}
-        if (argv[i][j] == 'S') {
-          b->steiner = 0;
-          while ((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) {
-            j++;
-            b->steiner = b->steiner * 10 + (int) (argv[i][j] - '0');
-          }
-        }
-#endif /* not CDT_ONLY */
-#ifndef REDUCED
-        if (argv[i][j] == 'i') {
-          b->incremental = 1;
-        }
-        if (argv[i][j] == 'F') {
-          b->sweepline = 1;
-        }
-#endif /* not REDUCED */
-        if (argv[i][j] == 'l') {
-          b->dwyer = 0;
-        }
-#ifndef REDUCED
-#ifndef CDT_ONLY
-        if (argv[i][j] == 's') {
-          b->splitseg = 1;
-        }
-        if ((argv[i][j] == 'D') || (argv[i][j] == 'L')) {
-          b->quality = 1;
-          b->conformdel = 1;
-        }
-#endif /* not CDT_ONLY */
-        if (argv[i][j] == 'C') {
-          b->docheck = 1;
-        }
-#endif /* not REDUCED */
-        if (argv[i][j] == 'Q') {
-          b->quiet = 1;
-        }
-        if (argv[i][j] == 'V') {
-          b->verbose++;
-        }
-#ifndef TRILIBRARY
-        if ((argv[i][j] == 'h') || (argv[i][j] == 'H') ||
-            (argv[i][j] == '?')) {
-          info();
-	}
-#endif /* not TRILIBRARY */
-      }
-#ifndef TRILIBRARY
-    } else {
-      strncpy(b->innodefilename, argv[i], FILENAMESIZE - 1);
-      b->innodefilename[FILENAMESIZE - 1] = '\0';
-    }
-#endif /* not TRILIBRARY */
-  }
-#ifndef TRILIBRARY
-  if (b->innodefilename[0] == '\0') {
-    syntax();
-  }
-  if (!strcmp(&b->innodefilename[strlen(b->innodefilename) - 5], ".node")) {
-    b->innodefilename[strlen(b->innodefilename) - 5] = '\0';
-  }
-  if (!strcmp(&b->innodefilename[strlen(b->innodefilename) - 5], ".poly")) {
-    b->innodefilename[strlen(b->innodefilename) - 5] = '\0';
-    b->poly = 1;
-  }
-#ifndef CDT_ONLY
-  if (!strcmp(&b->innodefilename[strlen(b->innodefilename) - 4], ".ele")) {
-    b->innodefilename[strlen(b->innodefilename) - 4] = '\0';
-    b->refine = 1;
-  }
-  if (!strcmp(&b->innodefilename[strlen(b->innodefilename) - 5], ".area")) {
-    b->innodefilename[strlen(b->innodefilename) - 5] = '\0';
-    b->refine = 1;
-    b->quality = 1;
-    b->vararea = 1;
-  }
-#endif /* not CDT_ONLY */
-#endif /* not TRILIBRARY */
-  b->usesegments = b->poly || b->refine || b->quality || b->convex;
-  b->goodangle = cos(b->minangle * PI / 180.0);
-  if (b->goodangle == 1.0) {
-    b->offconstant = 0.0;
-  } else {
-    b->offconstant = 0.475 * sqrt((1.0 + b->goodangle) / (1.0 - b->goodangle));
-  }
-  b->goodangle *= b->goodangle;
-  if (b->refine && b->noiterationnum) {
-    printf(
-      "Error:  You cannot use the -I switch when refining a triangulation.\n");
-    triexit(1);
-  }
-  /* Be careful not to allocate space for element area constraints that */
-  /*   will never be assigned any value (other than the default -1.0).  */
-  if (!b->refine && !b->poly) {
-    b->vararea = 0;
-  }
-  /* Be careful not to add an extra attribute to each element unless the */
-  /*   input supports it (PSLG in, but not refining a preexisting mesh). */
-  if (b->refine || !b->poly) {
-    b->regionattrib = 0;
-  }
-  /* Regular/weighted triangulations are incompatible with PSLGs */
-  /*   and meshing.                                              */
-  if (b->weighted && (b->poly || b->quality)) {
-    b->weighted = 0;
-    if (!b->quiet) {
-      printf("Warning:  weighted triangulations (-w, -W) are incompatible\n");
-      printf("  with PSLGs (-p) and meshing (-q, -a, -u).  Weights ignored.\n"
-             );
-    }
-  }
-  if (b->jettison && b->nonodewritten && !b->quiet) {
-    printf("Warning:  -j and -N switches are somewhat incompatible.\n");
-    printf("  If any vertices are jettisoned, you will need the output\n");
-    printf("  .node file to reconstruct the new node indices.");
-  }
-
-#ifndef TRILIBRARY
-  strcpy(b->inpolyfilename, b->innodefilename);
-  strcpy(b->inelefilename, b->innodefilename);
-  strcpy(b->areafilename, b->innodefilename);
-  increment = 0;
-  strcpy(workstring, b->innodefilename);
-  j = 1;
-  while (workstring[j] != '\0') {
-    if ((workstring[j] == '.') && (workstring[j + 1] != '\0')) {
-      increment = j + 1;
-    }
-    j++;
-  }
-  meshnumber = 0;
-  if (increment > 0) {
-    j = increment;
-    do {
-      if ((workstring[j] >= '0') && (workstring[j] <= '9')) {
-        meshnumber = meshnumber * 10 + (int) (workstring[j] - '0');
-      } else {
-        increment = 0;
-      }
-      j++;
-    } while (workstring[j] != '\0');
-  }
-  if (b->noiterationnum) {
-    strcpy(b->outnodefilename, b->innodefilename);
-    strcpy(b->outelefilename, b->innodefilename);
-    strcpy(b->edgefilename, b->innodefilename);
-    strcpy(b->vnodefilename, b->innodefilename);
-    strcpy(b->vedgefilename, b->innodefilename);
-    strcpy(b->neighborfilename, b->innodefilename);
-    strcpy(b->offfilename, b->innodefilename);
-    strcat(b->outnodefilename, ".node");
-    strcat(b->outelefilename, ".ele");
-    strcat(b->edgefilename, ".edge");
-    strcat(b->vnodefilename, ".v.node");
-    strcat(b->vedgefilename, ".v.edge");
-    strcat(b->neighborfilename, ".neigh");
-    strcat(b->offfilename, ".off");
-  } else if (increment == 0) {
-    strcpy(b->outnodefilename, b->innodefilename);
-    strcpy(b->outpolyfilename, b->innodefilename);
-    strcpy(b->outelefilename, b->innodefilename);
-    strcpy(b->edgefilename, b->innodefilename);
-    strcpy(b->vnodefilename, b->innodefilename);
-    strcpy(b->vedgefilename, b->innodefilename);
-    strcpy(b->neighborfilename, b->innodefilename);
-    strcpy(b->offfilename, b->innodefilename);
-    strcat(b->outnodefilename, ".1.node");
-    strcat(b->outpolyfilename, ".1.poly");
-    strcat(b->outelefilename, ".1.ele");
-    strcat(b->edgefilename, ".1.edge");
-    strcat(b->vnodefilename, ".1.v.node");
-    strcat(b->vedgefilename, ".1.v.edge");
-    strcat(b->neighborfilename, ".1.neigh");
-    strcat(b->offfilename, ".1.off");
-  } else {
-    workstring[increment] = '%';
-    workstring[increment + 1] = 'd';
-    workstring[increment + 2] = '\0';
-    sprintf(b->outnodefilename, workstring, meshnumber + 1);
-    strcpy(b->outpolyfilename, b->outnodefilename);
-    strcpy(b->outelefilename, b->outnodefilename);
-    strcpy(b->edgefilename, b->outnodefilename);
-    strcpy(b->vnodefilename, b->outnodefilename);
-    strcpy(b->vedgefilename, b->outnodefilename);
-    strcpy(b->neighborfilename, b->outnodefilename);
-    strcpy(b->offfilename, b->outnodefilename);
-    strcat(b->outnodefilename, ".node");
-    strcat(b->outpolyfilename, ".poly");
-    strcat(b->outelefilename, ".ele");
-    strcat(b->edgefilename, ".edge");
-    strcat(b->vnodefilename, ".v.node");
-    strcat(b->vedgefilename, ".v.edge");
-    strcat(b->neighborfilename, ".neigh");
-    strcat(b->offfilename, ".off");
-  }
-  strcat(b->innodefilename, ".node");
-  strcat(b->inpolyfilename, ".poly");
-  strcat(b->inelefilename, ".ele");
-  strcat(b->areafilename, ".area");
-#endif /* not TRILIBRARY */
-}
-
-/**                                                                         **/
-/**                                                                         **/
-/********* User interaction routines begin here                      *********/
-
-/********* Debugging routines begin here                             *********/
-/**                                                                         **/
-/**                                                                         **/
-
-/*****************************************************************************/
-/*                                                                           */
-/*  printtriangle()   Print out the details of an oriented triangle.         */
-/*                                                                           */
-/*  I originally wrote this procedure to simplify debugging; it can be       */
-/*  called directly from the debugger, and presents information about an     */
-/*  oriented triangle in digestible form.  It's also used when the           */
-/*  highest level of verbosity (`-VVV') is specified.                        */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef ANSI_DECLARATORS
-void printtriangle(struct mesh *m, struct behavior *b, struct otri *t)
-#else /* not ANSI_DECLARATORS */
-void printtriangle(m, b, t)
-struct mesh *m;
-struct behavior *b;
-struct otri *t;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  struct otri printtri;
-  struct osub printsh;
-  vertex printvertex;
-
-  printf("triangle x%lx with orientation %d:\n", (unsigned long) t->tri,
-         t->orient);
-  decode(t->tri[0], printtri);
-  if (printtri.tri == m->dummytri) {
-    printf("    [0] = Outer space\n");
-  } else {
-    printf("    [0] = x%lx  %d\n", (unsigned long) printtri.tri,
-           printtri.orient);
-  }
-  decode(t->tri[1], printtri);
-  if (printtri.tri == m->dummytri) {
-    printf("    [1] = Outer space\n");
-  } else {
-    printf("    [1] = x%lx  %d\n", (unsigned long) printtri.tri,
-           printtri.orient);
-  }
-  decode(t->tri[2], printtri);
-  if (printtri.tri == m->dummytri) {
-    printf("    [2] = Outer space\n");
-  } else {
-    printf("    [2] = x%lx  %d\n", (unsigned long) printtri.tri,
-           printtri.orient);
-  }
-
-  org(*t, printvertex);
-  if (printvertex == (vertex) NULL)
-    printf("    Origin[%d] = NULL\n", (t->orient + 1) % 3 + 3);
-  else
-    printf("    Origin[%d] = x%lx  (%.12g, %.12g)\n",
-           (t->orient + 1) % 3 + 3, (unsigned long) printvertex,
-           printvertex[0], printvertex[1]);
-  dest(*t, printvertex);
-  if (printvertex == (vertex) NULL)
-    printf("    Dest  [%d] = NULL\n", (t->orient + 2) % 3 + 3);
-  else
-    printf("    Dest  [%d] = x%lx  (%.12g, %.12g)\n",
-           (t->orient + 2) % 3 + 3, (unsigned long) printvertex,
-           printvertex[0], printvertex[1]);
-  apex(*t, printvertex);
-  if (printvertex == (vertex) NULL)
-    printf("    Apex  [%d] = NULL\n", t->orient + 3);
-  else
-    printf("    Apex  [%d] = x%lx  (%.12g, %.12g)\n",
-           t->orient + 3, (unsigned long) printvertex,
-           printvertex[0], printvertex[1]);
-
-  if (b->usesegments) {
-    sdecode(t->tri[6], printsh);
-    if (printsh.ss != m->dummysub) {
-      printf("    [6] = x%lx  %d\n", (unsigned long) printsh.ss,
-             printsh.ssorient);
-    }
-    sdecode(t->tri[7], printsh);
-    if (printsh.ss != m->dummysub) {
-      printf("    [7] = x%lx  %d\n", (unsigned long) printsh.ss,
-             printsh.ssorient);
-    }
-    sdecode(t->tri[8], printsh);
-    if (printsh.ss != m->dummysub) {
-      printf("    [8] = x%lx  %d\n", (unsigned long) printsh.ss,
-             printsh.ssorient);
-    }
-  }
-
-  if (b->vararea) {
-    printf("    Area constraint:  %.4g\n", areabound(*t));
-  }
-}
-
-/*****************************************************************************/
-/*                                                                           */
-/*  printsubseg()   Print out the details of an oriented subsegment.         */
-/*                                                                           */
-/*  I originally wrote this procedure to simplify debugging; it can be       */
-/*  called directly from the debugger, and presents information about an     */
-/*  oriented subsegment in digestible form.  It's also used when the highest */
-/*  level of verbosity (`-VVV') is specified.                                */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef ANSI_DECLARATORS
-void printsubseg(struct mesh *m, struct behavior *b, struct osub *s)
-#else /* not ANSI_DECLARATORS */
-void printsubseg(m, b, s)
-struct mesh *m;
-struct behavior *b;
-struct osub *s;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  struct osub printsh;
-  struct otri printtri;
-  vertex printvertex;
-
-  printf("subsegment x%lx with orientation %d and mark %d:\n",
-         (unsigned long) s->ss, s->ssorient, mark(*s));
-  sdecode(s->ss[0], printsh);
-  if (printsh.ss == m->dummysub) {
-    printf("    [0] = No subsegment\n");
-  } else {
-    printf("    [0] = x%lx  %d\n", (unsigned long) printsh.ss,
-           printsh.ssorient);
-  }
-  sdecode(s->ss[1], printsh);
-  if (printsh.ss == m->dummysub) {
-    printf("    [1] = No subsegment\n");
-  } else {
-    printf("    [1] = x%lx  %d\n", (unsigned long) printsh.ss,
-           printsh.ssorient);
-  }
-
-  sorg(*s, printvertex);
-  if (printvertex == (vertex) NULL)
-    printf("    Origin[%d] = NULL\n", 2 + s->ssorient);
-  else
-    printf("    Origin[%d] = x%lx  (%.12g, %.12g)\n",
-           2 + s->ssorient, (unsigned long) printvertex,
-           printvertex[0], printvertex[1]);
-  sdest(*s, printvertex);
-  if (printvertex == (vertex) NULL)
-    printf("    Dest  [%d] = NULL\n", 3 - s->ssorient);
-  else
-    printf("    Dest  [%d] = x%lx  (%.12g, %.12g)\n",
-           3 - s->ssorient, (unsigned long) printvertex,
-           printvertex[0], printvertex[1]);
-
-  decode(s->ss[6], printtri);
-  if (printtri.tri == m->dummytri) {
-    printf("    [6] = Outer space\n");
-  } else {
-    printf("    [6] = x%lx  %d\n", (unsigned long) printtri.tri,
-           printtri.orient);
-  }
-  decode(s->ss[7], printtri);
-  if (printtri.tri == m->dummytri) {
-    printf("    [7] = Outer space\n");
-  } else {
-    printf("    [7] = x%lx  %d\n", (unsigned long) printtri.tri,
-           printtri.orient);
-  }
-
-  segorg(*s, printvertex);
-  if (printvertex == (vertex) NULL)
-    printf("    Segment origin[%d] = NULL\n", 4 + s->ssorient);
-  else
-    printf("    Segment origin[%d] = x%lx  (%.12g, %.12g)\n",
-           4 + s->ssorient, (unsigned long) printvertex,
-           printvertex[0], printvertex[1]);
-  segdest(*s, printvertex);
-  if (printvertex == (vertex) NULL)
-    printf("    Segment dest  [%d] = NULL\n", 5 - s->ssorient);
-  else
-    printf("    Segment dest  [%d] = x%lx  (%.12g, %.12g)\n",
-           5 - s->ssorient, (unsigned long) printvertex,
-           printvertex[0], printvertex[1]);
-}
-
-/**                                                                         **/
-/**                                                                         **/
-/********* Debugging routines end here                               *********/
-
-/********* Memory management routines begin here                     *********/
-/**                                                                         **/
-/**                                                                         **/
-
-/*****************************************************************************/
-/*                                                                           */
-/*  poolzero()   Set all of a pool's fields to zero.                         */
-/*                                                                           */
-/*  This procedure should never be called on a pool that has any memory      */
-/*  allocated to it, as that memory would leak.                              */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef ANSI_DECLARATORS
-void poolzero(struct memorypool *pool)
-#else /* not ANSI_DECLARATORS */
-void poolzero(pool)
-struct memorypool *pool;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  pool->firstblock = (VOID **) NULL;
-  pool->nowblock = (VOID **) NULL;
-  pool->nextitem = (VOID *) NULL;
-  pool->deaditemstack = (VOID *) NULL;
-  pool->pathblock = (VOID **) NULL;
-  pool->pathitem = (VOID *) NULL;
-  pool->alignbytes = 0;
-  pool->itembytes = 0;
-  pool->itemsperblock = 0;
-  pool->itemsfirstblock = 0;
-  pool->items = 0;
-  pool->maxitems = 0;
-  pool->unallocateditems = 0;
-  pool->pathitemsleft = 0;
-}
-
-/*****************************************************************************/
-/*                                                                           */
-/*  poolrestart()   Deallocate all items in a pool.                          */
-/*                                                                           */
-/*  The pool is returned to its starting state, except that no memory is     */
-/*  freed to the operating system.  Rather, the previously allocated blocks  */
-/*  are ready to be reused.                                                  */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef ANSI_DECLARATORS
-void poolrestart(struct memorypool *pool)
-#else /* not ANSI_DECLARATORS */
-void poolrestart(pool)
-struct memorypool *pool;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  unsigned long alignptr;
-
-  pool->items = 0;
-  pool->maxitems = 0;
-
-  /* Set the currently active block. */
-  pool->nowblock = pool->firstblock;
-  /* Find the first item in the pool.  Increment by the size of (VOID *). */
-  alignptr = (unsigned long) (pool->nowblock + 1);
-  /* Align the item on an `alignbytes'-byte boundary. */
-  pool->nextitem = (VOID *)
-    (alignptr + (unsigned long) pool->alignbytes -
-     (alignptr % (unsigned long) pool->alignbytes));
-  /* There are lots of unallocated items left in this block. */
-  pool->unallocateditems = pool->itemsfirstblock;
-  /* The stack of deallocated items is empty. */
-  pool->deaditemstack = (VOID *) NULL;
-}
-
-/*****************************************************************************/
-/*                                                                           */
-/*  poolinit()   Initialize a pool of memory for allocation of items.        */
-/*                                                                           */
-/*  This routine initializes the machinery for allocating items.  A `pool'   */
-/*  is created whose records have size at least `bytecount'.  Items will be  */
-/*  allocated in `itemcount'-item blocks.  Each item is assumed to be a      */
-/*  collection of words, and either pointers or floating-point values are    */
-/*  assumed to be the "primary" word type.  (The "primary" word type is used */
-/*  to determine alignment of items.)  If `alignment' isn't zero, all items  */
-/*  will be `alignment'-byte aligned in memory.  `alignment' must be either  */
-/*  a multiple or a factor of the primary word size; powers of two are safe. */
-/*  `alignment' is normally used to create a few unused bits at the bottom   */
-/*  of each item's pointer, in which information may be stored.              */
-/*                                                                           */
-/*  Don't change this routine unless you understand it.                      */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef ANSI_DECLARATORS
-void poolinit(struct memorypool *pool, int bytecount, int itemcount,
-              int firstitemcount, int alignment)
-#else /* not ANSI_DECLARATORS */
-void poolinit(pool, bytecount, itemcount, firstitemcount, alignment)
-struct memorypool *pool;
-int bytecount;
-int itemcount;
-int firstitemcount;
-int alignment;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  /* Find the proper alignment, which must be at least as large as:   */
-  /*   - The parameter `alignment'.                                   */
-  /*   - sizeof(VOID *), so the stack of dead items can be maintained */
-  /*       without unaligned accesses.                                */
-  if (alignment > sizeof(VOID *)) {
-    pool->alignbytes = alignment;
-  } else {
-    pool->alignbytes = sizeof(VOID *);
-  }
-  pool->itembytes = ((bytecount - 1) / pool->alignbytes + 1) *
-                    pool->alignbytes;
-  pool->itemsperblock = itemcount;
-  if (firstitemcount == 0) {
-    pool->itemsfirstblock = itemcount;
-  } else {
-    pool->itemsfirstblock = firstitemcount;
-  }
-
-  /* Allocate a block of items.  Space for `itemsfirstblock' items and one  */
-  /*   pointer (to point to the next block) are allocated, as well as space */
-  /*   to ensure alignment of the items.                                    */
-  pool->firstblock = (VOID **)
-    trimalloc(pool->itemsfirstblock * pool->itembytes + (int) sizeof(VOID *) +
-              pool->alignbytes);
-  /* Set the next block pointer to NULL. */
-  *(pool->firstblock) = (VOID *) NULL;
-  poolrestart(pool);
-}
-
-/*****************************************************************************/
-/*                                                                           */
-/*  pooldeinit()   Free to the operating system all memory taken by a pool.  */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef ANSI_DECLARATORS
-void pooldeinit(struct memorypool *pool)
-#else /* not ANSI_DECLARATORS */
-void pooldeinit(pool)
-struct memorypool *pool;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  while (pool->firstblock != (VOID **) NULL) {
-    pool->nowblock = (VOID **) *(pool->firstblock);
-    trifree((VOID *) pool->firstblock);
-    pool->firstblock = pool->nowblock;
-  }
-}
-
-/*****************************************************************************/
-/*                                                                           */
-/*  poolalloc()   Allocate space for an item.                                */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef ANSI_DECLARATORS
-VOID *poolalloc(struct memorypool *pool)
-#else /* not ANSI_DECLARATORS */
-VOID *poolalloc(pool)
-struct memorypool *pool;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  VOID *newitem;
-  VOID **newblock;
-  unsigned long alignptr;
-
-  /* First check the linked list of dead items.  If the list is not   */
-  /*   empty, allocate an item from the list rather than a fresh one. */
-  if (pool->deaditemstack != (VOID *) NULL) {
-    newitem = pool->deaditemstack;               /* Take first item in list. */
-    pool->deaditemstack = * (VOID **) pool->deaditemstack;
-  } else {
-    /* Check if there are any free items left in the current block. */
-    if (pool->unallocateditems == 0) {
-      /* Check if another block must be allocated. */
-      if (*(pool->nowblock) == (VOID *) NULL) {
-        /* Allocate a new block of items, pointed to by the previous block. */
-        newblock = (VOID **) trimalloc(pool->itemsperblock * pool->itembytes +
-                                       (int) sizeof(VOID *) +
-                                       pool->alignbytes);
-        *(pool->nowblock) = (VOID *) newblock;
-        /* The next block pointer is NULL. */
-        *newblock = (VOID *) NULL;
-      }
-
-      /* Move to the new block. */
-      pool->nowblock = (VOID **) *(pool->nowblock);
-      /* Find the first item in the block.    */
-      /*   Increment by the size of (VOID *). */
-      alignptr = (unsigned long) (pool->nowblock + 1);
-      /* Align the item on an `alignbytes'-byte boundary. */
-      pool->nextitem = (VOID *)
-        (alignptr + (unsigned long) pool->alignbytes -
-         (alignptr % (unsigned long) pool->alignbytes));
-      /* There are lots of unallocated items left in this block. */
-      pool->unallocateditems = pool->itemsperblock;
-    }
-
-    /* Allocate a new item. */
-    newitem = pool->nextitem;
-    /* Advance `nextitem' pointer to next free item in block. */
-    pool->nextitem = (VOID *) ((char *) pool->nextitem + pool->itembytes);
-    pool->unallocateditems--;
-    pool->maxitems++;
-  }
-  pool->items++;
-  return newitem;
-}
-
-/*****************************************************************************/
-/*                                                                           */
-/*  pooldealloc()   Deallocate space for an item.                            */
-/*                                                                           */
-/*  The deallocated space is stored in a queue for later reuse.              */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef ANSI_DECLARATORS
-void pooldealloc(struct memorypool *pool, VOID *dyingitem)
-#else /* not ANSI_DECLARATORS */
-void pooldealloc(pool, dyingitem)
-struct memorypool *pool;
-VOID *dyingitem;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  /* Push freshly killed item onto stack. */
-  *((VOID **) dyingitem) = pool->deaditemstack;
-  pool->deaditemstack = dyingitem;
-  pool->items--;
-}
-
-/*****************************************************************************/
-/*                                                                           */
-/*  traversalinit()   Prepare to traverse the entire list of items.          */
-/*                                                                           */
-/*  This routine is used in conjunction with traverse().                     */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef ANSI_DECLARATORS
-void traversalinit(struct memorypool *pool)
-#else /* not ANSI_DECLARATORS */
-void traversalinit(pool)
-struct memorypool *pool;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  unsigned long alignptr;
-
-  /* Begin the traversal in the first block. */
-  pool->pathblock = pool->firstblock;
-  /* Find the first item in the block.  Increment by the size of (VOID *). */
-  alignptr = (unsigned long) (pool->pathblock + 1);
-  /* Align with item on an `alignbytes'-byte boundary. */
-  pool->pathitem = (VOID *)
-    (alignptr + (unsigned long) pool->alignbytes -
-     (alignptr % (unsigned long) pool->alignbytes));
-  /* Set the number of items left in the current block. */
-  pool->pathitemsleft = pool->itemsfirstblock;
-}
-
-/*****************************************************************************/
-/*                                                                           */
-/*  traverse()   Find the next item in the list.                             */
-/*                                                                           */
-/*  This routine is used in conjunction with traversalinit().  Be forewarned */
-/*  that this routine successively returns all items in the list, including  */
-/*  deallocated ones on the deaditemqueue.  It's up to you to figure out     */
-/*  which ones are actually dead.  Why?  I don't want to allocate extra      */
-/*  space just to demarcate dead items.  It can usually be done more         */
-/*  space-efficiently by a routine that knows something about the structure  */
-/*  of the item.                                                             */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef ANSI_DECLARATORS
-VOID *traverse(struct memorypool *pool)
-#else /* not ANSI_DECLARATORS */
-VOID *traverse(pool)
-struct memorypool *pool;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  VOID *newitem;
-  unsigned long alignptr;
-
-  /* Stop upon exhausting the list of items. */
-  if (pool->pathitem == pool->nextitem) {
-    return (VOID *) NULL;
-  }
-
-  /* Check whether any untraversed items remain in the current block. */
-  if (pool->pathitemsleft == 0) {
-    /* Find the next block. */
-    pool->pathblock = (VOID **) *(pool->pathblock);
-    /* Find the first item in the block.  Increment by the size of (VOID *). */
-    alignptr = (unsigned long) (pool->pathblock + 1);
-    /* Align with item on an `alignbytes'-byte boundary. */
-    pool->pathitem = (VOID *)
-      (alignptr + (unsigned long) pool->alignbytes -
-       (alignptr % (unsigned long) pool->alignbytes));
-    /* Set the number of items left in the current block. */
-    pool->pathitemsleft = pool->itemsperblock;
-  }
-
-  newitem = pool->pathitem;
-  /* Find the next item in the block. */
-  pool->pathitem = (VOID *) ((char *) pool->pathitem + pool->itembytes);
-  pool->pathitemsleft--;
-  return newitem;
-}
-
-/*****************************************************************************/
-/*                                                                           */
-/*  dummyinit()   Initialize the triangle that fills "outer space" and the   */
-/*                omnipresent subsegment.                                    */
-/*                                                                           */
-/*  The triangle that fills "outer space," called `dummytri', is pointed to  */
-/*  by every triangle and subsegment on a boundary (be it outer or inner) of */
-/*  the triangulation.  Also, `dummytri' points to one of the triangles on   */
-/*  the convex hull (until the holes and concavities are carved), making it  */
-/*  possible to find a starting triangle for point location.                 */
-/*                                                                           */
-/*  The omnipresent subsegment, `dummysub', is pointed to by every triangle  */
-/*  or subsegment that doesn't have a full complement of real subsegments    */
-/*  to point to.                                                             */
-/*                                                                           */
-/*  `dummytri' and `dummysub' are generally required to fulfill only a few   */
-/*  invariants:  their vertices must remain NULL and `dummytri' must always  */
-/*  be bonded (at offset zero) to some triangle on the convex hull of the    */
-/*  mesh, via a boundary edge.  Otherwise, the connections of `dummytri' and */
-/*  `dummysub' may change willy-nilly.  This makes it possible to avoid      */
-/*  writing a good deal of special-case code (in the edge flip, for example) */
-/*  for dealing with the boundary of the mesh, places where no subsegment is */
-/*  present, and so forth.  Other entities are frequently bonded to          */
-/*  `dummytri' and `dummysub' as if they were real mesh entities, with no    */
-/*  harm done.                                                               */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef ANSI_DECLARATORS
-void dummyinit(struct mesh *m, struct behavior *b, int trianglebytes,
-               int subsegbytes)
-#else /* not ANSI_DECLARATORS */
-void dummyinit(m, b, trianglebytes, subsegbytes)
-struct mesh *m;
-struct behavior *b;
-int trianglebytes;
-int subsegbytes;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  unsigned long alignptr;
-
-  /* Set up `dummytri', the `triangle' that occupies "outer space." */
-  m->dummytribase = (triangle *) trimalloc(trianglebytes +
-                                           m->triangles.alignbytes);
-  /* Align `dummytri' on a `triangles.alignbytes'-byte boundary. */
-  alignptr = (unsigned long) m->dummytribase;
-  m->dummytri = (triangle *)
-    (alignptr + (unsigned long) m->triangles.alignbytes -
-     (alignptr % (unsigned long) m->triangles.alignbytes));
-  /* Initialize the three adjoining triangles to be "outer space."  These  */
-  /*   will eventually be changed by various bonding operations, but their */
-  /*   values don't really matter, as long as they can legally be          */
-  /*   dereferenced.                                                       */
-  m->dummytri[0] = (triangle) m->dummytri;
-  m->dummytri[1] = (triangle) m->dummytri;
-  m->dummytri[2] = (triangle) m->dummytri;
-  /* Three NULL vertices. */
-  m->dummytri[3] = (triangle) NULL;
-  m->dummytri[4] = (triangle) NULL;
-  m->dummytri[5] = (triangle) NULL;
-
-  if (b->usesegments) {
-    /* Set up `dummysub', the omnipresent subsegment pointed to by any */
-    /*   triangle side or subsegment end that isn't attached to a real */
-    /*   subsegment.                                                   */
-    m->dummysubbase = (subseg *) trimalloc(subsegbytes +
-                                           m->subsegs.alignbytes);
-    /* Align `dummysub' on a `subsegs.alignbytes'-byte boundary. */
-    alignptr = (unsigned long) m->dummysubbase;
-    m->dummysub = (subseg *)
-      (alignptr + (unsigned long) m->subsegs.alignbytes -
-       (alignptr % (unsigned long) m->subsegs.alignbytes));
-    /* Initialize the two adjoining subsegments to be the omnipresent      */
-    /*   subsegment.  These will eventually be changed by various bonding  */
-    /*   operations, but their values don't really matter, as long as they */
-    /*   can legally be dereferenced.                                      */
-    m->dummysub[0] = (subseg) m->dummysub;
-    m->dummysub[1] = (subseg) m->dummysub;
-    /* Four NULL vertices. */
-    m->dummysub[2] = (subseg) NULL;
-    m->dummysub[3] = (subseg) NULL;
-    m->dummysub[4] = (subseg) NULL;
-    m->dummysub[5] = (subseg) NULL;
-    /* Initialize the two adjoining triangles to be "outer space." */
-    m->dummysub[6] = (subseg) m->dummytri;
-    m->dummysub[7] = (subseg) m->dummytri;
-    /* Set the boundary marker to zero. */
-    * (int *) (m->dummysub + 8) = 0;
-
-    /* Initialize the three adjoining subsegments of `dummytri' to be */
-    /*   the omnipresent subsegment.                                  */
-    m->dummytri[6] = (triangle) m->dummysub;
-    m->dummytri[7] = (triangle) m->dummysub;
-    m->dummytri[8] = (triangle) m->dummysub;
-  }
-}
-
-/*****************************************************************************/
-/*                                                                           */
-/*  initializevertexpool()   Calculate the size of the vertex data structure */
-/*                           and initialize its memory pool.                 */
-/*                                                                           */
-/*  This routine also computes the `vertexmarkindex' and `vertex2triindex'   */
-/*  indices used to find values within each vertex.                          */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef ANSI_DECLARATORS
-void initializevertexpool(struct mesh *m, struct behavior *b)
-#else /* not ANSI_DECLARATORS */
-void initializevertexpool(m, b)
-struct mesh *m;
-struct behavior *b;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  int vertexsize;
-
-  /* The index within each vertex at which the boundary marker is found,    */
-  /*   followed by the vertex type.  Ensure the vertex marker is aligned to */
-  /*   a sizeof(int)-byte address.                                          */
-  m->vertexmarkindex = ((m->mesh_dim + m->nextras) * sizeof(REAL) +
-                        sizeof(int) - 1) /
-                       sizeof(int);
-  vertexsize = (m->vertexmarkindex + 2) * sizeof(int);
-  if (b->poly) {
-    /* The index within each vertex at which a triangle pointer is found.  */
-    /*   Ensure the pointer is aligned to a sizeof(triangle)-byte address. */
-    m->vertex2triindex = (vertexsize + sizeof(triangle) - 1) /
-                         sizeof(triangle);
-    vertexsize = (m->vertex2triindex + 1) * sizeof(triangle);
-  }
-
-  /* Initialize the pool of vertices. */
-  poolinit(&m->vertices, vertexsize, VERTEXPERBLOCK,
-           m->invertices > VERTEXPERBLOCK ? m->invertices : VERTEXPERBLOCK,
-           sizeof(REAL));
-}
-
-/*****************************************************************************/
-/*                                                                           */
-/*  initializetrisubpools()   Calculate the sizes of the triangle and        */
-/*                            subsegment data structures and initialize      */
-/*                            their memory pools.                            */
-/*                                                                           */
-/*  This routine also computes the `highorderindex', `elemattribindex', and  */
-/*  `areaboundindex' indices used to find values within each triangle.       */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef ANSI_DECLARATORS
-void initializetrisubpools(struct mesh *m, struct behavior *b)
-#else /* not ANSI_DECLARATORS */
-void initializetrisubpools(m, b)
-struct mesh *m;
-struct behavior *b;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  int trisize;
-
-  /* The index within each triangle at which the extra nodes (above three)  */
-  /*   associated with high order elements are found.  There are three      */
-  /*   pointers to other triangles, three pointers to corners, and possibly */
-  /*   three pointers to subsegments before the extra nodes.                */
-  m->highorderindex = 6 + (b->usesegments * 3);
-  /* The number of bytes occupied by a triangle. */
-  trisize = ((b->order + 1) * (b->order + 2) / 2 + (m->highorderindex - 3)) *
-            sizeof(triangle);
-  /* The index within each triangle at which its attributes are found, */
-  /*   where the index is measured in REALs.                           */
-  m->elemattribindex = (trisize + sizeof(REAL) - 1) / sizeof(REAL);
-  /* The index within each triangle at which the maximum area constraint  */
-  /*   is found, where the index is measured in REALs.  Note that if the  */
-  /*   `regionattrib' flag is set, an additional attribute will be added. */
-  m->areaboundindex = m->elemattribindex + m->eextras + b->regionattrib;
-  /* If triangle attributes or an area bound are needed, increase the number */
-  /*   of bytes occupied by a triangle.                                      */
-  if (b->vararea) {
-    trisize = (m->areaboundindex + 1) * sizeof(REAL);
-  } else if (m->eextras + b->regionattrib > 0) {
-    trisize = m->areaboundindex * sizeof(REAL);
-  }
-  /* If a Voronoi diagram or triangle neighbor graph is requested, make    */
-  /*   sure there's room to store an integer index in each triangle.  This */
-  /*   integer index can occupy the same space as the subsegment pointers  */
-  /*   or attributes or area constraint or extra nodes.                    */
-  if ((b->voronoi || b->neighbors) &&
-      (trisize < 6 * sizeof(triangle) + sizeof(int))) {
-    trisize = 6 * sizeof(triangle) + sizeof(int);
-  }
-
-  /* Having determined the memory size of a triangle, initialize the pool. */
-  poolinit(&m->triangles, trisize, TRIPERBLOCK,
-           (2 * m->invertices - 2) > TRIPERBLOCK ? (2 * m->invertices - 2) :
-           TRIPERBLOCK, 4);
-
-  if (b->usesegments) {
-    /* Initialize the pool of subsegments.  Take into account all eight */
-    /*   pointers and one boundary marker.                              */
-    poolinit(&m->subsegs, 8 * sizeof(triangle) + sizeof(int),
-             SUBSEGPERBLOCK, SUBSEGPERBLOCK, 4);
-
-    /* Initialize the "outer space" triangle and omnipresent subsegment. */
-    dummyinit(m, b, m->triangles.itembytes, m->subsegs.itembytes);
-  } else {
-    /* Initialize the "outer space" triangle. */
-    dummyinit(m, b, m->triangles.itembytes, 0);
-  }
-}
-
-/*****************************************************************************/
-/*                                                                           */
-/*  triangledealloc()   Deallocate space for a triangle, marking it dead.    */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef ANSI_DECLARATORS
-void triangledealloc(struct mesh *m, triangle *dyingtriangle)
-#else /* not ANSI_DECLARATORS */
-void triangledealloc(m, dyingtriangle)
-struct mesh *m;
-triangle *dyingtriangle;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  /* Mark the triangle as dead.  This makes it possible to detect dead */
-  /*   triangles when traversing the list of all triangles.            */
-  killtri(dyingtriangle);
-  pooldealloc(&m->triangles, (VOID *) dyingtriangle);
-}
-
-/*****************************************************************************/
-/*                                                                           */
-/*  triangletraverse()   Traverse the triangles, skipping dead ones.         */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef ANSI_DECLARATORS
-triangle *triangletraverse(struct mesh *m)
-#else /* not ANSI_DECLARATORS */
-triangle *triangletraverse(m)
-struct mesh *m;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  triangle *newtriangle;
-
-  do {
-    newtriangle = (triangle *) traverse(&m->triangles);
-    if (newtriangle == (triangle *) NULL) {
-      return (triangle *) NULL;
-    }
-  } while (deadtri(newtriangle));                         /* Skip dead ones. */
-  return newtriangle;
-}
-
-/*****************************************************************************/
-/*                                                                           */
-/*  subsegdealloc()   Deallocate space for a subsegment, marking it dead.    */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef ANSI_DECLARATORS
-void subsegdealloc(struct mesh *m, subseg *dyingsubseg)
-#else /* not ANSI_DECLARATORS */
-void subsegdealloc(m, dyingsubseg)
-struct mesh *m;
-subseg *dyingsubseg;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  /* Mark the subsegment as dead.  This makes it possible to detect dead */
-  /*   subsegments when traversing the list of all subsegments.          */
-  killsubseg(dyingsubseg);
-  pooldealloc(&m->subsegs, (VOID *) dyingsubseg);
-}
-
-/*****************************************************************************/
-/*                                                                           */
-/*  subsegtraverse()   Traverse the subsegments, skipping dead ones.         */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef ANSI_DECLARATORS
-subseg *subsegtraverse(struct mesh *m)
-#else /* not ANSI_DECLARATORS */
-subseg *subsegtraverse(m)
-struct mesh *m;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  subseg *newsubseg;
-
-  do {
-    newsubseg = (subseg *) traverse(&m->subsegs);
-    if (newsubseg == (subseg *) NULL) {
-      return (subseg *) NULL;
-    }
-  } while (deadsubseg(newsubseg));                        /* Skip dead ones. */
-  return newsubseg;
-}
-
-/*****************************************************************************/
-/*                                                                           */
-/*  vertexdealloc()   Deallocate space for a vertex, marking it dead.        */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef ANSI_DECLARATORS
-void vertexdealloc(struct mesh *m, vertex dyingvertex)
-#else /* not ANSI_DECLARATORS */
-void vertexdealloc(m, dyingvertex)
-struct mesh *m;
-vertex dyingvertex;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  /* Mark the vertex as dead.  This makes it possible to detect dead */
-  /*   vertices when traversing the list of all vertices.            */
-  setvertextype(dyingvertex, DEADVERTEX);
-  pooldealloc(&m->vertices, (VOID *) dyingvertex);
-}
-
-/*****************************************************************************/
-/*                                                                           */
-/*  vertextraverse()   Traverse the vertices, skipping dead ones.            */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef ANSI_DECLARATORS
-vertex vertextraverse(struct mesh *m)
-#else /* not ANSI_DECLARATORS */
-vertex vertextraverse(m)
-struct mesh *m;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  vertex newvertex;
-
-  do {
-    newvertex = (vertex) traverse(&m->vertices);
-    if (newvertex == (vertex) NULL) {
-      return (vertex) NULL;
-    }
-  } while (vertextype(newvertex) == DEADVERTEX);          /* Skip dead ones. */
-  return newvertex;
-}
-
-/*****************************************************************************/
-/*                                                                           */
-/*  badsubsegdealloc()   Deallocate space for a bad subsegment, marking it   */
-/*                       dead.                                               */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifndef CDT_ONLY
-
-#ifdef ANSI_DECLARATORS
-void badsubsegdealloc(struct mesh *m, struct badsubseg *dyingseg)
-#else /* not ANSI_DECLARATORS */
-void badsubsegdealloc(m, dyingseg)
-struct mesh *m;
-struct badsubseg *dyingseg;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  /* Set subsegment's origin to NULL.  This makes it possible to detect dead */
-  /*   badsubsegs when traversing the list of all badsubsegs             .   */
-  dyingseg->subsegorg = (vertex) NULL;
-  pooldealloc(&m->badsubsegs, (VOID *) dyingseg);
-}
-
-#endif /* not CDT_ONLY */
-
-/*****************************************************************************/
-/*                                                                           */
-/*  badsubsegtraverse()   Traverse the bad subsegments, skipping dead ones.  */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifndef CDT_ONLY
-
-#ifdef ANSI_DECLARATORS
-struct badsubseg *badsubsegtraverse(struct mesh *m)
-#else /* not ANSI_DECLARATORS */
-struct badsubseg *badsubsegtraverse(m)
-struct mesh *m;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  struct badsubseg *newseg;
-
-  do {
-    newseg = (struct badsubseg *) traverse(&m->badsubsegs);
-    if (newseg == (struct badsubseg *) NULL) {
-      return (struct badsubseg *) NULL;
-    }
-  } while (newseg->subsegorg == (vertex) NULL);           /* Skip dead ones. */
-  return newseg;
-}
-
-#endif /* not CDT_ONLY */
-
-/*****************************************************************************/
-/*                                                                           */
-/*  getvertex()   Get a specific vertex, by number, from the list.           */
-/*                                                                           */
-/*  The first vertex is number 'firstnumber'.                                */
-/*                                                                           */
-/*  Note that this takes O(n) time (with a small constant, if VERTEXPERBLOCK */
-/*  is large).  I don't care to take the trouble to make it work in constant */
-/*  time.                                                                    */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef ANSI_DECLARATORS
-vertex getvertex(struct mesh *m, struct behavior *b, int number)
-#else /* not ANSI_DECLARATORS */
-vertex getvertex(m, b, number)
-struct mesh *m;
-struct behavior *b;
-int number;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  VOID **getblock;
-  char *foundvertex;
-  unsigned long alignptr;
-  int current;
-
-  getblock = m->vertices.firstblock;
-  current = b->firstnumber;
-
-  /* Find the right block. */
-  if (current + m->vertices.itemsfirstblock <= number) {
-    getblock = (VOID **) *getblock;
-    current += m->vertices.itemsfirstblock;
-    while (current + m->vertices.itemsperblock <= number) {
-      getblock = (VOID **) *getblock;
-      current += m->vertices.itemsperblock;
-    }
-  }
-
-  /* Now find the right vertex. */
-  alignptr = (unsigned long) (getblock + 1);
-  foundvertex = (char *) (alignptr + (unsigned long) m->vertices.alignbytes -
-                          (alignptr % (unsigned long) m->vertices.alignbytes));
-  return (vertex) (foundvertex + m->vertices.itembytes * (number - current));
-}
-
-/*****************************************************************************/
-/*                                                                           */
-/*  triangledeinit()   Free all remaining allocated memory.                  */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef ANSI_DECLARATORS
-void triangledeinit(struct mesh *m, struct behavior *b)
-#else /* not ANSI_DECLARATORS */
-void triangledeinit(m, b)
-struct mesh *m;
-struct behavior *b;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  pooldeinit(&m->triangles);
-  trifree((VOID *) m->dummytribase);
-  if (b->usesegments) {
-    pooldeinit(&m->subsegs);
-    trifree((VOID *) m->dummysubbase);
-  }
-  pooldeinit(&m->vertices);
-#ifndef CDT_ONLY
-  if (b->quality) {
-    pooldeinit(&m->badsubsegs);
-    if ((b->minangle > 0.0) || b->vararea || b->fixedarea || b->usertest) {
-      pooldeinit(&m->badtriangles);
-      pooldeinit(&m->flipstackers);
-    }
-  }
-#endif /* not CDT_ONLY */
-}
-
-/**                                                                         **/
-/**                                                                         **/
-/********* Memory management routines end here                       *********/
-
-/********* Constructors begin here                                   *********/
-/**                                                                         **/
-/**                                                                         **/
-
-/*****************************************************************************/
-/*                                                                           */
-/*  maketriangle()   Create a new triangle with orientation zero.            */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef ANSI_DECLARATORS
-void maketriangle(struct mesh *m, struct behavior *b, struct otri *newotri)
-#else /* not ANSI_DECLARATORS */
-void maketriangle(m, b, newotri)
-struct mesh *m;
-struct behavior *b;
-struct otri *newotri;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  int i;
-
-  newotri->tri = (triangle *) poolalloc(&m->triangles);
-  /* Initialize the three adjoining triangles to be "outer space". */
-  newotri->tri[0] = (triangle) m->dummytri;
-  newotri->tri[1] = (triangle) m->dummytri;
-  newotri->tri[2] = (triangle) m->dummytri;
-  /* Three NULL vertices. */
-  newotri->tri[3] = (triangle) NULL;
-  newotri->tri[4] = (triangle) NULL;
-  newotri->tri[5] = (triangle) NULL;
-  if (b->usesegments) {
-    /* Initialize the three adjoining subsegments to be the omnipresent */
-    /*   subsegment.                                                    */
-    newotri->tri[6] = (triangle) m->dummysub;
-    newotri->tri[7] = (triangle) m->dummysub;
-    newotri->tri[8] = (triangle) m->dummysub;
-  }
-  for (i = 0; i < m->eextras; i++) {
-    setelemattribute(*newotri, i, 0.0);
-  }
-  if (b->vararea) {
-    setareabound(*newotri, -1.0);
-  }
-
-  newotri->orient = 0;
-}
-
-/*****************************************************************************/
-/*                                                                           */
-/*  makesubseg()   Create a new subsegment with orientation zero.            */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef ANSI_DECLARATORS
-void makesubseg(struct mesh *m, struct osub *newsubseg)
-#else /* not ANSI_DECLARATORS */
-void makesubseg(m, newsubseg)
-struct mesh *m;
-struct osub *newsubseg;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  newsubseg->ss = (subseg *) poolalloc(&m->subsegs);
-  /* Initialize the two adjoining subsegments to be the omnipresent */
-  /*   subsegment.                                                  */
-  newsubseg->ss[0] = (subseg) m->dummysub;
-  newsubseg->ss[1] = (subseg) m->dummysub;
-  /* Four NULL vertices. */
-  newsubseg->ss[2] = (subseg) NULL;
-  newsubseg->ss[3] = (subseg) NULL;
-  newsubseg->ss[4] = (subseg) NULL;
-  newsubseg->ss[5] = (subseg) NULL;
-  /* Initialize the two adjoining triangles to be "outer space." */
-  newsubseg->ss[6] = (subseg) m->dummytri;
-  newsubseg->ss[7] = (subseg) m->dummytri;
-  /* Set the boundary marker to zero. */
-  setmark(*newsubseg, 0);
-
-  newsubseg->ssorient = 0;
-}
-
-/**                                                                         **/
-/**                                                                         **/
-/********* Constructors end here                                     *********/
-
-/********* Geometric primitives begin here                           *********/
-/**                                                                         **/
-/**                                                                         **/
-
-/* The adaptive exact arithmetic geometric predicates implemented herein are */
-/*   described in detail in my paper, "Adaptive Precision Floating-Point     */
-/*   Arithmetic and Fast Robust Geometric Predicates."  See the header for a */
-/*   full citation.                                                          */
-
-/* Which of the following two methods of finding the absolute values is      */
-/*   fastest is compiler-dependent.  A few compilers can inline and optimize */
-/*   the fabs() call; but most will incur the overhead of a function call,   */
-/*   which is disastrously slow.  A faster way on IEEE machines might be to  */
-/*   mask the appropriate bit, but that's difficult to do in C without       */
-/*   forcing the value to be stored to memory (rather than be kept in the    */
-/*   register to which the optimizer assigned it).                           */
-
-#define Absolute(a)  ((a) >= 0.0 ? (a) : -(a))
-/* #define Absolute(a)  fabs(a) */
-
-/* Many of the operations are broken up into two pieces, a main part that    */
-/*   performs an approximate operation, and a "tail" that computes the       */
-/*   roundoff error of that operation.                                       */
-/*                                                                           */
-/* The operations Fast_Two_Sum(), Fast_Two_Diff(), Two_Sum(), Two_Diff(),    */
-/*   Split(), and Two_Product() are all implemented as described in the      */
-/*   reference.  Each of these macros requires certain variables to be       */
-/*   defined in the calling routine.  The variables `bvirt', `c', `abig',    */
-/*   `_i', `_j', `_k', `_l', `_m', and `_n' are declared `INEXACT' because   */
-/*   they store the result of an operation that may incur roundoff error.    */
-/*   The input parameter `x' (or the highest numbered `x_' parameter) must   */
-/*   also be declared `INEXACT'.                                             */
-
-#define Fast_Two_Sum_Tail(a, b, x, y) \
-  bvirt = x - a; \
-  y = b - bvirt
-
-#define Fast_Two_Sum(a, b, x, y) \
-  x = (REAL) (a + b); \
-  Fast_Two_Sum_Tail(a, b, x, y)
-
-#define Two_Sum_Tail(a, b, x, y) \
-  bvirt = (REAL) (x - a); \
-  avirt = x - bvirt; \
-  bround = b - bvirt; \
-  around = a - avirt; \
-  y = around + bround
-
-#define Two_Sum(a, b, x, y) \
-  x = (REAL) (a + b); \
-  Two_Sum_Tail(a, b, x, y)
-
-#define Two_Diff_Tail(a, b, x, y) \
-  bvirt = (REAL) (a - x); \
-  avirt = x + bvirt; \
-  bround = bvirt - b; \
-  around = a - avirt; \
-  y = around + bround
-
-#define Two_Diff(a, b, x, y) \
-  x = (REAL) (a - b); \
-  Two_Diff_Tail(a, b, x, y)
-
-#define Split(a, ahi, alo) \
-  c = (REAL) (splitter * a); \
-  abig = (REAL) (c - a); \
-  ahi = c - abig; \
-  alo = a - ahi
-
-#define Two_Product_Tail(a, b, x, y) \
-  Split(a, ahi, alo); \
-  Split(b, bhi, blo); \
-  err1 = x - (ahi * bhi); \
-  err2 = err1 - (alo * bhi); \
-  err3 = err2 - (ahi * blo); \
-  y = (alo * blo) - err3
-
-#define Two_Product(a, b, x, y) \
-  x = (REAL) (a * b); \
-  Two_Product_Tail(a, b, x, y)
-
-/* Two_Product_Presplit() is Two_Product() where one of the inputs has       */
-/*   already been split.  Avoids redundant splitting.                        */
-
-#define Two_Product_Presplit(a, b, bhi, blo, x, y) \
-  x = (REAL) (a * b); \
-  Split(a, ahi, alo); \
-  err1 = x - (ahi * bhi); \
-  err2 = err1 - (alo * bhi); \
-  err3 = err2 - (ahi * blo); \
-  y = (alo * blo) - err3
-
-/* Square() can be done more quickly than Two_Product().                     */
-
-#define Square_Tail(a, x, y) \
-  Split(a, ahi, alo); \
-  err1 = x - (ahi * ahi); \
-  err3 = err1 - ((ahi + ahi) * alo); \
-  y = (alo * alo) - err3
-
-#define Square(a, x, y) \
-  x = (REAL) (a * a); \
-  Square_Tail(a, x, y)
-
-/* Macros for summing expansions of various fixed lengths.  These are all    */
-/*   unrolled versions of Expansion_Sum().                                   */
-
-#define Two_One_Sum(a1, a0, b, x2, x1, x0) \
-  Two_Sum(a0, b , _i, x0); \
-  Two_Sum(a1, _i, x2, x1)
-
-#define Two_One_Diff(a1, a0, b, x2, x1, x0) \
-  Two_Diff(a0, b , _i, x0); \
-  Two_Sum( a1, _i, x2, x1)
-
-#define Two_Two_Sum(a1, a0, b1, b0, x3, x2, x1, x0) \
-  Two_One_Sum(a1, a0, b0, _j, _0, x0); \
-  Two_One_Sum(_j, _0, b1, x3, x2, x1)
-
-#define Two_Two_Diff(a1, a0, b1, b0, x3, x2, x1, x0) \
-  Two_One_Diff(a1, a0, b0, _j, _0, x0); \
-  Two_One_Diff(_j, _0, b1, x3, x2, x1)
-
-/* Macro for multiplying a two-component expansion by a single component.    */
-
-#define Two_One_Product(a1, a0, b, x3, x2, x1, x0) \
-  Split(b, bhi, blo); \
-  Two_Product_Presplit(a0, b, bhi, blo, _i, x0); \
-  Two_Product_Presplit(a1, b, bhi, blo, _j, _0); \
-  Two_Sum(_i, _0, _k, x1); \
-  Fast_Two_Sum(_j, _k, x3, x2)
-
-/*****************************************************************************/
-/*                                                                           */
-/*  exactinit()   Initialize the variables used for exact arithmetic.        */
-/*                                                                           */
-/*  `epsilon' is the largest power of two such that 1.0 + epsilon = 1.0 in   */
-/*  floating-point arithmetic.  `epsilon' bounds the relative roundoff       */
-/*  error.  It is used for floating-point error analysis.                    */
-/*                                                                           */
-/*  `splitter' is used to split floating-point numbers into two half-        */
-/*  length significands for exact multiplication.                            */
-/*                                                                           */
-/*  I imagine that a highly optimizing compiler might be too smart for its   */
-/*  own good, and somehow cause this routine to fail, if it pretends that    */
-/*  floating-point arithmetic is too much like real arithmetic.              */
-/*                                                                           */
-/*  Don't change this routine unless you fully understand it.                */
-/*                                                                           */
-/*****************************************************************************/
-
-void exactinit()
-{
-  REAL half;
-  REAL check, lastcheck;
-  int every_other;
-#ifdef LINUX
-  int cword;
-#endif /* LINUX */
-
-#ifdef CPU86
-#ifdef SINGLE
-  _control87(_PC_24, _MCW_PC); /* Set FPU control word for single precision. */
-#else /* not SINGLE */
-  _control87(_PC_53, _MCW_PC); /* Set FPU control word for double precision. */
-#endif /* not SINGLE */
-#endif /* CPU86 */
-#ifdef LINUX
-#ifdef SINGLE
-  /*  cword = 4223; */
-  cword = 4210;                 /* set FPU control word for single precision */
-#else /* not SINGLE */
-  /*  cword = 4735; */
-  cword = 4722;                 /* set FPU control word for double precision */
-#endif /* not SINGLE */
-  _FPU_SETCW(cword);
-#endif /* LINUX */
-
-  every_other = 1;
-  half = 0.5;
-  epsilon = 1.0;
-  splitter = 1.0;
-  check = 1.0;
-  /* Repeatedly divide `epsilon' by two until it is too small to add to      */
-  /*   one without causing roundoff.  (Also check if the sum is equal to     */
-  /*   the previous sum, for machines that round up instead of using exact   */
-  /*   rounding.  Not that these routines will work on such machines.)       */
-  do {
-    lastcheck = check;
-    epsilon *= half;
-    if (every_other) {
-      splitter *= 2.0;
-    }
-    every_other = !every_other;
-    check = 1.0 + epsilon;
-  } while ((check != 1.0) && (check != lastcheck));
-  splitter += 1.0;
-  /* Error bounds for orientation and incircle tests. */
-  resulterrbound = (3.0 + 8.0 * epsilon) * epsilon;
-  ccwerrboundA = (3.0 + 16.0 * epsilon) * epsilon;
-  ccwerrboundB = (2.0 + 12.0 * epsilon) * epsilon;
-  ccwerrboundC = (9.0 + 64.0 * epsilon) * epsilon * epsilon;
-  iccerrboundA = (10.0 + 96.0 * epsilon) * epsilon;
-  iccerrboundB = (4.0 + 48.0 * epsilon) * epsilon;
-  iccerrboundC = (44.0 + 576.0 * epsilon) * epsilon * epsilon;
-  o3derrboundA = (7.0 + 56.0 * epsilon) * epsilon;
-  o3derrboundB = (3.0 + 28.0 * epsilon) * epsilon;
-  o3derrboundC = (26.0 + 288.0 * epsilon) * epsilon * epsilon;
-}
-
-/*****************************************************************************/
-/*                                                                           */
-/*  fast_expansion_sum_zeroelim()   Sum two expansions, eliminating zero     */
-/*                                  components from the output expansion.    */
-/*                                                                           */
-/*  Sets h = e + f.  See my Robust Predicates paper for details.             */
-/*                                                                           */
-/*  If round-to-even is used (as with IEEE 754), maintains the strongly      */
-/*  nonoverlapping property.  (That is, if e is strongly nonoverlapping, h   */
-/*  will be also.)  Does NOT maintain the nonoverlapping or nonadjacent      */
-/*  properties.                                                              */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef ANSI_DECLARATORS
-int fast_expansion_sum_zeroelim(int elen, REAL *e, int flen, REAL *f, REAL *h)
-#else /* not ANSI_DECLARATORS */
-int fast_expansion_sum_zeroelim(elen, e, flen, f, h)  /* h cannot be e or f. */
-int elen;
-REAL *e;
-int flen;
-REAL *f;
-REAL *h;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  REAL Q;
-  INEXACT REAL Qnew;
-  INEXACT REAL hh;
-  INEXACT REAL bvirt;
-  REAL avirt, bround, around;
-  int eindex, findex, hindex;
-  REAL enow, fnow;
-
-  enow = e[0];
-  fnow = f[0];
-  eindex = findex = 0;
-  if ((fnow > enow) == (fnow > -enow)) {
-    Q = enow;
-    enow = e[++eindex];
-  } else {
-    Q = fnow;
-    fnow = f[++findex];
-  }
-  hindex = 0;
-  if ((eindex < elen) && (findex < flen)) {
-    if ((fnow > enow) == (fnow > -enow)) {
-      Fast_Two_Sum(enow, Q, Qnew, hh);
-      enow = e[++eindex];
-    } else {
-      Fast_Two_Sum(fnow, Q, Qnew, hh);
-      fnow = f[++findex];
-    }
-    Q = Qnew;
-    if (hh != 0.0) {
-      h[hindex++] = hh;
-    }
-    while ((eindex < elen) && (findex < flen)) {
-      if ((fnow > enow) == (fnow > -enow)) {
-        Two_Sum(Q, enow, Qnew, hh);
-        enow = e[++eindex];
-      } else {
-        Two_Sum(Q, fnow, Qnew, hh);
-        fnow = f[++findex];
-      }
-      Q = Qnew;
-      if (hh != 0.0) {
-        h[hindex++] = hh;
-      }
-    }
-  }
-  while (eindex < elen) {
-    Two_Sum(Q, enow, Qnew, hh);
-    enow = e[++eindex];
-    Q = Qnew;
-    if (hh != 0.0) {
-      h[hindex++] = hh;
-    }
-  }
-  while (findex < flen) {
-    Two_Sum(Q, fnow, Qnew, hh);
-    fnow = f[++findex];
-    Q = Qnew;
-    if (hh != 0.0) {
-      h[hindex++] = hh;
-    }
-  }
-  if ((Q != 0.0) || (hindex == 0)) {
-    h[hindex++] = Q;
-  }
-  return hindex;
-}
-
-/*****************************************************************************/
-/*                                                                           */
-/*  scale_expansion_zeroelim()   Multiply an expansion by a scalar,          */
-/*                               eliminating zero components from the        */
-/*                               output expansion.                           */
-/*                                                                           */
-/*  Sets h = be.  See my Robust Predicates paper for details.                */
-/*                                                                           */
-/*  Maintains the nonoverlapping property.  If round-to-even is used (as     */
-/*  with IEEE 754), maintains the strongly nonoverlapping and nonadjacent    */
-/*  properties as well.  (That is, if e has one of these properties, so      */
-/*  will h.)                                                                 */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef ANSI_DECLARATORS
-int scale_expansion_zeroelim(int elen, REAL *e, REAL b, REAL *h)
-#else /* not ANSI_DECLARATORS */
-int scale_expansion_zeroelim(elen, e, b, h)   /* e and h cannot be the same. */
-int elen;
-REAL *e;
-REAL b;
-REAL *h;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  INEXACT REAL Q, sum;
-  REAL hh;
-  INEXACT REAL product1;
-  REAL product0;
-  int eindex, hindex;
-  REAL enow;
-  INEXACT REAL bvirt;
-  REAL avirt, bround, around;
-  INEXACT REAL c;
-  INEXACT REAL abig;
-  REAL ahi, alo, bhi, blo;
-  REAL err1, err2, err3;
-
-  Split(b, bhi, blo);
-  Two_Product_Presplit(e[0], b, bhi, blo, Q, hh);
-  hindex = 0;
-  if (hh != 0) {
-    h[hindex++] = hh;
-  }
-  for (eindex = 1; eindex < elen; eindex++) {
-    enow = e[eindex];
-    Two_Product_Presplit(enow, b, bhi, blo, product1, product0);
-    Two_Sum(Q, product0, sum, hh);
-    if (hh != 0) {
-      h[hindex++] = hh;
-    }
-    Fast_Two_Sum(product1, sum, Q, hh);
-    if (hh != 0) {
-      h[hindex++] = hh;
-    }
-  }
-  if ((Q != 0.0) || (hindex == 0)) {
-    h[hindex++] = Q;
-  }
-  return hindex;
-}
-
-/*****************************************************************************/
-/*                                                                           */
-/*  estimate()   Produce a one-word estimate of an expansion's value.        */
-/*                                                                           */
-/*  See my Robust Predicates paper for details.                              */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef ANSI_DECLARATORS
-REAL estimate(int elen, REAL *e)
-#else /* not ANSI_DECLARATORS */
-REAL estimate(elen, e)
-int elen;
-REAL *e;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  REAL Q;
-  int eindex;
-
-  Q = e[0];
-  for (eindex = 1; eindex < elen; eindex++) {
-    Q += e[eindex];
-  }
-  return Q;
-}
-
-/*****************************************************************************/
-/*                                                                           */
-/*  counterclockwise()   Return a positive value if the points pa, pb, and   */
-/*                       pc occur in counterclockwise order; a negative      */
-/*                       value if they occur in clockwise order; and zero    */
-/*                       if they are collinear.  The result is also a rough  */
-/*                       approximation of twice the signed area of the       */
-/*                       triangle defined by the three points.               */
-/*                                                                           */
-/*  Uses exact arithmetic if necessary to ensure a correct answer.  The      */
-/*  result returned is the determinant of a matrix.  This determinant is     */
-/*  computed adaptively, in the sense that exact arithmetic is used only to  */
-/*  the degree it is needed to ensure that the returned value has the        */
-/*  correct sign.  Hence, this function is usually quite fast, but will run  */
-/*  more slowly when the input points are collinear or nearly so.            */
-/*                                                                           */
-/*  See my Robust Predicates paper for details.                              */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef ANSI_DECLARATORS
-REAL counterclockwiseadapt(vertex pa, vertex pb, vertex pc, REAL detsum)
-#else /* not ANSI_DECLARATORS */
-REAL counterclockwiseadapt(pa, pb, pc, detsum)
-vertex pa;
-vertex pb;
-vertex pc;
-REAL detsum;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  INEXACT REAL acx, acy, bcx, bcy;
-  REAL acxtail, acytail, bcxtail, bcytail;
-  INEXACT REAL detleft, detright;
-  REAL detlefttail, detrighttail;
-  REAL det, errbound;
-  REAL B[4], C1[8], C2[12], D[16];
-  INEXACT REAL B3;
-  int C1length, C2length, Dlength;
-  REAL u[4];
-  INEXACT REAL u3;
-  INEXACT REAL s1, t1;
-  REAL s0, t0;
-
-  INEXACT REAL bvirt;
-  REAL avirt, bround, around;
-  INEXACT REAL c;
-  INEXACT REAL abig;
-  REAL ahi, alo, bhi, blo;
-  REAL err1, err2, err3;
-  INEXACT REAL _i, _j;
-  REAL _0;
-
-  acx = (REAL) (pa[0] - pc[0]);
-  bcx = (REAL) (pb[0] - pc[0]);
-  acy = (REAL) (pa[1] - pc[1]);
-  bcy = (REAL) (pb[1] - pc[1]);
-
-  Two_Product(acx, bcy, detleft, detlefttail);
-  Two_Product(acy, bcx, detright, detrighttail);
-
-  Two_Two_Diff(detleft, detlefttail, detright, detrighttail,
-               B3, B[2], B[1], B[0]);
-  B[3] = B3;
-
-  det = estimate(4, B);
-  errbound = ccwerrboundB * detsum;
-  if ((det >= errbound) || (-det >= errbound)) {
-    return det;
-  }
-
-  Two_Diff_Tail(pa[0], pc[0], acx, acxtail);
-  Two_Diff_Tail(pb[0], pc[0], bcx, bcxtail);
-  Two_Diff_Tail(pa[1], pc[1], acy, acytail);
-  Two_Diff_Tail(pb[1], pc[1], bcy, bcytail);
-
-  if ((acxtail == 0.0) && (acytail == 0.0)
-      && (bcxtail == 0.0) && (bcytail == 0.0)) {
-    return det;
-  }
-
-  errbound = ccwerrboundC * detsum + resulterrbound * Absolute(det);
-  det += (acx * bcytail + bcy * acxtail)
-       - (acy * bcxtail + bcx * acytail);
-  if ((det >= errbound) || (-det >= errbound)) {
-    return det;
-  }
-
-  Two_Product(acxtail, bcy, s1, s0);
-  Two_Product(acytail, bcx, t1, t0);
-  Two_Two_Diff(s1, s0, t1, t0, u3, u[2], u[1], u[0]);
-  u[3] = u3;
-  C1length = fast_expansion_sum_zeroelim(4, B, 4, u, C1);
-
-  Two_Product(acx, bcytail, s1, s0);
-  Two_Product(acy, bcxtail, t1, t0);
-  Two_Two_Diff(s1, s0, t1, t0, u3, u[2], u[1], u[0]);
-  u[3] = u3;
-  C2length = fast_expansion_sum_zeroelim(C1length, C1, 4, u, C2);
-
-  Two_Product(acxtail, bcytail, s1, s0);
-  Two_Product(acytail, bcxtail, t1, t0);
-  Two_Two_Diff(s1, s0, t1, t0, u3, u[2], u[1], u[0]);
-  u[3] = u3;
-  Dlength = fast_expansion_sum_zeroelim(C2length, C2, 4, u, D);
-
-  return(D[Dlength - 1]);
-}
-
-#ifdef ANSI_DECLARATORS
-REAL counterclockwise(struct mesh *m, struct behavior *b,
-                      vertex pa, vertex pb, vertex pc)
-#else /* not ANSI_DECLARATORS */
-REAL counterclockwise(m, b, pa, pb, pc)
-struct mesh *m;
-struct behavior *b;
-vertex pa;
-vertex pb;
-vertex pc;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  REAL detleft, detright, det;
-  REAL detsum, errbound;
-
-  m->counterclockcount++;
-
-  detleft = (pa[0] - pc[0]) * (pb[1] - pc[1]);
-  detright = (pa[1] - pc[1]) * (pb[0] - pc[0]);
-  det = detleft - detright;
-
-  if (b->noexact) {
-    return det;
-  }
-
-  if (detleft > 0.0) {
-    if (detright <= 0.0) {
-      return det;
-    } else {
-      detsum = detleft + detright;
-    }
-  } else if (detleft < 0.0) {
-    if (detright >= 0.0) {
-      return det;
-    } else {
-      detsum = -detleft - detright;
-    }
-  } else {
-    return det;
-  }
-
-  errbound = ccwerrboundA * detsum;
-  if ((det >= errbound) || (-det >= errbound)) {
-    return det;
-  }
-
-  return counterclockwiseadapt(pa, pb, pc, detsum);
-}
-
-/*****************************************************************************/
-/*                                                                           */
-/*  incircle()   Return a positive value if the point pd lies inside the     */
-/*               circle passing through pa, pb, and pc; a negative value if  */
-/*               it lies outside; and zero if the four points are cocircular.*/
-/*               The points pa, pb, and pc must be in counterclockwise       */
-/*               order, or the sign of the result will be reversed.          */
-/*                                                                           */
-/*  Uses exact arithmetic if necessary to ensure a correct answer.  The      */
-/*  result returned is the determinant of a matrix.  This determinant is     */
-/*  computed adaptively, in the sense that exact arithmetic is used only to  */
-/*  the degree it is needed to ensure that the returned value has the        */
-/*  correct sign.  Hence, this function is usually quite fast, but will run  */
-/*  more slowly when the input points are cocircular or nearly so.           */
-/*                                                                           */
-/*  See my Robust Predicates paper for details.                              */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef ANSI_DECLARATORS
-REAL incircleadapt(vertex pa, vertex pb, vertex pc, vertex pd, REAL permanent)
-#else /* not ANSI_DECLARATORS */
-REAL incircleadapt(pa, pb, pc, pd, permanent)
-vertex pa;
-vertex pb;
-vertex pc;
-vertex pd;
-REAL permanent;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  INEXACT REAL adx, bdx, cdx, ady, bdy, cdy;
-  REAL det, errbound;
-
-  INEXACT REAL bdxcdy1, cdxbdy1, cdxady1, adxcdy1, adxbdy1, bdxady1;
-  REAL bdxcdy0, cdxbdy0, cdxady0, adxcdy0, adxbdy0, bdxady0;
-  REAL bc[4], ca[4], ab[4];
-  INEXACT REAL bc3, ca3, ab3;
-  REAL axbc[8], axxbc[16], aybc[8], ayybc[16], adet[32];
-  int axbclen, axxbclen, aybclen, ayybclen, alen;
-  REAL bxca[8], bxxca[16], byca[8], byyca[16], bdet[32];
-  int bxcalen, bxxcalen, bycalen, byycalen, blen;
-  REAL cxab[8], cxxab[16], cyab[8], cyyab[16], cdet[32];
-  int cxablen, cxxablen, cyablen, cyyablen, clen;
-  REAL abdet[64];
-  int ablen;
-  REAL fin1[1152], fin2[1152];
-  REAL *finnow, *finother, *finswap;
-  int finlength;
-
-  REAL adxtail, bdxtail, cdxtail, adytail, bdytail, cdytail;
-  INEXACT REAL adxadx1, adyady1, bdxbdx1, bdybdy1, cdxcdx1, cdycdy1;
-  REAL adxadx0, adyady0, bdxbdx0, bdybdy0, cdxcdx0, cdycdy0;
-  REAL aa[4], bb[4], cc[4];
-  INEXACT REAL aa3, bb3, cc3;
-  INEXACT REAL ti1, tj1;
-  REAL ti0, tj0;
-  REAL u[4], v[4];
-  INEXACT REAL u3, v3;
-  REAL temp8[8], temp16a[16], temp16b[16], temp16c[16];
-  REAL temp32a[32], temp32b[32], temp48[48], temp64[64];
-  int temp8len, temp16alen, temp16blen, temp16clen;
-  int temp32alen, temp32blen, temp48len, temp64len;
-  REAL axtbb[8], axtcc[8], aytbb[8], aytcc[8];
-  int axtbblen, axtcclen, aytbblen, aytcclen;
-  REAL bxtaa[8], bxtcc[8], bytaa[8], bytcc[8];
-  int bxtaalen, bxtcclen, bytaalen, bytcclen;
-  REAL cxtaa[8], cxtbb[8], cytaa[8], cytbb[8];
-  int cxtaalen, cxtbblen, cytaalen, cytbblen;
-  REAL axtbc[8], aytbc[8], bxtca[8], bytca[8], cxtab[8], cytab[8];
-  int axtbclen = 0, aytbclen = 0, bxtcalen = 0, bytcalen = 0, cxtablen = 0, cytablen = 0;
-  REAL axtbct[16], aytbct[16], bxtcat[16], bytcat[16], cxtabt[16], cytabt[16];
-  int axtbctlen, aytbctlen, bxtcatlen, bytcatlen, cxtabtlen, cytabtlen;
-  REAL axtbctt[8], aytbctt[8], bxtcatt[8];
-  REAL bytcatt[8], cxtabtt[8], cytabtt[8];
-  int axtbcttlen, aytbcttlen, bxtcattlen, bytcattlen, cxtabttlen, cytabttlen;
-  REAL abt[8], bct[8], cat[8];
-  int abtlen, bctlen, catlen;
-  REAL abtt[4], bctt[4], catt[4];
-  int abttlen, bcttlen, cattlen;
-  INEXACT REAL abtt3, bctt3, catt3;
-  REAL negate;
-
-  INEXACT REAL bvirt;
-  REAL avirt, bround, around;
-  INEXACT REAL c;
-  INEXACT REAL abig;
-  REAL ahi, alo, bhi, blo;
-  REAL err1, err2, err3;
-  INEXACT REAL _i, _j;
-  REAL _0;
-
-  adx = (REAL) (pa[0] - pd[0]);
-  bdx = (REAL) (pb[0] - pd[0]);
-  cdx = (REAL) (pc[0] - pd[0]);
-  ady = (REAL) (pa[1] - pd[1]);
-  bdy = (REAL) (pb[1] - pd[1]);
-  cdy = (REAL) (pc[1] - pd[1]);
-
-  Two_Product(bdx, cdy, bdxcdy1, bdxcdy0);
-  Two_Product(cdx, bdy, cdxbdy1, cdxbdy0);
-  Two_Two_Diff(bdxcdy1, bdxcdy0, cdxbdy1, cdxbdy0, bc3, bc[2], bc[1], bc[0]);
-  bc[3] = bc3;
-  axbclen = scale_expansion_zeroelim(4, bc, adx, axbc);
-  axxbclen = scale_expansion_zeroelim(axbclen, axbc, adx, axxbc);
-  aybclen = scale_expansion_zeroelim(4, bc, ady, aybc);
-  ayybclen = scale_expansion_zeroelim(aybclen, aybc, ady, ayybc);
-  alen = fast_expansion_sum_zeroelim(axxbclen, axxbc, ayybclen, ayybc, adet);
-
-  Two_Product(cdx, ady, cdxady1, cdxady0);
-  Two_Product(adx, cdy, adxcdy1, adxcdy0);
-  Two_Two_Diff(cdxady1, cdxady0, adxcdy1, adxcdy0, ca3, ca[2], ca[1], ca[0]);
-  ca[3] = ca3;
-  bxcalen = scale_expansion_zeroelim(4, ca, bdx, bxca);
-  bxxcalen = scale_expansion_zeroelim(bxcalen, bxca, bdx, bxxca);
-  bycalen = scale_expansion_zeroelim(4, ca, bdy, byca);
-  byycalen = scale_expansion_zeroelim(bycalen, byca, bdy, byyca);
-  blen = fast_expansion_sum_zeroelim(bxxcalen, bxxca, byycalen, byyca, bdet);
-
-  Two_Product(adx, bdy, adxbdy1, adxbdy0);
-  Two_Product(bdx, ady, bdxady1, bdxady0);
-  Two_Two_Diff(adxbdy1, adxbdy0, bdxady1, bdxady0, ab3, ab[2], ab[1], ab[0]);
-  ab[3] = ab3;
-  cxablen = scale_expansion_zeroelim(4, ab, cdx, cxab);
-  cxxablen = scale_expansion_zeroelim(cxablen, cxab, cdx, cxxab);
-  cyablen = scale_expansion_zeroelim(4, ab, cdy, cyab);
-  cyyablen = scale_expansion_zeroelim(cyablen, cyab, cdy, cyyab);
-  clen = fast_expansion_sum_zeroelim(cxxablen, cxxab, cyyablen, cyyab, cdet);
-
-  ablen = fast_expansion_sum_zeroelim(alen, adet, blen, bdet, abdet);
-  finlength = fast_expansion_sum_zeroelim(ablen, abdet, clen, cdet, fin1);
-
-  det = estimate(finlength, fin1);
-  errbound = iccerrboundB * permanent;
-  if ((det >= errbound) || (-det >= errbound)) {
-    return det;
-  }
-
-  Two_Diff_Tail(pa[0], pd[0], adx, adxtail);
-  Two_Diff_Tail(pa[1], pd[1], ady, adytail);
-  Two_Diff_Tail(pb[0], pd[0], bdx, bdxtail);
-  Two_Diff_Tail(pb[1], pd[1], bdy, bdytail);
-  Two_Diff_Tail(pc[0], pd[0], cdx, cdxtail);
-  Two_Diff_Tail(pc[1], pd[1], cdy, cdytail);
-  if ((adxtail == 0.0) && (bdxtail == 0.0) && (cdxtail == 0.0)
-      && (adytail == 0.0) && (bdytail == 0.0) && (cdytail == 0.0)) {
-    return det;
-  }
-
-  errbound = iccerrboundC * permanent + resulterrbound * Absolute(det);
-  det += ((adx * adx + ady * ady) * ((bdx * cdytail + cdy * bdxtail)
-                                     - (bdy * cdxtail + cdx * bdytail))
-          + 2.0 * (adx * adxtail + ady * adytail) * (bdx * cdy - bdy * cdx))
-       + ((bdx * bdx + bdy * bdy) * ((cdx * adytail + ady * cdxtail)
-                                     - (cdy * adxtail + adx * cdytail))
-          + 2.0 * (bdx * bdxtail + bdy * bdytail) * (cdx * ady - cdy * adx))
-       + ((cdx * cdx + cdy * cdy) * ((adx * bdytail + bdy * adxtail)
-                                     - (ady * bdxtail + bdx * adytail))
-          + 2.0 * (cdx * cdxtail + cdy * cdytail) * (adx * bdy - ady * bdx));
-  if ((det >= errbound) || (-det >= errbound)) {
-    return det;
-  }
-
-  finnow = fin1;
-  finother = fin2;
-
-  if ((bdxtail != 0.0) || (bdytail != 0.0)
-      || (cdxtail != 0.0) || (cdytail != 0.0)) {
-    Square(adx, adxadx1, adxadx0);
-    Square(ady, adyady1, adyady0);
-    Two_Two_Sum(adxadx1, adxadx0, adyady1, adyady0, aa3, aa[2], aa[1], aa[0]);
-    aa[3] = aa3;
-  }
-  if ((cdxtail != 0.0) || (cdytail != 0.0)
-      || (adxtail != 0.0) || (adytail != 0.0)) {
-    Square(bdx, bdxbdx1, bdxbdx0);
-    Square(bdy, bdybdy1, bdybdy0);
-    Two_Two_Sum(bdxbdx1, bdxbdx0, bdybdy1, bdybdy0, bb3, bb[2], bb[1], bb[0]);
-    bb[3] = bb3;
-  }
-  if ((adxtail != 0.0) || (adytail != 0.0)
-      || (bdxtail != 0.0) || (bdytail != 0.0)) {
-    Square(cdx, cdxcdx1, cdxcdx0);
-    Square(cdy, cdycdy1, cdycdy0);
-    Two_Two_Sum(cdxcdx1, cdxcdx0, cdycdy1, cdycdy0, cc3, cc[2], cc[1], cc[0]);
-    cc[3] = cc3;
-  }
-
-  if (adxtail != 0.0) {
-    axtbclen = scale_expansion_zeroelim(4, bc, adxtail, axtbc);
-    temp16alen = scale_expansion_zeroelim(axtbclen, axtbc, 2.0 * adx,
-                                          temp16a);
-
-    axtcclen = scale_expansion_zeroelim(4, cc, adxtail, axtcc);
-    temp16blen = scale_expansion_zeroelim(axtcclen, axtcc, bdy, temp16b);
-
-    axtbblen = scale_expansion_zeroelim(4, bb, adxtail, axtbb);
-    temp16clen = scale_expansion_zeroelim(axtbblen, axtbb, -cdy, temp16c);
-
-    temp32alen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
-                                            temp16blen, temp16b, temp32a);
-    temp48len = fast_expansion_sum_zeroelim(temp16clen, temp16c,
-                                            temp32alen, temp32a, temp48);
-    finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
-                                            temp48, finother);
-    finswap = finnow; finnow = finother; finother = finswap;
-  }
-  if (adytail != 0.0) {
-    aytbclen = scale_expansion_zeroelim(4, bc, adytail, aytbc);
-    temp16alen = scale_expansion_zeroelim(aytbclen, aytbc, 2.0 * ady,
-                                          temp16a);
-
-    aytbblen = scale_expansion_zeroelim(4, bb, adytail, aytbb);
-    temp16blen = scale_expansion_zeroelim(aytbblen, aytbb, cdx, temp16b);
-
-    aytcclen = scale_expansion_zeroelim(4, cc, adytail, aytcc);
-    temp16clen = scale_expansion_zeroelim(aytcclen, aytcc, -bdx, temp16c);
-
-    temp32alen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
-                                            temp16blen, temp16b, temp32a);
-    temp48len = fast_expansion_sum_zeroelim(temp16clen, temp16c,
-                                            temp32alen, temp32a, temp48);
-    finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
-                                            temp48, finother);
-    finswap = finnow; finnow = finother; finother = finswap;
-  }
-  if (bdxtail != 0.0) {
-    bxtcalen = scale_expansion_zeroelim(4, ca, bdxtail, bxtca);
-    temp16alen = scale_expansion_zeroelim(bxtcalen, bxtca, 2.0 * bdx,
-                                          temp16a);
-
-    bxtaalen = scale_expansion_zeroelim(4, aa, bdxtail, bxtaa);
-    temp16blen = scale_expansion_zeroelim(bxtaalen, bxtaa, cdy, temp16b);
-
-    bxtcclen = scale_expansion_zeroelim(4, cc, bdxtail, bxtcc);
-    temp16clen = scale_expansion_zeroelim(bxtcclen, bxtcc, -ady, temp16c);
-
-    temp32alen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
-                                            temp16blen, temp16b, temp32a);
-    temp48len = fast_expansion_sum_zeroelim(temp16clen, temp16c,
-                                            temp32alen, temp32a, temp48);
-    finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
-                                            temp48, finother);
-    finswap = finnow; finnow = finother; finother = finswap;
-  }
-  if (bdytail != 0.0) {
-    bytcalen = scale_expansion_zeroelim(4, ca, bdytail, bytca);
-    temp16alen = scale_expansion_zeroelim(bytcalen, bytca, 2.0 * bdy,
-                                          temp16a);
-
-    bytcclen = scale_expansion_zeroelim(4, cc, bdytail, bytcc);
-    temp16blen = scale_expansion_zeroelim(bytcclen, bytcc, adx, temp16b);
-
-    bytaalen = scale_expansion_zeroelim(4, aa, bdytail, bytaa);
-    temp16clen = scale_expansion_zeroelim(bytaalen, bytaa, -cdx, temp16c);
-
-    temp32alen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
-                                            temp16blen, temp16b, temp32a);
-    temp48len = fast_expansion_sum_zeroelim(temp16clen, temp16c,
-                                            temp32alen, temp32a, temp48);
-    finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
-                                            temp48, finother);
-    finswap = finnow; finnow = finother; finother = finswap;
-  }
-  if (cdxtail != 0.0) {
-    cxtablen = scale_expansion_zeroelim(4, ab, cdxtail, cxtab);
-    temp16alen = scale_expansion_zeroelim(cxtablen, cxtab, 2.0 * cdx,
-                                          temp16a);
-
-    cxtbblen = scale_expansion_zeroelim(4, bb, cdxtail, cxtbb);
-    temp16blen = scale_expansion_zeroelim(cxtbblen, cxtbb, ady, temp16b);
-
-    cxtaalen = scale_expansion_zeroelim(4, aa, cdxtail, cxtaa);
-    temp16clen = scale_expansion_zeroelim(cxtaalen, cxtaa, -bdy, temp16c);
-
-    temp32alen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
-                                            temp16blen, temp16b, temp32a);
-    temp48len = fast_expansion_sum_zeroelim(temp16clen, temp16c,
-                                            temp32alen, temp32a, temp48);
-    finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
-                                            temp48, finother);
-    finswap = finnow; finnow = finother; finother = finswap;
-  }
-  if (cdytail != 0.0) {
-    cytablen = scale_expansion_zeroelim(4, ab, cdytail, cytab);
-    temp16alen = scale_expansion_zeroelim(cytablen, cytab, 2.0 * cdy,
-                                          temp16a);
-
-    cytaalen = scale_expansion_zeroelim(4, aa, cdytail, cytaa);
-    temp16blen = scale_expansion_zeroelim(cytaalen, cytaa, bdx, temp16b);
-
-    cytbblen = scale_expansion_zeroelim(4, bb, cdytail, cytbb);
-    temp16clen = scale_expansion_zeroelim(cytbblen, cytbb, -adx, temp16c);
-
-    temp32alen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
-                                            temp16blen, temp16b, temp32a);
-    temp48len = fast_expansion_sum_zeroelim(temp16clen, temp16c,
-                                            temp32alen, temp32a, temp48);
-    finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
-                                            temp48, finother);
-    finswap = finnow; finnow = finother; finother = finswap;
-  }
-
-  if ((adxtail != 0.0) || (adytail != 0.0)) {
-    if ((bdxtail != 0.0) || (bdytail != 0.0)
-        || (cdxtail != 0.0) || (cdytail != 0.0)) {
-      Two_Product(bdxtail, cdy, ti1, ti0);
-      Two_Product(bdx, cdytail, tj1, tj0);
-      Two_Two_Sum(ti1, ti0, tj1, tj0, u3, u[2], u[1], u[0]);
-      u[3] = u3;
-      negate = -bdy;
-      Two_Product(cdxtail, negate, ti1, ti0);
-      negate = -bdytail;
-      Two_Product(cdx, negate, tj1, tj0);
-      Two_Two_Sum(ti1, ti0, tj1, tj0, v3, v[2], v[1], v[0]);
-      v[3] = v3;
-      bctlen = fast_expansion_sum_zeroelim(4, u, 4, v, bct);
-
-      Two_Product(bdxtail, cdytail, ti1, ti0);
-      Two_Product(cdxtail, bdytail, tj1, tj0);
-      Two_Two_Diff(ti1, ti0, tj1, tj0, bctt3, bctt[2], bctt[1], bctt[0]);
-      bctt[3] = bctt3;
-      bcttlen = 4;
-    } else {
-      bct[0] = 0.0;
-      bctlen = 1;
-      bctt[0] = 0.0;
-      bcttlen = 1;
-    }
-
-    if (adxtail != 0.0) {
-      temp16alen = scale_expansion_zeroelim(axtbclen, axtbc, adxtail, temp16a);
-      axtbctlen = scale_expansion_zeroelim(bctlen, bct, adxtail, axtbct);
-      temp32alen = scale_expansion_zeroelim(axtbctlen, axtbct, 2.0 * adx,
-                                            temp32a);
-      temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a,
-                                              temp32alen, temp32a, temp48);
-      finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
-                                              temp48, finother);
-      finswap = finnow; finnow = finother; finother = finswap;
-      if (bdytail != 0.0) {
-        temp8len = scale_expansion_zeroelim(4, cc, adxtail, temp8);
-        temp16alen = scale_expansion_zeroelim(temp8len, temp8, bdytail,
-                                              temp16a);
-        finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen,
-                                                temp16a, finother);
-        finswap = finnow; finnow = finother; finother = finswap;
-      }
-      if (cdytail != 0.0) {
-        temp8len = scale_expansion_zeroelim(4, bb, -adxtail, temp8);
-        temp16alen = scale_expansion_zeroelim(temp8len, temp8, cdytail,
-                                              temp16a);
-        finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen,
-                                                temp16a, finother);
-        finswap = finnow; finnow = finother; finother = finswap;
-      }
-
-      temp32alen = scale_expansion_zeroelim(axtbctlen, axtbct, adxtail,
-                                            temp32a);
-      axtbcttlen = scale_expansion_zeroelim(bcttlen, bctt, adxtail, axtbctt);
-      temp16alen = scale_expansion_zeroelim(axtbcttlen, axtbctt, 2.0 * adx,
-                                            temp16a);
-      temp16blen = scale_expansion_zeroelim(axtbcttlen, axtbctt, adxtail,
-                                            temp16b);
-      temp32blen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
-                                              temp16blen, temp16b, temp32b);
-      temp64len = fast_expansion_sum_zeroelim(temp32alen, temp32a,
-                                              temp32blen, temp32b, temp64);
-      finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp64len,
-                                              temp64, finother);
-      finswap = finnow; finnow = finother; finother = finswap;
-    }
-    if (adytail != 0.0) {
-      temp16alen = scale_expansion_zeroelim(aytbclen, aytbc, adytail, temp16a);
-      aytbctlen = scale_expansion_zeroelim(bctlen, bct, adytail, aytbct);
-      temp32alen = scale_expansion_zeroelim(aytbctlen, aytbct, 2.0 * ady,
-                                            temp32a);
-      temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a,
-                                              temp32alen, temp32a, temp48);
-      finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
-                                              temp48, finother);
-      finswap = finnow; finnow = finother; finother = finswap;
-
-
-      temp32alen = scale_expansion_zeroelim(aytbctlen, aytbct, adytail,
-                                            temp32a);
-      aytbcttlen = scale_expansion_zeroelim(bcttlen, bctt, adytail, aytbctt);
-      temp16alen = scale_expansion_zeroelim(aytbcttlen, aytbctt, 2.0 * ady,
-                                            temp16a);
-      temp16blen = scale_expansion_zeroelim(aytbcttlen, aytbctt, adytail,
-                                            temp16b);
-      temp32blen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
-                                              temp16blen, temp16b, temp32b);
-      temp64len = fast_expansion_sum_zeroelim(temp32alen, temp32a,
-                                              temp32blen, temp32b, temp64);
-      finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp64len,
-                                              temp64, finother);
-      finswap = finnow; finnow = finother; finother = finswap;
-    }
-  }
-  if ((bdxtail != 0.0) || (bdytail != 0.0)) {
-    if ((cdxtail != 0.0) || (cdytail != 0.0)
-        || (adxtail != 0.0) || (adytail != 0.0)) {
-      Two_Product(cdxtail, ady, ti1, ti0);
-      Two_Product(cdx, adytail, tj1, tj0);
-      Two_Two_Sum(ti1, ti0, tj1, tj0, u3, u[2], u[1], u[0]);
-      u[3] = u3;
-      negate = -cdy;
-      Two_Product(adxtail, negate, ti1, ti0);
-      negate = -cdytail;
-      Two_Product(adx, negate, tj1, tj0);
-      Two_Two_Sum(ti1, ti0, tj1, tj0, v3, v[2], v[1], v[0]);
-      v[3] = v3;
-      catlen = fast_expansion_sum_zeroelim(4, u, 4, v, cat);
-
-      Two_Product(cdxtail, adytail, ti1, ti0);
-      Two_Product(adxtail, cdytail, tj1, tj0);
-      Two_Two_Diff(ti1, ti0, tj1, tj0, catt3, catt[2], catt[1], catt[0]);
-      catt[3] = catt3;
-      cattlen = 4;
-    } else {
-      cat[0] = 0.0;
-      catlen = 1;
-      catt[0] = 0.0;
-      cattlen = 1;
-    }
-
-    if (bdxtail != 0.0) {
-      temp16alen = scale_expansion_zeroelim(bxtcalen, bxtca, bdxtail, temp16a);
-      bxtcatlen = scale_expansion_zeroelim(catlen, cat, bdxtail, bxtcat);
-      temp32alen = scale_expansion_zeroelim(bxtcatlen, bxtcat, 2.0 * bdx,
-                                            temp32a);
-      temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a,
-                                              temp32alen, temp32a, temp48);
-      finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
-                                              temp48, finother);
-      finswap = finnow; finnow = finother; finother = finswap;
-      if (cdytail != 0.0) {
-        temp8len = scale_expansion_zeroelim(4, aa, bdxtail, temp8);
-        temp16alen = scale_expansion_zeroelim(temp8len, temp8, cdytail,
-                                              temp16a);
-        finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen,
-                                                temp16a, finother);
-        finswap = finnow; finnow = finother; finother = finswap;
-      }
-      if (adytail != 0.0) {
-        temp8len = scale_expansion_zeroelim(4, cc, -bdxtail, temp8);
-        temp16alen = scale_expansion_zeroelim(temp8len, temp8, adytail,
-                                              temp16a);
-        finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen,
-                                                temp16a, finother);
-        finswap = finnow; finnow = finother; finother = finswap;
-      }
-
-      temp32alen = scale_expansion_zeroelim(bxtcatlen, bxtcat, bdxtail,
-                                            temp32a);
-      bxtcattlen = scale_expansion_zeroelim(cattlen, catt, bdxtail, bxtcatt);
-      temp16alen = scale_expansion_zeroelim(bxtcattlen, bxtcatt, 2.0 * bdx,
-                                            temp16a);
-      temp16blen = scale_expansion_zeroelim(bxtcattlen, bxtcatt, bdxtail,
-                                            temp16b);
-      temp32blen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
-                                              temp16blen, temp16b, temp32b);
-      temp64len = fast_expansion_sum_zeroelim(temp32alen, temp32a,
-                                              temp32blen, temp32b, temp64);
-      finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp64len,
-                                              temp64, finother);
-      finswap = finnow; finnow = finother; finother = finswap;
-    }
-    if (bdytail != 0.0) {
-      temp16alen = scale_expansion_zeroelim(bytcalen, bytca, bdytail, temp16a);
-      bytcatlen = scale_expansion_zeroelim(catlen, cat, bdytail, bytcat);
-      temp32alen = scale_expansion_zeroelim(bytcatlen, bytcat, 2.0 * bdy,
-                                            temp32a);
-      temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a,
-                                              temp32alen, temp32a, temp48);
-      finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
-                                              temp48, finother);
-      finswap = finnow; finnow = finother; finother = finswap;
-
-
-      temp32alen = scale_expansion_zeroelim(bytcatlen, bytcat, bdytail,
-                                            temp32a);
-      bytcattlen = scale_expansion_zeroelim(cattlen, catt, bdytail, bytcatt);
-      temp16alen = scale_expansion_zeroelim(bytcattlen, bytcatt, 2.0 * bdy,
-                                            temp16a);
-      temp16blen = scale_expansion_zeroelim(bytcattlen, bytcatt, bdytail,
-                                            temp16b);
-      temp32blen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
-                                              temp16blen, temp16b, temp32b);
-      temp64len = fast_expansion_sum_zeroelim(temp32alen, temp32a,
-                                              temp32blen, temp32b, temp64);
-      finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp64len,
-                                              temp64, finother);
-      finswap = finnow; finnow = finother; finother = finswap;
-    }
-  }
-  if ((cdxtail != 0.0) || (cdytail != 0.0)) {
-    if ((adxtail != 0.0) || (adytail != 0.0)
-        || (bdxtail != 0.0) || (bdytail != 0.0)) {
-      Two_Product(adxtail, bdy, ti1, ti0);
-      Two_Product(adx, bdytail, tj1, tj0);
-      Two_Two_Sum(ti1, ti0, tj1, tj0, u3, u[2], u[1], u[0]);
-      u[3] = u3;
-      negate = -ady;
-      Two_Product(bdxtail, negate, ti1, ti0);
-      negate = -adytail;
-      Two_Product(bdx, negate, tj1, tj0);
-      Two_Two_Sum(ti1, ti0, tj1, tj0, v3, v[2], v[1], v[0]);
-      v[3] = v3;
-      abtlen = fast_expansion_sum_zeroelim(4, u, 4, v, abt);
-
-      Two_Product(adxtail, bdytail, ti1, ti0);
-      Two_Product(bdxtail, adytail, tj1, tj0);
-      Two_Two_Diff(ti1, ti0, tj1, tj0, abtt3, abtt[2], abtt[1], abtt[0]);
-      abtt[3] = abtt3;
-      abttlen = 4;
-    } else {
-      abt[0] = 0.0;
-      abtlen = 1;
-      abtt[0] = 0.0;
-      abttlen = 1;
-    }
-
-    if (cdxtail != 0.0) {
-      temp16alen = scale_expansion_zeroelim(cxtablen, cxtab, cdxtail, temp16a);
-      cxtabtlen = scale_expansion_zeroelim(abtlen, abt, cdxtail, cxtabt);
-      temp32alen = scale_expansion_zeroelim(cxtabtlen, cxtabt, 2.0 * cdx,
-                                            temp32a);
-      temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a,
-                                              temp32alen, temp32a, temp48);
-      finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
-                                              temp48, finother);
-      finswap = finnow; finnow = finother; finother = finswap;
-      if (adytail != 0.0) {
-        temp8len = scale_expansion_zeroelim(4, bb, cdxtail, temp8);
-        temp16alen = scale_expansion_zeroelim(temp8len, temp8, adytail,
-                                              temp16a);
-        finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen,
-                                                temp16a, finother);
-        finswap = finnow; finnow = finother; finother = finswap;
-      }
-      if (bdytail != 0.0) {
-        temp8len = scale_expansion_zeroelim(4, aa, -cdxtail, temp8);
-        temp16alen = scale_expansion_zeroelim(temp8len, temp8, bdytail,
-                                              temp16a);
-        finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen,
-                                                temp16a, finother);
-        finswap = finnow; finnow = finother; finother = finswap;
-      }
-
-      temp32alen = scale_expansion_zeroelim(cxtabtlen, cxtabt, cdxtail,
-                                            temp32a);
-      cxtabttlen = scale_expansion_zeroelim(abttlen, abtt, cdxtail, cxtabtt);
-      temp16alen = scale_expansion_zeroelim(cxtabttlen, cxtabtt, 2.0 * cdx,
-                                            temp16a);
-      temp16blen = scale_expansion_zeroelim(cxtabttlen, cxtabtt, cdxtail,
-                                            temp16b);
-      temp32blen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
-                                              temp16blen, temp16b, temp32b);
-      temp64len = fast_expansion_sum_zeroelim(temp32alen, temp32a,
-                                              temp32blen, temp32b, temp64);
-      finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp64len,
-                                              temp64, finother);
-      finswap = finnow; finnow = finother; finother = finswap;
-    }
-    if (cdytail != 0.0) {
-      temp16alen = scale_expansion_zeroelim(cytablen, cytab, cdytail, temp16a);
-      cytabtlen = scale_expansion_zeroelim(abtlen, abt, cdytail, cytabt);
-      temp32alen = scale_expansion_zeroelim(cytabtlen, cytabt, 2.0 * cdy,
-                                            temp32a);
-      temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a,
-                                              temp32alen, temp32a, temp48);
-      finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
-                                              temp48, finother);
-      finswap = finnow; finnow = finother; finother = finswap;
-
-
-      temp32alen = scale_expansion_zeroelim(cytabtlen, cytabt, cdytail,
-                                            temp32a);
-      cytabttlen = scale_expansion_zeroelim(abttlen, abtt, cdytail, cytabtt);
-      temp16alen = scale_expansion_zeroelim(cytabttlen, cytabtt, 2.0 * cdy,
-                                            temp16a);
-      temp16blen = scale_expansion_zeroelim(cytabttlen, cytabtt, cdytail,
-                                            temp16b);
-      temp32blen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
-                                              temp16blen, temp16b, temp32b);
-      temp64len = fast_expansion_sum_zeroelim(temp32alen, temp32a,
-                                              temp32blen, temp32b, temp64);
-      finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp64len,
-                                              temp64, finother);
-      finswap = finnow; finnow = finother; finother = finswap;
-    }
-  }
-
-  return finnow[finlength - 1];
-}
-
-#ifdef ANSI_DECLARATORS
-REAL incircle(struct mesh *m, struct behavior *b,
-              vertex pa, vertex pb, vertex pc, vertex pd)
-#else /* not ANSI_DECLARATORS */
-REAL incircle(m, b, pa, pb, pc, pd)
-struct mesh *m;
-struct behavior *b;
-vertex pa;
-vertex pb;
-vertex pc;
-vertex pd;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  REAL adx, bdx, cdx, ady, bdy, cdy;
-  REAL bdxcdy, cdxbdy, cdxady, adxcdy, adxbdy, bdxady;
-  REAL alift, blift, clift;
-  REAL det;
-  REAL permanent, errbound;
-
-  m->incirclecount++;
-
-  adx = pa[0] - pd[0];
-  bdx = pb[0] - pd[0];
-  cdx = pc[0] - pd[0];
-  ady = pa[1] - pd[1];
-  bdy = pb[1] - pd[1];
-  cdy = pc[1] - pd[1];
-
-  bdxcdy = bdx * cdy;
-  cdxbdy = cdx * bdy;
-  alift = adx * adx + ady * ady;
-
-  cdxady = cdx * ady;
-  adxcdy = adx * cdy;
-  blift = bdx * bdx + bdy * bdy;
-
-  adxbdy = adx * bdy;
-  bdxady = bdx * ady;
-  clift = cdx * cdx + cdy * cdy;
-
-  det = alift * (bdxcdy - cdxbdy)
-      + blift * (cdxady - adxcdy)
-      + clift * (adxbdy - bdxady);
-
-  if (b->noexact) {
-    return det;
-  }
-
-  permanent = (Absolute(bdxcdy) + Absolute(cdxbdy)) * alift
-            + (Absolute(cdxady) + Absolute(adxcdy)) * blift
-            + (Absolute(adxbdy) + Absolute(bdxady)) * clift;
-  errbound = iccerrboundA * permanent;
-  if ((det > errbound) || (-det > errbound)) {
-    return det;
-  }
-
-  return incircleadapt(pa, pb, pc, pd, permanent);
-}
-
-/*****************************************************************************/
-/*                                                                           */
-/*  orient3d()   Return a positive value if the point pd lies below the      */
-/*               plane passing through pa, pb, and pc; "below" is defined so */
-/*               that pa, pb, and pc appear in counterclockwise order when   */
-/*               viewed from above the plane.  Returns a negative value if   */
-/*               pd lies above the plane.  Returns zero if the points are    */
-/*               coplanar.  The result is also a rough approximation of six  */
-/*               times the signed volume of the tetrahedron defined by the   */
-/*               four points.                                                */
-/*                                                                           */
-/*  Uses exact arithmetic if necessary to ensure a correct answer.  The      */
-/*  result returned is the determinant of a matrix.  This determinant is     */
-/*  computed adaptively, in the sense that exact arithmetic is used only to  */
-/*  the degree it is needed to ensure that the returned value has the        */
-/*  correct sign.  Hence, this function is usually quite fast, but will run  */
-/*  more slowly when the input points are coplanar or nearly so.             */
-/*                                                                           */
-/*  See my Robust Predicates paper for details.                              */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef ANSI_DECLARATORS
-REAL orient3dadapt(vertex pa, vertex pb, vertex pc, vertex pd,
-                   REAL aheight, REAL bheight, REAL cheight, REAL dheight,
-                   REAL permanent)
-#else /* not ANSI_DECLARATORS */
-REAL orient3dadapt(pa, pb, pc, pd,
-                   aheight, bheight, cheight, dheight, permanent)
-vertex pa;
-vertex pb;
-vertex pc;
-vertex pd;
-REAL aheight;
-REAL bheight;
-REAL cheight;
-REAL dheight;
-REAL permanent;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  INEXACT REAL adx, bdx, cdx, ady, bdy, cdy, adheight, bdheight, cdheight;
-  REAL det, errbound;
-
-  INEXACT REAL bdxcdy1, cdxbdy1, cdxady1, adxcdy1, adxbdy1, bdxady1;
-  REAL bdxcdy0, cdxbdy0, cdxady0, adxcdy0, adxbdy0, bdxady0;
-  REAL bc[4], ca[4], ab[4];
-  INEXACT REAL bc3, ca3, ab3;
-  REAL adet[8], bdet[8], cdet[8];
-  int alen, blen, clen;
-  REAL abdet[16];
-  int ablen;
-  REAL *finnow, *finother, *finswap;
-  REAL fin1[192], fin2[192];
-  int finlength;
-
-  REAL adxtail, bdxtail, cdxtail;
-  REAL adytail, bdytail, cdytail;
-  REAL adheighttail, bdheighttail, cdheighttail;
-  INEXACT REAL at_blarge, at_clarge;
-  INEXACT REAL bt_clarge, bt_alarge;
-  INEXACT REAL ct_alarge, ct_blarge;
-  REAL at_b[4], at_c[4], bt_c[4], bt_a[4], ct_a[4], ct_b[4];
-  int at_blen, at_clen, bt_clen, bt_alen, ct_alen, ct_blen;
-  INEXACT REAL bdxt_cdy1, cdxt_bdy1, cdxt_ady1;
-  INEXACT REAL adxt_cdy1, adxt_bdy1, bdxt_ady1;
-  REAL bdxt_cdy0, cdxt_bdy0, cdxt_ady0;
-  REAL adxt_cdy0, adxt_bdy0, bdxt_ady0;
-  INEXACT REAL bdyt_cdx1, cdyt_bdx1, cdyt_adx1;
-  INEXACT REAL adyt_cdx1, adyt_bdx1, bdyt_adx1;
-  REAL bdyt_cdx0, cdyt_bdx0, cdyt_adx0;
-  REAL adyt_cdx0, adyt_bdx0, bdyt_adx0;
-  REAL bct[8], cat[8], abt[8];
-  int bctlen, catlen, abtlen;
-  INEXACT REAL bdxt_cdyt1, cdxt_bdyt1, cdxt_adyt1;
-  INEXACT REAL adxt_cdyt1, adxt_bdyt1, bdxt_adyt1;
-  REAL bdxt_cdyt0, cdxt_bdyt0, cdxt_adyt0;
-  REAL adxt_cdyt0, adxt_bdyt0, bdxt_adyt0;
-  REAL u[4], v[12], w[16];
-  INEXACT REAL u3;
-  int vlength, wlength;
-  REAL negate;
-
-  INEXACT REAL bvirt;
-  REAL avirt, bround, around;
-  INEXACT REAL c;
-  INEXACT REAL abig;
-  REAL ahi, alo, bhi, blo;
-  REAL err1, err2, err3;
-  INEXACT REAL _i, _j, _k;
-  REAL _0;
-
-  adx = (REAL) (pa[0] - pd[0]);
-  bdx = (REAL) (pb[0] - pd[0]);
-  cdx = (REAL) (pc[0] - pd[0]);
-  ady = (REAL) (pa[1] - pd[1]);
-  bdy = (REAL) (pb[1] - pd[1]);
-  cdy = (REAL) (pc[1] - pd[1]);
-  adheight = (REAL) (aheight - dheight);
-  bdheight = (REAL) (bheight - dheight);
-  cdheight = (REAL) (cheight - dheight);
-
-  Two_Product(bdx, cdy, bdxcdy1, bdxcdy0);
-  Two_Product(cdx, bdy, cdxbdy1, cdxbdy0);
-  Two_Two_Diff(bdxcdy1, bdxcdy0, cdxbdy1, cdxbdy0, bc3, bc[2], bc[1], bc[0]);
-  bc[3] = bc3;
-  alen = scale_expansion_zeroelim(4, bc, adheight, adet);
-
-  Two_Product(cdx, ady, cdxady1, cdxady0);
-  Two_Product(adx, cdy, adxcdy1, adxcdy0);
-  Two_Two_Diff(cdxady1, cdxady0, adxcdy1, adxcdy0, ca3, ca[2], ca[1], ca[0]);
-  ca[3] = ca3;
-  blen = scale_expansion_zeroelim(4, ca, bdheight, bdet);
-
-  Two_Product(adx, bdy, adxbdy1, adxbdy0);
-  Two_Product(bdx, ady, bdxady1, bdxady0);
-  Two_Two_Diff(adxbdy1, adxbdy0, bdxady1, bdxady0, ab3, ab[2], ab[1], ab[0]);
-  ab[3] = ab3;
-  clen = scale_expansion_zeroelim(4, ab, cdheight, cdet);
-
-  ablen = fast_expansion_sum_zeroelim(alen, adet, blen, bdet, abdet);
-  finlength = fast_expansion_sum_zeroelim(ablen, abdet, clen, cdet, fin1);
-
-  det = estimate(finlength, fin1);
-  errbound = o3derrboundB * permanent;
-  if ((det >= errbound) || (-det >= errbound)) {
-    return det;
-  }
-
-  Two_Diff_Tail(pa[0], pd[0], adx, adxtail);
-  Two_Diff_Tail(pb[0], pd[0], bdx, bdxtail);
-  Two_Diff_Tail(pc[0], pd[0], cdx, cdxtail);
-  Two_Diff_Tail(pa[1], pd[1], ady, adytail);
-  Two_Diff_Tail(pb[1], pd[1], bdy, bdytail);
-  Two_Diff_Tail(pc[1], pd[1], cdy, cdytail);
-  Two_Diff_Tail(aheight, dheight, adheight, adheighttail);
-  Two_Diff_Tail(bheight, dheight, bdheight, bdheighttail);
-  Two_Diff_Tail(cheight, dheight, cdheight, cdheighttail);
-
-  if ((adxtail == 0.0) && (bdxtail == 0.0) && (cdxtail == 0.0) &&
-      (adytail == 0.0) && (bdytail == 0.0) && (cdytail == 0.0) &&
-      (adheighttail == 0.0) &&
-      (bdheighttail == 0.0) &&
-      (cdheighttail == 0.0)) {
-    return det;
-  }
-
-  errbound = o3derrboundC * permanent + resulterrbound * Absolute(det);
-  det += (adheight * ((bdx * cdytail + cdy * bdxtail) -
-                      (bdy * cdxtail + cdx * bdytail)) +
-          adheighttail * (bdx * cdy - bdy * cdx)) +
-         (bdheight * ((cdx * adytail + ady * cdxtail) -
-                      (cdy * adxtail + adx * cdytail)) +
-          bdheighttail * (cdx * ady - cdy * adx)) +
-         (cdheight * ((adx * bdytail + bdy * adxtail) -
-                      (ady * bdxtail + bdx * adytail)) +
-          cdheighttail * (adx * bdy - ady * bdx));
-  if ((det >= errbound) || (-det >= errbound)) {
-    return det;
-  }
-
-  finnow = fin1;
-  finother = fin2;
-
-  if (adxtail == 0.0) {
-    if (adytail == 0.0) {
-      at_b[0] = 0.0;
-      at_blen = 1;
-      at_c[0] = 0.0;
-      at_clen = 1;
-    } else {
-      negate = -adytail;
-      Two_Product(negate, bdx, at_blarge, at_b[0]);
-      at_b[1] = at_blarge;
-      at_blen = 2;
-      Two_Product(adytail, cdx, at_clarge, at_c[0]);
-      at_c[1] = at_clarge;
-      at_clen = 2;
-    }
-  } else {
-    if (adytail == 0.0) {
-      Two_Product(adxtail, bdy, at_blarge, at_b[0]);
-      at_b[1] = at_blarge;
-      at_blen = 2;
-      negate = -adxtail;
-      Two_Product(negate, cdy, at_clarge, at_c[0]);
-      at_c[1] = at_clarge;
-      at_clen = 2;
-    } else {
-      Two_Product(adxtail, bdy, adxt_bdy1, adxt_bdy0);
-      Two_Product(adytail, bdx, adyt_bdx1, adyt_bdx0);
-      Two_Two_Diff(adxt_bdy1, adxt_bdy0, adyt_bdx1, adyt_bdx0,
-                   at_blarge, at_b[2], at_b[1], at_b[0]);
-      at_b[3] = at_blarge;
-      at_blen = 4;
-      Two_Product(adytail, cdx, adyt_cdx1, adyt_cdx0);
-      Two_Product(adxtail, cdy, adxt_cdy1, adxt_cdy0);
-      Two_Two_Diff(adyt_cdx1, adyt_cdx0, adxt_cdy1, adxt_cdy0,
-                   at_clarge, at_c[2], at_c[1], at_c[0]);
-      at_c[3] = at_clarge;
-      at_clen = 4;
-    }
-  }
-  if (bdxtail == 0.0) {
-    if (bdytail == 0.0) {
-      bt_c[0] = 0.0;
-      bt_clen = 1;
-      bt_a[0] = 0.0;
-      bt_alen = 1;
-    } else {
-      negate = -bdytail;
-      Two_Product(negate, cdx, bt_clarge, bt_c[0]);
-      bt_c[1] = bt_clarge;
-      bt_clen = 2;
-      Two_Product(bdytail, adx, bt_alarge, bt_a[0]);
-      bt_a[1] = bt_alarge;
-      bt_alen = 2;
-    }
-  } else {
-    if (bdytail == 0.0) {
-      Two_Product(bdxtail, cdy, bt_clarge, bt_c[0]);
-      bt_c[1] = bt_clarge;
-      bt_clen = 2;
-      negate = -bdxtail;
-      Two_Product(negate, ady, bt_alarge, bt_a[0]);
-      bt_a[1] = bt_alarge;
-      bt_alen = 2;
-    } else {
-      Two_Product(bdxtail, cdy, bdxt_cdy1, bdxt_cdy0);
-      Two_Product(bdytail, cdx, bdyt_cdx1, bdyt_cdx0);
-      Two_Two_Diff(bdxt_cdy1, bdxt_cdy0, bdyt_cdx1, bdyt_cdx0,
-                   bt_clarge, bt_c[2], bt_c[1], bt_c[0]);
-      bt_c[3] = bt_clarge;
-      bt_clen = 4;
-      Two_Product(bdytail, adx, bdyt_adx1, bdyt_adx0);
-      Two_Product(bdxtail, ady, bdxt_ady1, bdxt_ady0);
-      Two_Two_Diff(bdyt_adx1, bdyt_adx0, bdxt_ady1, bdxt_ady0,
-                  bt_alarge, bt_a[2], bt_a[1], bt_a[0]);
-      bt_a[3] = bt_alarge;
-      bt_alen = 4;
-    }
-  }
-  if (cdxtail == 0.0) {
-    if (cdytail == 0.0) {
-      ct_a[0] = 0.0;
-      ct_alen = 1;
-      ct_b[0] = 0.0;
-      ct_blen = 1;
-    } else {
-      negate = -cdytail;
-      Two_Product(negate, adx, ct_alarge, ct_a[0]);
-      ct_a[1] = ct_alarge;
-      ct_alen = 2;
-      Two_Product(cdytail, bdx, ct_blarge, ct_b[0]);
-      ct_b[1] = ct_blarge;
-      ct_blen = 2;
-    }
-  } else {
-    if (cdytail == 0.0) {
-      Two_Product(cdxtail, ady, ct_alarge, ct_a[0]);
-      ct_a[1] = ct_alarge;
-      ct_alen = 2;
-      negate = -cdxtail;
-      Two_Product(negate, bdy, ct_blarge, ct_b[0]);
-      ct_b[1] = ct_blarge;
-      ct_blen = 2;
-    } else {
-      Two_Product(cdxtail, ady, cdxt_ady1, cdxt_ady0);
-      Two_Product(cdytail, adx, cdyt_adx1, cdyt_adx0);
-      Two_Two_Diff(cdxt_ady1, cdxt_ady0, cdyt_adx1, cdyt_adx0,
-                   ct_alarge, ct_a[2], ct_a[1], ct_a[0]);
-      ct_a[3] = ct_alarge;
-      ct_alen = 4;
-      Two_Product(cdytail, bdx, cdyt_bdx1, cdyt_bdx0);
-      Two_Product(cdxtail, bdy, cdxt_bdy1, cdxt_bdy0);
-      Two_Two_Diff(cdyt_bdx1, cdyt_bdx0, cdxt_bdy1, cdxt_bdy0,
-                   ct_blarge, ct_b[2], ct_b[1], ct_b[0]);
-      ct_b[3] = ct_blarge;
-      ct_blen = 4;
-    }
-  }
-
-  bctlen = fast_expansion_sum_zeroelim(bt_clen, bt_c, ct_blen, ct_b, bct);
-  wlength = scale_expansion_zeroelim(bctlen, bct, adheight, w);
-  finlength = fast_expansion_sum_zeroelim(finlength, finnow, wlength, w,
-                                          finother);
-  finswap = finnow; finnow = finother; finother = finswap;
-
-  catlen = fast_expansion_sum_zeroelim(ct_alen, ct_a, at_clen, at_c, cat);
-  wlength = scale_expansion_zeroelim(catlen, cat, bdheight, w);
-  finlength = fast_expansion_sum_zeroelim(finlength, finnow, wlength, w,
-                                          finother);
-  finswap = finnow; finnow = finother; finother = finswap;
-
-  abtlen = fast_expansion_sum_zeroelim(at_blen, at_b, bt_alen, bt_a, abt);
-  wlength = scale_expansion_zeroelim(abtlen, abt, cdheight, w);
-  finlength = fast_expansion_sum_zeroelim(finlength, finnow, wlength, w,
-                                          finother);
-  finswap = finnow; finnow = finother; finother = finswap;
-
-  if (adheighttail != 0.0) {
-    vlength = scale_expansion_zeroelim(4, bc, adheighttail, v);
-    finlength = fast_expansion_sum_zeroelim(finlength, finnow, vlength, v,
-                                            finother);
-    finswap = finnow; finnow = finother; finother = finswap;
-  }
-  if (bdheighttail != 0.0) {
-    vlength = scale_expansion_zeroelim(4, ca, bdheighttail, v);
-    finlength = fast_expansion_sum_zeroelim(finlength, finnow, vlength, v,
-                                            finother);
-    finswap = finnow; finnow = finother; finother = finswap;
-  }
-  if (cdheighttail != 0.0) {
-    vlength = scale_expansion_zeroelim(4, ab, cdheighttail, v);
-    finlength = fast_expansion_sum_zeroelim(finlength, finnow, vlength, v,
-                                            finother);
-    finswap = finnow; finnow = finother; finother = finswap;
-  }
-
-  if (adxtail != 0.0) {
-    if (bdytail != 0.0) {
-      Two_Product(adxtail, bdytail, adxt_bdyt1, adxt_bdyt0);
-      Two_One_Product(adxt_bdyt1, adxt_bdyt0, cdheight, u3, u[2], u[1], u[0]);
-      u[3] = u3;
-      finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
-                                              finother);
-      finswap = finnow; finnow = finother; finother = finswap;
-      if (cdheighttail != 0.0) {
-        Two_One_Product(adxt_bdyt1, adxt_bdyt0, cdheighttail,
-                        u3, u[2], u[1], u[0]);
-        u[3] = u3;
-        finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
-                                                finother);
-        finswap = finnow; finnow = finother; finother = finswap;
-      }
-    }
-    if (cdytail != 0.0) {
-      negate = -adxtail;
-      Two_Product(negate, cdytail, adxt_cdyt1, adxt_cdyt0);
-      Two_One_Product(adxt_cdyt1, adxt_cdyt0, bdheight, u3, u[2], u[1], u[0]);
-      u[3] = u3;
-      finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
-                                              finother);
-      finswap = finnow; finnow = finother; finother = finswap;
-      if (bdheighttail != 0.0) {
-        Two_One_Product(adxt_cdyt1, adxt_cdyt0, bdheighttail,
-                        u3, u[2], u[1], u[0]);
-        u[3] = u3;
-        finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
-                                                finother);
-        finswap = finnow; finnow = finother; finother = finswap;
-      }
-    }
-  }
-  if (bdxtail != 0.0) {
-    if (cdytail != 0.0) {
-      Two_Product(bdxtail, cdytail, bdxt_cdyt1, bdxt_cdyt0);
-      Two_One_Product(bdxt_cdyt1, bdxt_cdyt0, adheight, u3, u[2], u[1], u[0]);
-      u[3] = u3;
-      finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
-                                              finother);
-      finswap = finnow; finnow = finother; finother = finswap;
-      if (adheighttail != 0.0) {
-        Two_One_Product(bdxt_cdyt1, bdxt_cdyt0, adheighttail,
-                        u3, u[2], u[1], u[0]);
-        u[3] = u3;
-        finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
-                                                finother);
-        finswap = finnow; finnow = finother; finother = finswap;
-      }
-    }
-    if (adytail != 0.0) {
-      negate = -bdxtail;
-      Two_Product(negate, adytail, bdxt_adyt1, bdxt_adyt0);
-      Two_One_Product(bdxt_adyt1, bdxt_adyt0, cdheight, u3, u[2], u[1], u[0]);
-      u[3] = u3;
-      finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
-                                              finother);
-      finswap = finnow; finnow = finother; finother = finswap;
-      if (cdheighttail != 0.0) {
-        Two_One_Product(bdxt_adyt1, bdxt_adyt0, cdheighttail,
-                        u3, u[2], u[1], u[0]);
-        u[3] = u3;
-        finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
-                                                finother);
-        finswap = finnow; finnow = finother; finother = finswap;
-      }
-    }
-  }
-  if (cdxtail != 0.0) {
-    if (adytail != 0.0) {
-      Two_Product(cdxtail, adytail, cdxt_adyt1, cdxt_adyt0);
-      Two_One_Product(cdxt_adyt1, cdxt_adyt0, bdheight, u3, u[2], u[1], u[0]);
-      u[3] = u3;
-      finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
-                                              finother);
-      finswap = finnow; finnow = finother; finother = finswap;
-      if (bdheighttail != 0.0) {
-        Two_One_Product(cdxt_adyt1, cdxt_adyt0, bdheighttail,
-                        u3, u[2], u[1], u[0]);
-        u[3] = u3;
-        finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
-                                                finother);
-        finswap = finnow; finnow = finother; finother = finswap;
-      }
-    }
-    if (bdytail != 0.0) {
-      negate = -cdxtail;
-      Two_Product(negate, bdytail, cdxt_bdyt1, cdxt_bdyt0);
-      Two_One_Product(cdxt_bdyt1, cdxt_bdyt0, adheight, u3, u[2], u[1], u[0]);
-      u[3] = u3;
-      finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
-                                              finother);
-      finswap = finnow; finnow = finother; finother = finswap;
-      if (adheighttail != 0.0) {
-        Two_One_Product(cdxt_bdyt1, cdxt_bdyt0, adheighttail,
-                        u3, u[2], u[1], u[0]);
-        u[3] = u3;
-        finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
-                                                finother);
-        finswap = finnow; finnow = finother; finother = finswap;
-      }
-    }
-  }
-
-  if (adheighttail != 0.0) {
-    wlength = scale_expansion_zeroelim(bctlen, bct, adheighttail, w);
-    finlength = fast_expansion_sum_zeroelim(finlength, finnow, wlength, w,
-                                            finother);
-    finswap = finnow; finnow = finother; finother = finswap;
-  }
-  if (bdheighttail != 0.0) {
-    wlength = scale_expansion_zeroelim(catlen, cat, bdheighttail, w);
-    finlength = fast_expansion_sum_zeroelim(finlength, finnow, wlength, w,
-                                            finother);
-    finswap = finnow; finnow = finother; finother = finswap;
-  }
-  if (cdheighttail != 0.0) {
-    wlength = scale_expansion_zeroelim(abtlen, abt, cdheighttail, w);
-    finlength = fast_expansion_sum_zeroelim(finlength, finnow, wlength, w,
-                                            finother);
-    finswap = finnow; finnow = finother; finother = finswap;
-  }
-
-  return finnow[finlength - 1];
-}
-
-#ifdef ANSI_DECLARATORS
-REAL orient3d(struct mesh *m, struct behavior *b,
-              vertex pa, vertex pb, vertex pc, vertex pd,
-              REAL aheight, REAL bheight, REAL cheight, REAL dheight)
-#else /* not ANSI_DECLARATORS */
-REAL orient3d(m, b, pa, pb, pc, pd, aheight, bheight, cheight, dheight)
-struct mesh *m;
-struct behavior *b;
-vertex pa;
-vertex pb;
-vertex pc;
-vertex pd;
-REAL aheight;
-REAL bheight;
-REAL cheight;
-REAL dheight;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  REAL adx, bdx, cdx, ady, bdy, cdy, adheight, bdheight, cdheight;
-  REAL bdxcdy, cdxbdy, cdxady, adxcdy, adxbdy, bdxady;
-  REAL det;
-  REAL permanent, errbound;
-
-  m->orient3dcount++;
-
-  adx = pa[0] - pd[0];
-  bdx = pb[0] - pd[0];
-  cdx = pc[0] - pd[0];
-  ady = pa[1] - pd[1];
-  bdy = pb[1] - pd[1];
-  cdy = pc[1] - pd[1];
-  adheight = aheight - dheight;
-  bdheight = bheight - dheight;
-  cdheight = cheight - dheight;
-
-  bdxcdy = bdx * cdy;
-  cdxbdy = cdx * bdy;
-
-  cdxady = cdx * ady;
-  adxcdy = adx * cdy;
-
-  adxbdy = adx * bdy;
-  bdxady = bdx * ady;
-
-  det = adheight * (bdxcdy - cdxbdy)
-      + bdheight * (cdxady - adxcdy)
-      + cdheight * (adxbdy - bdxady);
-
-  if (b->noexact) {
-    return det;
-  }
-
-  permanent = (Absolute(bdxcdy) + Absolute(cdxbdy)) * Absolute(adheight)
-            + (Absolute(cdxady) + Absolute(adxcdy)) * Absolute(bdheight)
-            + (Absolute(adxbdy) + Absolute(bdxady)) * Absolute(cdheight);
-  errbound = o3derrboundA * permanent;
-  if ((det > errbound) || (-det > errbound)) {
-    return det;
-  }
-
-  return orient3dadapt(pa, pb, pc, pd, aheight, bheight, cheight, dheight,
-                       permanent);
-}
-
-/*****************************************************************************/
-/*                                                                           */
-/*  nonregular()   Return a positive value if the point pd is incompatible   */
-/*                 with the circle or plane passing through pa, pb, and pc   */
-/*                 (meaning that pd is inside the circle or below the        */
-/*                 plane); a negative value if it is compatible; and zero if */
-/*                 the four points are cocircular/coplanar.  The points pa,  */
-/*                 pb, and pc must be in counterclockwise order, or the sign */
-/*                 of the result will be reversed.                           */
-/*                                                                           */
-/*  If the -w switch is used, the points are lifted onto the parabolic       */
-/*  lifting map, then they are dropped according to their weights, then the  */
-/*  3D orientation test is applied.  If the -W switch is used, the points'   */
-/*  heights are already provided, so the 3D orientation test is applied      */
-/*  directly.  If neither switch is used, the incircle test is applied.      */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef ANSI_DECLARATORS
-REAL nonregular(struct mesh *m, struct behavior *b,
-                vertex pa, vertex pb, vertex pc, vertex pd)
-#else /* not ANSI_DECLARATORS */
-REAL nonregular(m, b, pa, pb, pc, pd)
-struct mesh *m;
-struct behavior *b;
-vertex pa;
-vertex pb;
-vertex pc;
-vertex pd;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  if (b->weighted == 0) {
-    return incircle(m, b, pa, pb, pc, pd);
-  } else if (b->weighted == 1) {
-    return orient3d(m, b, pa, pb, pc, pd,
-                    pa[0] * pa[0] + pa[1] * pa[1] - pa[2],
-                    pb[0] * pb[0] + pb[1] * pb[1] - pb[2],
-                    pc[0] * pc[0] + pc[1] * pc[1] - pc[2],
-                    pd[0] * pd[0] + pd[1] * pd[1] - pd[2]);
-  } else {
-    return orient3d(m, b, pa, pb, pc, pd, pa[2], pb[2], pc[2], pd[2]);
-  }
-}
-
-/*****************************************************************************/
-/*                                                                           */
-/*  findcircumcenter()   Find the circumcenter of a triangle.                */
-/*                                                                           */
-/*  The result is returned both in terms of x-y coordinates and xi-eta       */
-/*  (barycentric) coordinates.  The xi-eta coordinate system is defined in   */
-/*  terms of the triangle:  the origin of the triangle is the origin of the  */
-/*  coordinate system; the destination of the triangle is one unit along the */
-/*  xi axis; and the apex of the triangle is one unit along the eta axis.    */
-/*  This procedure also returns the square of the length of the triangle's   */
-/*  shortest edge.                                                           */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef ANSI_DECLARATORS
-void findcircumcenter(struct mesh *m, struct behavior *b,
-                      vertex torg, vertex tdest, vertex tapex,
-                      vertex circumcenter, REAL *xi, REAL *eta, int offcenter)
-#else /* not ANSI_DECLARATORS */
-void findcircumcenter(m, b, torg, tdest, tapex, circumcenter, xi, eta,
-                      offcenter)
-struct mesh *m;
-struct behavior *b;
-vertex torg;
-vertex tdest;
-vertex tapex;
-vertex circumcenter;
-REAL *xi;
-REAL *eta;
-int offcenter;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  REAL xdo, ydo, xao, yao;
-  REAL dodist, aodist, dadist;
-  REAL denominator;
-  REAL dx, dy, dxoff, dyoff;
-
-  m->circumcentercount++;
-
-  /* Compute the circumcenter of the triangle. */
-  xdo = tdest[0] - torg[0];
-  ydo = tdest[1] - torg[1];
-  xao = tapex[0] - torg[0];
-  yao = tapex[1] - torg[1];
-  dodist = xdo * xdo + ydo * ydo;
-  aodist = xao * xao + yao * yao;
-  dadist = (tdest[0] - tapex[0]) * (tdest[0] - tapex[0]) +
-           (tdest[1] - tapex[1]) * (tdest[1] - tapex[1]);
-  if (b->noexact) {
-    denominator = 0.5 / (xdo * yao - xao * ydo);
-  } else {
-    /* Use the counterclockwise() routine to ensure a positive (and */
-    /*   reasonably accurate) result, avoiding any possibility of   */
-    /*   division by zero.                                          */
-    denominator = 0.5 / counterclockwise(m, b, tdest, tapex, torg);
-    /* Don't count the above as an orientation test. */
-    m->counterclockcount--;
-  }
-  dx = (yao * dodist - ydo * aodist) * denominator;
-  dy = (xdo * aodist - xao * dodist) * denominator;
-
-  /* Find the (squared) length of the triangle's shortest edge.  This   */
-  /*   serves as a conservative estimate of the insertion radius of the */
-  /*   circumcenter's parent.  The estimate is used to ensure that      */
-  /*   the algorithm terminates even if very small angles appear in     */
-  /*   the input PSLG.                                                  */
-  if ((dodist < aodist) && (dodist < dadist)) {
-    if (offcenter && (b->offconstant > 0.0)) {
-      /* Find the position of the off-center, as described by Alper Ungor. */
-      dxoff = 0.5 * xdo - b->offconstant * ydo;
-      dyoff = 0.5 * ydo + b->offconstant * xdo;
-      /* If the off-center is closer to the origin than the */
-      /*   circumcenter, use the off-center instead.        */
-      if (dxoff * dxoff + dyoff * dyoff < dx * dx + dy * dy) {
-        dx = dxoff;
-        dy = dyoff;
-      }
-    }
-  } else if (aodist < dadist) {
-    if (offcenter && (b->offconstant > 0.0)) {
-      dxoff = 0.5 * xao + b->offconstant * yao;
-      dyoff = 0.5 * yao - b->offconstant * xao;
-      /* If the off-center is closer to the origin than the */
-      /*   circumcenter, use the off-center instead.        */
-      if (dxoff * dxoff + dyoff * dyoff < dx * dx + dy * dy) {
-        dx = dxoff;
-        dy = dyoff;
-      }
-    }
-  } else {
-    if (offcenter && (b->offconstant > 0.0)) {
-      dxoff = 0.5 * (tapex[0] - tdest[0]) -
-              b->offconstant * (tapex[1] - tdest[1]);
-      dyoff = 0.5 * (tapex[1] - tdest[1]) +
-              b->offconstant * (tapex[0] - tdest[0]);
-      /* If the off-center is closer to the destination than the */
-      /*   circumcenter, use the off-center instead.             */
-      if (dxoff * dxoff + dyoff * dyoff <
-          (dx - xdo) * (dx - xdo) + (dy - ydo) * (dy - ydo)) {
-        dx = xdo + dxoff;
-        dy = ydo + dyoff;
-      }
-    }
-  }
-
-  circumcenter[0] = torg[0] + dx;
-  circumcenter[1] = torg[1] + dy;
-
-  /* To interpolate vertex attributes for the new vertex inserted at */
-  /*   the circumcenter, define a coordinate system with a xi-axis,  */
-  /*   directed from the triangle's origin to its destination, and   */
-  /*   an eta-axis, directed from its origin to its apex.            */
-  /*   Calculate the xi and eta coordinates of the circumcenter.     */
-  *xi = (yao * dx - xao * dy) * (2.0 * denominator);
-  *eta = (xdo * dy - ydo * dx) * (2.0 * denominator);
-}
-
-/**                                                                         **/
-/**                                                                         **/
-/********* Geometric primitives end here                             *********/
-
-/*****************************************************************************/
-/*                                                                           */
-/*  triangleinit()   Initialize some variables.                              */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef ANSI_DECLARATORS
-void triangleinit(struct mesh *m)
-#else /* not ANSI_DECLARATORS */
-void triangleinit(m)
-struct mesh *m;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  poolzero(&m->vertices);
-  poolzero(&m->triangles);
-  poolzero(&m->subsegs);
-  poolzero(&m->viri);
-  poolzero(&m->badsubsegs);
-  poolzero(&m->badtriangles);
-  poolzero(&m->flipstackers);
-  poolzero(&m->splaynodes);
-
-  m->recenttri.tri = (triangle *) NULL; /* No triangle has been visited yet. */
-  m->undeads = 0;                       /* No eliminated input vertices yet. */
-  m->samples = 1;         /* Point location should take at least one sample. */
-  m->checksegments = 0;   /* There are no segments in the triangulation yet. */
-  m->checkquality = 0;     /* The quality triangulation stage has not begun. */
-  m->incirclecount = m->counterclockcount = m->orient3dcount = 0;
-  m->hyperbolacount = m->circletopcount = m->circumcentercount = 0;
-  randomseed = 1;
-
-  exactinit();                     /* Initialize exact arithmetic constants. */
-}
-
-/*****************************************************************************/
-/*                                                                           */
-/*  randomnation()   Generate a random number between 0 and `choices' - 1.   */
-/*                                                                           */
-/*  This is a simple linear congruential random number generator.  Hence, it */
-/*  is a bad random number generator, but good enough for most randomized    */
-/*  geometric algorithms.                                                    */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef ANSI_DECLARATORS
-unsigned long randomnation(unsigned int choices)
-#else /* not ANSI_DECLARATORS */
-unsigned long randomnation(choices)
-unsigned int choices;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  randomseed = (randomseed * 1366l + 150889l) % 714025l;
-  return randomseed / (714025l / choices + 1);
-}
-
-/********* Mesh quality testing routines begin here                  *********/
-/**                                                                         **/
-/**                                                                         **/
-
-/*****************************************************************************/
-/*                                                                           */
-/*  checkmesh()   Test the mesh for topological consistency.                 */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifndef REDUCED
-
-#ifdef ANSI_DECLARATORS
-void checkmesh(struct mesh *m, struct behavior *b)
-#else /* not ANSI_DECLARATORS */
-void checkmesh(m, b)
-struct mesh *m;
-struct behavior *b;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  struct otri triangleloop;
-  struct otri oppotri, oppooppotri;
-  vertex triorg, tridest, triapex;
-  vertex oppoorg, oppodest;
-  int horrors;
-  int saveexact;
-  triangle ptr;                         /* Temporary variable used by sym(). */
-
-  /* Temporarily turn on exact arithmetic if it's off. */
-  saveexact = b->noexact;
-  b->noexact = 0;
-  if (!b->quiet) {
-    printf("  Checking consistency of mesh...\n");
-  }
-  horrors = 0;
-  /* Run through the list of triangles, checking each one. */
-  traversalinit(&m->triangles);
-  triangleloop.tri = triangletraverse(m);
-  while (triangleloop.tri != (triangle *) NULL) {
-    /* Check all three edges of the triangle. */
-    for (triangleloop.orient = 0; triangleloop.orient < 3;
-         triangleloop.orient++) {
-      org(triangleloop, triorg);
-      dest(triangleloop, tridest);
-      if (triangleloop.orient == 0) {       /* Only test for inversion once. */
-        /* Test if the triangle is flat or inverted. */
-        apex(triangleloop, triapex);
-        if (counterclockwise(m, b, triorg, tridest, triapex) <= 0.0) {
-          printf("  !! !! Inverted ");
-          printtriangle(m, b, &triangleloop);
-          horrors++;
-        }
-      }
-      /* Find the neighboring triangle on this edge. */
-      sym(triangleloop, oppotri);
-      if (oppotri.tri != m->dummytri) {
-        /* Check that the triangle's neighbor knows it's a neighbor. */
-        sym(oppotri, oppooppotri);
-        if ((triangleloop.tri != oppooppotri.tri)
-            || (triangleloop.orient != oppooppotri.orient)) {
-          printf("  !! !! Asymmetric triangle-triangle bond:\n");
-          if (triangleloop.tri == oppooppotri.tri) {
-            printf("   (Right triangle, wrong orientation)\n");
-          }
-          printf("    First ");
-          printtriangle(m, b, &triangleloop);
-          printf("    Second (nonreciprocating) ");
-          printtriangle(m, b, &oppotri);
-          horrors++;
-        }
-        /* Check that both triangles agree on the identities */
-        /*   of their shared vertices.                       */
-        org(oppotri, oppoorg);
-        dest(oppotri, oppodest);
-        if ((triorg != oppodest) || (tridest != oppoorg)) {
-          printf("  !! !! Mismatched edge coordinates between two triangles:\n"
-                 );
-          printf("    First mismatched ");
-          printtriangle(m, b, &triangleloop);
-          printf("    Second mismatched ");
-          printtriangle(m, b, &oppotri);
-          horrors++;
-        }
-      }
-    }
-    triangleloop.tri = triangletraverse(m);
-  }
-  if (horrors == 0) {
-    if (!b->quiet) {
-      printf("  In my studied opinion, the mesh appears to be consistent.\n");
-    }
-  } else if (horrors == 1) {
-    printf("  !! !! !! !! Precisely one festering wound discovered.\n");
-  } else {
-    printf("  !! !! !! !! %d abominations witnessed.\n", horrors);
-  }
-  /* Restore the status of exact arithmetic. */
-  b->noexact = saveexact;
-}
-
-#endif /* not REDUCED */
-
-/*****************************************************************************/
-/*                                                                           */
-/*  checkdelaunay()   Ensure that the mesh is (constrained) Delaunay.        */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifndef REDUCED
-
-#ifdef ANSI_DECLARATORS
-void checkdelaunay(struct mesh *m, struct behavior *b)
-#else /* not ANSI_DECLARATORS */
-void checkdelaunay(m, b)
-struct mesh *m;
-struct behavior *b;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  struct otri triangleloop;
-  struct otri oppotri;
-  struct osub opposubseg;
-  vertex triorg, tridest, triapex;
-  vertex oppoapex;
-  int shouldbedelaunay;
-  int horrors;
-  int saveexact;
-  triangle ptr;                         /* Temporary variable used by sym(). */
-  subseg sptr;                      /* Temporary variable used by tspivot(). */
-
-  /* Temporarily turn on exact arithmetic if it's off. */
-  saveexact = b->noexact;
-  b->noexact = 0;
-  if (!b->quiet) {
-    printf("  Checking Delaunay property of mesh...\n");
-  }
-  horrors = 0;
-  /* Run through the list of triangles, checking each one. */
-  traversalinit(&m->triangles);
-  triangleloop.tri = triangletraverse(m);
-  while (triangleloop.tri != (triangle *) NULL) {
-    /* Check all three edges of the triangle. */
-    for (triangleloop.orient = 0; triangleloop.orient < 3;
-         triangleloop.orient++) {
-      org(triangleloop, triorg);
-      dest(triangleloop, tridest);
-      apex(triangleloop, triapex);
-      sym(triangleloop, oppotri);
-      apex(oppotri, oppoapex);
-      /* Only test that the edge is locally Delaunay if there is an   */
-      /*   adjoining triangle whose pointer is larger (to ensure that */
-      /*   each pair isn't tested twice).                             */
-      shouldbedelaunay = (oppotri.tri != m->dummytri) &&
-            !deadtri(oppotri.tri) && (triangleloop.tri < oppotri.tri) &&
-            (triorg != m->infvertex1) && (triorg != m->infvertex2) &&
-            (triorg != m->infvertex3) &&
-            (tridest != m->infvertex1) && (tridest != m->infvertex2) &&
-            (tridest != m->infvertex3) &&
-            (triapex != m->infvertex1) && (triapex != m->infvertex2) &&
-            (triapex != m->infvertex3) &&
-            (oppoapex != m->infvertex1) && (oppoapex != m->infvertex2) &&
-            (oppoapex != m->infvertex3);
-      if (m->checksegments && shouldbedelaunay) {
-        /* If a subsegment separates the triangles, then the edge is */
-        /*   constrained, so no local Delaunay test should be done.  */
-        tspivot(triangleloop, opposubseg);
-        if (opposubseg.ss != m->dummysub){
-          shouldbedelaunay = 0;
-        }
-      }
-      if (shouldbedelaunay) {
-        if (nonregular(m, b, triorg, tridest, triapex, oppoapex) > 0.0) {
-          if (!b->weighted) {
-            printf("  !! !! Non-Delaunay pair of triangles:\n");
-            printf("    First non-Delaunay ");
-            printtriangle(m, b, &triangleloop);
-            printf("    Second non-Delaunay ");
-          } else {
-            printf("  !! !! Non-regular pair of triangles:\n");
-            printf("    First non-regular ");
-            printtriangle(m, b, &triangleloop);
-            printf("    Second non-regular ");
-          }
-          printtriangle(m, b, &oppotri);
-          horrors++;
-        }
-      }
-    }
-    triangleloop.tri = triangletraverse(m);
-  }
-  if (horrors == 0) {
-    if (!b->quiet) {
-      printf(
-  "  By virtue of my perceptive intelligence, I declare the mesh Delaunay.\n");
-    }
-  } else if (horrors == 1) {
-    printf(
-         "  !! !! !! !! Precisely one terrifying transgression identified.\n");
-  } else {
-    printf("  !! !! !! !! %d obscenities viewed with horror.\n", horrors);
-  }
-  /* Restore the status of exact arithmetic. */
-  b->noexact = saveexact;
-}
-
-#endif /* not REDUCED */
-
-/*****************************************************************************/
-/*                                                                           */
-/*  enqueuebadtriang()   Add a bad triangle data structure to the end of a   */
-/*                       queue.                                              */
-/*                                                                           */
-/*  The queue is actually a set of 4096 queues.  I use multiple queues to    */
-/*  give priority to smaller angles.  I originally implemented a heap, but   */
-/*  the queues are faster by a larger margin than I'd suspected.             */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifndef CDT_ONLY
-
-#ifdef ANSI_DECLARATORS
-void enqueuebadtriang(struct mesh *m, struct behavior *b,
-                      struct badtriang *badtri)
-#else /* not ANSI_DECLARATORS */
-void enqueuebadtriang(m, b, badtri)
-struct mesh *m;
-struct behavior *b;
-struct badtriang *badtri;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  REAL length, multiplier;
-  int exponent, expincrement;
-  int queuenumber;
-  int posexponent;
-  int i;
-
-  if (b->verbose > 2) {
-    printf("  Queueing bad triangle:\n");
-    printf("    (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n",
-           badtri->triangorg[0], badtri->triangorg[1],
-           badtri->triangdest[0], badtri->triangdest[1],
-           badtri->triangapex[0], badtri->triangapex[1]);
-  }
-
-  /* Determine the appropriate queue to put the bad triangle into.    */
-  /*   Recall that the key is the square of its shortest edge length. */
-  if (badtri->key >= 1.0) {
-    length = badtri->key;
-    posexponent = 1;
-  } else {
-    /* `badtri->key' is 2.0 to a negative exponent, so we'll record that */
-    /*   fact and use the reciprocal of `badtri->key', which is > 1.0.   */
-    length = 1.0 / badtri->key;
-    posexponent = 0;
-  }
-  /* `length' is approximately 2.0 to what exponent?  The following code */
-  /*   determines the answer in time logarithmic in the exponent.        */
-  exponent = 0;
-  while (length > 2.0) {
-    /* Find an approximation by repeated squaring of two. */
-    expincrement = 1;
-    multiplier = 0.5;
-    while (length * multiplier * multiplier > 1.0) {
-      expincrement *= 2;
-      multiplier *= multiplier;
-    }
-    /* Reduce the value of `length', then iterate if necessary. */
-    exponent += expincrement;
-    length *= multiplier;
-  }
-  /* `length' is approximately squareroot(2.0) to what exponent? */
-  exponent = (int)(2.0 * exponent + (length > SQUAREROOTTWO));
-  /* `exponent' is now in the range 0...2047 for IEEE double precision.   */
-  /*   Choose a queue in the range 0...4095.  The shortest edges have the */
-  /*   highest priority (queue 4095).                                     */
-  if (posexponent) {
-    queuenumber = 2047 - exponent;
-  } else {
-    queuenumber = 2048 + exponent;
-  }
-
-  /* Are we inserting into an empty queue? */
-  if (m->queuefront[queuenumber] == (struct badtriang *) NULL) {
-    /* Yes, we are inserting into an empty queue.     */
-    /*   Will this become the highest-priority queue? */
-    if (queuenumber > m->firstnonemptyq) {
-      /* Yes, this is the highest-priority queue. */
-      m->nextnonemptyq[queuenumber] = m->firstnonemptyq;
-      m->firstnonemptyq = queuenumber;
-    } else {
-      /* No, this is not the highest-priority queue. */
-      /*   Find the queue with next higher priority. */
-      i = queuenumber + 1;
-      while (m->queuefront[i] == (struct badtriang *) NULL) {
-        i++;
-      }
-      /* Mark the newly nonempty queue as following a higher-priority queue. */
-      m->nextnonemptyq[queuenumber] = m->nextnonemptyq[i];
-      m->nextnonemptyq[i] = queuenumber;
-    }
-    /* Put the bad triangle at the beginning of the (empty) queue. */
-    m->queuefront[queuenumber] = badtri;
-  } else {
-    /* Add the bad triangle to the end of an already nonempty queue. */
-    m->queuetail[queuenumber]->nexttriang = badtri;
-  }
-  /* Maintain a pointer to the last triangle of the queue. */
-  m->queuetail[queuenumber] = badtri;
-  /* Newly enqueued bad triangle has no successor in the queue. */
-  badtri->nexttriang = (struct badtriang *) NULL;
-}
-
-#endif /* not CDT_ONLY */
-
-/*****************************************************************************/
-/*                                                                           */
-/*  enqueuebadtri()   Add a bad triangle to the end of a queue.              */
-/*                                                                           */
-/*  Allocates a badtriang data structure for the triangle, then passes it to */
-/*  enqueuebadtriang().                                                      */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifndef CDT_ONLY
-
-#ifdef ANSI_DECLARATORS
-void enqueuebadtri(struct mesh *m, struct behavior *b, struct otri *enqtri,
-                   REAL minedge, vertex enqapex, vertex enqorg, vertex enqdest)
-#else /* not ANSI_DECLARATORS */
-void enqueuebadtri(m, b, enqtri, minedge, enqapex, enqorg, enqdest)
-struct mesh *m;
-struct behavior *b;
-struct otri *enqtri;
-REAL minedge;
-vertex enqapex;
-vertex enqorg;
-vertex enqdest;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  struct badtriang *newbad;
-
-  /* Allocate space for the bad triangle. */
-  newbad = (struct badtriang *) poolalloc(&m->badtriangles);
-  newbad->poortri = encode(*enqtri);
-  newbad->key = minedge;
-  newbad->triangapex = enqapex;
-  newbad->triangorg = enqorg;
-  newbad->triangdest = enqdest;
-  enqueuebadtriang(m, b, newbad);
-}
-
-#endif /* not CDT_ONLY */
-
-/*****************************************************************************/
-/*                                                                           */
-/*  dequeuebadtriang()   Remove a triangle from the front of the queue.      */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifndef CDT_ONLY
-
-#ifdef ANSI_DECLARATORS
-struct badtriang *dequeuebadtriang(struct mesh *m)
-#else /* not ANSI_DECLARATORS */
-struct badtriang *dequeuebadtriang(m)
-struct mesh *m;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  struct badtriang *result;
-
-  /* If no queues are nonempty, return NULL. */
-  if (m->firstnonemptyq < 0) {
-    return (struct badtriang *) NULL;
-  }
-  /* Find the first triangle of the highest-priority queue. */
-  result = m->queuefront[m->firstnonemptyq];
-  /* Remove the triangle from the queue. */
-  m->queuefront[m->firstnonemptyq] = result->nexttriang;
-  /* If this queue is now empty, note the new highest-priority */
-  /*   nonempty queue.                                         */
-  if (result == m->queuetail[m->firstnonemptyq]) {
-    m->firstnonemptyq = m->nextnonemptyq[m->firstnonemptyq];
-  }
-  return result;
-}
-
-#endif /* not CDT_ONLY */
-
-/*****************************************************************************/
-/*                                                                           */
-/*  checkseg4encroach()   Check a subsegment to see if it is encroached; add */
-/*                        it to the list if it is.                           */
-/*                                                                           */
-/*  A subsegment is encroached if there is a vertex in its diametral lens.   */
-/*  For Ruppert's algorithm (-D switch), the "diametral lens" is the         */
-/*  diametral circle.  For Chew's algorithm (default), the diametral lens is */
-/*  just big enough to enclose two isosceles triangles whose bases are the   */
-/*  subsegment.  Each of the two isosceles triangles has two angles equal    */
-/*  to `b->minangle'.                                                        */
-/*                                                                           */
-/*  Chew's algorithm does not require diametral lenses at all--but they save */
-/*  time.  Any vertex inside a subsegment's diametral lens implies that the  */
-/*  triangle adjoining the subsegment will be too skinny, so it's only a     */
-/*  matter of time before the encroaching vertex is deleted by Chew's        */
-/*  algorithm.  It's faster to simply not insert the doomed vertex in the    */
-/*  first place, which is why I use diametral lenses with Chew's algorithm.  */
-/*                                                                           */
-/*  Returns a nonzero value if the subsegment is encroached.                 */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifndef CDT_ONLY
-
-#ifdef ANSI_DECLARATORS
-int checkseg4encroach(struct mesh *m, struct behavior *b,
-                      struct osub *testsubseg)
-#else /* not ANSI_DECLARATORS */
-int checkseg4encroach(m, b, testsubseg)
-struct mesh *m;
-struct behavior *b;
-struct osub *testsubseg;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  struct otri neighbortri;
-  struct osub testsym;
-  struct badsubseg *encroachedseg;
-  REAL dotproduct;
-  int encroached;
-  int sides;
-  vertex eorg, edest, eapex;
-  triangle ptr;                     /* Temporary variable used by stpivot(). */
-
-  encroached = 0;
-  sides = 0;
-
-  sorg(*testsubseg, eorg);
-  sdest(*testsubseg, edest);
-  /* Check one neighbor of the subsegment. */
-  stpivot(*testsubseg, neighbortri);
-  /* Does the neighbor exist, or is this a boundary edge? */
-  if (neighbortri.tri != m->dummytri) {
-    sides++;
-    /* Find a vertex opposite this subsegment. */
-    apex(neighbortri, eapex);
-    /* Check whether the apex is in the diametral lens of the subsegment */
-    /*   (the diametral circle if `conformdel' is set).  A dot product   */
-    /*   of two sides of the triangle is used to check whether the angle */
-    /*   at the apex is greater than (180 - 2 `minangle') degrees (for   */
-    /*   lenses; 90 degrees for diametral circles).                      */
-    dotproduct = (eorg[0] - eapex[0]) * (edest[0] - eapex[0]) +
-                 (eorg[1] - eapex[1]) * (edest[1] - eapex[1]);
-    if (dotproduct < 0.0) {
-      if (b->conformdel ||
-          (dotproduct * dotproduct >=
-           (2.0 * b->goodangle - 1.0) * (2.0 * b->goodangle - 1.0) *
-           ((eorg[0] - eapex[0]) * (eorg[0] - eapex[0]) +
-            (eorg[1] - eapex[1]) * (eorg[1] - eapex[1])) *
-           ((edest[0] - eapex[0]) * (edest[0] - eapex[0]) +
-            (edest[1] - eapex[1]) * (edest[1] - eapex[1])))) {
-        encroached = 1;
-      }
-    }
-  }
-  /* Check the other neighbor of the subsegment. */
-  ssym(*testsubseg, testsym);
-  stpivot(testsym, neighbortri);
-  /* Does the neighbor exist, or is this a boundary edge? */
-  if (neighbortri.tri != m->dummytri) {
-    sides++;
-    /* Find the other vertex opposite this subsegment. */
-    apex(neighbortri, eapex);
-    /* Check whether the apex is in the diametral lens of the subsegment */
-    /*   (or the diametral circle, if `conformdel' is set).              */
-    dotproduct = (eorg[0] - eapex[0]) * (edest[0] - eapex[0]) +
-                 (eorg[1] - eapex[1]) * (edest[1] - eapex[1]);
-    if (dotproduct < 0.0) {
-      if (b->conformdel ||
-          (dotproduct * dotproduct >=
-           (2.0 * b->goodangle - 1.0) * (2.0 * b->goodangle - 1.0) *
-           ((eorg[0] - eapex[0]) * (eorg[0] - eapex[0]) +
-            (eorg[1] - eapex[1]) * (eorg[1] - eapex[1])) *
-           ((edest[0] - eapex[0]) * (edest[0] - eapex[0]) +
-            (edest[1] - eapex[1]) * (edest[1] - eapex[1])))) {
-        encroached += 2;
-      }
-    }
-  }
-
-  if (encroached && (!b->nobisect || ((b->nobisect == 1) && (sides == 2)))) {
-    if (b->verbose > 2) {
-      printf(
-        "  Queueing encroached subsegment (%.12g, %.12g) (%.12g, %.12g).\n",
-        eorg[0], eorg[1], edest[0], edest[1]);
-    }
-    /* Add the subsegment to the list of encroached subsegments. */
-    /*   Be sure to get the orientation right.                   */
-    encroachedseg = (struct badsubseg *) poolalloc(&m->badsubsegs);
-    if (encroached == 1) {
-      encroachedseg->encsubseg = sencode(*testsubseg);
-      encroachedseg->subsegorg = eorg;
-      encroachedseg->subsegdest = edest;
-    } else {
-      encroachedseg->encsubseg = sencode(testsym);
-      encroachedseg->subsegorg = edest;
-      encroachedseg->subsegdest = eorg;
-    }
-  }
-
-  return encroached;
-}
-
-#endif /* not CDT_ONLY */
-
-/*****************************************************************************/
-/*                                                                           */
-/*  testtriangle()   Test a triangle for quality and size.                   */
-/*                                                                           */
-/*  Tests a triangle to see if it satisfies the minimum angle condition and  */
-/*  the maximum area condition.  Triangles that aren't up to spec are added  */
-/*  to the bad triangle queue.                                               */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifndef CDT_ONLY
-
-#ifdef ANSI_DECLARATORS
-void testtriangle(struct mesh *m, struct behavior *b, struct otri *testtri)
-#else /* not ANSI_DECLARATORS */
-void testtriangle(m, b, testtri)
-struct mesh *m;
-struct behavior *b;
-struct otri *testtri;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  struct otri tri1, tri2;
-  struct osub testsub;
-  vertex torg, tdest, tapex;
-  vertex base1, base2;
-  vertex org1, dest1, org2, dest2;
-  vertex joinvertex;
-  REAL dxod, dyod, dxda, dyda, dxao, dyao;
-  REAL dxod2, dyod2, dxda2, dyda2, dxao2, dyao2;
-  REAL apexlen, orglen, destlen, minedge;
-  REAL angle;
-  REAL area;
-  REAL dist1, dist2;
-  subseg sptr;                      /* Temporary variable used by tspivot(). */
-  triangle ptr;           /* Temporary variable used by oprev() and dnext(). */
-
-  org(*testtri, torg);
-  dest(*testtri, tdest);
-  apex(*testtri, tapex);
-  dxod = torg[0] - tdest[0];
-  dyod = torg[1] - tdest[1];
-  dxda = tdest[0] - tapex[0];
-  dyda = tdest[1] - tapex[1];
-  dxao = tapex[0] - torg[0];
-  dyao = tapex[1] - torg[1];
-  dxod2 = dxod * dxod;
-  dyod2 = dyod * dyod;
-  dxda2 = dxda * dxda;
-  dyda2 = dyda * dyda;
-  dxao2 = dxao * dxao;
-  dyao2 = dyao * dyao;
-  /* Find the lengths of the triangle's three edges. */
-  apexlen = dxod2 + dyod2;
-  orglen = dxda2 + dyda2;
-  destlen = dxao2 + dyao2;
-
-  if ((apexlen < orglen) && (apexlen < destlen)) {
-    /* The edge opposite the apex is shortest. */
-    minedge = apexlen;
-    /* Find the square of the cosine of the angle at the apex. */
-    angle = dxda * dxao + dyda * dyao;
-    angle = angle * angle / (orglen * destlen);
-    base1 = torg;
-    base2 = tdest;
-    otricopy(*testtri, tri1);
-  } else if (orglen < destlen) {
-    /* The edge opposite the origin is shortest. */
-    minedge = orglen;
-    /* Find the square of the cosine of the angle at the origin. */
-    angle = dxod * dxao + dyod * dyao;
-    angle = angle * angle / (apexlen * destlen);
-    base1 = tdest;
-    base2 = tapex;
-    lnext(*testtri, tri1);
-  } else {
-    /* The edge opposite the destination is shortest. */
-    minedge = destlen;
-    /* Find the square of the cosine of the angle at the destination. */
-    angle = dxod * dxda + dyod * dyda;
-    angle = angle * angle / (apexlen * orglen);
-    base1 = tapex;
-    base2 = torg;
-    lprev(*testtri, tri1);
-  }
-
-  if (b->vararea || b->fixedarea || b->usertest) {
-    /* Check whether the area is larger than permitted. */
-    area = 0.5 * (dxod * dyda - dyod * dxda);
-    if (b->fixedarea && (area > b->maxarea)) {
-      /* Add this triangle to the list of bad triangles. */
-      enqueuebadtri(m, b, testtri, minedge, tapex, torg, tdest);
-      return;
-    }
-
-    /* Nonpositive area constraints are treated as unconstrained. */
-    if ((b->vararea) && (area > areabound(*testtri)) &&
-        (areabound(*testtri) > 0.0)) {
-      /* Add this triangle to the list of bad triangles. */
-      enqueuebadtri(m, b, testtri, minedge, tapex, torg, tdest);
-      return;
-    }
-
-    if (b->usertest) {
-      /* Check whether the user thinks this triangle is too large. */
-      if (triunsuitable(torg, tdest, tapex, area)) {
-        enqueuebadtri(m, b, testtri, minedge, tapex, torg, tdest);
-        return;
-      }
-    }
-  }
-
-  /* Check whether the angle is smaller than permitted. */
-  if (angle > b->goodangle) {
-    /* Use the rules of Miller, Pav, and Walkington to decide that certain */
-    /*   triangles should not be split, even if they have bad angles.      */
-    /*   A skinny triangle is not split if its shortest edge subtends a    */
-    /*   small input angle, and both endpoints of the edge lie on a        */
-    /*   concentric circular shell.  For convenience, I make a small       */
-    /*   adjustment to that rule:  I check if the endpoints of the edge    */
-    /*   both lie in segment interiors, equidistant from the apex where    */
-    /*   the two segments meet.                                            */
-    /* First, check if both points lie in segment interiors.               */
-    if ((vertextype(base1) == SEGMENTVERTEX) &&
-        (vertextype(base2) == SEGMENTVERTEX)) {
-      /* Check if both points lie in a common segment.  If they do, the */
-      /*   skinny triangle is enqueued to be split as usual.            */
-      tspivot(tri1, testsub);
-      if (testsub.ss == m->dummysub) {
-        /* No common segment.  Find a subsegment that contains `torg'. */
-        otricopy(tri1, tri2);
-        do {
-          oprevself(tri1);
-          tspivot(tri1, testsub);
-        } while (testsub.ss == m->dummysub);
-        /* Find the endpoints of the containing segment. */
-        segorg(testsub, org1);
-        segdest(testsub, dest1);
-        /* Find a subsegment that contains `tdest'. */
-        do {
-          dnextself(tri2);
-          tspivot(tri2, testsub);
-        } while (testsub.ss == m->dummysub);
-        /* Find the endpoints of the containing segment. */
-        segorg(testsub, org2);
-        segdest(testsub, dest2);
-        /* Check if the two containing segments have an endpoint in common. */
-        joinvertex = (vertex) NULL;
-        if ((dest1[0] == org2[0]) && (dest1[1] == org2[1])) {
-          joinvertex = dest1;
-        } else if ((org1[0] == dest2[0]) && (org1[1] == dest2[1])) {
-          joinvertex = org1;
-        }
-        if (joinvertex != (vertex) NULL) {
-          /* Compute the distance from the common endpoint (of the two  */
-          /*   segments) to each of the endpoints of the shortest edge. */
-          dist1 = ((base1[0] - joinvertex[0]) * (base1[0] - joinvertex[0]) +
-                   (base1[1] - joinvertex[1]) * (base1[1] - joinvertex[1]));
-          dist2 = ((base2[0] - joinvertex[0]) * (base2[0] - joinvertex[0]) +
-                   (base2[1] - joinvertex[1]) * (base2[1] - joinvertex[1]));
-          /* If the two distances are equal, don't split the triangle. */
-          if ((dist1 < 1.001 * dist2) && (dist1 > 0.999 * dist2)) {
-            /* Return now to avoid enqueueing the bad triangle. */
-            return;
-          }
-        }
-      }
-    }
-
-    /* Add this triangle to the list of bad triangles. */
-    enqueuebadtri(m, b, testtri, minedge, tapex, torg, tdest);
-  }
-}
-
-#endif /* not CDT_ONLY */
-
-/**                                                                         **/
-/**                                                                         **/
-/********* Mesh quality testing routines end here                    *********/
-
-/********* Point location routines begin here                        *********/
-/**                                                                         **/
-/**                                                                         **/
-
-/*****************************************************************************/
-/*                                                                           */
-/*  makevertexmap()   Construct a mapping from vertices to triangles to      */
-/*                    improve the speed of point location for segment        */
-/*                    insertion.                                             */
-/*                                                                           */
-/*  Traverses all the triangles, and provides each corner of each triangle   */
-/*  with a pointer to that triangle.  Of course, pointers will be            */
-/*  overwritten by other pointers because (almost) each vertex is a corner   */
-/*  of several triangles, but in the end every vertex will point to some     */
-/*  triangle that contains it.                                               */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef ANSI_DECLARATORS
-void makevertexmap(struct mesh *m, struct behavior *b)
-#else /* not ANSI_DECLARATORS */
-void makevertexmap(m, b)
-struct mesh *m;
-struct behavior *b;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  struct otri triangleloop;
-  vertex triorg;
-
-  if (b->verbose) {
-    printf("    Constructing mapping from vertices to triangles.\n");
-  }
-  traversalinit(&m->triangles);
-  triangleloop.tri = triangletraverse(m);
-  while (triangleloop.tri != (triangle *) NULL) {
-    /* Check all three vertices of the triangle. */
-    for (triangleloop.orient = 0; triangleloop.orient < 3;
-         triangleloop.orient++) {
-      org(triangleloop, triorg);
-      setvertex2tri(triorg, encode(triangleloop));
-    }
-    triangleloop.tri = triangletraverse(m);
-  }
-}
-
-/*****************************************************************************/
-/*                                                                           */
-/*  preciselocate()   Find a triangle or edge containing a given point.      */
-/*                                                                           */
-/*  Begins its search from `searchtri'.  It is important that `searchtri'    */
-/*  be a handle with the property that `searchpoint' is strictly to the left */
-/*  of the edge denoted by `searchtri', or is collinear with that edge and   */
-/*  does not intersect that edge.  (In particular, `searchpoint' should not  */
-/*  be the origin or destination of that edge.)                              */
-/*                                                                           */
-/*  These conditions are imposed because preciselocate() is normally used in */
-/*  one of two situations:                                                   */
-/*                                                                           */
-/*  (1)  To try to find the location to insert a new point.  Normally, we    */
-/*       know an edge that the point is strictly to the left of.  In the     */
-/*       incremental Delaunay algorithm, that edge is a bounding box edge.   */
-/*       In Ruppert's Delaunay refinement algorithm for quality meshing,     */
-/*       that edge is the shortest edge of the triangle whose circumcenter   */
-/*       is being inserted.                                                  */
-/*                                                                           */
-/*  (2)  To try to find an existing point.  In this case, any edge on the    */
-/*       convex hull is a good starting edge.  You must screen out the       */
-/*       possibility that the vertex sought is an endpoint of the starting   */
-/*       edge before you call preciselocate().                               */
-/*                                                                           */
-/*  On completion, `searchtri' is a triangle that contains `searchpoint'.    */
-/*                                                                           */
-/*  This implementation differs from that given by Guibas and Stolfi.  It    */
-/*  walks from triangle to triangle, crossing an edge only if `searchpoint'  */
-/*  is on the other side of the line containing that edge.  After entering   */
-/*  a triangle, there are two edges by which one can leave that triangle.    */
-/*  If both edges are valid (`searchpoint' is on the other side of both      */
-/*  edges), one of the two is chosen by drawing a line perpendicular to      */
-/*  the entry edge (whose endpoints are `forg' and `fdest') passing through  */
-/*  `fapex'.  Depending on which side of this perpendicular `searchpoint'    */
-/*  falls on, an exit edge is chosen.                                        */
-/*                                                                           */
-/*  This implementation is empirically faster than the Guibas and Stolfi     */
-/*  point location routine (which I originally used), which tends to spiral  */
-/*  in toward its target.                                                    */
-/*                                                                           */
-/*  Returns ONVERTEX if the point lies on an existing vertex.  `searchtri'   */
-/*  is a handle whose origin is the existing vertex.                         */
-/*                                                                           */
-/*  Returns ONEDGE if the point lies on a mesh edge.  `searchtri' is a       */
-/*  handle whose primary edge is the edge on which the point lies.           */
-/*                                                                           */
-/*  Returns INTRIANGLE if the point lies strictly within a triangle.         */
-/*  `searchtri' is a handle on the triangle that contains the point.         */
-/*                                                                           */
-/*  Returns OUTSIDE if the point lies outside the mesh.  `searchtri' is a    */
-/*  handle whose primary edge the point is to the right of.  This might      */
-/*  occur when the circumcenter of a triangle falls just slightly outside    */
-/*  the mesh due to floating-point roundoff error.  It also occurs when      */
-/*  seeking a hole or region point that a foolish user has placed outside    */
-/*  the mesh.                                                                */
-/*                                                                           */
-/*  If `stopatsubsegment' is nonzero, the search will stop if it tries to    */
-/*  walk through a subsegment, and will return OUTSIDE.                      */
-/*                                                                           */
-/*  WARNING:  This routine is designed for convex triangulations, and will   */
-/*  not generally work after the holes and concavities have been carved.     */
-/*  However, it can still be used to find the circumcenter of a triangle, as */
-/*  long as the search is begun from the triangle in question.               */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef ANSI_DECLARATORS
-enum locateresult preciselocate(struct mesh *m, struct behavior *b,
-                                vertex searchpoint, struct otri *searchtri,
-                                int stopatsubsegment)
-#else /* not ANSI_DECLARATORS */
-enum locateresult preciselocate(m, b, searchpoint, searchtri, stopatsubsegment)
-struct mesh *m;
-struct behavior *b;
-vertex searchpoint;
-struct otri *searchtri;
-int stopatsubsegment;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  struct otri backtracktri;
-  struct osub checkedge;
-  vertex forg, fdest, fapex;
-  REAL orgorient, destorient;
-  int moveleft;
-  triangle ptr;                         /* Temporary variable used by sym(). */
-  subseg sptr;                      /* Temporary variable used by tspivot(). */
-
-  if (b->verbose > 2) {
-    printf("  Searching for point (%.12g, %.12g).\n",
-           searchpoint[0], searchpoint[1]);
-  }
-  /* Where are we? */
-  org(*searchtri, forg);
-  dest(*searchtri, fdest);
-  apex(*searchtri, fapex);
-  while (1) {
-    if (b->verbose > 2) {
-      printf("    At (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n",
-             forg[0], forg[1], fdest[0], fdest[1], fapex[0], fapex[1]);
-    }
-    /* Check whether the apex is the point we seek. */
-    if ((fapex[0] == searchpoint[0]) && (fapex[1] == searchpoint[1])) {
-      lprevself(*searchtri);
-      return ONVERTEX;
-    }
-    /* Does the point lie on the other side of the line defined by the */
-    /*   triangle edge opposite the triangle's destination?            */
-    destorient = counterclockwise(m, b, forg, fapex, searchpoint);
-    /* Does the point lie on the other side of the line defined by the */
-    /*   triangle edge opposite the triangle's origin?                 */
-    orgorient = counterclockwise(m, b, fapex, fdest, searchpoint);
-    if (destorient > 0.0) {
-      if (orgorient > 0.0) {
-        /* Move left if the inner product of (fapex - searchpoint) and  */
-        /*   (fdest - forg) is positive.  This is equivalent to drawing */
-        /*   a line perpendicular to the line (forg, fdest) and passing */
-        /*   through `fapex', and determining which side of this line   */
-        /*   `searchpoint' falls on.                                    */
-        moveleft = (fapex[0] - searchpoint[0]) * (fdest[0] - forg[0]) +
-                   (fapex[1] - searchpoint[1]) * (fdest[1] - forg[1]) > 0.0;
-      } else {
-        moveleft = 1;
-      }
-    } else {
-      if (orgorient > 0.0) {
-        moveleft = 0;
-      } else {
-        /* The point we seek must be on the boundary of or inside this */
-        /*   triangle.                                                 */
-        if (destorient == 0.0) {
-          lprevself(*searchtri);
-          return ONEDGE;
-        }
-        if (orgorient == 0.0) {
-          lnextself(*searchtri);
-          return ONEDGE;
-        }
-        return INTRIANGLE;
-      }
-    }
-
-    /* Move to another triangle.  Leave a trace `backtracktri' in case */
-    /*   floating-point roundoff or some such bogey causes us to walk  */
-    /*   off a boundary of the triangulation.                          */
-    if (moveleft) {
-      lprev(*searchtri, backtracktri);
-      fdest = fapex;
-    } else {
-      lnext(*searchtri, backtracktri);
-      forg = fapex;
-    }
-    sym(backtracktri, *searchtri);
-
-    if (m->checksegments && stopatsubsegment) {
-      /* Check for walking through a subsegment. */
-      tspivot(backtracktri, checkedge);
-      if (checkedge.ss != m->dummysub) {
-        /* Go back to the last triangle. */
-        otricopy(backtracktri, *searchtri);
-        return OUTSIDE;
-      }
-    }
-    /* Check for walking right out of the triangulation. */
-    if (searchtri->tri == m->dummytri) {
-      /* Go back to the last triangle. */
-      otricopy(backtracktri, *searchtri);
-      return OUTSIDE;
-    }
-
-    apex(*searchtri, fapex);
-  }
-}
-
-/*****************************************************************************/
-/*                                                                           */
-/*  locate()   Find a triangle or edge containing a given point.             */
-/*                                                                           */
-/*  Searching begins from one of:  the input `searchtri', a recently         */
-/*  encountered triangle `recenttri', or from a triangle chosen from a       */
-/*  random sample.  The choice is made by determining which triangle's       */
-/*  origin is closest to the point we are searching for.  Normally,          */
-/*  `searchtri' should be a handle on the convex hull of the triangulation.  */
-/*                                                                           */
-/*  Details on the random sampling method can be found in the Mucke, Saias,  */
-/*  and Zhu paper cited in the header of this code.                          */
-/*                                                                           */
-/*  On completion, `searchtri' is a triangle that contains `searchpoint'.    */
-/*                                                                           */
-/*  Returns ONVERTEX if the point lies on an existing vertex.  `searchtri'   */
-/*  is a handle whose origin is the existing vertex.                         */
-/*                                                                           */
-/*  Returns ONEDGE if the point lies on a mesh edge.  `searchtri' is a       */
-/*  handle whose primary edge is the edge on which the point lies.           */
-/*                                                                           */
-/*  Returns INTRIANGLE if the point lies strictly within a triangle.         */
-/*  `searchtri' is a handle on the triangle that contains the point.         */
-/*                                                                           */
-/*  Returns OUTSIDE if the point lies outside the mesh.  `searchtri' is a    */
-/*  handle whose primary edge the point is to the right of.  This might      */
-/*  occur when the circumcenter of a triangle falls just slightly outside    */
-/*  the mesh due to floating-point roundoff error.  It also occurs when      */
-/*  seeking a hole or region point that a foolish user has placed outside    */
-/*  the mesh.                                                                */
-/*                                                                           */
-/*  WARNING:  This routine is designed for convex triangulations, and will   */
-/*  not generally work after the holes and concavities have been carved.     */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef ANSI_DECLARATORS
-enum locateresult locate(struct mesh *m, struct behavior *b,
-                         vertex searchpoint, struct otri *searchtri)
-#else /* not ANSI_DECLARATORS */
-enum locateresult locate(m, b, searchpoint, searchtri)
-struct mesh *m;
-struct behavior *b;
-vertex searchpoint;
-struct otri *searchtri;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  VOID **sampleblock;
-  char *firsttri;
-  struct otri sampletri;
-  vertex torg, tdest;
-  unsigned long alignptr;
-  REAL searchdist, dist;
-  REAL ahead;
-  long samplesperblock, totalsamplesleft, samplesleft;
-  long population, totalpopulation;
-  triangle ptr;                         /* Temporary variable used by sym(). */
-
-  if (b->verbose > 2) {
-    printf("  Randomly sampling for a triangle near point (%.12g, %.12g).\n",
-           searchpoint[0], searchpoint[1]);
-  }
-  /* Record the distance from the suggested starting triangle to the */
-  /*   point we seek.                                                */
-  org(*searchtri, torg);
-  searchdist = (searchpoint[0] - torg[0]) * (searchpoint[0] - torg[0]) +
-               (searchpoint[1] - torg[1]) * (searchpoint[1] - torg[1]);
-  if (b->verbose > 2) {
-    printf("    Boundary triangle has origin (%.12g, %.12g).\n",
-           torg[0], torg[1]);
-  }
-
-  /* If a recently encountered triangle has been recorded and has not been */
-  /*   deallocated, test it as a good starting point.                      */
-  if (m->recenttri.tri != (triangle *) NULL) {
-    if (!deadtri(m->recenttri.tri)) {
-      org(m->recenttri, torg);
-      if ((torg[0] == searchpoint[0]) && (torg[1] == searchpoint[1])) {
-        otricopy(m->recenttri, *searchtri);
-        return ONVERTEX;
-      }
-      dist = (searchpoint[0] - torg[0]) * (searchpoint[0] - torg[0]) +
-             (searchpoint[1] - torg[1]) * (searchpoint[1] - torg[1]);
-      if (dist < searchdist) {
-        otricopy(m->recenttri, *searchtri);
-        searchdist = dist;
-        if (b->verbose > 2) {
-          printf("    Choosing recent triangle with origin (%.12g, %.12g).\n",
-                 torg[0], torg[1]);
-        }
-      }
-    }
-  }
-
-  /* The number of random samples taken is proportional to the cube root of */
-  /*   the number of triangles in the mesh.  The next bit of code assumes   */
-  /*   that the number of triangles increases monotonically (or at least    */
-  /*   doesn't decrease enough to matter).                                  */
-  while (SAMPLEFACTOR * m->samples * m->samples * m->samples <
-         m->triangles.items) {
-    m->samples++;
-  }
-
-  /* We'll draw ceiling(samples * TRIPERBLOCK / maxitems) random samples  */
-  /*   from each block of triangles (except the first)--until we meet the */
-  /*   sample quota.  The ceiling means that blocks at the end might be   */
-  /*   neglected, but I don't care.                                       */
-  samplesperblock = (m->samples * TRIPERBLOCK - 1) / m->triangles.maxitems + 1;
-  /* We'll draw ceiling(samples * itemsfirstblock / maxitems) random samples */
-  /*   from the first block of triangles.                                    */
-  samplesleft = (m->samples * m->triangles.itemsfirstblock - 1) /
-                m->triangles.maxitems + 1;
-  totalsamplesleft = m->samples;
-  population = m->triangles.itemsfirstblock;
-  totalpopulation = m->triangles.maxitems;
-  sampleblock = m->triangles.firstblock;
-  sampletri.orient = 0;
-  while (totalsamplesleft > 0) {
-    /* If we're in the last block, `population' needs to be corrected. */
-    if (population > totalpopulation) {
-      population = totalpopulation;
-    }
-    /* Find a pointer to the first triangle in the block. */
-    alignptr = (unsigned long) (sampleblock + 1);
-    firsttri = (char *) (alignptr +
-                         (unsigned long) m->triangles.alignbytes -
-                         (alignptr %
-                          (unsigned long) m->triangles.alignbytes));
-
-    /* Choose `samplesleft' randomly sampled triangles in this block. */
-    do {
-      sampletri.tri = (triangle *) (firsttri +
-                                    (randomnation((unsigned int) population) *
-                                     m->triangles.itembytes));
-      if (!deadtri(sampletri.tri)) {
-        org(sampletri, torg);
-        dist = (searchpoint[0] - torg[0]) * (searchpoint[0] - torg[0]) +
-               (searchpoint[1] - torg[1]) * (searchpoint[1] - torg[1]);
-        if (dist < searchdist) {
-          otricopy(sampletri, *searchtri);
-          searchdist = dist;
-          if (b->verbose > 2) {
-            printf("    Choosing triangle with origin (%.12g, %.12g).\n",
-                   torg[0], torg[1]);
-          }
-        }
-      }
-
-      samplesleft--;
-      totalsamplesleft--;
-    } while ((samplesleft > 0) && (totalsamplesleft > 0));
-
-    if (totalsamplesleft > 0) {
-      sampleblock = (VOID **) *sampleblock;
-      samplesleft = samplesperblock;
-      totalpopulation -= population;
-      population = TRIPERBLOCK;
-    }
-  }
-
-  /* Where are we? */
-  org(*searchtri, torg);
-  dest(*searchtri, tdest);
-  /* Check the starting triangle's vertices. */
-  if ((torg[0] == searchpoint[0]) && (torg[1] == searchpoint[1])) {
-    return ONVERTEX;
-  }
-  if ((tdest[0] == searchpoint[0]) && (tdest[1] == searchpoint[1])) {
-    lnextself(*searchtri);
-    return ONVERTEX;
-  }
-  /* Orient `searchtri' to fit the preconditions of calling preciselocate(). */
-  ahead = counterclockwise(m, b, torg, tdest, searchpoint);
-  if (ahead < 0.0) {
-    /* Turn around so that `searchpoint' is to the left of the */
-    /*   edge specified by `searchtri'.                        */
-    symself(*searchtri);
-  } else if (ahead == 0.0) {
-    /* Check if `searchpoint' is between `torg' and `tdest'. */
-    if (((torg[0] < searchpoint[0]) == (searchpoint[0] < tdest[0])) &&
-        ((torg[1] < searchpoint[1]) == (searchpoint[1] < tdest[1]))) {
-      return ONEDGE;
-    }
-  }
-  return preciselocate(m, b, searchpoint, searchtri, 0);
-}
-
-/**                                                                         **/
-/**                                                                         **/
-/********* Point location routines end here                          *********/
-
-/********* Mesh transformation routines begin here                   *********/
-/**                                                                         **/
-/**                                                                         **/
-
-/*****************************************************************************/
-/*                                                                           */
-/*  insertsubseg()   Create a new subsegment and insert it between two       */
-/*                   triangles.                                              */
-/*                                                                           */
-/*  The new subsegment is inserted at the edge described by the handle       */
-/*  `tri'.  Its vertices are properly initialized.  The marker `subsegmark'  */
-/*  is applied to the subsegment and, if appropriate, its vertices.          */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef ANSI_DECLARATORS
-void insertsubseg(struct mesh *m, struct behavior *b, struct otri *tri,
-                  int subsegmark)
-#else /* not ANSI_DECLARATORS */
-void insertsubseg(m, b, tri, subsegmark)
-struct mesh *m;
-struct behavior *b;
-struct otri *tri;             /* Edge at which to insert the new subsegment. */
-int subsegmark;                            /* Marker for the new subsegment. */
-#endif /* not ANSI_DECLARATORS */
-
-{
-  struct otri oppotri;
-  struct osub newsubseg;
-  vertex triorg, tridest;
-  triangle ptr;                         /* Temporary variable used by sym(). */
-  subseg sptr;                      /* Temporary variable used by tspivot(). */
-
-  org(*tri, triorg);
-  dest(*tri, tridest);
-  /* Mark vertices if possible. */
-  if (vertexmark(triorg) == 0) {
-    setvertexmark(triorg, subsegmark);
-  }
-  if (vertexmark(tridest) == 0) {
-    setvertexmark(tridest, subsegmark);
-  }
-  /* Check if there's already a subsegment here. */
-  tspivot(*tri, newsubseg);
-  if (newsubseg.ss == m->dummysub) {
-    /* Make new subsegment and initialize its vertices. */
-    makesubseg(m, &newsubseg);
-    setsorg(newsubseg, tridest);
-    setsdest(newsubseg, triorg);
-    setsegorg(newsubseg, tridest);
-    setsegdest(newsubseg, triorg);
-    /* Bond new subsegment to the two triangles it is sandwiched between. */
-    /*   Note that the facing triangle `oppotri' might be equal to        */
-    /*   `dummytri' (outer space), but the new subsegment is bonded to it */
-    /*   all the same.                                                    */
-    tsbond(*tri, newsubseg);
-    sym(*tri, oppotri);
-    ssymself(newsubseg);
-    tsbond(oppotri, newsubseg);
-    setmark(newsubseg, subsegmark);
-    if (b->verbose > 2) {
-      printf("  Inserting new ");
-      printsubseg(m, b, &newsubseg);
-    }
-  } else {
-    if (mark(newsubseg) == 0) {
-      setmark(newsubseg, subsegmark);
-    }
-  }
-}
-
-/*****************************************************************************/
-/*                                                                           */
-/*  Terminology                                                              */
-/*                                                                           */
-/*  A "local transformation" replaces a small set of triangles with another  */
-/*  set of triangles.  This may or may not involve inserting or deleting a   */
-/*  vertex.                                                                  */
-/*                                                                           */
-/*  The term "casing" is used to describe the set of triangles that are      */
-/*  attached to the triangles being transformed, but are not transformed     */
-/*  themselves.  Think of the casing as a fixed hollow structure inside      */
-/*  which all the action happens.  A "casing" is only defined relative to    */
-/*  a single transformation; each occurrence of a transformation will        */
-/*  involve a different casing.                                              */
-/*                                                                           */
-/*****************************************************************************/
-
-/*****************************************************************************/
-/*                                                                           */
-/*  flip()   Transform two triangles to two different triangles by flipping  */
-/*           an edge counterclockwise within a quadrilateral.                */
-/*                                                                           */
-/*  Imagine the original triangles, abc and bad, oriented so that the        */
-/*  shared edge ab lies in a horizontal plane, with the vertex b on the left */
-/*  and the vertex a on the right.  The vertex c lies below the edge, and    */
-/*  the vertex d lies above the edge.  The `flipedge' handle holds the edge  */
-/*  ab of triangle abc, and is directed left, from vertex a to vertex b.     */
-/*                                                                           */
-/*  The triangles abc and bad are deleted and replaced by the triangles cdb  */
-/*  and dca.  The triangles that represent abc and bad are NOT deallocated;  */
-/*  they are reused for dca and cdb, respectively.  Hence, any handles that  */
-/*  may have held the original triangles are still valid, although not       */
-/*  directed as they were before.                                            */
-/*                                                                           */
-/*  Upon completion of this routine, the `flipedge' handle holds the edge    */
-/*  dc of triangle dca, and is directed down, from vertex d to vertex c.     */
-/*  (Hence, the two triangles have rotated counterclockwise.)                */
-/*                                                                           */
-/*  WARNING:  This transformation is geometrically valid only if the         */
-/*  quadrilateral adbc is convex.  Furthermore, this transformation is       */
-/*  valid only if there is not a subsegment between the triangles abc and    */
-/*  bad.  This routine does not check either of these preconditions, and     */
-/*  it is the responsibility of the calling routine to ensure that they are  */
-/*  met.  If they are not, the streets shall be filled with wailing and      */
-/*  gnashing of teeth.                                                       */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef ANSI_DECLARATORS
-void flip(struct mesh *m, struct behavior *b, struct otri *flipedge)
-#else /* not ANSI_DECLARATORS */
-void flip(m, b, flipedge)
-struct mesh *m;
-struct behavior *b;
-struct otri *flipedge;                    /* Handle for the triangle abc. */
-#endif /* not ANSI_DECLARATORS */
-
-{
-  struct otri botleft, botright;
-  struct otri topleft, topright;
-  struct otri top;
-  struct otri botlcasing, botrcasing;
-  struct otri toplcasing, toprcasing;
-  struct osub botlsubseg, botrsubseg;
-  struct osub toplsubseg, toprsubseg;
-  vertex leftvertex, rightvertex, botvertex;
-  vertex farvertex;
-  triangle ptr;                         /* Temporary variable used by sym(). */
-  subseg sptr;                      /* Temporary variable used by tspivot(). */
-
-  /* Identify the vertices of the quadrilateral. */
-  org(*flipedge, rightvertex);
-  dest(*flipedge, leftvertex);
-  apex(*flipedge, botvertex);
-  sym(*flipedge, top);
-#ifdef SELF_CHECK
-  if (top.tri == m->dummytri) {
-    printf("Internal error in flip():  Attempt to flip on boundary.\n");
-    lnextself(*flipedge);
-    return;
-  }
-  if (m->checksegments) {
-    tspivot(*flipedge, toplsubseg);
-    if (toplsubseg.ss != m->dummysub) {
-      printf("Internal error in flip():  Attempt to flip a segment.\n");
-      lnextself(*flipedge);
-      return;
-    }
-  }
-#endif /* SELF_CHECK */
-  apex(top, farvertex);
-
-  /* Identify the casing of the quadrilateral. */
-  lprev(top, topleft);
-  sym(topleft, toplcasing);
-  lnext(top, topright);
-  sym(topright, toprcasing);
-  lnext(*flipedge, botleft);
-  sym(botleft, botlcasing);
-  lprev(*flipedge, botright);
-  sym(botright, botrcasing);
-  /* Rotate the quadrilateral one-quarter turn counterclockwise. */
-  bond(topleft, botlcasing);
-  bond(botleft, botrcasing);
-  bond(botright, toprcasing);
-  bond(topright, toplcasing);
-
-  if (m->checksegments) {
-    /* Check for subsegments and rebond them to the quadrilateral. */
-    tspivot(topleft, toplsubseg);
-    tspivot(botleft, botlsubseg);
-    tspivot(botright, botrsubseg);
-    tspivot(topright, toprsubseg);
-    if (toplsubseg.ss == m->dummysub) {
-      tsdissolve(topright);
-    } else {
-      tsbond(topright, toplsubseg);
-    }
-    if (botlsubseg.ss == m->dummysub) {
-      tsdissolve(topleft);
-    } else {
-      tsbond(topleft, botlsubseg);
-    }
-    if (botrsubseg.ss == m->dummysub) {
-      tsdissolve(botleft);
-    } else {
-      tsbond(botleft, botrsubseg);
-    }
-    if (toprsubseg.ss == m->dummysub) {
-      tsdissolve(botright);
-    } else {
-      tsbond(botright, toprsubseg);
-    }
-  }
-
-  /* New vertex assignments for the rotated quadrilateral. */
-  setorg(*flipedge, farvertex);
-  setdest(*flipedge, botvertex);
-  setapex(*flipedge, rightvertex);
-  setorg(top, botvertex);
-  setdest(top, farvertex);
-  setapex(top, leftvertex);
-  if (b->verbose > 2) {
-    printf("  Edge flip results in left ");
-    printtriangle(m, b, &top);
-    printf("  and right ");
-    printtriangle(m, b, flipedge);
-  }
-}
-
-/*****************************************************************************/
-/*                                                                           */
-/*  unflip()   Transform two triangles to two different triangles by         */
-/*             flipping an edge clockwise within a quadrilateral.  Reverses  */
-/*             the flip() operation so that the data structures representing */
-/*             the triangles are back where they were before the flip().     */
-/*                                                                           */
-/*  Imagine the original triangles, abc and bad, oriented so that the        */
-/*  shared edge ab lies in a horizontal plane, with the vertex b on the left */
-/*  and the vertex a on the right.  The vertex c lies below the edge, and    */
-/*  the vertex d lies above the edge.  The `flipedge' handle holds the edge  */
-/*  ab of triangle abc, and is directed left, from vertex a to vertex b.     */
-/*                                                                           */
-/*  The triangles abc and bad are deleted and replaced by the triangles cdb  */
-/*  and dca.  The triangles that represent abc and bad are NOT deallocated;  */
-/*  they are reused for cdb and dca, respectively.  Hence, any handles that  */
-/*  may have held the original triangles are still valid, although not       */
-/*  directed as they were before.                                            */
-/*                                                                           */
-/*  Upon completion of this routine, the `flipedge' handle holds the edge    */
-/*  cd of triangle cdb, and is directed up, from vertex c to vertex d.       */
-/*  (Hence, the two triangles have rotated clockwise.)                       */
-/*                                                                           */
-/*  WARNING:  This transformation is geometrically valid only if the         */
-/*  quadrilateral adbc is convex.  Furthermore, this transformation is       */
-/*  valid only if there is not a subsegment between the triangles abc and    */
-/*  bad.  This routine does not check either of these preconditions, and     */
-/*  it is the responsibility of the calling routine to ensure that they are  */
-/*  met.  If they are not, the streets shall be filled with wailing and      */
-/*  gnashing of teeth.                                                       */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef ANSI_DECLARATORS
-void unflip(struct mesh *m, struct behavior *b, struct otri *flipedge)
-#else /* not ANSI_DECLARATORS */
-void unflip(m, b, flipedge)
-struct mesh *m;
-struct behavior *b;
-struct otri *flipedge;                    /* Handle for the triangle abc. */
-#endif /* not ANSI_DECLARATORS */
-
-{
-  struct otri botleft, botright;
-  struct otri topleft, topright;
-  struct otri top;
-  struct otri botlcasing, botrcasing;
-  struct otri toplcasing, toprcasing;
-  struct osub botlsubseg, botrsubseg;
-  struct osub toplsubseg, toprsubseg;
-  vertex leftvertex, rightvertex, botvertex;
-  vertex farvertex;
-  triangle ptr;                         /* Temporary variable used by sym(). */
-  subseg sptr;                      /* Temporary variable used by tspivot(). */
-
-  /* Identify the vertices of the quadrilateral. */
-  org(*flipedge, rightvertex);
-  dest(*flipedge, leftvertex);
-  apex(*flipedge, botvertex);
-  sym(*flipedge, top);
-#ifdef SELF_CHECK
-  if (top.tri == m->dummytri) {
-    printf("Internal error in unflip():  Attempt to flip on boundary.\n");
-    lnextself(*flipedge);
-    return;
-  }
-  if (m->checksegments) {
-    tspivot(*flipedge, toplsubseg);
-    if (toplsubseg.ss != m->dummysub) {
-      printf("Internal error in unflip():  Attempt to flip a subsegment.\n");
-      lnextself(*flipedge);
-      return;
-    }
-  }
-#endif /* SELF_CHECK */
-  apex(top, farvertex);
-
-  /* Identify the casing of the quadrilateral. */
-  lprev(top, topleft);
-  sym(topleft, toplcasing);
-  lnext(top, topright);
-  sym(topright, toprcasing);
-  lnext(*flipedge, botleft);
-  sym(botleft, botlcasing);
-  lprev(*flipedge, botright);
-  sym(botright, botrcasing);
-  /* Rotate the quadrilateral one-quarter turn clockwise. */
-  bond(topleft, toprcasing);
-  bond(botleft, toplcasing);
-  bond(botright, botlcasing);
-  bond(topright, botrcasing);
-
-  if (m->checksegments) {
-    /* Check for subsegments and rebond them to the quadrilateral. */
-    tspivot(topleft, toplsubseg);
-    tspivot(botleft, botlsubseg);
-    tspivot(botright, botrsubseg);
-    tspivot(topright, toprsubseg);
-    if (toplsubseg.ss == m->dummysub) {
-      tsdissolve(botleft);
-    } else {
-      tsbond(botleft, toplsubseg);
-    }
-    if (botlsubseg.ss == m->dummysub) {
-      tsdissolve(botright);
-    } else {
-      tsbond(botright, botlsubseg);
-    }
-    if (botrsubseg.ss == m->dummysub) {
-      tsdissolve(topright);
-    } else {
-      tsbond(topright, botrsubseg);
-    }
-    if (toprsubseg.ss == m->dummysub) {
-      tsdissolve(topleft);
-    } else {
-      tsbond(topleft, toprsubseg);
-    }
-  }
-
-  /* New vertex assignments for the rotated quadrilateral. */
-  setorg(*flipedge, botvertex);
-  setdest(*flipedge, farvertex);
-  setapex(*flipedge, leftvertex);
-  setorg(top, farvertex);
-  setdest(top, botvertex);
-  setapex(top, rightvertex);
-  if (b->verbose > 2) {
-    printf("  Edge unflip results in left ");
-    printtriangle(m, b, flipedge);
-    printf("  and right ");
-    printtriangle(m, b, &top);
-  }
-}
-
-/*****************************************************************************/
-/*                                                                           */
-/*  insertvertex()   Insert a vertex into a Delaunay triangulation,          */
-/*                   performing flips as necessary to maintain the Delaunay  */
-/*                   property.                                               */
-/*                                                                           */
-/*  The point `insertvertex' is located.  If `searchtri.tri' is not NULL,    */
-/*  the search for the containing triangle begins from `searchtri'.  If      */
-/*  `searchtri.tri' is NULL, a full point location procedure is called.      */
-/*  If `insertvertex' is found inside a triangle, the triangle is split into */
-/*  three; if `insertvertex' lies on an edge, the edge is split in two,      */
-/*  thereby splitting the two adjacent triangles into four.  Edge flips are  */
-/*  used to restore the Delaunay property.  If `insertvertex' lies on an     */
-/*  existing vertex, no action is taken, and the value DUPLICATEVERTEX is    */
-/*  returned.  On return, `searchtri' is set to a handle whose origin is the */
-/*  existing vertex.                                                         */
-/*                                                                           */
-/*  Normally, the parameter `splitseg' is set to NULL, implying that no      */
-/*  subsegment should be split.  In this case, if `insertvertex' is found to */
-/*  lie on a segment, no action is taken, and the value VIOLATINGVERTEX is   */
-/*  returned.  On return, `searchtri' is set to a handle whose primary edge  */
-/*  is the violated subsegment.                                              */
-/*                                                                           */
-/*  If the calling routine wishes to split a subsegment by inserting a       */
-/*  vertex in it, the parameter `splitseg' should be that subsegment.  In    */
-/*  this case, `searchtri' MUST be the triangle handle reached by pivoting   */
-/*  from that subsegment; no point location is done.                         */
-/*                                                                           */
-/*  `segmentflaws' and `triflaws' are flags that indicate whether or not     */
-/*  there should be checks for the creation of encroached subsegments or bad */
-/*  quality triangles.  If a newly inserted vertex encroaches upon           */
-/*  subsegments, these subsegments are added to the list of subsegments to   */
-/*  be split if `segmentflaws' is set.  If bad triangles are created, these  */
-/*  are added to the queue if `triflaws' is set.                             */
-/*                                                                           */
-/*  If a duplicate vertex or violated segment does not prevent the vertex    */
-/*  from being inserted, the return value will be ENCROACHINGVERTEX if the   */
-/*  vertex encroaches upon a subsegment (and checking is enabled), or        */
-/*  SUCCESSFULVERTEX otherwise.  In either case, `searchtri' is set to a     */
-/*  handle whose origin is the newly inserted vertex.                        */
-/*                                                                           */
-/*  insertvertex() does not use flip() for reasons of speed; some            */
-/*  information can be reused from edge flip to edge flip, like the          */
-/*  locations of subsegments.                                                */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef ANSI_DECLARATORS
-enum insertvertexresult insertvertex(struct mesh *m, struct behavior *b,
-                                     vertex newvertex, struct otri *searchtri,
-                                     struct osub *splitseg,
-                                     int segmentflaws, int triflaws)
-#else /* not ANSI_DECLARATORS */
-enum insertvertexresult insertvertex(m, b, newvertex, searchtri, splitseg,
-                                     segmentflaws, triflaws)
-struct mesh *m;
-struct behavior *b;
-vertex newvertex;
-struct otri *searchtri;
-struct osub *splitseg;
-int segmentflaws;
-int triflaws;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  struct otri horiz;
-  struct otri top;
-  struct otri botleft, botright;
-  struct otri topleft, topright;
-  struct otri newbotleft, newbotright;
-  struct otri newtopright;
-  struct otri botlcasing, botrcasing;
-  struct otri toplcasing, toprcasing;
-  struct otri testtri;
-  struct osub botlsubseg, botrsubseg;
-  struct osub toplsubseg, toprsubseg;
-  struct osub brokensubseg;
-  struct osub checksubseg;
-  struct osub rightsubseg;
-  struct osub newsubseg;
-  struct badsubseg *encroached;
-  struct flipstacker *newflip;
-  vertex first;
-  vertex leftvertex, rightvertex, botvertex, topvertex, farvertex;
-  vertex segmentorg, segmentdest;
-  REAL attrib;
-  REAL area;
-  enum insertvertexresult success;
-  enum locateresult intersect;
-  int doflip;
-  int mirrorflag;
-  int enq;
-  int i;
-  triangle ptr;                         /* Temporary variable used by sym(). */
-  subseg sptr;         /* Temporary variable used by spivot() and tspivot(). */
-
-  if (b->verbose > 1) {
-    printf("  Inserting (%.12g, %.12g).\n", newvertex[0], newvertex[1]);
-  }
-
-  if (splitseg == (struct osub *) NULL) {
-    /* Find the location of the vertex to be inserted.  Check if a good */
-    /*   starting triangle has already been provided by the caller.     */
-    if (searchtri->tri == m->dummytri) {
-      /* Find a boundary triangle. */
-      horiz.tri = m->dummytri;
-      horiz.orient = 0;
-      symself(horiz);
-      /* Search for a triangle containing `newvertex'. */
-      intersect = locate(m, b, newvertex, &horiz);
-    } else {
-      /* Start searching from the triangle provided by the caller. */
-      otricopy(*searchtri, horiz);
-      intersect = preciselocate(m, b, newvertex, &horiz, 1);
-    }
-  } else {
-    /* The calling routine provides the subsegment in which */
-    /*   the vertex is inserted.                             */
-    otricopy(*searchtri, horiz);
-    intersect = ONEDGE;
-  }
-
-  if (intersect == ONVERTEX) {
-    /* There's already a vertex there.  Return in `searchtri' a triangle */
-    /*   whose origin is the existing vertex.                            */
-    otricopy(horiz, *searchtri);
-    otricopy(horiz, m->recenttri);
-    return DUPLICATEVERTEX;
-  }
-  if ((intersect == ONEDGE) || (intersect == OUTSIDE)) {
-    /* The vertex falls on an edge or boundary. */
-    if (m->checksegments && (splitseg == (struct osub *) NULL)) {
-      /* Check whether the vertex falls on a subsegment. */
-      tspivot(horiz, brokensubseg);
-      if (brokensubseg.ss != m->dummysub) {
-        /* The vertex falls on a subsegment, and hence will not be inserted. */
-        if (segmentflaws) {
-          enq = b->nobisect != 2;
-          if (enq && (b->nobisect == 1)) {
-            /* This subsegment may be split only if it is an */
-            /*   internal boundary.                          */
-            sym(horiz, testtri);
-            enq = testtri.tri != m->dummytri;
-          }
-          if (enq) {
-            /* Add the subsegment to the list of encroached subsegments. */
-            encroached = (struct badsubseg *) poolalloc(&m->badsubsegs);
-            encroached->encsubseg = sencode(brokensubseg);
-            sorg(brokensubseg, encroached->subsegorg);
-            sdest(brokensubseg, encroached->subsegdest);
-            if (b->verbose > 2) {
-              printf(
-          "  Queueing encroached subsegment (%.12g, %.12g) (%.12g, %.12g).\n",
-                     encroached->subsegorg[0], encroached->subsegorg[1],
-                     encroached->subsegdest[0], encroached->subsegdest[1]);
-            }
-          }
-        }
-        /* Return a handle whose primary edge contains the vertex, */
-        /*   which has not been inserted.                          */
-        otricopy(horiz, *searchtri);
-        otricopy(horiz, m->recenttri);
-        return VIOLATINGVERTEX;
-      }
-    }
-
-    /* Insert the vertex on an edge, dividing one triangle into two (if */
-    /*   the edge lies on a boundary) or two triangles into four.       */
-    lprev(horiz, botright);
-    sym(botright, botrcasing);
-    sym(horiz, topright);
-    /* Is there a second triangle?  (Or does this edge lie on a boundary?) */
-    mirrorflag = topright.tri != m->dummytri;
-    if (mirrorflag) {
-      lnextself(topright);
-      sym(topright, toprcasing);
-      maketriangle(m, b, &newtopright);
-    } else {
-      /* Splitting a boundary edge increases the number of boundary edges. */
-      m->hullsize++;
-    }
-    maketriangle(m, b, &newbotright);
-
-    /* Set the vertices of changed and new triangles. */
-    org(horiz, rightvertex);
-    dest(horiz, leftvertex);
-    apex(horiz, botvertex);
-    setorg(newbotright, botvertex);
-    setdest(newbotright, rightvertex);
-    setapex(newbotright, newvertex);
-    setorg(horiz, newvertex);
-    for (i = 0; i < m->eextras; i++) {
-      /* Set the element attributes of a new triangle. */
-      setelemattribute(newbotright, i, elemattribute(botright, i));
-    }
-    if (b->vararea) {
-      /* Set the area constraint of a new triangle. */
-      setareabound(newbotright, areabound(botright));
-    }
-    if (mirrorflag) {
-      dest(topright, topvertex);
-      setorg(newtopright, rightvertex);
-      setdest(newtopright, topvertex);
-      setapex(newtopright, newvertex);
-      setorg(topright, newvertex);
-      for (i = 0; i < m->eextras; i++) {
-        /* Set the element attributes of another new triangle. */
-        setelemattribute(newtopright, i, elemattribute(topright, i));
-      }
-      if (b->vararea) {
-        /* Set the area constraint of another new triangle. */
-        setareabound(newtopright, areabound(topright));
-      }
-    }
-
-    /* There may be subsegments that need to be bonded */
-    /*   to the new triangle(s).                       */
-    if (m->checksegments) {
-      tspivot(botright, botrsubseg);
-      if (botrsubseg.ss != m->dummysub) {
-        tsdissolve(botright);
-        tsbond(newbotright, botrsubseg);
-      }
-      if (mirrorflag) {
-        tspivot(topright, toprsubseg);
-        if (toprsubseg.ss != m->dummysub) {
-          tsdissolve(topright);
-          tsbond(newtopright, toprsubseg);
-        }
-      }
-    }
-
-    /* Bond the new triangle(s) to the surrounding triangles. */
-    bond(newbotright, botrcasing);
-    lprevself(newbotright);
-    bond(newbotright, botright);
-    lprevself(newbotright);
-    if (mirrorflag) {
-      bond(newtopright, toprcasing);
-      lnextself(newtopright);
-      bond(newtopright, topright);
-      lnextself(newtopright);
-      bond(newtopright, newbotright);
-    }
-
-    if (splitseg != (struct osub *) NULL) {
-      /* Split the subsegment into two. */
-      setsdest(*splitseg, newvertex);
-      segorg(*splitseg, segmentorg);
-      segdest(*splitseg, segmentdest);
-      ssymself(*splitseg);
-      spivot(*splitseg, rightsubseg);
-      insertsubseg(m, b, &newbotright, mark(*splitseg));
-      tspivot(newbotright, newsubseg);
-      setsegorg(newsubseg, segmentorg);
-      setsegdest(newsubseg, segmentdest);
-      sbond(*splitseg, newsubseg);
-      ssymself(newsubseg);
-      sbond(newsubseg, rightsubseg);
-      ssymself(*splitseg);
-      /* Transfer the subsegment's boundary marker to the vertex */
-      /*   if required.                                          */
-      if (vertexmark(newvertex) == 0) {
-        setvertexmark(newvertex, mark(*splitseg));
-      }
-    }
-
-    if (m->checkquality) {
-      poolrestart(&m->flipstackers);
-      m->lastflip = (struct flipstacker *) poolalloc(&m->flipstackers);
-      m->lastflip->flippedtri = encode(horiz);
-      m->lastflip->prevflip = (struct flipstacker *) &insertvertex;
-    }
-
-#ifdef SELF_CHECK
-    if (counterclockwise(m, b, rightvertex, leftvertex, botvertex) < 0.0) {
-      printf("Internal error in insertvertex():\n");
-      printf(
-            "  Clockwise triangle prior to edge vertex insertion (bottom).\n");
-    }
-    if (mirrorflag) {
-      if (counterclockwise(m, b, leftvertex, rightvertex, topvertex) < 0.0) {
-        printf("Internal error in insertvertex():\n");
-        printf("  Clockwise triangle prior to edge vertex insertion (top).\n");
-      }
-      if (counterclockwise(m, b, rightvertex, topvertex, newvertex) < 0.0) {
-        printf("Internal error in insertvertex():\n");
-        printf(
-            "  Clockwise triangle after edge vertex insertion (top right).\n");
-      }
-      if (counterclockwise(m, b, topvertex, leftvertex, newvertex) < 0.0) {
-        printf("Internal error in insertvertex():\n");
-        printf(
-            "  Clockwise triangle after edge vertex insertion (top left).\n");
-      }
-    }
-    if (counterclockwise(m, b, leftvertex, botvertex, newvertex) < 0.0) {
-      printf("Internal error in insertvertex():\n");
-      printf(
-          "  Clockwise triangle after edge vertex insertion (bottom left).\n");
-    }
-    if (counterclockwise(m, b, botvertex, rightvertex, newvertex) < 0.0) {
-      printf("Internal error in insertvertex():\n");
-      printf(
-        "  Clockwise triangle after edge vertex insertion (bottom right).\n");
-    }
-#endif /* SELF_CHECK */
-    if (b->verbose > 2) {
-      printf("  Updating bottom left ");
-      printtriangle(m, b, &botright);
-      if (mirrorflag) {
-        printf("  Updating top left ");
-        printtriangle(m, b, &topright);
-        printf("  Creating top right ");
-        printtriangle(m, b, &newtopright);
-      }
-      printf("  Creating bottom right ");
-      printtriangle(m, b, &newbotright);
-    }
-
-    /* Position `horiz' on the first edge to check for */
-    /*   the Delaunay property.                        */
-    lnextself(horiz);
-  } else {
-    /* Insert the vertex in a triangle, splitting it into three. */
-    lnext(horiz, botleft);
-    lprev(horiz, botright);
-    sym(botleft, botlcasing);
-    sym(botright, botrcasing);
-    maketriangle(m, b, &newbotleft);
-    maketriangle(m, b, &newbotright);
-
-    /* Set the vertices of changed and new triangles. */
-    org(horiz, rightvertex);
-    dest(horiz, leftvertex);
-    apex(horiz, botvertex);
-    setorg(newbotleft, leftvertex);
-    setdest(newbotleft, botvertex);
-    setapex(newbotleft, newvertex);
-    setorg(newbotright, botvertex);
-    setdest(newbotright, rightvertex);
-    setapex(newbotright, newvertex);
-    setapex(horiz, newvertex);
-    for (i = 0; i < m->eextras; i++) {
-      /* Set the element attributes of the new triangles. */
-      attrib = elemattribute(horiz, i);
-      setelemattribute(newbotleft, i, attrib);
-      setelemattribute(newbotright, i, attrib);
-    }
-    if (b->vararea) {
-      /* Set the area constraint of the new triangles. */
-      area = areabound(horiz);
-      setareabound(newbotleft, area);
-      setareabound(newbotright, area);
-    }
-
-    /* There may be subsegments that need to be bonded */
-    /*   to the new triangles.                         */
-    if (m->checksegments) {
-      tspivot(botleft, botlsubseg);
-      if (botlsubseg.ss != m->dummysub) {
-        tsdissolve(botleft);
-        tsbond(newbotleft, botlsubseg);
-      }
-      tspivot(botright, botrsubseg);
-      if (botrsubseg.ss != m->dummysub) {
-        tsdissolve(botright);
-        tsbond(newbotright, botrsubseg);
-      }
-    }
-
-    /* Bond the new triangles to the surrounding triangles. */
-    bond(newbotleft, botlcasing);
-    bond(newbotright, botrcasing);
-    lnextself(newbotleft);
-    lprevself(newbotright);
-    bond(newbotleft, newbotright);
-    lnextself(newbotleft);
-    bond(botleft, newbotleft);
-    lprevself(newbotright);
-    bond(botright, newbotright);
-
-    if (m->checkquality) {
-      poolrestart(&m->flipstackers);
-      m->lastflip = (struct flipstacker *) poolalloc(&m->flipstackers);
-      m->lastflip->flippedtri = encode(horiz);
-      m->lastflip->prevflip = (struct flipstacker *) NULL;
-    }
-
-#ifdef SELF_CHECK
-    if (counterclockwise(m, b, rightvertex, leftvertex, botvertex) < 0.0) {
-      printf("Internal error in insertvertex():\n");
-      printf("  Clockwise triangle prior to vertex insertion.\n");
-    }
-    if (counterclockwise(m, b, rightvertex, leftvertex, newvertex) < 0.0) {
-      printf("Internal error in insertvertex():\n");
-      printf("  Clockwise triangle after vertex insertion (top).\n");
-    }
-    if (counterclockwise(m, b, leftvertex, botvertex, newvertex) < 0.0) {
-      printf("Internal error in insertvertex():\n");
-      printf("  Clockwise triangle after vertex insertion (left).\n");
-    }
-    if (counterclockwise(m, b, botvertex, rightvertex, newvertex) < 0.0) {
-      printf("Internal error in insertvertex():\n");
-      printf("  Clockwise triangle after vertex insertion (right).\n");
-    }
-#endif /* SELF_CHECK */
-    if (b->verbose > 2) {
-      printf("  Updating top ");
-      printtriangle(m, b, &horiz);
-      printf("  Creating left ");
-      printtriangle(m, b, &newbotleft);
-      printf("  Creating right ");
-      printtriangle(m, b, &newbotright);
-    }
-  }
-
-  /* The insertion is successful by default, unless an encroached */
-  /*   subsegment is found.                                       */
-  success = SUCCESSFULVERTEX;
-  /* Circle around the newly inserted vertex, checking each edge opposite */
-  /*   it for the Delaunay property.  Non-Delaunay edges are flipped.     */
-  /*   `horiz' is always the edge being checked.  `first' marks where to  */
-  /*   stop circling.                                                     */
-  org(horiz, first);
-  rightvertex = first;
-  dest(horiz, leftvertex);
-  /* Circle until finished. */
-  while (1) {
-    /* By default, the edge will be flipped. */
-    doflip = 1;
-
-    if (m->checksegments) {
-      /* Check for a subsegment, which cannot be flipped. */
-      tspivot(horiz, checksubseg);
-      if (checksubseg.ss != m->dummysub) {
-        /* The edge is a subsegment and cannot be flipped. */
-        doflip = 0;
-#ifndef CDT_ONLY
-        if (segmentflaws) {
-          /* Does the new vertex encroach upon this subsegment? */
-          if (checkseg4encroach(m, b, &checksubseg)) {
-            success = ENCROACHINGVERTEX;
-          }
-        }
-#endif /* not CDT_ONLY */
-      }
-    }
-
-    if (doflip) {
-      /* Check if the edge is a boundary edge. */
-      sym(horiz, top);
-      if (top.tri == m->dummytri) {
-        /* The edge is a boundary edge and cannot be flipped. */
-        doflip = 0;
-      } else {
-        /* Find the vertex on the other side of the edge. */
-        apex(top, farvertex);
-        /* In the incremental Delaunay triangulation algorithm, any of      */
-        /*   `leftvertex', `rightvertex', and `farvertex' could be vertices */
-        /*   of the triangular bounding box.  These vertices must be        */
-        /*   treated as if they are infinitely distant, even though their   */
-        /*   "coordinates" are not.                                         */
-        if ((leftvertex == m->infvertex1) || (leftvertex == m->infvertex2) ||
-            (leftvertex == m->infvertex3)) {
-          /* `leftvertex' is infinitely distant.  Check the convexity of  */
-          /*   the boundary of the triangulation.  'farvertex' might be   */
-          /*   infinite as well, but trust me, this same condition should */
-          /*   be applied.                                                */
-          doflip = counterclockwise(m, b, newvertex, rightvertex, farvertex)
-                   > 0.0;
-        } else if ((rightvertex == m->infvertex1) ||
-                   (rightvertex == m->infvertex2) ||
-                   (rightvertex == m->infvertex3)) {
-          /* `rightvertex' is infinitely distant.  Check the convexity of */
-          /*   the boundary of the triangulation.  'farvertex' might be   */
-          /*   infinite as well, but trust me, this same condition should */
-          /*   be applied.                                                */
-          doflip = counterclockwise(m, b, farvertex, leftvertex, newvertex)
-                   > 0.0;
-        } else if ((farvertex == m->infvertex1) ||
-                   (farvertex == m->infvertex2) ||
-                   (farvertex == m->infvertex3)) {
-          /* `farvertex' is infinitely distant and cannot be inside */
-          /*   the circumcircle of the triangle `horiz'.            */
-          doflip = 0;
-        } else {
-          /* Test whether the edge is locally Delaunay. */
-          doflip = incircle(m, b, leftvertex, newvertex, rightvertex,
-                            farvertex) > 0.0;
-        }
-        if (doflip) {
-          /* We made it!  Flip the edge `horiz' by rotating its containing */
-          /*   quadrilateral (the two triangles adjacent to `horiz').      */
-          /* Identify the casing of the quadrilateral. */
-          lprev(top, topleft);
-          sym(topleft, toplcasing);
-          lnext(top, topright);
-          sym(topright, toprcasing);
-          lnext(horiz, botleft);
-          sym(botleft, botlcasing);
-          lprev(horiz, botright);
-          sym(botright, botrcasing);
-          /* Rotate the quadrilateral one-quarter turn counterclockwise. */
-          bond(topleft, botlcasing);
-          bond(botleft, botrcasing);
-          bond(botright, toprcasing);
-          bond(topright, toplcasing);
-          if (m->checksegments) {
-            /* Check for subsegments and rebond them to the quadrilateral. */
-            tspivot(topleft, toplsubseg);
-            tspivot(botleft, botlsubseg);
-            tspivot(botright, botrsubseg);
-            tspivot(topright, toprsubseg);
-            if (toplsubseg.ss == m->dummysub) {
-              tsdissolve(topright);
-            } else {
-              tsbond(topright, toplsubseg);
-            }
-            if (botlsubseg.ss == m->dummysub) {
-              tsdissolve(topleft);
-            } else {
-              tsbond(topleft, botlsubseg);
-            }
-            if (botrsubseg.ss == m->dummysub) {
-              tsdissolve(botleft);
-            } else {
-              tsbond(botleft, botrsubseg);
-            }
-            if (toprsubseg.ss == m->dummysub) {
-              tsdissolve(botright);
-            } else {
-              tsbond(botright, toprsubseg);
-            }
-          }
-          /* New vertex assignments for the rotated quadrilateral. */
-          setorg(horiz, farvertex);
-          setdest(horiz, newvertex);
-          setapex(horiz, rightvertex);
-          setorg(top, newvertex);
-          setdest(top, farvertex);
-          setapex(top, leftvertex);
-          for (i = 0; i < m->eextras; i++) {
-            /* Take the average of the two triangles' attributes. */
-            attrib = 0.5 * (elemattribute(top, i) + elemattribute(horiz, i));
-            setelemattribute(top, i, attrib);
-            setelemattribute(horiz, i, attrib);
-          }
-          if (b->vararea) {
-            if ((areabound(top) <= 0.0) || (areabound(horiz) <= 0.0)) {
-              area = -1.0;
-            } else {
-              /* Take the average of the two triangles' area constraints.    */
-              /*   This prevents small area constraints from migrating a     */
-              /*   long, long way from their original location due to flips. */
-              area = 0.5 * (areabound(top) + areabound(horiz));
-            }
-            setareabound(top, area);
-            setareabound(horiz, area);
-          }
-
-          if (m->checkquality) {
-            newflip = (struct flipstacker *) poolalloc(&m->flipstackers);
-            newflip->flippedtri = encode(horiz);
-            newflip->prevflip = m->lastflip;
-            m->lastflip = newflip;
-          }
-
-#ifdef SELF_CHECK
-          if (newvertex != (vertex) NULL) {
-            if (counterclockwise(m, b, leftvertex, newvertex, rightvertex) <
-                0.0) {
-              printf("Internal error in insertvertex():\n");
-              printf("  Clockwise triangle prior to edge flip (bottom).\n");
-            }
-            /* The following test has been removed because constrainededge() */
-            /*   sometimes generates inverted triangles that insertvertex()  */
-            /*   removes.                                                    */
-/*
-            if (counterclockwise(m, b, rightvertex, farvertex, leftvertex) <
-                0.0) {
-              printf("Internal error in insertvertex():\n");
-              printf("  Clockwise triangle prior to edge flip (top).\n");
-            }
-*/
-            if (counterclockwise(m, b, farvertex, leftvertex, newvertex) <
-                0.0) {
-              printf("Internal error in insertvertex():\n");
-              printf("  Clockwise triangle after edge flip (left).\n");
-            }
-            if (counterclockwise(m, b, newvertex, rightvertex, farvertex) <
-                0.0) {
-              printf("Internal error in insertvertex():\n");
-              printf("  Clockwise triangle after edge flip (right).\n");
-            }
-          }
-#endif /* SELF_CHECK */
-          if (b->verbose > 2) {
-            printf("  Edge flip results in left ");
-            lnextself(topleft);
-            printtriangle(m, b, &topleft);
-            printf("  and right ");
-            printtriangle(m, b, &horiz);
-          }
-          /* On the next iterations, consider the two edges that were  */
-          /*   exposed (this is, are now visible to the newly inserted */
-          /*   vertex) by the edge flip.                               */
-          lprevself(horiz);
-          leftvertex = farvertex;
-        }
-      }
-    }
-    if (!doflip) {
-      /* The handle `horiz' is accepted as locally Delaunay. */
-#ifndef CDT_ONLY
-      if (triflaws) {
-        /* Check the triangle `horiz' for quality. */
-        testtriangle(m, b, &horiz);
-      }
-#endif /* not CDT_ONLY */
-      /* Look for the next edge around the newly inserted vertex. */
-      lnextself(horiz);
-      sym(horiz, testtri);
-      /* Check for finishing a complete revolution about the new vertex, or */
-      /*   falling outside  of the triangulation.  The latter will happen   */
-      /*   when a vertex is inserted at a boundary.                         */
-      if ((leftvertex == first) || (testtri.tri == m->dummytri)) {
-        /* We're done.  Return a triangle whose origin is the new vertex. */
-        lnext(horiz, *searchtri);
-        lnext(horiz, m->recenttri);
-        return success;
-      }
-      /* Finish finding the next edge around the newly inserted vertex. */
-      lnext(testtri, horiz);
-      rightvertex = leftvertex;
-      dest(horiz, leftvertex);
-    }
-  }
-}
-
-/*****************************************************************************/
-/*                                                                           */
-/*  triangulatepolygon()   Find the Delaunay triangulation of a polygon that */
-/*                         has a certain "nice" shape.  This includes the    */
-/*                         polygons that result from deletion of a vertex or */
-/*                         insertion of a segment.                           */
-/*                                                                           */
-/*  This is a conceptually difficult routine.  The starting assumption is    */
-/*  that we have a polygon with n sides.  n - 1 of these sides are currently */
-/*  represented as edges in the mesh.  One side, called the "base", need not */
-/*  be.                                                                      */
-/*                                                                           */
-/*  Inside the polygon is a structure I call a "fan", consisting of n - 1    */
-/*  triangles that share a common origin.  For each of these triangles, the  */
-/*  edge opposite the origin is one of the sides of the polygon.  The        */
-/*  primary edge of each triangle is the edge directed from the origin to    */
-/*  the destination; note that this is not the same edge that is a side of   */
-/*  the polygon.  `firstedge' is the primary edge of the first triangle.     */
-/*  From there, the triangles follow in counterclockwise order about the     */
-/*  polygon, until `lastedge', the primary edge of the last triangle.        */
-/*  `firstedge' and `lastedge' are probably connected to other triangles     */
-/*  beyond the extremes of the fan, but their identity is not important, as  */
-/*  long as the fan remains connected to them.                               */
-/*                                                                           */
-/*  Imagine the polygon oriented so that its base is at the bottom.  This    */
-/*  puts `firstedge' on the far right, and `lastedge' on the far left.       */
-/*  The right vertex of the base is the destination of `firstedge', and the  */
-/*  left vertex of the base is the apex of `lastedge'.                       */
-/*                                                                           */
-/*  The challenge now is to find the right sequence of edge flips to         */
-/*  transform the fan into a Delaunay triangulation of the polygon.  Each    */
-/*  edge flip effectively removes one triangle from the fan, committing it   */
-/*  to the polygon.  The resulting polygon has one fewer edge.  If `doflip'  */
-/*  is set, the final flip will be performed, resulting in a fan of one      */
-/*  (useless?) triangle.  If `doflip' is not set, the final flip is not      */
-/*  performed, resulting in a fan of two triangles, and an unfinished        */
-/*  triangular polygon that is not yet filled out with a single triangle.    */
-/*  On completion of the routine, `lastedge' is the last remaining triangle, */
-/*  or the leftmost of the last two.                                         */
-/*                                                                           */
-/*  Although the flips are performed in the order described above, the       */
-/*  decisions about what flips to perform are made in precisely the reverse  */
-/*  order.  The recursive triangulatepolygon() procedure makes a decision,   */
-/*  uses up to two recursive calls to triangulate the "subproblems"          */
-/*  (polygons with fewer edges), and then performs an edge flip.             */
-/*                                                                           */
-/*  The "decision" it makes is which vertex of the polygon should be         */
-/*  connected to the base.  This decision is made by testing every possible  */
-/*  vertex.  Once the best vertex is found, the two edges that connect this  */
-/*  vertex to the base become the bases for two smaller polygons.  These     */
-/*  are triangulated recursively.  Unfortunately, this approach can take     */
-/*  O(n^2) time not only in the worst case, but in many common cases.  It's  */
-/*  rarely a big deal for vertex deletion, where n is rarely larger than     */
-/*  ten, but it could be a big deal for segment insertion, especially if     */
-/*  there's a lot of long segments that each cut many triangles.  I ought to */
-/*  code a faster algorithm some day.                                        */
-/*                                                                           */
-/*  The `edgecount' parameter is the number of sides of the polygon,         */
-/*  including its base.  `triflaws' is a flag that determines whether the    */
-/*  new triangles should be tested for quality, and enqueued if they are     */
-/*  bad.                                                                     */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef ANSI_DECLARATORS
-void triangulatepolygon(struct mesh *m, struct behavior *b,
-                        struct otri *firstedge, struct otri *lastedge,
-                        int edgecount, int doflip, int triflaws)
-#else /* not ANSI_DECLARATORS */
-void triangulatepolygon(m, b, firstedge, lastedge, edgecount, doflip, triflaws)
-struct mesh *m;
-struct behavior *b;
-struct otri *firstedge;
-struct otri *lastedge;
-int edgecount;
-int doflip;
-int triflaws;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  struct otri testtri;
-  struct otri besttri;
-  struct otri tempedge;
-  vertex leftbasevertex, rightbasevertex;
-  vertex testvertex;
-  vertex bestvertex;
-  int bestnumber;
-  int i;
-  triangle ptr;   /* Temporary variable used by sym(), onext(), and oprev(). */
-
-  /* Identify the base vertices. */
-  apex(*lastedge, leftbasevertex);
-  dest(*firstedge, rightbasevertex);
-  if (b->verbose > 2) {
-    printf("  Triangulating interior polygon at edge\n");
-    printf("    (%.12g, %.12g) (%.12g, %.12g)\n", leftbasevertex[0],
-           leftbasevertex[1], rightbasevertex[0], rightbasevertex[1]);
-  }
-  /* Find the best vertex to connect the base to. */
-  onext(*firstedge, besttri);
-  dest(besttri, bestvertex);
-  otricopy(besttri, testtri);
-  bestnumber = 1;
-  for (i = 2; i <= edgecount - 2; i++) {
-    onextself(testtri);
-    dest(testtri, testvertex);
-    /* Is this a better vertex? */
-    if (incircle(m, b, leftbasevertex, rightbasevertex, bestvertex,
-                 testvertex) > 0.0) {
-      otricopy(testtri, besttri);
-      bestvertex = testvertex;
-      bestnumber = i;
-    }
-  }
-  if (b->verbose > 2) {
-    printf("    Connecting edge to (%.12g, %.12g)\n", bestvertex[0],
-           bestvertex[1]);
-  }
-  if (bestnumber > 1) {
-    /* Recursively triangulate the smaller polygon on the right. */
-    oprev(besttri, tempedge);
-    triangulatepolygon(m, b, firstedge, &tempedge, bestnumber + 1, 1,
-                       triflaws);
-  }
-  if (bestnumber < edgecount - 2) {
-    /* Recursively triangulate the smaller polygon on the left. */
-    sym(besttri, tempedge);
-    triangulatepolygon(m, b, &besttri, lastedge, edgecount - bestnumber, 1,
-                       triflaws);
-    /* Find `besttri' again; it may have been lost to edge flips. */
-    sym(tempedge, besttri);
-  }
-  if (doflip) {
-    /* Do one final edge flip. */
-    flip(m, b, &besttri);
-#ifndef CDT_ONLY
-    if (triflaws) {
-      /* Check the quality of the newly committed triangle. */
-      sym(besttri, testtri);
-      testtriangle(m, b, &testtri);
-    }
-#endif /* not CDT_ONLY */
-  }
-  /* Return the base triangle. */
-  otricopy(besttri, *lastedge);
-}
-
-/*****************************************************************************/
-/*                                                                           */
-/*  deletevertex()   Delete a vertex from a Delaunay triangulation, ensuring */
-/*                   that the triangulation remains Delaunay.                */
-/*                                                                           */
-/*  The origin of `deltri' is deleted.  The union of the triangles adjacent  */
-/*  to this vertex is a polygon, for which the Delaunay triangulation is     */
-/*  found.  Two triangles are removed from the mesh.                         */
-/*                                                                           */
-/*  Only interior vertices that do not lie on segments or boundaries may be  */
-/*  deleted.                                                                 */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifndef CDT_ONLY
-
-#ifdef ANSI_DECLARATORS
-void deletevertex(struct mesh *m, struct behavior *b, struct otri *deltri)
-#else /* not ANSI_DECLARATORS */
-void deletevertex(m, b, deltri)
-struct mesh *m;
-struct behavior *b;
-struct otri *deltri;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  struct otri countingtri;
-  struct otri firstedge, lastedge;
-  struct otri deltriright;
-  struct otri lefttri, righttri;
-  struct otri leftcasing, rightcasing;
-  struct osub leftsubseg, rightsubseg;
-  vertex delvertex;
-  vertex neworg;
-  int edgecount;
-  triangle ptr;   /* Temporary variable used by sym(), onext(), and oprev(). */
-  subseg sptr;                      /* Temporary variable used by tspivot(). */
-
-  org(*deltri, delvertex);
-  if (b->verbose > 1) {
-    printf("  Deleting (%.12g, %.12g).\n", delvertex[0], delvertex[1]);
-  }
-  vertexdealloc(m, delvertex);
-
-  /* Count the degree of the vertex being deleted. */
-  onext(*deltri, countingtri);
-  edgecount = 1;
-  while (!otriequal(*deltri, countingtri)) {
-#ifdef SELF_CHECK
-    if (countingtri.tri == m->dummytri) {
-      printf("Internal error in deletevertex():\n");
-      printf("  Attempt to delete boundary vertex.\n");
-      internalerror();
-    }
-#endif /* SELF_CHECK */
-    edgecount++;
-    onextself(countingtri);
-  }
-
-#ifdef SELF_CHECK
-  if (edgecount < 3) {
-    printf("Internal error in deletevertex():\n  Vertex has degree %d.\n",
-           edgecount);
-    internalerror();
-  }
-#endif /* SELF_CHECK */
-  if (edgecount > 3) {
-    /* Triangulate the polygon defined by the union of all triangles */
-    /*   adjacent to the vertex being deleted.  Check the quality of */
-    /*   the resulting triangles.                                    */
-    onext(*deltri, firstedge);
-    oprev(*deltri, lastedge);
-    triangulatepolygon(m, b, &firstedge, &lastedge, edgecount, 0,
-                       !b->nobisect);
-  }
-  /* Splice out two triangles. */
-  lprev(*deltri, deltriright);
-  dnext(*deltri, lefttri);
-  sym(lefttri, leftcasing);
-  oprev(deltriright, righttri);
-  sym(righttri, rightcasing);
-  bond(*deltri, leftcasing);
-  bond(deltriright, rightcasing);
-  tspivot(lefttri, leftsubseg);
-  if (leftsubseg.ss != m->dummysub) {
-    tsbond(*deltri, leftsubseg);
-  }
-  tspivot(righttri, rightsubseg);
-  if (rightsubseg.ss != m->dummysub) {
-    tsbond(deltriright, rightsubseg);
-  }
-
-  /* Set the new origin of `deltri' and check its quality. */
-  org(lefttri, neworg);
-  setorg(*deltri, neworg);
-  if (!b->nobisect) {
-    testtriangle(m, b, deltri);
-  }
-
-  /* Delete the two spliced-out triangles. */
-  triangledealloc(m, lefttri.tri);
-  triangledealloc(m, righttri.tri);
-}
-
-#endif /* not CDT_ONLY */
-
-/*****************************************************************************/
-/*                                                                           */
-/*  undovertex()   Undo the most recent vertex insertion.                    */
-/*                                                                           */
-/*  Walks through the list of transformations (flips and a vertex insertion) */
-/*  in the reverse of the order in which they were done, and undoes them.    */
-/*  The inserted vertex is removed from the triangulation and deallocated.   */
-/*  Two triangles (possibly just one) are also deallocated.                  */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifndef CDT_ONLY
-
-#ifdef ANSI_DECLARATORS
-void undovertex(struct mesh *m, struct behavior *b)
-#else /* not ANSI_DECLARATORS */
-void undovertex(m, b)
-struct mesh *m;
-struct behavior *b;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  struct otri fliptri;
-  struct otri botleft, botright, topright;
-  struct otri botlcasing, botrcasing, toprcasing;
-  struct otri gluetri;
-  struct osub botlsubseg, botrsubseg, toprsubseg;
-  vertex botvertex, rightvertex;
-  triangle ptr;                         /* Temporary variable used by sym(). */
-  subseg sptr;                      /* Temporary variable used by tspivot(). */
-
-  /* Walk through the list of transformations (flips and a vertex insertion) */
-  /*   in the reverse of the order in which they were done, and undo them.   */
-  while (m->lastflip != (struct flipstacker *) NULL) {
-    /* Find a triangle involved in the last unreversed transformation. */
-    decode(m->lastflip->flippedtri, fliptri);
-
-    /* We are reversing one of three transformations:  a trisection of one */
-    /*   triangle into three (by inserting a vertex in the triangle), a    */
-    /*   bisection of two triangles into four (by inserting a vertex in an */
-    /*   edge), or an edge flip.                                           */
-    if (m->lastflip->prevflip == (struct flipstacker *) NULL) {
-      /* Restore a triangle that was split into three triangles, */
-      /*   so it is again one triangle.                          */
-      dprev(fliptri, botleft);
-      lnextself(botleft);
-      onext(fliptri, botright);
-      lprevself(botright);
-      sym(botleft, botlcasing);
-      sym(botright, botrcasing);
-      dest(botleft, botvertex);
-
-      setapex(fliptri, botvertex);
-      lnextself(fliptri);
-      bond(fliptri, botlcasing);
-      tspivot(botleft, botlsubseg);
-      tsbond(fliptri, botlsubseg);
-      lnextself(fliptri);
-      bond(fliptri, botrcasing);
-      tspivot(botright, botrsubseg);
-      tsbond(fliptri, botrsubseg);
-
-      /* Delete the two spliced-out triangles. */
-      triangledealloc(m, botleft.tri);
-      triangledealloc(m, botright.tri);
-    } else if (m->lastflip->prevflip == (struct flipstacker *) &insertvertex) {
-      /* Restore two triangles that were split into four triangles, */
-      /*   so they are again two triangles.                         */
-      lprev(fliptri, gluetri);
-      sym(gluetri, botright);
-      lnextself(botright);
-      sym(botright, botrcasing);
-      dest(botright, rightvertex);
-
-      setorg(fliptri, rightvertex);
-      bond(gluetri, botrcasing);
-      tspivot(botright, botrsubseg);
-      tsbond(gluetri, botrsubseg);
-
-      /* Delete the spliced-out triangle. */
-      triangledealloc(m, botright.tri);
-
-      sym(fliptri, gluetri);
-      if (gluetri.tri != m->dummytri) {
-        lnextself(gluetri);
-        dnext(gluetri, topright);
-        sym(topright, toprcasing);
-
-        setorg(gluetri, rightvertex);
-        bond(gluetri, toprcasing);
-        tspivot(topright, toprsubseg);
-        tsbond(gluetri, toprsubseg);
-
-        /* Delete the spliced-out triangle. */
-        triangledealloc(m, topright.tri);
-      }
-
-      /* This is the end of the list, sneakily encoded. */
-      m->lastflip->prevflip = (struct flipstacker *) NULL;
-    } else {
-      /* Undo an edge flip. */
-      unflip(m, b, &fliptri);
-    }
-
-    /* Go on and process the next transformation. */
-    m->lastflip = m->lastflip->prevflip;
-  }
-}
-
-#endif /* not CDT_ONLY */
-
-/**                                                                         **/
-/**                                                                         **/
-/********* Mesh transformation routines end here                     *********/
-
-/********* Divide-and-conquer Delaunay triangulation begins here     *********/
-/**                                                                         **/
-/**                                                                         **/
-
-/*****************************************************************************/
-/*                                                                           */
-/*  The divide-and-conquer bounding box                                      */
-/*                                                                           */
-/*  I originally implemented the divide-and-conquer and incremental Delaunay */
-/*  triangulations using the edge-based data structure presented by Guibas   */
-/*  and Stolfi.  Switching to a triangle-based data structure doubled the    */
-/*  speed.  However, I had to think of a few extra tricks to maintain the    */
-/*  elegance of the original algorithms.                                     */
-/*                                                                           */
-/*  The "bounding box" used by my variant of the divide-and-conquer          */
-/*  algorithm uses one triangle for each edge of the convex hull of the      */
-/*  triangulation.  These bounding triangles all share a common apical       */
-/*  vertex, which is represented by NULL and which represents nothing.       */
-/*  The bounding triangles are linked in a circular fan about this NULL      */
-/*  vertex, and the edges on the convex hull of the triangulation appear     */
-/*  opposite the NULL vertex.  You might find it easiest to imagine that     */
-/*  the NULL vertex is a point in 3D space behind the center of the          */
-/*  triangulation, and that the bounding triangles form a sort of cone.      */
-/*                                                                           */
-/*  This bounding box makes it easy to represent degenerate cases.  For      */
-/*  instance, the triangulation of two vertices is a single edge.  This edge */
-/*  is represented by two bounding box triangles, one on each "side" of the  */
-/*  edge.  These triangles are also linked together in a fan about the NULL  */
-/*  vertex.                                                                  */
-/*                                                                           */
-/*  The bounding box also makes it easy to traverse the convex hull, as the  */
-/*  divide-and-conquer algorithm needs to do.                                */
-/*                                                                           */
-/*****************************************************************************/
-
-/*****************************************************************************/
-/*                                                                           */
-/*  vertexsort()   Sort an array of vertices by x-coordinate, using the      */
-/*                 y-coordinate as a secondary key.                          */
-/*                                                                           */
-/*  Uses quicksort.  Randomized O(n log n) time.  No, I did not make any of  */
-/*  the usual quicksort mistakes.                                            */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef ANSI_DECLARATORS
-void vertexsort(vertex *sortarray, int arraysize)
-#else /* not ANSI_DECLARATORS */
-void vertexsort(sortarray, arraysize)
-vertex *sortarray;
-int arraysize;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  int left, right;
-  int pivot;
-  REAL pivotx, pivoty;
-  vertex temp;
-
-  if (arraysize == 2) {
-    /* Recursive base case. */
-    if ((sortarray[0][0] > sortarray[1][0]) ||
-        ((sortarray[0][0] == sortarray[1][0]) &&
-         (sortarray[0][1] > sortarray[1][1]))) {
-      temp = sortarray[1];
-      sortarray[1] = sortarray[0];
-      sortarray[0] = temp;
-    }
-    return;
-  }
-  /* Choose a random pivot to split the array. */
-  pivot = (int) randomnation((unsigned int) arraysize);
-  pivotx = sortarray[pivot][0];
-  pivoty = sortarray[pivot][1];
-  /* Split the array. */
-  left = -1;
-  right = arraysize;
-  while (left < right) {
-    /* Search for a vertex whose x-coordinate is too large for the left. */
-    do {
-      left++;
-    } while ((left <= right) && ((sortarray[left][0] < pivotx) ||
-                                 ((sortarray[left][0] == pivotx) &&
-                                  (sortarray[left][1] < pivoty))));
-    /* Search for a vertex whose x-coordinate is too small for the right. */
-    do {
-      right--;
-    } while ((left <= right) && ((sortarray[right][0] > pivotx) ||
-                                 ((sortarray[right][0] == pivotx) &&
-                                  (sortarray[right][1] > pivoty))));
-    if (left < right) {
-      /* Swap the left and right vertices. */
-      temp = sortarray[left];
-      sortarray[left] = sortarray[right];
-      sortarray[right] = temp;
-    }
-  }
-  if (left > 1) {
-    /* Recursively sort the left subset. */
-    vertexsort(sortarray, left);
-  }
-  if (right < arraysize - 2) {
-    /* Recursively sort the right subset. */
-    vertexsort(&sortarray[right + 1], arraysize - right - 1);
-  }
-}
-
-/*****************************************************************************/
-/*                                                                           */
-/*  vertexmedian()   An order statistic algorithm, almost.  Shuffles an      */
-/*                   array of vertices so that the first `median' vertices   */
-/*                   occur lexicographically before the remaining vertices.  */
-/*                                                                           */
-/*  Uses the x-coordinate as the primary key if axis == 0; the y-coordinate  */
-/*  if axis == 1.  Very similar to the vertexsort() procedure, but runs in   */
-/*  randomized linear time.                                                  */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef ANSI_DECLARATORS
-void vertexmedian(vertex *sortarray, int arraysize, int median, int axis)
-#else /* not ANSI_DECLARATORS */
-void vertexmedian(sortarray, arraysize, median, axis)
-vertex *sortarray;
-int arraysize;
-int median;
-int axis;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  int left, right;
-  int pivot;
-  REAL pivot1, pivot2;
-  vertex temp;
-
-  if (arraysize == 2) {
-    /* Recursive base case. */
-    if ((sortarray[0][axis] > sortarray[1][axis]) ||
-        ((sortarray[0][axis] == sortarray[1][axis]) &&
-         (sortarray[0][1 - axis] > sortarray[1][1 - axis]))) {
-      temp = sortarray[1];
-      sortarray[1] = sortarray[0];
-      sortarray[0] = temp;
-    }
-    return;
-  }
-  /* Choose a random pivot to split the array. */
-  pivot = (int) randomnation((unsigned int) arraysize);
-  pivot1 = sortarray[pivot][axis];
-  pivot2 = sortarray[pivot][1 - axis];
-  /* Split the array. */
-  left = -1;
-  right = arraysize;
-  while (left < right) {
-    /* Search for a vertex whose x-coordinate is too large for the left. */
-    do {
-      left++;
-    } while ((left <= right) && ((sortarray[left][axis] < pivot1) ||
-                                 ((sortarray[left][axis] == pivot1) &&
-                                  (sortarray[left][1 - axis] < pivot2))));
-    /* Search for a vertex whose x-coordinate is too small for the right. */
-    do {
-      right--;
-    } while ((left <= right) && ((sortarray[right][axis] > pivot1) ||
-                                 ((sortarray[right][axis] == pivot1) &&
-                                  (sortarray[right][1 - axis] > pivot2))));
-    if (left < right) {
-      /* Swap the left and right vertices. */
-      temp = sortarray[left];
-      sortarray[left] = sortarray[right];
-      sortarray[right] = temp;
-    }
-  }
-  /* Unlike in vertexsort(), at most one of the following */
-  /*   conditionals is true.                             */
-  if (left > median) {
-    /* Recursively shuffle the left subset. */
-    vertexmedian(sortarray, left, median, axis);
-  }
-  if (right < median - 1) {
-    /* Recursively shuffle the right subset. */
-    vertexmedian(&sortarray[right + 1], arraysize - right - 1,
-                 median - right - 1, axis);
-  }
-}
-
-/*****************************************************************************/
-/*                                                                           */
-/*  alternateaxes()   Sorts the vertices as appropriate for the divide-and-  */
-/*                    conquer algorithm with alternating cuts.               */
-/*                                                                           */
-/*  Partitions by x-coordinate if axis == 0; by y-coordinate if axis == 1.   */
-/*  For the base case, subsets containing only two or three vertices are     */
-/*  always sorted by x-coordinate.                                           */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef ANSI_DECLARATORS
-void alternateaxes(vertex *sortarray, int arraysize, int axis)
-#else /* not ANSI_DECLARATORS */
-void alternateaxes(sortarray, arraysize, axis)
-vertex *sortarray;
-int arraysize;
-int axis;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  int divider;
-
-  divider = arraysize >> 1;
-  if (arraysize <= 3) {
-    /* Recursive base case:  subsets of two or three vertices will be    */
-    /*   handled specially, and should always be sorted by x-coordinate. */
-    axis = 0;
-  }
-  /* Partition with a horizontal or vertical cut. */
-  vertexmedian(sortarray, arraysize, divider, axis);
-  /* Recursively partition the subsets with a cross cut. */
-  if (arraysize - divider >= 2) {
-    if (divider >= 2) {
-      alternateaxes(sortarray, divider, 1 - axis);
-    }
-    alternateaxes(&sortarray[divider], arraysize - divider, 1 - axis);
-  }
-}
-
-/*****************************************************************************/
-/*                                                                           */
-/*  mergehulls()   Merge two adjacent Delaunay triangulations into a         */
-/*                 single Delaunay triangulation.                            */
-/*                                                                           */
-/*  This is similar to the algorithm given by Guibas and Stolfi, but uses    */
-/*  a triangle-based, rather than edge-based, data structure.                */
-/*                                                                           */
-/*  The algorithm walks up the gap between the two triangulations, knitting  */
-/*  them together.  As they are merged, some of their bounding triangles     */
-/*  are converted into real triangles of the triangulation.  The procedure   */
-/*  pulls each hull's bounding triangles apart, then knits them together     */
-/*  like the teeth of two gears.  The Delaunay property determines, at each  */
-/*  step, whether the next "tooth" is a bounding triangle of the left hull   */
-/*  or the right.  When a bounding triangle becomes real, its apex is        */
-/*  changed from NULL to a real vertex.                                      */
-/*                                                                           */
-/*  Only two new triangles need to be allocated.  These become new bounding  */
-/*  triangles at the top and bottom of the seam.  They are used to connect   */
-/*  the remaining bounding triangles (those that have not been converted     */
-/*  into real triangles) into a single fan.                                  */
-/*                                                                           */
-/*  On entry, `farleft' and `innerleft' are bounding triangles of the left   */
-/*  triangulation.  The origin of `farleft' is the leftmost vertex, and      */
-/*  the destination of `innerleft' is the rightmost vertex of the            */
-/*  triangulation.  Similarly, `innerright' and `farright' are bounding      */
-/*  triangles of the right triangulation.  The origin of `innerright' and    */
-/*  destination of `farright' are the leftmost and rightmost vertices.       */
-/*                                                                           */
-/*  On completion, the origin of `farleft' is the leftmost vertex of the     */
-/*  merged triangulation, and the destination of `farright' is the rightmost */
-/*  vertex.                                                                  */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef ANSI_DECLARATORS
-void mergehulls(struct mesh *m, struct behavior *b, struct otri *farleft,
-                struct otri *innerleft, struct otri *innerright,
-                struct otri *farright, int axis)
-#else /* not ANSI_DECLARATORS */
-void mergehulls(m, b, farleft, innerleft, innerright, farright, axis)
-struct mesh *m;
-struct behavior *b;
-struct otri *farleft;
-struct otri *innerleft;
-struct otri *innerright;
-struct otri *farright;
-int axis;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  struct otri leftcand, rightcand;
-  struct otri baseedge;
-  struct otri nextedge;
-  struct otri sidecasing, topcasing, outercasing;
-  struct otri checkedge;
-  vertex innerleftdest;
-  vertex innerrightorg;
-  vertex innerleftapex, innerrightapex;
-  vertex farleftpt, farrightpt;
-  vertex farleftapex, farrightapex;
-  vertex lowerleft, lowerright;
-  vertex upperleft, upperright;
-  vertex nextapex;
-  vertex checkvertex;
-  int changemade;
-  int badedge;
-  int leftfinished, rightfinished;
-  triangle ptr;                         /* Temporary variable used by sym(). */
-
-  dest(*innerleft, innerleftdest);
-  apex(*innerleft, innerleftapex);
-  org(*innerright, innerrightorg);
-  apex(*innerright, innerrightapex);
-  /* Special treatment for horizontal cuts. */
-  if (b->dwyer && (axis == 1)) {
-    org(*farleft, farleftpt);
-    apex(*farleft, farleftapex);
-    dest(*farright, farrightpt);
-    apex(*farright, farrightapex);
-    /* The pointers to the extremal vertices are shifted to point to the */
-    /*   topmost and bottommost vertex of each hull, rather than the     */
-    /*   leftmost and rightmost vertices.                                */
-    while (farleftapex[1] < farleftpt[1]) {
-      lnextself(*farleft);
-      symself(*farleft);
-      farleftpt = farleftapex;
-      apex(*farleft, farleftapex);
-    }
-    sym(*innerleft, checkedge);
-    apex(checkedge, checkvertex);
-    while (checkvertex[1] > innerleftdest[1]) {
-      lnext(checkedge, *innerleft);
-      innerleftapex = innerleftdest;
-      innerleftdest = checkvertex;
-      sym(*innerleft, checkedge);
-      apex(checkedge, checkvertex);
-    }
-    while (innerrightapex[1] < innerrightorg[1]) {
-      lnextself(*innerright);
-      symself(*innerright);
-      innerrightorg = innerrightapex;
-      apex(*innerright, innerrightapex);
-    }
-    sym(*farright, checkedge);
-    apex(checkedge, checkvertex);
-    while (checkvertex[1] > farrightpt[1]) {
-      lnext(checkedge, *farright);
-      farrightapex = farrightpt;
-      farrightpt = checkvertex;
-      sym(*farright, checkedge);
-      apex(checkedge, checkvertex);
-    }
-  }
-  /* Find a line tangent to and below both hulls. */
-  do {
-    changemade = 0;
-    /* Make innerleftdest the "bottommost" vertex of the left hull. */
-    if (counterclockwise(m, b, innerleftdest, innerleftapex, innerrightorg) >
-        0.0) {
-      lprevself(*innerleft);
-      symself(*innerleft);
-      innerleftdest = innerleftapex;
-      apex(*innerleft, innerleftapex);
-      changemade = 1;
-    }
-    /* Make innerrightorg the "bottommost" vertex of the right hull. */
-    if (counterclockwise(m, b, innerrightapex, innerrightorg, innerleftdest) >
-        0.0) {
-      lnextself(*innerright);
-      symself(*innerright);
-      innerrightorg = innerrightapex;
-      apex(*innerright, innerrightapex);
-      changemade = 1;
-    }
-  } while (changemade);
-  /* Find the two candidates to be the next "gear tooth." */
-  sym(*innerleft, leftcand);
-  sym(*innerright, rightcand);
-  /* Create the bottom new bounding triangle. */
-  maketriangle(m, b, &baseedge);
-  /* Connect it to the bounding boxes of the left and right triangulations. */
-  bond(baseedge, *innerleft);
-  lnextself(baseedge);
-  bond(baseedge, *innerright);
-  lnextself(baseedge);
-  setorg(baseedge, innerrightorg);
-  setdest(baseedge, innerleftdest);
-  /* Apex is intentionally left NULL. */
-  if (b->verbose > 2) {
-    printf("  Creating base bounding ");
-    printtriangle(m, b, &baseedge);
-  }
-  /* Fix the extreme triangles if necessary. */
-  org(*farleft, farleftpt);
-  if (innerleftdest == farleftpt) {
-    lnext(baseedge, *farleft);
-  }
-  dest(*farright, farrightpt);
-  if (innerrightorg == farrightpt) {
-    lprev(baseedge, *farright);
-  }
-  /* The vertices of the current knitting edge. */
-  lowerleft = innerleftdest;
-  lowerright = innerrightorg;
-  /* The candidate vertices for knitting. */
-  apex(leftcand, upperleft);
-  apex(rightcand, upperright);
-  /* Walk up the gap between the two triangulations, knitting them together. */
-  while (1) {
-    /* Have we reached the top?  (This isn't quite the right question,       */
-    /*   because even though the left triangulation might seem finished now, */
-    /*   moving up on the right triangulation might reveal a new vertex of   */
-    /*   the left triangulation.  And vice-versa.)                           */
-    leftfinished = counterclockwise(m, b, upperleft, lowerleft, lowerright) <=
-                   0.0;
-    rightfinished = counterclockwise(m, b, upperright, lowerleft, lowerright)
-                 <= 0.0;
-    if (leftfinished && rightfinished) {
-      /* Create the top new bounding triangle. */
-      maketriangle(m, b, &nextedge);
-      setorg(nextedge, lowerleft);
-      setdest(nextedge, lowerright);
-      /* Apex is intentionally left NULL. */
-      /* Connect it to the bounding boxes of the two triangulations. */
-      bond(nextedge, baseedge);
-      lnextself(nextedge);
-      bond(nextedge, rightcand);
-      lnextself(nextedge);
-      bond(nextedge, leftcand);
-      if (b->verbose > 2) {
-        printf("  Creating top bounding ");
-        printtriangle(m, b, &nextedge);
-      }
-      /* Special treatment for horizontal cuts. */
-      if (b->dwyer && (axis == 1)) {
-        org(*farleft, farleftpt);
-        apex(*farleft, farleftapex);
-        dest(*farright, farrightpt);
-        apex(*farright, farrightapex);
-        sym(*farleft, checkedge);
-        apex(checkedge, checkvertex);
-        /* The pointers to the extremal vertices are restored to the  */
-        /*   leftmost and rightmost vertices (rather than topmost and */
-        /*   bottommost).                                             */
-        while (checkvertex[0] < farleftpt[0]) {
-          lprev(checkedge, *farleft);
-          farleftapex = farleftpt;
-          farleftpt = checkvertex;
-          sym(*farleft, checkedge);
-          apex(checkedge, checkvertex);
-        }
-        while (farrightapex[0] > farrightpt[0]) {
-          lprevself(*farright);
-          symself(*farright);
-          farrightpt = farrightapex;
-          apex(*farright, farrightapex);
-        }
-      }
-      return;
-    }
-    /* Consider eliminating edges from the left triangulation. */
-    if (!leftfinished) {
-      /* What vertex would be exposed if an edge were deleted? */
-      lprev(leftcand, nextedge);
-      symself(nextedge);
-      apex(nextedge, nextapex);
-      /* If nextapex is NULL, then no vertex would be exposed; the */
-      /*   triangulation would have been eaten right through.      */
-      if (nextapex != (vertex) NULL) {
-        /* Check whether the edge is Delaunay. */
-        badedge = incircle(m, b, lowerleft, lowerright, upperleft, nextapex) >
-                  0.0;
-        while (badedge) {
-          /* Eliminate the edge with an edge flip.  As a result, the    */
-          /*   left triangulation will have one more boundary triangle. */
-          lnextself(nextedge);
-          sym(nextedge, topcasing);
-          lnextself(nextedge);
-          sym(nextedge, sidecasing);
-          bond(nextedge, topcasing);
-          bond(leftcand, sidecasing);
-          lnextself(leftcand);
-          sym(leftcand, outercasing);
-          lprevself(nextedge);
-          bond(nextedge, outercasing);
-          /* Correct the vertices to reflect the edge flip. */
-          setorg(leftcand, lowerleft);
-          setdest(leftcand, NULL);
-          setapex(leftcand, nextapex);
-          setorg(nextedge, NULL);
-          setdest(nextedge, upperleft);
-          setapex(nextedge, nextapex);
-          /* Consider the newly exposed vertex. */
-          upperleft = nextapex;
-          /* What vertex would be exposed if another edge were deleted? */
-          otricopy(sidecasing, nextedge);
-          apex(nextedge, nextapex);
-          if (nextapex != (vertex) NULL) {
-            /* Check whether the edge is Delaunay. */
-            badedge = incircle(m, b, lowerleft, lowerright, upperleft,
-                               nextapex) > 0.0;
-          } else {
-            /* Avoid eating right through the triangulation. */
-            badedge = 0;
-          }
-        }
-      }
-    }
-    /* Consider eliminating edges from the right triangulation. */
-    if (!rightfinished) {
-      /* What vertex would be exposed if an edge were deleted? */
-      lnext(rightcand, nextedge);
-      symself(nextedge);
-      apex(nextedge, nextapex);
-      /* If nextapex is NULL, then no vertex would be exposed; the */
-      /*   triangulation would have been eaten right through.      */
-      if (nextapex != (vertex) NULL) {
-        /* Check whether the edge is Delaunay. */
-        badedge = incircle(m, b, lowerleft, lowerright, upperright, nextapex) >
-                  0.0;
-        while (badedge) {
-          /* Eliminate the edge with an edge flip.  As a result, the     */
-          /*   right triangulation will have one more boundary triangle. */
-          lprevself(nextedge);
-          sym(nextedge, topcasing);
-          lprevself(nextedge);
-          sym(nextedge, sidecasing);
-          bond(nextedge, topcasing);
-          bond(rightcand, sidecasing);
-          lprevself(rightcand);
-          sym(rightcand, outercasing);
-          lnextself(nextedge);
-          bond(nextedge, outercasing);
-          /* Correct the vertices to reflect the edge flip. */
-          setorg(rightcand, NULL);
-          setdest(rightcand, lowerright);
-          setapex(rightcand, nextapex);
-          setorg(nextedge, upperright);
-          setdest(nextedge, NULL);
-          setapex(nextedge, nextapex);
-          /* Consider the newly exposed vertex. */
-          upperright = nextapex;
-          /* What vertex would be exposed if another edge were deleted? */
-          otricopy(sidecasing, nextedge);
-          apex(nextedge, nextapex);
-          if (nextapex != (vertex) NULL) {
-            /* Check whether the edge is Delaunay. */
-            badedge = incircle(m, b, lowerleft, lowerright, upperright,
-                               nextapex) > 0.0;
-          } else {
-            /* Avoid eating right through the triangulation. */
-            badedge = 0;
-          }
-        }
-      }
-    }
-    if (leftfinished || (!rightfinished &&
-           (incircle(m, b, upperleft, lowerleft, lowerright, upperright) >
-            0.0))) {
-      /* Knit the triangulations, adding an edge from `lowerleft' */
-      /*   to `upperright'.                                       */
-      bond(baseedge, rightcand);
-      lprev(rightcand, baseedge);
-      setdest(baseedge, lowerleft);
-      lowerright = upperright;
-      sym(baseedge, rightcand);
-      apex(rightcand, upperright);
-    } else {
-      /* Knit the triangulations, adding an edge from `upperleft' */
-      /*   to `lowerright'.                                       */
-      bond(baseedge, leftcand);
-      lnext(leftcand, baseedge);
-      setorg(baseedge, lowerright);
-      lowerleft = upperleft;
-      sym(baseedge, leftcand);
-      apex(leftcand, upperleft);
-    }
-    if (b->verbose > 2) {
-      printf("  Connecting ");
-      printtriangle(m, b, &baseedge);
-    }
-  }
-}
-
-/*****************************************************************************/
-/*                                                                           */
-/*  divconqrecurse()   Recursively form a Delaunay triangulation by the      */
-/*                     divide-and-conquer method.                            */
-/*                                                                           */
-/*  Recursively breaks down the problem into smaller pieces, which are       */
-/*  knitted together by mergehulls().  The base cases (problems of two or    */
-/*  three vertices) are handled specially here.                              */
-/*                                                                           */
-/*  On completion, `farleft' and `farright' are bounding triangles such that */
-/*  the origin of `farleft' is the leftmost vertex (breaking ties by         */
-/*  choosing the highest leftmost vertex), and the destination of            */
-/*  `farright' is the rightmost vertex (breaking ties by choosing the        */
-/*  lowest rightmost vertex).                                                */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef ANSI_DECLARATORS
-void divconqrecurse(struct mesh *m, struct behavior *b, vertex *sortarray,
-                    int vertices, int axis,
-                    struct otri *farleft, struct otri *farright)
-#else /* not ANSI_DECLARATORS */
-void divconqrecurse(m, b, sortarray, vertices, axis, farleft, farright)
-struct mesh *m;
-struct behavior *b;
-vertex *sortarray;
-int vertices;
-int axis;
-struct otri *farleft;
-struct otri *farright;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  struct otri midtri, tri1, tri2, tri3;
-  struct otri innerleft, innerright;
-  REAL area;
-  int divider;
-
-  if (b->verbose > 2) {
-    printf("  Triangulating %d vertices.\n", vertices);
-  }
-  if (vertices == 2) {
-    /* The triangulation of two vertices is an edge.  An edge is */
-    /*   represented by two bounding triangles.                  */
-    maketriangle(m, b, farleft);
-    setorg(*farleft, sortarray[0]);
-    setdest(*farleft, sortarray[1]);
-    /* The apex is intentionally left NULL. */
-    maketriangle(m, b, farright);
-    setorg(*farright, sortarray[1]);
-    setdest(*farright, sortarray[0]);
-    /* The apex is intentionally left NULL. */
-    bond(*farleft, *farright);
-    lprevself(*farleft);
-    lnextself(*farright);
-    bond(*farleft, *farright);
-    lprevself(*farleft);
-    lnextself(*farright);
-    bond(*farleft, *farright);
-    if (b->verbose > 2) {
-      printf("  Creating ");
-      printtriangle(m, b, farleft);
-      printf("  Creating ");
-      printtriangle(m, b, farright);
-    }
-    /* Ensure that the origin of `farleft' is sortarray[0]. */
-    lprev(*farright, *farleft);
-    return;
-  } else if (vertices == 3) {
-    /* The triangulation of three vertices is either a triangle (with */
-    /*   three bounding triangles) or two edges (with four bounding   */
-    /*   triangles).  In either case, four triangles are created.     */
-    maketriangle(m, b, &midtri);
-    maketriangle(m, b, &tri1);
-    maketriangle(m, b, &tri2);
-    maketriangle(m, b, &tri3);
-    area = counterclockwise(m, b, sortarray[0], sortarray[1], sortarray[2]);
-    if (area == 0.0) {
-      /* Three collinear vertices; the triangulation is two edges. */
-      setorg(midtri, sortarray[0]);
-      setdest(midtri, sortarray[1]);
-      setorg(tri1, sortarray[1]);
-      setdest(tri1, sortarray[0]);
-      setorg(tri2, sortarray[2]);
-      setdest(tri2, sortarray[1]);
-      setorg(tri3, sortarray[1]);
-      setdest(tri3, sortarray[2]);
-      /* All apices are intentionally left NULL. */
-      bond(midtri, tri1);
-      bond(tri2, tri3);
-      lnextself(midtri);
-      lprevself(tri1);
-      lnextself(tri2);
-      lprevself(tri3);
-      bond(midtri, tri3);
-      bond(tri1, tri2);
-      lnextself(midtri);
-      lprevself(tri1);
-      lnextself(tri2);
-      lprevself(tri3);
-      bond(midtri, tri1);
-      bond(tri2, tri3);
-      /* Ensure that the origin of `farleft' is sortarray[0]. */
-      otricopy(tri1, *farleft);
-      /* Ensure that the destination of `farright' is sortarray[2]. */
-      otricopy(tri2, *farright);
-    } else {
-      /* The three vertices are not collinear; the triangulation is one */
-      /*   triangle, namely `midtri'.                                   */
-      setorg(midtri, sortarray[0]);
-      setdest(tri1, sortarray[0]);
-      setorg(tri3, sortarray[0]);
-      /* Apices of tri1, tri2, and tri3 are left NULL. */
-      if (area > 0.0) {
-        /* The vertices are in counterclockwise order. */
-        setdest(midtri, sortarray[1]);
-        setorg(tri1, sortarray[1]);
-        setdest(tri2, sortarray[1]);
-        setapex(midtri, sortarray[2]);
-        setorg(tri2, sortarray[2]);
-        setdest(tri3, sortarray[2]);
-      } else {
-        /* The vertices are in clockwise order. */
-        setdest(midtri, sortarray[2]);
-        setorg(tri1, sortarray[2]);
-        setdest(tri2, sortarray[2]);
-        setapex(midtri, sortarray[1]);
-        setorg(tri2, sortarray[1]);
-        setdest(tri3, sortarray[1]);
-      }
-      /* The topology does not depend on how the vertices are ordered. */
-      bond(midtri, tri1);
-      lnextself(midtri);
-      bond(midtri, tri2);
-      lnextself(midtri);
-      bond(midtri, tri3);
-      lprevself(tri1);
-      lnextself(tri2);
-      bond(tri1, tri2);
-      lprevself(tri1);
-      lprevself(tri3);
-      bond(tri1, tri3);
-      lnextself(tri2);
-      lprevself(tri3);
-      bond(tri2, tri3);
-      /* Ensure that the origin of `farleft' is sortarray[0]. */
-      otricopy(tri1, *farleft);
-      /* Ensure that the destination of `farright' is sortarray[2]. */
-      if (area > 0.0) {
-        otricopy(tri2, *farright);
-      } else {
-        lnext(*farleft, *farright);
-      }
-    }
-    if (b->verbose > 2) {
-      printf("  Creating ");
-      printtriangle(m, b, &midtri);
-      printf("  Creating ");
-      printtriangle(m, b, &tri1);
-      printf("  Creating ");
-      printtriangle(m, b, &tri2);
-      printf("  Creating ");
-      printtriangle(m, b, &tri3);
-    }
-    return;
-  } else {
-    /* Split the vertices in half. */
-    divider = vertices >> 1;
-    /* Recursively triangulate each half. */
-    divconqrecurse(m, b, sortarray, divider, 1 - axis, farleft, &innerleft);
-    divconqrecurse(m, b, &sortarray[divider], vertices - divider, 1 - axis,
-                   &innerright, farright);
-    if (b->verbose > 1) {
-      printf("  Joining triangulations with %d and %d vertices.\n", divider,
-             vertices - divider);
-    }
-    /* Merge the two triangulations into one. */
-    mergehulls(m, b, farleft, &innerleft, &innerright, farright, axis);
-  }
-}
-
-#ifdef ANSI_DECLARATORS
-long removeghosts(struct mesh *m, struct behavior *b, struct otri *startghost)
-#else /* not ANSI_DECLARATORS */
-long removeghosts(m, b, startghost)
-struct mesh *m;
-struct behavior *b;
-struct otri *startghost;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  struct otri searchedge;
-  struct otri dissolveedge;
-  struct otri deadtriangle;
-  vertex markorg;
-  long hullsize;
-  triangle ptr;                         /* Temporary variable used by sym(). */
-
-  if (b->verbose) {
-    printf("  Removing ghost triangles.\n");
-  }
-  /* Find an edge on the convex hull to start point location from. */
-  lprev(*startghost, searchedge);
-  symself(searchedge);
-  m->dummytri[0] = encode(searchedge);
-  /* Remove the bounding box and count the convex hull edges. */
-  otricopy(*startghost, dissolveedge);
-  hullsize = 0;
-  do {
-    hullsize++;
-    lnext(dissolveedge, deadtriangle);
-    lprevself(dissolveedge);
-    symself(dissolveedge);
-    /* If no PSLG is involved, set the boundary markers of all the vertices */
-    /*   on the convex hull.  If a PSLG is used, this step is done later.   */
-    if (!b->poly) {
-      /* Watch out for the case where all the input vertices are collinear. */
-      if (dissolveedge.tri != m->dummytri) {
-        org(dissolveedge, markorg);
-        if (vertexmark(markorg) == 0) {
-          setvertexmark(markorg, 1);
-        }
-      }
-    }
-    /* Remove a bounding triangle from a convex hull triangle. */
-    dissolve(dissolveedge);
-    /* Find the next bounding triangle. */
-    sym(deadtriangle, dissolveedge);
-    /* Delete the bounding triangle. */
-    triangledealloc(m, deadtriangle.tri);
-  } while (!otriequal(dissolveedge, *startghost));
-  return hullsize;
-}
-
-/*****************************************************************************/
-/*                                                                           */
-/*  divconqdelaunay()   Form a Delaunay triangulation by the divide-and-     */
-/*                      conquer method.                                      */
-/*                                                                           */
-/*  Sorts the vertices, calls a recursive procedure to triangulate them, and */
-/*  removes the bounding box, setting boundary markers as appropriate.       */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef ANSI_DECLARATORS
-long divconqdelaunay(struct mesh *m, struct behavior *b)
-#else /* not ANSI_DECLARATORS */
-long divconqdelaunay(m, b)
-struct mesh *m;
-struct behavior *b;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  vertex *sortarray;
-  struct otri hullleft, hullright;
-  int divider;
-  int i, j;
-
-  if (b->verbose) {
-    printf("  Sorting vertices.\n");
-  }
-
-  /* Allocate an array of pointers to vertices for sorting. */
-  sortarray = (vertex *) trimalloc(m->invertices * (int) sizeof(vertex));
-  traversalinit(&m->vertices);
-  for (i = 0; i < m->invertices; i++) {
-    sortarray[i] = vertextraverse(m);
-  }
-  /* Sort the vertices. */
-  vertexsort(sortarray, m->invertices);
-  /* Discard duplicate vertices, which can really mess up the algorithm. */
-  i = 0;
-  for (j = 1; j < m->invertices; j++) {
-    if ((sortarray[i][0] == sortarray[j][0])
-        && (sortarray[i][1] == sortarray[j][1])) {
-      if (!b->quiet) {
-        printf(
-"Warning:  A duplicate vertex at (%.12g, %.12g) appeared and was ignored.\n",
-               sortarray[j][0], sortarray[j][1]);
-      }
-      setvertextype(sortarray[j], UNDEADVERTEX);
-      m->undeads++;
-    } else {
-      i++;
-      sortarray[i] = sortarray[j];
-    }
-  }
-  i++;
-  if (b->dwyer) {
-    /* Re-sort the array of vertices to accommodate alternating cuts. */
-    divider = i >> 1;
-    if (i - divider >= 2) {
-      if (divider >= 2) {
-        alternateaxes(sortarray, divider, 1);
-      }
-      alternateaxes(&sortarray[divider], i - divider, 1);
-    }
-  }
-
-  if (b->verbose) {
-    printf("  Forming triangulation.\n");
-  }
-
-  /* Form the Delaunay triangulation. */
-  divconqrecurse(m, b, sortarray, i, 0, &hullleft, &hullright);
-  trifree((VOID *) sortarray);
-
-  return removeghosts(m, b, &hullleft);
-}
-
-/**                                                                         **/
-/**                                                                         **/
-/********* Divide-and-conquer Delaunay triangulation ends here       *********/
-
-/********* Incremental Delaunay triangulation begins here            *********/
-/**                                                                         **/
-/**                                                                         **/
-
-/*****************************************************************************/
-/*                                                                           */
-/*  boundingbox()   Form an "infinite" bounding triangle to insert vertices  */
-/*                  into.                                                    */
-/*                                                                           */
-/*  The vertices at "infinity" are assigned finite coordinates, which are    */
-/*  used by the point location routines, but (mostly) ignored by the         */
-/*  Delaunay edge flip routines.                                             */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifndef REDUCED
-
-#ifdef ANSI_DECLARATORS
-void boundingbox(struct mesh *m, struct behavior *b)
-#else /* not ANSI_DECLARATORS */
-void boundingbox(m, b)
-struct mesh *m;
-struct behavior *b;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  struct otri inftri;          /* Handle for the triangular bounding box. */
-  REAL width;
-
-  if (b->verbose) {
-    printf("  Creating triangular bounding box.\n");
-  }
-  /* Find the width (or height, whichever is larger) of the triangulation. */
-  width = m->xmax - m->xmin;
-  if (m->ymax - m->ymin > width) {
-    width = m->ymax - m->ymin;
-  }
-  if (width == 0.0) {
-    width = 1.0;
-  }
-  /* Create the vertices of the bounding box. */
-  m->infvertex1 = (vertex) trimalloc(m->vertices.itembytes);
-  m->infvertex2 = (vertex) trimalloc(m->vertices.itembytes);
-  m->infvertex3 = (vertex) trimalloc(m->vertices.itembytes);
-  m->infvertex1[0] = m->xmin - 50.0 * width;
-  m->infvertex1[1] = m->ymin - 40.0 * width;
-  m->infvertex2[0] = m->xmax + 50.0 * width;
-  m->infvertex2[1] = m->ymin - 40.0 * width;
-  m->infvertex3[0] = 0.5 * (m->xmin + m->xmax);
-  m->infvertex3[1] = m->ymax + 60.0 * width;
-
-  /* Create the bounding box. */
-  maketriangle(m, b, &inftri);
-  setorg(inftri, m->infvertex1);
-  setdest(inftri, m->infvertex2);
-  setapex(inftri, m->infvertex3);
-  /* Link dummytri to the bounding box so we can always find an */
-  /*   edge to begin searching (point location) from.           */
-  m->dummytri[0] = (triangle) inftri.tri;
-  if (b->verbose > 2) {
-    printf("  Creating ");
-    printtriangle(m, b, &inftri);
-  }
-}
-
-#endif /* not REDUCED */
-
-/*****************************************************************************/
-/*                                                                           */
-/*  removebox()   Remove the "infinite" bounding triangle, setting boundary  */
-/*                markers as appropriate.                                    */
-/*                                                                           */
-/*  The triangular bounding box has three boundary triangles (one for each   */
-/*  side of the bounding box), and a bunch of triangles fanning out from     */
-/*  the three bounding box vertices (one triangle for each edge of the       */
-/*  convex hull of the inner mesh).  This routine removes these triangles.   */
-/*                                                                           */
-/*  Returns the number of edges on the convex hull of the triangulation.     */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifndef REDUCED
-
-#ifdef ANSI_DECLARATORS
-long removebox(struct mesh *m, struct behavior *b)
-#else /* not ANSI_DECLARATORS */
-long removebox(m, b)
-struct mesh *m;
-struct behavior *b;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  struct otri deadtriangle;
-  struct otri searchedge;
-  struct otri checkedge;
-  struct otri nextedge, finaledge, dissolveedge;
-  vertex markorg;
-  long hullsize;
-  triangle ptr;                         /* Temporary variable used by sym(). */
-
-  if (b->verbose) {
-    printf("  Removing triangular bounding box.\n");
-  }
-  /* Find a boundary triangle. */
-  nextedge.tri = m->dummytri;
-  nextedge.orient = 0;
-  symself(nextedge);
-  /* Mark a place to stop. */
-  lprev(nextedge, finaledge);
-  lnextself(nextedge);
-  symself(nextedge);
-  /* Find a triangle (on the boundary of the vertex set) that isn't */
-  /*   a bounding box triangle.                                     */
-  lprev(nextedge, searchedge);
-  symself(searchedge);
-  /* Check whether nextedge is another boundary triangle */
-  /*   adjacent to the first one.                        */
-  lnext(nextedge, checkedge);
-  symself(checkedge);
-  if (checkedge.tri == m->dummytri) {
-    /* Go on to the next triangle.  There are only three boundary   */
-    /*   triangles, and this next triangle cannot be the third one, */
-    /*   so it's safe to stop here.                                 */
-    lprevself(searchedge);
-    symself(searchedge);
-  }
-  /* Find a new boundary edge to search from, as the current search */
-  /*   edge lies on a bounding box triangle and will be deleted.    */
-  m->dummytri[0] = encode(searchedge);
-  hullsize = -2l;
-  while (!otriequal(nextedge, finaledge)) {
-    hullsize++;
-    lprev(nextedge, dissolveedge);
-    symself(dissolveedge);
-    /* If not using a PSLG, the vertices should be marked now. */
-    /*   (If using a PSLG, markhull() will do the job.)        */
-    if (!b->poly) {
-      /* Be careful!  One must check for the case where all the input     */
-      /*   vertices are collinear, and thus all the triangles are part of */
-      /*   the bounding box.  Otherwise, the setvertexmark() call below   */
-      /*   will cause a bad pointer reference.                            */
-      if (dissolveedge.tri != m->dummytri) {
-        org(dissolveedge, markorg);
-        if (vertexmark(markorg) == 0) {
-          setvertexmark(markorg, 1);
-        }
-      }
-    }
-    /* Disconnect the bounding box triangle from the mesh triangle. */
-    dissolve(dissolveedge);
-    lnext(nextedge, deadtriangle);
-    sym(deadtriangle, nextedge);
-    /* Get rid of the bounding box triangle. */
-    triangledealloc(m, deadtriangle.tri);
-    /* Do we need to turn the corner? */
-    if (nextedge.tri == m->dummytri) {
-      /* Turn the corner. */
-      otricopy(dissolveedge, nextedge);
-    }
-  }
-  triangledealloc(m, finaledge.tri);
-
-  trifree((VOID *) m->infvertex1);  /* Deallocate the bounding box vertices. */
-  trifree((VOID *) m->infvertex2);
-  trifree((VOID *) m->infvertex3);
-
-  return hullsize;
-}
-
-#endif /* not REDUCED */
-
-/*****************************************************************************/
-/*                                                                           */
-/*  incrementaldelaunay()   Form a Delaunay triangulation by incrementally   */
-/*                          inserting vertices.                              */
-/*                                                                           */
-/*  Returns the number of edges on the convex hull of the triangulation.     */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifndef REDUCED
-
-#ifdef ANSI_DECLARATORS
-long incrementaldelaunay(struct mesh *m, struct behavior *b)
-#else /* not ANSI_DECLARATORS */
-long incrementaldelaunay(m, b)
-struct mesh *m;
-struct behavior *b;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  struct otri starttri;
-  vertex vertexloop;
-
-  /* Create a triangular bounding box. */
-  boundingbox(m, b);
-  if (b->verbose) {
-    printf("  Incrementally inserting vertices.\n");
-  }
-  traversalinit(&m->vertices);
-  vertexloop = vertextraverse(m);
-  while (vertexloop != (vertex) NULL) {
-    starttri.tri = m->dummytri;
-    if (insertvertex(m, b, vertexloop, &starttri, (struct osub *) NULL, 0, 0)
-        == DUPLICATEVERTEX) {
-      if (!b->quiet) {
-        printf(
-"Warning:  A duplicate vertex at (%.12g, %.12g) appeared and was ignored.\n",
-               vertexloop[0], vertexloop[1]);
-      }
-      setvertextype(vertexloop, UNDEADVERTEX);
-      m->undeads++;
-    }
-    vertexloop = vertextraverse(m);
-  }
-  /* Remove the bounding box. */
-  return removebox(m, b);
-}
-
-#endif /* not REDUCED */
-
-/**                                                                         **/
-/**                                                                         **/
-/********* Incremental Delaunay triangulation ends here              *********/
-
-/********* Sweepline Delaunay triangulation begins here              *********/
-/**                                                                         **/
-/**                                                                         **/
-
-#ifndef REDUCED
-
-#ifdef ANSI_DECLARATORS
-void eventheapinsert(struct event **heap, int heapsize, struct event *newevent)
-#else /* not ANSI_DECLARATORS */
-void eventheapinsert(heap, heapsize, newevent)
-struct event **heap;
-int heapsize;
-struct event *newevent;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  REAL eventx, eventy;
-  int eventnum;
-  int parent;
-  int notdone;
-
-  eventx = newevent->xkey;
-  eventy = newevent->ykey;
-  eventnum = heapsize;
-  notdone = eventnum > 0;
-  while (notdone) {
-    parent = (eventnum - 1) >> 1;
-    if ((heap[parent]->ykey < eventy) ||
-        ((heap[parent]->ykey == eventy)
-         && (heap[parent]->xkey <= eventx))) {
-      notdone = 0;
-    } else {
-      heap[eventnum] = heap[parent];
-      heap[eventnum]->heapposition = eventnum;
-
-      eventnum = parent;
-      notdone = eventnum > 0;
-    }
-  }
-  heap[eventnum] = newevent;
-  newevent->heapposition = eventnum;
-}
-
-#endif /* not REDUCED */
-
-#ifndef REDUCED
-
-#ifdef ANSI_DECLARATORS
-void eventheapify(struct event **heap, int heapsize, int eventnum)
-#else /* not ANSI_DECLARATORS */
-void eventheapify(heap, heapsize, eventnum)
-struct event **heap;
-int heapsize;
-int eventnum;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  struct event *thisevent;
-  REAL eventx, eventy;
-  int leftchild, rightchild;
-  int smallest;
-  int notdone;
-
-  thisevent = heap[eventnum];
-  eventx = thisevent->xkey;
-  eventy = thisevent->ykey;
-  leftchild = 2 * eventnum + 1;
-  notdone = leftchild < heapsize;
-  while (notdone) {
-    if ((heap[leftchild]->ykey < eventy) ||
-        ((heap[leftchild]->ykey == eventy)
-         && (heap[leftchild]->xkey < eventx))) {
-      smallest = leftchild;
-    } else {
-      smallest = eventnum;
-    }
-    rightchild = leftchild + 1;
-    if (rightchild < heapsize) {
-      if ((heap[rightchild]->ykey < heap[smallest]->ykey) ||
-          ((heap[rightchild]->ykey == heap[smallest]->ykey)
-           && (heap[rightchild]->xkey < heap[smallest]->xkey))) {
-        smallest = rightchild;
-      }
-    }
-    if (smallest == eventnum) {
-      notdone = 0;
-    } else {
-      heap[eventnum] = heap[smallest];
-      heap[eventnum]->heapposition = eventnum;
-      heap[smallest] = thisevent;
-      thisevent->heapposition = smallest;
-
-      eventnum = smallest;
-      leftchild = 2 * eventnum + 1;
-      notdone = leftchild < heapsize;
-    }
-  }
-}
-
-#endif /* not REDUCED */
-
-#ifndef REDUCED
-
-#ifdef ANSI_DECLARATORS
-void eventheapdelete(struct event **heap, int heapsize, int eventnum)
-#else /* not ANSI_DECLARATORS */
-void eventheapdelete(heap, heapsize, eventnum)
-struct event **heap;
-int heapsize;
-int eventnum;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  struct event *moveevent;
-  REAL eventx, eventy;
-  int parent;
-  int notdone;
-
-  moveevent = heap[heapsize - 1];
-  if (eventnum > 0) {
-    eventx = moveevent->xkey;
-    eventy = moveevent->ykey;
-    do {
-      parent = (eventnum - 1) >> 1;
-      if ((heap[parent]->ykey < eventy) ||
-          ((heap[parent]->ykey == eventy)
-           && (heap[parent]->xkey <= eventx))) {
-        notdone = 0;
-      } else {
-        heap[eventnum] = heap[parent];
-        heap[eventnum]->heapposition = eventnum;
-
-        eventnum = parent;
-        notdone = eventnum > 0;
-      }
-    } while (notdone);
-  }
-  heap[eventnum] = moveevent;
-  moveevent->heapposition = eventnum;
-  eventheapify(heap, heapsize - 1, eventnum);
-}
-
-#endif /* not REDUCED */
-
-#ifndef REDUCED
-
-#ifdef ANSI_DECLARATORS
-void createeventheap(struct mesh *m, struct event ***eventheap,
-                     struct event **events, struct event **freeevents)
-#else /* not ANSI_DECLARATORS */
-void createeventheap(m, eventheap, events, freeevents)
-struct mesh *m;
-struct event ***eventheap;
-struct event **events;
-struct event **freeevents;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  vertex thisvertex;
-  int maxevents;
-  int i;
-
-  maxevents = (3 * m->invertices) / 2;
-  *eventheap = (struct event **) trimalloc(maxevents *
-                                           (int) sizeof(struct event *));
-  *events = (struct event *) trimalloc(maxevents * (int) sizeof(struct event));
-  traversalinit(&m->vertices);
-  for (i = 0; i < m->invertices; i++) {
-    thisvertex = vertextraverse(m);
-    (*events)[i].eventptr = (VOID *) thisvertex;
-    (*events)[i].xkey = thisvertex[0];
-    (*events)[i].ykey = thisvertex[1];
-    eventheapinsert(*eventheap, i, *events + i);
-  }
-  *freeevents = (struct event *) NULL;
-  for (i = maxevents - 1; i >= m->invertices; i--) {
-    (*events)[i].eventptr = (VOID *) *freeevents;
-    *freeevents = *events + i;
-  }
-}
-
-#endif /* not REDUCED */
-
-#ifndef REDUCED
-
-#ifdef ANSI_DECLARATORS
-int rightofhyperbola(struct mesh *m, struct otri *fronttri, vertex newsite)
-#else /* not ANSI_DECLARATORS */
-int rightofhyperbola(m, fronttri, newsite)
-struct mesh *m;
-struct otri *fronttri;
-vertex newsite;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  vertex leftvertex, rightvertex;
-  REAL dxa, dya, dxb, dyb;
-
-  m->hyperbolacount++;
-
-  dest(*fronttri, leftvertex);
-  apex(*fronttri, rightvertex);
-  if ((leftvertex[1] < rightvertex[1]) ||
-      ((leftvertex[1] == rightvertex[1]) &&
-       (leftvertex[0] < rightvertex[0]))) {
-    if (newsite[0] >= rightvertex[0]) {
-      return 1;
-    }
-  } else {
-    if (newsite[0] <= leftvertex[0]) {
-      return 0;
-    }
-  }
-  dxa = leftvertex[0] - newsite[0];
-  dya = leftvertex[1] - newsite[1];
-  dxb = rightvertex[0] - newsite[0];
-  dyb = rightvertex[1] - newsite[1];
-  return dya * (dxb * dxb + dyb * dyb) > dyb * (dxa * dxa + dya * dya);
-}
-
-#endif /* not REDUCED */
-
-#ifndef REDUCED
-
-#ifdef ANSI_DECLARATORS
-REAL circletop(struct mesh *m, vertex pa, vertex pb, vertex pc, REAL ccwabc)
-#else /* not ANSI_DECLARATORS */
-REAL circletop(m, pa, pb, pc, ccwabc)
-struct mesh *m;
-vertex pa;
-vertex pb;
-vertex pc;
-REAL ccwabc;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  REAL xac, yac, xbc, ybc, xab, yab;
-  REAL aclen2, bclen2, ablen2;
-
-  m->circletopcount++;
-
-  xac = pa[0] - pc[0];
-  yac = pa[1] - pc[1];
-  xbc = pb[0] - pc[0];
-  ybc = pb[1] - pc[1];
-  xab = pa[0] - pb[0];
-  yab = pa[1] - pb[1];
-  aclen2 = xac * xac + yac * yac;
-  bclen2 = xbc * xbc + ybc * ybc;
-  ablen2 = xab * xab + yab * yab;
-  return pc[1] + (xac * bclen2 - xbc * aclen2 + sqrt(aclen2 * bclen2 * ablen2))
-               / (2.0 * ccwabc);
-}
-
-#endif /* not REDUCED */
-
-#ifndef REDUCED
-
-#ifdef ANSI_DECLARATORS
-void check4deadevent(struct otri *checktri, struct event **freeevents,
-                     struct event **eventheap, int *heapsize)
-#else /* not ANSI_DECLARATORS */
-void check4deadevent(checktri, freeevents, eventheap, heapsize)
-struct otri *checktri;
-struct event **freeevents;
-struct event **eventheap;
-int *heapsize;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  struct event *deadevent;
-  vertex eventvertex;
-  int eventnum;
-
-  org(*checktri, eventvertex);
-  if (eventvertex != (vertex) NULL) {
-    deadevent = (struct event *) eventvertex;
-    eventnum = deadevent->heapposition;
-    deadevent->eventptr = (VOID *) *freeevents;
-    *freeevents = deadevent;
-    eventheapdelete(eventheap, *heapsize, eventnum);
-    (*heapsize)--;
-    setorg(*checktri, NULL);
-  }
-}
-
-#endif /* not REDUCED */
-
-#ifndef REDUCED
-
-#ifdef ANSI_DECLARATORS
-struct splaynode *splay(struct mesh *m, struct splaynode *splaytree,
-                        vertex searchpoint, struct otri *searchtri)
-#else /* not ANSI_DECLARATORS */
-struct splaynode *splay(m, splaytree, searchpoint, searchtri)
-struct mesh *m;
-struct splaynode *splaytree;
-vertex searchpoint;
-struct otri *searchtri;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  struct splaynode *child, *grandchild;
-  struct splaynode *lefttree, *righttree;
-  struct splaynode *leftright;
-  vertex checkvertex;
-  int rightofroot, rightofchild;
-
-  if (splaytree == (struct splaynode *) NULL) {
-    return (struct splaynode *) NULL;
-  }
-  dest(splaytree->keyedge, checkvertex);
-  if (checkvertex == splaytree->keydest) {
-    rightofroot = rightofhyperbola(m, &splaytree->keyedge, searchpoint);
-    if (rightofroot) {
-      otricopy(splaytree->keyedge, *searchtri);
-      child = splaytree->rchild;
-    } else {
-      child = splaytree->lchild;
-    }
-    if (child == (struct splaynode *) NULL) {
-      return splaytree;
-    }
-    dest(child->keyedge, checkvertex);
-    if (checkvertex != child->keydest) {
-      child = splay(m, child, searchpoint, searchtri);
-      if (child == (struct splaynode *) NULL) {
-        if (rightofroot) {
-          splaytree->rchild = (struct splaynode *) NULL;
-        } else {
-          splaytree->lchild = (struct splaynode *) NULL;
-        }
-        return splaytree;
-      }
-    }
-    rightofchild = rightofhyperbola(m, &child->keyedge, searchpoint);
-    if (rightofchild) {
-      otricopy(child->keyedge, *searchtri);
-      grandchild = splay(m, child->rchild, searchpoint, searchtri);
-      child->rchild = grandchild;
-    } else {
-      grandchild = splay(m, child->lchild, searchpoint, searchtri);
-      child->lchild = grandchild;
-    }
-    if (grandchild == (struct splaynode *) NULL) {
-      if (rightofroot) {
-        splaytree->rchild = child->lchild;
-        child->lchild = splaytree;
-      } else {
-        splaytree->lchild = child->rchild;
-        child->rchild = splaytree;
-      }
-      return child;
-    }
-    if (rightofchild) {
-      if (rightofroot) {
-        splaytree->rchild = child->lchild;
-        child->lchild = splaytree;
-      } else {
-        splaytree->lchild = grandchild->rchild;
-        grandchild->rchild = splaytree;
-      }
-      child->rchild = grandchild->lchild;
-      grandchild->lchild = child;
-    } else {
-      if (rightofroot) {
-        splaytree->rchild = grandchild->lchild;
-        grandchild->lchild = splaytree;
-      } else {
-        splaytree->lchild = child->rchild;
-        child->rchild = splaytree;
-      }
-      child->lchild = grandchild->rchild;
-      grandchild->rchild = child;
-    }
-    return grandchild;
-  } else {
-    lefttree = splay(m, splaytree->lchild, searchpoint, searchtri);
-    righttree = splay(m, splaytree->rchild, searchpoint, searchtri);
-
-    pooldealloc(&m->splaynodes, (VOID *) splaytree);
-    if (lefttree == (struct splaynode *) NULL) {
-      return righttree;
-    } else if (righttree == (struct splaynode *) NULL) {
-      return lefttree;
-    } else if (lefttree->rchild == (struct splaynode *) NULL) {
-      lefttree->rchild = righttree->lchild;
-      righttree->lchild = lefttree;
-      return righttree;
-    } else if (righttree->lchild == (struct splaynode *) NULL) {
-      righttree->lchild = lefttree->rchild;
-      lefttree->rchild = righttree;
-      return lefttree;
-    } else {
-/*      printf("Holy Toledo!!!\n"); */
-      leftright = lefttree->rchild;
-      while (leftright->rchild != (struct splaynode *) NULL) {
-        leftright = leftright->rchild;
-      }
-      leftright->rchild = righttree;
-      return lefttree;
-    }
-  }
-}
-
-#endif /* not REDUCED */
-
-#ifndef REDUCED
-
-#ifdef ANSI_DECLARATORS
-struct splaynode *splayinsert(struct mesh *m, struct splaynode *splayroot,
-                              struct otri *newkey, vertex searchpoint)
-#else /* not ANSI_DECLARATORS */
-struct splaynode *splayinsert(m, splayroot, newkey, searchpoint)
-struct mesh *m;
-struct splaynode *splayroot;
-struct otri *newkey;
-vertex searchpoint;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  struct splaynode *newsplaynode;
-
-  newsplaynode = (struct splaynode *) poolalloc(&m->splaynodes);
-  otricopy(*newkey, newsplaynode->keyedge);
-  dest(*newkey, newsplaynode->keydest);
-  if (splayroot == (struct splaynode *) NULL) {
-    newsplaynode->lchild = (struct splaynode *) NULL;
-    newsplaynode->rchild = (struct splaynode *) NULL;
-  } else if (rightofhyperbola(m, &splayroot->keyedge, searchpoint)) {
-    newsplaynode->lchild = splayroot;
-    newsplaynode->rchild = splayroot->rchild;
-    splayroot->rchild = (struct splaynode *) NULL;
-  } else {
-    newsplaynode->lchild = splayroot->lchild;
-    newsplaynode->rchild = splayroot;
-    splayroot->lchild = (struct splaynode *) NULL;
-  }
-  return newsplaynode;
-}
-
-#endif /* not REDUCED */
-
-#ifndef REDUCED
-
-#ifdef ANSI_DECLARATORS
-struct splaynode *circletopinsert(struct mesh *m, struct behavior *b,
-                                  struct splaynode *splayroot,
-                                  struct otri *newkey,
-                                  vertex pa, vertex pb, vertex pc, REAL topy)
-#else /* not ANSI_DECLARATORS */
-struct splaynode *circletopinsert(m, b, splayroot, newkey, pa, pb, pc, topy)
-struct mesh *m;
-struct behavior *b;
-struct splaynode *splayroot;
-struct otri *newkey;
-vertex pa;
-vertex pb;
-vertex pc;
-REAL topy;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  REAL ccwabc;
-  REAL xac, yac, xbc, ybc;
-  REAL aclen2, bclen2;
-  REAL searchpoint[2];
-  struct otri dummytri;
-
-  ccwabc = counterclockwise(m, b, pa, pb, pc);
-  xac = pa[0] - pc[0];
-  yac = pa[1] - pc[1];
-  xbc = pb[0] - pc[0];
-  ybc = pb[1] - pc[1];
-  aclen2 = xac * xac + yac * yac;
-  bclen2 = xbc * xbc + ybc * ybc;
-  searchpoint[0] = pc[0] - (yac * bclen2 - ybc * aclen2) / (2.0 * ccwabc);
-  searchpoint[1] = topy;
-  return splayinsert(m, splay(m, splayroot, (vertex) searchpoint, &dummytri),
-                     newkey, (vertex) searchpoint);
-}
-
-#endif /* not REDUCED */
-
-#ifndef REDUCED
-
-#ifdef ANSI_DECLARATORS
-struct splaynode *frontlocate(struct mesh *m, struct splaynode *splayroot,
-                              struct otri *bottommost, vertex searchvertex,
-                              struct otri *searchtri, int *farright)
-#else /* not ANSI_DECLARATORS */
-struct splaynode *frontlocate(m, splayroot, bottommost, searchvertex,
-                              searchtri, farright)
-struct mesh *m;
-struct splaynode *splayroot;
-struct otri *bottommost;
-vertex searchvertex;
-struct otri *searchtri;
-int *farright;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  int farrightflag;
-  triangle ptr;                       /* Temporary variable used by onext(). */
-
-  otricopy(*bottommost, *searchtri);
-  splayroot = splay(m, splayroot, searchvertex, searchtri);
-
-  farrightflag = 0;
-  while (!farrightflag && rightofhyperbola(m, searchtri, searchvertex)) {
-    onextself(*searchtri);
-    farrightflag = otriequal(*searchtri, *bottommost);
-  }
-  *farright = farrightflag;
-  return splayroot;
-}
-
-#endif /* not REDUCED */
-
-#ifndef REDUCED
-
-#ifdef ANSI_DECLARATORS
-long sweeplinedelaunay(struct mesh *m, struct behavior *b)
-#else /* not ANSI_DECLARATORS */
-long sweeplinedelaunay(m, b)
-struct mesh *m;
-struct behavior *b;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  struct event **eventheap;
-  struct event *events;
-  struct event *freeevents;
-  struct event *nextevent;
-  struct event *newevent;
-  struct splaynode *splayroot;
-  struct otri bottommost;
-  struct otri searchtri;
-  struct otri fliptri;
-  struct otri lefttri, righttri, farlefttri, farrighttri;
-  struct otri inserttri;
-  vertex firstvertex, secondvertex;
-  vertex nextvertex, lastvertex;
-  vertex connectvertex;
-  vertex leftvertex, midvertex, rightvertex;
-  REAL lefttest, righttest;
-  int heapsize;
-  int check4events, farrightflag;
-  triangle ptr;   /* Temporary variable used by sym(), onext(), and oprev(). */
-
-  poolinit(&m->splaynodes, sizeof(struct splaynode), SPLAYNODEPERBLOCK,
-           SPLAYNODEPERBLOCK, 0);
-  splayroot = (struct splaynode *) NULL;
-
-  if (b->verbose) {
-    printf("  Placing vertices in event heap.\n");
-  }
-  createeventheap(m, &eventheap, &events, &freeevents);
-  heapsize = m->invertices;
-
-  if (b->verbose) {
-    printf("  Forming triangulation.\n");
-  }
-  maketriangle(m, b, &lefttri);
-  maketriangle(m, b, &righttri);
-  bond(lefttri, righttri);
-  lnextself(lefttri);
-  lprevself(righttri);
-  bond(lefttri, righttri);
-  lnextself(lefttri);
-  lprevself(righttri);
-  bond(lefttri, righttri);
-  firstvertex = (vertex) eventheap[0]->eventptr;
-  eventheap[0]->eventptr = (VOID *) freeevents;
-  freeevents = eventheap[0];
-  eventheapdelete(eventheap, heapsize, 0);
-  heapsize--;
-  do {
-    if (heapsize == 0) {
-      printf("Error:  Input vertices are all identical.\n");
-      triexit(1);
-    }
-    secondvertex = (vertex) eventheap[0]->eventptr;
-    eventheap[0]->eventptr = (VOID *) freeevents;
-    freeevents = eventheap[0];
-    eventheapdelete(eventheap, heapsize, 0);
-    heapsize--;
-    if ((firstvertex[0] == secondvertex[0]) &&
-        (firstvertex[1] == secondvertex[1])) {
-      if (!b->quiet) {
-        printf(
-"Warning:  A duplicate vertex at (%.12g, %.12g) appeared and was ignored.\n",
-               secondvertex[0], secondvertex[1]);
-      }
-      setvertextype(secondvertex, UNDEADVERTEX);
-      m->undeads++;
-    }
-  } while ((firstvertex[0] == secondvertex[0]) &&
-           (firstvertex[1] == secondvertex[1]));
-  setorg(lefttri, firstvertex);
-  setdest(lefttri, secondvertex);
-  setorg(righttri, secondvertex);
-  setdest(righttri, firstvertex);
-  lprev(lefttri, bottommost);
-  lastvertex = secondvertex;
-  while (heapsize > 0) {
-    nextevent = eventheap[0];
-    eventheapdelete(eventheap, heapsize, 0);
-    heapsize--;
-    check4events = 1;
-    if (nextevent->xkey < m->xmin) {
-      decode(nextevent->eventptr, fliptri);
-      oprev(fliptri, farlefttri);
-      check4deadevent(&farlefttri, &freeevents, eventheap, &heapsize);
-      onext(fliptri, farrighttri);
-      check4deadevent(&farrighttri, &freeevents, eventheap, &heapsize);
-
-      if (otriequal(farlefttri, bottommost)) {
-        lprev(fliptri, bottommost);
-      }
-      flip(m, b, &fliptri);
-      setapex(fliptri, NULL);
-      lprev(fliptri, lefttri);
-      lnext(fliptri, righttri);
-      sym(lefttri, farlefttri);
-
-      if (randomnation(SAMPLERATE) == 0) {
-        symself(fliptri);
-        dest(fliptri, leftvertex);
-        apex(fliptri, midvertex);
-        org(fliptri, rightvertex);
-        splayroot = circletopinsert(m, b, splayroot, &lefttri, leftvertex,
-                                    midvertex, rightvertex, nextevent->ykey);
-      }
-    } else {
-      nextvertex = (vertex) nextevent->eventptr;
-      if ((nextvertex[0] == lastvertex[0]) &&
-          (nextvertex[1] == lastvertex[1])) {
-        if (!b->quiet) {
-          printf(
-"Warning:  A duplicate vertex at (%.12g, %.12g) appeared and was ignored.\n",
-                 nextvertex[0], nextvertex[1]);
-        }
-        setvertextype(nextvertex, UNDEADVERTEX);
-        m->undeads++;
-        check4events = 0;
-      } else {
-        lastvertex = nextvertex;
-
-        splayroot = frontlocate(m, splayroot, &bottommost, nextvertex,
-                                &searchtri, &farrightflag);
-/*
-        otricopy(bottommost, searchtri);
-        farrightflag = 0;
-        while (!farrightflag && rightofhyperbola(m, &searchtri, nextvertex)) {
-          onextself(searchtri);
-          farrightflag = otriequal(searchtri, bottommost);
-        }
-*/
-
-        check4deadevent(&searchtri, &freeevents, eventheap, &heapsize);
-
-        otricopy(searchtri, farrighttri);
-        sym(searchtri, farlefttri);
-        maketriangle(m, b, &lefttri);
-        maketriangle(m, b, &righttri);
-        dest(farrighttri, connectvertex);
-        setorg(lefttri, connectvertex);
-        setdest(lefttri, nextvertex);
-        setorg(righttri, nextvertex);
-        setdest(righttri, connectvertex);
-        bond(lefttri, righttri);
-        lnextself(lefttri);
-        lprevself(righttri);
-        bond(lefttri, righttri);
-        lnextself(lefttri);
-        lprevself(righttri);
-        bond(lefttri, farlefttri);
-        bond(righttri, farrighttri);
-        if (!farrightflag && otriequal(farrighttri, bottommost)) {
-          otricopy(lefttri, bottommost);
-        }
-
-        if (randomnation(SAMPLERATE) == 0) {
-          splayroot = splayinsert(m, splayroot, &lefttri, nextvertex);
-        } else if (randomnation(SAMPLERATE) == 0) {
-          lnext(righttri, inserttri);
-          splayroot = splayinsert(m, splayroot, &inserttri, nextvertex);
-        }
-      }
-    }
-    nextevent->eventptr = (VOID *) freeevents;
-    freeevents = nextevent;
-
-    if (check4events) {
-      apex(farlefttri, leftvertex);
-      dest(lefttri, midvertex);
-      apex(lefttri, rightvertex);
-      lefttest = counterclockwise(m, b, leftvertex, midvertex, rightvertex);
-      if (lefttest > 0.0) {
-        newevent = freeevents;
-        freeevents = (struct event *) freeevents->eventptr;
-        newevent->xkey = m->xminextreme;
-        newevent->ykey = circletop(m, leftvertex, midvertex, rightvertex,
-                                   lefttest);
-        newevent->eventptr = (VOID *) encode(lefttri);
-        eventheapinsert(eventheap, heapsize, newevent);
-        heapsize++;
-        setorg(lefttri, newevent);
-      }
-      apex(righttri, leftvertex);
-      org(righttri, midvertex);
-      apex(farrighttri, rightvertex);
-      righttest = counterclockwise(m, b, leftvertex, midvertex, rightvertex);
-      if (righttest > 0.0) {
-        newevent = freeevents;
-        freeevents = (struct event *) freeevents->eventptr;
-        newevent->xkey = m->xminextreme;
-        newevent->ykey = circletop(m, leftvertex, midvertex, rightvertex,
-                                   righttest);
-        newevent->eventptr = (VOID *) encode(farrighttri);
-        eventheapinsert(eventheap, heapsize, newevent);
-        heapsize++;
-        setorg(farrighttri, newevent);
-      }
-    }
-  }
-
-  pooldeinit(&m->splaynodes);
-  lprevself(bottommost);
-  return removeghosts(m, b, &bottommost);
-}
-
-#endif /* not REDUCED */
-
-/**                                                                         **/
-/**                                                                         **/
-/********* Sweepline Delaunay triangulation ends here                *********/
-
-/********* General mesh construction routines begin here             *********/
-/**                                                                         **/
-/**                                                                         **/
-
-/*****************************************************************************/
-/*                                                                           */
-/*  delaunay()   Form a Delaunay triangulation.                              */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef ANSI_DECLARATORS
-long delaunay(struct mesh *m, struct behavior *b)
-#else /* not ANSI_DECLARATORS */
-long delaunay(m, b)
-struct mesh *m;
-struct behavior *b;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  long hulledges;
-
-  m->eextras = 0;
-  initializetrisubpools(m, b);
-
-#ifdef REDUCED
-  if (!b->quiet) {
-    printf(
-      "Constructing Delaunay triangulation by divide-and-conquer method.\n");
-  }
-  hulledges = divconqdelaunay(m, b);
-#else /* not REDUCED */
-  if (!b->quiet) {
-    printf("Constructing Delaunay triangulation ");
-    if (b->incremental) {
-      printf("by incremental method.\n");
-    } else if (b->sweepline) {
-      printf("by sweepline method.\n");
-    } else {
-      printf("by divide-and-conquer method.\n");
-    }
-  }
-  if (b->incremental) {
-    hulledges = incrementaldelaunay(m, b);
-  } else if (b->sweepline) {
-    hulledges = sweeplinedelaunay(m, b);
-  } else {
-    hulledges = divconqdelaunay(m, b);
-  }
-#endif /* not REDUCED */
-
-  if (m->triangles.items == 0) {
-    /* The input vertices were all collinear, so there are no triangles. */
-    return 0l;
-  } else {
-    return hulledges;
-  }
-}
-
-/*****************************************************************************/
-/*                                                                           */
-/*  reconstruct()   Reconstruct a triangulation from its .ele (and possibly  */
-/*                  .poly) file.  Used when the -r switch is used.           */
-/*                                                                           */
-/*  Reads an .ele file and reconstructs the original mesh.  If the -p switch */
-/*  is used, this procedure will also read a .poly file and reconstruct the  */
-/*  subsegments of the original mesh.  If the -a switch is used, this        */
-/*  procedure will also read an .area file and set a maximum area constraint */
-/*  on each triangle.                                                        */
-/*                                                                           */
-/*  Vertices that are not corners of triangles, such as nodes on edges of    */
-/*  subparametric elements, are discarded.                                   */
-/*                                                                           */
-/*  This routine finds the adjacencies between triangles (and subsegments)   */
-/*  by forming one stack of triangles for each vertex.  Each triangle is on  */
-/*  three different stacks simultaneously.  Each triangle's subsegment       */
-/*  pointers are used to link the items in each stack.  This memory-saving   */
-/*  feature makes the code harder to read.  The most important thing to keep */
-/*  in mind is that each triangle is removed from a stack precisely when     */
-/*  the corresponding pointer is adjusted to refer to a subsegment rather    */
-/*  than the next triangle of the stack.                                     */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifndef CDT_ONLY
-
-#ifdef TRILIBRARY
-
-#ifdef ANSI_DECLARATORS
-int reconstruct(struct mesh *m, struct behavior *b, int *trianglelist,
-                REAL *triangleattriblist, REAL *trianglearealist,
-                int elements, int corners, int attribs,
-                int *segmentlist,int *segmentmarkerlist, int numberofsegments)
-#else /* not ANSI_DECLARATORS */
-int reconstruct(m, b, trianglelist, triangleattriblist, trianglearealist,
-                elements, corners, attribs, segmentlist, segmentmarkerlist,
-                numberofsegments)
-struct mesh *m;
-struct behavior *b;
-int *trianglelist;
-REAL *triangleattriblist;
-REAL *trianglearealist;
-int elements;
-int corners;
-int attribs;
-int *segmentlist;
-int *segmentmarkerlist;
-int numberofsegments;
-#endif /* not ANSI_DECLARATORS */
-
-#else /* not TRILIBRARY */
-
-#ifdef ANSI_DECLARATORS
-long reconstruct(struct mesh *m, struct behavior *b, char *elefilename,
-                 char *areafilename, char *polyfilename, FILE *polyfile)
-#else /* not ANSI_DECLARATORS */
-long reconstruct(m, b, elefilename, areafilename, polyfilename, polyfile)
-struct mesh *m;
-struct behavior *b;
-char *elefilename;
-char *areafilename;
-char *polyfilename;
-FILE *polyfile;
-#endif /* not ANSI_DECLARATORS */
-
-#endif /* not TRILIBRARY */
-
-{
-#ifdef TRILIBRARY
-  int vertexindex;
-  int attribindex;
-#else /* not TRILIBRARY */
-  FILE *elefile;
-  FILE *areafile;
-  char inputline[INPUTLINESIZE];
-  char *stringptr;
-  int areaelements;
-#endif /* not TRILIBRARY */
-  struct otri triangleloop;
-  struct otri triangleleft;
-  struct otri checktri;
-  struct otri checkleft;
-  struct otri checkneighbor;
-  struct osub subsegloop;
-  triangle *vertexarray;
-  triangle *prevlink;
-  triangle nexttri;
-  vertex tdest, tapex;
-  vertex checkdest, checkapex;
-  vertex shorg;
-  vertex killvertex;
-  vertex segmentorg, segmentdest;
-  REAL area;
-  int corner[3];
-  int end[2];
-  int killvertexindex;
-  int incorners;
-  int segmentmarkers;
-  int boundmarker;
-  int aroundvertex;
-  long hullsize;
-  int notfound;
-  long elementnumber, segmentnumber;
-  int i, j;
-  triangle ptr;                         /* Temporary variable used by sym(). */
-
-#ifdef TRILIBRARY
-  m->inelements = elements;
-  incorners = corners;
-  if (incorners < 3) {
-    printf("Error:  Triangles must have at least 3 vertices.\n");
-    triexit(1);
-  }
-  m->eextras = attribs;
-#else /* not TRILIBRARY */
-  /* Read the triangles from an .ele file. */
-  if (!b->quiet) {
-    printf("Opening %s.\n", elefilename);
-  }
-  elefile = fopen(elefilename, "r");
-  if (elefile == (FILE *) NULL) {
-    printf("  Error:  Cannot access file %s.\n", elefilename);
-    triexit(1);
-  }
-  /* Read number of triangles, number of vertices per triangle, and */
-  /*   number of triangle attributes from .ele file.                */
-  stringptr = readline(inputline, elefile, elefilename);
-  m->inelements = (int) strtol(stringptr, &stringptr, 0);
-  stringptr = findfield(stringptr);
-  if (*stringptr == '\0') {
-    incorners = 3;
-  } else {
-    incorners = (int) strtol(stringptr, &stringptr, 0);
-    if (incorners < 3) {
-      printf("Error:  Triangles in %s must have at least 3 vertices.\n",
-             elefilename);
-      triexit(1);
-    }
-  }
-  stringptr = findfield(stringptr);
-  if (*stringptr == '\0') {
-    m->eextras = 0;
-  } else {
-    m->eextras = (int) strtol(stringptr, &stringptr, 0);
-  }
-#endif /* not TRILIBRARY */
-
-  initializetrisubpools(m, b);
-
-  /* Create the triangles. */
-  for (elementnumber = 1; elementnumber <= m->inelements; elementnumber++) {
-    maketriangle(m, b, &triangleloop);
-    /* Mark the triangle as living. */
-    triangleloop.tri[3] = (triangle) triangleloop.tri;
-  }
-
-  segmentmarkers = 0;
-  if (b->poly) {
-#ifdef TRILIBRARY
-    m->insegments = numberofsegments;
-    segmentmarkers = segmentmarkerlist != (int *) NULL;
-#else /* not TRILIBRARY */
-    /* Read number of segments and number of segment */
-    /*   boundary markers from .poly file.           */
-    stringptr = readline(inputline, polyfile, b->inpolyfilename);
-    m->insegments = (int) strtol(stringptr, &stringptr, 0);
-    stringptr = findfield(stringptr);
-    if (*stringptr != '\0') {
-      segmentmarkers = (int) strtol(stringptr, &stringptr, 0);
-    }
-#endif /* not TRILIBRARY */
-
-    /* Create the subsegments. */
-    for (segmentnumber = 1; segmentnumber <= m->insegments; segmentnumber++) {
-      makesubseg(m, &subsegloop);
-      /* Mark the subsegment as living. */
-      subsegloop.ss[2] = (subseg) subsegloop.ss;
-    }
-  }
-
-#ifdef TRILIBRARY
-  vertexindex = 0;
-  attribindex = 0;
-#else /* not TRILIBRARY */
-  if (b->vararea) {
-    /* Open an .area file, check for consistency with the .ele file. */
-    if (!b->quiet) {
-      printf("Opening %s.\n", areafilename);
-    }
-    areafile = fopen(areafilename, "r");
-    if (areafile == (FILE *) NULL) {
-      printf("  Error:  Cannot access file %s.\n", areafilename);
-      triexit(1);
-    }
-    stringptr = readline(inputline, areafile, areafilename);
-    areaelements = (int) strtol(stringptr, &stringptr, 0);
-    if (areaelements != m->inelements) {
-      printf("Error:  %s and %s disagree on number of triangles.\n",
-             elefilename, areafilename);
-      triexit(1);
-    }
-  }
-#endif /* not TRILIBRARY */
-
-  if (!b->quiet) {
-    printf("Reconstructing mesh.\n");
-  }
-  /* Allocate a temporary array that maps each vertex to some adjacent */
-  /*   triangle.  I took care to allocate all the permanent memory for */
-  /*   triangles and subsegments first.                                */
-  vertexarray = (triangle *) trimalloc(m->vertices.items *
-                                       (int) sizeof(triangle));
-  /* Each vertex is initially unrepresented. */
-  for (i = 0; i < m->vertices.items; i++) {
-    vertexarray[i] = (triangle) m->dummytri;
-  }
-
-  if (b->verbose) {
-    printf("  Assembling triangles.\n");
-  }
-  /* Read the triangles from the .ele file, and link */
-  /*   together those that share an edge.            */
-  traversalinit(&m->triangles);
-  triangleloop.tri = triangletraverse(m);
-  elementnumber = b->firstnumber;
-  while (triangleloop.tri != (triangle *) NULL) {
-#ifdef TRILIBRARY
-    /* Copy the triangle's three corners. */
-    for (j = 0; j < 3; j++) {
-      corner[j] = trianglelist[vertexindex++];
-      if ((corner[j] < b->firstnumber) ||
-          (corner[j] >= b->firstnumber + m->invertices)) {
-        printf("Error:  Triangle %ld has an invalid vertex index.\n",
-               elementnumber);
-        triexit(1);
-      }
-    }
-#else /* not TRILIBRARY */
-    /* Read triangle number and the triangle's three corners. */
-    stringptr = readline(inputline, elefile, elefilename);
-    for (j = 0; j < 3; j++) {
-      stringptr = findfield(stringptr);
-      if (*stringptr == '\0') {
-        printf("Error:  Triangle %ld is missing vertex %d in %s.\n",
-               elementnumber, j + 1, elefilename);
-        triexit(1);
-      } else {
-        corner[j] = (int) strtol(stringptr, &stringptr, 0);
-        if ((corner[j] < b->firstnumber) ||
-            (corner[j] >= b->firstnumber + m->invertices)) {
-          printf("Error:  Triangle %ld has an invalid vertex index.\n",
-                 elementnumber);
-          triexit(1);
-        }
-      }
-    }
-#endif /* not TRILIBRARY */
-
-    /* Find out about (and throw away) extra nodes. */
-    for (j = 3; j < incorners; j++) {
-#ifdef TRILIBRARY
-      killvertexindex = trianglelist[vertexindex++];
-#else /* not TRILIBRARY */
-      stringptr = findfield(stringptr);
-      if (*stringptr != '\0') {
-        killvertexindex = (int) strtol(stringptr, &stringptr, 0);
-#endif /* not TRILIBRARY */
-        if ((killvertexindex >= b->firstnumber) &&
-            (killvertexindex < b->firstnumber + m->invertices)) {
-          /* Delete the non-corner vertex if it's not already deleted. */
-          killvertex = getvertex(m, b, killvertexindex);
-          if (vertextype(killvertex) != DEADVERTEX) {
-            vertexdealloc(m, killvertex);
-          }
-        }
-#ifndef TRILIBRARY
-      }
-#endif /* not TRILIBRARY */
-    }
-
-    /* Read the triangle's attributes. */
-    for (j = 0; j < m->eextras; j++) {
-#ifdef TRILIBRARY
-      setelemattribute(triangleloop, j, triangleattriblist[attribindex++]);
-#else /* not TRILIBRARY */
-      stringptr = findfield(stringptr);
-      if (*stringptr == '\0') {
-        setelemattribute(triangleloop, j, 0);
-      } else {
-        setelemattribute(triangleloop, j,
-                         (REAL) strtod(stringptr, &stringptr));
-      }
-#endif /* not TRILIBRARY */
-    }
-
-    if (b->vararea) {
-#ifdef TRILIBRARY
-      area = trianglearealist[elementnumber - b->firstnumber];
-#else /* not TRILIBRARY */
-      /* Read an area constraint from the .area file. */
-      stringptr = readline(inputline, areafile, areafilename);
-      stringptr = findfield(stringptr);
-      if (*stringptr == '\0') {
-        area = -1.0;                      /* No constraint on this triangle. */
-      } else {
-        area = (REAL) strtod(stringptr, &stringptr);
-      }
-#endif /* not TRILIBRARY */
-      setareabound(triangleloop, area);
-    }
-
-    /* Set the triangle's vertices. */
-    triangleloop.orient = 0;
-    setorg(triangleloop, getvertex(m, b, corner[0]));
-    setdest(triangleloop, getvertex(m, b, corner[1]));
-    setapex(triangleloop, getvertex(m, b, corner[2]));
-    /* Try linking the triangle to others that share these vertices. */
-    for (triangleloop.orient = 0; triangleloop.orient < 3;
-         triangleloop.orient++) {
-      /* Take the number for the origin of triangleloop. */
-      aroundvertex = corner[triangleloop.orient];
-      /* Look for other triangles having this vertex. */
-      nexttri = vertexarray[aroundvertex - b->firstnumber];
-      /* Link the current triangle to the next one in the stack. */
-      triangleloop.tri[6 + triangleloop.orient] = nexttri;
-      /* Push the current triangle onto the stack. */
-      vertexarray[aroundvertex - b->firstnumber] = encode(triangleloop);
-      decode(nexttri, checktri);
-      if (checktri.tri != m->dummytri) {
-        dest(triangleloop, tdest);
-        apex(triangleloop, tapex);
-        /* Look for other triangles that share an edge. */
-        do {
-          dest(checktri, checkdest);
-          apex(checktri, checkapex);
-          if (tapex == checkdest) {
-            /* The two triangles share an edge; bond them together. */
-            lprev(triangleloop, triangleleft);
-            bond(triangleleft, checktri);
-          }
-          if (tdest == checkapex) {
-            /* The two triangles share an edge; bond them together. */
-            lprev(checktri, checkleft);
-            bond(triangleloop, checkleft);
-          }
-          /* Find the next triangle in the stack. */
-          nexttri = checktri.tri[6 + checktri.orient];
-          decode(nexttri, checktri);
-        } while (checktri.tri != m->dummytri);
-      }
-    }
-    triangleloop.tri = triangletraverse(m);
-    elementnumber++;
-  }
-
-#ifdef TRILIBRARY
-  vertexindex = 0;
-#else /* not TRILIBRARY */
-  fclose(elefile);
-  if (b->vararea) {
-    fclose(areafile);
-  }
-#endif /* not TRILIBRARY */
-
-  hullsize = 0;                      /* Prepare to count the boundary edges. */
-  if (b->poly) {
-    if (b->verbose) {
-      printf("  Marking segments in triangulation.\n");
-    }
-    /* Read the segments from the .poly file, and link them */
-    /*   to their neighboring triangles.                    */
-    boundmarker = 0;
-    traversalinit(&m->subsegs);
-    subsegloop.ss = subsegtraverse(m);
-    segmentnumber = b->firstnumber;
-    while (subsegloop.ss != (subseg *) NULL) {
-#ifdef TRILIBRARY
-      end[0] = segmentlist[vertexindex++];
-      end[1] = segmentlist[vertexindex++];
-      if (segmentmarkers) {
-        boundmarker = segmentmarkerlist[segmentnumber - b->firstnumber];
-      }
-#else /* not TRILIBRARY */
-      /* Read the endpoints of each segment, and possibly a boundary marker. */
-      stringptr = readline(inputline, polyfile, b->inpolyfilename);
-      /* Skip the first (segment number) field. */
-      stringptr = findfield(stringptr);
-      if (*stringptr == '\0') {
-        printf("Error:  Segment %ld has no endpoints in %s.\n", segmentnumber,
-               polyfilename);
-        triexit(1);
-      } else {
-        end[0] = (int) strtol(stringptr, &stringptr, 0);
-      }
-      stringptr = findfield(stringptr);
-      if (*stringptr == '\0') {
-        printf("Error:  Segment %ld is missing its second endpoint in %s.\n",
-               segmentnumber, polyfilename);
-        triexit(1);
-      } else {
-        end[1] = (int) strtol(stringptr, &stringptr, 0);
-      }
-      if (segmentmarkers) {
-        stringptr = findfield(stringptr);
-        if (*stringptr == '\0') {
-          boundmarker = 0;
-        } else {
-          boundmarker = (int) strtol(stringptr, &stringptr, 0);
-        }
-      }
-#endif /* not TRILIBRARY */
-      for (j = 0; j < 2; j++) {
-        if ((end[j] < b->firstnumber) ||
-            (end[j] >= b->firstnumber + m->invertices)) {
-          printf("Error:  Segment %ld has an invalid vertex index.\n",
-                 segmentnumber);
-          triexit(1);
-        }
-      }
-
-      /* set the subsegment's vertices. */
-      subsegloop.ssorient = 0;
-      segmentorg = getvertex(m, b, end[0]);
-      segmentdest = getvertex(m, b, end[1]);
-      setsorg(subsegloop, segmentorg);
-      setsdest(subsegloop, segmentdest);
-      setsegorg(subsegloop, segmentorg);
-      setsegdest(subsegloop, segmentdest);
-      setmark(subsegloop, boundmarker);
-      /* Try linking the subsegment to triangles that share these vertices. */
-      for (subsegloop.ssorient = 0; subsegloop.ssorient < 2;
-           subsegloop.ssorient++) {
-        /* Take the number for the destination of subsegloop. */
-        aroundvertex = end[1 - subsegloop.ssorient];
-        /* Look for triangles having this vertex. */
-        prevlink = &vertexarray[aroundvertex - b->firstnumber];
-        nexttri = vertexarray[aroundvertex - b->firstnumber];
-        decode(nexttri, checktri);
-        sorg(subsegloop, shorg);
-        notfound = 1;
-        /* Look for triangles having this edge.  Note that I'm only       */
-        /*   comparing each triangle's destination with the subsegment;   */
-        /*   each triangle's apex is handled through a different vertex.  */
-        /*   Because each triangle appears on three vertices' lists, each */
-        /*   occurrence of a triangle on a list can (and does) represent  */
-        /*   an edge.  In this way, most edges are represented twice, and */
-        /*   every triangle-subsegment bond is represented once.          */
-        while (notfound && (checktri.tri != m->dummytri)) {
-          dest(checktri, checkdest);
-          if (shorg == checkdest) {
-            /* We have a match.  Remove this triangle from the list. */
-            *prevlink = checktri.tri[6 + checktri.orient];
-            /* Bond the subsegment to the triangle. */
-            tsbond(checktri, subsegloop);
-            /* Check if this is a boundary edge. */
-            sym(checktri, checkneighbor);
-            if (checkneighbor.tri == m->dummytri) {
-              /* The next line doesn't insert a subsegment (because there's */
-              /*   already one there), but it sets the boundary markers of  */
-              /*   the existing subsegment and its vertices.                */
-              insertsubseg(m, b, &checktri, 1);
-              hullsize++;
-            }
-            notfound = 0;
-          }
-          /* Find the next triangle in the stack. */
-          prevlink = &checktri.tri[6 + checktri.orient];
-          nexttri = checktri.tri[6 + checktri.orient];
-          decode(nexttri, checktri);
-        }
-      }
-      subsegloop.ss = subsegtraverse(m);
-      segmentnumber++;
-    }
-  }
-
-  /* Mark the remaining edges as not being attached to any subsegment. */
-  /* Also, count the (yet uncounted) boundary edges.                   */
-  for (i = 0; i < m->vertices.items; i++) {
-    /* Search the stack of triangles adjacent to a vertex. */
-    nexttri = vertexarray[i];
-    decode(nexttri, checktri);
-    while (checktri.tri != m->dummytri) {
-      /* Find the next triangle in the stack before this */
-      /*   information gets overwritten.                 */
-      nexttri = checktri.tri[6 + checktri.orient];
-      /* No adjacent subsegment.  (This overwrites the stack info.) */
-      tsdissolve(checktri);
-      sym(checktri, checkneighbor);
-      if (checkneighbor.tri == m->dummytri) {
-        insertsubseg(m, b, &checktri, 1);
-        hullsize++;
-      }
-      decode(nexttri, checktri);
-    }
-  }
-
-  trifree((VOID *) vertexarray);
-  return hullsize;
-}
-
-#endif /* not CDT_ONLY */
-
-/**                                                                         **/
-/**                                                                         **/
-/********* General mesh construction routines end here               *********/
-
-/********* Segment insertion begins here                             *********/
-/**                                                                         **/
-/**                                                                         **/
-
-/*****************************************************************************/
-/*                                                                           */
-/*  finddirection()   Find the first triangle on the path from one point     */
-/*                    to another.                                            */
-/*                                                                           */
-/*  Finds the triangle that intersects a line segment drawn from the         */
-/*  origin of `searchtri' to the point `searchpoint', and returns the result */
-/*  in `searchtri'.  The origin of `searchtri' does not change, even though  */
-/*  the triangle returned may differ from the one passed in.  This routine   */
-/*  is used to find the direction to move in to get from one point to        */
-/*  another.                                                                 */
-/*                                                                           */
-/*  The return value notes whether the destination or apex of the found      */
-/*  triangle is collinear with the two points in question.                   */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef ANSI_DECLARATORS
-enum finddirectionresult finddirection(struct mesh *m, struct behavior *b,
-                                       struct otri *searchtri,
-                                       vertex searchpoint)
-#else /* not ANSI_DECLARATORS */
-enum finddirectionresult finddirection(m, b, searchtri, searchpoint)
-struct mesh *m;
-struct behavior *b;
-struct otri *searchtri;
-vertex searchpoint;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  struct otri checktri;
-  vertex startvertex;
-  vertex leftvertex, rightvertex;
-  REAL leftccw, rightccw;
-  int leftflag, rightflag;
-  triangle ptr;           /* Temporary variable used by onext() and oprev(). */
-
-  org(*searchtri, startvertex);
-  dest(*searchtri, rightvertex);
-  apex(*searchtri, leftvertex);
-  /* Is `searchpoint' to the left? */
-  leftccw = counterclockwise(m, b, searchpoint, startvertex, leftvertex);
-  leftflag = leftccw > 0.0;
-  /* Is `searchpoint' to the right? */
-  rightccw = counterclockwise(m, b, startvertex, searchpoint, rightvertex);
-  rightflag = rightccw > 0.0;
-  if (leftflag && rightflag) {
-    /* `searchtri' faces directly away from `searchpoint'.  We could go left */
-    /*   or right.  Ask whether it's a triangle or a boundary on the left.   */
-    onext(*searchtri, checktri);
-    if (checktri.tri == m->dummytri) {
-      leftflag = 0;
-    } else {
-      rightflag = 0;
-    }
-  }
-  while (leftflag) {
-    /* Turn left until satisfied. */
-    onextself(*searchtri);
-    if (searchtri->tri == m->dummytri) {
-      printf("Internal error in finddirection():  Unable to find a\n");
-      printf("  triangle leading from (%.12g, %.12g) to", startvertex[0],
-             startvertex[1]);
-      printf("  (%.12g, %.12g).\n", searchpoint[0], searchpoint[1]);
-      internalerror();
-    }
-    apex(*searchtri, leftvertex);
-    rightccw = leftccw;
-    leftccw = counterclockwise(m, b, searchpoint, startvertex, leftvertex);
-    leftflag = leftccw > 0.0;
-  }
-  while (rightflag) {
-    /* Turn right until satisfied. */
-    oprevself(*searchtri);
-    if (searchtri->tri == m->dummytri) {
-      printf("Internal error in finddirection():  Unable to find a\n");
-      printf("  triangle leading from (%.12g, %.12g) to", startvertex[0],
-             startvertex[1]);
-      printf("  (%.12g, %.12g).\n", searchpoint[0], searchpoint[1]);
-      internalerror();
-    }
-    dest(*searchtri, rightvertex);
-    leftccw = rightccw;
-    rightccw = counterclockwise(m, b, startvertex, searchpoint, rightvertex);
-    rightflag = rightccw > 0.0;
-  }
-  if (leftccw == 0.0) {
-    return LEFTCOLLINEAR;
-  } else if (rightccw == 0.0) {
-    return RIGHTCOLLINEAR;
-  } else {
-    return WITHIN;
-  }
-}
-
-/*****************************************************************************/
-/*                                                                           */
-/*  segmentintersection()   Find the intersection of an existing segment     */
-/*                          and a segment that is being inserted.  Insert    */
-/*                          a vertex at the intersection, splitting an       */
-/*                          existing subsegment.                             */
-/*                                                                           */
-/*  The segment being inserted connects the apex of splittri to endpoint2.   */
-/*  splitsubseg is the subsegment being split, and MUST adjoin splittri.     */
-/*  Hence, endpoints of the subsegment being split are the origin and        */
-/*  destination of splittri.                                                 */
-/*                                                                           */
-/*  On completion, splittri is a handle having the newly inserted            */
-/*  intersection point as its origin, and endpoint1 as its destination.      */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef ANSI_DECLARATORS
-void segmentintersection(struct mesh *m, struct behavior *b,
-                         struct otri *splittri, struct osub *splitsubseg,
-                         vertex endpoint2)
-#else /* not ANSI_DECLARATORS */
-void segmentintersection(m, b, splittri, splitsubseg, endpoint2)
-struct mesh *m;
-struct behavior *b;
-struct otri *splittri;
-struct osub *splitsubseg;
-vertex endpoint2;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  struct osub opposubseg;
-  vertex endpoint1;
-  vertex torg, tdest;
-  vertex leftvertex, rightvertex;
-  vertex newvertex;
-  enum insertvertexresult success;
-  enum finddirectionresult collinear;
-  REAL ex, ey;
-  REAL tx, ty;
-  REAL etx, ety;
-  REAL split, denom;
-  int i;
-  triangle ptr;                       /* Temporary variable used by onext(). */
-  subseg sptr;                        /* Temporary variable used by snext(). */
-
-  /* Find the other three segment endpoints. */
-  apex(*splittri, endpoint1);
-  org(*splittri, torg);
-  dest(*splittri, tdest);
-  /* Segment intersection formulae; see the Antonio reference. */
-  tx = tdest[0] - torg[0];
-  ty = tdest[1] - torg[1];
-  ex = endpoint2[0] - endpoint1[0];
-  ey = endpoint2[1] - endpoint1[1];
-  etx = torg[0] - endpoint2[0];
-  ety = torg[1] - endpoint2[1];
-  denom = ty * ex - tx * ey;
-  if (denom == 0.0) {
-    printf("Internal error in segmentintersection():");
-    printf("  Attempt to find intersection of parallel segments.\n");
-    internalerror();
-  }
-  split = (ey * etx - ex * ety) / denom;
-  /* Create the new vertex. */
-  newvertex = (vertex) poolalloc(&m->vertices);
-  /* Interpolate its coordinate and attributes. */
-  for (i = 0; i < 2 + m->nextras; i++) {
-    newvertex[i] = torg[i] + split * (tdest[i] - torg[i]);
-  }
-  setvertexmark(newvertex, mark(*splitsubseg));
-  setvertextype(newvertex, INPUTVERTEX);
-  if (b->verbose > 1) {
-    printf(
-  "  Splitting subsegment (%.12g, %.12g) (%.12g, %.12g) at (%.12g, %.12g).\n",
-           torg[0], torg[1], tdest[0], tdest[1], newvertex[0], newvertex[1]);
-  }
-  /* Insert the intersection vertex.  This should always succeed. */
-  success = insertvertex(m, b, newvertex, splittri, splitsubseg, 0, 0);
-  if (success != SUCCESSFULVERTEX) {
-    printf("Internal error in segmentintersection():\n");
-    printf("  Failure to split a segment.\n");
-    internalerror();
-  }
-  /* Record a triangle whose origin is the new vertex. */
-  setvertex2tri(newvertex, encode(*splittri));
-  if (m->steinerleft > 0) {
-    m->steinerleft--;
-  }
-
-  /* Divide the segment into two, and correct the segment endpoints. */
-  ssymself(*splitsubseg);
-  spivot(*splitsubseg, opposubseg);
-  sdissolve(*splitsubseg);
-  sdissolve(opposubseg);
-  do {
-    setsegorg(*splitsubseg, newvertex);
-    snextself(*splitsubseg);
-  } while (splitsubseg->ss != m->dummysub);
-  do {
-    setsegorg(opposubseg, newvertex);
-    snextself(opposubseg);
-  } while (opposubseg.ss != m->dummysub);
-
-  /* Inserting the vertex may have caused edge flips.  We wish to rediscover */
-  /*   the edge connecting endpoint1 to the new intersection vertex.         */
-  collinear = finddirection(m, b, splittri, endpoint1);
-  dest(*splittri, rightvertex);
-  apex(*splittri, leftvertex);
-  if ((leftvertex[0] == endpoint1[0]) && (leftvertex[1] == endpoint1[1])) {
-    onextself(*splittri);
-  } else if ((rightvertex[0] != endpoint1[0]) ||
-             (rightvertex[1] != endpoint1[1])) {
-    printf("Internal error in segmentintersection():\n");
-    printf("  Topological inconsistency after splitting a segment.\n");
-    internalerror();
-  }
-  /* `splittri' should have destination endpoint1. */
-}
-
-/*****************************************************************************/
-/*                                                                           */
-/*  scoutsegment()   Scout the first triangle on the path from one endpoint  */
-/*                   to another, and check for completion (reaching the      */
-/*                   second endpoint), a collinear vertex, or the            */
-/*                   intersection of two segments.                           */
-/*                                                                           */
-/*  Returns one if the entire segment is successfully inserted, and zero if  */
-/*  the job must be finished by conformingedge() or constrainededge().       */
-/*                                                                           */
-/*  If the first triangle on the path has the second endpoint as its         */
-/*  destination or apex, a subsegment is inserted and the job is done.       */
-/*                                                                           */
-/*  If the first triangle on the path has a destination or apex that lies on */
-/*  the segment, a subsegment is inserted connecting the first endpoint to   */
-/*  the collinear vertex, and the search is continued from the collinear     */
-/*  vertex.                                                                  */
-/*                                                                           */
-/*  If the first triangle on the path has a subsegment opposite its origin,  */
-/*  then there is a segment that intersects the segment being inserted.      */
-/*  Their intersection vertex is inserted, splitting the subsegment.         */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef ANSI_DECLARATORS
-int scoutsegment(struct mesh *m, struct behavior *b, struct otri *searchtri,
-                 vertex endpoint2, int newmark)
-#else /* not ANSI_DECLARATORS */
-int scoutsegment(m, b, searchtri, endpoint2, newmark)
-struct mesh *m;
-struct behavior *b;
-struct otri *searchtri;
-vertex endpoint2;
-int newmark;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  struct otri crosstri;
-  struct osub crosssubseg;
-  vertex leftvertex, rightvertex;
-  enum finddirectionresult collinear;
-  subseg sptr;                      /* Temporary variable used by tspivot(). */
-
-  collinear = finddirection(m, b, searchtri, endpoint2);
-  dest(*searchtri, rightvertex);
-  apex(*searchtri, leftvertex);
-  if (((leftvertex[0] == endpoint2[0]) && (leftvertex[1] == endpoint2[1])) ||
-      ((rightvertex[0] == endpoint2[0]) && (rightvertex[1] == endpoint2[1]))) {
-    /* The segment is already an edge in the mesh. */
-    if ((leftvertex[0] == endpoint2[0]) && (leftvertex[1] == endpoint2[1])) {
-      lprevself(*searchtri);
-    }
-    /* Insert a subsegment, if there isn't already one there. */
-    insertsubseg(m, b, searchtri, newmark);
-    return 1;
-  } else if (collinear == LEFTCOLLINEAR) {
-    /* We've collided with a vertex between the segment's endpoints. */
-    /* Make the collinear vertex be the triangle's origin. */
-    lprevself(*searchtri);
-    insertsubseg(m, b, searchtri, newmark);
-    /* Insert the remainder of the segment. */
-    return scoutsegment(m, b, searchtri, endpoint2, newmark);
-  } else if (collinear == RIGHTCOLLINEAR) {
-    /* We've collided with a vertex between the segment's endpoints. */
-    insertsubseg(m, b, searchtri, newmark);
-    /* Make the collinear vertex be the triangle's origin. */
-    lnextself(*searchtri);
-    /* Insert the remainder of the segment. */
-    return scoutsegment(m, b, searchtri, endpoint2, newmark);
-  } else {
-    lnext(*searchtri, crosstri);
-    tspivot(crosstri, crosssubseg);
-    /* Check for a crossing segment. */
-    if (crosssubseg.ss == m->dummysub) {
-      return 0;
-    } else {
-      /* Insert a vertex at the intersection. */
-      segmentintersection(m, b, &crosstri, &crosssubseg, endpoint2);
-      otricopy(crosstri, *searchtri);
-      insertsubseg(m, b, searchtri, newmark);
-      /* Insert the remainder of the segment. */
-      return scoutsegment(m, b, searchtri, endpoint2, newmark);
-    }
-  }
-}
-
-/*****************************************************************************/
-/*                                                                           */
-/*  conformingedge()   Force a segment into a conforming Delaunay            */
-/*                     triangulation by inserting a vertex at its midpoint,  */
-/*                     and recursively forcing in the two half-segments if   */
-/*                     necessary.                                            */
-/*                                                                           */
-/*  Generates a sequence of subsegments connecting `endpoint1' to            */
-/*  `endpoint2'.  `newmark' is the boundary marker of the segment, assigned  */
-/*  to each new splitting vertex and subsegment.                             */
-/*                                                                           */
-/*  Note that conformingedge() does not always maintain the conforming       */
-/*  Delaunay property.  Once inserted, segments are locked into place;       */
-/*  vertices inserted later (to force other segments in) may render these    */
-/*  fixed segments non-Delaunay.  The conforming Delaunay property will be   */
-/*  restored by enforcequality() by splitting encroached subsegments.        */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifndef REDUCED
-#ifndef CDT_ONLY
-
-#ifdef ANSI_DECLARATORS
-void conformingedge(struct mesh *m, struct behavior *b,
-                    vertex endpoint1, vertex endpoint2, int newmark)
-#else /* not ANSI_DECLARATORS */
-void conformingedge(m, b, endpoint1, endpoint2, newmark)
-struct mesh *m;
-struct behavior *b;
-vertex endpoint1;
-vertex endpoint2;
-int newmark;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  struct otri searchtri1, searchtri2;
-  struct osub brokensubseg;
-  vertex newvertex;
-  vertex midvertex1, midvertex2;
-  enum insertvertexresult success;
-  int i;
-  subseg sptr;                      /* Temporary variable used by tspivot(). */
-
-  if (b->verbose > 2) {
-    printf("Forcing segment into triangulation by recursive splitting:\n");
-    printf("  (%.12g, %.12g) (%.12g, %.12g)\n", endpoint1[0], endpoint1[1],
-           endpoint2[0], endpoint2[1]);
-  }
-  /* Create a new vertex to insert in the middle of the segment. */
-  newvertex = (vertex) poolalloc(&m->vertices);
-  /* Interpolate coordinates and attributes. */
-  for (i = 0; i < 2 + m->nextras; i++) {
-    newvertex[i] = 0.5 * (endpoint1[i] + endpoint2[i]);
-  }
-  setvertexmark(newvertex, newmark);
-  setvertextype(newvertex, SEGMENTVERTEX);
-  /* No known triangle to search from. */
-  searchtri1.tri = m->dummytri;
-  /* Attempt to insert the new vertex. */
-  success = insertvertex(m, b, newvertex, &searchtri1, (struct osub *) NULL,
-                         0, 0);
-  if (success == DUPLICATEVERTEX) {
-    if (b->verbose > 2) {
-      printf("  Segment intersects existing vertex (%.12g, %.12g).\n",
-             newvertex[0], newvertex[1]);
-    }
-    /* Use the vertex that's already there. */
-    vertexdealloc(m, newvertex);
-    org(searchtri1, newvertex);
-  } else {
-    if (success == VIOLATINGVERTEX) {
-      if (b->verbose > 2) {
-        printf("  Two segments intersect at (%.12g, %.12g).\n",
-               newvertex[0], newvertex[1]);
-      }
-      /* By fluke, we've landed right on another segment.  Split it. */
-      tspivot(searchtri1, brokensubseg);
-      success = insertvertex(m, b, newvertex, &searchtri1, &brokensubseg,
-                             0, 0);
-      if (success != SUCCESSFULVERTEX) {
-        printf("Internal error in conformingedge():\n");
-        printf("  Failure to split a segment.\n");
-        internalerror();
-      }
-    }
-    /* The vertex has been inserted successfully. */
-    if (m->steinerleft > 0) {
-      m->steinerleft--;
-    }
-  }
-  otricopy(searchtri1, searchtri2);
-  /* `searchtri1' and `searchtri2' are fastened at their origins to         */
-  /*   `newvertex', and will be directed toward `endpoint1' and `endpoint2' */
-  /*   respectively.  First, we must get `searchtri2' out of the way so it  */
-  /*   won't be invalidated during the insertion of the first half of the   */
-  /*   segment.                                                             */
-  finddirection(m, b, &searchtri2, endpoint2);
-  if (!scoutsegment(m, b, &searchtri1, endpoint1, newmark)) {
-    /* The origin of searchtri1 may have changed if a collision with an */
-    /*   intervening vertex on the segment occurred.                    */
-    org(searchtri1, midvertex1);
-    conformingedge(m, b, midvertex1, endpoint1, newmark);
-  }
-  if (!scoutsegment(m, b, &searchtri2, endpoint2, newmark)) {
-    /* The origin of searchtri2 may have changed if a collision with an */
-    /*   intervening vertex on the segment occurred.                    */
-    org(searchtri2, midvertex2);
-    conformingedge(m, b, midvertex2, endpoint2, newmark);
-  }
-}
-
-#endif /* not CDT_ONLY */
-#endif /* not REDUCED */
-
-/*****************************************************************************/
-/*                                                                           */
-/*  delaunayfixup()   Enforce the Delaunay condition at an edge, fanning out */
-/*                    recursively from an existing vertex.  Pay special      */
-/*                    attention to stacking inverted triangles.              */
-/*                                                                           */
-/*  This is a support routine for inserting segments into a constrained      */
-/*  Delaunay triangulation.                                                  */
-/*                                                                           */
-/*  The origin of fixuptri is treated as if it has just been inserted, and   */
-/*  the local Delaunay condition needs to be enforced.  It is only enforced  */
-/*  in one sector, however, that being the angular range defined by          */
-/*  fixuptri.                                                                */
-/*                                                                           */
-/*  This routine also needs to make decisions regarding the "stacking" of    */
-/*  triangles.  (Read the description of constrainededge() below before      */
-/*  reading on here, so you understand the algorithm.)  If the position of   */
-/*  the new vertex (the origin of fixuptri) indicates that the vertex before */
-/*  it on the polygon is a reflex vertex, then "stack" the triangle by       */
-/*  doing nothing.  (fixuptri is an inverted triangle, which is how stacked  */
-/*  triangles are identified.)                                               */
-/*                                                                           */
-/*  Otherwise, check whether the vertex before that was a reflex vertex.     */
-/*  If so, perform an edge flip, thereby eliminating an inverted triangle    */
-/*  (popping it off the stack).  The edge flip may result in the creation    */
-/*  of a new inverted triangle, depending on whether or not the new vertex   */
-/*  is visible to the vertex three edges behind on the polygon.              */
-/*                                                                           */
-/*  If neither of the two vertices behind the new vertex are reflex          */
-/*  vertices, fixuptri and fartri, the triangle opposite it, are not         */
-/*  inverted; hence, ensure that the edge between them is locally Delaunay.  */
-/*                                                                           */
-/*  `leftside' indicates whether or not fixuptri is to the left of the       */
-/*  segment being inserted.  (Imagine that the segment is pointing up from   */
-/*  endpoint1 to endpoint2.)                                                 */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef ANSI_DECLARATORS
-void delaunayfixup(struct mesh *m, struct behavior *b,
-                   struct otri *fixuptri, int leftside)
-#else /* not ANSI_DECLARATORS */
-void delaunayfixup(m, b, fixuptri, leftside)
-struct mesh *m;
-struct behavior *b;
-struct otri *fixuptri;
-int leftside;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  struct otri neartri;
-  struct otri fartri;
-  struct osub faredge;
-  vertex nearvertex, leftvertex, rightvertex, farvertex;
-  triangle ptr;                         /* Temporary variable used by sym(). */
-  subseg sptr;                      /* Temporary variable used by tspivot(). */
-
-  lnext(*fixuptri, neartri);
-  sym(neartri, fartri);
-  /* Check if the edge opposite the origin of fixuptri can be flipped. */
-  if (fartri.tri == m->dummytri) {
-    return;
-  }
-  tspivot(neartri, faredge);
-  if (faredge.ss != m->dummysub) {
-    return;
-  }
-  /* Find all the relevant vertices. */
-  apex(neartri, nearvertex);
-  org(neartri, leftvertex);
-  dest(neartri, rightvertex);
-  apex(fartri, farvertex);
-  /* Check whether the previous polygon vertex is a reflex vertex. */
-  if (leftside) {
-    if (counterclockwise(m, b, nearvertex, leftvertex, farvertex) <= 0.0) {
-      /* leftvertex is a reflex vertex too.  Nothing can */
-      /*   be done until a convex section is found.      */
-      return;
-    }
-  } else {
-    if (counterclockwise(m, b, farvertex, rightvertex, nearvertex) <= 0.0) {
-      /* rightvertex is a reflex vertex too.  Nothing can */
-      /*   be done until a convex section is found.       */
-      return;
-    }
-  }
-  if (counterclockwise(m, b, rightvertex, leftvertex, farvertex) > 0.0) {
-    /* fartri is not an inverted triangle, and farvertex is not a reflex */
-    /*   vertex.  As there are no reflex vertices, fixuptri isn't an     */
-    /*   inverted triangle, either.  Hence, test the edge between the    */
-    /*   triangles to ensure it is locally Delaunay.                     */
-    if (incircle(m, b, leftvertex, farvertex, rightvertex, nearvertex) <=
-        0.0) {
-      return;
-    }
-    /* Not locally Delaunay; go on to an edge flip. */
-  }        /* else fartri is inverted; remove it from the stack by flipping. */
-  flip(m, b, &neartri);
-  lprevself(*fixuptri);    /* Restore the origin of fixuptri after the flip. */
-  /* Recursively process the two triangles that result from the flip. */
-  delaunayfixup(m, b, fixuptri, leftside);
-  delaunayfixup(m, b, &fartri, leftside);
-}
-
-/*****************************************************************************/
-/*                                                                           */
-/*  constrainededge()   Force a segment into a constrained Delaunay          */
-/*                      triangulation by deleting the triangles it           */
-/*                      intersects, and triangulating the polygons that      */
-/*                      form on each side of it.                             */
-/*                                                                           */
-/*  Generates a single subsegment connecting `endpoint1' to `endpoint2'.     */
-/*  The triangle `starttri' has `endpoint1' as its origin.  `newmark' is the */
-/*  boundary marker of the segment.                                          */
-/*                                                                           */
-/*  To insert a segment, every triangle whose interior intersects the        */
-/*  segment is deleted.  The union of these deleted triangles is a polygon   */
-/*  (which is not necessarily monotone, but is close enough), which is       */
-/*  divided into two polygons by the new segment.  This routine's task is    */
-/*  to generate the Delaunay triangulation of these two polygons.            */
-/*                                                                           */
-/*  You might think of this routine's behavior as a two-step process.  The   */
-/*  first step is to walk from endpoint1 to endpoint2, flipping each edge    */
-/*  encountered.  This step creates a fan of edges connected to endpoint1,   */
-/*  including the desired edge to endpoint2.  The second step enforces the   */
-/*  Delaunay condition on each side of the segment in an incremental manner: */
-/*  proceeding along the polygon from endpoint1 to endpoint2 (this is done   */
-/*  independently on each side of the segment), each vertex is "enforced"    */
-/*  as if it had just been inserted, but affecting only the previous         */
-/*  vertices.  The result is the same as if the vertices had been inserted   */
-/*  in the order they appear on the polygon, so the result is Delaunay.      */
-/*                                                                           */
-/*  In truth, constrainededge() interleaves these two steps.  The procedure  */
-/*  walks from endpoint1 to endpoint2, and each time an edge is encountered  */
-/*  and flipped, the newly exposed vertex (at the far end of the flipped     */
-/*  edge) is "enforced" upon the previously flipped edges, usually affecting */
-/*  only one side of the polygon (depending upon which side of the segment   */
-/*  the vertex falls on).                                                    */
-/*                                                                           */
-/*  The algorithm is complicated by the need to handle polygons that are not */
-/*  convex.  Although the polygon is not necessarily monotone, it can be     */
-/*  triangulated in a manner similar to the stack-based algorithms for       */
-/*  monotone polygons.  For each reflex vertex (local concavity) of the      */
-/*  polygon, there will be an inverted triangle formed by one of the edge    */
-/*  flips.  (An inverted triangle is one with negative area - that is, its   */
-/*  vertices are arranged in clockwise order - and is best thought of as a   */
-/*  wrinkle in the fabric of the mesh.)  Each inverted triangle can be       */
-/*  thought of as a reflex vertex pushed on the stack, waiting to be fixed   */
-/*  later.                                                                   */
-/*                                                                           */
-/*  A reflex vertex is popped from the stack when a vertex is inserted that  */
-/*  is visible to the reflex vertex.  (However, if the vertex behind the     */
-/*  reflex vertex is not visible to the reflex vertex, a new inverted        */
-/*  triangle will take its place on the stack.)  These details are handled   */
-/*  by the delaunayfixup() routine above.                                    */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef ANSI_DECLARATORS
-void constrainededge(struct mesh *m, struct behavior *b,
-                     struct otri *starttri, vertex endpoint2, int newmark)
-#else /* not ANSI_DECLARATORS */
-void constrainededge(m, b, starttri, endpoint2, newmark)
-struct mesh *m;
-struct behavior *b;
-struct otri *starttri;
-vertex endpoint2;
-int newmark;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  struct otri fixuptri, fixuptri2;
-  struct osub crosssubseg;
-  vertex endpoint1;
-  vertex farvertex;
-  REAL area;
-  int collision;
-  int done;
-  triangle ptr;             /* Temporary variable used by sym() and oprev(). */
-  subseg sptr;                      /* Temporary variable used by tspivot(). */
-
-  org(*starttri, endpoint1);
-  lnext(*starttri, fixuptri);
-  flip(m, b, &fixuptri);
-  /* `collision' indicates whether we have found a vertex directly */
-  /*   between endpoint1 and endpoint2.                            */
-  collision = 0;
-  done = 0;
-  do {
-    org(fixuptri, farvertex);
-    /* `farvertex' is the extreme point of the polygon we are "digging" */
-    /*   to get from endpoint1 to endpoint2.                           */
-    if ((farvertex[0] == endpoint2[0]) && (farvertex[1] == endpoint2[1])) {
-      oprev(fixuptri, fixuptri2);
-      /* Enforce the Delaunay condition around endpoint2. */
-      delaunayfixup(m, b, &fixuptri, 0);
-      delaunayfixup(m, b, &fixuptri2, 1);
-      done = 1;
-    } else {
-      /* Check whether farvertex is to the left or right of the segment */
-      /*   being inserted, to decide which edge of fixuptri to dig      */
-      /*   through next.                                                */
-      area = counterclockwise(m, b, endpoint1, endpoint2, farvertex);
-      if (area == 0.0) {
-        /* We've collided with a vertex between endpoint1 and endpoint2. */
-        collision = 1;
-        oprev(fixuptri, fixuptri2);
-        /* Enforce the Delaunay condition around farvertex. */
-        delaunayfixup(m, b, &fixuptri, 0);
-        delaunayfixup(m, b, &fixuptri2, 1);
-        done = 1;
-      } else {
-        if (area > 0.0) {        /* farvertex is to the left of the segment. */
-          oprev(fixuptri, fixuptri2);
-          /* Enforce the Delaunay condition around farvertex, on the */
-          /*   left side of the segment only.                        */
-          delaunayfixup(m, b, &fixuptri2, 1);
-          /* Flip the edge that crosses the segment.  After the edge is */
-          /*   flipped, one of its endpoints is the fan vertex, and the */
-          /*   destination of fixuptri is the fan vertex.               */
-          lprevself(fixuptri);
-        } else {                /* farvertex is to the right of the segment. */
-          delaunayfixup(m, b, &fixuptri, 0);
-          /* Flip the edge that crosses the segment.  After the edge is */
-          /*   flipped, one of its endpoints is the fan vertex, and the */
-          /*   destination of fixuptri is the fan vertex.               */
-          oprevself(fixuptri);
-        }
-        /* Check for two intersecting segments. */
-        tspivot(fixuptri, crosssubseg);
-        if (crosssubseg.ss == m->dummysub) {
-          flip(m, b, &fixuptri);    /* May create inverted triangle at left. */
-        } else {
-          /* We've collided with a segment between endpoint1 and endpoint2. */
-          collision = 1;
-          /* Insert a vertex at the intersection. */
-          segmentintersection(m, b, &fixuptri, &crosssubseg, endpoint2);
-          done = 1;
-        }
-      }
-    }
-  } while (!done);
-  /* Insert a subsegment to make the segment permanent. */
-  insertsubseg(m, b, &fixuptri, newmark);
-  /* If there was a collision with an interceding vertex, install another */
-  /*   segment connecting that vertex with endpoint2.                     */
-  if (collision) {
-    /* Insert the remainder of the segment. */
-    if (!scoutsegment(m, b, &fixuptri, endpoint2, newmark)) {
-      constrainededge(m, b, &fixuptri, endpoint2, newmark);
-    }
-  }
-}
-
-/*****************************************************************************/
-/*                                                                           */
-/*  insertsegment()   Insert a PSLG segment into a triangulation.            */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef ANSI_DECLARATORS
-void insertsegment(struct mesh *m, struct behavior *b,
-                   vertex endpoint1, vertex endpoint2, int newmark)
-#else /* not ANSI_DECLARATORS */
-void insertsegment(m, b, endpoint1, endpoint2, newmark)
-struct mesh *m;
-struct behavior *b;
-vertex endpoint1;
-vertex endpoint2;
-int newmark;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  struct otri searchtri1, searchtri2;
-  triangle encodedtri;
-  vertex checkvertex;
-  triangle ptr;                         /* Temporary variable used by sym(). */
-
-  if (b->verbose > 1) {
-    printf("  Connecting (%.12g, %.12g) to (%.12g, %.12g).\n",
-           endpoint1[0], endpoint1[1], endpoint2[0], endpoint2[1]);
-  }
-
-  /* Find a triangle whose origin is the segment's first endpoint. */
-  checkvertex = (vertex) NULL;
-  encodedtri = vertex2tri(endpoint1);
-  if (encodedtri != (triangle) NULL) {
-    decode(encodedtri, searchtri1);
-    org(searchtri1, checkvertex);
-  }
-  if (checkvertex != endpoint1) {
-    /* Find a boundary triangle to search from. */
-    searchtri1.tri = m->dummytri;
-    searchtri1.orient = 0;
-    symself(searchtri1);
-    /* Search for the segment's first endpoint by point location. */
-    if (locate(m, b, endpoint1, &searchtri1) != ONVERTEX) {
-      printf(
-        "Internal error in insertsegment():  Unable to locate PSLG vertex\n");
-      printf("  (%.12g, %.12g) in triangulation.\n",
-             endpoint1[0], endpoint1[1]);
-      internalerror();
-    }
-  }
-  /* Remember this triangle to improve subsequent point location. */
-  otricopy(searchtri1, m->recenttri);
-  /* Scout the beginnings of a path from the first endpoint */
-  /*   toward the second.                                   */
-  if (scoutsegment(m, b, &searchtri1, endpoint2, newmark)) {
-    /* The segment was easily inserted. */
-    return;
-  }
-  /* The first endpoint may have changed if a collision with an intervening */
-  /*   vertex on the segment occurred.                                      */
-  org(searchtri1, endpoint1);
-
-  /* Find a triangle whose origin is the segment's second endpoint. */
-  checkvertex = (vertex) NULL;
-  encodedtri = vertex2tri(endpoint2);
-  if (encodedtri != (triangle) NULL) {
-    decode(encodedtri, searchtri2);
-    org(searchtri2, checkvertex);
-  }
-  if (checkvertex != endpoint2) {
-    /* Find a boundary triangle to search from. */
-    searchtri2.tri = m->dummytri;
-    searchtri2.orient = 0;
-    symself(searchtri2);
-    /* Search for the segment's second endpoint by point location. */
-    if (locate(m, b, endpoint2, &searchtri2) != ONVERTEX) {
-      printf(
-        "Internal error in insertsegment():  Unable to locate PSLG vertex\n");
-      printf("  (%.12g, %.12g) in triangulation.\n",
-             endpoint2[0], endpoint2[1]);
-      internalerror();
-    }
-  }
-  /* Remember this triangle to improve subsequent point location. */
-  otricopy(searchtri2, m->recenttri);
-  /* Scout the beginnings of a path from the second endpoint */
-  /*   toward the first.                                     */
-  if (scoutsegment(m, b, &searchtri2, endpoint1, newmark)) {
-    /* The segment was easily inserted. */
-    return;
-  }
-  /* The second endpoint may have changed if a collision with an intervening */
-  /*   vertex on the segment occurred.                                       */
-  org(searchtri2, endpoint2);
-
-#ifndef REDUCED
-#ifndef CDT_ONLY
-  if (b->splitseg) {
-    /* Insert vertices to force the segment into the triangulation. */
-    conformingedge(m, b, endpoint1, endpoint2, newmark);
-  } else {
-#endif /* not CDT_ONLY */
-#endif /* not REDUCED */
-    /* Insert the segment directly into the triangulation. */
-    constrainededge(m, b, &searchtri1, endpoint2, newmark);
-#ifndef REDUCED
-#ifndef CDT_ONLY
-  }
-#endif /* not CDT_ONLY */
-#endif /* not REDUCED */
-}
-
-/*****************************************************************************/
-/*                                                                           */
-/*  markhull()   Cover the convex hull of a triangulation with subsegments.  */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef ANSI_DECLARATORS
-void markhull(struct mesh *m, struct behavior *b)
-#else /* not ANSI_DECLARATORS */
-void markhull(m, b)
-struct mesh *m;
-struct behavior *b;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  struct otri hulltri;
-  struct otri nexttri;
-  struct otri starttri;
-  triangle ptr;             /* Temporary variable used by sym() and oprev(). */
-
-  /* Find a triangle handle on the hull. */
-  hulltri.tri = m->dummytri;
-  hulltri.orient = 0;
-  symself(hulltri);
-  /* Remember where we started so we know when to stop. */
-  otricopy(hulltri, starttri);
-  /* Go once counterclockwise around the convex hull. */
-  do {
-    /* Create a subsegment if there isn't already one here. */
-    insertsubseg(m, b, &hulltri, 1);
-    /* To find the next hull edge, go clockwise around the next vertex. */
-    lnextself(hulltri);
-    oprev(hulltri, nexttri);
-    while (nexttri.tri != m->dummytri) {
-      otricopy(nexttri, hulltri);
-      oprev(hulltri, nexttri);
-    }
-  } while (!otriequal(hulltri, starttri));
-}
-
-/*****************************************************************************/
-/*                                                                           */
-/*  formskeleton()   Create the segments of a triangulation, including PSLG  */
-/*                   segments and edges on the convex hull.                  */
-/*                                                                           */
-/*  The PSLG segments are read from a .poly file.  The return value is the   */
-/*  number of segments in the file.                                          */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef TRILIBRARY
-
-#ifdef ANSI_DECLARATORS
-void formskeleton(struct mesh *m, struct behavior *b, int *segmentlist,
-                  int *segmentmarkerlist, int numberofsegments)
-#else /* not ANSI_DECLARATORS */
-void formskeleton(m, b, segmentlist, segmentmarkerlist, numberofsegments)
-struct mesh *m;
-struct behavior *b;
-int *segmentlist;
-int *segmentmarkerlist;
-int numberofsegments;
-#endif /* not ANSI_DECLARATORS */
-
-#else /* not TRILIBRARY */
-
-#ifdef ANSI_DECLARATORS
-void formskeleton(struct mesh *m, struct behavior *b,
-                  FILE *polyfile, char *polyfilename)
-#else /* not ANSI_DECLARATORS */
-void formskeleton(m, b, polyfile, polyfilename)
-struct mesh *m;
-struct behavior *b;
-FILE *polyfile;
-char *polyfilename;
-#endif /* not ANSI_DECLARATORS */
-
-#endif /* not TRILIBRARY */
-
-{
-#ifdef TRILIBRARY
-  char polyfilename[6];
-  int index;
-#else /* not TRILIBRARY */
-  char inputline[INPUTLINESIZE];
-  char *stringptr;
-#endif /* not TRILIBRARY */
-  vertex endpoint1, endpoint2;
-  int segmentmarkers;
-  int end1, end2;
-  int boundmarker;
-  int i;
-
-  if (b->poly) {
-    if (!b->quiet) {
-      printf("Recovering segments in Delaunay triangulation.\n");
-    }
-#ifdef TRILIBRARY
-    strcpy(polyfilename, "input");
-    m->insegments = numberofsegments;
-    segmentmarkers = segmentmarkerlist != (int *) NULL;
-    index = 0;
-#else /* not TRILIBRARY */
-    /* Read the segments from a .poly file. */
-    /* Read number of segments and number of boundary markers. */
-    stringptr = readline(inputline, polyfile, polyfilename);
-    m->insegments = (int) strtol(stringptr, &stringptr, 0);
-    stringptr = findfield(stringptr);
-    if (*stringptr == '\0') {
-      segmentmarkers = 0;
-    } else {
-      segmentmarkers = (int) strtol(stringptr, &stringptr, 0);
-    }
-#endif /* not TRILIBRARY */
-    /* If the input vertices are collinear, there is no triangulation, */
-    /*   so don't try to insert segments.                              */
-    if (m->triangles.items == 0) {
-      return;
-    }
-
-    /* If segments are to be inserted, compute a mapping */
-    /*   from vertices to triangles.                     */
-    if (m->insegments > 0) {
-      makevertexmap(m, b);
-      if (b->verbose) {
-        printf("  Recovering PSLG segments.\n");
-      }
-    }
-
-    boundmarker = 0;
-    /* Read and insert the segments. */
-    for (i = 0; i < m->insegments; i++) {
-#ifdef TRILIBRARY
-      end1 = segmentlist[index++];
-      end2 = segmentlist[index++];
-      if (segmentmarkers) {
-        boundmarker = segmentmarkerlist[i];
-      }
-#else /* not TRILIBRARY */
-      stringptr = readline(inputline, polyfile, b->inpolyfilename);
-      stringptr = findfield(stringptr);
-      if (*stringptr == '\0') {
-        printf("Error:  Segment %d has no endpoints in %s.\n",
-               b->firstnumber + i, polyfilename);
-        triexit(1);
-      } else {
-        end1 = (int) strtol(stringptr, &stringptr, 0);
-      }
-      stringptr = findfield(stringptr);
-      if (*stringptr == '\0') {
-        printf("Error:  Segment %d is missing its second endpoint in %s.\n",
-               b->firstnumber + i, polyfilename);
-        triexit(1);
-      } else {
-        end2 = (int) strtol(stringptr, &stringptr, 0);
-      }
-      if (segmentmarkers) {
-        stringptr = findfield(stringptr);
-        if (*stringptr == '\0') {
-          boundmarker = 0;
-        } else {
-          boundmarker = (int) strtol(stringptr, &stringptr, 0);
-        }
-      }
-#endif /* not TRILIBRARY */
-      if ((end1 < b->firstnumber) ||
-          (end1 >= b->firstnumber + m->invertices)) {
-        if (!b->quiet) {
-          printf("Warning:  Invalid first endpoint of segment %d in %s.\n",
-                 b->firstnumber + i, polyfilename);
-        }
-      } else if ((end2 < b->firstnumber) ||
-                 (end2 >= b->firstnumber + m->invertices)) {
-        if (!b->quiet) {
-          printf("Warning:  Invalid second endpoint of segment %d in %s.\n",
-                 b->firstnumber + i, polyfilename);
-        }
-      } else {
-        /* Find the vertices numbered `end1' and `end2'. */
-        endpoint1 = getvertex(m, b, end1);
-        endpoint2 = getvertex(m, b, end2);
-        if ((endpoint1[0] == endpoint2[0]) && (endpoint1[1] == endpoint2[1])) {
-          if (!b->quiet) {
-            printf("Warning:  Endpoints of segment %d are coincident in %s.\n",
-                   b->firstnumber + i, polyfilename);
-          }
-        } else {
-          insertsegment(m, b, endpoint1, endpoint2, boundmarker);
-        }
-      }
-    }
-  } else {
-    m->insegments = 0;
-  }
-  if (b->convex || !b->poly) {
-    /* Enclose the convex hull with subsegments. */
-    if (b->verbose) {
-      printf("  Enclosing convex hull with segments.\n");
-    }
-    markhull(m, b);
-  }
-}
-
-/**                                                                         **/
-/**                                                                         **/
-/********* Segment insertion ends here                               *********/
-
-/********* Carving out holes and concavities begins here             *********/
-/**                                                                         **/
-/**                                                                         **/
-
-/*****************************************************************************/
-/*                                                                           */
-/*  infecthull()   Virally infect all of the triangles of the convex hull    */
-/*                 that are not protected by subsegments.  Where there are   */
-/*                 subsegments, set boundary markers as appropriate.         */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef ANSI_DECLARATORS
-void infecthull(struct mesh *m, struct behavior *b)
-#else /* not ANSI_DECLARATORS */
-void infecthull(m, b)
-struct mesh *m;
-struct behavior *b;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  struct otri hulltri;
-  struct otri nexttri;
-  struct otri starttri;
-  struct osub hullsubseg;
-  triangle **deadtriangle;
-  vertex horg, hdest;
-  triangle ptr;                         /* Temporary variable used by sym(). */
-  subseg sptr;                      /* Temporary variable used by tspivot(). */
-
-  if (b->verbose) {
-    printf("  Marking concavities (external triangles) for elimination.\n");
-  }
-  /* Find a triangle handle on the hull. */
-  hulltri.tri = m->dummytri;
-  hulltri.orient = 0;
-  symself(hulltri);
-  /* Remember where we started so we know when to stop. */
-  otricopy(hulltri, starttri);
-  /* Go once counterclockwise around the convex hull. */
-  do {
-    /* Ignore triangles that are already infected. */
-    if (!infected(hulltri)) {
-      /* Is the triangle protected by a subsegment? */
-      tspivot(hulltri, hullsubseg);
-      if (hullsubseg.ss == m->dummysub) {
-        /* The triangle is not protected; infect it. */
-        if (!infected(hulltri)) {
-          infect(hulltri);
-          deadtriangle = (triangle **) poolalloc(&m->viri);
-          *deadtriangle = hulltri.tri;
-        }
-      } else {
-        /* The triangle is protected; set boundary markers if appropriate. */
-        if (mark(hullsubseg) == 0) {
-          setmark(hullsubseg, 1);
-          org(hulltri, horg);
-          dest(hulltri, hdest);
-          if (vertexmark(horg) == 0) {
-            setvertexmark(horg, 1);
-          }
-          if (vertexmark(hdest) == 0) {
-            setvertexmark(hdest, 1);
-          }
-        }
-      }
-    }
-    /* To find the next hull edge, go clockwise around the next vertex. */
-    lnextself(hulltri);
-    oprev(hulltri, nexttri);
-    while (nexttri.tri != m->dummytri) {
-      otricopy(nexttri, hulltri);
-      oprev(hulltri, nexttri);
-    }
-  } while (!otriequal(hulltri, starttri));
-}
-
-/*****************************************************************************/
-/*                                                                           */
-/*  plague()   Spread the virus from all infected triangles to any neighbors */
-/*             not protected by subsegments.  Delete all infected triangles. */
-/*                                                                           */
-/*  This is the procedure that actually creates holes and concavities.       */
-/*                                                                           */
-/*  This procedure operates in two phases.  The first phase identifies all   */
-/*  the triangles that will die, and marks them as infected.  They are       */
-/*  marked to ensure that each triangle is added to the virus pool only      */
-/*  once, so the procedure will terminate.                                   */
-/*                                                                           */
-/*  The second phase actually eliminates the infected triangles.  It also    */
-/*  eliminates orphaned vertices.                                            */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef ANSI_DECLARATORS
-void plague(struct mesh *m, struct behavior *b)
-#else /* not ANSI_DECLARATORS */
-void plague(m, b)
-struct mesh *m;
-struct behavior *b;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  struct otri testtri;
-  struct otri neighbor;
-  triangle **virusloop;
-  triangle **deadtriangle;
-  struct osub neighborsubseg;
-  vertex testvertex;
-  vertex norg, ndest;
-  vertex deadorg, deaddest, deadapex;
-  int killorg;
-  triangle ptr;             /* Temporary variable used by sym() and onext(). */
-  subseg sptr;                      /* Temporary variable used by tspivot(). */
-
-  if (b->verbose) {
-    printf("  Marking neighbors of marked triangles.\n");
-  }
-  /* Loop through all the infected triangles, spreading the virus to */
-  /*   their neighbors, then to their neighbors' neighbors.          */
-  traversalinit(&m->viri);
-  virusloop = (triangle **) traverse(&m->viri);
-  while (virusloop != (triangle **) NULL) {
-    testtri.tri = *virusloop;
-    /* A triangle is marked as infected by messing with one of its pointers */
-    /*   to subsegments, setting it to an illegal value.  Hence, we have to */
-    /*   temporarily uninfect this triangle so that we can examine its      */
-    /*   adjacent subsegments.                                              */
-    uninfect(testtri);
-    if (b->verbose > 2) {
-      /* Assign the triangle an orientation for convenience in */
-      /*   checking its vertices.                              */
-      testtri.orient = 0;
-      org(testtri, deadorg);
-      dest(testtri, deaddest);
-      apex(testtri, deadapex);
-      printf("    Checking (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n",
-             deadorg[0], deadorg[1], deaddest[0], deaddest[1],
-             deadapex[0], deadapex[1]);
-    }
-    /* Check each of the triangle's three neighbors. */
-    for (testtri.orient = 0; testtri.orient < 3; testtri.orient++) {
-      /* Find the neighbor. */
-      sym(testtri, neighbor);
-      /* Check for a subsegment between the triangle and its neighbor. */
-      tspivot(testtri, neighborsubseg);
-      /* Check if the neighbor is nonexistent or already infected. */
-      if ((neighbor.tri == m->dummytri) || infected(neighbor)) {
-        if (neighborsubseg.ss != m->dummysub) {
-          /* There is a subsegment separating the triangle from its      */
-          /*   neighbor, but both triangles are dying, so the subsegment */
-          /*   dies too.                                                 */
-          subsegdealloc(m, neighborsubseg.ss);
-          if (neighbor.tri != m->dummytri) {
-            /* Make sure the subsegment doesn't get deallocated again */
-            /*   later when the infected neighbor is visited.         */
-            uninfect(neighbor);
-            tsdissolve(neighbor);
-            infect(neighbor);
-          }
-        }
-      } else {                   /* The neighbor exists and is not infected. */
-        if (neighborsubseg.ss == m->dummysub) {
-          /* There is no subsegment protecting the neighbor, so */
-          /*   the neighbor becomes infected.                   */
-          if (b->verbose > 2) {
-            org(neighbor, deadorg);
-            dest(neighbor, deaddest);
-            apex(neighbor, deadapex);
-            printf(
-              "    Marking (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n",
-                   deadorg[0], deadorg[1], deaddest[0], deaddest[1],
-                   deadapex[0], deadapex[1]);
-          }
-          infect(neighbor);
-          /* Ensure that the neighbor's neighbors will be infected. */
-          deadtriangle = (triangle **) poolalloc(&m->viri);
-          *deadtriangle = neighbor.tri;
-        } else {               /* The neighbor is protected by a subsegment. */
-          /* Remove this triangle from the subsegment. */
-          stdissolve(neighborsubseg);
-          /* The subsegment becomes a boundary.  Set markers accordingly. */
-          if (mark(neighborsubseg) == 0) {
-            setmark(neighborsubseg, 1);
-          }
-          org(neighbor, norg);
-          dest(neighbor, ndest);
-          if (vertexmark(norg) == 0) {
-            setvertexmark(norg, 1);
-          }
-          if (vertexmark(ndest) == 0) {
-            setvertexmark(ndest, 1);
-          }
-        }
-      }
-    }
-    /* Remark the triangle as infected, so it doesn't get added to the */
-    /*   virus pool again.                                             */
-    infect(testtri);
-    virusloop = (triangle **) traverse(&m->viri);
-  }
-
-  if (b->verbose) {
-    printf("  Deleting marked triangles.\n");
-  }
-
-  traversalinit(&m->viri);
-  virusloop = (triangle **) traverse(&m->viri);
-  while (virusloop != (triangle **) NULL) {
-    testtri.tri = *virusloop;
-
-    /* Check each of the three corners of the triangle for elimination. */
-    /*   This is done by walking around each vertex, checking if it is  */
-    /*   still connected to at least one live triangle.                 */
-    for (testtri.orient = 0; testtri.orient < 3; testtri.orient++) {
-      org(testtri, testvertex);
-      /* Check if the vertex has already been tested. */
-      if (testvertex != (vertex) NULL) {
-        killorg = 1;
-        /* Mark the corner of the triangle as having been tested. */
-        setorg(testtri, NULL);
-        /* Walk counterclockwise about the vertex. */
-        onext(testtri, neighbor);
-        /* Stop upon reaching a boundary or the starting triangle. */
-        while ((neighbor.tri != m->dummytri) &&
-               (!otriequal(neighbor, testtri))) {
-          if (infected(neighbor)) {
-            /* Mark the corner of this triangle as having been tested. */
-            setorg(neighbor, NULL);
-          } else {
-            /* A live triangle.  The vertex survives. */
-            killorg = 0;
-          }
-          /* Walk counterclockwise about the vertex. */
-          onextself(neighbor);
-        }
-        /* If we reached a boundary, we must walk clockwise as well. */
-        if (neighbor.tri == m->dummytri) {
-          /* Walk clockwise about the vertex. */
-          oprev(testtri, neighbor);
-          /* Stop upon reaching a boundary. */
-          while (neighbor.tri != m->dummytri) {
-            if (infected(neighbor)) {
-            /* Mark the corner of this triangle as having been tested. */
-              setorg(neighbor, NULL);
-            } else {
-              /* A live triangle.  The vertex survives. */
-              killorg = 0;
-            }
-            /* Walk clockwise about the vertex. */
-            oprevself(neighbor);
-          }
-        }
-        if (killorg) {
-          if (b->verbose > 1) {
-            printf("    Deleting vertex (%.12g, %.12g)\n",
-                   testvertex[0], testvertex[1]);
-          }
-          setvertextype(testvertex, UNDEADVERTEX);
-          m->undeads++;
-        }
-      }
-    }
-
-    /* Record changes in the number of boundary edges, and disconnect */
-    /*   dead triangles from their neighbors.                         */
-    for (testtri.orient = 0; testtri.orient < 3; testtri.orient++) {
-      sym(testtri, neighbor);
-      if (neighbor.tri == m->dummytri) {
-        /* There is no neighboring triangle on this edge, so this edge    */
-        /*   is a boundary edge.  This triangle is being deleted, so this */
-        /*   boundary edge is deleted.                                    */
-        m->hullsize--;
-      } else {
-        /* Disconnect the triangle from its neighbor. */
-        dissolve(neighbor);
-        /* There is a neighboring triangle on this edge, so this edge */
-        /*   becomes a boundary edge when this triangle is deleted.   */
-        m->hullsize++;
-      }
-    }
-    /* Return the dead triangle to the pool of triangles. */
-    triangledealloc(m, testtri.tri);
-    virusloop = (triangle **) traverse(&m->viri);
-  }
-  /* Empty the virus pool. */
-  poolrestart(&m->viri);
-}
-
-/*****************************************************************************/
-/*                                                                           */
-/*  regionplague()   Spread regional attributes and/or area constraints      */
-/*                   (from a .poly file) throughout the mesh.                */
-/*                                                                           */
-/*  This procedure operates in two phases.  The first phase spreads an       */
-/*  attribute and/or an area constraint through a (segment-bounded) region.  */
-/*  The triangles are marked to ensure that each triangle is added to the    */
-/*  virus pool only once, so the procedure will terminate.                   */
-/*                                                                           */
-/*  The second phase uninfects all infected triangles, returning them to     */
-/*  normal.                                                                  */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef ANSI_DECLARATORS
-void regionplague(struct mesh *m, struct behavior *b,
-                  REAL attribute, REAL area)
-#else /* not ANSI_DECLARATORS */
-void regionplague(m, b, attribute, area)
-struct mesh *m;
-struct behavior *b;
-REAL attribute;
-REAL area;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  struct otri testtri;
-  struct otri neighbor;
-  triangle **virusloop;
-  triangle **regiontri;
-  struct osub neighborsubseg;
-  vertex regionorg, regiondest, regionapex;
-  triangle ptr;             /* Temporary variable used by sym() and onext(). */
-  subseg sptr;                      /* Temporary variable used by tspivot(). */
-
-  if (b->verbose > 1) {
-    printf("  Marking neighbors of marked triangles.\n");
-  }
-  /* Loop through all the infected triangles, spreading the attribute      */
-  /*   and/or area constraint to their neighbors, then to their neighbors' */
-  /*   neighbors.                                                          */
-  traversalinit(&m->viri);
-  virusloop = (triangle **) traverse(&m->viri);
-  while (virusloop != (triangle **) NULL) {
-    testtri.tri = *virusloop;
-    /* A triangle is marked as infected by messing with one of its pointers */
-    /*   to subsegments, setting it to an illegal value.  Hence, we have to */
-    /*   temporarily uninfect this triangle so that we can examine its      */
-    /*   adjacent subsegments.                                              */
-    uninfect(testtri);
-    if (b->regionattrib) {
-      /* Set an attribute. */
-      setelemattribute(testtri, m->eextras, attribute);
-    }
-    if (b->vararea) {
-      /* Set an area constraint. */
-      setareabound(testtri, area);
-    }
-    if (b->verbose > 2) {
-      /* Assign the triangle an orientation for convenience in */
-      /*   checking its vertices.                              */
-      testtri.orient = 0;
-      org(testtri, regionorg);
-      dest(testtri, regiondest);
-      apex(testtri, regionapex);
-      printf("    Checking (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n",
-             regionorg[0], regionorg[1], regiondest[0], regiondest[1],
-             regionapex[0], regionapex[1]);
-    }
-    /* Check each of the triangle's three neighbors. */
-    for (testtri.orient = 0; testtri.orient < 3; testtri.orient++) {
-      /* Find the neighbor. */
-      sym(testtri, neighbor);
-      /* Check for a subsegment between the triangle and its neighbor. */
-      tspivot(testtri, neighborsubseg);
-      /* Make sure the neighbor exists, is not already infected, and */
-      /*   isn't protected by a subsegment.                          */
-      if ((neighbor.tri != m->dummytri) && !infected(neighbor)
-          && (neighborsubseg.ss == m->dummysub)) {
-        if (b->verbose > 2) {
-          org(neighbor, regionorg);
-          dest(neighbor, regiondest);
-          apex(neighbor, regionapex);
-          printf("    Marking (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n",
-                 regionorg[0], regionorg[1], regiondest[0], regiondest[1],
-                 regionapex[0], regionapex[1]);
-        }
-        /* Infect the neighbor. */
-        infect(neighbor);
-        /* Ensure that the neighbor's neighbors will be infected. */
-        regiontri = (triangle **) poolalloc(&m->viri);
-        *regiontri = neighbor.tri;
-      }
-    }
-    /* Remark the triangle as infected, so it doesn't get added to the */
-    /*   virus pool again.                                             */
-    infect(testtri);
-    virusloop = (triangle **) traverse(&m->viri);
-  }
-
-  /* Uninfect all triangles. */
-  if (b->verbose > 1) {
-    printf("  Unmarking marked triangles.\n");
-  }
-  traversalinit(&m->viri);
-  virusloop = (triangle **) traverse(&m->viri);
-  while (virusloop != (triangle **) NULL) {
-    testtri.tri = *virusloop;
-    uninfect(testtri);
-    virusloop = (triangle **) traverse(&m->viri);
-  }
-  /* Empty the virus pool. */
-  poolrestart(&m->viri);
-}
-
-/*****************************************************************************/
-/*                                                                           */
-/*  carveholes()   Find the holes and infect them.  Find the area            */
-/*                 constraints and infect them.  Infect the convex hull.     */
-/*                 Spread the infection and kill triangles.  Spread the      */
-/*                 area constraints.                                         */
-/*                                                                           */
-/*  This routine mainly calls other routines to carry out all these          */
-/*  functions.                                                               */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef ANSI_DECLARATORS
-void carveholes(struct mesh *m, struct behavior *b, REAL *holelist, int holes,
-                REAL *regionlist, int regions)
-#else /* not ANSI_DECLARATORS */
-void carveholes(m, b, holelist, holes, regionlist, regions)
-struct mesh *m;
-struct behavior *b;
-REAL *holelist;
-int holes;
-REAL *regionlist;
-int regions;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  struct otri searchtri;
-  struct otri triangleloop;
-  struct otri *regiontris;
-  triangle **holetri;
-  triangle **regiontri;
-  vertex searchorg, searchdest;
-  enum locateresult intersect;
-  int i;
-  triangle ptr;                         /* Temporary variable used by sym(). */
-
-  if (!(b->quiet || (b->noholes && b->convex))) {
-    printf("Removing unwanted triangles.\n");
-    if (b->verbose && (holes > 0)) {
-      printf("  Marking holes for elimination.\n");
-    }
-  }
-
-  if (regions > 0) {
-    /* Allocate storage for the triangles in which region points fall. */
-    regiontris = (struct otri *) trimalloc(regions *
-                                           (int) sizeof(struct otri));
-  } else {
-    regiontris = (struct otri *) NULL;
-  }
-
-  if (((holes > 0) && !b->noholes) || !b->convex || (regions > 0)) {
-    /* Initialize a pool of viri to be used for holes, concavities, */
-    /*   regional attributes, and/or regional area constraints.     */
-    poolinit(&m->viri, sizeof(triangle *), VIRUSPERBLOCK, VIRUSPERBLOCK, 0);
-  }
-
-  if (!b->convex) {
-    /* Mark as infected any unprotected triangles on the boundary. */
-    /*   This is one way by which concavities are created.         */
-    infecthull(m, b);
-  }
-
-  if ((holes > 0) && !b->noholes) {
-    /* Infect each triangle in which a hole lies. */
-    for (i = 0; i < 2 * holes; i += 2) {
-      /* Ignore holes that aren't within the bounds of the mesh. */
-      if ((holelist[i] >= m->xmin) && (holelist[i] <= m->xmax)
-          && (holelist[i + 1] >= m->ymin) && (holelist[i + 1] <= m->ymax)) {
-        /* Start searching from some triangle on the outer boundary. */
-        searchtri.tri = m->dummytri;
-        searchtri.orient = 0;
-        symself(searchtri);
-        /* Ensure that the hole is to the left of this boundary edge; */
-        /*   otherwise, locate() will falsely report that the hole    */
-        /*   falls within the starting triangle.                      */
-        org(searchtri, searchorg);
-        dest(searchtri, searchdest);
-        if (counterclockwise(m, b, searchorg, searchdest, &holelist[i]) >
-            0.0) {
-          /* Find a triangle that contains the hole. */
-          intersect = locate(m, b, &holelist[i], &searchtri);
-          if ((intersect != OUTSIDE) && (!infected(searchtri))) {
-            /* Infect the triangle.  This is done by marking the triangle  */
-            /*   as infected and including the triangle in the virus pool. */
-            infect(searchtri);
-            holetri = (triangle **) poolalloc(&m->viri);
-            *holetri = searchtri.tri;
-          }
-        }
-      }
-    }
-  }
-
-  /* Now, we have to find all the regions BEFORE we carve the holes, because */
-  /*   locate() won't work when the triangulation is no longer convex.       */
-  /*   (Incidentally, this is the reason why regional attributes and area    */
-  /*   constraints can't be used when refining a preexisting mesh, which     */
-  /*   might not be convex; they can only be used with a freshly             */
-  /*   triangulated PSLG.)                                                   */
-  if (regions > 0) {
-    /* Find the starting triangle for each region. */
-    for (i = 0; i < regions; i++) {
-      regiontris[i].tri = m->dummytri;
-      /* Ignore region points that aren't within the bounds of the mesh. */
-      if ((regionlist[4 * i] >= m->xmin) && (regionlist[4 * i] <= m->xmax) &&
-          (regionlist[4 * i + 1] >= m->ymin) &&
-          (regionlist[4 * i + 1] <= m->ymax)) {
-        /* Start searching from some triangle on the outer boundary. */
-        searchtri.tri = m->dummytri;
-        searchtri.orient = 0;
-        symself(searchtri);
-        /* Ensure that the region point is to the left of this boundary */
-        /*   edge; otherwise, locate() will falsely report that the     */
-        /*   region point falls within the starting triangle.           */
-        org(searchtri, searchorg);
-        dest(searchtri, searchdest);
-        if (counterclockwise(m, b, searchorg, searchdest, &regionlist[4 * i]) >
-            0.0) {
-          /* Find a triangle that contains the region point. */
-          intersect = locate(m, b, &regionlist[4 * i], &searchtri);
-          if ((intersect != OUTSIDE) && (!infected(searchtri))) {
-            /* Record the triangle for processing after the */
-            /*   holes have been carved.                    */
-            otricopy(searchtri, regiontris[i]);
-          }
-        }
-      }
-    }
-  }
-
-  if (m->viri.items > 0) {
-    /* Carve the holes and concavities. */
-    plague(m, b);
-  }
-  /* The virus pool should be empty now. */
-
-  if (regions > 0) {
-    if (!b->quiet) {
-      if (b->regionattrib) {
-        if (b->vararea) {
-          printf("Spreading regional attributes and area constraints.\n");
-        } else {
-          printf("Spreading regional attributes.\n");
-        }
-      } else {
-        printf("Spreading regional area constraints.\n");
-      }
-    }
-    if (b->regionattrib && !b->refine) {
-      /* Assign every triangle a regional attribute of zero. */
-      traversalinit(&m->triangles);
-      triangleloop.orient = 0;
-      triangleloop.tri = triangletraverse(m);
-      while (triangleloop.tri != (triangle *) NULL) {
-        setelemattribute(triangleloop, m->eextras, 0.0);
-        triangleloop.tri = triangletraverse(m);
-      }
-    }
-    for (i = 0; i < regions; i++) {
-      if (regiontris[i].tri != m->dummytri) {
-        /* Make sure the triangle under consideration still exists. */
-        /*   It may have been eaten by the virus.                   */
-        if (!deadtri(regiontris[i].tri)) {
-          /* Put one triangle in the virus pool. */
-          infect(regiontris[i]);
-          regiontri = (triangle **) poolalloc(&m->viri);
-          *regiontri = regiontris[i].tri;
-          /* Apply one region's attribute and/or area constraint. */
-          regionplague(m, b, regionlist[4 * i + 2], regionlist[4 * i + 3]);
-          /* The virus pool should be empty now. */
-        }
-      }
-    }
-    if (b->regionattrib && !b->refine) {
-      /* Note the fact that each triangle has an additional attribute. */
-      m->eextras++;
-    }
-  }
-
-  /* Free up memory. */
-  if (((holes > 0) && !b->noholes) || !b->convex || (regions > 0)) {
-    pooldeinit(&m->viri);
-  }
-  if (regions > 0) {
-    trifree((VOID *) regiontris);
-  }
-}
-
-/**                                                                         **/
-/**                                                                         **/
-/********* Carving out holes and concavities ends here               *********/
-
-/********* Mesh quality maintenance begins here                      *********/
-/**                                                                         **/
-/**                                                                         **/
-
-/*****************************************************************************/
-/*                                                                           */
-/*  tallyencs()   Traverse the entire list of subsegments, and check each    */
-/*                to see if it is encroached.  If so, add it to the list.    */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifndef CDT_ONLY
-
-#ifdef ANSI_DECLARATORS
-void tallyencs(struct mesh *m, struct behavior *b)
-#else /* not ANSI_DECLARATORS */
-void tallyencs(m, b)
-struct mesh *m;
-struct behavior *b;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  struct osub subsegloop;
-  int dummy;
-
-  traversalinit(&m->subsegs);
-  subsegloop.ssorient = 0;
-  subsegloop.ss = subsegtraverse(m);
-  while (subsegloop.ss != (subseg *) NULL) {
-    /* If the segment is encroached, add it to the list. */
-    dummy = checkseg4encroach(m, b, &subsegloop);
-    subsegloop.ss = subsegtraverse(m);
-  }
-}
-
-#endif /* not CDT_ONLY */
-
-/*****************************************************************************/
-/*                                                                           */
-/*  precisionerror()  Print an error message for precision problems.         */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifndef CDT_ONLY
-
-void precisionerror()
-{
-  printf("Try increasing the area criterion and/or reducing the minimum\n");
-  printf("  allowable angle so that tiny triangles are not created.\n");
-#ifdef SINGLE
-  printf("Alternatively, try recompiling me with double precision\n");
-  printf("  arithmetic (by removing \"#define SINGLE\" from the\n");
-  printf("  source file or \"-DSINGLE\" from the makefile).\n");
-#endif /* SINGLE */
-}
-
-#endif /* not CDT_ONLY */
-
-/*****************************************************************************/
-/*                                                                           */
-/*  splitencsegs()   Split all the encroached subsegments.                   */
-/*                                                                           */
-/*  Each encroached subsegment is repaired by splitting it - inserting a     */
-/*  vertex at or near its midpoint.  Newly inserted vertices may encroach    */
-/*  upon other subsegments; these are also repaired.                         */
-/*                                                                           */
-/*  `triflaws' is a flag that specifies whether one should take note of new  */
-/*  bad triangles that result from inserting vertices to repair encroached   */
-/*  subsegments.                                                             */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifndef CDT_ONLY
-
-#ifdef ANSI_DECLARATORS
-void splitencsegs(struct mesh *m, struct behavior *b, int triflaws)
-#else /* not ANSI_DECLARATORS */
-void splitencsegs(m, b, triflaws)
-struct mesh *m;
-struct behavior *b;
-int triflaws;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  struct otri enctri;
-  struct otri testtri;
-  struct osub testsh;
-  struct osub currentenc;
-  struct badsubseg *encloop;
-  vertex eorg, edest, eapex;
-  vertex newvertex;
-  enum insertvertexresult success;
-  REAL segmentlength, nearestpoweroftwo;
-  REAL split;
-  REAL multiplier, divisor;
-  int acuteorg, acuteorg2, acutedest, acutedest2;
-  int dummy;
-  int i;
-  triangle ptr;                     /* Temporary variable used by stpivot(). */
-  subseg sptr;                        /* Temporary variable used by snext(). */
-
-  /* Note that steinerleft == -1 if an unlimited number */
-  /*   of Steiner points is allowed.                    */
-  while ((m->badsubsegs.items > 0) && (m->steinerleft != 0)) {
-    traversalinit(&m->badsubsegs);
-    encloop = badsubsegtraverse(m);
-    while ((encloop != (struct badsubseg *) NULL) && (m->steinerleft != 0)) {
-      sdecode(encloop->encsubseg, currentenc);
-      sorg(currentenc, eorg);
-      sdest(currentenc, edest);
-      /* Make sure that this segment is still the same segment it was   */
-      /*   when it was determined to be encroached.  If the segment was */
-      /*   enqueued multiple times (because several newly inserted      */
-      /*   vertices encroached it), it may have already been split.     */
-      if (!deadsubseg(currentenc.ss) &&
-          (eorg == encloop->subsegorg) && (edest == encloop->subsegdest)) {
-        /* To decide where to split a segment, we need to know if the   */
-        /*   segment shares an endpoint with an adjacent segment.       */
-        /*   The concern is that, if we simply split every encroached   */
-        /*   segment in its center, two adjacent segments with a small  */
-        /*   angle between them might lead to an infinite loop; each    */
-        /*   vertex added to split one segment will encroach upon the   */
-        /*   other segment, which must then be split with a vertex that */
-        /*   will encroach upon the first segment, and so on forever.   */
-        /* To avoid this, imagine a set of concentric circles, whose    */
-        /*   radii are powers of two, about each segment endpoint.      */
-        /*   These concentric circles determine where the segment is    */
-        /*   split.  (If both endpoints are shared with adjacent        */
-        /*   segments, split the segment in the middle, and apply the   */
-        /*   concentric circles for later splittings.)                  */
-
-        /* Is the origin shared with another segment? */
-        stpivot(currentenc, enctri);
-        lnext(enctri, testtri);
-        tspivot(testtri, testsh);
-        acuteorg = testsh.ss != m->dummysub;
-        /* Is the destination shared with another segment? */
-        lnextself(testtri);
-        tspivot(testtri, testsh);
-        acutedest = testsh.ss != m->dummysub;
-
-        /* If we're using Chew's algorithm (rather than Ruppert's) */
-        /*   to define encroachment, delete free vertices from the */
-        /*   subsegment's diametral circle.                        */
-        if (!b->conformdel && !acuteorg && !acutedest) {
-          apex(enctri, eapex);
-          while ((vertextype(eapex) == FREEVERTEX) &&
-                 ((eorg[0] - eapex[0]) * (edest[0] - eapex[0]) +
-                  (eorg[1] - eapex[1]) * (edest[1] - eapex[1]) < 0.0)) {
-            deletevertex(m, b, &testtri);
-            stpivot(currentenc, enctri);
-            apex(enctri, eapex);
-            lprev(enctri, testtri);
-          }
-        }
-
-        /* Now, check the other side of the segment, if there's a triangle */
-        /*   there.                                                        */
-        sym(enctri, testtri);
-        if (testtri.tri != m->dummytri) {
-          /* Is the destination shared with another segment? */
-          lnextself(testtri);
-          tspivot(testtri, testsh);
-          acutedest2 = testsh.ss != m->dummysub;
-          acutedest = acutedest || acutedest2;
-          /* Is the origin shared with another segment? */
-          lnextself(testtri);
-          tspivot(testtri, testsh);
-          acuteorg2 = testsh.ss != m->dummysub;
-          acuteorg = acuteorg || acuteorg2;
-
-          /* Delete free vertices from the subsegment's diametral circle. */
-          if (!b->conformdel && !acuteorg2 && !acutedest2) {
-            org(testtri, eapex);
-            while ((vertextype(eapex) == FREEVERTEX) &&
-                   ((eorg[0] - eapex[0]) * (edest[0] - eapex[0]) +
-                    (eorg[1] - eapex[1]) * (edest[1] - eapex[1]) < 0.0)) {
-              deletevertex(m, b, &testtri);
-              sym(enctri, testtri);
-              apex(testtri, eapex);
-              lprevself(testtri);
-            }
-          }
-        }
-
-        /* Use the concentric circles if exactly one endpoint is shared */
-        /*   with another adjacent segment.                             */
-        if (acuteorg || acutedest) {
-          segmentlength = sqrt((edest[0] - eorg[0]) * (edest[0] - eorg[0]) +
-                               (edest[1] - eorg[1]) * (edest[1] - eorg[1]));
-          /* Find the power of two that most evenly splits the segment.  */
-          /*   The worst case is a 2:1 ratio between subsegment lengths. */
-          nearestpoweroftwo = 1.0;
-          while (segmentlength > 3.0 * nearestpoweroftwo) {
-            nearestpoweroftwo *= 2.0;
-          }
-          while (segmentlength < 1.5 * nearestpoweroftwo) {
-            nearestpoweroftwo *= 0.5;
-          }
-          /* Where do we split the segment? */
-          split = nearestpoweroftwo / segmentlength;
-          if (acutedest) {
-            split = 1.0 - split;
-          }
-        } else {
-          /* If we're not worried about adjacent segments, split */
-          /*   this segment in the middle.                       */
-          split = 0.5;
-        }
-
-        /* Create the new vertex. */
-        newvertex = (vertex) poolalloc(&m->vertices);
-        /* Interpolate its coordinate and attributes. */
-        for (i = 0; i < 2 + m->nextras; i++) {
-          newvertex[i] = eorg[i] + split * (edest[i] - eorg[i]);
-        }
-
-        if (!b->noexact) {
-          /* Roundoff in the above calculation may yield a `newvertex'   */
-          /*   that is not precisely collinear with `eorg' and `edest'.  */
-          /*   Improve collinearity by one step of iterative refinement. */
-          multiplier = counterclockwise(m, b, eorg, edest, newvertex);
-          divisor = ((eorg[0] - edest[0]) * (eorg[0] - edest[0]) +
-                     (eorg[1] - edest[1]) * (eorg[1] - edest[1]));
-          if ((multiplier != 0.0) && (divisor != 0.0)) {
-            multiplier = multiplier / divisor;
-            /* Watch out for NANs. */
-            if (multiplier == multiplier) {
-              newvertex[0] += multiplier * (edest[1] - eorg[1]);
-              newvertex[1] += multiplier * (eorg[0] - edest[0]);
-            }
-          }
-        }
-
-        setvertexmark(newvertex, mark(currentenc));
-        setvertextype(newvertex, SEGMENTVERTEX);
-        if (b->verbose > 1) {
-          printf(
-  "  Splitting subsegment (%.12g, %.12g) (%.12g, %.12g) at (%.12g, %.12g).\n",
-                 eorg[0], eorg[1], edest[0], edest[1],
-                 newvertex[0], newvertex[1]);
-        }
-        /* Check whether the new vertex lies on an endpoint. */
-        if (((newvertex[0] == eorg[0]) && (newvertex[1] == eorg[1])) ||
-            ((newvertex[0] == edest[0]) && (newvertex[1] == edest[1]))) {
-          printf("Error:  Ran out of precision at (%.12g, %.12g).\n",
-                 newvertex[0], newvertex[1]);
-          printf("I attempted to split a segment to a smaller size than\n");
-          printf("  can be accommodated by the finite precision of\n");
-          printf("  floating point arithmetic.\n");
-          precisionerror();
-          triexit(1);
-        }
-        /* Insert the splitting vertex.  This should always succeed. */
-        success = insertvertex(m, b, newvertex, &enctri, &currentenc,
-                               1, triflaws);
-        if ((success != SUCCESSFULVERTEX) && (success != ENCROACHINGVERTEX)) {
-          printf("Internal error in splitencsegs():\n");
-          printf("  Failure to split a segment.\n");
-          internalerror();
-        }
-        if (m->steinerleft > 0) {
-          m->steinerleft--;
-        }
-        /* Check the two new subsegments to see if they're encroached. */
-        dummy = checkseg4encroach(m, b, &currentenc);
-        snextself(currentenc);
-        dummy = checkseg4encroach(m, b, &currentenc);
-      }
-
-      badsubsegdealloc(m, encloop);
-      encloop = badsubsegtraverse(m);
-    }
-  }
-}
-
-#endif /* not CDT_ONLY */
-
-/*****************************************************************************/
-/*                                                                           */
-/*  tallyfaces()   Test every triangle in the mesh for quality measures.     */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifndef CDT_ONLY
-
-#ifdef ANSI_DECLARATORS
-void tallyfaces(struct mesh *m, struct behavior *b)
-#else /* not ANSI_DECLARATORS */
-void tallyfaces(m, b)
-struct mesh *m;
-struct behavior *b;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  struct otri triangleloop;
-
-  if (b->verbose) {
-    printf("  Making a list of bad triangles.\n");
-  }
-  traversalinit(&m->triangles);
-  triangleloop.orient = 0;
-  triangleloop.tri = triangletraverse(m);
-  while (triangleloop.tri != (triangle *) NULL) {
-    /* If the triangle is bad, enqueue it. */
-    testtriangle(m, b, &triangleloop);
-    triangleloop.tri = triangletraverse(m);
-  }
-}
-
-#endif /* not CDT_ONLY */
-
-/*****************************************************************************/
-/*                                                                           */
-/*  splittriangle()   Inserts a vertex at the circumcenter of a triangle.    */
-/*                    Deletes the newly inserted vertex if it encroaches     */
-/*                    upon a segment.                                        */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifndef CDT_ONLY
-
-#ifdef ANSI_DECLARATORS
-void splittriangle(struct mesh *m, struct behavior *b,
-                   struct badtriang *badtri)
-#else /* not ANSI_DECLARATORS */
-void splittriangle(m, b, badtri)
-struct mesh *m;
-struct behavior *b;
-struct badtriang *badtri;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  struct otri badotri;
-  vertex borg, bdest, bapex;
-  vertex newvertex;
-  REAL xi, eta;
-  enum insertvertexresult success;
-  int errorflag;
-  int i;
-
-  decode(badtri->poortri, badotri);
-  org(badotri, borg);
-  dest(badotri, bdest);
-  apex(badotri, bapex);
-  /* Make sure that this triangle is still the same triangle it was      */
-  /*   when it was tested and determined to be of bad quality.           */
-  /*   Subsequent transformations may have made it a different triangle. */
-  if (!deadtri(badotri.tri) && (borg == badtri->triangorg) &&
-      (bdest == badtri->triangdest) && (bapex == badtri->triangapex)) {
-    if (b->verbose > 1) {
-      printf("  Splitting this triangle at its circumcenter:\n");
-      printf("    (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n", borg[0],
-             borg[1], bdest[0], bdest[1], bapex[0], bapex[1]);
-    }
-
-    errorflag = 0;
-    /* Create a new vertex at the triangle's circumcenter. */
-    newvertex = (vertex) poolalloc(&m->vertices);
-    findcircumcenter(m, b, borg, bdest, bapex, newvertex, &xi, &eta, 1);
-
-    /* Check whether the new vertex lies on a triangle vertex. */
-    if (((newvertex[0] == borg[0]) && (newvertex[1] == borg[1])) ||
-        ((newvertex[0] == bdest[0]) && (newvertex[1] == bdest[1])) ||
-        ((newvertex[0] == bapex[0]) && (newvertex[1] == bapex[1]))) {
-      if (!b->quiet) {
-        printf(
-             "Warning:  New vertex (%.12g, %.12g) falls on existing vertex.\n",
-               newvertex[0], newvertex[1]);
-        errorflag = 1;
-      }
-      vertexdealloc(m, newvertex);
-    } else {
-      for (i = 2; i < 2 + m->nextras; i++) {
-        /* Interpolate the vertex attributes at the circumcenter. */
-        newvertex[i] = borg[i] + xi * (bdest[i] - borg[i])
-                              + eta * (bapex[i] - borg[i]);
-      }
-      /* The new vertex must be in the interior, and therefore is a */
-      /*   free vertex with a marker of zero.                       */
-      setvertexmark(newvertex, 0);
-      setvertextype(newvertex, FREEVERTEX);
-
-      /* Ensure that the handle `badotri' does not represent the longest  */
-      /*   edge of the triangle.  This ensures that the circumcenter must */
-      /*   fall to the left of this edge, so point location will work.    */
-      /*   (If the angle org-apex-dest exceeds 90 degrees, then the       */
-      /*   circumcenter lies outside the org-dest edge, and eta is        */
-      /*   negative.  Roundoff error might prevent eta from being         */
-      /*   negative when it should be, so I test eta against xi.)         */
-      if (eta < xi) {
-        lprevself(badotri);
-      }
-
-      /* Insert the circumcenter, searching from the edge of the triangle, */
-      /*   and maintain the Delaunay property of the triangulation.        */
-      success = insertvertex(m, b, newvertex, &badotri, (struct osub *) NULL,
-                             1, 1);
-      if (success == SUCCESSFULVERTEX) {
-        if (m->steinerleft > 0) {
-          m->steinerleft--;
-        }
-      } else if (success == ENCROACHINGVERTEX) {
-        /* If the newly inserted vertex encroaches upon a subsegment, */
-        /*   delete the new vertex.                                   */
-        undovertex(m, b);
-        if (b->verbose > 1) {
-          printf("  Rejecting (%.12g, %.12g).\n", newvertex[0], newvertex[1]);
-        }
-        vertexdealloc(m, newvertex);
-      } else if (success == VIOLATINGVERTEX) {
-        /* Failed to insert the new vertex, but some subsegment was */
-        /*   marked as being encroached.                            */
-        vertexdealloc(m, newvertex);
-      } else {                                 /* success == DUPLICATEVERTEX */
-        /* Couldn't insert the new vertex because a vertex is already there. */
-        if (!b->quiet) {
-          printf(
-            "Warning:  New vertex (%.12g, %.12g) falls on existing vertex.\n",
-                 newvertex[0], newvertex[1]);
-          errorflag = 1;
-        }
-        vertexdealloc(m, newvertex);
-      }
-    }
-    if (errorflag) {
-      if (b->verbose) {
-        printf("  The new vertex is at the circumcenter of triangle\n");
-        printf("    (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n",
-               borg[0], borg[1], bdest[0], bdest[1], bapex[0], bapex[1]);
-      }
-      printf("This probably means that I am trying to refine triangles\n");
-      printf("  to a smaller size than can be accommodated by the finite\n");
-      printf("  precision of floating point arithmetic.  (You can be\n");
-      printf("  sure of this if I fail to terminate.)\n");
-      precisionerror();
-    }
-  }
-}
-
-#endif /* not CDT_ONLY */
-
-/*****************************************************************************/
-/*                                                                           */
-/*  enforcequality()   Remove all the encroached subsegments and bad         */
-/*                     triangles from the triangulation.                     */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifndef CDT_ONLY
-
-#ifdef ANSI_DECLARATORS
-void enforcequality(struct mesh *m, struct behavior *b)
-#else /* not ANSI_DECLARATORS */
-void enforcequality(m, b)
-struct mesh *m;
-struct behavior *b;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  struct badtriang *badtri;
-  int i;
-
-  if (!b->quiet) {
-    printf("Adding Steiner points to enforce quality.\n");
-  }
-  /* Initialize the pool of encroached subsegments. */
-  poolinit(&m->badsubsegs, sizeof(struct badsubseg), BADSUBSEGPERBLOCK,
-           BADSUBSEGPERBLOCK, 0);
-  if (b->verbose) {
-    printf("  Looking for encroached subsegments.\n");
-  }
-  /* Test all segments to see if they're encroached. */
-  tallyencs(m, b);
-  if (b->verbose && (m->badsubsegs.items > 0)) {
-    printf("  Splitting encroached subsegments.\n");
-  }
-  /* Fix encroached subsegments without noting bad triangles. */
-  splitencsegs(m, b, 0);
-  /* At this point, if we haven't run out of Steiner points, the */
-  /*   triangulation should be (conforming) Delaunay.            */
-
-  /* Next, we worry about enforcing triangle quality. */
-  if ((b->minangle > 0.0) || b->vararea || b->fixedarea || b->usertest) {
-    /* Initialize the pool of bad triangles. */
-    poolinit(&m->badtriangles, sizeof(struct badtriang), BADTRIPERBLOCK,
-             BADTRIPERBLOCK, 0);
-    /* Initialize the queues of bad triangles. */
-    for (i = 0; i < 4096; i++) {
-      m->queuefront[i] = (struct badtriang *) NULL;
-    }
-    m->firstnonemptyq = -1;
-    /* Test all triangles to see if they're bad. */
-    tallyfaces(m, b);
-    /* Initialize the pool of recently flipped triangles. */
-    poolinit(&m->flipstackers, sizeof(struct flipstacker), FLIPSTACKERPERBLOCK,
-             FLIPSTACKERPERBLOCK, 0);
-    m->checkquality = 1;
-    if (b->verbose) {
-      printf("  Splitting bad triangles.\n");
-    }
-    while ((m->badtriangles.items > 0) && (m->steinerleft != 0)) {
-      /* Fix one bad triangle by inserting a vertex at its circumcenter. */
-      badtri = dequeuebadtriang(m);
-      splittriangle(m, b, badtri);
-      if (m->badsubsegs.items > 0) {
-        /* Put bad triangle back in queue for another try later. */
-        enqueuebadtriang(m, b, badtri);
-        /* Fix any encroached subsegments that resulted. */
-        /*   Record any new bad triangles that result.   */
-        splitencsegs(m, b, 1);
-      } else {
-        /* Return the bad triangle to the pool. */
-        pooldealloc(&m->badtriangles, (VOID *) badtri);
-      }
-    }
-  }
-  /* At this point, if the "-D" switch was selected and we haven't run out  */
-  /*   of Steiner points, the triangulation should be (conforming) Delaunay */
-  /*   and have no low-quality triangles.                                   */
-
-  /* Might we have run out of Steiner points too soon? */
-  if (!b->quiet && b->conformdel && (m->badsubsegs.items > 0) &&
-      (m->steinerleft == 0)) {
-    printf("\nWarning:  I ran out of Steiner points, but the mesh has\n");
-    if (m->badsubsegs.items == 1) {
-      printf("  one encroached subsegment, and therefore might not be truly\n"
-             );
-    } else {
-      printf("  %ld encroached subsegments, and therefore might not be truly\n"
-             , m->badsubsegs.items);
-    }
-    printf("  Delaunay.  If the Delaunay property is important to you,\n");
-    printf("  try increasing the number of Steiner points (controlled by\n");
-    printf("  the -S switch) slightly and try again.\n\n");
-  }
-}
-
-#endif /* not CDT_ONLY */
-
-/**                                                                         **/
-/**                                                                         **/
-/********* Mesh quality maintenance ends here                        *********/
-
-/*****************************************************************************/
-/*                                                                           */
-/*  highorder()   Create extra nodes for quadratic subparametric elements.   */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef ANSI_DECLARATORS
-void highorder(struct mesh *m, struct behavior *b)
-#else /* not ANSI_DECLARATORS */
-void highorder(m, b)
-struct mesh *m;
-struct behavior *b;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  struct otri triangleloop, trisym;
-  struct osub checkmark;
-  vertex newvertex;
-  vertex torg, tdest;
-  int i;
-  triangle ptr;                         /* Temporary variable used by sym(). */
-  subseg sptr;                      /* Temporary variable used by tspivot(). */
-
-  if (!b->quiet) {
-    printf("Adding vertices for second-order triangles.\n");
-  }
-  /* The following line ensures that dead items in the pool of nodes    */
-  /*   cannot be allocated for the extra nodes associated with high     */
-  /*   order elements.  This ensures that the primary nodes (at the     */
-  /*   corners of elements) will occur earlier in the output files, and */
-  /*   have lower indices, than the extra nodes.                        */
-  m->vertices.deaditemstack = (VOID *) NULL;
-
-  traversalinit(&m->triangles);
-  triangleloop.tri = triangletraverse(m);
-  /* To loop over the set of edges, loop over all triangles, and look at   */
-  /*   the three edges of each triangle.  If there isn't another triangle  */
-  /*   adjacent to the edge, operate on the edge.  If there is another     */
-  /*   adjacent triangle, operate on the edge only if the current triangle */
-  /*   has a smaller pointer than its neighbor.  This way, each edge is    */
-  /*   considered only once.                                               */
-  while (triangleloop.tri != (triangle *) NULL) {
-    for (triangleloop.orient = 0; triangleloop.orient < 3;
-         triangleloop.orient++) {
-      sym(triangleloop, trisym);
-      if ((triangleloop.tri < trisym.tri) || (trisym.tri == m->dummytri)) {
-        org(triangleloop, torg);
-        dest(triangleloop, tdest);
-        /* Create a new node in the middle of the edge.  Interpolate */
-        /*   its attributes.                                         */
-        newvertex = (vertex) poolalloc(&m->vertices);
-        for (i = 0; i < 2 + m->nextras; i++) {
-          newvertex[i] = 0.5 * (torg[i] + tdest[i]);
-        }
-        /* Set the new node's marker to zero or one, depending on */
-        /*   whether it lies on a boundary.                       */
-        setvertexmark(newvertex, trisym.tri == m->dummytri);
-        setvertextype(newvertex,
-                      trisym.tri == m->dummytri ? FREEVERTEX : SEGMENTVERTEX);
-        if (b->usesegments) {
-          tspivot(triangleloop, checkmark);
-          /* If this edge is a segment, transfer the marker to the new node. */
-          if (checkmark.ss != m->dummysub) {
-            setvertexmark(newvertex, mark(checkmark));
-            setvertextype(newvertex, SEGMENTVERTEX);
-          }
-        }
-        if (b->verbose > 1) {
-          printf("  Creating (%.12g, %.12g).\n", newvertex[0], newvertex[1]);
-        }
-        /* Record the new node in the (one or two) adjacent elements. */
-        triangleloop.tri[m->highorderindex + triangleloop.orient] =
-                (triangle) newvertex;
-        if (trisym.tri != m->dummytri) {
-          trisym.tri[m->highorderindex + trisym.orient] = (triangle) newvertex;
-        }
-      }
-    }
-    triangleloop.tri = triangletraverse(m);
-  }
-}
-
-/********* File I/O routines begin here                              *********/
-/**                                                                         **/
-/**                                                                         **/
-
-/*****************************************************************************/
-/*                                                                           */
-/*  readline()   Read a nonempty line from a file.                           */
-/*                                                                           */
-/*  A line is considered "nonempty" if it contains something that looks like */
-/*  a number.  Comments (prefaced by `#') are ignored.                       */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifndef TRILIBRARY
-
-#ifdef ANSI_DECLARATORS
-char *readline(char *string, FILE *infile, char *infilename)
-#else /* not ANSI_DECLARATORS */
-char *readline(string, infile, infilename)
-char *string;
-FILE *infile;
-char *infilename;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  char *result;
-
-  /* Search for something that looks like a number. */
-  do {
-    result = fgets(string, INPUTLINESIZE, infile);
-    if (result == (char *) NULL) {
-      printf("  Error:  Unexpected end of file in %s.\n", infilename);
-      triexit(1);
-    }
-    /* Skip anything that doesn't look like a number, a comment, */
-    /*   or the end of a line.                                   */
-    while ((*result != '\0') && (*result != '#')
-           && (*result != '.') && (*result != '+') && (*result != '-')
-           && ((*result < '0') || (*result > '9'))) {
-      result++;
-    }
-  /* If it's a comment or end of line, read another line and try again. */
-  } while ((*result == '#') || (*result == '\0'));
-  return result;
-}
-
-#endif /* not TRILIBRARY */
-
-/*****************************************************************************/
-/*                                                                           */
-/*  findfield()   Find the next field of a string.                           */
-/*                                                                           */
-/*  Jumps past the current field by searching for whitespace, then jumps     */
-/*  past the whitespace to find the next field.                              */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifndef TRILIBRARY
-
-#ifdef ANSI_DECLARATORS
-char *findfield(char *string)
-#else /* not ANSI_DECLARATORS */
-char *findfield(string)
-char *string;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  char *result;
-
-  result = string;
-  /* Skip the current field.  Stop upon reaching whitespace. */
-  while ((*result != '\0') && (*result != '#')
-         && (*result != ' ') && (*result != '\t')) {
-    result++;
-  }
-  /* Now skip the whitespace and anything else that doesn't look like a */
-  /*   number, a comment, or the end of a line.                         */
-  while ((*result != '\0') && (*result != '#')
-         && (*result != '.') && (*result != '+') && (*result != '-')
-         && ((*result < '0') || (*result > '9'))) {
-    result++;
-  }
-  /* Check for a comment (prefixed with `#'). */
-  if (*result == '#') {
-    *result = '\0';
-  }
-  return result;
-}
-
-#endif /* not TRILIBRARY */
-
-/*****************************************************************************/
-/*                                                                           */
-/*  readnodes()   Read the vertices from a file, which may be a .node or     */
-/*                .poly file.                                                */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifndef TRILIBRARY
-
-#ifdef ANSI_DECLARATORS
-void readnodes(struct mesh *m, struct behavior *b, char *nodefilename,
-               char *polyfilename, FILE **polyfile)
-#else /* not ANSI_DECLARATORS */
-void readnodes(m, b, nodefilename, polyfilename, polyfile)
-struct mesh *m;
-struct behavior *b;
-char *nodefilename;
-char *polyfilename;
-FILE **polyfile;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  FILE *infile;
-  vertex vertexloop;
-  char inputline[INPUTLINESIZE];
-  char *stringptr;
-  char *infilename;
-  REAL x, y;
-  int firstnode;
-  int nodemarkers;
-  int currentmarker;
-  int i, j;
-
-  if (b->poly) {
-    /* Read the vertices from a .poly file. */
-    if (!b->quiet) {
-      printf("Opening %s.\n", polyfilename);
-    }
-    *polyfile = fopen(polyfilename, "r");
-    if (*polyfile == (FILE *) NULL) {
-      printf("  Error:  Cannot access file %s.\n", polyfilename);
-      triexit(1);
-    }
-    /* Read number of vertices, number of dimensions, number of vertex */
-    /*   attributes, and number of boundary markers.                   */
-    stringptr = readline(inputline, *polyfile, polyfilename);
-    m->invertices = (int) strtol(stringptr, &stringptr, 0);
-    stringptr = findfield(stringptr);
-    if (*stringptr == '\0') {
-      m->mesh_dim = 2;
-    } else {
-      m->mesh_dim = (int) strtol(stringptr, &stringptr, 0);
-    }
-    stringptr = findfield(stringptr);
-    if (*stringptr == '\0') {
-      m->nextras = 0;
-    } else {
-      m->nextras = (int) strtol(stringptr, &stringptr, 0);
-    }
-    stringptr = findfield(stringptr);
-    if (*stringptr == '\0') {
-      nodemarkers = 0;
-    } else {
-      nodemarkers = (int) strtol(stringptr, &stringptr, 0);
-    }
-    if (m->invertices > 0) {
-      infile = *polyfile;
-      infilename = polyfilename;
-      m->readnodefile = 0;
-    } else {
-      /* If the .poly file claims there are zero vertices, that means that */
-      /*   the vertices should be read from a separate .node file.         */
-      m->readnodefile = 1;
-      infilename = nodefilename;
-    }
-  } else {
-    m->readnodefile = 1;
-    infilename = nodefilename;
-    *polyfile = (FILE *) NULL;
-  }
-
-  if (m->readnodefile) {
-    /* Read the vertices from a .node file. */
-    if (!b->quiet) {
-      printf("Opening %s.\n", nodefilename);
-    }
-    infile = fopen(nodefilename, "r");
-    if (infile == (FILE *) NULL) {
-      printf("  Error:  Cannot access file %s.\n", nodefilename);
-      triexit(1);
-    }
-    /* Read number of vertices, number of dimensions, number of vertex */
-    /*   attributes, and number of boundary markers.                   */
-    stringptr = readline(inputline, infile, nodefilename);
-    m->invertices = (int) strtol(stringptr, &stringptr, 0);
-    stringptr = findfield(stringptr);
-    if (*stringptr == '\0') {
-      m->mesh_dim = 2;
-    } else {
-      m->mesh_dim = (int) strtol(stringptr, &stringptr, 0);
-    }
-    stringptr = findfield(stringptr);
-    if (*stringptr == '\0') {
-      m->nextras = 0;
-    } else {
-      m->nextras = (int) strtol(stringptr, &stringptr, 0);
-    }
-    stringptr = findfield(stringptr);
-    if (*stringptr == '\0') {
-      nodemarkers = 0;
-    } else {
-      nodemarkers = (int) strtol(stringptr, &stringptr, 0);
-    }
-  }
-
-  if (m->invertices < 3) {
-    printf("Error:  Input must have at least three input vertices.\n");
-    triexit(1);
-  }
-  if (m->mesh_dim != 2) {
-    printf("Error:  Triangle only works with two-dimensional meshes.\n");
-    triexit(1);
-  }
-  if (m->nextras == 0) {
-    b->weighted = 0;
-  }
-
-  initializevertexpool(m, b);
-
-  /* Read the vertices. */
-  for (i = 0; i < m->invertices; i++) {
-    vertexloop = (vertex) poolalloc(&m->vertices);
-    stringptr = readline(inputline, infile, infilename);
-    if (i == 0) {
-      firstnode = (int) strtol(stringptr, &stringptr, 0);
-      if ((firstnode == 0) || (firstnode == 1)) {
-        b->firstnumber = firstnode;
-      }
-    }
-    stringptr = findfield(stringptr);
-    if (*stringptr == '\0') {
-      printf("Error:  Vertex %d has no x coordinate.\n", b->firstnumber + i);
-      triexit(1);
-    }
-    x = (REAL) strtod(stringptr, &stringptr);
-    stringptr = findfield(stringptr);
-    if (*stringptr == '\0') {
-      printf("Error:  Vertex %d has no y coordinate.\n", b->firstnumber + i);
-      triexit(1);
-    }
-    y = (REAL) strtod(stringptr, &stringptr);
-    vertexloop[0] = x;
-    vertexloop[1] = y;
-    /* Read the vertex attributes. */
-    for (j = 2; j < 2 + m->nextras; j++) {
-      stringptr = findfield(stringptr);
-      if (*stringptr == '\0') {
-        vertexloop[j] = 0.0;
-      } else {
-        vertexloop[j] = (REAL) strtod(stringptr, &stringptr);
-      }
-    }
-    if (nodemarkers) {
-      /* Read a vertex marker. */
-      stringptr = findfield(stringptr);
-      if (*stringptr == '\0') {
-        setvertexmark(vertexloop, 0);
-      } else {
-        currentmarker = (int) strtol(stringptr, &stringptr, 0);
-        setvertexmark(vertexloop, currentmarker);
-      }
-    } else {
-      /* If no markers are specified in the file, they default to zero. */
-      setvertexmark(vertexloop, 0);
-    }
-    setvertextype(vertexloop, INPUTVERTEX);
-    /* Determine the smallest and largest x and y coordinates. */
-    if (i == 0) {
-      m->xmin = m->xmax = x;
-      m->ymin = m->ymax = y;
-    } else {
-      m->xmin = (x < m->xmin) ? x : m->xmin;
-      m->xmax = (x > m->xmax) ? x : m->xmax;
-      m->ymin = (y < m->ymin) ? y : m->ymin;
-      m->ymax = (y > m->ymax) ? y : m->ymax;
-    }
-  }
-  if (m->readnodefile) {
-    fclose(infile);
-  }
-
-  /* Nonexistent x value used as a flag to mark circle events in sweepline */
-  /*   Delaunay algorithm.                                                 */
-  m->xminextreme = 10 * m->xmin - 9 * m->xmax;
-}
-
-#endif /* not TRILIBRARY */
-
-/*****************************************************************************/
-/*                                                                           */
-/*  transfernodes()   Read the vertices from memory.                         */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef TRILIBRARY
-
-#ifdef ANSI_DECLARATORS
-void transfernodes(struct mesh *m, struct behavior *b, REAL *pointlist,
-                   REAL *pointattriblist, int *pointmarkerlist,
-                   int numberofpoints, int numberofpointattribs)
-#else /* not ANSI_DECLARATORS */
-void transfernodes(m, b, pointlist, pointattriblist, pointmarkerlist,
-                   numberofpoints, numberofpointattribs)
-struct mesh *m;
-struct behavior *b;
-REAL *pointlist;
-REAL *pointattriblist;
-int *pointmarkerlist;
-int numberofpoints;
-int numberofpointattribs;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  vertex vertexloop;
-  REAL x, y;
-  int i, j;
-  int coordindex;
-  int attribindex;
-
-  m->invertices = numberofpoints;
-  m->mesh_dim = 2;
-  m->nextras = numberofpointattribs;
-  m->readnodefile = 0;
-  if (m->invertices < 3) {
-    printf("Error:  Input must have at least three input vertices.\n");
-    triexit(1);
-  }
-  if (m->nextras == 0) {
-    b->weighted = 0;
-  }
-
-  initializevertexpool(m, b);
-
-  /* Read the vertices. */
-  coordindex = 0;
-  attribindex = 0;
-  for (i = 0; i < m->invertices; i++) {
-    vertexloop = (vertex) poolalloc(&m->vertices);
-    /* Read the vertex coordinates. */
-    x = vertexloop[0] = pointlist[coordindex++];
-    y = vertexloop[1] = pointlist[coordindex++];
-    /* Read the vertex attributes. */
-    for (j = 0; j < numberofpointattribs; j++) {
-      vertexloop[2 + j] = pointattriblist[attribindex++];
-    }
-    if (pointmarkerlist != (int *) NULL) {
-      /* Read a vertex marker. */
-      setvertexmark(vertexloop, pointmarkerlist[i]);
-    } else {
-      /* If no markers are specified, they default to zero. */
-      setvertexmark(vertexloop, 0);
-    }
-    setvertextype(vertexloop, INPUTVERTEX);
-    /* Determine the smallest and largest x and y coordinates. */
-    if (i == 0) {
-      m->xmin = m->xmax = x;
-      m->ymin = m->ymax = y;
-    } else {
-      m->xmin = (x < m->xmin) ? x : m->xmin;
-      m->xmax = (x > m->xmax) ? x : m->xmax;
-      m->ymin = (y < m->ymin) ? y : m->ymin;
-      m->ymax = (y > m->ymax) ? y : m->ymax;
-    }
-  }
-
-  /* Nonexistent x value used as a flag to mark circle events in sweepline */
-  /*   Delaunay algorithm.                                                 */
-  m->xminextreme = 10 * m->xmin - 9 * m->xmax;
-}
-
-#endif /* TRILIBRARY */
-
-/*****************************************************************************/
-/*                                                                           */
-/*  readholes()   Read the holes, and possibly regional attributes and area  */
-/*                constraints, from a .poly file.                            */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifndef TRILIBRARY
-
-#ifdef ANSI_DECLARATORS
-void readholes(struct mesh *m, struct behavior *b,
-               FILE *polyfile, char *polyfilename, REAL **hlist, int *holes,
-               REAL **rlist, int *regions)
-#else /* not ANSI_DECLARATORS */
-void readholes(m, b, polyfile, polyfilename, hlist, holes, rlist, regions)
-struct mesh *m;
-struct behavior *b;
-FILE *polyfile;
-char *polyfilename;
-REAL **hlist;
-int *holes;
-REAL **rlist;
-int *regions;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  REAL *holelist;
-  REAL *regionlist;
-  char inputline[INPUTLINESIZE];
-  char *stringptr;
-  int index;
-  int i;
-
-  /* Read the holes. */
-  stringptr = readline(inputline, polyfile, polyfilename);
-  *holes = (int) strtol(stringptr, &stringptr, 0);
-  if (*holes > 0) {
-    holelist = (REAL *) trimalloc(2 * *holes * (int) sizeof(REAL));
-    *hlist = holelist;
-    for (i = 0; i < 2 * *holes; i += 2) {
-      stringptr = readline(inputline, polyfile, polyfilename);
-      stringptr = findfield(stringptr);
-      if (*stringptr == '\0') {
-        printf("Error:  Hole %d has no x coordinate.\n",
-               b->firstnumber + (i >> 1));
-        triexit(1);
-      } else {
-        holelist[i] = (REAL) strtod(stringptr, &stringptr);
-      }
-      stringptr = findfield(stringptr);
-      if (*stringptr == '\0') {
-        printf("Error:  Hole %d has no y coordinate.\n",
-               b->firstnumber + (i >> 1));
-        triexit(1);
-      } else {
-        holelist[i + 1] = (REAL) strtod(stringptr, &stringptr);
-      }
-    }
-  } else {
-    *hlist = (REAL *) NULL;
-  }
-
-#ifndef CDT_ONLY
-  if ((b->regionattrib || b->vararea) && !b->refine) {
-    /* Read the area constraints. */
-    stringptr = readline(inputline, polyfile, polyfilename);
-    *regions = (int) strtol(stringptr, &stringptr, 0);
-    if (*regions > 0) {
-      regionlist = (REAL *) trimalloc(4 * *regions * (int) sizeof(REAL));
-      *rlist = regionlist;
-      index = 0;
-      for (i = 0; i < *regions; i++) {
-        stringptr = readline(inputline, polyfile, polyfilename);
-        stringptr = findfield(stringptr);
-        if (*stringptr == '\0') {
-          printf("Error:  Region %d has no x coordinate.\n",
-                 b->firstnumber + i);
-          triexit(1);
-        } else {
-          regionlist[index++] = (REAL) strtod(stringptr, &stringptr);
-        }
-        stringptr = findfield(stringptr);
-        if (*stringptr == '\0') {
-          printf("Error:  Region %d has no y coordinate.\n",
-                 b->firstnumber + i);
-          triexit(1);
-        } else {
-          regionlist[index++] = (REAL) strtod(stringptr, &stringptr);
-        }
-        stringptr = findfield(stringptr);
-        if (*stringptr == '\0') {
-          printf(
-            "Error:  Region %d has no region attribute or area constraint.\n",
-                 b->firstnumber + i);
-          triexit(1);
-        } else {
-          regionlist[index++] = (REAL) strtod(stringptr, &stringptr);
-        }
-        stringptr = findfield(stringptr);
-        if (*stringptr == '\0') {
-          regionlist[index] = regionlist[index - 1];
-        } else {
-          regionlist[index] = (REAL) strtod(stringptr, &stringptr);
-        }
-        index++;
-      }
-    }
-  } else {
-    /* Set `*regions' to zero to avoid an accidental free() later. */
-    *regions = 0;
-    *rlist = (REAL *) NULL;
-  }
-#endif /* not CDT_ONLY */
-
-  fclose(polyfile);
-}
-
-#endif /* not TRILIBRARY */
-
-/*****************************************************************************/
-/*                                                                           */
-/*  finishfile()   Write the command line to the output file so the user     */
-/*                 can remember how the file was generated.  Close the file. */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifndef TRILIBRARY
-
-#ifdef ANSI_DECLARATORS
-void finishfile(FILE *outfile, int argc, char **argv)
-#else /* not ANSI_DECLARATORS */
-void finishfile(outfile, argc, argv)
-FILE *outfile;
-int argc;
-char **argv;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  int i;
-
-  fprintf(outfile, "# Generated by");
-  for (i = 0; i < argc; i++) {
-    fprintf(outfile, " ");
-    fputs(argv[i], outfile);
-  }
-  fprintf(outfile, "\n");
-  fclose(outfile);
-}
-
-#endif /* not TRILIBRARY */
-
-/*****************************************************************************/
-/*                                                                           */
-/*  writenodes()   Number the vertices and write them to a .node file.       */
-/*                                                                           */
-/*  To save memory, the vertex numbers are written over the boundary markers */
-/*  after the vertices are written to a file.                                */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef TRILIBRARY
-
-#ifdef ANSI_DECLARATORS
-void writenodes(struct mesh *m, struct behavior *b, REAL **pointlist,
-                REAL **pointattriblist, int **pointmarkerlist)
-#else /* not ANSI_DECLARATORS */
-void writenodes(m, b, pointlist, pointattriblist, pointmarkerlist)
-struct mesh *m;
-struct behavior *b;
-REAL **pointlist;
-REAL **pointattriblist;
-int **pointmarkerlist;
-#endif /* not ANSI_DECLARATORS */
-
-#else /* not TRILIBRARY */
-
-#ifdef ANSI_DECLARATORS
-void writenodes(struct mesh *m, struct behavior *b, char *nodefilename,
-                int argc, char **argv)
-#else /* not ANSI_DECLARATORS */
-void writenodes(m, b, nodefilename, argc, argv)
-struct mesh *m;
-struct behavior *b;
-char *nodefilename;
-int argc;
-char **argv;
-#endif /* not ANSI_DECLARATORS */
-
-#endif /* not TRILIBRARY */
-
-{
-#ifdef TRILIBRARY
-  REAL *plist;
-  REAL *palist;
-  int *pmlist;
-  int coordindex;
-  int attribindex;
-#else /* not TRILIBRARY */
-  FILE *outfile;
-#endif /* not TRILIBRARY */
-  vertex vertexloop;
-  long outvertices;
-  int vertexnumber;
-  int i;
-
-  if (b->jettison) {
-    outvertices = m->vertices.items - m->undeads;
-  } else {
-    outvertices = m->vertices.items;
-  }
-
-#ifdef TRILIBRARY
-  if (!b->quiet) {
-    printf("Writing vertices.\n");
-  }
-  /* Allocate memory for output vertices if necessary. */
-  if (*pointlist == (REAL *) NULL) {
-    *pointlist = (REAL *) trimalloc((int) (outvertices * 2 * sizeof(REAL)));
-  }
-  /* Allocate memory for output vertex attributes if necessary. */
-  if ((m->nextras > 0) && (*pointattriblist == (REAL *) NULL)) {
-    *pointattriblist = (REAL *) trimalloc((int) (outvertices * m->nextras *
-                                                 sizeof(REAL)));
-  }
-  /* Allocate memory for output vertex markers if necessary. */
-  if (!b->nobound && (*pointmarkerlist == (int *) NULL)) {
-    *pointmarkerlist = (int *) trimalloc((int) (outvertices * sizeof(int)));
-  }
-  plist = *pointlist;
-  palist = *pointattriblist;
-  pmlist = *pointmarkerlist;
-  coordindex = 0;
-  attribindex = 0;
-#else /* not TRILIBRARY */
-  if (!b->quiet) {
-    printf("Writing %s.\n", nodefilename);
-  }
-  outfile = fopen(nodefilename, "w");
-  if (outfile == (FILE *) NULL) {
-    printf("  Error:  Cannot create file %s.\n", nodefilename);
-    triexit(1);
-  }
-  /* Number of vertices, number of dimensions, number of vertex attributes, */
-  /*   and number of boundary markers (zero or one).                        */
-  fprintf(outfile, "%ld  %d  %d  %d\n", outvertices, m->mesh_dim,
-          m->nextras, 1 - b->nobound);
-#endif /* not TRILIBRARY */
-
-  traversalinit(&m->vertices);
-  vertexnumber = b->firstnumber;
-  vertexloop = vertextraverse(m);
-  while (vertexloop != (vertex) NULL) {
-    if (!b->jettison || (vertextype(vertexloop) != UNDEADVERTEX)) {
-#ifdef TRILIBRARY
-      /* X and y coordinates. */
-      plist[coordindex++] = vertexloop[0];
-      plist[coordindex++] = vertexloop[1];
-      /* Vertex attributes. */
-      for (i = 0; i < m->nextras; i++) {
-        palist[attribindex++] = vertexloop[2 + i];
-      }
-      if (!b->nobound) {
-        /* Copy the boundary marker. */
-        pmlist[vertexnumber - b->firstnumber] = vertexmark(vertexloop);
-      }
-#else /* not TRILIBRARY */
-      /* Vertex number, x and y coordinates. */
-      fprintf(outfile, "%4d    %.17g  %.17g", vertexnumber, vertexloop[0],
-              vertexloop[1]);
-      for (i = 0; i < m->nextras; i++) {
-        /* Write an attribute. */
-        fprintf(outfile, "  %.17g", vertexloop[i + 2]);
-      }
-      if (b->nobound) {
-        fprintf(outfile, "\n");
-      } else {
-        /* Write the boundary marker. */
-        fprintf(outfile, "    %d\n", vertexmark(vertexloop));
-      }
-#endif /* not TRILIBRARY */
-
-      setvertexmark(vertexloop, vertexnumber);
-      vertexnumber++;
-    }
-    vertexloop = vertextraverse(m);
-  }
-
-#ifndef TRILIBRARY
-  finishfile(outfile, argc, argv);
-#endif /* not TRILIBRARY */
-}
-
-/*****************************************************************************/
-/*                                                                           */
-/*  numbernodes()   Number the vertices.                                     */
-/*                                                                           */
-/*  Each vertex is assigned a marker equal to its number.                    */
-/*                                                                           */
-/*  Used when writenodes() is not called because no .node file is written.   */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef ANSI_DECLARATORS
-void numbernodes(struct mesh *m, struct behavior *b)
-#else /* not ANSI_DECLARATORS */
-void numbernodes(m, b)
-struct mesh *m;
-struct behavior *b;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  vertex vertexloop;
-  int vertexnumber;
-
-  traversalinit(&m->vertices);
-  vertexnumber = b->firstnumber;
-  vertexloop = vertextraverse(m);
-  while (vertexloop != (vertex) NULL) {
-    setvertexmark(vertexloop, vertexnumber);
-    if (!b->jettison || (vertextype(vertexloop) != UNDEADVERTEX)) {
-      vertexnumber++;
-    }
-    vertexloop = vertextraverse(m);
-  }
-}
-
-/*****************************************************************************/
-/*                                                                           */
-/*  writeelements()   Write the triangles to an .ele file.                   */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef TRILIBRARY
-
-#ifdef ANSI_DECLARATORS
-void writeelements(struct mesh *m, struct behavior *b,
-                   int **trianglelist, REAL **triangleattriblist)
-#else /* not ANSI_DECLARATORS */
-void writeelements(m, b, trianglelist, triangleattriblist)
-struct mesh *m;
-struct behavior *b;
-int **trianglelist;
-REAL **triangleattriblist;
-#endif /* not ANSI_DECLARATORS */
-
-#else /* not TRILIBRARY */
-
-#ifdef ANSI_DECLARATORS
-void writeelements(struct mesh *m, struct behavior *b, char *elefilename,
-                   int argc, char **argv)
-#else /* not ANSI_DECLARATORS */
-void writeelements(m, b, elefilename, argc, argv)
-struct mesh *m;
-struct behavior *b;
-char *elefilename;
-int argc;
-char **argv;
-#endif /* not ANSI_DECLARATORS */
-
-#endif /* not TRILIBRARY */
-
-{
-#ifdef TRILIBRARY
-  int *tlist;
-  REAL *talist;
-  int vertexindex;
-  int attribindex;
-#else /* not TRILIBRARY */
-  FILE *outfile;
-#endif /* not TRILIBRARY */
-  struct otri triangleloop;
-  vertex p1, p2, p3;
-  vertex mid1, mid2, mid3;
-  long elementnumber;
-  int i;
-
-#ifdef TRILIBRARY
-  if (!b->quiet) {
-    printf("Writing triangles.\n");
-  }
-  /* Allocate memory for output triangles if necessary. */
-  if (*trianglelist == (int *) NULL) {
-    *trianglelist = (int *) trimalloc((int) (m->triangles.items *
-                                             ((b->order + 1) * (b->order + 2) /
-                                              2) * sizeof(int)));
-  }
-  /* Allocate memory for output triangle attributes if necessary. */
-  if ((m->eextras > 0) && (*triangleattriblist == (REAL *) NULL)) {
-    *triangleattriblist = (REAL *) trimalloc((int) (m->triangles.items *
-                                                    m->eextras *
-                                                    sizeof(REAL)));
-  }
-  tlist = *trianglelist;
-  talist = *triangleattriblist;
-  vertexindex = 0;
-  attribindex = 0;
-#else /* not TRILIBRARY */
-  if (!b->quiet) {
-    printf("Writing %s.\n", elefilename);
-  }
-  outfile = fopen(elefilename, "w");
-  if (outfile == (FILE *) NULL) {
-    printf("  Error:  Cannot create file %s.\n", elefilename);
-    triexit(1);
-  }
-  /* Number of triangles, vertices per triangle, attributes per triangle. */
-  fprintf(outfile, "%ld  %d  %d\n", m->triangles.items,
-          (b->order + 1) * (b->order + 2) / 2, m->eextras);
-#endif /* not TRILIBRARY */
-
-  traversalinit(&m->triangles);
-  triangleloop.tri = triangletraverse(m);
-  triangleloop.orient = 0;
-  elementnumber = b->firstnumber;
-  while (triangleloop.tri != (triangle *) NULL) {
-    org(triangleloop, p1);
-    dest(triangleloop, p2);
-    apex(triangleloop, p3);
-    if (b->order == 1) {
-#ifdef TRILIBRARY
-      tlist[vertexindex++] = vertexmark(p1);
-      tlist[vertexindex++] = vertexmark(p2);
-      tlist[vertexindex++] = vertexmark(p3);
-#else /* not TRILIBRARY */
-      /* Triangle number, indices for three vertices. */
-      fprintf(outfile, "%4ld    %4d  %4d  %4d", elementnumber,
-              vertexmark(p1), vertexmark(p2), vertexmark(p3));
-#endif /* not TRILIBRARY */
-    } else {
-      mid1 = (vertex) triangleloop.tri[m->highorderindex + 1];
-      mid2 = (vertex) triangleloop.tri[m->highorderindex + 2];
-      mid3 = (vertex) triangleloop.tri[m->highorderindex];
-#ifdef TRILIBRARY
-      tlist[vertexindex++] = vertexmark(p1);
-      tlist[vertexindex++] = vertexmark(p2);
-      tlist[vertexindex++] = vertexmark(p3);
-      tlist[vertexindex++] = vertexmark(mid1);
-      tlist[vertexindex++] = vertexmark(mid2);
-      tlist[vertexindex++] = vertexmark(mid3);
-#else /* not TRILIBRARY */
-      /* Triangle number, indices for six vertices. */
-      fprintf(outfile, "%4ld    %4d  %4d  %4d  %4d  %4d  %4d", elementnumber,
-              vertexmark(p1), vertexmark(p2), vertexmark(p3), vertexmark(mid1),
-              vertexmark(mid2), vertexmark(mid3));
-#endif /* not TRILIBRARY */
-    }
-
-#ifdef TRILIBRARY
-    for (i = 0; i < m->eextras; i++) {
-      talist[attribindex++] = elemattribute(triangleloop, i);
-    }
-#else /* not TRILIBRARY */
-    for (i = 0; i < m->eextras; i++) {
-      fprintf(outfile, "  %.17g", elemattribute(triangleloop, i));
-    }
-    fprintf(outfile, "\n");
-#endif /* not TRILIBRARY */
-
-    triangleloop.tri = triangletraverse(m);
-    elementnumber++;
-  }
-
-#ifndef TRILIBRARY
-  finishfile(outfile, argc, argv);
-#endif /* not TRILIBRARY */
-}
-
-/*****************************************************************************/
-/*                                                                           */
-/*  writepoly()   Write the segments and holes to a .poly file.              */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef TRILIBRARY
-
-#ifdef ANSI_DECLARATORS
-void writepoly(struct mesh *m, struct behavior *b,
-               int **segmentlist, int **segmentmarkerlist)
-#else /* not ANSI_DECLARATORS */
-void writepoly(m, b, segmentlist, segmentmarkerlist)
-struct mesh *m;
-struct behavior *b;
-int **segmentlist;
-int **segmentmarkerlist;
-#endif /* not ANSI_DECLARATORS */
-
-#else /* not TRILIBRARY */
-
-#ifdef ANSI_DECLARATORS
-void writepoly(struct mesh *m, struct behavior *b, char *polyfilename,
-               REAL *holelist, int holes, REAL *regionlist, int regions,
-               int argc, char **argv)
-#else /* not ANSI_DECLARATORS */
-void writepoly(m, b, polyfilename, holelist, holes, regionlist, regions,
-               argc, argv)
-struct mesh *m;
-struct behavior *b;
-char *polyfilename;
-REAL *holelist;
-int holes;
-REAL *regionlist;
-int regions;
-int argc;
-char **argv;
-#endif /* not ANSI_DECLARATORS */
-
-#endif /* not TRILIBRARY */
-
-{
-#ifdef TRILIBRARY
-  int *slist;
-  int *smlist;
-  int index;
-#else /* not TRILIBRARY */
-  FILE *outfile;
-  long holenumber, regionnumber;
-#endif /* not TRILIBRARY */
-  struct osub subsegloop;
-  vertex endpoint1, endpoint2;
-  long subsegnumber;
-
-#ifdef TRILIBRARY
-  if (!b->quiet) {
-    printf("Writing segments.\n");
-  }
-  /* Allocate memory for output segments if necessary. */
-  if (*segmentlist == (int *) NULL) {
-    *segmentlist = (int *) trimalloc((int) (m->subsegs.items * 2 *
-                                            sizeof(int)));
-  }
-  /* Allocate memory for output segment markers if necessary. */
-  if (!b->nobound && (*segmentmarkerlist == (int *) NULL)) {
-    *segmentmarkerlist = (int *) trimalloc((int) (m->subsegs.items *
-                                                  sizeof(int)));
-  }
-  slist = *segmentlist;
-  smlist = *segmentmarkerlist;
-  index = 0;
-#else /* not TRILIBRARY */
-  if (!b->quiet) {
-    printf("Writing %s.\n", polyfilename);
-  }
-  outfile = fopen(polyfilename, "w");
-  if (outfile == (FILE *) NULL) {
-    printf("  Error:  Cannot create file %s.\n", polyfilename);
-    triexit(1);
-  }
-  /* The zero indicates that the vertices are in a separate .node file. */
-  /*   Followed by number of dimensions, number of vertex attributes,   */
-  /*   and number of boundary markers (zero or one).                    */
-  fprintf(outfile, "%d  %d  %d  %d\n", 0, m->mesh_dim, m->nextras,
-          1 - b->nobound);
-  /* Number of segments, number of boundary markers (zero or one). */
-  fprintf(outfile, "%ld  %d\n", m->subsegs.items, 1 - b->nobound);
-#endif /* not TRILIBRARY */
-
-  traversalinit(&m->subsegs);
-  subsegloop.ss = subsegtraverse(m);
-  subsegloop.ssorient = 0;
-  subsegnumber = b->firstnumber;
-  while (subsegloop.ss != (subseg *) NULL) {
-    sorg(subsegloop, endpoint1);
-    sdest(subsegloop, endpoint2);
-#ifdef TRILIBRARY
-    /* Copy indices of the segment's two endpoints. */
-    slist[index++] = vertexmark(endpoint1);
-    slist[index++] = vertexmark(endpoint2);
-    if (!b->nobound) {
-      /* Copy the boundary marker. */
-      smlist[subsegnumber - b->firstnumber] = mark(subsegloop);
-    }
-#else /* not TRILIBRARY */
-    /* Segment number, indices of its two endpoints, and possibly a marker. */
-    if (b->nobound) {
-      fprintf(outfile, "%4ld    %4d  %4d\n", subsegnumber,
-              vertexmark(endpoint1), vertexmark(endpoint2));
-    } else {
-      fprintf(outfile, "%4ld    %4d  %4d    %4d\n", subsegnumber,
-              vertexmark(endpoint1), vertexmark(endpoint2), mark(subsegloop));
-    }
-#endif /* not TRILIBRARY */
-
-    subsegloop.ss = subsegtraverse(m);
-    subsegnumber++;
-  }
-
-#ifndef TRILIBRARY
-#ifndef CDT_ONLY
-  fprintf(outfile, "%d\n", holes);
-  if (holes > 0) {
-    for (holenumber = 0; holenumber < holes; holenumber++) {
-      /* Hole number, x and y coordinates. */
-      fprintf(outfile, "%4ld   %.17g  %.17g\n", b->firstnumber + holenumber,
-              holelist[2 * holenumber], holelist[2 * holenumber + 1]);
-    }
-  }
-  if (regions > 0) {
-    fprintf(outfile, "%d\n", regions);
-    for (regionnumber = 0; regionnumber < regions; regionnumber++) {
-      /* Region number, x and y coordinates, attribute, maximum area. */
-      fprintf(outfile, "%4ld   %.17g  %.17g  %.17g  %.17g\n",
-              b->firstnumber + regionnumber,
-              regionlist[4 * regionnumber], regionlist[4 * regionnumber + 1],
-              regionlist[4 * regionnumber + 2],
-              regionlist[4 * regionnumber + 3]);
-    }
-  }
-#endif /* not CDT_ONLY */
-
-  finishfile(outfile, argc, argv);
-#endif /* not TRILIBRARY */
-}
-
-/*****************************************************************************/
-/*                                                                           */
-/*  writeedges()   Write the edges to an .edge file.                         */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef TRILIBRARY
-
-#ifdef ANSI_DECLARATORS
-void writeedges(struct mesh *m, struct behavior *b,
-                int **edgelist, int **edgemarkerlist)
-#else /* not ANSI_DECLARATORS */
-void writeedges(m, b, edgelist, edgemarkerlist)
-struct mesh *m;
-struct behavior *b;
-int **edgelist;
-int **edgemarkerlist;
-#endif /* not ANSI_DECLARATORS */
-
-#else /* not TRILIBRARY */
-
-#ifdef ANSI_DECLARATORS
-void writeedges(struct mesh *m, struct behavior *b, char *edgefilename,
-                int argc, char **argv)
-#else /* not ANSI_DECLARATORS */
-void writeedges(m, b, edgefilename, argc, argv)
-struct mesh *m;
-struct behavior *b;
-char *edgefilename;
-int argc;
-char **argv;
-#endif /* not ANSI_DECLARATORS */
-
-#endif /* not TRILIBRARY */
-
-{
-#ifdef TRILIBRARY
-  int *elist;
-  int *emlist;
-  int index;
-#else /* not TRILIBRARY */
-  FILE *outfile;
-#endif /* not TRILIBRARY */
-  struct otri triangleloop, trisym;
-  struct osub checkmark;
-  vertex p1, p2;
-  long edgenumber;
-  triangle ptr;                         /* Temporary variable used by sym(). */
-  subseg sptr;                      /* Temporary variable used by tspivot(). */
-
-#ifdef TRILIBRARY
-  if (!b->quiet) {
-    printf("Writing edges.\n");
-  }
-  /* Allocate memory for edges if necessary. */
-  if (*edgelist == (int *) NULL) {
-    *edgelist = (int *) trimalloc((int) (m->edges * 2 * sizeof(int)));
-  }
-  /* Allocate memory for edge markers if necessary. */
-  if (!b->nobound && (*edgemarkerlist == (int *) NULL)) {
-    *edgemarkerlist = (int *) trimalloc((int) (m->edges * sizeof(int)));
-  }
-  elist = *edgelist;
-  emlist = *edgemarkerlist;
-  index = 0;
-#else /* not TRILIBRARY */
-  if (!b->quiet) {
-    printf("Writing %s.\n", edgefilename);
-  }
-  outfile = fopen(edgefilename, "w");
-  if (outfile == (FILE *) NULL) {
-    printf("  Error:  Cannot create file %s.\n", edgefilename);
-    triexit(1);
-  }
-  /* Number of edges, number of boundary markers (zero or one). */
-  fprintf(outfile, "%ld  %d\n", m->edges, 1 - b->nobound);
-#endif /* not TRILIBRARY */
-
-  traversalinit(&m->triangles);
-  triangleloop.tri = triangletraverse(m);
-  edgenumber = b->firstnumber;
-  /* To loop over the set of edges, loop over all triangles, and look at   */
-  /*   the three edges of each triangle.  If there isn't another triangle  */
-  /*   adjacent to the edge, operate on the edge.  If there is another     */
-  /*   adjacent triangle, operate on the edge only if the current triangle */
-  /*   has a smaller pointer than its neighbor.  This way, each edge is    */
-  /*   considered only once.                                               */
-  while (triangleloop.tri != (triangle *) NULL) {
-    for (triangleloop.orient = 0; triangleloop.orient < 3;
-         triangleloop.orient++) {
-      sym(triangleloop, trisym);
-      if ((triangleloop.tri < trisym.tri) || (trisym.tri == m->dummytri)) {
-        org(triangleloop, p1);
-        dest(triangleloop, p2);
-#ifdef TRILIBRARY
-        elist[index++] = vertexmark(p1);
-        elist[index++] = vertexmark(p2);
-#endif /* TRILIBRARY */
-        if (b->nobound) {
-#ifndef TRILIBRARY
-          /* Edge number, indices of two endpoints. */
-          fprintf(outfile, "%4ld   %d  %d\n", edgenumber,
-                  vertexmark(p1), vertexmark(p2));
-#endif /* not TRILIBRARY */
-        } else {
-          /* Edge number, indices of two endpoints, and a boundary marker. */
-          /*   If there's no subsegment, the boundary marker is zero.      */
-          if (b->usesegments) {
-            tspivot(triangleloop, checkmark);
-            if (checkmark.ss == m->dummysub) {
-#ifdef TRILIBRARY
-              emlist[edgenumber - b->firstnumber] = 0;
-#else /* not TRILIBRARY */
-              fprintf(outfile, "%4ld   %d  %d  %d\n", edgenumber,
-                      vertexmark(p1), vertexmark(p2), 0);
-#endif /* not TRILIBRARY */
-            } else {
-#ifdef TRILIBRARY
-              emlist[edgenumber - b->firstnumber] = mark(checkmark);
-#else /* not TRILIBRARY */
-              fprintf(outfile, "%4ld   %d  %d  %d\n", edgenumber,
-                      vertexmark(p1), vertexmark(p2), mark(checkmark));
-#endif /* not TRILIBRARY */
-            }
-          } else {
-#ifdef TRILIBRARY
-            emlist[edgenumber - b->firstnumber] = trisym.tri == m->dummytri;
-#else /* not TRILIBRARY */
-            fprintf(outfile, "%4ld   %d  %d  %d\n", edgenumber,
-                    vertexmark(p1), vertexmark(p2), trisym.tri == m->dummytri);
-#endif /* not TRILIBRARY */
-          }
-        }
-        edgenumber++;
-      }
-    }
-    triangleloop.tri = triangletraverse(m);
-  }
-
-#ifndef TRILIBRARY
-  finishfile(outfile, argc, argv);
-#endif /* not TRILIBRARY */
-}
-
-/*****************************************************************************/
-/*                                                                           */
-/*  writevoronoi()   Write the Voronoi diagram to a .v.node and .v.edge      */
-/*                   file.                                                   */
-/*                                                                           */
-/*  The Voronoi diagram is the geometric dual of the Delaunay triangulation. */
-/*  Hence, the Voronoi vertices are listed by traversing the Delaunay        */
-/*  triangles, and the Voronoi edges are listed by traversing the Delaunay   */
-/*  edges.                                                                   */
-/*                                                                           */
-/*  WARNING:  In order to assign numbers to the Voronoi vertices, this       */
-/*  procedure messes up the subsegments or the extra nodes of every          */
-/*  element.  Hence, you should call this procedure last.                    */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef TRILIBRARY
-
-#ifdef ANSI_DECLARATORS
-void writevoronoi(struct mesh *m, struct behavior *b, REAL **vpointlist,
-                  REAL **vpointattriblist, int **vpointmarkerlist,
-                  int **vedgelist, int **vedgemarkerlist, REAL **vnormlist)
-#else /* not ANSI_DECLARATORS */
-void writevoronoi(m, b, vpointlist, vpointattriblist, vpointmarkerlist,
-                  vedgelist, vedgemarkerlist, vnormlist)
-struct mesh *m;
-struct behavior *b;
-REAL **vpointlist;
-REAL **vpointattriblist;
-int **vpointmarkerlist;
-int **vedgelist;
-int **vedgemarkerlist;
-REAL **vnormlist;
-#endif /* not ANSI_DECLARATORS */
-
-#else /* not TRILIBRARY */
-
-#ifdef ANSI_DECLARATORS
-void writevoronoi(struct mesh *m, struct behavior *b, char *vnodefilename,
-                  char *vedgefilename, int argc, char **argv)
-#else /* not ANSI_DECLARATORS */
-void writevoronoi(m, b, vnodefilename, vedgefilename, argc, argv)
-struct mesh *m;
-struct behavior *b;
-char *vnodefilename;
-char *vedgefilename;
-int argc;
-char **argv;
-#endif /* not ANSI_DECLARATORS */
-
-#endif /* not TRILIBRARY */
-
-{
-#ifdef TRILIBRARY
-  REAL *plist;
-  REAL *palist;
-  int *elist;
-  REAL *normlist;
-  int coordindex;
-  int attribindex;
-#else /* not TRILIBRARY */
-  FILE *outfile;
-#endif /* not TRILIBRARY */
-  struct otri triangleloop, trisym;
-  vertex torg, tdest, tapex;
-  REAL circumcenter[2];
-  REAL xi, eta;
-  long vnodenumber, vedgenumber;
-  int p1, p2;
-  int i;
-  triangle ptr;                         /* Temporary variable used by sym(). */
-
-#ifdef TRILIBRARY
-  if (!b->quiet) {
-    printf("Writing Voronoi vertices.\n");
-  }
-  /* Allocate memory for Voronoi vertices if necessary. */
-  if (*vpointlist == (REAL *) NULL) {
-    *vpointlist = (REAL *) trimalloc((int) (m->triangles.items * 2 *
-                                            sizeof(REAL)));
-  }
-  /* Allocate memory for Voronoi vertex attributes if necessary. */
-  if (*vpointattriblist == (REAL *) NULL) {
-    *vpointattriblist = (REAL *) trimalloc((int) (m->triangles.items *
-                                                  m->nextras * sizeof(REAL)));
-  }
-  *vpointmarkerlist = (int *) NULL;
-  plist = *vpointlist;
-  palist = *vpointattriblist;
-  coordindex = 0;
-  attribindex = 0;
-#else /* not TRILIBRARY */
-  if (!b->quiet) {
-    printf("Writing %s.\n", vnodefilename);
-  }
-  outfile = fopen(vnodefilename, "w");
-  if (outfile == (FILE *) NULL) {
-    printf("  Error:  Cannot create file %s.\n", vnodefilename);
-    triexit(1);
-  }
-  /* Number of triangles, two dimensions, number of vertex attributes, */
-  /*   no markers.                                                     */
-  fprintf(outfile, "%ld  %d  %d  %d\n", m->triangles.items, 2, m->nextras, 0);
-#endif /* not TRILIBRARY */
-
-  traversalinit(&m->triangles);
-  triangleloop.tri = triangletraverse(m);
-  triangleloop.orient = 0;
-  vnodenumber = b->firstnumber;
-  while (triangleloop.tri != (triangle *) NULL) {
-    org(triangleloop, torg);
-    dest(triangleloop, tdest);
-    apex(triangleloop, tapex);
-    findcircumcenter(m, b, torg, tdest, tapex, circumcenter, &xi, &eta, 0);
-#ifdef TRILIBRARY
-    /* X and y coordinates. */
-    plist[coordindex++] = circumcenter[0];
-    plist[coordindex++] = circumcenter[1];
-    for (i = 2; i < 2 + m->nextras; i++) {
-      /* Interpolate the vertex attributes at the circumcenter. */
-      palist[attribindex++] = torg[i] + xi * (tdest[i] - torg[i])
-                                     + eta * (tapex[i] - torg[i]);
-    }
-#else /* not TRILIBRARY */
-    /* Voronoi vertex number, x and y coordinates. */
-    fprintf(outfile, "%4ld    %.17g  %.17g", vnodenumber, circumcenter[0],
-            circumcenter[1]);
-    for (i = 2; i < 2 + m->nextras; i++) {
-      /* Interpolate the vertex attributes at the circumcenter. */
-      fprintf(outfile, "  %.17g", torg[i] + xi * (tdest[i] - torg[i])
-                                         + eta * (tapex[i] - torg[i]));
-    }
-    fprintf(outfile, "\n");
-#endif /* not TRILIBRARY */
-
-    * (int *) (triangleloop.tri + 6) = (int) vnodenumber;
-    triangleloop.tri = triangletraverse(m);
-    vnodenumber++;
-  }
-
-#ifndef TRILIBRARY
-  finishfile(outfile, argc, argv);
-#endif /* not TRILIBRARY */
-
-#ifdef TRILIBRARY
-  if (!b->quiet) {
-    printf("Writing Voronoi edges.\n");
-  }
-  /* Allocate memory for output Voronoi edges if necessary. */
-  if (*vedgelist == (int *) NULL) {
-    *vedgelist = (int *) trimalloc((int) (m->edges * 2 * sizeof(int)));
-  }
-  *vedgemarkerlist = (int *) NULL;
-  /* Allocate memory for output Voronoi norms if necessary. */
-  if (*vnormlist == (REAL *) NULL) {
-    *vnormlist = (REAL *) trimalloc((int) (m->edges * 2 * sizeof(REAL)));
-  }
-  elist = *vedgelist;
-  normlist = *vnormlist;
-  coordindex = 0;
-#else /* not TRILIBRARY */
-  if (!b->quiet) {
-    printf("Writing %s.\n", vedgefilename);
-  }
-  outfile = fopen(vedgefilename, "w");
-  if (outfile == (FILE *) NULL) {
-    printf("  Error:  Cannot create file %s.\n", vedgefilename);
-    triexit(1);
-  }
-  /* Number of edges, zero boundary markers. */
-  fprintf(outfile, "%ld  %d\n", m->edges, 0);
-#endif /* not TRILIBRARY */
-
-  traversalinit(&m->triangles);
-  triangleloop.tri = triangletraverse(m);
-  vedgenumber = b->firstnumber;
-  /* To loop over the set of edges, loop over all triangles, and look at   */
-  /*   the three edges of each triangle.  If there isn't another triangle  */
-  /*   adjacent to the edge, operate on the edge.  If there is another     */
-  /*   adjacent triangle, operate on the edge only if the current triangle */
-  /*   has a smaller pointer than its neighbor.  This way, each edge is    */
-  /*   considered only once.                                               */
-  while (triangleloop.tri != (triangle *) NULL) {
-    for (triangleloop.orient = 0; triangleloop.orient < 3;
-         triangleloop.orient++) {
-      sym(triangleloop, trisym);
-      if ((triangleloop.tri < trisym.tri) || (trisym.tri == m->dummytri)) {
-        /* Find the number of this triangle (and Voronoi vertex). */
-        p1 = * (int *) (triangleloop.tri + 6);
-        if (trisym.tri == m->dummytri) {
-          org(triangleloop, torg);
-          dest(triangleloop, tdest);
-#ifdef TRILIBRARY
-          /* Copy an infinite ray.  Index of one endpoint, and -1. */
-          elist[coordindex] = p1;
-          normlist[coordindex++] = tdest[1] - torg[1];
-          elist[coordindex] = -1;
-          normlist[coordindex++] = torg[0] - tdest[0];
-#else /* not TRILIBRARY */
-          /* Write an infinite ray.  Edge number, index of one endpoint, -1, */
-          /*   and x and y coordinates of a vector representing the          */
-          /*   direction of the ray.                                         */
-          fprintf(outfile, "%4ld   %d  %d   %.17g  %.17g\n", vedgenumber,
-                  p1, -1, tdest[1] - torg[1], torg[0] - tdest[0]);
-#endif /* not TRILIBRARY */
-        } else {
-          /* Find the number of the adjacent triangle (and Voronoi vertex). */
-          p2 = * (int *) (trisym.tri + 6);
-          /* Finite edge.  Write indices of two endpoints. */
-#ifdef TRILIBRARY
-          elist[coordindex] = p1;
-          normlist[coordindex++] = 0.0;
-          elist[coordindex] = p2;
-          normlist[coordindex++] = 0.0;
-#else /* not TRILIBRARY */
-          fprintf(outfile, "%4ld   %d  %d\n", vedgenumber, p1, p2);
-#endif /* not TRILIBRARY */
-        }
-        vedgenumber++;
-      }
-    }
-    triangleloop.tri = triangletraverse(m);
-  }
-
-#ifndef TRILIBRARY
-  finishfile(outfile, argc, argv);
-#endif /* not TRILIBRARY */
-}
-
-#ifdef TRILIBRARY
-
-#ifdef ANSI_DECLARATORS
-void writeneighbors(struct mesh *m, struct behavior *b, int **neighborlist)
-#else /* not ANSI_DECLARATORS */
-void writeneighbors(m, b, neighborlist)
-struct mesh *m;
-struct behavior *b;
-int **neighborlist;
-#endif /* not ANSI_DECLARATORS */
-
-#else /* not TRILIBRARY */
-
-#ifdef ANSI_DECLARATORS
-void writeneighbors(struct mesh *m, struct behavior *b, char *neighborfilename,
-                    int argc, char **argv)
-#else /* not ANSI_DECLARATORS */
-void writeneighbors(m, b, neighborfilename, argc, argv)
-struct mesh *m;
-struct behavior *b;
-char *neighborfilename;
-int argc;
-char **argv;
-#endif /* not ANSI_DECLARATORS */
-
-#endif /* not TRILIBRARY */
-
-{
-#ifdef TRILIBRARY
-  int *nlist;
-  int index;
-#else /* not TRILIBRARY */
-  FILE *outfile;
-#endif /* not TRILIBRARY */
-  struct otri triangleloop, trisym;
-  long elementnumber;
-  int neighbor1, neighbor2, neighbor3;
-  triangle ptr;                         /* Temporary variable used by sym(). */
-
-#ifdef TRILIBRARY
-  if (!b->quiet) {
-    printf("Writing neighbors.\n");
-  }
-  /* Allocate memory for neighbors if necessary. */
-  if (*neighborlist == (int *) NULL) {
-    *neighborlist = (int *) trimalloc((int) (m->triangles.items * 3 *
-                                             sizeof(int)));
-  }
-  nlist = *neighborlist;
-  index = 0;
-#else /* not TRILIBRARY */
-  if (!b->quiet) {
-    printf("Writing %s.\n", neighborfilename);
-  }
-  outfile = fopen(neighborfilename, "w");
-  if (outfile == (FILE *) NULL) {
-    printf("  Error:  Cannot create file %s.\n", neighborfilename);
-    triexit(1);
-  }
-  /* Number of triangles, three neighbors per triangle. */
-  fprintf(outfile, "%ld  %d\n", m->triangles.items, 3);
-#endif /* not TRILIBRARY */
-
-  traversalinit(&m->triangles);
-  triangleloop.tri = triangletraverse(m);
-  triangleloop.orient = 0;
-  elementnumber = b->firstnumber;
-  while (triangleloop.tri != (triangle *) NULL) {
-    * (int *) (triangleloop.tri + 6) = (int) elementnumber;
-    triangleloop.tri = triangletraverse(m);
-    elementnumber++;
-  }
-  * (int *) (m->dummytri + 6) = -1;
-
-  traversalinit(&m->triangles);
-  triangleloop.tri = triangletraverse(m);
-  elementnumber = b->firstnumber;
-  while (triangleloop.tri != (triangle *) NULL) {
-    triangleloop.orient = 1;
-    sym(triangleloop, trisym);
-    neighbor1 = * (int *) (trisym.tri + 6);
-    triangleloop.orient = 2;
-    sym(triangleloop, trisym);
-    neighbor2 = * (int *) (trisym.tri + 6);
-    triangleloop.orient = 0;
-    sym(triangleloop, trisym);
-    neighbor3 = * (int *) (trisym.tri + 6);
-#ifdef TRILIBRARY
-    nlist[index++] = neighbor1;
-    nlist[index++] = neighbor2;
-    nlist[index++] = neighbor3;
-#else /* not TRILIBRARY */
-    /* Triangle number, neighboring triangle numbers. */
-    fprintf(outfile, "%4ld    %d  %d  %d\n", elementnumber,
-            neighbor1, neighbor2, neighbor3);
-#endif /* not TRILIBRARY */
-
-    triangleloop.tri = triangletraverse(m);
-    elementnumber++;
-  }
-
-#ifndef TRILIBRARY
-  finishfile(outfile, argc, argv);
-#endif /* not TRILIBRARY */
-}
-
-/*****************************************************************************/
-/*                                                                           */
-/*  writeoff()   Write the triangulation to an .off file.                    */
-/*                                                                           */
-/*  OFF stands for the Object File Format, a format used by the Geometry     */
-/*  Center's Geomview package.                                               */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifndef TRILIBRARY
-
-#ifdef ANSI_DECLARATORS
-void writeoff(struct mesh *m, struct behavior *b, char *offfilename,
-              int argc, char **argv)
-#else /* not ANSI_DECLARATORS */
-void writeoff(m, b, offfilename, argc, argv)
-struct mesh *m;
-struct behavior *b;
-char *offfilename;
-int argc;
-char **argv;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  FILE *outfile;
-  struct otri triangleloop;
-  vertex vertexloop;
-  vertex p1, p2, p3;
-  long outvertices;
-
-  if (!b->quiet) {
-    printf("Writing %s.\n", offfilename);
-  }
-
-  if (b->jettison) {
-    outvertices = m->vertices.items - m->undeads;
-  } else {
-    outvertices = m->vertices.items;
-  }
-
-  outfile = fopen(offfilename, "w");
-  if (outfile == (FILE *) NULL) {
-    printf("  Error:  Cannot create file %s.\n", offfilename);
-    triexit(1);
-  }
-  /* Number of vertices, triangles, and edges. */
-  fprintf(outfile, "OFF\n%ld  %ld  %ld\n", outvertices, m->triangles.items,
-          m->edges);
-
-  /* Write the vertices. */
-  traversalinit(&m->vertices);
-  vertexloop = vertextraverse(m);
-  while (vertexloop != (vertex) NULL) {
-    if (!b->jettison || (vertextype(vertexloop) != UNDEADVERTEX)) {
-      /* The "0.0" is here because the OFF format uses 3D coordinates. */
-      fprintf(outfile, " %.17g  %.17g  %.17g\n", vertexloop[0], vertexloop[1],
-              0.0);
-    }
-    vertexloop = vertextraverse(m);
-  }
-
-  /* Write the triangles. */
-  traversalinit(&m->triangles);
-  triangleloop.tri = triangletraverse(m);
-  triangleloop.orient = 0;
-  while (triangleloop.tri != (triangle *) NULL) {
-    org(triangleloop, p1);
-    dest(triangleloop, p2);
-    apex(triangleloop, p3);
-    /* The "3" means a three-vertex polygon. */
-    fprintf(outfile, " 3   %4d  %4d  %4d\n", vertexmark(p1) - b->firstnumber,
-            vertexmark(p2) - b->firstnumber, vertexmark(p3) - b->firstnumber);
-    triangleloop.tri = triangletraverse(m);
-  }
-  finishfile(outfile, argc, argv);
-}
-
-#endif /* not TRILIBRARY */
-
-/**                                                                         **/
-/**                                                                         **/
-/********* File I/O routines end here                                *********/
-
-/*****************************************************************************/
-/*                                                                           */
-/*  quality_statistics()   Print statistics about the quality of the mesh.   */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef ANSI_DECLARATORS
-void quality_statistics(struct mesh *m, struct behavior *b)
-#else /* not ANSI_DECLARATORS */
-void quality_statistics(m, b)
-struct mesh *m;
-struct behavior *b;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  struct otri triangleloop;
-  vertex p[3];
-  REAL cossquaretable[8];
-  REAL ratiotable[16];
-  REAL dx[3], dy[3];
-  REAL edgelength[3];
-  REAL dotproduct;
-  REAL cossquare;
-  REAL triarea;
-  REAL shortest, longest;
-  REAL trilongest2;
-  REAL smallestarea, biggestarea;
-  REAL triminaltitude2;
-  REAL minaltitude;
-  REAL triaspect2;
-  REAL worstaspect;
-  REAL smallestangle, biggestangle;
-  REAL radconst, degconst;
-  int angletable[18];
-  int aspecttable[16];
-  int aspectindex;
-  int tendegree;
-  int acutebiggest;
-  int i, ii, j, k;
-
-  printf("Mesh quality statistics:\n\n");
-  radconst = PI / 18.0;
-  degconst = 180.0 / PI;
-  for (i = 0; i < 8; i++) {
-    cossquaretable[i] = cos(radconst * (REAL) (i + 1));
-    cossquaretable[i] = cossquaretable[i] * cossquaretable[i];
-  }
-  for (i = 0; i < 18; i++) {
-    angletable[i] = 0;
-  }
-
-  ratiotable[0]  =      1.5;      ratiotable[1]  =     2.0;
-  ratiotable[2]  =      2.5;      ratiotable[3]  =     3.0;
-  ratiotable[4]  =      4.0;      ratiotable[5]  =     6.0;
-  ratiotable[6]  =     10.0;      ratiotable[7]  =    15.0;
-  ratiotable[8]  =     25.0;      ratiotable[9]  =    50.0;
-  ratiotable[10] =    100.0;      ratiotable[11] =   300.0;
-  ratiotable[12] =   1000.0;      ratiotable[13] = 10000.0;
-  ratiotable[14] = 100000.0;      ratiotable[15] =     0.0;
-  for (i = 0; i < 16; i++) {
-    aspecttable[i] = 0;
-  }
-
-  worstaspect = 0.0;
-  minaltitude = m->xmax - m->xmin + m->ymax - m->ymin;
-  minaltitude = minaltitude * minaltitude;
-  shortest = minaltitude;
-  longest = 0.0;
-  smallestarea = minaltitude;
-  biggestarea = 0.0;
-  worstaspect = 0.0;
-  smallestangle = 0.0;
-  biggestangle = 2.0;
-  acutebiggest = 1;
-
-  traversalinit(&m->triangles);
-  triangleloop.tri = triangletraverse(m);
-  triangleloop.orient = 0;
-  while (triangleloop.tri != (triangle *) NULL) {
-    org(triangleloop, p[0]);
-    dest(triangleloop, p[1]);
-    apex(triangleloop, p[2]);
-    trilongest2 = 0.0;
-
-    for (i = 0; i < 3; i++) {
-      j = plus1mod3[i];
-      k = minus1mod3[i];
-      dx[i] = p[j][0] - p[k][0];
-      dy[i] = p[j][1] - p[k][1];
-      edgelength[i] = dx[i] * dx[i] + dy[i] * dy[i];
-      if (edgelength[i] > trilongest2) {
-        trilongest2 = edgelength[i];
-      }
-      if (edgelength[i] > longest) {
-        longest = edgelength[i];
-      }
-      if (edgelength[i] < shortest) {
-        shortest = edgelength[i];
-      }
-    }
-
-    triarea = counterclockwise(m, b, p[0], p[1], p[2]);
-    if (triarea < smallestarea) {
-      smallestarea = triarea;
-    }
-    if (triarea > biggestarea) {
-      biggestarea = triarea;
-    }
-    triminaltitude2 = triarea * triarea / trilongest2;
-    if (triminaltitude2 < minaltitude) {
-      minaltitude = triminaltitude2;
-    }
-    triaspect2 = trilongest2 / triminaltitude2;
-    if (triaspect2 > worstaspect) {
-      worstaspect = triaspect2;
-    }
-    aspectindex = 0;
-    while ((triaspect2 > ratiotable[aspectindex] * ratiotable[aspectindex])
-           && (aspectindex < 15)) {
-      aspectindex++;
-    }
-    aspecttable[aspectindex]++;
-
-    for (i = 0; i < 3; i++) {
-      j = plus1mod3[i];
-      k = minus1mod3[i];
-      dotproduct = dx[j] * dx[k] + dy[j] * dy[k];
-      cossquare = dotproduct * dotproduct / (edgelength[j] * edgelength[k]);
-      tendegree = 8;
-      for (ii = 7; ii >= 0; ii--) {
-        if (cossquare > cossquaretable[ii]) {
-          tendegree = ii;
-        }
-      }
-      if (dotproduct <= 0.0) {
-        angletable[tendegree]++;
-        if (cossquare > smallestangle) {
-          smallestangle = cossquare;
-        }
-        if (acutebiggest && (cossquare < biggestangle)) {
-          biggestangle = cossquare;
-        }
-      } else {
-        angletable[17 - tendegree]++;
-        if (acutebiggest || (cossquare > biggestangle)) {
-          biggestangle = cossquare;
-          acutebiggest = 0;
-        }
-      }
-    }
-    triangleloop.tri = triangletraverse(m);
-  }
-
-  shortest = sqrt(shortest);
-  longest = sqrt(longest);
-  minaltitude = sqrt(minaltitude);
-  worstaspect = sqrt(worstaspect);
-  smallestarea *= 0.5;
-  biggestarea *= 0.5;
-  if (smallestangle >= 1.0) {
-    smallestangle = 0.0;
-  } else {
-    smallestangle = degconst * acos(sqrt(smallestangle));
-  }
-  if (biggestangle >= 1.0) {
-    biggestangle = 180.0;
-  } else {
-    if (acutebiggest) {
-      biggestangle = degconst * acos(sqrt(biggestangle));
-    } else {
-      biggestangle = 180.0 - degconst * acos(sqrt(biggestangle));
-    }
-  }
-
-  printf("  Smallest area: %16.5g   |  Largest area: %16.5g\n",
-         smallestarea, biggestarea);
-  printf("  Shortest edge: %16.5g   |  Longest edge: %16.5g\n",
-         shortest, longest);
-  printf("  Shortest altitude: %12.5g   |  Largest aspect ratio: %8.5g\n\n",
-         minaltitude, worstaspect);
-
-  printf("  Triangle aspect ratio histogram:\n");
-  printf("  1.1547 - %-6.6g    :  %8d    | %6.6g - %-6.6g     :  %8d\n",
-         ratiotable[0], aspecttable[0], ratiotable[7], ratiotable[8],
-         aspecttable[8]);
-  for (i = 1; i < 7; i++) {
-    printf("  %6.6g - %-6.6g    :  %8d    | %6.6g - %-6.6g     :  %8d\n",
-           ratiotable[i - 1], ratiotable[i], aspecttable[i],
-           ratiotable[i + 7], ratiotable[i + 8], aspecttable[i + 8]);
-  }
-  printf("  %6.6g - %-6.6g    :  %8d    | %6.6g -            :  %8d\n",
-         ratiotable[6], ratiotable[7], aspecttable[7], ratiotable[14],
-         aspecttable[15]);
-  printf("  (Aspect ratio is longest edge divided by shortest altitude)\n\n");
-
-  printf("  Smallest angle: %15.5g   |  Largest angle: %15.5g\n\n",
-         smallestangle, biggestangle);
-
-  printf("  Angle histogram:\n");
-  for (i = 0; i < 9; i++) {
-    printf("    %3d - %3d degrees:  %8d    |    %3d - %3d degrees:  %8d\n",
-           i * 10, i * 10 + 10, angletable[i],
-           i * 10 + 90, i * 10 + 100, angletable[i + 9]);
-  }
-  printf("\n");
-}
-
-/*****************************************************************************/
-/*                                                                           */
-/*  statistics()   Print all sorts of cool facts.                            */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef ANSI_DECLARATORS
-void statistics(struct mesh *m, struct behavior *b)
-#else /* not ANSI_DECLARATORS */
-void statistics(m, b)
-struct mesh *m;
-struct behavior *b;
-#endif /* not ANSI_DECLARATORS */
-
-{
-  printf("\nStatistics:\n\n");
-  printf("  Input vertices: %d\n", m->invertices);
-  if (b->refine) {
-    printf("  Input triangles: %d\n", m->inelements);
-  }
-  if (b->poly) {
-    printf("  Input segments: %d\n", m->insegments);
-    if (!b->refine) {
-      printf("  Input holes: %d\n", m->holes);
-    }
-  }
-
-  printf("\n  Mesh vertices: %ld\n", m->vertices.items - m->undeads);
-  printf("  Mesh triangles: %ld\n", m->triangles.items);
-  printf("  Mesh edges: %ld\n", m->edges);
-  printf("  Mesh exterior boundary edges: %ld\n", m->hullsize);
-  if (b->poly || b->refine) {
-    printf("  Mesh interior boundary edges: %ld\n",
-           m->subsegs.items - m->hullsize);
-    printf("  Mesh subsegments (constrained edges): %ld\n",
-           m->subsegs.items);
-  }
-  printf("\n");
-
-  if (b->verbose) {
-    quality_statistics(m, b);
-    printf("Memory allocation statistics:\n\n");
-    printf("  Maximum number of vertices: %ld\n", m->vertices.maxitems);
-    printf("  Maximum number of triangles: %ld\n", m->triangles.maxitems);
-    if (m->subsegs.maxitems > 0) {
-      printf("  Maximum number of subsegments: %ld\n", m->subsegs.maxitems);
-    }
-    if (m->viri.maxitems > 0) {
-      printf("  Maximum number of viri: %ld\n", m->viri.maxitems);
-    }
-    if (m->badsubsegs.maxitems > 0) {
-      printf("  Maximum number of encroached subsegments: %ld\n",
-             m->badsubsegs.maxitems);
-    }
-    if (m->badtriangles.maxitems > 0) {
-      printf("  Maximum number of bad triangles: %ld\n",
-             m->badtriangles.maxitems);
-    }
-    if (m->flipstackers.maxitems > 0) {
-      printf("  Maximum number of stacked triangle flips: %ld\n",
-             m->flipstackers.maxitems);
-    }
-    if (m->splaynodes.maxitems > 0) {
-      printf("  Maximum number of splay tree nodes: %ld\n",
-             m->splaynodes.maxitems);
-    }
-    printf("  Approximate heap memory use (bytes): %ld\n\n",
-           m->vertices.maxitems * m->vertices.itembytes +
-           m->triangles.maxitems * m->triangles.itembytes +
-           m->subsegs.maxitems * m->subsegs.itembytes +
-           m->viri.maxitems * m->viri.itembytes +
-           m->badsubsegs.maxitems * m->badsubsegs.itembytes +
-           m->badtriangles.maxitems * m->badtriangles.itembytes +
-           m->flipstackers.maxitems * m->flipstackers.itembytes +
-           m->splaynodes.maxitems * m->splaynodes.itembytes);
-
-    printf("Algorithmic statistics:\n\n");
-    if (!b->weighted) {
-      printf("  Number of incircle tests: %ld\n", m->incirclecount);
-    } else {
-      printf("  Number of 3D orientation tests: %ld\n", m->orient3dcount);
-    }
-    printf("  Number of 2D orientation tests: %ld\n", m->counterclockcount);
-    if (m->hyperbolacount > 0) {
-      printf("  Number of right-of-hyperbola tests: %ld\n",
-             m->hyperbolacount);
-    }
-    if (m->circletopcount > 0) {
-      printf("  Number of circle top computations: %ld\n",
-             m->circletopcount);
-    }
-    if (m->circumcentercount > 0) {
-      printf("  Number of triangle circumcenter computations: %ld\n",
-             m->circumcentercount);
-    }
-    printf("\n");
-  }
-}
-
-/*****************************************************************************/
-/*                                                                           */
-/*  main() or triangulate()   Gosh, do everything.                           */
-/*                                                                           */
-/*  The sequence is roughly as follows.  Many of these steps can be skipped, */
-/*  depending on the command line switches.                                  */
-/*                                                                           */
-/*  - Initialize constants and parse the command line.                       */
-/*  - Read the vertices from a file and either                               */
-/*    - triangulate them (no -r), or                                         */
-/*    - read an old mesh from files and reconstruct it (-r).                 */
-/*  - Insert the PSLG segments (-p), and possibly segments on the convex     */
-/*      hull (-c).                                                           */
-/*  - Read the holes (-p), regional attributes (-pA), and regional area      */
-/*      constraints (-pa).  Carve the holes and concavities, and spread the  */
-/*      regional attributes and area constraints.                            */
-/*  - Enforce the constraints on minimum angle (-q) and maximum area (-a).   */
-/*      Also enforce the conforming Delaunay property (-q and -a).           */
-/*  - Compute the number of edges in the resulting mesh.                     */
-/*  - Promote the mesh's linear triangles to higher order elements (-o).     */
-/*  - Write the output files and print the statistics.                       */
-/*  - Check the consistency and Delaunay property of the mesh (-C).          */
-/*                                                                           */
-/*****************************************************************************/
-
-#ifdef TRILIBRARY
-
-#ifdef ANSI_DECLARATORS
-void triangulate(char *triswitches, struct triangulateio *in,
-                 struct triangulateio *out, struct triangulateio *vorout)
-#else /* not ANSI_DECLARATORS */
-void triangulate(triswitches, in, out, vorout)
-char *triswitches;
-struct triangulateio *in;
-struct triangulateio *out;
-struct triangulateio *vorout;
-#endif /* not ANSI_DECLARATORS */
-
-#else /* not TRILIBRARY */
-
-#ifdef ANSI_DECLARATORS
-int main(int argc, char **argv)
-#else /* not ANSI_DECLARATORS */
-int main(argc, argv)
-int argc;
-char **argv;
-#endif /* not ANSI_DECLARATORS */
-
-#endif /* not TRILIBRARY */
-
-{
-  struct mesh m;
-  struct behavior b;
-  REAL *holearray;                                        /* Array of holes. */
-  REAL *regionarray;   /* Array of regional attributes and area constraints. */
-#ifndef TRILIBRARY
-  FILE *polyfile;
-#endif /* not TRILIBRARY */
-#ifndef NO_TIMER
-  /* Variables for timing the performance of Triangle.  The types are */
-  /*   defined in sys/time.h.                                         */
-  struct timeval tv0, tv1, tv2, tv3, tv4, tv5, tv6;
-  struct timezone tz;
-#endif /* not NO_TIMER */
-
-#ifndef NO_TIMER
-  gettimeofday(&tv0, &tz);
-#endif /* not NO_TIMER */
-
-  triangleinit(&m);
-#ifdef TRILIBRARY
-  parsecommandline(1, &triswitches, &b);
-#else /* not TRILIBRARY */
-  parsecommandline(argc, argv, &b);
-#endif /* not TRILIBRARY */
-  m.steinerleft = b.steiner;
-
-#ifdef TRILIBRARY
-  transfernodes(&m, &b, in->pointlist, in->pointattributelist,
-                in->pointmarkerlist, in->numberofpoints,
-                in->numberofpointattributes);
-#else /* not TRILIBRARY */
-  readnodes(&m, &b, b.innodefilename, b.inpolyfilename, &polyfile);
-#endif /* not TRILIBRARY */
-
-#ifndef NO_TIMER
-  if (!b.quiet) {
-    gettimeofday(&tv1, &tz);
-  }
-#endif /* not NO_TIMER */
-
-#ifdef CDT_ONLY
-  m.hullsize = delaunay(&m, &b);                /* Triangulate the vertices. */
-#else /* not CDT_ONLY */
-  if (b.refine) {
-    /* Read and reconstruct a mesh. */
-#ifdef TRILIBRARY
-    m.hullsize = reconstruct(&m, &b, in->trianglelist,
-                             in->triangleattributelist, in->trianglearealist,
-                             in->numberoftriangles, in->numberofcorners,
-                             in->numberoftriangleattributes,
-                             in->segmentlist, in->segmentmarkerlist,
-                             in->numberofsegments);
-#else /* not TRILIBRARY */
-    m.hullsize = reconstruct(&m, &b, b.inelefilename, b.areafilename,
-                             b.inpolyfilename, polyfile);
-#endif /* not TRILIBRARY */
-  } else {
-    m.hullsize = delaunay(&m, &b);              /* Triangulate the vertices. */
-  }
-#endif /* not CDT_ONLY */
-
-#ifndef NO_TIMER
-  if (!b.quiet) {
-    gettimeofday(&tv2, &tz);
-    if (b.refine) {
-      printf("Mesh reconstruction");
-    } else {
-      printf("Delaunay");
-    }
-    printf(" milliseconds:  %ld\n", 1000l * (tv2.tv_sec - tv1.tv_sec) +
-           (tv2.tv_usec - tv1.tv_usec) / 1000l);
-  }
-#endif /* not NO_TIMER */
-
-  /* Ensure that no vertex can be mistaken for a triangular bounding */
-  /*   box vertex in insertvertex().                                 */
-  m.infvertex1 = (vertex) NULL;
-  m.infvertex2 = (vertex) NULL;
-  m.infvertex3 = (vertex) NULL;
-
-  if (b.usesegments) {
-    m.checksegments = 1;                /* Segments will be introduced next. */
-    if (!b.refine) {
-      /* Insert PSLG segments and/or convex hull segments. */
-#ifdef TRILIBRARY
-      formskeleton(&m, &b, in->segmentlist,
-                   in->segmentmarkerlist, in->numberofsegments);
-#else /* not TRILIBRARY */
-      formskeleton(&m, &b, polyfile, b.inpolyfilename);
-#endif /* not TRILIBRARY */
-    }
-  }
-
-#ifndef NO_TIMER
-  if (!b.quiet) {
-    gettimeofday(&tv3, &tz);
-    if (b.usesegments && !b.refine) {
-      printf("Segment milliseconds:  %ld\n",
-             1000l * (tv3.tv_sec - tv2.tv_sec) +
-             (tv3.tv_usec - tv2.tv_usec) / 1000l);
-    }
-  }
-#endif /* not NO_TIMER */
-
-  if (b.poly && (m.triangles.items > 0)) {
-#ifdef TRILIBRARY
-    holearray = in->holelist;
-    m.holes = in->numberofholes;
-    regionarray = in->regionlist;
-    m.regions = in->numberofregions;
-#else /* not TRILIBRARY */
-    readholes(&m, &b, polyfile, b.inpolyfilename, &holearray, &m.holes,
-              &regionarray, &m.regions);
-#endif /* not TRILIBRARY */
-    if (!b.refine) {
-      /* Carve out holes and concavities. */
-      carveholes(&m, &b, holearray, m.holes, regionarray, m.regions);
-    }
-  } else {
-    /* Without a PSLG, there can be no holes or regional attributes   */
-    /*   or area constraints.  The following are set to zero to avoid */
-    /*   an accidental free() later.                                  */
-    m.holes = 0;
-    m.regions = 0;
-  }
-
-#ifndef NO_TIMER
-  if (!b.quiet) {
-    gettimeofday(&tv4, &tz);
-    if (b.poly && !b.refine) {
-      printf("Hole milliseconds:  %ld\n", 1000l * (tv4.tv_sec - tv3.tv_sec) +
-             (tv4.tv_usec - tv3.tv_usec) / 1000l);
-    }
-  }
-#endif /* not NO_TIMER */
-
-#ifndef CDT_ONLY
-  if (b.quality && (m.triangles.items > 0)) {
-    enforcequality(&m, &b);           /* Enforce angle and area constraints. */
-  }
-#endif /* not CDT_ONLY */
-
-#ifndef NO_TIMER
-  if (!b.quiet) {
-    gettimeofday(&tv5, &tz);
-#ifndef CDT_ONLY
-    if (b.quality) {
-      printf("Quality milliseconds:  %ld\n",
-             1000l * (tv5.tv_sec - tv4.tv_sec) +
-             (tv5.tv_usec - tv4.tv_usec) / 1000l);
-    }
-#endif /* not CDT_ONLY */
-  }
-#endif /* not NO_TIMER */
-
-  /* Calculate the number of edges. */
-  m.edges = (3l * m.triangles.items + m.hullsize) / 2l;
-
-  if (b.order > 1) {
-    highorder(&m, &b);       /* Promote elements to higher polynomial order. */
-  }
-  if (!b.quiet) {
-    printf("\n");
-  }
-
-#ifdef TRILIBRARY
-  if (b.jettison) {
-    out->numberofpoints = m.vertices.items - m.undeads;
-  } else {
-    out->numberofpoints = m.vertices.items;
-  }
-  out->numberofpointattributes = m.nextras;
-  out->numberoftriangles = m.triangles.items;
-  out->numberofcorners = (b.order + 1) * (b.order + 2) / 2;
-  out->numberoftriangleattributes = m.eextras;
-  out->numberofedges = m.edges;
-  if (b.usesegments) {
-    out->numberofsegments = m.subsegs.items;
-  } else {
-    out->numberofsegments = m.hullsize;
-  }
-  if (vorout != (struct triangulateio *) NULL) {
-    vorout->numberofpoints = m.triangles.items;
-    vorout->numberofpointattributes = m.nextras;
-    vorout->numberofedges = m.edges;
-  }
-#endif /* TRILIBRARY */
-  /* If not using iteration numbers, don't write a .node file if one was */
-  /*   read, because the original one would be overwritten!              */
-  if (b.nonodewritten || (b.noiterationnum && m.readnodefile)) {
-    if (!b.quiet) {
-#ifdef TRILIBRARY
-      printf("NOT writing vertices.\n");
-#else /* not TRILIBRARY */
-      printf("NOT writing a .node file.\n");
-#endif /* not TRILIBRARY */
-    }
-    numbernodes(&m, &b);         /* We must remember to number the vertices. */
-  } else {
-    /* writenodes() numbers the vertices too. */
-#ifdef TRILIBRARY
-    writenodes(&m, &b, &out->pointlist, &out->pointattributelist,
-               &out->pointmarkerlist);
-#else /* not TRILIBRARY */
-    writenodes(&m, &b, b.outnodefilename, argc, argv);
-#endif /* TRILIBRARY */
-  }
-  if (b.noelewritten) {
-    if (!b.quiet) {
-#ifdef TRILIBRARY
-      printf("NOT writing triangles.\n");
-#else /* not TRILIBRARY */
-      printf("NOT writing an .ele file.\n");
-#endif /* not TRILIBRARY */
-    }
-  } else {
-#ifdef TRILIBRARY
-    writeelements(&m, &b, &out->trianglelist, &out->triangleattributelist);
-#else /* not TRILIBRARY */
-    writeelements(&m, &b, b.outelefilename, argc, argv);
-#endif /* not TRILIBRARY */
-  }
-  /* The -c switch (convex switch) causes a PSLG to be written */
-  /*   even if none was read.                                  */
-  if (b.poly || b.convex) {
-    /* If not using iteration numbers, don't overwrite the .poly file. */
-    if (b.nopolywritten || b.noiterationnum) {
-      if (!b.quiet) {
-#ifdef TRILIBRARY
-        printf("NOT writing segments.\n");
-#else /* not TRILIBRARY */
-        printf("NOT writing a .poly file.\n");
-#endif /* not TRILIBRARY */
-      }
-    } else {
-#ifdef TRILIBRARY
-      writepoly(&m, &b, &out->segmentlist, &out->segmentmarkerlist);
-      out->numberofholes = m.holes;
-      out->numberofregions = m.regions;
-      if (b.poly) {
-        out->holelist = in->holelist;
-        out->regionlist = in->regionlist;
-      } else {
-        out->holelist = (REAL *) NULL;
-        out->regionlist = (REAL *) NULL;
-      }
-#else /* not TRILIBRARY */
-      writepoly(&m, &b, b.outpolyfilename, holearray, m.holes, regionarray,
-                m.regions, argc, argv);
-#endif /* not TRILIBRARY */
-    }
-  }
-#ifndef TRILIBRARY
-#ifndef CDT_ONLY
-  if (m.regions > 0) {
-    trifree((VOID *) regionarray);
-  }
-#endif /* not CDT_ONLY */
-  if (m.holes > 0) {
-    trifree((VOID *) holearray);
-  }
-  if (b.geomview) {
-    writeoff(&m, &b, b.offfilename, argc, argv);
-  }
-#endif /* not TRILIBRARY */
-  if (b.edgesout) {
-#ifdef TRILIBRARY
-    writeedges(&m, &b, &out->edgelist, &out->edgemarkerlist);
-#else /* not TRILIBRARY */
-    writeedges(&m, &b, b.edgefilename, argc, argv);
-#endif /* not TRILIBRARY */
-  }
-  if (b.voronoi) {
-#ifdef TRILIBRARY
-    writevoronoi(&m, &b, &vorout->pointlist, &vorout->pointattributelist,
-                 &vorout->pointmarkerlist, &vorout->edgelist,
-                 &vorout->edgemarkerlist, &vorout->normlist);
-#else /* not TRILIBRARY */
-    writevoronoi(&m, &b, b.vnodefilename, b.vedgefilename, argc, argv);
-#endif /* not TRILIBRARY */
-  }
-  if (b.neighbors) {
-#ifdef TRILIBRARY
-    writeneighbors(&m, &b, &out->neighborlist);
-#else /* not TRILIBRARY */
-    writeneighbors(&m, &b, b.neighborfilename, argc, argv);
-#endif /* not TRILIBRARY */
-  }
-
-  if (!b.quiet) {
-#ifndef NO_TIMER
-    gettimeofday(&tv6, &tz);
-    printf("\nOutput milliseconds:  %ld\n",
-           1000l * (tv6.tv_sec - tv5.tv_sec) +
-           (tv6.tv_usec - tv5.tv_usec) / 1000l);
-    printf("Total running milliseconds:  %ld\n",
-           1000l * (tv6.tv_sec - tv0.tv_sec) +
-           (tv6.tv_usec - tv0.tv_usec) / 1000l);
-#endif /* not NO_TIMER */
-
-    statistics(&m, &b);
-  }
-
-#ifndef REDUCED
-  if (b.docheck) {
-    checkmesh(&m, &b);
-    checkdelaunay(&m, &b);
-  }
-#endif /* not REDUCED */
-
-  triangledeinit(&m, &b);
-#ifndef TRILIBRARY
-  return 0;
-#endif /* not TRILIBRARY */
-}
diff --git a/src/modules/grid/grid_gridding/nn/triangle.h b/src/modules/grid/grid_gridding/nn/triangle.h
deleted file mode 100644
index c78fe20..0000000
--- a/src/modules/grid/grid_gridding/nn/triangle.h
+++ /dev/null
@@ -1,296 +0,0 @@
-/**********************************************************
- * Version $Id: triangle.h 911 2011-02-14 16:38:15Z reklov_w $
- *********************************************************/
-/*****************************************************************************/
-/*                                                                           */
-/*  (triangle.h)                                                             */
-/*                                                                           */
-/*  Include file for programs that call Triangle.                            */
-/*                                                                           */
-/*  Accompanies Triangle Version 1.6                                         */
-/*  July 28, 2005                                                            */
-/*                                                                           */
-/*  Copyright 1996, 2005                                                     */
-/*  Jonathan Richard Shewchuk                                                */
-/*  2360 Woolsey #H                                                          */
-/*  Berkeley, California  94705-1927                                         */
-/*  jrs at cs.berkeley.edu                                                      */
-/*                                                                           */
-/*****************************************************************************/
-
-/*****************************************************************************/
-/*                                                                           */
-/*  How to call Triangle from another program                                */
-/*                                                                           */
-/*                                                                           */
-/*  If you haven't read Triangle's instructions (run "triangle -h" to read   */
-/*  them), you won't understand what follows.                                */
-/*                                                                           */
-/*  Triangle must be compiled into an object file (triangle.o) with the      */
-/*  TRILIBRARY symbol defined (generally by using the -DTRILIBRARY compiler  */
-/*  switch).  The makefile included with Triangle will do this for you if    */
-/*  you run "make trilibrary".  The resulting object file can be called via  */
-/*  the procedure triangulate().                                             */
-/*                                                                           */
-/*  If the size of the object file is important to you, you may wish to      */
-/*  generate a reduced version of triangle.o.  The REDUCED symbol gets rid   */
-/*  of all features that are primarily of research interest.  Specifically,  */
-/*  the -DREDUCED switch eliminates Triangle's -i, -F, -s, and -C switches.  */
-/*  The CDT_ONLY symbol gets rid of all meshing algorithms above and beyond  */
-/*  constrained Delaunay triangulation.  Specifically, the -DCDT_ONLY switch */
-/*  eliminates Triangle's -r, -q, -a, -u, -D, -Y, -S, and -s switches.       */
-/*                                                                           */
-/*  IMPORTANT:  These definitions (TRILIBRARY, REDUCED, CDT_ONLY) must be    */
-/*  made in the makefile or in triangle.c itself.  Putting these definitions */
-/*  in this file (triangle.h) will not create the desired effect.            */
-/*                                                                           */
-/*                                                                           */
-/*  The calling convention for triangulate() follows.                        */
-/*                                                                           */
-/*      void triangulate(triswitches, in, out, vorout)                       */
-/*      char *triswitches;                                                   */
-/*      struct triangulateio *in;                                            */
-/*      struct triangulateio *out;                                           */
-/*      struct triangulateio *vorout;                                        */
-/*                                                                           */
-/*  `triswitches' is a string containing the command line switches you wish  */
-/*  to invoke.  No initial dash is required.  Some suggestions:              */
-/*                                                                           */
-/*  - You'll probably find it convenient to use the `z' switch so that       */
-/*    points (and other items) are numbered from zero.  This simplifies      */
-/*    indexing, because the first item of any type always starts at index    */
-/*    [0] of the corresponding array, whether that item's number is zero or  */
-/*    one.                                                                   */
-/*  - You'll probably want to use the `Q' (quiet) switch in your final code, */
-/*    but you can take advantage of Triangle's printed output (including the */
-/*    `V' switch) while debugging.                                           */
-/*  - If you are not using the `q', `a', `u', `D', `j', or `s' switches,     */
-/*    then the output points will be identical to the input points, except   */
-/*    possibly for the boundary markers.  If you don't need the boundary     */
-/*    markers, you should use the `N' (no nodes output) switch to save       */
-/*    memory.  (If you do need boundary markers, but need to save memory, a  */
-/*    good nasty trick is to set out->pointlist equal to in->pointlist       */
-/*    before calling triangulate(), so that Triangle overwrites the input    */
-/*    points with identical copies.)                                         */
-/*  - The `I' (no iteration numbers) and `g' (.off file output) switches     */
-/*    have no effect when Triangle is compiled with TRILIBRARY defined.      */
-/*                                                                           */
-/*  `in', `out', and `vorout' are descriptions of the input, the output,     */
-/*  and the Voronoi output.  If the `v' (Voronoi output) switch is not used, */
-/*  `vorout' may be NULL.  `in' and `out' may never be NULL.                 */
-/*                                                                           */
-/*  Certain fields of the input and output structures must be initialized,   */
-/*  as described below.                                                      */
-/*                                                                           */
-/*****************************************************************************/
-
-/*****************************************************************************/
-/*                                                                           */
-/*  The `triangulateio' structure.                                           */
-/*                                                                           */
-/*  Used to pass data into and out of the triangulate() procedure.           */
-/*                                                                           */
-/*                                                                           */
-/*  Arrays are used to store points, triangles, markers, and so forth.  In   */
-/*  all cases, the first item in any array is stored starting at index [0].  */
-/*  However, that item is item number `1' unless the `z' switch is used, in  */
-/*  which case it is item number `0'.  Hence, you may find it easier to      */
-/*  index points (and triangles in the neighbor list) if you use the `z'     */
-/*  switch.  Unless, of course, you're calling Triangle from a Fortran       */
-/*  program.                                                                 */
-/*                                                                           */
-/*  Description of fields (except the `numberof' fields, which are obvious): */
-/*                                                                           */
-/*  `pointlist':  An array of point coordinates.  The first point's x        */
-/*    coordinate is at index [0] and its y coordinate at index [1], followed */
-/*    by the coordinates of the remaining points.  Each point occupies two   */
-/*    REALs.                                                                 */
-/*  `pointattributelist':  An array of point attributes.  Each point's       */
-/*    attributes occupy `numberofpointattributes' REALs.                     */
-/*  `pointmarkerlist':  An array of point markers; one int per point.        */
-/*                                                                           */
-/*  `trianglelist':  An array of triangle corners.  The first triangle's     */
-/*    first corner is at index [0], followed by its other two corners in     */
-/*    counterclockwise order, followed by any other nodes if the triangle    */
-/*    represents a nonlinear element.  Each triangle occupies                */
-/*    `numberofcorners' ints.                                                */
-/*  `triangleattributelist':  An array of triangle attributes.  Each         */
-/*    triangle's attributes occupy `numberoftriangleattributes' REALs.       */
-/*  `trianglearealist':  An array of triangle area constraints; one REAL per */
-/*    triangle.  Input only.                                                 */
-/*  `neighborlist':  An array of triangle neighbors; three ints per          */
-/*    triangle.  Output only.                                                */
-/*                                                                           */
-/*  `segmentlist':  An array of segment endpoints.  The first segment's      */
-/*    endpoints are at indices [0] and [1], followed by the remaining        */
-/*    segments.  Two ints per segment.                                       */
-/*  `segmentmarkerlist':  An array of segment markers; one int per segment.  */
-/*                                                                           */
-/*  `holelist':  An array of holes.  The first hole's x and y coordinates    */
-/*    are at indices [0] and [1], followed by the remaining holes.  Two      */
-/*    REALs per hole.  Input only, although the pointer is copied to the     */
-/*    output structure for your convenience.                                 */
-/*                                                                           */
-/*  `regionlist':  An array of regional attributes and area constraints.     */
-/*    The first constraint's x and y coordinates are at indices [0] and [1], */
-/*    followed by the regional attribute at index [2], followed by the       */
-/*    maximum area at index [3], followed by the remaining area constraints. */
-/*    Four REALs per area constraint.  Note that each regional attribute is  */
-/*    used only if you select the `A' switch, and each area constraint is    */
-/*    used only if you select the `a' switch (with no number following), but */
-/*    omitting one of these switches does not change the memory layout.      */
-/*    Input only, although the pointer is copied to the output structure for */
-/*    your convenience.                                                      */
-/*                                                                           */
-/*  `edgelist':  An array of edge endpoints.  The first edge's endpoints are */
-/*    at indices [0] and [1], followed by the remaining edges.  Two ints per */
-/*    edge.  Output only.                                                    */
-/*  `edgemarkerlist':  An array of edge markers; one int per edge.  Output   */
-/*    only.                                                                  */
-/*  `normlist':  An array of normal vectors, used for infinite rays in       */
-/*    Voronoi diagrams.  The first normal vector's x and y magnitudes are    */
-/*    at indices [0] and [1], followed by the remaining vectors.  For each   */
-/*    finite edge in a Voronoi diagram, the normal vector written is the     */
-/*    zero vector.  Two REALs per edge.  Output only.                        */
-/*                                                                           */
-/*                                                                           */
-/*  Any input fields that Triangle will examine must be initialized.         */
-/*  Furthermore, for each output array that Triangle will write to, you      */
-/*  must either provide space by setting the appropriate pointer to point    */
-/*  to the space you want the data written to, or you must initialize the    */
-/*  pointer to NULL, which tells Triangle to allocate space for the results. */
-/*  The latter option is preferable, because Triangle always knows exactly   */
-/*  how much space to allocate.  The former option is provided mainly for    */
-/*  people who need to call Triangle from Fortran code, though it also makes */
-/*  possible some nasty space-saving tricks, like writing the output to the  */
-/*  same arrays as the input.                                                */
-/*                                                                           */
-/*  Triangle will not free() any input or output arrays, including those it  */
-/*  allocates itself; that's up to you.  You should free arrays allocated by */
-/*  Triangle by calling the trifree() procedure defined below.  (By default, */
-/*  trifree() just calls the standard free() library procedure, but          */
-/*  applications that call triangulate() may replace trimalloc() and         */
-/*  trifree() in triangle.c to use specialized memory allocators.)           */
-/*                                                                           */
-/*  Here's a guide to help you decide which fields you must initialize       */
-/*  before you call triangulate().                                           */
-/*                                                                           */
-/*  `in':                                                                    */
-/*                                                                           */
-/*    - `pointlist' must always point to a list of points; `numberofpoints'  */
-/*      and `numberofpointattributes' must be properly set.                  */
-/*      `pointmarkerlist' must either be set to NULL (in which case all      */
-/*      markers default to zero), or must point to a list of markers.  If    */
-/*      `numberofpointattributes' is not zero, `pointattributelist' must     */
-/*      point to a list of point attributes.                                 */
-/*    - If the `r' switch is used, `trianglelist' must point to a list of    */
-/*      triangles, and `numberoftriangles', `numberofcorners', and           */
-/*      `numberoftriangleattributes' must be properly set.  If               */
-/*      `numberoftriangleattributes' is not zero, `triangleattributelist'    */
-/*      must point to a list of triangle attributes.  If the `a' switch is   */
-/*      used (with no number following), `trianglearealist' must point to a  */
-/*      list of triangle area constraints.  `neighborlist' may be ignored.   */
-/*    - If the `p' switch is used, `segmentlist' must point to a list of     */
-/*      segments, `numberofsegments' must be properly set, and               */
-/*      `segmentmarkerlist' must either be set to NULL (in which case all    */
-/*      markers default to zero), or must point to a list of markers.        */
-/*    - If the `p' switch is used without the `r' switch, then               */
-/*      `numberofholes' and `numberofregions' must be properly set.  If      */
-/*      `numberofholes' is not zero, `holelist' must point to a list of      */
-/*      holes.  If `numberofregions' is not zero, `regionlist' must point to */
-/*      a list of region constraints.                                        */
-/*    - If the `p' switch is used, `holelist', `numberofholes',              */
-/*      `regionlist', and `numberofregions' is copied to `out'.  (You can    */
-/*      nonetheless get away with not initializing them if the `r' switch is */
-/*      used.)                                                               */
-/*    - `edgelist', `edgemarkerlist', `normlist', and `numberofedges' may be */
-/*      ignored.                                                             */
-/*                                                                           */
-/*  `out':                                                                   */
-/*                                                                           */
-/*    - `pointlist' must be initialized (NULL or pointing to memory) unless  */
-/*      the `N' switch is used.  `pointmarkerlist' must be initialized       */
-/*      unless the `N' or `B' switch is used.  If `N' is not used and        */
-/*      `in->numberofpointattributes' is not zero, `pointattributelist' must */
-/*      be initialized.                                                      */
-/*    - `trianglelist' must be initialized unless the `E' switch is used.    */
-/*      `neighborlist' must be initialized if the `n' switch is used.  If    */
-/*      the `E' switch is not used and (`in->numberofelementattributes' is   */
-/*      not zero or the `A' switch is used), `elementattributelist' must be  */
-/*      initialized.  `trianglearealist' may be ignored.                     */
-/*    - `segmentlist' must be initialized if the `p' or `c' switch is used,  */
-/*      and the `P' switch is not used.  `segmentmarkerlist' must also be    */
-/*      initialized under these circumstances unless the `B' switch is used. */
-/*    - `edgelist' must be initialized if the `e' switch is used.            */
-/*      `edgemarkerlist' must be initialized if the `e' switch is used and   */
-/*      the `B' switch is not.                                               */
-/*    - `holelist', `regionlist', `normlist', and all scalars may be ignored.*/
-/*                                                                           */
-/*  `vorout' (only needed if `v' switch is used):                            */
-/*                                                                           */
-/*    - `pointlist' must be initialized.  If `in->numberofpointattributes'   */
-/*      is not zero, `pointattributelist' must be initialized.               */
-/*      `pointmarkerlist' may be ignored.                                    */
-/*    - `edgelist' and `normlist' must both be initialized.                  */
-/*      `edgemarkerlist' may be ignored.                                     */
-/*    - Everything else may be ignored.                                      */
-/*                                                                           */
-/*  After a call to triangulate(), the valid fields of `out' and `vorout'    */
-/*  will depend, in an obvious way, on the choice of switches used.  Note    */
-/*  that when the `p' switch is used, the pointers `holelist' and            */
-/*  `regionlist' are copied from `in' to `out', but no new space is          */
-/*  allocated; be careful that you don't free() the same array twice.  On    */
-/*  the other hand, Triangle will never copy the `pointlist' pointer (or any */
-/*  others); new space is allocated for `out->pointlist', or if the `N'      */
-/*  switch is used, `out->pointlist' remains uninitialized.                  */
-/*                                                                           */
-/*  All of the meaningful `numberof' fields will be properly set; for        */
-/*  instance, `numberofedges' will represent the number of edges in the      */
-/*  triangulation whether or not the edges were written.  If segments are    */
-/*  not used, `numberofsegments' will indicate the number of boundary edges. */
-/*                                                                           */
-/*****************************************************************************/
-
-#define REAL	double
-
-struct triangulateio {
-  REAL *pointlist;                                               /* In / out */
-  REAL *pointattributelist;                                      /* In / out */
-  int *pointmarkerlist;                                          /* In / out */
-  int numberofpoints;                                            /* In / out */
-  int numberofpointattributes;                                   /* In / out */
-
-  int *trianglelist;                                             /* In / out */
-  REAL *triangleattributelist;                                   /* In / out */
-  REAL *trianglearealist;                                         /* In only */
-  int *neighborlist;                                             /* Out only */
-  int numberoftriangles;                                         /* In / out */
-  int numberofcorners;                                           /* In / out */
-  int numberoftriangleattributes;                                /* In / out */
-
-  int *segmentlist;                                              /* In / out */
-  int *segmentmarkerlist;                                        /* In / out */
-  int numberofsegments;                                          /* In / out */
-
-  REAL *holelist;                        /* In / pointer to array copied out */
-  int numberofholes;                                      /* In / copied out */
-
-  REAL *regionlist;                      /* In / pointer to array copied out */
-  int numberofregions;                                    /* In / copied out */
-
-  int *edgelist;                                                 /* Out only */
-  int *edgemarkerlist;            /* Not used with Voronoi diagram; out only */
-  REAL *normlist;                /* Used only with Voronoi diagram; out only */
-  int numberofedges;                                             /* Out only */
-};
-
-#define ANSI_DECLARATORS
-
-#ifdef ANSI_DECLARATORS
-void triangulate(char *, struct triangulateio *, struct triangulateio *,
-                 struct triangulateio *);
-void trifree(void *memptr);
-#else /* not ANSI_DECLARATORS */
-void triangulate();
-void trifree();
-#endif /* not ANSI_DECLARATORS */
diff --git a/src/modules/grid/grid_tools/Grid_Cut.cpp b/src/modules/grid/grid_tools/Grid_Cut.cpp
index 5d6ea7a..1aabd2b 100644
--- a/src/modules/grid/grid_tools/Grid_Cut.cpp
+++ b/src/modules/grid/grid_tools/Grid_Cut.cpp
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: Grid_Cut.cpp 2598 2015-09-23 14:12:34Z oconrad $
+ * Version $Id: Grid_Cut.cpp 2697 2015-11-24 13:43:39Z oconrad $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -90,31 +90,35 @@ void Fit_Extent(CSG_Parameters *pParameters, CSG_Parameter *pParameter, CSG_Grid
 {
 	if( pSystem && pSystem->is_Valid() )
 	{
-		CSG_Grid_System	s(Fit_Extent(*pSystem, CSG_Rect(
+		CSG_Grid_System	System(Fit_Extent(*pSystem, CSG_Rect(
 			pParameters->Get_Parameter("XMIN")->asDouble(),
 			pParameters->Get_Parameter("YMIN")->asDouble(),
 			pParameters->Get_Parameter("XMAX")->asDouble(),
 			pParameters->Get_Parameter("YMAX")->asDouble()
 		)));
 
-		if( !SG_STR_CMP(pParameter->Get_Identifier(), SG_T("NX")) )
+		if( !SG_STR_CMP(pParameter->Get_Identifier(), "NX") )
 		{
-			s.Assign(s.Get_Cellsize(), s.Get_XMin(), s.Get_YMin(), pParameters->Get_Parameter("NX")->asInt(), s.Get_NY());
+			System.Assign(System.Get_Cellsize(), System.Get_XMin(), System.Get_YMin(),
+				pParameters->Get_Parameter("NX")->asInt(), System.Get_NY()
+			);
 		}
 
-		if( !SG_STR_CMP(pParameter->Get_Identifier(), SG_T("NY")) )
+		if( !SG_STR_CMP(pParameter->Get_Identifier(), "NY") )
 		{
-			s.Assign(s.Get_Cellsize(), s.Get_XMin(), s.Get_YMin(), s.Get_NX(), pParameters->Get_Parameter("NY")->asInt());
+			System.Assign(System.Get_Cellsize(), System.Get_XMin(), System.Get_YMin(),
+				System.Get_NX(), pParameters->Get_Parameter("NY")->asInt()
+			);
 		}
 
-		if( s.is_Valid() )
+		if( System.is_Valid() )
 		{
-			pParameters->Get_Parameter("XMIN")->Set_Value(s.Get_XMin());
-			pParameters->Get_Parameter("XMAX")->Set_Value(s.Get_XMax());
-			pParameters->Get_Parameter("YMIN")->Set_Value(s.Get_YMin());
-			pParameters->Get_Parameter("YMAX")->Set_Value(s.Get_YMax());
-			pParameters->Get_Parameter("NX"  )->Set_Value(s.Get_NX  ());
-			pParameters->Get_Parameter("NY"  )->Set_Value(s.Get_NY  ());
+			pParameters->Get_Parameter("XMIN")->Set_Value(System.Get_XMin());
+			pParameters->Get_Parameter("XMAX")->Set_Value(System.Get_XMax());
+			pParameters->Get_Parameter("YMIN")->Set_Value(System.Get_YMin());
+			pParameters->Get_Parameter("YMAX")->Set_Value(System.Get_YMax());
+			pParameters->Get_Parameter("NX"  )->Set_Value(System.Get_NX  ());
+			pParameters->Get_Parameter("NY"  )->Set_Value(System.Get_NY  ());
 		}
 	}
 }
@@ -132,7 +136,7 @@ CGrid_Clip_Interactive::CGrid_Clip_Interactive(void)
 	//-----------------------------------------------------
 	Set_Name		(_TL("Clip Grids"));
 
-	Set_Author		(SG_T("O.Conrad (c) 2003"));
+	Set_Author		("O.Conrad (c) 2003");
 
 	Set_Description	(_TW(
 		"Clip selected grids to interactively defined extent."
@@ -140,17 +144,23 @@ CGrid_Clip_Interactive::CGrid_Clip_Interactive(void)
 
 	//-----------------------------------------------------
 	Parameters.Add_Grid_List(
-		NULL	, "GRIDS"	, _TL("Grids"),
+		NULL	, "GRIDS"		, _TL("Grids"),
 		_TL(""),
 		PARAMETER_INPUT
 	);
 
 	Parameters.Add_Grid_List(
-		NULL	, "CLIPPED"	, _TL("Clipped Grids"),
+		NULL	, "CLIPPED"		, _TL("Clipped Grids"),
 		_TL(""),
 		PARAMETER_OUTPUT, false
 	);
 
+	Parameters.Add_Value(
+		NULL	, "RUN_ONCE"	, _TL("Run Once"),
+		_TL(""),
+		PARAMETER_TYPE_Bool, true
+	);
+
 	//-----------------------------------------------------
 	CSG_Parameters	*pParameters	= Add_Parameters("EXTENT", _TL("Extent"), _TL(""));
 
@@ -170,12 +180,12 @@ CGrid_Clip_Interactive::CGrid_Clip_Interactive(void)
 //---------------------------------------------------------
 int CGrid_Clip_Interactive::On_Parameter_Changed(CSG_Parameters *pParameters, CSG_Parameter *pParameter)
 {
-	if( is_Executing() && !SG_STR_CMP(pParameters->Get_Identifier(), SG_T("EXTENT")) )
+	if( is_Executing() && !SG_STR_CMP(pParameters->Get_Identifier(), "EXTENT") )
 	{
 		Fit_Extent(pParameters, pParameter, Get_System());
 	}
 
-	return( 1 );
+	return( CSG_Module_Grid::On_Parameter_Changed(pParameters, pParameter) );
 }
 
 
@@ -186,7 +196,7 @@ int CGrid_Clip_Interactive::On_Parameter_Changed(CSG_Parameters *pParameters, CS
 //---------------------------------------------------------
 bool CGrid_Clip_Interactive::On_Execute(void)
 {
-	m_bDown		= false;
+	m_bDown	= false;
 
 	return( true );
 }
@@ -197,15 +207,6 @@ bool CGrid_Clip_Interactive::On_Execute(void)
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
-TSG_Point CGrid_Clip_Interactive::Fit_to_Grid(TSG_Point Point)
-{
-	Point.x	= Get_XMin() + Get_Cellsize() * (int)(0.5 + (Point.x - Get_XMin()) / Get_Cellsize());
-	Point.y	= Get_YMin() + Get_Cellsize() * (int)(0.5 + (Point.y - Get_YMin()) / Get_Cellsize());
-
-	return( Point );
-}
-
-//---------------------------------------------------------
 bool CGrid_Clip_Interactive::On_Execute_Position(CSG_Point ptWorld, TSG_Module_Interactive_Mode Mode)
 {
 	switch( Mode )
@@ -215,67 +216,81 @@ bool CGrid_Clip_Interactive::On_Execute_Position(CSG_Point ptWorld, TSG_Module_I
 		if( m_bDown == false )
 		{
 			m_bDown		= true;
-			m_ptDown	= Fit_to_Grid(ptWorld);
+			m_ptDown	= ptWorld;
 		}
 
-		return( true );
+		break;
 
 	//-----------------------------------------------------
 	case MODULE_INTERACTIVE_LUP:
 		if( m_bDown == true )
 		{
 			m_bDown		= false;
-			ptWorld		= Fit_to_Grid(ptWorld);
+			ptWorld		= ptWorld;
 
-			//---------------------------------------------
 			CSG_Grid_System	System	= Fit_Extent(*Get_System(), CSG_Rect(
 				m_ptDown.Get_X(), m_ptDown.Get_Y(), ptWorld.Get_X(), ptWorld.Get_Y()
 			));
 
 			CSG_Parameters	*pParameters	= Get_Parameters("EXTENT");
 
+			pParameters->Set_Callback(false);
 			pParameters->Get_Parameter("XMIN")->Set_Value(System.Get_XMin());
 			pParameters->Get_Parameter("XMAX")->Set_Value(System.Get_XMax());
 			pParameters->Get_Parameter("YMIN")->Set_Value(System.Get_YMin());
 			pParameters->Get_Parameter("YMAX")->Set_Value(System.Get_YMax());
 			pParameters->Get_Parameter("NX"  )->Set_Value(System.Get_NX  ());
 			pParameters->Get_Parameter("NY"  )->Set_Value(System.Get_NY  ());
+			pParameters->Set_Callback(true);
 
-			if( Dlg_Parameters(pParameters, _TL("Clip to Extent")) )
+			if( !Dlg_Parameters(pParameters, _TL("Clip to Extent")) )
 			{
-				System	= Fit_Extent(*Get_System(), CSG_Rect(
-					pParameters->Get_Parameter("XMIN")->asDouble(),
-					pParameters->Get_Parameter("YMIN")->asDouble(),
-					pParameters->Get_Parameter("XMAX")->asDouble(),
-					pParameters->Get_Parameter("YMAX")->asDouble()
-				));
+				return( false );
+			}
 
-				//-----------------------------------------
-				if( System.is_Valid() )
-				{
-					CSG_Parameter_Grid_List	*pInput		= Parameters("GRIDS"  )->asGridList();
-					CSG_Parameter_Grid_List	*pOutput	= Parameters("CLIPPED")->asGridList();
+			System	= Fit_Extent(*Get_System(), CSG_Rect(
+				pParameters->Get_Parameter("XMIN")->asDouble(),
+				pParameters->Get_Parameter("YMIN")->asDouble(),
+				pParameters->Get_Parameter("XMAX")->asDouble(),
+				pParameters->Get_Parameter("YMAX")->asDouble()
+			));
 
-					for(int i=0; i<pInput->Get_Count(); i++)
-					{
-						CSG_Grid	*pClip	= SG_Create_Grid(System, pInput->asGrid(i)->Get_Type());
+			if( !System.is_Valid() )
+			{
+				return( false );
+			}
 
-						pClip->Assign  (pInput->asGrid(i), GRID_INTERPOLATION_NearestNeighbour);
-						pClip->Set_Name(pInput->asGrid(i)->Get_Name());
+			//---------------------------------------------
+			CSG_Parameter_Grid_List	*pInput		= Parameters("GRIDS"  )->asGridList();
+			CSG_Parameter_Grid_List	*pOutput	= Parameters("CLIPPED")->asGridList();
 
-						pOutput->Add_Item(pClip);
-						DataObject_Add   (pClip);
-					}
-				}
+			for(int i=0; i<pInput->Get_Count(); i++)
+			{
+				CSG_Grid	*pClip	= SG_Create_Grid(System, pInput->asGrid(i)->Get_Type());
+
+				pClip->Set_Name              (pInput->asGrid(i)->Get_Name());
+				pClip->Set_Description       (pInput->asGrid(i)->Get_Description());
+				pClip->Set_Unit              (pInput->asGrid(i)->Get_Unit());
+				pClip->Set_NoData_Value_Range(pInput->asGrid(i)->Get_NoData_Value(), pInput->asGrid(i)->Get_NoData_hiValue());
+				pClip->Set_Scaling           (pInput->asGrid(i)->Get_Scaling(), pInput->asGrid(i)->Get_Offset());
+				pClip->Assign                (pInput->asGrid(i), GRID_INTERPOLATION_NearestNeighbour);
+
+				pOutput->Add_Item(pClip);
+				DataObject_Add   (pClip);
+			}
+
+			if( Parameters("RUN_ONCE")->asBool() )
+			{
+				Stop_Execution(false);
 			}
 		}
 
-		return( true );
+		break;
 
 	//-----------------------------------------------------
 	}
 
-	return( false );
+	return( true );
 }
 
 
@@ -293,7 +308,7 @@ CGrid_Clip::CGrid_Clip(void)
 	//-----------------------------------------------------
 	Set_Name		(_TL("Clip Grids"));
 
-	Set_Author		(SG_T("O.Conrad (c) 2003"));
+	Set_Author		("O.Conrad (c) 2003");
 
 	Set_Description	(_TW(
 		"Clip selected grids to specified extent."
@@ -316,7 +331,7 @@ CGrid_Clip::CGrid_Clip(void)
 	pNode	= Parameters.Add_Choice(
 		NULL	, "EXTENT"		, _TL("Extent"),
 		_TL(""),
-		CSG_String::Format(SG_T("%s|%s|%s|%s|"),
+		CSG_String::Format("%s|%s|%s|%s|",
 			_TL("user defined"),
 			_TL("grid system"),
 			_TL("shapes extent"),
@@ -464,8 +479,12 @@ bool CGrid_Clip::On_Execute(void)
 	{
 		CSG_Grid	*pClip	= SG_Create_Grid(System, pInput->asGrid(i)->Get_Type());
 
-		pClip->Assign  (pInput->asGrid(i), GRID_INTERPOLATION_NearestNeighbour);
-		pClip->Set_Name(pInput->asGrid(i)->Get_Name());
+		pClip->Set_Name              (pInput->asGrid(i)->Get_Name());
+		pClip->Set_Description       (pInput->asGrid(i)->Get_Description());
+		pClip->Set_Unit              (pInput->asGrid(i)->Get_Unit());
+		pClip->Set_NoData_Value_Range(pInput->asGrid(i)->Get_NoData_Value(), pInput->asGrid(i)->Get_NoData_hiValue());
+		pClip->Set_Scaling           (pInput->asGrid(i)->Get_Scaling(), pInput->asGrid(i)->Get_Offset());
+		pClip->Assign                (pInput->asGrid(i), GRID_INTERPOLATION_NearestNeighbour);
 
 		if( Mask.is_Valid() ) // && Parameters("EXTENT")->asInt() == 3 )	// polygon clip
 		{
diff --git a/src/modules/grid/grid_tools/Grid_Cut.h b/src/modules/grid/grid_tools/Grid_Cut.h
index 33265c8..994ba84 100644
--- a/src/modules/grid/grid_tools/Grid_Cut.h
+++ b/src/modules/grid/grid_tools/Grid_Cut.h
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: Grid_Cut.h 2097 2014-04-11 12:50:55Z oconrad $
+ * Version $Id: Grid_Cut.h 2672 2015-11-02 15:39:37Z oconrad $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -104,9 +104,6 @@ private:
 
 	CSG_Point					m_ptDown;
 
-
-	TSG_Point					Fit_to_Grid				(TSG_Point Point);
-
 };
 
 
diff --git a/src/modules/grid/grid_tools/Grid_Merge.cpp b/src/modules/grid/grid_tools/Grid_Merge.cpp
index bdf5d25..bba7628 100644
--- a/src/modules/grid/grid_tools/Grid_Merge.cpp
+++ b/src/modules/grid/grid_tools/Grid_Merge.cpp
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: Grid_Merge.cpp 2569 2015-09-02 10:42:56Z oconrad $
+ * Version $Id: Grid_Merge.cpp 2708 2015-12-01 16:16:14Z oconrad $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -76,10 +76,10 @@ CGrid_Merge::CGrid_Merge(void)
 	//-----------------------------------------------------
 	Set_Name		(_TL("Mosaicking"));
 
-	Set_Author		(SG_T("O.Conrad (c) 2003-12"));
+	Set_Author		("O.Conrad (c) 2003-12");
 
 	Set_Description	(_TW(
-		"Mosaicking several grids to a single new one. Formerly known as 'Merge Grids'."
+		"Merges multiple grids into one single grid."
 	));
 
 	//-----------------------------------------------------
@@ -89,10 +89,16 @@ CGrid_Merge::CGrid_Merge(void)
 		PARAMETER_INPUT
 	);
 
+	Parameters.Add_String(
+		NULL	, "NAME"		, _TL("Name"),
+		_TL(""),
+		_TL("Mosaic")
+	);
+
 	Parameters.Add_Choice(
-		NULL	, "TYPE"		, _TL("Preferred data storage type"),
+		NULL	, "TYPE"		, _TL("Data Storage Type"),
 		_TL(""),
-		CSG_String::Format(SG_T("%s|%s|%s|%s|%s|%s|%s|%s|%s|"),
+		CSG_String::Format("%s|%s|%s|%s|%s|%s|%s|%s|%s|",
 			_TL("1 bit"),
 			_TL("1 byte unsigned integer"),
 			_TL("1 byte signed integer"),
@@ -108,7 +114,7 @@ CGrid_Merge::CGrid_Merge(void)
 	Parameters.Add_Choice(
 		NULL	, "INTERPOL"	, _TL("Interpolation"),
 		_TL(""),
-		CSG_String::Format(SG_T("%s|%s|%s|%s|%s|"),
+		CSG_String::Format("%s|%s|%s|%s|%s|",
 			_TL("Nearest Neighbor"),
 			_TL("Bilinear Interpolation"),
 			_TL("Inverse Distance Interpolation"),
@@ -120,7 +126,7 @@ CGrid_Merge::CGrid_Merge(void)
 	Parameters.Add_Choice(
 		NULL	, "OVERLAP"		, _TL("Overlapping Areas"),
 		_TL(""),
-		CSG_String::Format(SG_T("%s|%s|%s|%s|%s|%s|%s|"),
+		CSG_String::Format("%s|%s|%s|%s|%s|%s|%s|",
 			_TL("first"),
 			_TL("last"),
 			_TL("minimum"),
@@ -140,7 +146,7 @@ CGrid_Merge::CGrid_Merge(void)
 	Parameters.Add_Choice(
 		NULL	, "MATCH"		, _TL("Match"),
 		_TL(""),
-		CSG_String::Format(SG_T("%s|%s|"),
+		CSG_String::Format("%s|%s|",
 			_TL("none"),
 			_TL("regression"),
 			_TL("histogram match")
@@ -154,8 +160,6 @@ CGrid_Merge::CGrid_Merge(void)
 
 ///////////////////////////////////////////////////////////
 //														 //
-//														 //
-//														 //
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
@@ -172,7 +176,7 @@ int CGrid_Merge::On_Parameter_Changed(CSG_Parameters *pParameters, CSG_Parameter
 //---------------------------------------------------------
 int CGrid_Merge::On_Parameters_Enable(CSG_Parameters *pParameters, CSG_Parameter *pParameter)
 {
-	if(	!SG_STR_CMP(pParameter->Get_Identifier(), SG_T("OVERLAP")) )
+	if(	!SG_STR_CMP(pParameter->Get_Identifier(), "OVERLAP") )
 	{
 		pParameters->Get_Parameter("BLEND_DIST")->Set_Enabled(pParameter->asInt() == 5 || pParameter->asInt() == 6);
 	}
@@ -183,8 +187,6 @@ int CGrid_Merge::On_Parameters_Enable(CSG_Parameters *pParameters, CSG_Parameter
 
 ///////////////////////////////////////////////////////////
 //														 //
-//														 //
-//														 //
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
@@ -203,10 +205,6 @@ bool CGrid_Merge::On_Execute(void)
 
 		Set_Weight(pGrid);
 
-		if( i > 0 && m_Overlap == 6 )
-		{
-		}
-
 		Get_Match(i > 0 ? pGrid : NULL);
 
 		int	ax	= (int)((pGrid->Get_XMin() - m_pMosaic->Get_XMin()) / m_pMosaic->Get_Cellsize());
@@ -215,7 +213,7 @@ bool CGrid_Merge::On_Execute(void)
 		//-------------------------------------------------
 		if(	is_Aligned(pGrid) )
 		{
-			Process_Set_Text(CSG_String::Format(SG_T("[%d/%d] %s: %s"), i + 1, m_pGrids->Get_Count(), _TL("copying"), pGrid->Get_Name()));
+			Process_Set_Text(CSG_String::Format("[%d/%d] %s: %s", i + 1, m_pGrids->Get_Count(), _TL("copying"), pGrid->Get_Name()));
 
 			int	nx	= pGrid->Get_NX(); if( nx > m_pMosaic->Get_NX() - ax )	nx	= m_pMosaic->Get_NX() - ax;
 			int	ny	= pGrid->Get_NY(); if( ny > m_pMosaic->Get_NY() - ay )	ny	= m_pMosaic->Get_NY() - ay;
@@ -239,7 +237,7 @@ bool CGrid_Merge::On_Execute(void)
 		//-------------------------------------------------
 		else
 		{
-			Process_Set_Text(CSG_String::Format(SG_T("[%d/%d] %s: %s"), i + 1, m_pGrids->Get_Count(), _TL("resampling"), pGrid->Get_Name()));
+			Process_Set_Text(CSG_String::Format("[%d/%d] %s: %s", i + 1, m_pGrids->Get_Count(), _TL("resampling"), pGrid->Get_Name()));
 
 			if( ax < 0 )	ax	= 0;
 			if( ay < 0 )	ay	= 0;
@@ -290,8 +288,6 @@ bool CGrid_Merge::On_Execute(void)
 
 ///////////////////////////////////////////////////////////
 //														 //
-//														 //
-//														 //
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
@@ -310,8 +306,6 @@ bool CGrid_Merge::Initialize(void)
 		return( false );
 	}
 
-	Set_Target(Get_Parameters("TARGET"), m_pGrids);	Dlg_Parameters("TARGET");	// if called from saga_cmd
-
 	//-----------------------------------------------------
 	switch( Parameters("INTERPOL")->asInt() )
 	{
@@ -340,39 +334,53 @@ bool CGrid_Merge::Initialize(void)
 	case 8:		Type	= SG_DATATYPE_Double;	break;
 	}
 
+	if( (m_pMosaic = m_Grid_Target.Get_Grid(Type)) == NULL )
+	{
+		return( false );
+	}
+
+	if( m_pMosaic->Get_Type() != Type && !m_pMosaic->Create(m_pMosaic->Get_System(), Type) )
+	{
+		return( false );
+	}
+
+	//-----------------------------------------------------
+	m_pMosaic->Set_Name(Parameters("NAME")->asString());
+
+	m_pMosaic->Assign_NoData();
+
 	//-----------------------------------------------------
-	if( (m_pMosaic = m_Grid_Target.Get_Grid(Type)) != NULL )
+	switch( m_Overlap )
 	{
-		m_pMosaic->Set_Name(_TL("Mosaic"));
+	case 4:	// mean
+		if( !m_Weights.Create(m_pMosaic->Get_System(), m_pGrids->Get_Count() < 256 ? SG_DATATYPE_Byte : SG_DATATYPE_Word) )
+		{
+			Error_Set(_TL("could not create weights grid"));
 
-		m_pMosaic->Assign_NoData();
+			return( false );
+		}
 
-		switch( m_Overlap )
+		break;
+
+	case 6:	// feathering
+		if( !m_Weights.Create(m_pMosaic->Get_System(), SG_DATATYPE_Word) )
 		{
-		case 4:	// mean
-		case 6:	// feathering
-			{
-				if( !m_Weights.Create(m_pMosaic->Get_System(), m_Overlap == 4 && m_pGrids->Get_Count() < 256 ? SG_DATATYPE_Byte : SG_DATATYPE_Word) )
-				{
-					Error_Set(_TL("could not create weights grid"));
+			Error_Set(_TL("could not create weights grid"));
 
-					return( false );
-				}
-			}
-			break;
+			return( false );
 		}
 
-		return( true );
+		m_Weights.Set_Scaling(m_pMosaic->Get_Cellsize());
+
+		break;
 	}
 
-	return( false );
+	return( true );
 }
 
 
 ///////////////////////////////////////////////////////////
 //														 //
-//														 //
-//														 //
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
@@ -500,19 +508,6 @@ inline void CGrid_Merge::Set_Value(int x, int y, double Value, double Weight)
 			}
 		}
 		break;
-
-	case 7:	// feathering
-		if( m_pMosaic->is_NoData(x, y) )
-		{
-			m_pMosaic->Set_Value(x, y, Weight * Value);
-			m_Weights .Set_Value(x, y, Weight);
-		}
-		else
-		{
-			m_pMosaic->Add_Value(x, y, Weight * Value);
-			m_Weights .Add_Value(x, y, Weight);
-		}
-		break;
 	}
 }
 
@@ -542,8 +537,6 @@ inline void CGrid_Merge::Set_Value(int x, int y, CSG_Grid *pGrid, double px, dou
 
 ///////////////////////////////////////////////////////////
 //														 //
-//														 //
-//														 //
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
@@ -656,8 +649,6 @@ bool CGrid_Merge::Set_Weight(CSG_Grid *pGrid)
 
 ///////////////////////////////////////////////////////////
 //														 //
-//														 //
-//														 //
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
@@ -665,7 +656,7 @@ void CGrid_Merge::Get_Match(CSG_Grid *pGrid)
 {
 	if( pGrid && Parameters("MATCH")->asInt() )
 	{
-		Process_Set_Text(CSG_String::Format(SG_T("%s: %s"), _TL("matching histogram"), pGrid->Get_Name()));
+		Process_Set_Text(CSG_String::Format("%s: %s", _TL("matching histogram"), pGrid->Get_Name()));
 
 		int	ax	= (int)((pGrid->Get_XMin() - m_pMosaic->Get_XMin()) / m_pMosaic->Get_Cellsize());	if( ax < 0 )	ax	= 0;
 		int	ay	= (int)((pGrid->Get_YMin() - m_pMosaic->Get_YMin()) / m_pMosaic->Get_Cellsize());	if( ay < 0 )	ay	= 0;
diff --git a/src/modules/imagery/imagery_opencv/opencv.cpp b/src/modules/imagery/imagery_opencv/opencv.cpp
index 7d0e10b..dfea7a6 100644
--- a/src/modules/imagery/imagery_opencv/opencv.cpp
+++ b/src/modules/imagery/imagery_opencv/opencv.cpp
@@ -260,7 +260,7 @@ bool	Copy_Grid_To_CVImage(CSG_Grid *pGrid, IplImage *pImage, bool bCheckSize)
 
 			for(int x=0; x<nx; x++)
 			{
-				switch( pImage->depth )
+				switch( (unsigned int)(pImage->depth) )
 				{
 				case IPL_DEPTH_8U:	Row.data.ptr[x]	= pGrid->asByte  (x, y);	break;
 				case IPL_DEPTH_8S:	Row.data.ptr[x]	= pGrid->asChar  (x, y);	break;
@@ -296,7 +296,7 @@ bool	Copy_CVImage_To_Grid(CSG_Grid *pGrid, IplImage *pImage, bool bCheckSize)
 
 			for(int x=0; x<nx; x++)
 			{
-				switch( pImage->depth )
+				switch( (unsigned int)(pImage->depth) )
 				{
 				case IPL_DEPTH_8U:	pGrid->Set_Value(x, y, Row.data.ptr[x]);	break;
 				case IPL_DEPTH_8S:	pGrid->Set_Value(x, y, ((char *)Row.data.ptr)[x]);	break;
diff --git a/src/modules/imagery/imagery_svm/svm.cpp b/src/modules/imagery/imagery_svm/svm.cpp
deleted file mode 100644
index 1ecb291..0000000
--- a/src/modules/imagery/imagery_svm/svm.cpp
+++ /dev/null
@@ -1,3089 +0,0 @@
-#include <math.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <ctype.h>
-#include <float.h>
-#include <string.h>
-#include <stdarg.h>
-#include <limits.h>
-#include "svm.h"
-int libsvm_version = LIBSVM_VERSION;
-typedef float Qfloat;
-typedef signed char schar;
-#ifndef min
-template <class T> static inline T min(T x,T y) { return (x<y)?x:y; }
-#endif
-#ifndef max
-template <class T> static inline T max(T x,T y) { return (x>y)?x:y; }
-#endif
-template <class T> static inline void swap(T& x, T& y) { T t=x; x=y; y=t; }
-template <class S, class T> static inline void clone(T*& dst, S* src, int n)
-{
-	dst = new T[n];
-	memcpy((void *)dst,(void *)src,sizeof(T)*n);
-}
-static inline double powi(double base, int times)
-{
-	double tmp = base, ret = 1.0;
-
-	for(int t=times; t>0; t/=2)
-	{
-		if(t%2==1) ret*=tmp;
-		tmp = tmp * tmp;
-	}
-	return ret;
-}
-#define INF HUGE_VAL
-#define TAU 1e-12
-#define Malloc(type,n) (type *)malloc((n)*sizeof(type))
-
-static void print_string_stdout(const char *s)
-{
-	fputs(s,stdout);
-	fflush(stdout);
-}
-static void (*svm_print_string) (const char *) = &print_string_stdout;
-#if 1
-static void info(const char *fmt,...)
-{
-	char buf[BUFSIZ];
-	va_list ap;
-	va_start(ap,fmt);
-	vsprintf(buf,fmt,ap);
-	va_end(ap);
-	(*svm_print_string)(buf);
-}
-#else
-static void info(const char *fmt,...) {}
-#endif
-
-//
-// Kernel Cache
-//
-// l is the number of total data items
-// size is the cache size limit in bytes
-//
-class Cache
-{
-public:
-	Cache(int l,long int size);
-	~Cache();
-
-	// request data [0,len)
-	// return some position p where [p,len) need to be filled
-	// (p >= len if nothing needs to be filled)
-	int get_data(const int index, Qfloat **data, int len);
-	void swap_index(int i, int j);	
-private:
-	int l;
-	long int size;
-	struct head_t
-	{
-		head_t *prev, *next;	// a circular list
-		Qfloat *data;
-		int len;		// data[0,len) is cached in this entry
-	};
-
-	head_t *head;
-	head_t lru_head;
-	void lru_delete(head_t *h);
-	void lru_insert(head_t *h);
-};
-
-Cache::Cache(int l_,long int size_):l(l_),size(size_)
-{
-	head = (head_t *)calloc(l,sizeof(head_t));	// initialized to 0
-	size /= sizeof(Qfloat);
-	size -= l * sizeof(head_t) / sizeof(Qfloat);
-	size = max(size, 2 * (long int) l);	// cache must be large enough for two columns
-	lru_head.next = lru_head.prev = &lru_head;
-}
-
-Cache::~Cache()
-{
-	for(head_t *h = lru_head.next; h != &lru_head; h=h->next)
-		free(h->data);
-	free(head);
-}
-
-void Cache::lru_delete(head_t *h)
-{
-	// delete from current location
-	h->prev->next = h->next;
-	h->next->prev = h->prev;
-}
-
-void Cache::lru_insert(head_t *h)
-{
-	// insert to last position
-	h->next = &lru_head;
-	h->prev = lru_head.prev;
-	h->prev->next = h;
-	h->next->prev = h;
-}
-
-int Cache::get_data(const int index, Qfloat **data, int len)
-{
-	head_t *h = &head[index];
-	if(h->len) lru_delete(h);
-	int more = len - h->len;
-
-	if(more > 0)
-	{
-		// free old space
-		while(size < more)
-		{
-			head_t *old = lru_head.next;
-			lru_delete(old);
-			free(old->data);
-			size += old->len;
-			old->data = 0;
-			old->len = 0;
-		}
-
-		// allocate new space
-		h->data = (Qfloat *)realloc(h->data,sizeof(Qfloat)*len);
-		size -= more;
-		swap(h->len,len);
-	}
-
-	lru_insert(h);
-	*data = h->data;
-	return len;
-}
-
-void Cache::swap_index(int i, int j)
-{
-	if(i==j) return;
-
-	if(head[i].len) lru_delete(&head[i]);
-	if(head[j].len) lru_delete(&head[j]);
-	swap(head[i].data,head[j].data);
-	swap(head[i].len,head[j].len);
-	if(head[i].len) lru_insert(&head[i]);
-	if(head[j].len) lru_insert(&head[j]);
-
-	if(i>j) swap(i,j);
-	for(head_t *h = lru_head.next; h!=&lru_head; h=h->next)
-	{
-		if(h->len > i)
-		{
-			if(h->len > j)
-				swap(h->data[i],h->data[j]);
-			else
-			{
-				// give up
-				lru_delete(h);
-				free(h->data);
-				size += h->len;
-				h->data = 0;
-				h->len = 0;
-			}
-		}
-	}
-}
-
-//
-// Kernel evaluation
-//
-// the static method k_function is for doing single kernel evaluation
-// the constructor of Kernel prepares to calculate the l*l kernel matrix
-// the member function get_Q is for getting one column from the Q Matrix
-//
-class QMatrix {
-public:
-	virtual Qfloat *get_Q(int column, int len) const = 0;
-	virtual double *get_QD() const = 0;
-	virtual void swap_index(int i, int j) const = 0;
-	virtual ~QMatrix() {}
-};
-
-class Kernel: public QMatrix {
-public:
-	Kernel(int l, svm_node * const * x, const svm_parameter& param);
-	virtual ~Kernel();
-
-	static double k_function(const svm_node *x, const svm_node *y,
-				 const svm_parameter& param);
-	virtual Qfloat *get_Q(int column, int len) const = 0;
-	virtual double *get_QD() const = 0;
-	virtual void swap_index(int i, int j) const	// no so const...
-	{
-		swap(x[i],x[j]);
-		if(x_square) swap(x_square[i],x_square[j]);
-	}
-protected:
-
-	double (Kernel::*kernel_function)(int i, int j) const;
-
-private:
-	const svm_node **x;
-	double *x_square;
-
-	// svm_parameter
-	const int kernel_type;
-	const int degree;
-	const double gamma;
-	const double coef0;
-
-	static double dot(const svm_node *px, const svm_node *py);
-	double kernel_linear(int i, int j) const
-	{
-		return dot(x[i],x[j]);
-	}
-	double kernel_poly(int i, int j) const
-	{
-		return powi(gamma*dot(x[i],x[j])+coef0,degree);
-	}
-	double kernel_rbf(int i, int j) const
-	{
-		return exp(-gamma*(x_square[i]+x_square[j]-2*dot(x[i],x[j])));
-	}
-	double kernel_sigmoid(int i, int j) const
-	{
-		return tanh(gamma*dot(x[i],x[j])+coef0);
-	}
-	double kernel_precomputed(int i, int j) const
-	{
-		return x[i][(int)(x[j][0].value)].value;
-	}
-};
-
-Kernel::Kernel(int l, svm_node * const * x_, const svm_parameter& param)
-:kernel_type(param.kernel_type), degree(param.degree),
- gamma(param.gamma), coef0(param.coef0)
-{
-	switch(kernel_type)
-	{
-		case LINEAR:
-			kernel_function = &Kernel::kernel_linear;
-			break;
-		case POLY:
-			kernel_function = &Kernel::kernel_poly;
-			break;
-		case RBF:
-			kernel_function = &Kernel::kernel_rbf;
-			break;
-		case SIGMOID:
-			kernel_function = &Kernel::kernel_sigmoid;
-			break;
-		case PRECOMPUTED:
-			kernel_function = &Kernel::kernel_precomputed;
-			break;
-	}
-
-	clone(x,x_,l);
-
-	if(kernel_type == RBF)
-	{
-		x_square = new double[l];
-		for(int i=0;i<l;i++)
-			x_square[i] = dot(x[i],x[i]);
-	}
-	else
-		x_square = 0;
-}
-
-Kernel::~Kernel()
-{
-	delete[] x;
-	delete[] x_square;
-}
-
-double Kernel::dot(const svm_node *px, const svm_node *py)
-{
-	double sum = 0;
-	while(px->index != -1 && py->index != -1)
-	{
-		if(px->index == py->index)
-		{
-			sum += px->value * py->value;
-			++px;
-			++py;
-		}
-		else
-		{
-			if(px->index > py->index)
-				++py;
-			else
-				++px;
-		}			
-	}
-	return sum;
-}
-
-double Kernel::k_function(const svm_node *x, const svm_node *y,
-			  const svm_parameter& param)
-{
-	switch(param.kernel_type)
-	{
-		case LINEAR:
-			return dot(x,y);
-		case POLY:
-			return powi(param.gamma*dot(x,y)+param.coef0,param.degree);
-		case RBF:
-		{
-			double sum = 0;
-			while(x->index != -1 && y->index !=-1)
-			{
-				if(x->index == y->index)
-				{
-					double d = x->value - y->value;
-					sum += d*d;
-					++x;
-					++y;
-				}
-				else
-				{
-					if(x->index > y->index)
-					{	
-						sum += y->value * y->value;
-						++y;
-					}
-					else
-					{
-						sum += x->value * x->value;
-						++x;
-					}
-				}
-			}
-
-			while(x->index != -1)
-			{
-				sum += x->value * x->value;
-				++x;
-			}
-
-			while(y->index != -1)
-			{
-				sum += y->value * y->value;
-				++y;
-			}
-			
-			return exp(-param.gamma*sum);
-		}
-		case SIGMOID:
-			return tanh(param.gamma*dot(x,y)+param.coef0);
-		case PRECOMPUTED:  //x: test (validation), y: SV
-			return x[(int)(y->value)].value;
-		default:
-			return 0;  // Unreachable 
-	}
-}
-
-// An SMO algorithm in Fan et al., JMLR 6(2005), p. 1889--1918
-// Solves:
-//
-//	min 0.5(\alpha^T Q \alpha) + p^T \alpha
-//
-//		y^T \alpha = \delta
-//		y_i = +1 or -1
-//		0 <= alpha_i <= Cp for y_i = 1
-//		0 <= alpha_i <= Cn for y_i = -1
-//
-// Given:
-//
-//	Q, p, y, Cp, Cn, and an initial feasible point \alpha
-//	l is the size of vectors and matrices
-//	eps is the stopping tolerance
-//
-// solution will be put in \alpha, objective value will be put in obj
-//
-class Solver {
-public:
-	Solver() {};
-	virtual ~Solver() {};
-
-	struct SolutionInfo {
-		double obj;
-		double rho;
-		double upper_bound_p;
-		double upper_bound_n;
-		double r;	// for Solver_NU
-	};
-
-	void Solve(int l, const QMatrix& Q, const double *p_, const schar *y_,
-		   double *alpha_, double Cp, double Cn, double eps,
-		   SolutionInfo* si, int shrinking);
-protected:
-	int active_size;
-	schar *y;
-	double *G;		// gradient of objective function
-	enum { LOWER_BOUND, UPPER_BOUND, FREE };
-	char *alpha_status;	// LOWER_BOUND, UPPER_BOUND, FREE
-	double *alpha;
-	const QMatrix *Q;
-	const double *QD;
-	double eps;
-	double Cp,Cn;
-	double *p;
-	int *active_set;
-	double *G_bar;		// gradient, if we treat free variables as 0
-	int l;
-	bool unshrink;	// XXX
-
-	double get_C(int i)
-	{
-		return (y[i] > 0)? Cp : Cn;
-	}
-	void update_alpha_status(int i)
-	{
-		if(alpha[i] >= get_C(i))
-			alpha_status[i] = UPPER_BOUND;
-		else if(alpha[i] <= 0)
-			alpha_status[i] = LOWER_BOUND;
-		else alpha_status[i] = FREE;
-	}
-	bool is_upper_bound(int i) { return alpha_status[i] == UPPER_BOUND; }
-	bool is_lower_bound(int i) { return alpha_status[i] == LOWER_BOUND; }
-	bool is_free(int i) { return alpha_status[i] == FREE; }
-	void swap_index(int i, int j);
-	void reconstruct_gradient();
-	virtual int select_working_set(int &i, int &j);
-	virtual double calculate_rho();
-	virtual void do_shrinking();
-private:
-	bool be_shrunk(int i, double Gmax1, double Gmax2);	
-};
-
-void Solver::swap_index(int i, int j)
-{
-	Q->swap_index(i,j);
-	swap(y[i],y[j]);
-	swap(G[i],G[j]);
-	swap(alpha_status[i],alpha_status[j]);
-	swap(alpha[i],alpha[j]);
-	swap(p[i],p[j]);
-	swap(active_set[i],active_set[j]);
-	swap(G_bar[i],G_bar[j]);
-}
-
-void Solver::reconstruct_gradient()
-{
-	// reconstruct inactive elements of G from G_bar and free variables
-
-	if(active_size == l) return;
-
-	int i,j;
-	int nr_free = 0;
-
-	for(j=active_size;j<l;j++)
-		G[j] = G_bar[j] + p[j];
-
-	for(j=0;j<active_size;j++)
-		if(is_free(j))
-			nr_free++;
-
-	if(2*nr_free < active_size)
-		info("\nWARNING: using -h 0 may be faster\n");
-
-	if (nr_free*l > 2*active_size*(l-active_size))
-	{
-		for(i=active_size;i<l;i++)
-		{
-			const Qfloat *Q_i = Q->get_Q(i,active_size);
-			for(j=0;j<active_size;j++)
-				if(is_free(j))
-					G[i] += alpha[j] * Q_i[j];
-		}
-	}
-	else
-	{
-		for(i=0;i<active_size;i++)
-			if(is_free(i))
-			{
-				const Qfloat *Q_i = Q->get_Q(i,l);
-				double alpha_i = alpha[i];
-				for(j=active_size;j<l;j++)
-					G[j] += alpha_i * Q_i[j];
-			}
-	}
-}
-
-void Solver::Solve(int l, const QMatrix& Q, const double *p_, const schar *y_,
-		   double *alpha_, double Cp, double Cn, double eps,
-		   SolutionInfo* si, int shrinking)
-{
-	this->l = l;
-	this->Q = &Q;
-	QD=Q.get_QD();
-	clone(p, p_,l);
-	clone(y, y_,l);
-	clone(alpha,alpha_,l);
-	this->Cp = Cp;
-	this->Cn = Cn;
-	this->eps = eps;
-	unshrink = false;
-
-	// initialize alpha_status
-	{
-		alpha_status = new char[l];
-		for(int i=0;i<l;i++)
-			update_alpha_status(i);
-	}
-
-	// initialize active set (for shrinking)
-	{
-		active_set = new int[l];
-		for(int i=0;i<l;i++)
-			active_set[i] = i;
-		active_size = l;
-	}
-
-	// initialize gradient
-	{
-		G = new double[l];
-		G_bar = new double[l];
-		int i;
-		for(i=0;i<l;i++)
-		{
-			G[i] = p[i];
-			G_bar[i] = 0;
-		}
-		for(i=0;i<l;i++)
-			if(!is_lower_bound(i))
-			{
-				const Qfloat *Q_i = Q.get_Q(i,l);
-				double alpha_i = alpha[i];
-				int j;
-				for(j=0;j<l;j++)
-					G[j] += alpha_i*Q_i[j];
-				if(is_upper_bound(i))
-					for(j=0;j<l;j++)
-						G_bar[j] += get_C(i) * Q_i[j];
-			}
-	}
-
-	// optimization step
-
-	int iter = 0;
-	int max_iter = max(10000000, l>INT_MAX/100 ? INT_MAX : 100*l);
-	int counter = min(l,1000)+1;
-	
-	while(iter < max_iter)
-	{
-		// show progress and do shrinking
-
-		if(--counter == 0)
-		{
-			counter = min(l,1000);
-			if(shrinking) do_shrinking();
-			info(".");
-		}
-
-		int i,j;
-		if(select_working_set(i,j)!=0)
-		{
-			// reconstruct the whole gradient
-			reconstruct_gradient();
-			// reset active set size and check
-			active_size = l;
-			info("*");
-			if(select_working_set(i,j)!=0)
-				break;
-			else
-				counter = 1;	// do shrinking next iteration
-		}
-		
-		++iter;
-
-		// update alpha[i] and alpha[j], handle bounds carefully
-		
-		const Qfloat *Q_i = Q.get_Q(i,active_size);
-		const Qfloat *Q_j = Q.get_Q(j,active_size);
-
-		double C_i = get_C(i);
-		double C_j = get_C(j);
-
-		double old_alpha_i = alpha[i];
-		double old_alpha_j = alpha[j];
-
-		if(y[i]!=y[j])
-		{
-			double quad_coef = QD[i]+QD[j]+2*Q_i[j];
-			if (quad_coef <= 0)
-				quad_coef = TAU;
-			double delta = (-G[i]-G[j])/quad_coef;
-			double diff = alpha[i] - alpha[j];
-			alpha[i] += delta;
-			alpha[j] += delta;
-			
-			if(diff > 0)
-			{
-				if(alpha[j] < 0)
-				{
-					alpha[j] = 0;
-					alpha[i] = diff;
-				}
-			}
-			else
-			{
-				if(alpha[i] < 0)
-				{
-					alpha[i] = 0;
-					alpha[j] = -diff;
-				}
-			}
-			if(diff > C_i - C_j)
-			{
-				if(alpha[i] > C_i)
-				{
-					alpha[i] = C_i;
-					alpha[j] = C_i - diff;
-				}
-			}
-			else
-			{
-				if(alpha[j] > C_j)
-				{
-					alpha[j] = C_j;
-					alpha[i] = C_j + diff;
-				}
-			}
-		}
-		else
-		{
-			double quad_coef = QD[i]+QD[j]-2*Q_i[j];
-			if (quad_coef <= 0)
-				quad_coef = TAU;
-			double delta = (G[i]-G[j])/quad_coef;
-			double sum = alpha[i] + alpha[j];
-			alpha[i] -= delta;
-			alpha[j] += delta;
-
-			if(sum > C_i)
-			{
-				if(alpha[i] > C_i)
-				{
-					alpha[i] = C_i;
-					alpha[j] = sum - C_i;
-				}
-			}
-			else
-			{
-				if(alpha[j] < 0)
-				{
-					alpha[j] = 0;
-					alpha[i] = sum;
-				}
-			}
-			if(sum > C_j)
-			{
-				if(alpha[j] > C_j)
-				{
-					alpha[j] = C_j;
-					alpha[i] = sum - C_j;
-				}
-			}
-			else
-			{
-				if(alpha[i] < 0)
-				{
-					alpha[i] = 0;
-					alpha[j] = sum;
-				}
-			}
-		}
-
-		// update G
-
-		double delta_alpha_i = alpha[i] - old_alpha_i;
-		double delta_alpha_j = alpha[j] - old_alpha_j;
-		
-		for(int k=0;k<active_size;k++)
-		{
-			G[k] += Q_i[k]*delta_alpha_i + Q_j[k]*delta_alpha_j;
-		}
-
-		// update alpha_status and G_bar
-
-		{
-			bool ui = is_upper_bound(i);
-			bool uj = is_upper_bound(j);
-			update_alpha_status(i);
-			update_alpha_status(j);
-			int k;
-			if(ui != is_upper_bound(i))
-			{
-				Q_i = Q.get_Q(i,l);
-				if(ui)
-					for(k=0;k<l;k++)
-						G_bar[k] -= C_i * Q_i[k];
-				else
-					for(k=0;k<l;k++)
-						G_bar[k] += C_i * Q_i[k];
-			}
-
-			if(uj != is_upper_bound(j))
-			{
-				Q_j = Q.get_Q(j,l);
-				if(uj)
-					for(k=0;k<l;k++)
-						G_bar[k] -= C_j * Q_j[k];
-				else
-					for(k=0;k<l;k++)
-						G_bar[k] += C_j * Q_j[k];
-			}
-		}
-	}
-
-	if(iter >= max_iter)
-	{
-		if(active_size < l)
-		{
-			// reconstruct the whole gradient to calculate objective value
-			reconstruct_gradient();
-			active_size = l;
-			info("*");
-		}
-		info("\nWARNING: reaching max number of iterations");
-	}
-
-	// calculate rho
-
-	si->rho = calculate_rho();
-
-	// calculate objective value
-	{
-		double v = 0;
-		int i;
-		for(i=0;i<l;i++)
-			v += alpha[i] * (G[i] + p[i]);
-
-		si->obj = v/2;
-	}
-
-	// put back the solution
-	{
-		for(int i=0;i<l;i++)
-			alpha_[active_set[i]] = alpha[i];
-	}
-
-	// juggle everything back
-	/*{
-		for(int i=0;i<l;i++)
-			while(active_set[i] != i)
-				swap_index(i,active_set[i]);
-				// or Q.swap_index(i,active_set[i]);
-	}*/
-
-	si->upper_bound_p = Cp;
-	si->upper_bound_n = Cn;
-
-	info("\noptimization finished, #iter = %d\n",iter);
-
-	delete[] p;
-	delete[] y;
-	delete[] alpha;
-	delete[] alpha_status;
-	delete[] active_set;
-	delete[] G;
-	delete[] G_bar;
-}
-
-// return 1 if already optimal, return 0 otherwise
-int Solver::select_working_set(int &out_i, int &out_j)
-{
-	// return i,j such that
-	// i: maximizes -y_i * grad(f)_i, i in I_up(\alpha)
-	// j: minimizes the decrease of obj value
-	//    (if quadratic coefficeint <= 0, replace it with tau)
-	//    -y_j*grad(f)_j < -y_i*grad(f)_i, j in I_low(\alpha)
-	
-	double Gmax = -INF;
-	double Gmax2 = -INF;
-	int Gmax_idx = -1;
-	int Gmin_idx = -1;
-	double obj_diff_min = INF;
-
-	for(int t=0;t<active_size;t++)
-		if(y[t]==+1)	
-		{
-			if(!is_upper_bound(t))
-				if(-G[t] >= Gmax)
-				{
-					Gmax = -G[t];
-					Gmax_idx = t;
-				}
-		}
-		else
-		{
-			if(!is_lower_bound(t))
-				if(G[t] >= Gmax)
-				{
-					Gmax = G[t];
-					Gmax_idx = t;
-				}
-		}
-
-	int i = Gmax_idx;
-	const Qfloat *Q_i = NULL;
-	if(i != -1) // NULL Q_i not accessed: Gmax=-INF if i=-1
-		Q_i = Q->get_Q(i,active_size);
-
-	for(int j=0;j<active_size;j++)
-	{
-		if(y[j]==+1)
-		{
-			if (!is_lower_bound(j))
-			{
-				double grad_diff=Gmax+G[j];
-				if (G[j] >= Gmax2)
-					Gmax2 = G[j];
-				if (grad_diff > 0)
-				{
-					double obj_diff; 
-					double quad_coef = QD[i]+QD[j]-2.0*y[i]*Q_i[j];
-					if (quad_coef > 0)
-						obj_diff = -(grad_diff*grad_diff)/quad_coef;
-					else
-						obj_diff = -(grad_diff*grad_diff)/TAU;
-
-					if (obj_diff <= obj_diff_min)
-					{
-						Gmin_idx=j;
-						obj_diff_min = obj_diff;
-					}
-				}
-			}
-		}
-		else
-		{
-			if (!is_upper_bound(j))
-			{
-				double grad_diff= Gmax-G[j];
-				if (-G[j] >= Gmax2)
-					Gmax2 = -G[j];
-				if (grad_diff > 0)
-				{
-					double obj_diff; 
-					double quad_coef = QD[i]+QD[j]+2.0*y[i]*Q_i[j];
-					if (quad_coef > 0)
-						obj_diff = -(grad_diff*grad_diff)/quad_coef;
-					else
-						obj_diff = -(grad_diff*grad_diff)/TAU;
-
-					if (obj_diff <= obj_diff_min)
-					{
-						Gmin_idx=j;
-						obj_diff_min = obj_diff;
-					}
-				}
-			}
-		}
-	}
-
-	if(Gmax+Gmax2 < eps)
-		return 1;
-
-	out_i = Gmax_idx;
-	out_j = Gmin_idx;
-	return 0;
-}
-
-bool Solver::be_shrunk(int i, double Gmax1, double Gmax2)
-{
-	if(is_upper_bound(i))
-	{
-		if(y[i]==+1)
-			return(-G[i] > Gmax1);
-		else
-			return(-G[i] > Gmax2);
-	}
-	else if(is_lower_bound(i))
-	{
-		if(y[i]==+1)
-			return(G[i] > Gmax2);
-		else	
-			return(G[i] > Gmax1);
-	}
-	else
-		return(false);
-}
-
-void Solver::do_shrinking()
-{
-	int i;
-	double Gmax1 = -INF;		// max { -y_i * grad(f)_i | i in I_up(\alpha) }
-	double Gmax2 = -INF;		// max { y_i * grad(f)_i | i in I_low(\alpha) }
-
-	// find maximal violating pair first
-	for(i=0;i<active_size;i++)
-	{
-		if(y[i]==+1)	
-		{
-			if(!is_upper_bound(i))	
-			{
-				if(-G[i] >= Gmax1)
-					Gmax1 = -G[i];
-			}
-			if(!is_lower_bound(i))	
-			{
-				if(G[i] >= Gmax2)
-					Gmax2 = G[i];
-			}
-		}
-		else	
-		{
-			if(!is_upper_bound(i))	
-			{
-				if(-G[i] >= Gmax2)
-					Gmax2 = -G[i];
-			}
-			if(!is_lower_bound(i))	
-			{
-				if(G[i] >= Gmax1)
-					Gmax1 = G[i];
-			}
-		}
-	}
-
-	if(unshrink == false && Gmax1 + Gmax2 <= eps*10) 
-	{
-		unshrink = true;
-		reconstruct_gradient();
-		active_size = l;
-		info("*");
-	}
-
-	for(i=0;i<active_size;i++)
-		if (be_shrunk(i, Gmax1, Gmax2))
-		{
-			active_size--;
-			while (active_size > i)
-			{
-				if (!be_shrunk(active_size, Gmax1, Gmax2))
-				{
-					swap_index(i,active_size);
-					break;
-				}
-				active_size--;
-			}
-		}
-}
-
-double Solver::calculate_rho()
-{
-	double r;
-	int nr_free = 0;
-	double ub = INF, lb = -INF, sum_free = 0;
-	for(int i=0;i<active_size;i++)
-	{
-		double yG = y[i]*G[i];
-
-		if(is_upper_bound(i))
-		{
-			if(y[i]==-1)
-				ub = min(ub,yG);
-			else
-				lb = max(lb,yG);
-		}
-		else if(is_lower_bound(i))
-		{
-			if(y[i]==+1)
-				ub = min(ub,yG);
-			else
-				lb = max(lb,yG);
-		}
-		else
-		{
-			++nr_free;
-			sum_free += yG;
-		}
-	}
-
-	if(nr_free>0)
-		r = sum_free/nr_free;
-	else
-		r = (ub+lb)/2;
-
-	return r;
-}
-
-//
-// Solver for nu-svm classification and regression
-//
-// additional constraint: e^T \alpha = constant
-//
-class Solver_NU : public Solver
-{
-public:
-	Solver_NU() {}
-	void Solve(int l, const QMatrix& Q, const double *p, const schar *y,
-		   double *alpha, double Cp, double Cn, double eps,
-		   SolutionInfo* si, int shrinking)
-	{
-		this->si = si;
-		Solver::Solve(l,Q,p,y,alpha,Cp,Cn,eps,si,shrinking);
-	}
-private:
-	SolutionInfo *si;
-	int select_working_set(int &i, int &j);
-	double calculate_rho();
-	bool be_shrunk(int i, double Gmax1, double Gmax2, double Gmax3, double Gmax4);
-	void do_shrinking();
-};
-
-// return 1 if already optimal, return 0 otherwise
-int Solver_NU::select_working_set(int &out_i, int &out_j)
-{
-	// return i,j such that y_i = y_j and
-	// i: maximizes -y_i * grad(f)_i, i in I_up(\alpha)
-	// j: minimizes the decrease of obj value
-	//    (if quadratic coefficeint <= 0, replace it with tau)
-	//    -y_j*grad(f)_j < -y_i*grad(f)_i, j in I_low(\alpha)
-
-	double Gmaxp = -INF;
-	double Gmaxp2 = -INF;
-	int Gmaxp_idx = -1;
-
-	double Gmaxn = -INF;
-	double Gmaxn2 = -INF;
-	int Gmaxn_idx = -1;
-
-	int Gmin_idx = -1;
-	double obj_diff_min = INF;
-
-	for(int t=0;t<active_size;t++)
-		if(y[t]==+1)
-		{
-			if(!is_upper_bound(t))
-				if(-G[t] >= Gmaxp)
-				{
-					Gmaxp = -G[t];
-					Gmaxp_idx = t;
-				}
-		}
-		else
-		{
-			if(!is_lower_bound(t))
-				if(G[t] >= Gmaxn)
-				{
-					Gmaxn = G[t];
-					Gmaxn_idx = t;
-				}
-		}
-
-	int ip = Gmaxp_idx;
-	int in = Gmaxn_idx;
-	const Qfloat *Q_ip = NULL;
-	const Qfloat *Q_in = NULL;
-	if(ip != -1) // NULL Q_ip not accessed: Gmaxp=-INF if ip=-1
-		Q_ip = Q->get_Q(ip,active_size);
-	if(in != -1)
-		Q_in = Q->get_Q(in,active_size);
-
-	for(int j=0;j<active_size;j++)
-	{
-		if(y[j]==+1)
-		{
-			if (!is_lower_bound(j))	
-			{
-				double grad_diff=Gmaxp+G[j];
-				if (G[j] >= Gmaxp2)
-					Gmaxp2 = G[j];
-				if (grad_diff > 0)
-				{
-					double obj_diff; 
-					double quad_coef = QD[ip]+QD[j]-2*Q_ip[j];
-					if (quad_coef > 0)
-						obj_diff = -(grad_diff*grad_diff)/quad_coef;
-					else
-						obj_diff = -(grad_diff*grad_diff)/TAU;
-
-					if (obj_diff <= obj_diff_min)
-					{
-						Gmin_idx=j;
-						obj_diff_min = obj_diff;
-					}
-				}
-			}
-		}
-		else
-		{
-			if (!is_upper_bound(j))
-			{
-				double grad_diff=Gmaxn-G[j];
-				if (-G[j] >= Gmaxn2)
-					Gmaxn2 = -G[j];
-				if (grad_diff > 0)
-				{
-					double obj_diff; 
-					double quad_coef = QD[in]+QD[j]-2*Q_in[j];
-					if (quad_coef > 0)
-						obj_diff = -(grad_diff*grad_diff)/quad_coef;
-					else
-						obj_diff = -(grad_diff*grad_diff)/TAU;
-
-					if (obj_diff <= obj_diff_min)
-					{
-						Gmin_idx=j;
-						obj_diff_min = obj_diff;
-					}
-				}
-			}
-		}
-	}
-
-	if(max(Gmaxp+Gmaxp2,Gmaxn+Gmaxn2) < eps)
-		return 1;
-
-	if (y[Gmin_idx] == +1)
-		out_i = Gmaxp_idx;
-	else
-		out_i = Gmaxn_idx;
-	out_j = Gmin_idx;
-
-	return 0;
-}
-
-bool Solver_NU::be_shrunk(int i, double Gmax1, double Gmax2, double Gmax3, double Gmax4)
-{
-	if(is_upper_bound(i))
-	{
-		if(y[i]==+1)
-			return(-G[i] > Gmax1);
-		else	
-			return(-G[i] > Gmax4);
-	}
-	else if(is_lower_bound(i))
-	{
-		if(y[i]==+1)
-			return(G[i] > Gmax2);
-		else	
-			return(G[i] > Gmax3);
-	}
-	else
-		return(false);
-}
-
-void Solver_NU::do_shrinking()
-{
-	double Gmax1 = -INF;	// max { -y_i * grad(f)_i | y_i = +1, i in I_up(\alpha) }
-	double Gmax2 = -INF;	// max { y_i * grad(f)_i | y_i = +1, i in I_low(\alpha) }
-	double Gmax3 = -INF;	// max { -y_i * grad(f)_i | y_i = -1, i in I_up(\alpha) }
-	double Gmax4 = -INF;	// max { y_i * grad(f)_i | y_i = -1, i in I_low(\alpha) }
-
-	// find maximal violating pair first
-	int i;
-	for(i=0;i<active_size;i++)
-	{
-		if(!is_upper_bound(i))
-		{
-			if(y[i]==+1)
-			{
-				if(-G[i] > Gmax1) Gmax1 = -G[i];
-			}
-			else	if(-G[i] > Gmax4) Gmax4 = -G[i];
-		}
-		if(!is_lower_bound(i))
-		{
-			if(y[i]==+1)
-			{	
-				if(G[i] > Gmax2) Gmax2 = G[i];
-			}
-			else	if(G[i] > Gmax3) Gmax3 = G[i];
-		}
-	}
-
-	if(unshrink == false && max(Gmax1+Gmax2,Gmax3+Gmax4) <= eps*10) 
-	{
-		unshrink = true;
-		reconstruct_gradient();
-		active_size = l;
-	}
-
-	for(i=0;i<active_size;i++)
-		if (be_shrunk(i, Gmax1, Gmax2, Gmax3, Gmax4))
-		{
-			active_size--;
-			while (active_size > i)
-			{
-				if (!be_shrunk(active_size, Gmax1, Gmax2, Gmax3, Gmax4))
-				{
-					swap_index(i,active_size);
-					break;
-				}
-				active_size--;
-			}
-		}
-}
-
-double Solver_NU::calculate_rho()
-{
-	int nr_free1 = 0,nr_free2 = 0;
-	double ub1 = INF, ub2 = INF;
-	double lb1 = -INF, lb2 = -INF;
-	double sum_free1 = 0, sum_free2 = 0;
-
-	for(int i=0;i<active_size;i++)
-	{
-		if(y[i]==+1)
-		{
-			if(is_upper_bound(i))
-				lb1 = max(lb1,G[i]);
-			else if(is_lower_bound(i))
-				ub1 = min(ub1,G[i]);
-			else
-			{
-				++nr_free1;
-				sum_free1 += G[i];
-			}
-		}
-		else
-		{
-			if(is_upper_bound(i))
-				lb2 = max(lb2,G[i]);
-			else if(is_lower_bound(i))
-				ub2 = min(ub2,G[i]);
-			else
-			{
-				++nr_free2;
-				sum_free2 += G[i];
-			}
-		}
-	}
-
-	double r1,r2;
-	if(nr_free1 > 0)
-		r1 = sum_free1/nr_free1;
-	else
-		r1 = (ub1+lb1)/2;
-	
-	if(nr_free2 > 0)
-		r2 = sum_free2/nr_free2;
-	else
-		r2 = (ub2+lb2)/2;
-	
-	si->r = (r1+r2)/2;
-	return (r1-r2)/2;
-}
-
-//
-// Q matrices for various formulations
-//
-class SVC_Q: public Kernel
-{ 
-public:
-	SVC_Q(const svm_problem& prob, const svm_parameter& param, const schar *y_)
-	:Kernel(prob.l, prob.x, param)
-	{
-		clone(y,y_,prob.l);
-		cache = new Cache(prob.l,(long int)(param.cache_size*(1<<20)));
-		QD = new double[prob.l];
-		for(int i=0;i<prob.l;i++)
-			QD[i] = (this->*kernel_function)(i,i);
-	}
-	
-	Qfloat *get_Q(int i, int len) const
-	{
-		Qfloat *data;
-		int start, j;
-		if((start = cache->get_data(i,&data,len)) < len)
-		{
-			for(j=start;j<len;j++)
-				data[j] = (Qfloat)(y[i]*y[j]*(this->*kernel_function)(i,j));
-		}
-		return data;
-	}
-
-	double *get_QD() const
-	{
-		return QD;
-	}
-
-	void swap_index(int i, int j) const
-	{
-		cache->swap_index(i,j);
-		Kernel::swap_index(i,j);
-		swap(y[i],y[j]);
-		swap(QD[i],QD[j]);
-	}
-
-	~SVC_Q()
-	{
-		delete[] y;
-		delete cache;
-		delete[] QD;
-	}
-private:
-	schar *y;
-	Cache *cache;
-	double *QD;
-};
-
-class ONE_CLASS_Q: public Kernel
-{
-public:
-	ONE_CLASS_Q(const svm_problem& prob, const svm_parameter& param)
-	:Kernel(prob.l, prob.x, param)
-	{
-		cache = new Cache(prob.l,(long int)(param.cache_size*(1<<20)));
-		QD = new double[prob.l];
-		for(int i=0;i<prob.l;i++)
-			QD[i] = (this->*kernel_function)(i,i);
-	}
-	
-	Qfloat *get_Q(int i, int len) const
-	{
-		Qfloat *data;
-		int start, j;
-		if((start = cache->get_data(i,&data,len)) < len)
-		{
-			for(j=start;j<len;j++)
-				data[j] = (Qfloat)(this->*kernel_function)(i,j);
-		}
-		return data;
-	}
-
-	double *get_QD() const
-	{
-		return QD;
-	}
-
-	void swap_index(int i, int j) const
-	{
-		cache->swap_index(i,j);
-		Kernel::swap_index(i,j);
-		swap(QD[i],QD[j]);
-	}
-
-	~ONE_CLASS_Q()
-	{
-		delete cache;
-		delete[] QD;
-	}
-private:
-	Cache *cache;
-	double *QD;
-};
-
-class SVR_Q: public Kernel
-{ 
-public:
-	SVR_Q(const svm_problem& prob, const svm_parameter& param)
-	:Kernel(prob.l, prob.x, param)
-	{
-		l = prob.l;
-		cache = new Cache(l,(long int)(param.cache_size*(1<<20)));
-		QD = new double[2*l];
-		sign = new schar[2*l];
-		index = new int[2*l];
-		for(int k=0;k<l;k++)
-		{
-			sign[k] = 1;
-			sign[k+l] = -1;
-			index[k] = k;
-			index[k+l] = k;
-			QD[k] = (this->*kernel_function)(k,k);
-			QD[k+l] = QD[k];
-		}
-		buffer[0] = new Qfloat[2*l];
-		buffer[1] = new Qfloat[2*l];
-		next_buffer = 0;
-	}
-
-	void swap_index(int i, int j) const
-	{
-		swap(sign[i],sign[j]);
-		swap(index[i],index[j]);
-		swap(QD[i],QD[j]);
-	}
-	
-	Qfloat *get_Q(int i, int len) const
-	{
-		Qfloat *data;
-		int j, real_i = index[i];
-		if(cache->get_data(real_i,&data,l) < l)
-		{
-			for(j=0;j<l;j++)
-				data[j] = (Qfloat)(this->*kernel_function)(real_i,j);
-		}
-
-		// reorder and copy
-		Qfloat *buf = buffer[next_buffer];
-		next_buffer = 1 - next_buffer;
-		schar si = sign[i];
-		for(j=0;j<len;j++)
-			buf[j] = (Qfloat) si * (Qfloat) sign[j] * data[index[j]];
-		return buf;
-	}
-
-	double *get_QD() const
-	{
-		return QD;
-	}
-
-	~SVR_Q()
-	{
-		delete cache;
-		delete[] sign;
-		delete[] index;
-		delete[] buffer[0];
-		delete[] buffer[1];
-		delete[] QD;
-	}
-private:
-	int l;
-	Cache *cache;
-	schar *sign;
-	int *index;
-	mutable int next_buffer;
-	Qfloat *buffer[2];
-	double *QD;
-};
-
-//
-// construct and solve various formulations
-//
-static void solve_c_svc(
-	const svm_problem *prob, const svm_parameter* param,
-	double *alpha, Solver::SolutionInfo* si, double Cp, double Cn)
-{
-	int l = prob->l;
-	double *minus_ones = new double[l];
-	schar *y = new schar[l];
-
-	int i;
-
-	for(i=0;i<l;i++)
-	{
-		alpha[i] = 0;
-		minus_ones[i] = -1;
-		if(prob->y[i] > 0) y[i] = +1; else y[i] = -1;
-	}
-
-	Solver s;
-	s.Solve(l, SVC_Q(*prob,*param,y), minus_ones, y,
-		alpha, Cp, Cn, param->eps, si, param->shrinking);
-
-	double sum_alpha=0;
-	for(i=0;i<l;i++)
-		sum_alpha += alpha[i];
-
-	if (Cp==Cn)
-		info("nu = %f\n", sum_alpha/(Cp*prob->l));
-
-	for(i=0;i<l;i++)
-		alpha[i] *= y[i];
-
-	delete[] minus_ones;
-	delete[] y;
-}
-
-static void solve_nu_svc(
-	const svm_problem *prob, const svm_parameter *param,
-	double *alpha, Solver::SolutionInfo* si)
-{
-	int i;
-	int l = prob->l;
-	double nu = param->nu;
-
-	schar *y = new schar[l];
-
-	for(i=0;i<l;i++)
-		if(prob->y[i]>0)
-			y[i] = +1;
-		else
-			y[i] = -1;
-
-	double sum_pos = nu*l/2;
-	double sum_neg = nu*l/2;
-
-	for(i=0;i<l;i++)
-		if(y[i] == +1)
-		{
-			alpha[i] = min(1.0,sum_pos);
-			sum_pos -= alpha[i];
-		}
-		else
-		{
-			alpha[i] = min(1.0,sum_neg);
-			sum_neg -= alpha[i];
-		}
-
-	double *zeros = new double[l];
-
-	for(i=0;i<l;i++)
-		zeros[i] = 0;
-
-	Solver_NU s;
-	s.Solve(l, SVC_Q(*prob,*param,y), zeros, y,
-		alpha, 1.0, 1.0, param->eps, si,  param->shrinking);
-	double r = si->r;
-
-	info("C = %f\n",1/r);
-
-	for(i=0;i<l;i++)
-		alpha[i] *= y[i]/r;
-
-	si->rho /= r;
-	si->obj /= (r*r);
-	si->upper_bound_p = 1/r;
-	si->upper_bound_n = 1/r;
-
-	delete[] y;
-	delete[] zeros;
-}
-
-static void solve_one_class(
-	const svm_problem *prob, const svm_parameter *param,
-	double *alpha, Solver::SolutionInfo* si)
-{
-	int l = prob->l;
-	double *zeros = new double[l];
-	schar *ones = new schar[l];
-	int i;
-
-	int n = (int)(param->nu*prob->l);	// # of alpha's at upper bound
-
-	for(i=0;i<n;i++)
-		alpha[i] = 1;
-	if(n<prob->l)
-		alpha[n] = param->nu * prob->l - n;
-	for(i=n+1;i<l;i++)
-		alpha[i] = 0;
-
-	for(i=0;i<l;i++)
-	{
-		zeros[i] = 0;
-		ones[i] = 1;
-	}
-
-	Solver s;
-	s.Solve(l, ONE_CLASS_Q(*prob,*param), zeros, ones,
-		alpha, 1.0, 1.0, param->eps, si, param->shrinking);
-
-	delete[] zeros;
-	delete[] ones;
-}
-
-static void solve_epsilon_svr(
-	const svm_problem *prob, const svm_parameter *param,
-	double *alpha, Solver::SolutionInfo* si)
-{
-	int l = prob->l;
-	double *alpha2 = new double[2*l];
-	double *linear_term = new double[2*l];
-	schar *y = new schar[2*l];
-	int i;
-
-	for(i=0;i<l;i++)
-	{
-		alpha2[i] = 0;
-		linear_term[i] = param->p - prob->y[i];
-		y[i] = 1;
-
-		alpha2[i+l] = 0;
-		linear_term[i+l] = param->p + prob->y[i];
-		y[i+l] = -1;
-	}
-
-	Solver s;
-	s.Solve(2*l, SVR_Q(*prob,*param), linear_term, y,
-		alpha2, param->C, param->C, param->eps, si, param->shrinking);
-
-	double sum_alpha = 0;
-	for(i=0;i<l;i++)
-	{
-		alpha[i] = alpha2[i] - alpha2[i+l];
-		sum_alpha += fabs(alpha[i]);
-	}
-	info("nu = %f\n",sum_alpha/(param->C*l));
-
-	delete[] alpha2;
-	delete[] linear_term;
-	delete[] y;
-}
-
-static void solve_nu_svr(
-	const svm_problem *prob, const svm_parameter *param,
-	double *alpha, Solver::SolutionInfo* si)
-{
-	int l = prob->l;
-	double C = param->C;
-	double *alpha2 = new double[2*l];
-	double *linear_term = new double[2*l];
-	schar *y = new schar[2*l];
-	int i;
-
-	double sum = C * param->nu * l / 2;
-	for(i=0;i<l;i++)
-	{
-		alpha2[i] = alpha2[i+l] = min(sum,C);
-		sum -= alpha2[i];
-
-		linear_term[i] = - prob->y[i];
-		y[i] = 1;
-
-		linear_term[i+l] = prob->y[i];
-		y[i+l] = -1;
-	}
-
-	Solver_NU s;
-	s.Solve(2*l, SVR_Q(*prob,*param), linear_term, y,
-		alpha2, C, C, param->eps, si, param->shrinking);
-
-	info("epsilon = %f\n",-si->r);
-
-	for(i=0;i<l;i++)
-		alpha[i] = alpha2[i] - alpha2[i+l];
-
-	delete[] alpha2;
-	delete[] linear_term;
-	delete[] y;
-}
-
-//
-// decision_function
-//
-struct decision_function
-{
-	double *alpha;
-	double rho;	
-};
-
-static decision_function svm_train_one(
-	const svm_problem *prob, const svm_parameter *param,
-	double Cp, double Cn)
-{
-	double *alpha = Malloc(double,prob->l);
-	Solver::SolutionInfo si;
-	switch(param->svm_type)
-	{
-		case C_SVC:
-			solve_c_svc(prob,param,alpha,&si,Cp,Cn);
-			break;
-		case NU_SVC:
-			solve_nu_svc(prob,param,alpha,&si);
-			break;
-		case ONE_CLASS:
-			solve_one_class(prob,param,alpha,&si);
-			break;
-		case EPSILON_SVR:
-			solve_epsilon_svr(prob,param,alpha,&si);
-			break;
-		case NU_SVR:
-			solve_nu_svr(prob,param,alpha,&si);
-			break;
-	}
-
-	info("obj = %f, rho = %f\n",si.obj,si.rho);
-
-	// output SVs
-
-	int nSV = 0;
-	int nBSV = 0;
-	for(int i=0;i<prob->l;i++)
-	{
-		if(fabs(alpha[i]) > 0)
-		{
-			++nSV;
-			if(prob->y[i] > 0)
-			{
-				if(fabs(alpha[i]) >= si.upper_bound_p)
-					++nBSV;
-			}
-			else
-			{
-				if(fabs(alpha[i]) >= si.upper_bound_n)
-					++nBSV;
-			}
-		}
-	}
-
-	info("nSV = %d, nBSV = %d\n",nSV,nBSV);
-
-	decision_function f;
-	f.alpha = alpha;
-	f.rho = si.rho;
-	return f;
-}
-
-// Platt's binary SVM Probablistic Output: an improvement from Lin et al.
-static void sigmoid_train(
-	int l, const double *dec_values, const double *labels, 
-	double& A, double& B)
-{
-	double prior1=0, prior0 = 0;
-	int i;
-
-	for (i=0;i<l;i++)
-		if (labels[i] > 0) prior1+=1;
-		else prior0+=1;
-	
-	int max_iter=100;	// Maximal number of iterations
-	double min_step=1e-10;	// Minimal step taken in line search
-	double sigma=1e-12;	// For numerically strict PD of Hessian
-	double eps=1e-5;
-	double hiTarget=(prior1+1.0)/(prior1+2.0);
-	double loTarget=1/(prior0+2.0);
-	double *t=Malloc(double,l);
-	double fApB,p,q,h11,h22,h21,g1,g2,det,dA,dB,gd,stepsize;
-	double newA,newB,newf,d1,d2;
-	int iter; 
-	
-	// Initial Point and Initial Fun Value
-	A=0.0; B=log((prior0+1.0)/(prior1+1.0));
-	double fval = 0.0;
-
-	for (i=0;i<l;i++)
-	{
-		if (labels[i]>0) t[i]=hiTarget;
-		else t[i]=loTarget;
-		fApB = dec_values[i]*A+B;
-		if (fApB>=0)
-			fval += t[i]*fApB + log(1+exp(-fApB));
-		else
-			fval += (t[i] - 1)*fApB +log(1+exp(fApB));
-	}
-	for (iter=0;iter<max_iter;iter++)
-	{
-		// Update Gradient and Hessian (use H' = H + sigma I)
-		h11=sigma; // numerically ensures strict PD
-		h22=sigma;
-		h21=0.0;g1=0.0;g2=0.0;
-		for (i=0;i<l;i++)
-		{
-			fApB = dec_values[i]*A+B;
-			if (fApB >= 0)
-			{
-				p=exp(-fApB)/(1.0+exp(-fApB));
-				q=1.0/(1.0+exp(-fApB));
-			}
-			else
-			{
-				p=1.0/(1.0+exp(fApB));
-				q=exp(fApB)/(1.0+exp(fApB));
-			}
-			d2=p*q;
-			h11+=dec_values[i]*dec_values[i]*d2;
-			h22+=d2;
-			h21+=dec_values[i]*d2;
-			d1=t[i]-p;
-			g1+=dec_values[i]*d1;
-			g2+=d1;
-		}
-
-		// Stopping Criteria
-		if (fabs(g1)<eps && fabs(g2)<eps)
-			break;
-
-		// Finding Newton direction: -inv(H') * g
-		det=h11*h22-h21*h21;
-		dA=-(h22*g1 - h21 * g2) / det;
-		dB=-(-h21*g1+ h11 * g2) / det;
-		gd=g1*dA+g2*dB;
-
-
-		stepsize = 1;		// Line Search
-		while (stepsize >= min_step)
-		{
-			newA = A + stepsize * dA;
-			newB = B + stepsize * dB;
-
-			// New function value
-			newf = 0.0;
-			for (i=0;i<l;i++)
-			{
-				fApB = dec_values[i]*newA+newB;
-				if (fApB >= 0)
-					newf += t[i]*fApB + log(1+exp(-fApB));
-				else
-					newf += (t[i] - 1)*fApB +log(1+exp(fApB));
-			}
-			// Check sufficient decrease
-			if (newf<fval+0.0001*stepsize*gd)
-			{
-				A=newA;B=newB;fval=newf;
-				break;
-			}
-			else
-				stepsize = stepsize / 2.0;
-		}
-
-		if (stepsize < min_step)
-		{
-			info("Line search fails in two-class probability estimates\n");
-			break;
-		}
-	}
-
-	if (iter>=max_iter)
-		info("Reaching maximal iterations in two-class probability estimates\n");
-	free(t);
-}
-
-static double sigmoid_predict(double decision_value, double A, double B)
-{
-	double fApB = decision_value*A+B;
-	// 1-p used later; avoid catastrophic cancellation
-	if (fApB >= 0)
-		return exp(-fApB)/(1.0+exp(-fApB));
-	else
-		return 1.0/(1+exp(fApB)) ;
-}
-
-// Method 2 from the multiclass_prob paper by Wu, Lin, and Weng
-static void multiclass_probability(int k, double **r, double *p)
-{
-	int t,j;
-	int iter = 0, max_iter=max(100,k);
-	double **Q=Malloc(double *,k);
-	double *Qp=Malloc(double,k);
-	double pQp, eps=0.005/k;
-	
-	for (t=0;t<k;t++)
-	{
-		p[t]=1.0/k;  // Valid if k = 1
-		Q[t]=Malloc(double,k);
-		Q[t][t]=0;
-		for (j=0;j<t;j++)
-		{
-			Q[t][t]+=r[j][t]*r[j][t];
-			Q[t][j]=Q[j][t];
-		}
-		for (j=t+1;j<k;j++)
-		{
-			Q[t][t]+=r[j][t]*r[j][t];
-			Q[t][j]=-r[j][t]*r[t][j];
-		}
-	}
-	for (iter=0;iter<max_iter;iter++)
-	{
-		// stopping condition, recalculate QP,pQP for numerical accuracy
-		pQp=0;
-		for (t=0;t<k;t++)
-		{
-			Qp[t]=0;
-			for (j=0;j<k;j++)
-				Qp[t]+=Q[t][j]*p[j];
-			pQp+=p[t]*Qp[t];
-		}
-		double max_error=0;
-		for (t=0;t<k;t++)
-		{
-			double error=fabs(Qp[t]-pQp);
-			if (error>max_error)
-				max_error=error;
-		}
-		if (max_error<eps) break;
-		
-		for (t=0;t<k;t++)
-		{
-			double diff=(-Qp[t]+pQp)/Q[t][t];
-			p[t]+=diff;
-			pQp=(pQp+diff*(diff*Q[t][t]+2*Qp[t]))/(1+diff)/(1+diff);
-			for (j=0;j<k;j++)
-			{
-				Qp[j]=(Qp[j]+diff*Q[t][j])/(1+diff);
-				p[j]/=(1+diff);
-			}
-		}
-	}
-	if (iter>=max_iter)
-		info("Exceeds max_iter in multiclass_prob\n");
-	for(t=0;t<k;t++) free(Q[t]);
-	free(Q);
-	free(Qp);
-}
-
-// Cross-validation decision values for probability estimates
-static void svm_binary_svc_probability(
-	const svm_problem *prob, const svm_parameter *param,
-	double Cp, double Cn, double& probA, double& probB)
-{
-	int i;
-	int nr_fold = 5;
-	int *perm = Malloc(int,prob->l);
-	double *dec_values = Malloc(double,prob->l);
-
-	// random shuffle
-	for(i=0;i<prob->l;i++) perm[i]=i;
-	for(i=0;i<prob->l;i++)
-	{
-		int j = i+rand()%(prob->l-i);
-		swap(perm[i],perm[j]);
-	}
-	for(i=0;i<nr_fold;i++)
-	{
-		int begin = i*prob->l/nr_fold;
-		int end = (i+1)*prob->l/nr_fold;
-		int j,k;
-		struct svm_problem subprob;
-
-		subprob.l = prob->l-(end-begin);
-		subprob.x = Malloc(struct svm_node*,subprob.l);
-		subprob.y = Malloc(double,subprob.l);
-			
-		k=0;
-		for(j=0;j<begin;j++)
-		{
-			subprob.x[k] = prob->x[perm[j]];
-			subprob.y[k] = prob->y[perm[j]];
-			++k;
-		}
-		for(j=end;j<prob->l;j++)
-		{
-			subprob.x[k] = prob->x[perm[j]];
-			subprob.y[k] = prob->y[perm[j]];
-			++k;
-		}
-		int p_count=0,n_count=0;
-		for(j=0;j<k;j++)
-			if(subprob.y[j]>0)
-				p_count++;
-			else
-				n_count++;
-
-		if(p_count==0 && n_count==0)
-			for(j=begin;j<end;j++)
-				dec_values[perm[j]] = 0;
-		else if(p_count > 0 && n_count == 0)
-			for(j=begin;j<end;j++)
-				dec_values[perm[j]] = 1;
-		else if(p_count == 0 && n_count > 0)
-			for(j=begin;j<end;j++)
-				dec_values[perm[j]] = -1;
-		else
-		{
-			svm_parameter subparam = *param;
-			subparam.probability=0;
-			subparam.C=1.0;
-			subparam.nr_weight=2;
-			subparam.weight_label = Malloc(int,2);
-			subparam.weight = Malloc(double,2);
-			subparam.weight_label[0]=+1;
-			subparam.weight_label[1]=-1;
-			subparam.weight[0]=Cp;
-			subparam.weight[1]=Cn;
-			struct svm_model *submodel = svm_train(&subprob,&subparam);
-			for(j=begin;j<end;j++)
-			{
-				svm_predict_values(submodel,prob->x[perm[j]],&(dec_values[perm[j]])); 
-				// ensure +1 -1 order; reason not using CV subroutine
-				dec_values[perm[j]] *= submodel->label[0];
-			}		
-			svm_free_and_destroy_model(&submodel);
-			svm_destroy_param(&subparam);
-		}
-		free(subprob.x);
-		free(subprob.y);
-	}		
-	sigmoid_train(prob->l,dec_values,prob->y,probA,probB);
-	free(dec_values);
-	free(perm);
-}
-
-// Return parameter of a Laplace distribution 
-static double svm_svr_probability(
-	const svm_problem *prob, const svm_parameter *param)
-{
-	int i;
-	int nr_fold = 5;
-	double *ymv = Malloc(double,prob->l);
-	double mae = 0;
-
-	svm_parameter newparam = *param;
-	newparam.probability = 0;
-	svm_cross_validation(prob,&newparam,nr_fold,ymv);
-	for(i=0;i<prob->l;i++)
-	{
-		ymv[i]=prob->y[i]-ymv[i];
-		mae += fabs(ymv[i]);
-	}		
-	mae /= prob->l;
-	double std=sqrt(2*mae*mae);
-	int count=0;
-	mae=0;
-	for(i=0;i<prob->l;i++)
-		if (fabs(ymv[i]) > 5*std) 
-			count=count+1;
-		else 
-			mae+=fabs(ymv[i]);
-	mae /= (prob->l-count);
-	info("Prob. model for test data: target value = predicted value + z,\nz: Laplace distribution e^(-|z|/sigma)/(2sigma),sigma= %g\n",mae);
-	free(ymv);
-	return mae;
-}
-
-
-// label: label name, start: begin of each class, count: #data of classes, perm: indices to the original data
-// perm, length l, must be allocated before calling this subroutine
-static void svm_group_classes(const svm_problem *prob, int *nr_class_ret, int **label_ret, int **start_ret, int **count_ret, int *perm)
-{
-	int l = prob->l;
-	int max_nr_class = 16;
-	int nr_class = 0;
-	int *label = Malloc(int,max_nr_class);
-	int *count = Malloc(int,max_nr_class);
-	int *data_label = Malloc(int,l);	
-	int i;
-
-	for(i=0;i<l;i++)
-	{
-		int this_label = (int)prob->y[i];
-		int j;
-		for(j=0;j<nr_class;j++)
-		{
-			if(this_label == label[j])
-			{
-				++count[j];
-				break;
-			}
-		}
-		data_label[i] = j;
-		if(j == nr_class)
-		{
-			if(nr_class == max_nr_class)
-			{
-				max_nr_class *= 2;
-				label = (int *)realloc(label,max_nr_class*sizeof(int));
-				count = (int *)realloc(count,max_nr_class*sizeof(int));
-			}
-			label[nr_class] = this_label;
-			count[nr_class] = 1;
-			++nr_class;
-		}
-	}
-
-	int *start = Malloc(int,nr_class);
-	start[0] = 0;
-	for(i=1;i<nr_class;i++)
-		start[i] = start[i-1]+count[i-1];
-	for(i=0;i<l;i++)
-	{
-		perm[start[data_label[i]]] = i;
-		++start[data_label[i]];
-	}
-	start[0] = 0;
-	for(i=1;i<nr_class;i++)
-		start[i] = start[i-1]+count[i-1];
-
-	*nr_class_ret = nr_class;
-	*label_ret = label;
-	*start_ret = start;
-	*count_ret = count;
-	free(data_label);
-}
-
-//
-// Interface functions
-//
-svm_model *svm_train(const svm_problem *prob, const svm_parameter *param)
-{
-	svm_model *model = Malloc(svm_model,1);
-	model->param = *param;
-	model->free_sv = 0;	// XXX
-
-	if(param->svm_type == ONE_CLASS ||
-	   param->svm_type == EPSILON_SVR ||
-	   param->svm_type == NU_SVR)
-	{
-		// regression or one-class-svm
-		model->nr_class = 2;
-		model->label = NULL;
-		model->nSV = NULL;
-		model->probA = NULL; model->probB = NULL;
-		model->sv_coef = Malloc(double *,1);
-
-		if(param->probability && 
-		   (param->svm_type == EPSILON_SVR ||
-		    param->svm_type == NU_SVR))
-		{
-			model->probA = Malloc(double,1);
-			model->probA[0] = svm_svr_probability(prob,param);
-		}
-
-		decision_function f = svm_train_one(prob,param,0,0);
-		model->rho = Malloc(double,1);
-		model->rho[0] = f.rho;
-
-		int nSV = 0;
-		int i;
-		for(i=0;i<prob->l;i++)
-			if(fabs(f.alpha[i]) > 0) ++nSV;
-		model->l = nSV;
-		model->SV = Malloc(svm_node *,nSV);
-		model->sv_coef[0] = Malloc(double,nSV);
-		int j = 0;
-		for(i=0;i<prob->l;i++)
-			if(fabs(f.alpha[i]) > 0)
-			{
-				model->SV[j] = prob->x[i];
-				model->sv_coef[0][j] = f.alpha[i];
-				++j;
-			}		
-
-		free(f.alpha);
-	}
-	else
-	{
-		// classification
-		int l = prob->l;
-		int nr_class;
-		int *label = NULL;
-		int *start = NULL;
-		int *count = NULL;
-		int *perm = Malloc(int,l);
-
-		// group training data of the same class
-		svm_group_classes(prob,&nr_class,&label,&start,&count,perm);
-		if(nr_class == 1) 
-			info("WARNING: training data in only one class. See README for details.\n");
-		
-		svm_node **x = Malloc(svm_node *,l);
-		int i;
-		for(i=0;i<l;i++)
-			x[i] = prob->x[perm[i]];
-
-		// calculate weighted C
-
-		double *weighted_C = Malloc(double, nr_class);
-		for(i=0;i<nr_class;i++)
-			weighted_C[i] = param->C;
-		for(i=0;i<param->nr_weight;i++)
-		{	
-			int j;
-			for(j=0;j<nr_class;j++)
-				if(param->weight_label[i] == label[j])
-					break;
-			if(j == nr_class)
-				fprintf(stderr,"WARNING: class label %d specified in weight is not found\n", param->weight_label[i]);
-			else
-				weighted_C[j] *= param->weight[i];
-		}
-
-		// train k*(k-1)/2 models
-		
-		bool *nonzero = Malloc(bool,l);
-		for(i=0;i<l;i++)
-			nonzero[i] = false;
-		decision_function *f = Malloc(decision_function,nr_class*(nr_class-1)/2);
-
-		double *probA=NULL,*probB=NULL;
-		if (param->probability)
-		{
-			probA=Malloc(double,nr_class*(nr_class-1)/2);
-			probB=Malloc(double,nr_class*(nr_class-1)/2);
-		}
-
-		int p = 0;
-		for(i=0;i<nr_class;i++)
-			for(int j=i+1;j<nr_class;j++)
-			{
-				svm_problem sub_prob;
-				int si = start[i], sj = start[j];
-				int ci = count[i], cj = count[j];
-				sub_prob.l = ci+cj;
-				sub_prob.x = Malloc(svm_node *,sub_prob.l);
-				sub_prob.y = Malloc(double,sub_prob.l);
-				int k;
-				for(k=0;k<ci;k++)
-				{
-					sub_prob.x[k] = x[si+k];
-					sub_prob.y[k] = +1;
-				}
-				for(k=0;k<cj;k++)
-				{
-					sub_prob.x[ci+k] = x[sj+k];
-					sub_prob.y[ci+k] = -1;
-				}
-
-				if(param->probability)
-					svm_binary_svc_probability(&sub_prob,param,weighted_C[i],weighted_C[j],probA[p],probB[p]);
-
-				f[p] = svm_train_one(&sub_prob,param,weighted_C[i],weighted_C[j]);
-				for(k=0;k<ci;k++)
-					if(!nonzero[si+k] && fabs(f[p].alpha[k]) > 0)
-						nonzero[si+k] = true;
-				for(k=0;k<cj;k++)
-					if(!nonzero[sj+k] && fabs(f[p].alpha[ci+k]) > 0)
-						nonzero[sj+k] = true;
-				free(sub_prob.x);
-				free(sub_prob.y);
-				++p;
-			}
-
-		// build output
-
-		model->nr_class = nr_class;
-		
-		model->label = Malloc(int,nr_class);
-		for(i=0;i<nr_class;i++)
-			model->label[i] = label[i];
-		
-		model->rho = Malloc(double,nr_class*(nr_class-1)/2);
-		for(i=0;i<nr_class*(nr_class-1)/2;i++)
-			model->rho[i] = f[i].rho;
-
-		if(param->probability)
-		{
-			model->probA = Malloc(double,nr_class*(nr_class-1)/2);
-			model->probB = Malloc(double,nr_class*(nr_class-1)/2);
-			for(i=0;i<nr_class*(nr_class-1)/2;i++)
-			{
-				model->probA[i] = probA[i];
-				model->probB[i] = probB[i];
-			}
-		}
-		else
-		{
-			model->probA=NULL;
-			model->probB=NULL;
-		}
-
-		int total_sv = 0;
-		int *nz_count = Malloc(int,nr_class);
-		model->nSV = Malloc(int,nr_class);
-		for(i=0;i<nr_class;i++)
-		{
-			int nSV = 0;
-			for(int j=0;j<count[i];j++)
-				if(nonzero[start[i]+j])
-				{	
-					++nSV;
-					++total_sv;
-				}
-			model->nSV[i] = nSV;
-			nz_count[i] = nSV;
-		}
-		
-		info("Total nSV = %d\n",total_sv);
-
-		model->l = total_sv;
-		model->SV = Malloc(svm_node *,total_sv);
-		p = 0;
-		for(i=0;i<l;i++)
-			if(nonzero[i]) model->SV[p++] = x[i];
-
-		int *nz_start = Malloc(int,nr_class);
-		nz_start[0] = 0;
-		for(i=1;i<nr_class;i++)
-			nz_start[i] = nz_start[i-1]+nz_count[i-1];
-
-		model->sv_coef = Malloc(double *,nr_class-1);
-		for(i=0;i<nr_class-1;i++)
-			model->sv_coef[i] = Malloc(double,total_sv);
-
-		p = 0;
-		for(i=0;i<nr_class;i++)
-			for(int j=i+1;j<nr_class;j++)
-			{
-				// classifier (i,j): coefficients with
-				// i are in sv_coef[j-1][nz_start[i]...],
-				// j are in sv_coef[i][nz_start[j]...]
-
-				int si = start[i];
-				int sj = start[j];
-				int ci = count[i];
-				int cj = count[j];
-				
-				int q = nz_start[i];
-				int k;
-				for(k=0;k<ci;k++)
-					if(nonzero[si+k])
-						model->sv_coef[j-1][q++] = f[p].alpha[k];
-				q = nz_start[j];
-				for(k=0;k<cj;k++)
-					if(nonzero[sj+k])
-						model->sv_coef[i][q++] = f[p].alpha[ci+k];
-				++p;
-			}
-		
-		free(label);
-		free(probA);
-		free(probB);
-		free(count);
-		free(perm);
-		free(start);
-		free(x);
-		free(weighted_C);
-		free(nonzero);
-		for(i=0;i<nr_class*(nr_class-1)/2;i++)
-			free(f[i].alpha);
-		free(f);
-		free(nz_count);
-		free(nz_start);
-	}
-	return model;
-}
-
-// Stratified cross validation
-void svm_cross_validation(const svm_problem *prob, const svm_parameter *param, int nr_fold, double *target)
-{
-	int i;
-	int *fold_start = Malloc(int,nr_fold+1);
-	int l = prob->l;
-	int *perm = Malloc(int,l);
-	int nr_class;
-
-	// stratified cv may not give leave-one-out rate
-	// Each class to l folds -> some folds may have zero elements
-	if((param->svm_type == C_SVC ||
-	    param->svm_type == NU_SVC) && nr_fold < l)
-	{
-		int *start = NULL;
-		int *label = NULL;
-		int *count = NULL;
-		svm_group_classes(prob,&nr_class,&label,&start,&count,perm);
-
-		// random shuffle and then data grouped by fold using the array perm
-		int *fold_count = Malloc(int,nr_fold);
-		int c;
-		int *index = Malloc(int,l);
-		for(i=0;i<l;i++)
-			index[i]=perm[i];
-		for (c=0; c<nr_class; c++) 
-			for(i=0;i<count[c];i++)
-			{
-				int j = i+rand()%(count[c]-i);
-				swap(index[start[c]+j],index[start[c]+i]);
-			}
-		for(i=0;i<nr_fold;i++)
-		{
-			fold_count[i] = 0;
-			for (c=0; c<nr_class;c++)
-				fold_count[i]+=(i+1)*count[c]/nr_fold-i*count[c]/nr_fold;
-		}
-		fold_start[0]=0;
-		for (i=1;i<=nr_fold;i++)
-			fold_start[i] = fold_start[i-1]+fold_count[i-1];
-		for (c=0; c<nr_class;c++)
-			for(i=0;i<nr_fold;i++)
-			{
-				int begin = start[c]+i*count[c]/nr_fold;
-				int end = start[c]+(i+1)*count[c]/nr_fold;
-				for(int j=begin;j<end;j++)
-				{
-					perm[fold_start[i]] = index[j];
-					fold_start[i]++;
-				}
-			}
-		fold_start[0]=0;
-		for (i=1;i<=nr_fold;i++)
-			fold_start[i] = fold_start[i-1]+fold_count[i-1];
-		free(start);	
-		free(label);
-		free(count);	
-		free(index);
-		free(fold_count);
-	}
-	else
-	{
-		for(i=0;i<l;i++) perm[i]=i;
-		for(i=0;i<l;i++)
-		{
-			int j = i+rand()%(l-i);
-			swap(perm[i],perm[j]);
-		}
-		for(i=0;i<=nr_fold;i++)
-			fold_start[i]=i*l/nr_fold;
-	}
-
-	for(i=0;i<nr_fold;i++)
-	{
-		int begin = fold_start[i];
-		int end = fold_start[i+1];
-		int j,k;
-		struct svm_problem subprob;
-
-		subprob.l = l-(end-begin);
-		subprob.x = Malloc(struct svm_node*,subprob.l);
-		subprob.y = Malloc(double,subprob.l);
-			
-		k=0;
-		for(j=0;j<begin;j++)
-		{
-			subprob.x[k] = prob->x[perm[j]];
-			subprob.y[k] = prob->y[perm[j]];
-			++k;
-		}
-		for(j=end;j<l;j++)
-		{
-			subprob.x[k] = prob->x[perm[j]];
-			subprob.y[k] = prob->y[perm[j]];
-			++k;
-		}
-		struct svm_model *submodel = svm_train(&subprob,param);
-		if(param->probability && 
-		   (param->svm_type == C_SVC || param->svm_type == NU_SVC))
-		{
-			double *prob_estimates=Malloc(double,svm_get_nr_class(submodel));
-			for(j=begin;j<end;j++)
-				target[perm[j]] = svm_predict_probability(submodel,prob->x[perm[j]],prob_estimates);
-			free(prob_estimates);			
-		}
-		else
-			for(j=begin;j<end;j++)
-				target[perm[j]] = svm_predict(submodel,prob->x[perm[j]]);
-		svm_free_and_destroy_model(&submodel);
-		free(subprob.x);
-		free(subprob.y);
-	}		
-	free(fold_start);
-	free(perm);	
-}
-
-
-int svm_get_svm_type(const svm_model *model)
-{
-	return model->param.svm_type;
-}
-
-int svm_get_nr_class(const svm_model *model)
-{
-	return model->nr_class;
-}
-
-void svm_get_labels(const svm_model *model, int* label)
-{
-	if (model->label != NULL)
-		for(int i=0;i<model->nr_class;i++)
-			label[i] = model->label[i];
-}
-
-double svm_get_svr_probability(const svm_model *model)
-{
-	if ((model->param.svm_type == EPSILON_SVR || model->param.svm_type == NU_SVR) &&
-	    model->probA!=NULL)
-		return model->probA[0];
-	else
-	{
-		fprintf(stderr,"Model doesn't contain information for SVR probability inference\n");
-		return 0;
-	}
-}
-
-double svm_predict_values(const svm_model *model, const svm_node *x, double* dec_values)
-{
-	int i;
-	if(model->param.svm_type == ONE_CLASS ||
-	   model->param.svm_type == EPSILON_SVR ||
-	   model->param.svm_type == NU_SVR)
-	{
-		double *sv_coef = model->sv_coef[0];
-		double sum = 0;
-		for(i=0;i<model->l;i++)
-			sum += sv_coef[i] * Kernel::k_function(x,model->SV[i],model->param);
-		sum -= model->rho[0];
-		*dec_values = sum;
-
-		if(model->param.svm_type == ONE_CLASS)
-			return (sum>0)?1:-1;
-		else
-			return sum;
-	}
-	else
-	{
-		int nr_class = model->nr_class;
-		int l = model->l;
-		
-		double *kvalue = Malloc(double,l);
-		for(i=0;i<l;i++)
-			kvalue[i] = Kernel::k_function(x,model->SV[i],model->param);
-
-		int *start = Malloc(int,nr_class);
-		start[0] = 0;
-		for(i=1;i<nr_class;i++)
-			start[i] = start[i-1]+model->nSV[i-1];
-
-		int *vote = Malloc(int,nr_class);
-		for(i=0;i<nr_class;i++)
-			vote[i] = 0;
-
-		int p=0;
-		for(i=0;i<nr_class;i++)
-			for(int j=i+1;j<nr_class;j++)
-			{
-				double sum = 0;
-				int si = start[i];
-				int sj = start[j];
-				int ci = model->nSV[i];
-				int cj = model->nSV[j];
-				
-				int k;
-				double *coef1 = model->sv_coef[j-1];
-				double *coef2 = model->sv_coef[i];
-				for(k=0;k<ci;k++)
-					sum += coef1[si+k] * kvalue[si+k];
-				for(k=0;k<cj;k++)
-					sum += coef2[sj+k] * kvalue[sj+k];
-				sum -= model->rho[p];
-				dec_values[p] = sum;
-
-				if(dec_values[p] > 0)
-					++vote[i];
-				else
-					++vote[j];
-				p++;
-			}
-
-		int vote_max_idx = 0;
-		for(i=1;i<nr_class;i++)
-			if(vote[i] > vote[vote_max_idx])
-				vote_max_idx = i;
-
-		free(kvalue);
-		free(start);
-		free(vote);
-		return model->label[vote_max_idx];
-	}
-}
-
-double svm_predict(const svm_model *model, const svm_node *x)
-{
-	int nr_class = model->nr_class;
-	double *dec_values;
-	if(model->param.svm_type == ONE_CLASS ||
-	   model->param.svm_type == EPSILON_SVR ||
-	   model->param.svm_type == NU_SVR)
-		dec_values = Malloc(double, 1);
-	else 
-		dec_values = Malloc(double, nr_class*(nr_class-1)/2);
-	double pred_result = svm_predict_values(model, x, dec_values);
-	free(dec_values);
-	return pred_result;
-}
-
-double svm_predict_probability(
-	const svm_model *model, const svm_node *x, double *prob_estimates)
-{
-	if ((model->param.svm_type == C_SVC || model->param.svm_type == NU_SVC) &&
-	    model->probA!=NULL && model->probB!=NULL)
-	{
-		int i;
-		int nr_class = model->nr_class;
-		double *dec_values = Malloc(double, nr_class*(nr_class-1)/2);
-		svm_predict_values(model, x, dec_values);
-
-		double min_prob=1e-7;
-		double **pairwise_prob=Malloc(double *,nr_class);
-		for(i=0;i<nr_class;i++)
-			pairwise_prob[i]=Malloc(double,nr_class);
-		int k=0;
-		for(i=0;i<nr_class;i++)
-			for(int j=i+1;j<nr_class;j++)
-			{
-				pairwise_prob[i][j]=min(max(sigmoid_predict(dec_values[k],model->probA[k],model->probB[k]),min_prob),1-min_prob);
-				pairwise_prob[j][i]=1-pairwise_prob[i][j];
-				k++;
-			}
-		multiclass_probability(nr_class,pairwise_prob,prob_estimates);
-
-		int prob_max_idx = 0;
-		for(i=1;i<nr_class;i++)
-			if(prob_estimates[i] > prob_estimates[prob_max_idx])
-				prob_max_idx = i;
-		for(i=0;i<nr_class;i++)
-			free(pairwise_prob[i]);
-		free(dec_values);
-		free(pairwise_prob);	     
-		return model->label[prob_max_idx];
-	}
-	else 
-		return svm_predict(model, x);
-}
-
-static const char *svm_type_table[] =
-{
-	"c_svc","nu_svc","one_class","epsilon_svr","nu_svr",NULL
-};
-
-static const char *kernel_type_table[]=
-{
-	"linear","polynomial","rbf","sigmoid","precomputed",NULL
-};
-
-int svm_save_model(const char *model_file_name, const svm_model *model)
-{
-	FILE *fp = fopen(model_file_name,"w");
-	if(fp==NULL) return -1;
-
-	const svm_parameter& param = model->param;
-
-	fprintf(fp,"svm_type %s\n", svm_type_table[param.svm_type]);
-	fprintf(fp,"kernel_type %s\n", kernel_type_table[param.kernel_type]);
-
-	if(param.kernel_type == POLY)
-		fprintf(fp,"degree %d\n", param.degree);
-
-	if(param.kernel_type == POLY || param.kernel_type == RBF || param.kernel_type == SIGMOID)
-		fprintf(fp,"gamma %g\n", param.gamma);
-
-	if(param.kernel_type == POLY || param.kernel_type == SIGMOID)
-		fprintf(fp,"coef0 %g\n", param.coef0);
-
-	int nr_class = model->nr_class;
-	int l = model->l;
-	fprintf(fp, "nr_class %d\n", nr_class);
-	fprintf(fp, "total_sv %d\n",l);
-	
-	{
-		fprintf(fp, "rho");
-		for(int i=0;i<nr_class*(nr_class-1)/2;i++)
-			fprintf(fp," %g",model->rho[i]);
-		fprintf(fp, "\n");
-	}
-	
-	if(model->label)
-	{
-		fprintf(fp, "label");
-		for(int i=0;i<nr_class;i++)
-			fprintf(fp," %d",model->label[i]);
-		fprintf(fp, "\n");
-	}
-
-	if(model->probA) // regression has probA only
-	{
-		fprintf(fp, "probA");
-		for(int i=0;i<nr_class*(nr_class-1)/2;i++)
-			fprintf(fp," %g",model->probA[i]);
-		fprintf(fp, "\n");
-	}
-	if(model->probB)
-	{
-		fprintf(fp, "probB");
-		for(int i=0;i<nr_class*(nr_class-1)/2;i++)
-			fprintf(fp," %g",model->probB[i]);
-		fprintf(fp, "\n");
-	}
-
-	if(model->nSV)
-	{
-		fprintf(fp, "nr_sv");
-		for(int i=0;i<nr_class;i++)
-			fprintf(fp," %d",model->nSV[i]);
-		fprintf(fp, "\n");
-	}
-
-	fprintf(fp, "SV\n");
-	const double * const *sv_coef = model->sv_coef;
-	const svm_node * const *SV = model->SV;
-
-	for(int i=0;i<l;i++)
-	{
-		for(int j=0;j<nr_class-1;j++)
-			fprintf(fp, "%.16g ",sv_coef[j][i]);
-
-		const svm_node *p = SV[i];
-
-		if(param.kernel_type == PRECOMPUTED)
-			fprintf(fp,"0:%d ",(int)(p->value));
-		else
-			while(p->index != -1)
-			{
-				fprintf(fp,"%d:%.8g ",p->index,p->value);
-				p++;
-			}
-		fprintf(fp, "\n");
-	}
-	if (ferror(fp) != 0 || fclose(fp) != 0) return -1;
-	else return 0;
-}
-
-static char *line = NULL;
-static int max_line_len;
-
-static char* readline(FILE *input)
-{
-	int len;
-
-	if(fgets(line,max_line_len,input) == NULL)
-		return NULL;
-
-	while(strrchr(line,'\n') == NULL)
-	{
-		max_line_len *= 2;
-		line = (char *) realloc(line,max_line_len);
-		len = (int) strlen(line);
-		if(fgets(line+len,max_line_len-len,input) == NULL)
-			break;
-	}
-	return line;
-}
-
-svm_model *svm_load_model(const char *model_file_name)
-{
-	FILE *fp = fopen(model_file_name,"rb");
-	if(fp==NULL) return NULL;
-	
-	// read parameters
-
-	svm_model *model = Malloc(svm_model,1);
-	svm_parameter& param = model->param;
-	model->rho = NULL;
-	model->probA = NULL;
-	model->probB = NULL;
-	model->label = NULL;
-	model->nSV = NULL;
-
-	char cmd[81];
-	while(1)
-	{
-		fscanf(fp,"%80s",cmd);
-
-		if(strcmp(cmd,"svm_type")==0)
-		{
-			fscanf(fp,"%80s",cmd);
-			int i;
-			for(i=0;svm_type_table[i];i++)
-			{
-				if(strcmp(svm_type_table[i],cmd)==0)
-				{
-					param.svm_type=i;
-					break;
-				}
-			}
-			if(svm_type_table[i] == NULL)
-			{
-				fprintf(stderr,"unknown svm type.\n");
-				free(model->rho);
-				free(model->label);
-				free(model->nSV);
-				free(model);
-				return NULL;
-			}
-		}
-		else if(strcmp(cmd,"kernel_type")==0)
-		{		
-			fscanf(fp,"%80s",cmd);
-			int i;
-			for(i=0;kernel_type_table[i];i++)
-			{
-				if(strcmp(kernel_type_table[i],cmd)==0)
-				{
-					param.kernel_type=i;
-					break;
-				}
-			}
-			if(kernel_type_table[i] == NULL)
-			{
-				fprintf(stderr,"unknown kernel function.\n");
-				free(model->rho);
-				free(model->label);
-				free(model->nSV);
-				free(model);
-				return NULL;
-			}
-		}
-		else if(strcmp(cmd,"degree")==0)
-			fscanf(fp,"%d",&param.degree);
-		else if(strcmp(cmd,"gamma")==0)
-			fscanf(fp,"%lf",&param.gamma);
-		else if(strcmp(cmd,"coef0")==0)
-			fscanf(fp,"%lf",&param.coef0);
-		else if(strcmp(cmd,"nr_class")==0)
-			fscanf(fp,"%d",&model->nr_class);
-		else if(strcmp(cmd,"total_sv")==0)
-			fscanf(fp,"%d",&model->l);
-		else if(strcmp(cmd,"rho")==0)
-		{
-			int n = model->nr_class * (model->nr_class-1)/2;
-			model->rho = Malloc(double,n);
-			for(int i=0;i<n;i++)
-				fscanf(fp,"%lf",&model->rho[i]);
-		}
-		else if(strcmp(cmd,"label")==0)
-		{
-			int n = model->nr_class;
-			model->label = Malloc(int,n);
-			for(int i=0;i<n;i++)
-				fscanf(fp,"%d",&model->label[i]);
-		}
-		else if(strcmp(cmd,"probA")==0)
-		{
-			int n = model->nr_class * (model->nr_class-1)/2;
-			model->probA = Malloc(double,n);
-			for(int i=0;i<n;i++)
-				fscanf(fp,"%lf",&model->probA[i]);
-		}
-		else if(strcmp(cmd,"probB")==0)
-		{
-			int n = model->nr_class * (model->nr_class-1)/2;
-			model->probB = Malloc(double,n);
-			for(int i=0;i<n;i++)
-				fscanf(fp,"%lf",&model->probB[i]);
-		}
-		else if(strcmp(cmd,"nr_sv")==0)
-		{
-			int n = model->nr_class;
-			model->nSV = Malloc(int,n);
-			for(int i=0;i<n;i++)
-				fscanf(fp,"%d",&model->nSV[i]);
-		}
-		else if(strcmp(cmd,"SV")==0)
-		{
-			while(1)
-			{
-				int c = getc(fp);
-				if(c==EOF || c=='\n') break;	
-			}
-			break;
-		}
-		else
-		{
-			fprintf(stderr,"unknown text in model file: [%s]\n",cmd);
-			free(model->rho);
-			free(model->label);
-			free(model->nSV);
-			free(model);
-			return NULL;
-		}
-	}
-
-	// read sv_coef and SV
-
-	int elements = 0;
-	long pos = ftell(fp);
-
-	max_line_len = 1024;
-	line = Malloc(char,max_line_len);
-	char *p,*endptr,*idx,*val;
-
-	while(readline(fp)!=NULL)
-	{
-		p = strtok(line,":");
-		while(1)
-		{
-			p = strtok(NULL,":");
-			if(p == NULL)
-				break;
-			++elements;
-		}
-	}
-	elements += model->l;
-
-	fseek(fp,pos,SEEK_SET);
-
-	int m = model->nr_class - 1;
-	int l = model->l;
-	model->sv_coef = Malloc(double *,m);
-	int i;
-	for(i=0;i<m;i++)
-		model->sv_coef[i] = Malloc(double,l);
-	model->SV = Malloc(svm_node*,l);
-	svm_node *x_space = NULL;
-	if(l>0) x_space = Malloc(svm_node,elements);
-
-	int j=0;
-	for(i=0;i<l;i++)
-	{
-		readline(fp);
-		model->SV[i] = &x_space[j];
-
-		p = strtok(line, " \t");
-		model->sv_coef[0][i] = strtod(p,&endptr);
-		for(int k=1;k<m;k++)
-		{
-			p = strtok(NULL, " \t");
-			model->sv_coef[k][i] = strtod(p,&endptr);
-		}
-
-		while(1)
-		{
-			idx = strtok(NULL, ":");
-			val = strtok(NULL, " \t");
-
-			if(val == NULL)
-				break;
-			x_space[j].index = (int) strtol(idx,&endptr,10);
-			x_space[j].value = strtod(val,&endptr);
-
-			++j;
-		}
-		x_space[j++].index = -1;
-	}
-	free(line);
-
-	if (ferror(fp) != 0 || fclose(fp) != 0)
-		return NULL;
-
-	model->free_sv = 1;	// XXX
-	return model;
-}
-
-void svm_free_model_content(svm_model* model_ptr)
-{
-	if(model_ptr->free_sv && model_ptr->l > 0 && model_ptr->SV != NULL)
-		free((void *)(model_ptr->SV[0]));
-	if(model_ptr->sv_coef)
-	{
-		for(int i=0;i<model_ptr->nr_class-1;i++)
-			free(model_ptr->sv_coef[i]);
-	}
-
-	free(model_ptr->SV);
-	model_ptr->SV = NULL;
-
-	free(model_ptr->sv_coef);
-	model_ptr->sv_coef = NULL;
-
-	free(model_ptr->rho);
-	model_ptr->rho = NULL;
-
-	free(model_ptr->label);
-	model_ptr->label= NULL;
-
-	free(model_ptr->probA);
-	model_ptr->probA = NULL;
-
-	free(model_ptr->probB);
-	model_ptr->probB= NULL;
-
-	free(model_ptr->nSV);
-	model_ptr->nSV = NULL;
-}
-
-void svm_free_and_destroy_model(svm_model** model_ptr_ptr)
-{
-	if(model_ptr_ptr != NULL && *model_ptr_ptr != NULL)
-	{
-		svm_free_model_content(*model_ptr_ptr);
-		free(*model_ptr_ptr);
-		*model_ptr_ptr = NULL;
-	}
-}
-
-void svm_destroy_param(svm_parameter* param)
-{
-	free(param->weight_label);
-	free(param->weight);
-}
-
-const char *svm_check_parameter(const svm_problem *prob, const svm_parameter *param)
-{
-	// svm_type
-
-	int svm_type = param->svm_type;
-	if(svm_type != C_SVC &&
-	   svm_type != NU_SVC &&
-	   svm_type != ONE_CLASS &&
-	   svm_type != EPSILON_SVR &&
-	   svm_type != NU_SVR)
-		return "unknown svm type";
-	
-	// kernel_type, degree
-	
-	int kernel_type = param->kernel_type;
-	if(kernel_type != LINEAR &&
-	   kernel_type != POLY &&
-	   kernel_type != RBF &&
-	   kernel_type != SIGMOID &&
-	   kernel_type != PRECOMPUTED)
-		return "unknown kernel type";
-
-	if(param->gamma < 0)
-		return "gamma < 0";
-
-	if(param->degree < 0)
-		return "degree of polynomial kernel < 0";
-
-	// cache_size,eps,C,nu,p,shrinking
-
-	if(param->cache_size <= 0)
-		return "cache_size <= 0";
-
-	if(param->eps <= 0)
-		return "eps <= 0";
-
-	if(svm_type == C_SVC ||
-	   svm_type == EPSILON_SVR ||
-	   svm_type == NU_SVR)
-		if(param->C <= 0)
-			return "C <= 0";
-
-	if(svm_type == NU_SVC ||
-	   svm_type == ONE_CLASS ||
-	   svm_type == NU_SVR)
-		if(param->nu <= 0 || param->nu > 1)
-			return "nu <= 0 or nu > 1";
-
-	if(svm_type == EPSILON_SVR)
-		if(param->p < 0)
-			return "p < 0";
-
-	if(param->shrinking != 0 &&
-	   param->shrinking != 1)
-		return "shrinking != 0 and shrinking != 1";
-
-	if(param->probability != 0 &&
-	   param->probability != 1)
-		return "probability != 0 and probability != 1";
-
-	if(param->probability == 1 &&
-	   svm_type == ONE_CLASS)
-		return "one-class SVM probability output not supported yet";
-
-
-	// check whether nu-svc is feasible
-	
-	if(svm_type == NU_SVC)
-	{
-		int l = prob->l;
-		int max_nr_class = 16;
-		int nr_class = 0;
-		int *label = Malloc(int,max_nr_class);
-		int *count = Malloc(int,max_nr_class);
-
-		int i;
-		for(i=0;i<l;i++)
-		{
-			int this_label = (int)prob->y[i];
-			int j;
-			for(j=0;j<nr_class;j++)
-				if(this_label == label[j])
-				{
-					++count[j];
-					break;
-				}
-			if(j == nr_class)
-			{
-				if(nr_class == max_nr_class)
-				{
-					max_nr_class *= 2;
-					label = (int *)realloc(label,max_nr_class*sizeof(int));
-					count = (int *)realloc(count,max_nr_class*sizeof(int));
-				}
-				label[nr_class] = this_label;
-				count[nr_class] = 1;
-				++nr_class;
-			}
-		}
-	
-		for(i=0;i<nr_class;i++)
-		{
-			int n1 = count[i];
-			for(int j=i+1;j<nr_class;j++)
-			{
-				int n2 = count[j];
-				if(param->nu*(n1+n2)/2 > min(n1,n2))
-				{
-					free(label);
-					free(count);
-					return "specified nu is infeasible";
-				}
-			}
-		}
-		free(label);
-		free(count);
-	}
-
-	return NULL;
-}
-
-int svm_check_probability_model(const svm_model *model)
-{
-	return ((model->param.svm_type == C_SVC || model->param.svm_type == NU_SVC) &&
-		model->probA!=NULL && model->probB!=NULL) ||
-		((model->param.svm_type == EPSILON_SVR || model->param.svm_type == NU_SVR) &&
-		 model->probA!=NULL);
-}
-
-void svm_set_print_string_function(void (*print_func)(const char *))
-{
-	if(print_func == NULL)
-		svm_print_string = &print_string_stdout;
-	else
-		svm_print_string = print_func;
-}
diff --git a/src/modules/imagery/imagery_svm/svm.h b/src/modules/imagery/imagery_svm/svm.h
deleted file mode 100644
index dbc5e08..0000000
--- a/src/modules/imagery/imagery_svm/svm.h
+++ /dev/null
@@ -1,101 +0,0 @@
-#ifndef _LIBSVM_H
-#define _LIBSVM_H
-
-#define LIBSVM_VERSION 311
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-extern int libsvm_version;
-
-struct svm_node
-{
-	int index;
-	double value;
-};
-
-struct svm_problem
-{
-	int l;
-	double *y;
-	struct svm_node **x;
-};
-
-enum { C_SVC, NU_SVC, ONE_CLASS, EPSILON_SVR, NU_SVR };	/* svm_type */
-enum { LINEAR, POLY, RBF, SIGMOID, PRECOMPUTED }; /* kernel_type */
-
-struct svm_parameter
-{
-	int svm_type;
-	int kernel_type;
-	int degree;	/* for poly */
-	double gamma;	/* for poly/rbf/sigmoid */
-	double coef0;	/* for poly/sigmoid */
-
-	/* these are for training only */
-	double cache_size; /* in MB */
-	double eps;	/* stopping criteria */
-	double C;	/* for C_SVC, EPSILON_SVR and NU_SVR */
-	int nr_weight;		/* for C_SVC */
-	int *weight_label;	/* for C_SVC */
-	double* weight;		/* for C_SVC */
-	double nu;	/* for NU_SVC, ONE_CLASS, and NU_SVR */
-	double p;	/* for EPSILON_SVR */
-	int shrinking;	/* use the shrinking heuristics */
-	int probability; /* do probability estimates */
-};
-
-//
-// svm_model
-// 
-struct svm_model
-{
-	struct svm_parameter param;	/* parameter */
-	int nr_class;		/* number of classes, = 2 in regression/one class svm */
-	int l;			/* total #SV */
-	struct svm_node **SV;		/* SVs (SV[l]) */
-	double **sv_coef;	/* coefficients for SVs in decision functions (sv_coef[k-1][l]) */
-	double *rho;		/* constants in decision functions (rho[k*(k-1)/2]) */
-	double *probA;		/* pariwise probability information */
-	double *probB;
-
-	/* for classification only */
-
-	int *label;		/* label of each class (label[k]) */
-	int *nSV;		/* number of SVs for each class (nSV[k]) */
-				/* nSV[0] + nSV[1] + ... + nSV[k-1] = l */
-	/* XXX */
-	int free_sv;		/* 1 if svm_model is created by svm_load_model*/
-				/* 0 if svm_model is created by svm_train */
-};
-
-struct svm_model *svm_train(const struct svm_problem *prob, const struct svm_parameter *param);
-void svm_cross_validation(const struct svm_problem *prob, const struct svm_parameter *param, int nr_fold, double *target);
-
-int svm_save_model(const char *model_file_name, const struct svm_model *model);
-struct svm_model *svm_load_model(const char *model_file_name);
-
-int svm_get_svm_type(const struct svm_model *model);
-int svm_get_nr_class(const struct svm_model *model);
-void svm_get_labels(const struct svm_model *model, int *label);
-double svm_get_svr_probability(const struct svm_model *model);
-
-double svm_predict_values(const struct svm_model *model, const struct svm_node *x, double* dec_values);
-double svm_predict(const struct svm_model *model, const struct svm_node *x);
-double svm_predict_probability(const struct svm_model *model, const struct svm_node *x, double* prob_estimates);
-
-void svm_free_model_content(struct svm_model *model_ptr);
-void svm_free_and_destroy_model(struct svm_model **model_ptr_ptr);
-void svm_destroy_param(struct svm_parameter *param);
-
-const char *svm_check_parameter(const struct svm_problem *prob, const struct svm_parameter *param);
-int svm_check_probability_model(const struct svm_model *model);
-
-void svm_set_print_string_function(void (*print_func)(const char *));
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* _LIBSVM_H */
diff --git a/src/modules/imagery/imagery_tools/landsat_toar.cpp b/src/modules/imagery/imagery_tools/landsat_toar.cpp
index af103da..14617eb 100644
--- a/src/modules/imagery/imagery_tools/landsat_toar.cpp
+++ b/src/modules/imagery/imagery_tools/landsat_toar.cpp
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: landsat_toar.cpp 2165 2014-06-18 15:38:29Z oconrad $
+ * Version $Id: landsat_toar.cpp 2685 2015-11-10 16:12:27Z oconrad $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -86,16 +86,16 @@ enum
 };
 
 //---------------------------------------------------------
-#define PRM_IN(sensor, id)				CSG_String::Format(SG_T("DN_%s%02d"), CSG_String(sensor).c_str(), id)
-#define PRM_OUT(sensor, id)				CSG_String::Format(SG_T("RF_%s%02d"), CSG_String(sensor).c_str(), id)
-#define PRM_ADD_BAND__IN(sensor, id)	Parameters.Add_Grid(pNode, PRM_IN (sensor, id), CSG_String::Format(SG_T("%s %s %d"), _TL("DN")         , _TL("Band"), id), _TL(""), PARAMETER_INPUT_OPTIONAL);
-#define PRM_ADD_BAND_OUT(sensor, id)	Parameters.Add_Grid(pNode, PRM_OUT(sensor, id), CSG_String::Format(SG_T("%s %s %d"), _TL("Reflectance"), _TL("Band"), id), _TL(""), PARAMETER_OUTPUT_OPTIONAL);
+#define PRM_IN(sensor, id)				CSG_String::Format("DN_%s%02d", CSG_String(sensor).c_str(), id)
+#define PRM_OUT(sensor, id)				CSG_String::Format("RF_%s%02d", CSG_String(sensor).c_str(), id)
+#define PRM_ADD_BAND__IN(sensor, id)	Parameters.Add_Grid(pNode, PRM_IN (sensor, id), CSG_String::Format("%s %s %d", _TL("DN")         , _TL("Band"), id), _TL(""), PARAMETER_INPUT_OPTIONAL);
+#define PRM_ADD_BAND_OUT(sensor, id)	Parameters.Add_Grid(pNode, PRM_OUT(sensor, id), CSG_String::Format("%s %s %d", _TL("Reflectance"), _TL("Band"), id), _TL(""), PARAMETER_OUTPUT, true, SG_DATATYPE_Byte);
 #define PRM_ENABLE_OUTPUT(sensor, id)	pParameters->Set_Enabled(PRM_OUT(sensor, id), pParameters->Get_Parameter(PRM_IN(sensor, id)) && pParameters->Get_Parameter(PRM_IN(sensor, id))->asGrid())
 
 //---------------------------------------------------------
-#define GET_DESC_INT(name, value)		CSG_String::Format(SG_T("%s: %d\n"), name, value)
-#define GET_DESC_FLT(name, value)		CSG_String::Format(SG_T("%s: %f\n"), name, value)
-#define GET_DESC_RNG(name, min, max)	CSG_String::Format(SG_T("%s: %f / %f\n"), name, min, max)
+#define GET_DESC_INT(name, value)		CSG_String::Format("%s: %d\n", name, value)
+#define GET_DESC_FLT(name, value)		CSG_String::Format("%s: %f\n", name, value)
+#define GET_DESC_RNG(name, min, max)	CSG_String::Format("%s: %f / %f\n", name, min, max)
 #define GET_DESC_STR(name, value)		CSG_String(name) + ": " + CSG_String(value) + "\n"
 
 
@@ -330,7 +330,7 @@ CLandsat_TOAR::CLandsat_TOAR(void)
 //---------------------------------------------------------
 int CLandsat_TOAR::On_Parameter_Changed(CSG_Parameters *pParameters, CSG_Parameter *pParameter)
 {
-	if(	!SG_STR_CMP(pParameter->Get_Identifier(), SG_T("METAFILE")) && *pParameter->asString() )
+	if(	!SG_STR_CMP(pParameter->Get_Identifier(), "METAFILE") && *pParameter->asString() )
 	{
 		lsat_data	lsat;
 
@@ -346,15 +346,17 @@ int CLandsat_TOAR::On_Parameter_Changed(CSG_Parameters *pParameters, CSG_Paramet
 			pParameters->Get_Parameter("DATE_ACQU")->Set_Value((const char *)lsat.date);
 			pParameters->Get_Parameter("DATE_PROD")->Set_Value((const char *)lsat.creation);
 			pParameters->Get_Parameter("SUN_HGT"  )->Set_Value(lsat.sun_elev);
+
+			On_Parameters_Enable(pParameters, pParameters->Get_Parameter("SENSOR"));
 		}
 	}
 
-	if(	!SG_STR_CMP(pParameter->Get_Identifier(), SG_T("SENSOR")) )
+	if(	!SG_STR_CMP(pParameter->Get_Identifier(), "SENSOR") )
 	{
 		pParameters->Get_Parameter("METAFILE")->Set_Value((const char *)"");
 	}
 
-	return( 0 );
+	return( CSG_Module::On_Parameter_Changed(pParameters, pParameter) );
 }
 
 //---------------------------------------------------------
@@ -404,7 +406,7 @@ int CLandsat_TOAR::On_Parameters_Enable(CSG_Parameters *pParameters, CSG_Paramet
 		PRM_ENABLE_OUTPUT("PAN", 8);
 	}
 
-	return( 0 );
+	return( CSG_Module::On_Parameters_Enable(pParameters, pParameter) );
 }
 
 
@@ -475,7 +477,7 @@ CSG_Grid * CLandsat_TOAR::Get_Band_Output(int iBand, int Sensor)
 		{
 			if( !pOutput->asGrid() )
 			{
-				CSG_Grid	*pGrid	= SG_Create_Grid(pInput);
+				CSG_Grid	*pGrid	= SG_Create_Grid(pInput, SG_DATATYPE_Byte);
 
 				if( pGrid && pGrid->is_Valid() && pGrid->Get_System() == pInput->Get_System() )
 				{
@@ -492,8 +494,6 @@ CSG_Grid * CLandsat_TOAR::Get_Band_Output(int iBand, int Sensor)
 				}
 			}
 
-			pOutput->asGrid()->Set_Name(CSG_String::Format(SG_T("%s [%s]"), pInput->Get_Name(), _TL("Reflectance")));
-
 			return( pOutput->asGrid() );
 		}
 	}
@@ -693,10 +693,32 @@ bool CLandsat_TOAR::On_Execute(void)
 			continue;
 		}
 
-		Process_Set_Text(CSG_String::Format(SG_T("%s [%d/%d]"),
-			bRadiance ? _TL("Radiance") : lsat.band[iBand].thermal ? _TL("Temperature") : _TL("Reflectance"),
-			lsat.band[iBand].number, lsat.bands
-		));
+		Process_Set_Text(CSG_String::Format("%s [%d/%d]", _TL("Processing"), lsat.band[iBand].number, lsat.bands));
+
+		//-------------------------------------------------
+		if( bRadiance )
+		{
+			pOutput->Set_Name(CSG_String::Format("%s [%s]", pInput->Get_Name(), _TL("Radiance"   )));
+			pOutput->asGrid()->Set_NoData_Value(255.0);
+
+			double	min	= lsat_qcal2rad(pInput->Get_ZMin(), &lsat.band[iBand]);
+			double	max	= lsat_qcal2rad(pInput->Get_ZMax(), &lsat.band[iBand]);
+
+			pOutput->asGrid()->Set_Scaling((max - min) / 254.0, min);
+		}
+		else if( lsat.band[iBand].thermal )
+		{
+			pOutput->Set_Name(CSG_String::Format("%s [%s]", pInput->Get_Name(), _TL("Temperature")));
+			pOutput->Set_Unit(_TL("Kelvin"));
+			pOutput->asGrid()->Set_NoData_Value(255.0);
+			pOutput->asGrid()->Set_Scaling(0.5, 200.0);
+		}
+		else
+		{
+			pOutput->Set_Name(CSG_String::Format("%s [%s]", pInput->Get_Name(), _TL("Reflectance")));
+			pOutput->asGrid()->Set_NoData_Value(255.0);
+			pOutput->asGrid()->Set_Scaling(1.0 / 254.0);
+		}
 
 		//-------------------------------------------------
 		for(int y=0; y<pInput->Get_NY() && Set_Progress(y, pInput->Get_NY()); y++)
@@ -739,18 +761,18 @@ bool CLandsat_TOAR::On_Execute(void)
 		sBand	+= GET_DESC_STR(_TL("Type"                     ), bRadiance ? _TL("Radiance") : lsat.band[iBand].thermal ? _TL("Temperature") : _TL("Reflectance"));
 		sBand	+= GET_DESC_RNG(_TL("Calibrated Digital Number"), lsat.band[iBand].qcalmin, lsat.band[iBand].qcalmax);
 		sBand	+= GET_DESC_RNG(_TL("Calibration Constants"    ), lsat.band[iBand].lmin   , lsat.band[iBand].lmax);
-		sBand	+= GET_DESC_STR(AC_Method > DOS ? _TL("At-Surface Radiance") : _TL("At-Sensor Radiance"), CSG_String::Format(SG_T("%.5lf * DN + %.5lf"), lsat.band[iBand].gain, lsat.band[iBand].bias));
+		sBand	+= GET_DESC_STR(AC_Method > DOS ? _TL("At-Surface Radiance") : _TL("At-Sensor Radiance"), CSG_String::Format("%.5lf * DN + %.5lf", lsat.band[iBand].gain, lsat.band[iBand].bias));
 
 		if( lsat.band[iBand].thermal )
 		{
-			sBand	+= GET_DESC_STR(_TL("At-Sensor Temperature"), CSG_String::Format(SG_T("%.3lf / ln[(%.3lf / %s) + 1.0]"), lsat.band[iBand].K2, lsat.band[iBand].K1, _TL("Radiance")));
+			sBand	+= GET_DESC_STR(_TL("At-Sensor Temperature"), CSG_String::Format("%.3lf / ln[(%.3lf / %s) + 1.0]", lsat.band[iBand].K2, lsat.band[iBand].K1, _TL("Radiance")));
 			sBand	+= GET_DESC_FLT(_TL("Temperature K1"       ), lsat.band[iBand].K1);
 			sBand	+= GET_DESC_FLT(_TL("Temperature K2"       ), lsat.band[iBand].K2);
 		}
 		else
 		{
 			sBand	+= GET_DESC_FLT(_TL("Mean Solar Irradiance"), lsat.band[iBand].esun);	// Mean Solar Exoatmospheric Irradiance
-			sBand	+= GET_DESC_STR(AC_Method > DOS ? _TL("At-Surface Reflectance") : _TL("At-Sensor Reflectance"), CSG_String::Format(SG_T("%s / %.5lf"), _TL("Radiance"), lsat.band[iBand].K2));
+			sBand	+= GET_DESC_STR(AC_Method > DOS ? _TL("At-Surface Reflectance") : _TL("At-Sensor Reflectance"), CSG_String::Format("%s / %.5lf", _TL("Radiance"), lsat.band[iBand].K2));
 
 			if( AC_Method > DOS )
 			{
@@ -765,16 +787,6 @@ bool CLandsat_TOAR::On_Execute(void)
 
 		Message_Add(sBand, true);
 
-		//-------------------------------------------------
-		pOutput->Set_Name(CSG_String::Format(SG_T("%s [%s]"), pInput->Get_Name(),
-			bRadiance ? _TL("Radiance") : lsat.band[iBand].thermal ? _TL("Temperature") : _TL("Reflectance")
-		));
-
-		if( lsat.band[iBand].thermal )
-		{
-			pOutput->Set_Unit(_TL("Kelvin"));
-		}
-
 		pOutput->Set_Description(sAll + sBand);
 	}
 
diff --git a/src/modules/io/io_gdal/MLB_Interface.cpp b/src/modules/io/io_gdal/MLB_Interface.cpp
index a940115..fa38d56 100644
--- a/src/modules/io/io_gdal/MLB_Interface.cpp
+++ b/src/modules/io/io_gdal/MLB_Interface.cpp
@@ -89,7 +89,7 @@ CSG_String Get_Info(int i)
 		return( SG_T("2.0") );
 
 	case MLB_INFO_Menu_Path:
-		return( _TL("File|GDAL/OGR") );
+		return( _TL("File") );
 	}
 }
 
@@ -101,6 +101,7 @@ CSG_String Get_Info(int i)
 #include "gdal_export.h"
 #include "gdal_export_geotiff.h"
 #include "gdal_import_netcdf.h"
+#include "gdal_catalogue.h"
 
 #include "ogr_import.h"
 #include "ogr_export.h"
@@ -118,6 +119,9 @@ CSG_Module *		Create_Module(int i)
 	case  1:	return( new CGDAL_Export );
 	case  2:	return( new CGDAL_Export_GeoTIFF );
 
+	case  7:	return( new CGDAL_Catalogue );
+	case  8:	return( new CGDAL_Catalogues );
+
 	case  3:	return( new COGR_Import );
 	case  4:	return( new COGR_Export );
 
diff --git a/src/modules/io/io_gdal/Makefile.am b/src/modules/io/io_gdal/Makefile.am
index 4c3709c..b3be151 100644
--- a/src/modules/io/io_gdal/Makefile.am
+++ b/src/modules/io/io_gdal/Makefile.am
@@ -14,6 +14,7 @@ AM_CXXFLAGS        = -fPIC $(CXX_INCS) $(DEF_SAGA) $(UC_DEFS) $(DBGFLAGS) $(GOMP
 AM_LDFLAGS         = -fPIC -shared -avoid-version $(DEP_LIBS)
 pkglib_LTLIBRARIES = libio_gdal.la
 libio_gdal_la_SOURCES =\
+gdal_catalogue.cpp\
 gdal_driver.cpp\
 gdal_export.cpp\
 gdal_export_geotiff.cpp\
@@ -24,6 +25,7 @@ ogr_driver.cpp\
 ogr_export.cpp\
 ogr_export_kml.cpp\
 ogr_import.cpp\
+gdal_catalogue.h\
 gdal_driver.h\
 gdal_export.h\
 gdal_export_geotiff.h\
diff --git a/src/modules/io/io_gdal/Makefile.in b/src/modules/io/io_gdal/Makefile.in
index 0fbe2b3..7d1b89d 100644
--- a/src/modules/io/io_gdal/Makefile.in
+++ b/src/modules/io/io_gdal/Makefile.in
@@ -127,10 +127,10 @@ am__installdirs = "$(DESTDIR)$(pkglibdir)"
 LTLIBRARIES = $(pkglib_LTLIBRARIES)
 libio_gdal_la_DEPENDENCIES =  \
 	$(top_srcdir)/src/saga_core/saga_api/libsaga_api.la
-am_libio_gdal_la_OBJECTS = gdal_driver.lo gdal_export.lo \
-	gdal_export_geotiff.lo gdal_import.lo gdal_import_netcdf.lo \
-	MLB_Interface.lo ogr_driver.lo ogr_export.lo ogr_export_kml.lo \
-	ogr_import.lo
+am_libio_gdal_la_OBJECTS = gdal_catalogue.lo gdal_driver.lo \
+	gdal_export.lo gdal_export_geotiff.lo gdal_import.lo \
+	gdal_import_netcdf.lo MLB_Interface.lo ogr_driver.lo \
+	ogr_export.lo ogr_export_kml.lo ogr_import.lo
 libio_gdal_la_OBJECTS = $(am_libio_gdal_la_OBJECTS)
 AM_V_lt = $(am__v_lt_ at AM_V@)
 am__v_lt_ = $(am__v_lt_ at AM_DEFAULT_V@)
@@ -375,6 +375,7 @@ AM_CXXFLAGS = -fPIC $(CXX_INCS) $(DEF_SAGA) $(UC_DEFS) $(DBGFLAGS) $(GOMPFLAGS)
 AM_LDFLAGS = -fPIC -shared -avoid-version $(DEP_LIBS)
 pkglib_LTLIBRARIES = libio_gdal.la
 libio_gdal_la_SOURCES = \
+gdal_catalogue.cpp\
 gdal_driver.cpp\
 gdal_export.cpp\
 gdal_export_geotiff.cpp\
@@ -385,6 +386,7 @@ ogr_driver.cpp\
 ogr_export.cpp\
 ogr_export_kml.cpp\
 ogr_import.cpp\
+gdal_catalogue.h\
 gdal_driver.h\
 gdal_export.h\
 gdal_export_geotiff.h\
@@ -477,6 +479,7 @@ distclean-compile:
 	-rm -f *.tab.c
 
 @AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/MLB_Interface.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/gdal_catalogue.Plo at am__quote@
 @AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/gdal_driver.Plo at am__quote@
 @AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/gdal_export.Plo at am__quote@
 @AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/gdal_export_geotiff.Plo at am__quote@
diff --git a/src/modules/io/io_gdal/gdal_catalogue.cpp b/src/modules/io/io_gdal/gdal_catalogue.cpp
new file mode 100644
index 0000000..9fb1465
--- /dev/null
+++ b/src/modules/io/io_gdal/gdal_catalogue.cpp
@@ -0,0 +1,587 @@
+/**********************************************************
+ * Version $Id: gdal_catalogue.cpp 1921 2014-01-09 10:24:11Z oconrad $
+ *********************************************************/
+
+///////////////////////////////////////////////////////////
+//                                                       //
+//                         SAGA                          //
+//                                                       //
+//      System for Automated Geoscientific Analyses      //
+//                                                       //
+//                    Module Library:                    //
+//                       io_gdal                         //
+//                                                       //
+//-------------------------------------------------------//
+//                                                       //
+//                  gdal_catalogue.cpp                   //
+//                                                       //
+//                 Copyright (C) 2015 by                 //
+//                      Olaf Conrad                      //
+//                                                       //
+//-------------------------------------------------------//
+//                                                       //
+// This file is part of 'SAGA - System for Automated     //
+// Geoscientific Analyses'. SAGA 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; version 2 of the License.   //
+//                                                       //
+// SAGA 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,       //
+// write to the Free Software Foundation, Inc.,          //
+// 51 Franklin Street, 5th Floor, Boston, MA 02110-1301, //
+// USA.                                                  //
+//                                                       //
+//-------------------------------------------------------//
+//                                                       //
+//    e-mail:     oconrad at saga-gis.de                    //
+//                                                       //
+//    contact:    Olaf Conrad                            //
+//                Institute of Geography                 //
+//                University of Hamburg                  //
+//                Germany                                //
+//                                                       //
+///////////////////////////////////////////////////////////
+
+
+///////////////////////////////////////////////////////////
+//														 //
+//														 //
+//														 //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+#include "gdal_catalogue.h"
+
+
+///////////////////////////////////////////////////////////
+//														 //
+//														 //
+//														 //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+CGDAL_Catalogue::CGDAL_Catalogue(void)
+{
+	//-----------------------------------------------------
+	Set_Name	(_TL("Create Raster Catalogue from Files"));
+
+	Set_Author	("O.Conrad (c) 2015");
+
+	CSG_String	Description;
+
+	Description	= _TW(
+		"Create a raster catalogue from selected files. Output is a polygon layer "
+		"that shows the extent for each valid raster file. Each extent is attributed with "
+		"the original file path and raster system properties.\n"
+		"\n"
+		"The \"GDAL Raster Import\" module imports grid data from various file formats using the "
+		"\"Geospatial Data Abstraction Library\" (GDAL) by Frank Warmerdam. "
+		"For more information have a look at the GDAL homepage:\n"
+		"  <a target=\"_blank\" href=\"http://www.gdal.org/\">"
+		"  http://www.gdal.org</a>\n"
+	);
+
+	Description	+= CSG_String::Format("\nGDAL %s:%s\n\n", _TL("Version"), SG_Get_GDAL_Drivers().Get_Version().c_str());
+
+	Description	+= _TW(
+		"Following raster formats are currently supported:\n"
+		"<table border=\"1\"><tr><th>ID</th><th>Name</th></tr>\n"
+	);
+
+	for(int i=0; i<SG_Get_GDAL_Drivers().Get_Count(); i++)
+    {
+		Description	+= CSG_String::Format("<tr><td>%s</td><td>%s</td></tr>\n",
+			SG_Get_GDAL_Drivers().Get_Description(i).c_str(),
+			SG_Get_GDAL_Drivers().Get_Name       (i).c_str()
+		);
+    }
+
+	Description	+= "</table>";
+
+	Set_Description(Description);
+
+	//-----------------------------------------------------
+	Parameters.Add_Shapes(
+		NULL	, "CATALOGUE"	, _TL("Raster Catalogue"),
+		_TL(""),
+		PARAMETER_OUTPUT, SHAPE_TYPE_Polygon
+	);
+
+	Parameters.Add_FilePath(
+		NULL	, "FILES"		, _TL("Files"),
+		_TL(""),
+		NULL, NULL, false, false, true
+	);
+}
+
+
+///////////////////////////////////////////////////////////
+//														 //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+int CGDAL_Catalogue::On_Parameters_Enable(CSG_Parameters *pParameters, CSG_Parameter *pParameter)
+{
+	return( CSG_Module::On_Parameters_Enable(pParameters, pParameter) );
+}
+
+
+///////////////////////////////////////////////////////////
+//														 //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+bool CGDAL_Catalogue::On_Execute(void)
+{
+	//-----------------------------------------------------
+	CSG_Strings	Files;
+
+	if( !Parameters("FILES")->asFilePath()->Get_FilePaths(Files) )
+	{
+		return( false );
+	}
+
+	//-----------------------------------------------------
+	CSG_Shapes	*pCatalogue	= Parameters("CATALOGUE")->asShapes();
+
+	pCatalogue->Create(SHAPE_TYPE_Polygon, _TL("Raster Catalogue"));
+
+	pCatalogue->Add_Field("ID"      , SG_DATATYPE_Int   );
+	pCatalogue->Add_Field("NAME"    , SG_DATATYPE_String);
+	pCatalogue->Add_Field("FILE"    , SG_DATATYPE_String);
+	pCatalogue->Add_Field("CRS"     , SG_DATATYPE_String);
+	pCatalogue->Add_Field("BANDS"   , SG_DATATYPE_Int   );
+	pCatalogue->Add_Field("CELLSIZE", SG_DATATYPE_Double);
+	pCatalogue->Add_Field("ROWS"    , SG_DATATYPE_Int   );
+	pCatalogue->Add_Field("COLUMNS" , SG_DATATYPE_Int   );
+
+	//-----------------------------------------------------
+	for(int i=0; i<Files.Get_Count() && Set_Progress(i, Files.Get_Count()); i++)
+	{
+		CSG_String	Name	= SG_File_Get_Name(Files[i], true);
+
+		Process_Set_Text(CSG_String::Format("\n%s: %s", _TL("analyzing"), Name.c_str()));
+
+		CSG_GDAL_DataSet	DataSet;
+
+		if( DataSet.Open_Read(Files[i]) == false )
+		{
+			Message_Add(_TL("failed: could not find a suitable import driver"));
+		}
+		else
+		{
+			CSG_Grid_System	System	= DataSet.Get_System();
+
+			CSG_Shape	*pEntry	= pCatalogue->Add_Shape();
+
+			pEntry->Set_Value(0, pCatalogue->Get_Count ());
+			pEntry->Set_Value(1, Name                    );
+			pEntry->Set_Value(2, DataSet.Get_File_Name ());
+			pEntry->Set_Value(3, DataSet.Get_Projection());
+			pEntry->Set_Value(4, DataSet.Get_Count     ());
+			pEntry->Set_Value(5, System.Get_Cellsize   ());
+			pEntry->Set_Value(6, System.Get_NX         ());
+			pEntry->Set_Value(7, System.Get_NY         ());
+
+			pEntry->Add_Point(System.Get_XMin(), System.Get_YMin());
+			pEntry->Add_Point(System.Get_XMin(), System.Get_YMax());
+			pEntry->Add_Point(System.Get_XMax(), System.Get_YMax());
+			pEntry->Add_Point(System.Get_XMax(), System.Get_YMin());
+			pEntry->Add_Point(System.Get_XMin(), System.Get_YMin());
+
+			if( !pCatalogue->Get_Projection().is_Okay() )
+			{
+				pCatalogue->Get_Projection().Create(DataSet.Get_Projection(), SG_PROJ_FMT_WKT);
+			}
+		}
+	}
+
+	//-----------------------------------------------------
+	return( pCatalogue->Get_Count() > 0 );
+}
+
+
+///////////////////////////////////////////////////////////
+//														 //
+//														 //
+//														 //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+CGDAL_Catalogues::CGDAL_Catalogues(void)
+{
+	//-----------------------------------------------------
+	Set_Name	(_TL("Create Raster Catalogues from Directory"));
+
+	Set_Author	("O.Conrad (c) 2015");
+
+	CSG_String	Description;
+
+	Description	= _TW(
+		"Creates raster catalogues from all raster files found in the selected directory. "
+		"Catalogues are splitted according to the coordinate reference system used by the "
+		"different raster files. Output are polygon layers that show the extent for each "
+		"raster file in it. Each extent is attributed with the original file path and "
+		"raster system properties.\n"
+		"\n"
+		"The \"GDAL Raster Import\" module imports grid data from various file formats using the "
+		"\"Geospatial Data Abstraction Library\" (GDAL) by Frank Warmerdam. "
+		"For more information have a look at the GDAL homepage:\n"
+		"  <a target=\"_blank\" href=\"http://www.gdal.org/\">"
+		"  http://www.gdal.org</a>\n"
+	);
+
+	Description	+= CSG_String::Format("\nGDAL %s:%s\n\n", _TL("Version"), SG_Get_GDAL_Drivers().Get_Version().c_str());
+
+	Description	+= _TW(
+		"Following raster formats are currently supported:\n"
+		"<table border=\"1\"><tr><th>ID</th><th>Name</th></tr>\n"
+	);
+
+	for(int i=0; i<SG_Get_GDAL_Drivers().Get_Count(); i++)
+    {
+		Description	+= CSG_String::Format("<tr><td>%s</td><td>%s</td></tr>\n",
+			SG_Get_GDAL_Drivers().Get_Description(i).c_str(),
+			SG_Get_GDAL_Drivers().Get_Name       (i).c_str()
+		);
+    }
+
+	Description	+= "</table>";
+
+	Set_Description(Description);
+
+	//-----------------------------------------------------
+	Parameters.Add_Shapes_List(
+		NULL	, "CATALOGUES"		, _TL("Raster Catalogues"),
+		_TL(""),
+		PARAMETER_OUTPUT, SHAPE_TYPE_Polygon
+	);
+
+	Parameters.Add_Shapes(
+		NULL	, "CATALOGUE_GCS"	, _TL("Raster Catalogue"),
+		_TL(""),
+		PARAMETER_OUTPUT, SHAPE_TYPE_Polygon
+	);
+
+	Parameters.Add_Shapes(
+		NULL	, "CATALOGUE_UKN"	, _TL("Raster Catalogue (unknown CRS)"),
+		_TL(""),
+		PARAMETER_OUTPUT_OPTIONAL, SHAPE_TYPE_Polygon
+	);
+
+	Parameters.Add_FilePath(
+		NULL	, "DIRECTORY"		, _TL("Directory"),
+		_TL(""),
+		NULL, NULL, false, true
+	);
+
+	Parameters.Add_String(
+		NULL	, "EXTENSIONS"		, _TL("Extensions"),
+		_TL(""),
+		"sgrd; tif"
+	);
+
+	Parameters.Add_Choice(
+		NULL	, "OUTPUT"		, _TL("Output"),
+		_TL(""),
+		CSG_String::Format("%s|%s|",
+			_TL("one catalogue for each coordinate system"),
+			_TL("one catalogue using geographic coordinates")
+		), 1
+	);
+}
+
+
+///////////////////////////////////////////////////////////
+//														 //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+int CGDAL_Catalogues::On_Parameters_Enable(CSG_Parameters *pParameters, CSG_Parameter *pParameter)
+{
+	if( !SG_STR_CMP(pParameter->Get_Identifier(), "OUTPUT") )
+	{
+		pParameters->Set_Enabled("CATALOGUES"   , pParameter->asInt() == 0);
+		pParameters->Set_Enabled("CATALOGUE_GCS", pParameter->asInt() == 1);
+		pParameters->Set_Enabled("CATALOGUE_UKN", pParameter->asInt() == 1);
+	}
+
+	return( CSG_Module::On_Parameters_Enable(pParameters, pParameter) );
+}
+
+
+///////////////////////////////////////////////////////////
+//														 //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+bool CGDAL_Catalogues::On_Execute(void)
+{
+	//-----------------------------------------------------
+	m_Directory	= Parameters("DIRECTORY")->asString();
+
+	if( !SG_Dir_Exists(m_Directory) )
+	{
+		return( false );
+	}
+
+	//-----------------------------------------------------
+	m_pCatalogues	= Parameters("CATALOGUES")->asShapesList();
+	m_pCatalogues	->Del_Items();
+
+	//-----------------------------------------------------
+	CSG_String_Tokenizer	Extensions(Parameters("EXTENSIONS")->asString(), ";");
+
+	while( Extensions.Has_More_Tokens() )
+	{
+		CSG_String	Extension	= Extensions.Get_Next_Token();	Extension.Trim(true);	Extension.Trim(false);
+
+		if( Extension.CmpNoCase("sgrd") == 0 )	// gdal ignores saga's grid header file, use grid data file instead!
+		{
+			Extension	= "sdat";
+		}
+
+		if( !Extension.is_Empty() )
+		{
+			m_Extensions	+= Extension;
+		}
+	}
+
+	if( m_Extensions.Get_Count() == 0 )
+	{
+		m_Extensions	+= "";
+	}
+
+	//-----------------------------------------------------
+	int	n	= Add_Directory(m_Directory);
+
+	m_Extensions.Clear();
+
+	if( n <= 0 )
+	{
+		Message_Add(CSG_String::Format("\n%s\n", _TL("No raster files have been found in directory.")));
+
+		return( false );
+	}
+
+	Message_Add(CSG_String::Format("\n%s: %d\n", _TL("Number of raster files found in directory"), n), false);
+
+	//-----------------------------------------------------
+	if( Parameters("OUTPUT")->asInt() == 1 )	// one catalogue using geographic coordinates
+	{
+		Get_Catalogue(CSG_Projection("+proj=longlat +datum=WGS84", SG_PROJ_FMT_Proj4),
+			Parameters("CATALOGUE_GCS")->asShapes(), _TL("Raster Catalogue")
+		);
+
+		Get_Catalogue(CSG_Projection(),
+			Parameters("CATALOGUE_UKN")->asShapes(), _TL("Raster Catalogue (unknown CRS)")
+		);
+
+		for(int i=m_pCatalogues->Get_Count()-1; i>=0 && Process_Get_Okay(true); i--)
+		{
+			CSG_Shapes	*pCatalogue	= m_pCatalogues->asShapes(i);
+
+			Add_To_Geographic(pCatalogue);
+
+			delete(pCatalogue);
+
+			m_pCatalogues->Del_Item(i);
+		}
+	}
+
+	return( true );
+}
+
+
+///////////////////////////////////////////////////////////
+//														 //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+CSG_Shapes * CGDAL_Catalogues::Get_Catalogue(const CSG_Projection &Projection, CSG_Shapes *pCatalogue, const CSG_String &Name)
+{
+	if( pCatalogue )
+	{
+		pCatalogue->Create(SHAPE_TYPE_Polygon, Name);
+
+		pCatalogue->Add_Field("ID"      , SG_DATATYPE_Int   );
+		pCatalogue->Add_Field("NAME"    , SG_DATATYPE_String);
+		pCatalogue->Add_Field("FILE_ABS", SG_DATATYPE_String);
+		pCatalogue->Add_Field("FILE_REL", SG_DATATYPE_String);
+		pCatalogue->Add_Field("CRS"     , SG_DATATYPE_String);
+		pCatalogue->Add_Field("PROJ4"   , SG_DATATYPE_String);
+		pCatalogue->Add_Field("BANDS"   , SG_DATATYPE_Int   );
+		pCatalogue->Add_Field("CELLSIZE", SG_DATATYPE_Double);
+		pCatalogue->Add_Field("ROWS"    , SG_DATATYPE_Int   );
+		pCatalogue->Add_Field("COLUMNS" , SG_DATATYPE_Int   );
+
+		pCatalogue->Get_Projection().Create(Projection);
+	}
+
+	return( pCatalogue );
+}
+
+//---------------------------------------------------------
+CSG_Shapes * CGDAL_Catalogues::Get_Catalogue(const CSG_Projection &Projection)
+{
+	for(int i=0; i<m_pCatalogues->Get_Count(); i++)
+	{
+		if( Projection.is_Equal(m_pCatalogues->asShapes(i)->Get_Projection()) )
+		{
+			return( m_pCatalogues->asShapes(i) );
+		}
+	}
+
+	//-----------------------------------------------------
+	CSG_Shapes	*pCatalogue	= Get_Catalogue(Projection, SG_Create_Shapes(), CSG_String::Format("%s No.%d", _TL("Raster Catalogue"), 1 + m_pCatalogues->Get_Count()));
+
+	m_pCatalogues->Add_Item(pCatalogue);
+
+	return( pCatalogue );
+}
+
+//---------------------------------------------------------
+int CGDAL_Catalogues::Add_Directory(const CSG_String &Directory)
+{
+	int	n	= 0;
+
+	CSG_Strings	List;
+
+	//-----------------------------------------------------
+	for(int iExtension=0; iExtension<m_Extensions.Get_Count(); iExtension++)
+	{
+		if( SG_Dir_List_Files(List, Directory, m_Extensions[iExtension]) )
+		{
+			for(int i=0; i<List.Get_Count() && Process_Get_Okay(true); i++)
+			{
+				n	+= Add_File(List[i]);
+			}
+		}
+	}
+
+	//-----------------------------------------------------
+	if( SG_Dir_List_Subdirectories(List, Directory) )
+	{
+		for(int i=0; i<List.Get_Count() && Process_Get_Okay(true); i++)
+		{
+			n	+= Add_Directory(List[i]);
+		}
+	}
+
+	return( n );
+}
+
+//---------------------------------------------------------
+int CGDAL_Catalogues::Add_File(const CSG_String &File)
+{
+	CSG_String	Name	= SG_File_Get_Name(File, true);
+
+	Process_Set_Text(CSG_String::Format("\n%s: %s", _TL("analyzing"), Name.c_str()));
+
+	//-----------------------------------------------------
+	CSG_GDAL_DataSet	DataSet;
+
+	if( DataSet.Open_Read(File) == false )
+	{
+		return( 0 );
+	}
+
+	//-----------------------------------------------------
+	CSG_Projection	Projection(DataSet.Get_Projection(), SG_PROJ_FMT_WKT);
+
+	CSG_Shapes	*pCatalogue	= Get_Catalogue(Projection);
+
+	if( !pCatalogue )
+	{
+		return( 0 );
+	}
+
+	//-----------------------------------------------------
+	CSG_Grid_System	System	= DataSet.Get_System();
+
+	CSG_Shape	*pEntry	= pCatalogue->Add_Shape();
+
+	CSG_String	Filename_Absolute	= DataSet.Get_File_Name();
+
+	if( SG_File_Cmp_Extension(Filename_Absolute, SG_T("sdat")) )
+	{
+		SG_File_Set_Extension(Filename_Absolute, "sgrd");
+	}
+
+	CSG_String	Filename_Relative	= SG_File_Get_Path_Relative(m_Directory, Filename_Absolute);
+
+	pEntry->Set_Value(0, pCatalogue->Get_Count ());
+	pEntry->Set_Value(1, Name                    );
+	pEntry->Set_Value(2, Filename_Absolute       );
+	pEntry->Set_Value(3, Filename_Relative       );
+	pEntry->Set_Value(4, DataSet.Get_Projection());
+	pEntry->Set_Value(5, Projection.Get_Proj4  ());
+	pEntry->Set_Value(6, DataSet.Get_Count     ());
+	pEntry->Set_Value(7, System.Get_Cellsize   ());
+	pEntry->Set_Value(8, System.Get_NX         ());
+	pEntry->Set_Value(9, System.Get_NY         ());
+
+	pEntry->Add_Point(System.Get_XMin(), System.Get_YMin());
+	pEntry->Add_Point(System.Get_XMin(), System.Get_YMax());
+	pEntry->Add_Point(System.Get_XMax(), System.Get_YMax());
+	pEntry->Add_Point(System.Get_XMax(), System.Get_YMin());
+	pEntry->Add_Point(System.Get_XMin(), System.Get_YMin());
+
+	return( 1 );
+}
+
+
+///////////////////////////////////////////////////////////
+//														 //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+bool CGDAL_Catalogues::Add_To_Geographic(CSG_Shapes *pCatalogue)
+{
+	CSG_Shapes	Catalogue, *pTarget	= Parameters("CATALOGUE_UKN")->asShapes();
+
+	if( pCatalogue->Get_Projection().is_Okay() )
+	{
+		bool	bResult;
+
+		SG_RUN_MODULE(bResult, "pj_proj4", 2,
+				SG_MODULE_PARAMETER_SET("SOURCE"   , pCatalogue)
+			&&	SG_MODULE_PARAMETER_SET("TARGET"   , &Catalogue)
+			&&	SG_MODULE_PARAMETER_SET("CRS_PROJ4", Parameters("CATALOGUE_GCS")->asShapes()->Get_Projection().Get_Proj4())
+		);
+
+		if( bResult )
+		{
+			pCatalogue	= &Catalogue;
+
+			pTarget	= Parameters("CATALOGUE_GCS")->asShapes();
+		}
+	}
+
+	//-----------------------------------------------------
+	if( pTarget )
+	{
+		for(int i=0; i<pCatalogue->Get_Count(); i++)
+		{
+			pTarget->Add_Shape(pCatalogue->Get_Shape(i));
+		}
+	}
+
+	return( true );
+}
+
+
+///////////////////////////////////////////////////////////
+//														 //
+//														 //
+//														 //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
diff --git a/src/modules/grid/grid_tools/Grid_Cut.h b/src/modules/io/io_gdal/gdal_catalogue.h
similarity index 73%
copy from src/modules/grid/grid_tools/Grid_Cut.h
copy to src/modules/io/io_gdal/gdal_catalogue.h
index 33265c8..1f66519 100644
--- a/src/modules/grid/grid_tools/Grid_Cut.h
+++ b/src/modules/io/io_gdal/gdal_catalogue.h
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: Grid_Cut.h 2097 2014-04-11 12:50:55Z oconrad $
+ * Version $Id: gdal_catalogue.h 1921 2014-01-09 10:24:11Z oconrad $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -8,15 +8,15 @@
 //                                                       //
 //      System for Automated Geoscientific Analyses      //
 //                                                       //
-//                    Module Library:                    //
-//                      Grid_Tools                       //
+//                    Module Library:                    //
+//                       io_gdal                         //
 //                                                       //
 //-------------------------------------------------------//
 //                                                       //
-//                      Grid_Cut.h                       //
+//                   gdal_catalogue.h                    //
 //                                                       //
-//                 Copyright (C) 2003 by                 //
-//                      Olaf Conrad                      //
+//                 Copyright (C) 2015 by                 //
+//                      Olaf Conrad                      //
 //                                                       //
 //-------------------------------------------------------//
 //                                                       //
@@ -40,20 +40,15 @@
 //                                                       //
 //-------------------------------------------------------//
 //                                                       //
-//    e-mail:     oconrad at saga-gis.org                   //
+//    e-mail:     oconrad at saga-gis.de                    //
 //                                                       //
 //    contact:    Olaf Conrad                            //
-//                Institute of Geography                 //
-//                University of Goettingen               //
-//                Goldschmidtstr. 5                      //
-//                37077 Goettingen                       //
+//                Institute of Geography                 //
+//                University of Hamburg                  //
 //                Germany                                //
 //                                                       //
 ///////////////////////////////////////////////////////////
 
-//---------------------------------------------------------
-
-
 ///////////////////////////////////////////////////////////
 //														 //
 //														 //
@@ -61,8 +56,8 @@
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
-#ifndef HEADER_INCLUDED__Grid_Cut_H
-#define HEADER_INCLUDED__Grid_Cut_H
+#ifndef HEADER_INCLUDED__gdal_catalogue_H
+#define HEADER_INCLUDED__gdal_catalogue_H
 
 
 ///////////////////////////////////////////////////////////
@@ -72,7 +67,7 @@
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
-#include "MLB_Interface.h"
+#include "gdal_driver.h"
 
 
 ///////////////////////////////////////////////////////////
@@ -82,30 +77,19 @@
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
-class CGrid_Clip_Interactive : public CSG_Module_Grid_Interactive
+class CGDAL_Catalogue : public CSG_Module
 {
 public:
-	CGrid_Clip_Interactive(void);
+	CGDAL_Catalogue(void);
 
-	virtual CSG_String			Get_MenuPath			(void)	{	return( _TL("A:Grid|Grid System") );	}
+	virtual CSG_String			Get_MenuPath			(void)	{	return( _TL("Grid") );	}
 
 
 protected:
 
-	virtual int					On_Parameter_Changed	(CSG_Parameters *pParameters, CSG_Parameter *pParameter);
+	virtual int					On_Parameters_Enable	(CSG_Parameters *pParameters, CSG_Parameter *pParameter);
 
 	virtual bool				On_Execute				(void);
-	virtual bool				On_Execute_Position		(CSG_Point ptWorld, TSG_Module_Interactive_Mode Mode);
-
-
-private:
-
-	bool						m_bDown;
-
-	CSG_Point					m_ptDown;
-
-
-	TSG_Point					Fit_to_Grid				(TSG_Point Point);
 
 };
 
@@ -115,17 +99,16 @@ private:
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
-class CGrid_Clip : public CSG_Module_Grid
+class CGDAL_Catalogues : public CSG_Module
 {
 public:
-	CGrid_Clip(void);
+	CGDAL_Catalogues(void);
 
-	virtual CSG_String			Get_MenuPath			(void)	{	return( _TL("A:Grid|Grid System") );	}
+	virtual CSG_String			Get_MenuPath			(void)	{	return( _TL("Grid") );	}
 
 
 protected:
 
-	virtual int					On_Parameter_Changed	(CSG_Parameters *pParameters, CSG_Parameter *pParameter);
 	virtual int					On_Parameters_Enable	(CSG_Parameters *pParameters, CSG_Parameter *pParameter);
 
 	virtual bool				On_Execute				(void);
@@ -133,7 +116,20 @@ protected:
 
 private:
 
-	bool						Get_Mask				(CSG_Grid &Mask, CSG_Grid_System &System, CSG_Shapes *pPolygons);
+	CSG_String					m_Directory;
+
+	CSG_Strings					m_Extensions;
+
+	CSG_Parameter_Shapes_List	*m_pCatalogues;
+
+
+	CSG_Shapes *				Get_Catalogue			(const CSG_Projection &Projection, CSG_Shapes *pCatalogue, const CSG_String &Name);
+	CSG_Shapes *				Get_Catalogue			(const CSG_Projection &Projection);
+
+	int							Add_Directory			(const CSG_String &Directory);
+	int							Add_File				(const CSG_String &File);
+
+	bool						Add_To_Geographic		(CSG_Shapes *pCatalogue);
 
 };
 
@@ -145,4 +141,4 @@ private:
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
-#endif // #ifndef HEADER_INCLUDED__Grid_Cut_H
+#endif // #ifndef HEADER_INCLUDED__gdal_catalogue_H
diff --git a/src/modules/io/io_gdal/gdal_driver.cpp b/src/modules/io/io_gdal/gdal_driver.cpp
index 07c041f..0d7a132 100644
--- a/src/modules/io/io_gdal/gdal_driver.cpp
+++ b/src/modules/io/io_gdal/gdal_driver.cpp
@@ -788,6 +788,40 @@ bool CSG_GDAL_DataSet::Write(int i, CSG_Grid *pGrid)
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
+CSG_Rect CSG_GDAL_DataSet::Get_Extent(bool bTransform)	const
+{
+	if( bTransform && Needs_Transformation() )
+	{
+		CSG_Grid_System	System;
+
+		if( Get_Transformation(System, false) )
+		{
+			return( System.Get_Extent() );
+		}
+	}
+
+	return( CSG_Rect(Get_xMin(), Get_yMin(), Get_xMax(), Get_yMax()) );
+}
+
+//---------------------------------------------------------
+CSG_Grid_System CSG_GDAL_DataSet::Get_System(void)	const
+{
+	CSG_Grid_System	System;
+
+	if( !Needs_Transformation() || !Get_Transformation(System, false) )
+	{
+		System.Assign(Get_Cellsize(), Get_xMin(), Get_yMin(), Get_NX(), Get_NY());
+	}
+
+	return( System );
+}
+
+
+///////////////////////////////////////////////////////////
+//														 //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
 bool CSG_GDAL_DataSet::Get_Transformation(CSG_Grid_System &System, bool bVerbose) const
 {
 	CSG_Vector	A;
diff --git a/src/modules/io/io_gdal/gdal_driver.h b/src/modules/io/io_gdal/gdal_driver.h
index db01762..b7eeefb 100644
--- a/src/modules/io/io_gdal/gdal_driver.h
+++ b/src/modules/io/io_gdal/gdal_driver.h
@@ -139,6 +139,9 @@ public:
 	double						Get_xMax			(void)	const	{	return( m_xMin + m_NX * m_Cellsize );	}
 	double						Get_yMax			(void)	const	{	return( m_yMin + m_NY * m_Cellsize );	}
 
+	CSG_Rect					Get_Extent			(bool bTransform = true)	const;
+	CSG_Grid_System				Get_System			(void)	const;
+
 	bool						Needs_Transformation(void)	const	{	return( m_bTransform );	}
 	void						Get_Transformation	(CSG_Vector &A, CSG_Matrix &B)				const	{	A	= m_TF_A;	B	= m_TF_B;	}
 	bool						Get_Transformation	(CSG_Grid_System &System, bool bVerbose)	const;
diff --git a/src/modules/io/io_gdal/gdal_export.cpp b/src/modules/io/io_gdal/gdal_export.cpp
index 3e45e74..72e865c 100644
--- a/src/modules/io/io_gdal/gdal_export.cpp
+++ b/src/modules/io/io_gdal/gdal_export.cpp
@@ -70,9 +70,9 @@
 //---------------------------------------------------------
 CGDAL_Export::CGDAL_Export(void)
 {
-	Set_Name	(_TL("GDAL: Export Raster"));
+	Set_Name	(_TL("Export Raster"));
 
-	Set_Author	(SG_T("O.Conrad (c) 2007"));
+	Set_Author	("O.Conrad (c) 2007");
 
 	CSG_String	Description, Formats;
 
diff --git a/src/modules/io/io_gdal/gdal_export.h b/src/modules/io/io_gdal/gdal_export.h
index d714e4a..7cfaa1a 100644
--- a/src/modules/io/io_gdal/gdal_export.h
+++ b/src/modules/io/io_gdal/gdal_export.h
@@ -76,10 +76,12 @@ class io_gdal_EXPORT CGDAL_Export : public CSG_Module_Grid
 public:
 	CGDAL_Export(void);
 
+	virtual CSG_String			Get_MenuPath	(void)	{	return( _TL("Grid|Export") );	}
+
 
 protected:
 
-	virtual bool		On_Execute		(void);
+	virtual bool				On_Execute		(void);
 
 
 };
diff --git a/src/modules/io/io_gdal/gdal_export_geotiff.cpp b/src/modules/io/io_gdal/gdal_export_geotiff.cpp
index ec54f9b..7020ceb 100644
--- a/src/modules/io/io_gdal/gdal_export_geotiff.cpp
+++ b/src/modules/io/io_gdal/gdal_export_geotiff.cpp
@@ -71,9 +71,9 @@
 //---------------------------------------------------------
 CGDAL_Export_GeoTIFF::CGDAL_Export_GeoTIFF(void)
 {
-	Set_Name		(_TL("GDAL: Export Raster to GeoTIFF"));
+	Set_Name		(_TL("Export GeoTIFF"));
 
-	Set_Author		(SG_T("O.Conrad (c) 2007"));
+	Set_Author		("O.Conrad (c) 2007");
 
 	Set_Description	(_TW(
 		"The \"GDAL GeoTIFF Export\" module exports one or more grids to a Geocoded Tagged Image File Format using the "
diff --git a/src/modules/io/io_gdal/gdal_export_geotiff.h b/src/modules/io/io_gdal/gdal_export_geotiff.h
index b25a154..34af08c 100644
--- a/src/modules/io/io_gdal/gdal_export_geotiff.h
+++ b/src/modules/io/io_gdal/gdal_export_geotiff.h
@@ -71,15 +71,17 @@
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
-class io_gdal_EXPORT CGDAL_Export_GeoTIFF : public CSG_Module_Grid
+class CGDAL_Export_GeoTIFF : public CSG_Module_Grid
 {
 public:
 	CGDAL_Export_GeoTIFF(void);
 
+	virtual CSG_String			Get_MenuPath	(void)	{	return( _TL("Grid|Export") );	}
+
 
 protected:
 
-	virtual bool		On_Execute		(void);
+	virtual bool				On_Execute		(void);
 
 };
 
diff --git a/src/modules/io/io_gdal/gdal_import.cpp b/src/modules/io/io_gdal/gdal_import.cpp
index a08345f..687ddfa 100644
--- a/src/modules/io/io_gdal/gdal_import.cpp
+++ b/src/modules/io/io_gdal/gdal_import.cpp
@@ -72,7 +72,7 @@ CGDAL_Import::CGDAL_Import(void)
 	CSG_Parameter	*pNode;
 
 	//-----------------------------------------------------
-	Set_Name	(_TL("GDAL: Import Raster"));
+	Set_Name	(_TL("Import Raster"));
 
 	Set_Author	("O.Conrad (c) 2007 (A.Ringeler)");
 
diff --git a/src/modules/io/io_gdal/gdal_import.h b/src/modules/io/io_gdal/gdal_import.h
index 8b33de1..6647140 100644
--- a/src/modules/io/io_gdal/gdal_import.h
+++ b/src/modules/io/io_gdal/gdal_import.h
@@ -76,6 +76,8 @@ class io_gdal_EXPORT CGDAL_Import : public CSG_Module
 public:
 	CGDAL_Import(void);
 
+	virtual CSG_String			Get_MenuPath			(void)	{	return( _TL("Grid|Import") );	}
+
 
 protected:
 
diff --git a/src/modules/io/io_gdal/gdal_import_netcdf.cpp b/src/modules/io/io_gdal/gdal_import_netcdf.cpp
index 02b2226..3f8f06f 100644
--- a/src/modules/io/io_gdal/gdal_import_netcdf.cpp
+++ b/src/modules/io/io_gdal/gdal_import_netcdf.cpp
@@ -72,7 +72,7 @@ CGDAL_Import_NetCDF::CGDAL_Import_NetCDF(void)
 	CSG_Parameter	*pNode;
 
 	//-----------------------------------------------------
-	Set_Name		(_TL("GDAL: Import NetCDF"));
+	Set_Name		(_TL("Import NetCDF"));
 
 	Set_Author		(SG_T("O.Conrad (c) 2012"));
 
diff --git a/src/modules/io/io_gdal/gdal_import_netcdf.h b/src/modules/io/io_gdal/gdal_import_netcdf.h
index 6a2c516..dba2148 100644
--- a/src/modules/io/io_gdal/gdal_import_netcdf.h
+++ b/src/modules/io/io_gdal/gdal_import_netcdf.h
@@ -76,6 +76,8 @@ class io_gdal_EXPORT CGDAL_Import_NetCDF : public CSG_Module
 public:
 	CGDAL_Import_NetCDF(void);
 
+	virtual CSG_String			Get_MenuPath			(void)	{	return( _TL("Grid|Import") );	}
+
 
 protected:
 
diff --git a/src/modules/io/io_gdal/ogr_export.cpp b/src/modules/io/io_gdal/ogr_export.cpp
index e92719f..eefa85f 100644
--- a/src/modules/io/io_gdal/ogr_export.cpp
+++ b/src/modules/io/io_gdal/ogr_export.cpp
@@ -69,14 +69,14 @@
 //---------------------------------------------------------
 COGR_Export::COGR_Export(void)
 {
-	Set_Name		(_TL("OGR: Export Vector Data"));
+	Set_Name		(_TL("Export Shapes"));
 
-	Set_Author		(SG_T("O.Conrad (c) 2008"));
+	Set_Author		("O.Conrad (c) 2008");
 
 	CSG_String	Description, Formats;
 
 	Description	= _TW(
-		"The \"GDAL Vector Data Export\" module exports vector data to various file formats using the "
+		"The \"OGR Vector Data Export\" module exports vector data to various file formats using the "
 		"\"Geospatial Data Abstraction Library\" (GDAL) by Frank Warmerdam. "
 		"For more information have a look at the GDAL homepage:\n"
 		"  <a target=\"_blank\" href=\"http://www.gdal.org/\">"
diff --git a/src/modules/io/io_gdal/ogr_export.h b/src/modules/io/io_gdal/ogr_export.h
index 473bdbb..229901a 100644
--- a/src/modules/io/io_gdal/ogr_export.h
+++ b/src/modules/io/io_gdal/ogr_export.h
@@ -76,10 +76,12 @@ class COGR_Export : public CSG_Module
 public:
 	COGR_Export(void);
 
+	virtual CSG_String			Get_MenuPath	(void)	{	return( _TL("Shapes|Export") );	}
+
 
 protected:
 
-	virtual bool		On_Execute		(void);
+	virtual bool				On_Execute		(void);
 
 };
 
diff --git a/src/modules/io/io_gdal/ogr_export_kml.cpp b/src/modules/io/io_gdal/ogr_export_kml.cpp
index 23d3fe4..6e0b511 100644
--- a/src/modules/io/io_gdal/ogr_export_kml.cpp
+++ b/src/modules/io/io_gdal/ogr_export_kml.cpp
@@ -71,9 +71,9 @@
 //---------------------------------------------------------
 COGR_Export_KML::COGR_Export_KML(void)
 {
-	Set_Name		(_TL("OGR: Export Shapes to KML"));
+	Set_Name		(_TL("Export Shapes to KML"));
 
-	Set_Author		(SG_T("O.Conrad (c) 2012"));
+	Set_Author		("O.Conrad (c) 2012");
 
 	Set_Description	(_TW(
 		"This module exports a vector layer to a Google Earth KML Format using "
@@ -131,9 +131,9 @@ bool COGR_Export_KML::On_Execute(void)
 		bool	bResult;
 
 		SG_RUN_MODULE(bResult, "pj_proj4", 2,
-				pModule->Get_Parameters()->Set_Parameter(SG_T("SOURCE"), pShapes)
-			&&	pModule->Get_Parameters()->Set_Parameter(SG_T("TARGET"), &Shapes)
-			&&	pModule->Get_Parameters()->Set_Parameter(SG_T("CRS_PROJ4"), SG_T("+proj=longlat +ellps=WGS84 +datum=WGS84"))
+				SG_MODULE_PARAMETER_SET("SOURCE"   , pShapes)
+			&&	SG_MODULE_PARAMETER_SET("TARGET"   , &Shapes)
+			&&	SG_MODULE_PARAMETER_SET("CRS_PROJ4", SG_T("+proj=longlat +ellps=WGS84 +datum=WGS84"))
 		);
 
 		if( bResult )
diff --git a/src/modules/io/io_gdal/ogr_export_kml.h b/src/modules/io/io_gdal/ogr_export_kml.h
index af9acad..dc58256 100644
--- a/src/modules/io/io_gdal/ogr_export_kml.h
+++ b/src/modules/io/io_gdal/ogr_export_kml.h
@@ -76,10 +76,12 @@ class COGR_Export_KML : public CSG_Module
 public:
 	COGR_Export_KML(void);
 
+	virtual CSG_String			Get_MenuPath	(void)	{	return( _TL("Shapes|Export") );	}
+
 
 protected:
 
-	virtual bool		On_Execute		(void);
+	virtual bool				On_Execute		(void);
 
 };
 
diff --git a/src/modules/io/io_gdal/ogr_import.cpp b/src/modules/io/io_gdal/ogr_import.cpp
index d855de7..bfaa0fa 100644
--- a/src/modules/io/io_gdal/ogr_import.cpp
+++ b/src/modules/io/io_gdal/ogr_import.cpp
@@ -69,14 +69,14 @@
 //---------------------------------------------------------
 COGR_Import::COGR_Import(void)
 {
-	Set_Name	(_TL("OGR: Import Vector Data"));
+	Set_Name	(_TL("Import Shapes"));
 
-	Set_Author	(SG_T("O.Conrad (c) 2008"));
+	Set_Author	("O.Conrad (c) 2008");
 
 	CSG_String	Description;
 
 	Description	= _TW(
-		"The \"GDAL Vector Data Import\" module imports vector data from various file/database formats using the "
+		"The \"OGR Vector Data Import\" module imports vector data from various file/database formats using the "
 		"\"Geospatial Data Abstraction Library\" (GDAL) by Frank Warmerdam. "
 		"For more information have a look at the GDAL homepage:\n"
 		"  <a target=\"_blank\" href=\"http://www.gdal.org/\">"
diff --git a/src/modules/io/io_gdal/ogr_import.h b/src/modules/io/io_gdal/ogr_import.h
index 60e65f9..096b62b 100644
--- a/src/modules/io/io_gdal/ogr_import.h
+++ b/src/modules/io/io_gdal/ogr_import.h
@@ -76,10 +76,12 @@ class COGR_Import : public CSG_Module
 public:
 	COGR_Import(void);
 
+	virtual CSG_String			Get_MenuPath	(void)	{	return( _TL("Shapes|Import") );	}
+
 
 protected:
 
-	virtual bool		On_Execute		(void);
+	virtual bool				On_Execute		(void);
 
 };
 
diff --git a/src/modules/io/io_grid_grib2/g2clib-1.0.4/cmplxpack.c b/src/modules/io/io_grid_grib2/g2clib-1.0.4/cmplxpack.c
deleted file mode 100644
index cea6e11..0000000
--- a/src/modules/io/io_grid_grib2/g2clib-1.0.4/cmplxpack.c
+++ /dev/null
@@ -1,78 +0,0 @@
-/**********************************************************
- * Version $Id: cmplxpack.c 911 2011-02-14 16:38:15Z reklov_w $
- *********************************************************/
-#include "grib2.h"
-
-void cmplxpack(g2float *fld,g2int ndpts, g2int idrsnum,g2int *idrstmpl,
-               unsigned char *cpack, g2int *lcpack)
-//$$$  SUBPROGRAM DOCUMENTATION BLOCK
-//                .      .    .                                       .
-// SUBPROGRAM:    cmplxpack
-//   PRGMMR: Gilbert          ORG: W/NP11    DATE: 2004-08-27
-//
-// ABSTRACT: This subroutine packs up a data field using a complex
-//   packing algorithm as defined in the GRIB2 documention.  It
-//   supports GRIB2 complex packing templates with or without
-//   spatial differences (i.e. DRTs 5.2 and 5.3).
-//   It also fills in GRIB2 Data Representation Template 5.2 or 5.3 
-//   with the appropriate values.
-//
-// PROGRAM HISTORY LOG:
-// 2004-08-27  Gilbert
-//
-// USAGE:    cmplxpack(g2float *fld,g2int ndpts, g2int idrsnum,g2int *idrstmpl,
-//             unsigned char *cpack, g2int *lcpack)
-//   INPUT ARGUMENT LIST:
-//     fld[]    - Contains the data values to pack
-//     ndpts    - The number of data values in array fld[]
-//     idrsnum  - Data Representation Template number 5.N
-//                Must equal 2 or 3.
-//     idrstmpl - Contains the array of values for Data Representation
-//                Template 5.2 or 5.3
-//                [0] = Reference value - ignored on input
-//                [1] = Binary Scale Factor
-//                [2] = Decimal Scale Factor
-//                    .
-//                    .
-//                [6] = Missing value management
-//                [7] = Primary missing value
-//                [8] = Secondary missing value
-//                    .
-//                    .
-//               [16] = Order of Spatial Differencing  ( 1 or 2 )
-//                    .
-//                    .
-//
-//   OUTPUT ARGUMENT LIST: 
-//     idrstmpl - Contains the array of values for Data Representation
-//                Template 5.3
-//                [0] = Reference value - set by compack routine.
-//                [1] = Binary Scale Factor - unchanged from input
-//                [2] = Decimal Scale Factor - unchanged from input
-//                    .
-//                    .
-//     cpack    - The packed data field (character*1 array)
-//     lcpack   - length of packed field cpack[].
-//
-// REMARKS: None
-//
-// ATTRIBUTES:
-//   LANGUAGE: C
-//   MACHINE:  IBM SP
-//
-//$$$
-{
-      
-
-      if ( idrstmpl[6] == 0 ) {       // No internal missing values
-         compack(fld,ndpts,idrsnum,idrstmpl,cpack,lcpack);
-      }
-      else if ( idrstmpl[6] == 1  ||  idrstmpl[6] == 2) {
-         misspack(fld,ndpts,idrsnum,idrstmpl,cpack,lcpack);
-      }
-      else {
-         printf("cmplxpack: Don:t recognize Missing value option.");
-         *lcpack=-1;
-      }
-
-}
diff --git a/src/modules/io/io_grid_grib2/g2clib-1.0.4/compack.c b/src/modules/io/io_grid_grib2/g2clib-1.0.4/compack.c
deleted file mode 100644
index 841323a..0000000
--- a/src/modules/io/io_grid_grib2/g2clib-1.0.4/compack.c
+++ /dev/null
@@ -1,419 +0,0 @@
-/**********************************************************
- * Version $Id: compack.c 911 2011-02-14 16:38:15Z reklov_w $
- *********************************************************/
-#include <stdlib.h>
-#include <math.h>
-#include "grib2.h"
-
-
-void compack(g2float *fld,g2int ndpts,g2int idrsnum,g2int *idrstmpl,
-             unsigned char *cpack,g2int *lcpack)
-//$$$  SUBPROGRAM DOCUMENTATION BLOCK
-//                .      .    .                                       .
-// SUBPROGRAM:    compack
-//   PRGMMR: Gilbert          ORG: W/NP11    DATE: 2002-11-07
-//
-// ABSTRACT: This subroutine packs up a data field using a complex
-//   packing algorithm as defined in the GRIB2 documention.  It
-//   supports GRIB2 complex packing templates with or without
-//   spatial differences (i.e. DRTs 5.2 and 5.3).
-//   It also fills in GRIB2 Data Representation Template 5.2 or 5.3 
-//   with the appropriate values.
-//
-// PROGRAM HISTORY LOG:
-// 2002-11-07  Gilbert
-//
-// USAGE:    void compack(g2float *fld,g2int ndpts,g2int idrsnum,
-//                g2int *idrstmpl,unsigned char *cpack,g2int *lcpack)
-//
-//   INPUT ARGUMENTS:
-//     fld[]    - Contains the data values to pack
-//     ndpts    - The number of data values in array fld[]
-//     idrsnum  - Data Representation Template number 5.N
-//                Must equal 2 or 3.
-//     idrstmpl - Contains the array of values for Data Representation
-//                Template 5.2 or 5.3
-//                [0] = Reference value - ignored on input
-//                [1] = Binary Scale Factor
-//                [2] = Decimal Scale Factor
-//                    .
-//                    .
-//                [6] = Missing value management
-//                [7] = Primary missing value
-//                [8] = Secondary missing value
-//                    .
-//                    .
-//               [16] = Order of Spatial Differencing  ( 1 or 2 )
-//                    .
-//                    .
-//
-//   OUTPUT ARGUMENTS: 
-//     idrstmpl - Contains the array of values for Data Representation
-//                Template 5.3
-//                [0] = Reference value - set by compack routine.
-//                [1] = Binary Scale Factor - unchanged from input
-//                [2] = Decimal Scale Factor - unchanged from input
-//                    .
-//                    .
-//     cpack    - The packed data field
-//     lcpack   - length of packed field cpack.
-//
-// REMARKS: None
-//
-// ATTRIBUTES:
-//   LANGUAGE: C
-//   MACHINE:
-//
-//$$$
-{
-
-      static g2int zero=0;
-      g2int  *ifld,*gref,*glen,*gwidth;
-      g2int  *jmin, *jmax, *lbit;
-      g2int  i,j,n,nbits,imin,imax,left;
-      g2int  isd,itemp,ilmax,ngwidthref=0,nbitsgwidth=0;
-      g2int  nglenref=0,nglenlast=0,iofst,ival1,ival2;
-      g2int  minsd,nbitsd=0,maxorig,nbitorig,ngroups;
-      g2int  lg,ng,igmax,iwmax,nbitsgref;
-      g2int  glength,grpwidth,nbitsglen=0;
-      g2int  kfildo, minpk, inc, maxgrps, ibit, jbit, kbit, novref, lbitref;
-      g2int  missopt, miss1, miss2, ier;
-      g2float  bscale,dscale,rmax,rmin,temp;
-      static g2int simple_alg = 0;
-      static g2float alog2=0.69314718;       //  ln(2.0)
-      static g2int one=1;
-
-      bscale=int_power(2.0,-idrstmpl[1]);
-      dscale=int_power(10.0,idrstmpl[2]);
-//
-//  Find max and min values in the data
-//
-      rmax=fld[0];
-      rmin=fld[0];
-      for (j=1;j<ndpts;j++) {
-        if (fld[j] > rmax) rmax=fld[j];
-        if (fld[j] < rmin) rmin=fld[j];
-      }
-
-//
-//  If max and min values are not equal, pack up field.
-//  If they are equal, we have a constant field, and the reference
-//  value (rmin) is the value for each point in the field and
-//  set nbits to 0.
-//
-      if (rmin != rmax) {
-        iofst=0;
-        ifld=calloc(ndpts,sizeof(g2int));
-        gref=calloc(ndpts,sizeof(g2int));
-        gwidth=calloc(ndpts,sizeof(g2int));
-        glen=calloc(ndpts,sizeof(g2int));
-        //
-        //  Scale original data
-        //
-        if (idrstmpl[1] == 0) {        //  No binary scaling
-           imin=(g2int)rint(rmin*dscale);
-           //imax=(g2int)rint(rmax*dscale);
-           rmin=(g2float)imin;
-           for (j=0;j<ndpts;j++) 
-              ifld[j]=(g2int)rint(fld[j]*dscale)-imin;
-        }
-        else {                             //  Use binary scaling factor
-           rmin=rmin*dscale;
-           //rmax=rmax*dscale;
-           for (j=0;j<ndpts;j++) 
-             ifld[j]=(g2int)rint(((fld[j]*dscale)-rmin)*bscale);
-        }
-        //
-        //  Calculate Spatial differences, if using DRS Template 5.3
-        //
-        if (idrsnum == 3) {        // spatial differences
-           if (idrstmpl[16]!=1 && idrstmpl[16]!=2) idrstmpl[16]=1;
-           if (idrstmpl[16] == 1) {      // first order
-              ival1=ifld[0];
-              for (j=ndpts-1;j>0;j--) 
-                 ifld[j]=ifld[j]-ifld[j-1];
-              ifld[0]=0;
-           }
-           else if (idrstmpl[16] == 2) {      // second order
-              ival1=ifld[0];
-              ival2=ifld[1];
-              for (j=ndpts-1;j>1;j--) 
-                 ifld[j]=ifld[j]-(2*ifld[j-1])+ifld[j-2];
-              ifld[0]=0;
-              ifld[1]=0;
-           }
-           //
-           //  subtract min value from spatial diff field
-           //
-           isd=idrstmpl[16];
-           minsd=ifld[isd];
-           for (j=isd;j<ndpts;j++)  if ( ifld[j] < minsd ) minsd=ifld[j];
-           for (j=isd;j<ndpts;j++)  ifld[j]=ifld[j]-minsd;
-           //
-           //   find num of bits need to store minsd and add 1 extra bit
-           //   to indicate sign
-           //
-           temp=log((double)(abs(minsd)+1))/alog2;
-           nbitsd=(g2int)ceil(temp)+1;
-           //
-           //   find num of bits need to store ifld[0] ( and ifld[1]
-           //   if using 2nd order differencing )
-           //
-           maxorig=ival1;
-           if (idrstmpl[16]==2 && ival2>ival1) maxorig=ival2;
-           temp=log((double)(maxorig+1))/alog2;
-           nbitorig=(g2int)ceil(temp)+1;
-           if (nbitorig > nbitsd) nbitsd=nbitorig;
-           //   increase number of bits to even multiple of 8 ( octet )
-           if ( (nbitsd%8) != 0) nbitsd=nbitsd+(8-(nbitsd%8));
-           //
-           //  Store extra spatial differencing info into the packed
-           //  data section.
-           //
-           if (nbitsd != 0) {
-              //   pack first original value
-              if (ival1 >= 0) {
-                 sbit(cpack,&ival1,iofst,nbitsd);
-                 iofst=iofst+nbitsd;
-              }
-              else {
-                 sbit(cpack,&one,iofst,1);
-                 iofst=iofst+1;
-                 itemp=abs(ival1);
-                 sbit(cpack,&itemp,iofst,nbitsd-1);
-                 iofst=iofst+nbitsd-1;
-              }
-              if (idrstmpl[16] == 2) {
-               //  pack second original value
-                 if (ival2 >= 0) {
-                    sbit(cpack,&ival2,iofst,nbitsd);
-                    iofst=iofst+nbitsd;
-                 }
-                 else {
-                    sbit(cpack,&one,iofst,1);
-                    iofst=iofst+1;
-                    itemp=abs(ival2);
-                    sbit(cpack,&itemp,iofst,nbitsd-1);
-                    iofst=iofst+nbitsd-1;
-                 }
-              }
-              //  pack overall min of spatial differences
-              if (minsd >= 0) {
-                 sbit(cpack,&minsd,iofst,nbitsd);
-                 iofst=iofst+nbitsd;
-              }
-              else {
-                 sbit(cpack,&one,iofst,1);
-                 iofst=iofst+1;
-                 itemp=abs(minsd);
-                 sbit(cpack,&itemp,iofst,nbitsd-1);
-                 iofst=iofst+nbitsd-1;
-              }
-           }
-           //printf("SDp %ld %ld %ld %ld\n",ival1,ival2,minsd,nbitsd);
-        }     //  end of spatial diff section
-        //
-        //   Determine Groups to be used.
-        //
-        if ( simple_alg == 1 ) {
-           //  set group length to 10;  calculate number of groups
-           //  and length of last group
-           ngroups=ndpts/10;
-           for (j=0;j<ngroups;j++) glen[j]=10;
-           itemp=ndpts%10;
-           if (itemp != 0) {
-              ngroups=ngroups+1;
-              glen[ngroups-1]=itemp;
-           }
-        }
-        else {
-           // Use Dr. Glahn's algorithm for determining grouping.
-           //
-           kfildo=6;
-           minpk=10;
-           inc=1;
-           maxgrps=(ndpts/minpk)+1;
-           jmin = calloc(maxgrps,sizeof(g2int));
-           jmax = calloc(maxgrps,sizeof(g2int));
-           lbit = calloc(maxgrps,sizeof(g2int));
-           missopt=0;
-           pack_gp(&kfildo,ifld,&ndpts,&missopt,&minpk,&inc,&miss1,&miss2,
-                        jmin,jmax,lbit,glen,&maxgrps,&ngroups,&ibit,&jbit,
-                        &kbit,&novref,&lbitref,&ier);
-           //print *,'SAGier = ',ier,ibit,jbit,kbit,novref,lbitref
-           for ( ng=0; ng<ngroups; ng++) glen[ng]=glen[ng]+novref;
-           free(jmin);
-           free(jmax);
-           free(lbit);
-        }
-        //  
-        //  For each group, find the group's reference value
-        //  and the number of bits needed to hold the remaining values
-        //
-        n=0;
-        for (ng=0;ng<ngroups;ng++) {
-           //    find max and min values of group
-           gref[ng]=ifld[n];
-           imax=ifld[n];
-           j=n+1;
-           for (lg=1;lg<glen[ng];lg++) {
-              if (ifld[j] < gref[ng]) gref[ng]=ifld[j]; 
-              if (ifld[j] > imax) imax=ifld[j];
-              j++;
-           }
-           //   calc num of bits needed to hold data
-           if ( gref[ng] != imax ) {
-              temp=log((double)(imax-gref[ng]+1))/alog2;
-              gwidth[ng]=(g2int)ceil(temp);
-           }
-           else 
-              gwidth[ng]=0;
-           //   Subtract min from data
-           j=n;
-           for (lg=0;lg<glen[ng];lg++) {
-              ifld[j]=ifld[j]-gref[ng];
-              j++;
-           }
-           //   increment fld array counter
-           n=n+glen[ng];
-        }
-        //  
-        //  Find max of the group references and calc num of bits needed 
-        //  to pack each groups reference value, then
-        //  pack up group reference values
-        //
-        igmax=gref[0];
-        for (j=1;j<ngroups;j++) if (gref[j] > igmax) igmax=gref[j];
-        if (igmax != 0) {
-           temp=log((double)(igmax+1))/alog2;
-           nbitsgref=(g2int)ceil(temp);
-           sbits(cpack,gref,iofst,nbitsgref,0,ngroups);
-           itemp=nbitsgref*ngroups;
-           iofst=iofst+itemp;
-           //         Pad last octet with Zeros, if necessary,
-           if ( (itemp%8) != 0) {
-              left=8-(itemp%8);
-              sbit(cpack,&zero,iofst,left);
-              iofst=iofst+left;
-           }
-        }
-        else
-           nbitsgref=0;
-        //
-        //  Find max/min of the group widths and calc num of bits needed
-        //  to pack each groups width value, then
-        //  pack up group width values
-        //
-        iwmax=gwidth[0];
-        ngwidthref=gwidth[0];
-        for (j=1;j<ngroups;j++) {
-           if (gwidth[j] > iwmax) iwmax=gwidth[j];
-           if (gwidth[j] < ngwidthref) ngwidthref=gwidth[j];
-        }
-        if (iwmax != ngwidthref) {
-           temp=log((double)(iwmax-ngwidthref+1))/alog2;
-           nbitsgwidth=(g2int)ceil(temp);
-           for (i=0;i<ngroups;i++) 
-              gwidth[i]=gwidth[i]-ngwidthref;
-           sbits(cpack,gwidth,iofst,nbitsgwidth,0,ngroups);
-           itemp=nbitsgwidth*ngroups;
-           iofst=iofst+itemp;
-           //         Pad last octet with Zeros, if necessary,
-           if ( (itemp%8) != 0) {
-              left=8-(itemp%8);
-              sbit(cpack,&zero,iofst,left);
-              iofst=iofst+left;
-           }
-        }
-        else {
-           nbitsgwidth=0;
-           for (i=0;i<ngroups;i++) gwidth[i]=0;
-        }
-        //
-        //  Find max/min of the group lengths and calc num of bits needed
-        //  to pack each groups length value, then
-        //  pack up group length values
-        //
-        //write(77,*)'GLENS: ',(glen(j),j=1,ngroups)
-        ilmax=glen[0];
-        nglenref=glen[0];
-        for (j=1;j<ngroups-1;j++) {
-           if (glen[j] > ilmax) ilmax=glen[j];
-           if (glen[j] < nglenref) nglenref=glen[j];
-        }
-        nglenlast=glen[ngroups-1];
-        if (ilmax != nglenref) {
-           temp=log((double)(ilmax-nglenref+1))/alog2;
-           nbitsglen=(g2int)ceil(temp);
-           for (i=0;i<ngroups-1;i++)  glen[i]=glen[i]-nglenref;
-           sbits(cpack,glen,iofst,nbitsglen,0,ngroups);
-           itemp=nbitsglen*ngroups;
-           iofst=iofst+itemp;
-           //         Pad last octet with Zeros, if necessary,
-           if ( (itemp%8) != 0) {
-              left=8-(itemp%8);
-              sbit(cpack,&zero,iofst,left);
-              iofst=iofst+left;
-           }
-        }
-        else {
-           nbitsglen=0;
-           for (i=0;i<ngroups;i++) glen[i]=0;
-        }
-        //
-        //  For each group, pack data values
-        //
-        n=0;
-        for (ng=0;ng<ngroups;ng++) {
-           glength=glen[ng]+nglenref;
-           if (ng == (ngroups-1) ) glength=nglenlast;
-           grpwidth=gwidth[ng]+ngwidthref;
-           if ( grpwidth != 0 ) {
-              sbits(cpack,ifld+n,iofst,grpwidth,0,glength);
-              iofst=iofst+(grpwidth*glength);
-           }
-           n=n+glength;
-        }
-        //         Pad last octet with Zeros, if necessary,
-        if ( (iofst%8) != 0) {
-           left=8-(iofst%8);
-           sbit(cpack,&zero,iofst,left);
-           iofst=iofst+left;
-        }
-        *lcpack=iofst/8;
-        //
-        if ( ifld!=0 ) free(ifld);
-        if ( gref!=0 ) free(gref);
-        if ( gwidth!=0 ) free(gwidth);
-        if ( glen!=0 ) free(glen);
-      }
-      else {          //   Constant field ( max = min )
-        nbits=0;
-        *lcpack=0;
-        nbitsgref=0;
-        ngroups=0;
-      }
-
-//
-//  Fill in ref value and number of bits in Template 5.2
-//
-      mkieee(&rmin,idrstmpl+0,1);   // ensure reference value is IEEE format
-      idrstmpl[3]=nbitsgref;
-      idrstmpl[4]=0;         // original data were reals
-      idrstmpl[5]=1;         // general group splitting
-      idrstmpl[6]=0;         // No internal missing values
-      idrstmpl[7]=0;         // Primary missing value
-      idrstmpl[8]=0;         // secondary missing value
-      idrstmpl[9]=ngroups;          // Number of groups
-      idrstmpl[10]=ngwidthref;       // reference for group widths
-      idrstmpl[11]=nbitsgwidth;      // num bits used for group widths
-      idrstmpl[12]=nglenref;         // Reference for group lengths
-      idrstmpl[13]=1;                // length increment for group lengths
-      idrstmpl[14]=nglenlast;        // True length of last group
-      idrstmpl[15]=nbitsglen;        // num bits used for group lengths
-      if (idrsnum == 3) {
-         idrstmpl[17]=nbitsd/8;      // num bits used for extra spatial
-                                     // differencing values
-      }
-
-}
diff --git a/src/modules/io/io_grid_grib2/g2clib-1.0.4/comunpack.c b/src/modules/io/io_grid_grib2/g2clib-1.0.4/comunpack.c
deleted file mode 100644
index 27c76c6..0000000
--- a/src/modules/io/io_grid_grib2/g2clib-1.0.4/comunpack.c
+++ /dev/null
@@ -1,333 +0,0 @@
-/**********************************************************
- * Version $Id: comunpack.c 911 2011-02-14 16:38:15Z reklov_w $
- *********************************************************/
-#include <stdio.h>
-#include <stdlib.h>
-#include "grib2.h"
-
-
-int comunpack(unsigned char *cpack,g2int lensec,g2int idrsnum,g2int *idrstmpl,g2int ndpts,g2float *fld)
-////$$$  SUBPROGRAM DOCUMENTATION BLOCK
-//                .      .    .                                       .
-// SUBPROGRAM:    comunpack
-//   PRGMMR: Gilbert          ORG: W/NP11    DATE: 2002-10-29
-//
-// ABSTRACT: This subroutine unpacks a data field that was packed using a
-//   complex packing algorithm as defined in the GRIB2 documention,
-//   using info from the GRIB2 Data Representation Template 5.2 or 5.3.
-//   Supports GRIB2 complex packing templates with or without
-//   spatial differences (i.e. DRTs 5.2 and 5.3).
-//
-// PROGRAM HISTORY LOG:
-// 2002-10-29  Gilbert
-// 2004-12-16  Gilbert  -  Added test ( provided by Arthur Taylor/MDL )
-//                         to verify that group widths and lengths are
-//                         consistent with section length.
-//
-// USAGE:    int comunpack(unsigned char *cpack,g2int lensec,g2int idrsnum,
-//                         g2int *idrstmpl, g2int ndpts,g2float *fld)
-//   INPUT ARGUMENT LIST:
-//     cpack    - pointer to the packed data field.
-//     lensec   - length of section 7 (used for error checking).
-//     idrsnum  - Data Representation Template number 5.N
-//                Must equal 2 or 3.
-//     idrstmpl - pointer to the array of values for Data Representation
-//                Template 5.2 or 5.3
-//     ndpts    - The number of data values to unpack
-//
-//   OUTPUT ARGUMENT LIST:
-//     fld      - Contains the unpacked data values.  fld must be allocated
-//                with at least ndpts*sizeof(g2float) bytes before
-//                calling this routine.
-//
-// REMARKS: None
-//
-// ATTRIBUTES:
-//   LANGUAGE: C
-//   MACHINE: 
-//
-//$$$//
-{
-
-      g2int   nbitsd=0,isign;
-      g2int  j,iofst,ival1,ival2,minsd,itemp,l,k,n,non=0;
-      g2int  *ifld,*ifldmiss=0;
-      g2int  *gref,*gwidth,*glen;
-      g2int  itype,ngroups,nbitsgref,nbitsgwidth,nbitsglen;
-      g2int  msng1,msng2;
-      g2float ref,bscale,dscale,rmiss1,rmiss2;
-      g2int totBit, totLen;
-
-      //printf('IDRSTMPL: ',(idrstmpl(j),j=1,16)
-      rdieee(idrstmpl+0,&ref,1);
-//      printf("SAGTref: %f\n",ref);
-      bscale = (g2float)int_power(2.0,idrstmpl[1]);
-      dscale = (g2float)int_power(10.0,-idrstmpl[2]);
-      nbitsgref = idrstmpl[3];
-      itype = idrstmpl[4];
-      ngroups = idrstmpl[9];
-      nbitsgwidth = idrstmpl[11];
-      nbitsglen = idrstmpl[15];
-      if (idrsnum == 3)
-         nbitsd=idrstmpl[17]*8;
-
-      //   Constant field
-
-      if (ngroups == 0) {
-         for (j=0;j<ndpts;j++) fld[j]=ref;
-         return(0);
-      }
-
-      iofst=0;
-      ifld=(g2int *)calloc(ndpts,sizeof(g2int));
-      //printf("ALLOC ifld: %d %x\n",(int)ndpts,ifld);
-      gref=(g2int *)calloc(ngroups,sizeof(g2int));
-      //printf("ALLOC gref: %d %x\n",(int)ngroups,gref);
-      gwidth=(g2int *)calloc(ngroups,sizeof(g2int));
-      //printf("ALLOC gwidth: %d %x\n",(int)ngroups,gwidth);
-//
-//  Get missing values, if supplied
-//
-      if ( idrstmpl[6] == 1 ) {
-         if (itype == 0) 
-            rdieee(idrstmpl+7,&rmiss1,1);
-         else 
-            rmiss1=(g2float)idrstmpl[7];
-      }
-      if ( idrstmpl[6] == 2 ) {
-         if (itype == 0) {
-            rdieee(idrstmpl+7,&rmiss1,1);
-            rdieee(idrstmpl+8,&rmiss2,1);
-         }
-         else {
-            rmiss1=(g2float)idrstmpl[7];
-            rmiss2=(g2float)idrstmpl[8];
-         }
-      }
-      
-      //printf("RMISSs: %f %f %f \n",rmiss1,rmiss2,ref);
-// 
-//  Extract Spatial differencing values, if using DRS Template 5.3
-//
-      if (idrsnum == 3) {
-         if (nbitsd != 0) {
-              gbit(cpack,&isign,iofst,1);
-              iofst=iofst+1;
-              gbit(cpack,&ival1,iofst,nbitsd-1);
-              iofst=iofst+nbitsd-1;
-              if (isign == 1) ival1=-ival1;
-              if (idrstmpl[16] == 2) {
-                 gbit(cpack,&isign,iofst,1);
-                 iofst=iofst+1;
-                 gbit(cpack,&ival2,iofst,nbitsd-1);
-                 iofst=iofst+nbitsd-1;
-                 if (isign == 1) ival2=-ival2;
-              }
-              gbit(cpack,&isign,iofst,1);
-              iofst=iofst+1;
-              gbit(cpack,&minsd,iofst,nbitsd-1);
-              iofst=iofst+nbitsd-1;
-              if (isign == 1) minsd=-minsd;
-         }
-         else {
-              ival1=0;
-              ival2=0;
-              minsd=0;
-         }
-       //printf("SDu %ld %ld %ld %ld \n",ival1,ival2,minsd,nbitsd);
-      }
-//
-//  Extract Each Group's reference value
-//
-      //printf("SAG1: %ld %ld %ld \n",nbitsgref,ngroups,iofst);
-      if (nbitsgref != 0) {
-         gbits(cpack,gref+0,iofst,nbitsgref,0,ngroups);
-         itemp=nbitsgref*ngroups;
-         iofst=iofst+itemp;
-         if (itemp%8 != 0) iofst=iofst+(8-(itemp%8));
-      }
-      else {
-         for (j=0;j<ngroups;j++)
-              gref[j]=0;
-      }
-//
-//  Extract Each Group's bit width
-//
-      //printf("SAG2: %ld %ld %ld %ld \n",nbitsgwidth,ngroups,iofst,idrstmpl[10]);
-      if (nbitsgwidth != 0) {
-         gbits(cpack,gwidth+0,iofst,nbitsgwidth,0,ngroups);
-         itemp=nbitsgwidth*ngroups;
-         iofst=iofst+itemp;
-         if (itemp%8 != 0) iofst=iofst+(8-(itemp%8));
-      }
-      else {
-         for (j=0;j<ngroups;j++)
-                gwidth[j]=0;
-      }
-
-      for (j=0;j<ngroups;j++)
-          gwidth[j]=gwidth[j]+idrstmpl[10];
-      
-//
-//  Extract Each Group's length (number of values in each group)
-//
-      glen=(g2int *)calloc(ngroups,sizeof(g2int));
-      //printf("ALLOC glen: %d %x\n",(int)ngroups,glen);
-      //printf("SAG3: %ld %ld %ld %ld %ld \n",nbitsglen,ngroups,iofst,idrstmpl[13],idrstmpl[12]);
-      if (nbitsglen != 0) {
-         gbits(cpack,glen,iofst,nbitsglen,0,ngroups);
-         itemp=nbitsglen*ngroups;
-         iofst=iofst+itemp;
-         if (itemp%8 != 0) iofst=iofst+(8-(itemp%8));
-      }
-      else {
-         for (j=0;j<ngroups;j++)
-              glen[j]=0;
-      }
-      for (j=0;j<ngroups;j++) 
-           glen[j]=(glen[j]*idrstmpl[13])+idrstmpl[12];
-      glen[ngroups-1]=idrstmpl[14];
-//
-//  Test to see if the group widths and lengths are consistent with number of
-//  values, and length of section 7.
-//
-      totBit = 0;
-      totLen = 0;
-      for (j=0;j<ngroups;j++) {
-        totBit += (gwidth[j]*glen[j]);
-        totLen += glen[j];
-      }
-      if (totLen != ndpts) {
-        return 1;
-      }
-      if (totBit / 8. > lensec) {
-        return 1;
-      }
-//
-//  For each group, unpack data values
-//
-      if ( idrstmpl[6] == 0 ) {        // no missing values
-         n=0;
-         for (j=0;j<ngroups;j++) {
-           if (gwidth[j] != 0) {
-             gbits(cpack,ifld+n,iofst,gwidth[j],0,glen[j]);
-             for (k=0;k<glen[j];k++) {
-               ifld[n]=ifld[n]+gref[j];
-               n=n+1;
-             }
-           }
-           else {
-             for (l=n;l<n+glen[j];l++) ifld[l]=gref[j];
-             n=n+glen[j];
-           }
-           iofst=iofst+(gwidth[j]*glen[j]);
-         }
-      }
-      else if ( idrstmpl[6]==1 || idrstmpl[6]==2 ) {
-         // missing values included
-         ifldmiss=(g2int *)malloc(ndpts*sizeof(g2int));
-         //printf("ALLOC ifldmiss: %d %x\n",(int)ndpts,ifldmiss);
-         //for (j=0;j<ndpts;j++) ifldmiss[j]=0;
-         n=0;
-         non=0;
-         for (j=0;j<ngroups;j++) {
-           //printf(" SAGNGP %d %d %d %d\n",j,gwidth[j],glen[j],gref[j]);
-           if (gwidth[j] != 0) {
-             msng1=(g2int)int_power(2.0,gwidth[j])-1;
-             msng2=msng1-1;
-             gbits(cpack,ifld+n,iofst,gwidth[j],0,glen[j]);
-             iofst=iofst+(gwidth[j]*glen[j]);
-             for (k=0;k<glen[j];k++) {
-               if (ifld[n] == msng1) {
-                  ifldmiss[n]=1;
-                  //ifld[n]=0;
-               }
-               else if (idrstmpl[6]==2 && ifld[n]==msng2) {
-                  ifldmiss[n]=2;
-                  //ifld[n]=0;
-               }
-               else {
-                  ifldmiss[n]=0;
-                  ifld[non++]=ifld[n]+gref[j];
-               }
-               n++;
-             }
-           }
-           else {
-             msng1=(g2int)int_power(2.0,nbitsgref)-1;
-             msng2=msng1-1;
-             if (gref[j] == msng1) {
-                for (l=n;l<n+glen[j];l++) ifldmiss[l]=1;
-             }
-             else if (idrstmpl[6]==2 && gref[j]==msng2) {
-                for (l=n;l<n+glen[j];l++) ifldmiss[l]=2;
-             }
-             else {
-                for (l=n;l<n+glen[j];l++) ifldmiss[l]=0;
-                for (l=non;l<non+glen[j];l++) ifld[l]=gref[j];
-                non += glen[j];
-             }
-             n=n+glen[j];
-           }
-         }
-      }
-
-      if ( gref != 0 ) free(gref);
-      if ( gwidth != 0 ) free(gwidth);
-      if ( glen != 0 ) free(glen);
-//
-//  If using spatial differences, add overall min value, and
-//  sum up recursively
-//
-      //printf("SAGod: %ld %ld\n",idrsnum,idrstmpl[16]);
-      if (idrsnum == 3) {         // spatial differencing
-         if (idrstmpl[16] == 1) {      // first order
-            ifld[0]=ival1;
-            if ( idrstmpl[6] == 0 ) itemp=ndpts;        // no missing values
-            else  itemp=non;
-            for (n=1;n<itemp;n++) {
-               ifld[n]=ifld[n]+minsd;
-               ifld[n]=ifld[n]+ifld[n-1];
-            }
-         }
-         else if (idrstmpl[16] == 2) {    // second order
-            ifld[0]=ival1;
-            ifld[1]=ival2;
-            if ( idrstmpl[6] == 0 ) itemp=ndpts;        // no missing values
-            else  itemp=non;
-            for (n=2;n<itemp;n++) {
-               ifld[n]=ifld[n]+minsd;
-               ifld[n]=ifld[n]+(2*ifld[n-1])-ifld[n-2];
-            }
-         }
-      }
-//
-//  Scale data back to original form
-//
-      //printf("SAGT: %f %f %f\n",ref,bscale,dscale);
-      if ( idrstmpl[6] == 0 ) {        // no missing values
-         for (n=0;n<ndpts;n++) {
-            fld[n]=(((g2float)ifld[n]*bscale)+ref)*dscale;
-         }
-      }
-      else if ( idrstmpl[6]==1 || idrstmpl[6]==2 ) {
-         // missing values included
-         non=0;
-         for (n=0;n<ndpts;n++) {
-            if ( ifldmiss[n] == 0 ) {
-               fld[n]=(((g2float)ifld[non++]*bscale)+ref)*dscale;
-               //printf(" SAG %d %f %d %f %f %f\n",n,fld[n],ifld[non-1],bscale,ref,dscale);
-            }
-            else if ( ifldmiss[n] == 1 ) 
-               fld[n]=rmiss1;
-            else if ( ifldmiss[n] == 2 ) 
-               fld[n]=rmiss2;
-         }
-         if ( ifldmiss != 0 ) free(ifldmiss);
-      }
-
-      if ( ifld != 0 ) free(ifld);
-
-      return(0);
-      
-}
diff --git a/src/modules/io/io_grid_grib2/g2clib-1.0.4/dec_jpeg2000.c b/src/modules/io/io_grid_grib2/g2clib-1.0.4/dec_jpeg2000.c
deleted file mode 100644
index 9d76962..0000000
--- a/src/modules/io/io_grid_grib2/g2clib-1.0.4/dec_jpeg2000.c
+++ /dev/null
@@ -1,147 +0,0 @@
-/**********************************************************
- * Version $Id: dec_jpeg2000.c 911 2011-02-14 16:38:15Z reklov_w $
- *********************************************************/
-#ifndef USE_JPEG2000
-#include "grib2.h"
- int dec_jpeg2000(char *injpc,g2int bufsize,g2int *outfld)
- {	return( 0 );	}
-#else   /* USE_JPEG2000 */
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include "grib2.h"
-#include "jasper/jasper.h"
-#define JAS_1_700_2
-
-
-   int dec_jpeg2000(char *injpc,g2int bufsize,g2int *outfld)
-/*$$$  SUBPROGRAM DOCUMENTATION BLOCK
-*                .      .    .                                       .
-* SUBPROGRAM:    dec_jpeg2000      Decodes JPEG2000 code stream
-*   PRGMMR: Gilbert          ORG: W/NP11     DATE: 2002-12-02
-*
-* ABSTRACT: This Function decodes a JPEG2000 code stream specified in the
-*   JPEG2000 Part-1 standard (i.e., ISO/IEC 15444-1) using JasPer 
-*   Software version 1.500.4 (or 1.700.2) written by the University of British
-*   Columbia and Image Power Inc, and others.
-*   JasPer is available at http://www.ece.uvic.ca/~mdadams/jasper/.
-*
-* PROGRAM HISTORY LOG:
-* 2002-12-02  Gilbert
-*
-* USAGE:     int dec_jpeg2000(char *injpc,g2int bufsize,g2int *outfld)
-*
-*   INPUT ARGUMENTS:
-*      injpc - Input JPEG2000 code stream.
-*    bufsize - Length (in bytes) of the input JPEG2000 code stream.
-*
-*   OUTPUT ARGUMENTS:
-*     outfld - Output matrix of grayscale image values.
-*
-*   RETURN VALUES :
-*          0 = Successful decode
-*         -3 = Error decode jpeg2000 code stream.
-*         -5 = decoded image had multiple color components.
-*              Only grayscale is expected.
-*
-* REMARKS:
-*
-*      Requires JasPer Software version 1.500.4 or 1.700.2
-*
-* ATTRIBUTES:
-*   LANGUAGE: C
-*   MACHINE:  IBM SP
-*
-*$$$*/
-
-{
-    int ier;
-    g2int i,j,k;
-    jas_image_t *image=0;
-    jas_stream_t *jpcstream;
-    jas_image_cmpt_t *pcmpt;
-    char *opts=0;
-    jas_matrix_t *data;
-
-//    jas_init();
-
-    ier=0;
-//   
-//     Create jas_stream_t containing input JPEG200 codestream in memory.
-//       
-
-    jpcstream=jas_stream_memopen(injpc,bufsize);
-
-//   
-//     Decode JPEG200 codestream into jas_image_t structure.
-//       
-    image=jpc_decode(jpcstream,opts);
-    if ( image == 0 ) {
-       printf(" jpc_decode return = %d \n",ier);
-       return -3;
-    }
-    
-    pcmpt=image->cmpts_[0];
-/*
-    printf(" SAGOUT DECODE:\n");
-    printf(" tlx %d \n",image->tlx_);
-    printf(" tly %d \n",image->tly_);
-    printf(" brx %d \n",image->brx_);
-    printf(" bry %d \n",image->bry_);
-    printf(" numcmpts %d \n",image->numcmpts_);
-    printf(" maxcmpts %d \n",image->maxcmpts_);
-#ifdef JAS_1_500_4
-    printf(" colormodel %d \n",image->colormodel_);
-#endif
-#ifdef JAS_1_700_2
-    printf(" colorspace %d \n",image->clrspc_);
-#endif
-    printf(" inmem %d \n",image->inmem_);
-    printf(" COMPONENT:\n");
-    printf(" tlx %d \n",pcmpt->tlx_);
-    printf(" tly %d \n",pcmpt->tly_);
-    printf(" hstep %d \n",pcmpt->hstep_);
-    printf(" vstep %d \n",pcmpt->vstep_);
-    printf(" width %d \n",pcmpt->width_);
-    printf(" height %d \n",pcmpt->height_);
-    printf(" prec %d \n",pcmpt->prec_);
-    printf(" sgnd %d \n",pcmpt->sgnd_);
-    printf(" cps %d \n",pcmpt->cps_);
-#ifdef JAS_1_700_2
-    printf(" type %d \n",pcmpt->type_);
-#endif
-*/
-
-//   Expecting jpeg2000 image to be grayscale only.
-//   No color components.
-//
-    if (image->numcmpts_ != 1 ) {
-       printf("dec_jpeg2000: Found color image.  Grayscale expected.\n");
-       return (-5);
-    }
-
-// 
-//    Create a data matrix of grayscale image values decoded from
-//    the jpeg2000 codestream.
-//
-    data=jas_matrix_create(jas_image_height(image), jas_image_width(image));
-    jas_image_readcmpt(image,0,0,0,jas_image_width(image),
-                       jas_image_height(image),data);
-//
-//    Copy data matrix to output integer array.
-//
-    k=0;
-    for (i=0;i<pcmpt->height_;i++) 
-      for (j=0;j<pcmpt->width_;j++) 
-        outfld[k++]=data->rows_[i][j];
-//
-//     Clean up JasPer work structures.
-//
-    jas_matrix_destroy(data);
-    ier=jas_stream_close(jpcstream);
-    jas_image_destroy(image);
-
-    return 0;
-
-}
-#endif   /* USE_JPEG2000 */
diff --git a/src/modules/io/io_grid_grib2/g2clib-1.0.4/dec_png.c b/src/modules/io/io_grid_grib2/g2clib-1.0.4/dec_png.c
deleted file mode 100644
index 28161af..0000000
--- a/src/modules/io/io_grid_grib2/g2clib-1.0.4/dec_png.c
+++ /dev/null
@@ -1,144 +0,0 @@
-/**********************************************************
- * Version $Id: dec_png.c 911 2011-02-14 16:38:15Z reklov_w $
- *********************************************************/
-#ifndef USE_PNG
-#include "grib2.h"
- int dec_png(unsigned char *pngbuf,g2int *width,g2int *height,char *cout)
- {	return( 0 );	}
-#else   /* USE_PNG */
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <png.h>
-#include "grib2.h"
-
-
-struct png_stream {
-   unsigned char *stream_ptr;     /*  location to write PNG stream  */
-   g2int stream_len;               /*  number of bytes written       */
-};
-typedef struct png_stream png_stream;
-
-void user_read_data(png_structp , png_bytep , png_uint_32 );
-
-void user_read_data(png_structp png_ptr,png_bytep data, png_uint_32 length)
-/*
-        Custom read function used so that libpng will read a PNG stream
-        from memory instead of a file on disk.
-*/
-{
-     char *ptr;
-     g2int offset;
-     png_stream *mem;
-
-     mem=(png_stream *)png_get_io_ptr(png_ptr);
-     ptr=(void *)mem->stream_ptr;
-     offset=mem->stream_len;
-/*     printf("SAGrd %ld %ld %x\n",offset,length,ptr);  */
-     memcpy(data,ptr+offset,length);
-     mem->stream_len += length;
-}
-
-
-
-int dec_png(unsigned char *pngbuf,g2int *width,g2int *height,char *cout)
-{
-    int interlace,color,compres,filter,bit_depth;
-    g2int j,k,n,bytes,clen;
-    png_structp png_ptr;
-    png_infop info_ptr,end_info;
-    png_bytepp row_pointers;
-    png_stream read_io_ptr;
-
-/*  check if stream is a valid PNG format   */
-
-    if ( png_sig_cmp(pngbuf,0,8) != 0) 
-       return (-3);
-
-/* create and initialize png_structs  */
-
-    png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, (png_voidp)NULL, 
-                                      NULL, NULL);
-    if (!png_ptr)
-       return (-1);
-
-    info_ptr = png_create_info_struct(png_ptr);
-    if (!info_ptr)
-    {
-       png_destroy_read_struct(&png_ptr,(png_infopp)NULL,(png_infopp)NULL);
-       return (-2);
-    }
-
-    end_info = png_create_info_struct(png_ptr);
-    if (!end_info)
-    {
-       png_destroy_read_struct(&png_ptr,(png_infopp)info_ptr,(png_infopp)NULL);
-       return (-2);
-    }
-
-/*     Set Error callback   */
-
-    if (setjmp(png_jmpbuf(png_ptr)))
-    {
-       png_destroy_read_struct(&png_ptr, &info_ptr,&end_info);
-       return (-3);
-    }
-
-/*    Initialize info for reading PNG stream from memory   */
-
-    read_io_ptr.stream_ptr=(png_voidp)pngbuf;
-    read_io_ptr.stream_len=0;
-
-/*    Set new custom read function    */
-
-    png_set_read_fn(png_ptr,(voidp)&read_io_ptr,(png_rw_ptr)user_read_data);
-/*     png_init_io(png_ptr, fptr);   */
-
-/*     Read and decode PNG stream   */
-
-    png_read_png(png_ptr, info_ptr, PNG_TRANSFORM_IDENTITY, NULL);
-
-/*     Get pointer to each row of image data   */
-
-    row_pointers = png_get_rows(png_ptr, info_ptr);
-
-/*     Get image info, such as size, depth, colortype, etc...   */
-
-    /*printf("SAGT:png %d %d %d\n",info_ptr->width,info_ptr->height,info_ptr->bit_depth);*/
-    (void)png_get_IHDR(png_ptr, info_ptr, (png_uint_32 *)width, (png_uint_32 *)height,
-               &bit_depth, &color, &interlace, &compres, &filter);
-
-/*     Check if image was grayscale      */
-
-/*
-    if (color != PNG_COLOR_TYPE_GRAY ) {
-       fprintf(stderr,"dec_png: Grayscale image was expected. \n");
-    }
-*/
-    if ( color == PNG_COLOR_TYPE_RGB ) {
-       bit_depth=24;
-    }
-    else if ( color == PNG_COLOR_TYPE_RGB_ALPHA ) {
-       bit_depth=32;
-    }
-/*     Copy image data to output string   */
-
-    n=0;
-    bytes=bit_depth/8;
-    clen=(*width)*bytes;
-    for (j=0;j<*height;j++) {
-      for (k=0;k<clen;k++) {
-        cout[n]=*(row_pointers[j]+k);
-        n++;
-      }
-    }
-
-/*      Clean up   */
-
-    png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
-    return 0;
-
-}
-
-#endif   /* USE_PNG */
diff --git a/src/modules/io/io_grid_grib2/g2clib-1.0.4/drstemplates.c b/src/modules/io/io_grid_grib2/g2clib-1.0.4/drstemplates.c
deleted file mode 100644
index 0797645..0000000
--- a/src/modules/io/io_grid_grib2/g2clib-1.0.4/drstemplates.c
+++ /dev/null
@@ -1,157 +0,0 @@
-/**********************************************************
- * Version $Id: drstemplates.c 911 2011-02-14 16:38:15Z reklov_w $
- *********************************************************/
-#include <stdlib.h>
-#include "grib2.h"
-#include "drstemplates.h"
-
-g2int getdrsindex(g2int number)
-/*!$$$  SUBPROGRAM DOCUMENTATION BLOCK
-!                .      .    .                                       .
-! SUBPROGRAM:    getdrsindex 
-!   PRGMMR: Gilbert         ORG: W/NP11    DATE: 2001-06-28
-!
-! ABSTRACT: This function returns the index of specified Data 
-!   Representation Template 5.NN (NN=number) in array templates.
-!
-! PROGRAM HISTORY LOG:
-! 2001-06-28  Gilbert
-!
-! USAGE:    index=getdrsindex(number)
-!   INPUT ARGUMENT LIST:
-!     number   - NN, indicating the number of the Data Representation 
-!                Template 5.NN that is being requested.
-!
-! RETURNS:  Index of DRT 5.NN in array templates, if template exists.
-!           = -1, otherwise.
-!
-! REMARKS: None
-!
-! ATTRIBUTES:
-!   LANGUAGE: C
-!   MACHINE:  IBM SP
-!
-!$$$*/
-{
-           g2int j,getdrsindex=-1;
-
-           for (j=0;j<MAXDRSTEMP;j++) {
-              if (number == templatesdrs[j].template_num) {
-                 getdrsindex=j;
-                 return(getdrsindex);
-              }
-           }
-
-           return(getdrsindex);
-}
-
-
-template *getdrstemplate(g2int number)
-/*!$$$  SUBPROGRAM DOCUMENTATION BLOCK
-!                .      .    .                                       .
-! SUBPROGRAM:    getdrstemplate 
-!   PRGMMR: Gilbert         ORG: W/NP11    DATE: 2000-05-11
-!
-! ABSTRACT: This subroutine returns DRS template information for a 
-!   specified Data Representation Template 5.NN.
-!   The number of entries in the template is returned along with a map
-!   of the number of octets occupied by each entry.  Also, a flag is
-!   returned to indicate whether the template would need to be extended.
-!
-! PROGRAM HISTORY LOG:
-! 2000-05-11  Gilbert
-!
-! USAGE:    new=getdrstemplate(number);
-!   INPUT ARGUMENT LIST:
-!     number   - NN, indicating the number of the Data Representation 
-!                Template 5.NN that is being requested.
-!
-!   RETURN VALUE:      
-!        - Pointer to the returned template struct. 
-!          Returns NULL pointer, if template not found.
-!
-! REMARKS: None
-!
-! ATTRIBUTES:
-!   LANGUAGE: C
-!   MACHINE:  IBM SP
-!
-!$$$*/
-{
-           g2int index;
-           template *new;
-
-           index=getdrsindex(number);
-
-           if (index != -1) {
-              new=(template *)malloc(sizeof(template));
-              new->type=5;
-              new->num=templatesdrs[index].template_num;
-              new->maplen=templatesdrs[index].mapdrslen;
-              new->needext=templatesdrs[index].needext;
-              new->map=(g2int *)templatesdrs[index].mapdrs;
-              new->extlen=0;
-              new->ext=0;        //NULL
-              return(new);
-           }
-           else {
-             printf("getdrstemplate: DRS Template 5.%d not defined.\n",(int)number);
-             return(0);        //NULL
-           }
-
-         return(0);        //NULL
-}
-
-template *extdrstemplate(g2int number,g2int *list)
-/*!$$$  SUBPROGRAM DOCUMENTATION BLOCK
-!                .      .    .                                       .
-! SUBPROGRAM:    extdrstemplate 
-!   PRGMMR: Gilbert         ORG: W/NP11    DATE: 2000-05-11
-!
-! ABSTRACT: This subroutine generates the remaining octet map for a
-!   given Data Representation Template, if required.  Some Templates can
-!   vary depending on data values given in an earlier part of the 
-!   Template, and it is necessary to know some of the earlier entry
-!   values to generate the full octet map of the Template.
-!
-! PROGRAM HISTORY LOG:
-! 2000-05-11  Gilbert
-!
-! USAGE:    new=extdrstemplate(number,list);
-!   INPUT ARGUMENT LIST:
-!     number   - NN, indicating the number of the Data Representation 
-!                Template 5.NN that is being requested.
-!     list()   - The list of values for each entry in the 
-!                the Data Representation Template 5.NN.
-!
-!   RETURN VALUE:      
-!        - Pointer to the returned template struct. 
-!          Returns NULL pointer, if template not found.
-!
-! ATTRIBUTES:
-!   LANGUAGE: C
-!   MACHINE:  IBM SP
-!
-!$$$*/
-{
-           template *new;
-           g2int index,i;
-
-           index=getdrsindex(number);
-           if (index == -1) return(0);
-
-           new=getdrstemplate(number);
-
-           if ( ! new->needext ) return(new);
-
-           if ( number == 1 ) {
-              new->extlen=list[10]+list[12];
-              new->ext=(g2int *)malloc(sizeof(g2int)*new->extlen);
-              for (i=0;i<new->extlen;i++) {
-                new->ext[i]=4;
-              }
-           }
-           return(new);
-
-}
-
diff --git a/src/modules/io/io_grid_grib2/g2clib-1.0.4/drstemplates.h b/src/modules/io/io_grid_grib2/g2clib-1.0.4/drstemplates.h
deleted file mode 100644
index 759c52d..0000000
--- a/src/modules/io/io_grid_grib2/g2clib-1.0.4/drstemplates.h
+++ /dev/null
@@ -1,72 +0,0 @@
-/**********************************************************
- * Version $Id: drstemplates.h 911 2011-02-14 16:38:15Z reklov_w $
- *********************************************************/
-#ifndef _drstemplates_H
-#define _drstemplates_H
-#include "grib2.h"
-
-//   PRGMMR: Gilbert         ORG: W/NP11    DATE: 2002-10-26
-//
-// ABSTRACT: This Fortran Module contains info on all the available 
-//   GRIB2 Data Representation Templates used in Section 5 (DRS).
-//   The information decribing each template is stored in the
-//   drstemplate structure defined below.
-//
-//   Each Template has three parts: The number of entries in the template
-//   (mapdrslen);  A map of the template (mapdrs), which contains the
-//   number of octets in which to pack each of the template values; and
-//   a logical value (needext) that indicates whether the Template needs 
-//   to be extended.  In some cases the number of entries in a template 
-//   can vary depending upon values specified in the "static" part of 
-//   the template.  ( See Template 5.1 as an example )
-//
-//   NOTE:  Array mapdrs contains the number of octets in which the 
-//   corresponding template values will be stored.  A negative value in
-//   mapdrs is used to indicate that the corresponding template entry can
-//   contain negative values.  This information is used later when packing
-//   (or unpacking) the template data values.  Negative data values in GRIB
-//   are stored with the left most bit set to one, and a negative number
-//   of octets value in mapdrs[] indicates that this possibility should
-//   be considered.  The number of octets used to store the data value
-//   in this case would be the absolute value of the negative value in 
-//   mapdrs[].
-//  
-//
-///////////////////////////////////////////////////////////////////////
-
-      #define MAXDRSTEMP 9              // maximum number of templates
-      #define MAXDRSMAPLEN 200          // maximum template map length
-
-      struct drstemplate
-      {
-          g2int template_num;
-          g2int mapdrslen;
-          g2int needext;
-          g2int mapdrs[MAXDRSMAPLEN];
-      };
-
-      const struct drstemplate templatesdrs[MAXDRSTEMP] = {
-             // 5.0: Grid point data - Simple Packing
-         { 0, 5, 0, {4,-2,-2,1,1} },
-             // 5.2: Grid point data - Complex Packing
-         { 2, 16, 0, {4,-2,-2,1,1,1,1,4,4,4,1,1,4,1,4,1} },
-             // 5.3: Grid point data - Complex Packing and spatial differencing
-         { 3, 18, 0, {4,-2,-2,1,1,1,1,4,4,4,1,1,4,1,4,1,1,1} },
-             // 5.50: Spectral Data - Simple Packing
-         { 50, 5, 0, {4,-2,-2,1,4} },
-             // 5.51: Spherical Harmonics data - Complex packing 
-         { 51, 10, 0, {4,-2,-2,1,-4,2,2,2,4,1} },
-//           // 5.1: Matrix values at gridpoint - Simple packing
-//         { 1, 15, 1, {4,-2,-2,1,1,1,4,2,2,1,1,1,1,1,1} },
-             // 5.40: Grid point data - JPEG2000 encoding
-         { 40, 7, 0, {4,-2,-2,1,1,1,1} },
-             // 5.41: Grid point data - PNG encoding
-         { 41, 5, 0, {4,-2,-2,1,1} },
-             // 5.40000: Grid point data - JPEG2000 encoding
-         { 40000, 7, 0, {4,-2,-2,1,1,1,1} },
-             // 5.40010: Grid point data - PNG encoding
-         { 40010, 5, 0, {4,-2,-2,1,1} }
-      } ;
-
-
-#endif  /*  _drstemplates_H  */
diff --git a/src/modules/io/io_grid_grib2/g2clib-1.0.4/enc_jpeg2000.c b/src/modules/io/io_grid_grib2/g2clib-1.0.4/enc_jpeg2000.c
deleted file mode 100644
index c56010a..0000000
--- a/src/modules/io/io_grid_grib2/g2clib-1.0.4/enc_jpeg2000.c
+++ /dev/null
@@ -1,190 +0,0 @@
-/**********************************************************
- * Version $Id: enc_jpeg2000.c 911 2011-02-14 16:38:15Z reklov_w $
- *********************************************************/
-#ifndef USE_JPEG2000
-#include "grib2.h"
- int enc_jpeg2000(unsigned char *cin,g2int width,g2int height,g2int nbits,
-                 g2int ltype, g2int ratio, g2int retry, char *outjpc, 
-                 g2int jpclen)
- {	return( 0 );	}
-#else   /* USE_JPEG2000 */
-
-#include <stdio.h>
-#include <stdlib.h>
-#include "grib2.h"
-#include "jasper/jasper.h"
-#define JAS_1_700_2
-
-
-int enc_jpeg2000(unsigned char *cin,g2int width,g2int height,g2int nbits,
-                 g2int ltype, g2int ratio, g2int retry, char *outjpc, 
-                 g2int jpclen)
-/*$$$  SUBPROGRAM DOCUMENTATION BLOCK
-*                .      .    .                                       .
-* SUBPROGRAM:    enc_jpeg2000      Encodes JPEG2000 code stream
-*   PRGMMR: Gilbert          ORG: W/NP11     DATE: 2002-12-02
-*
-* ABSTRACT: This Function encodes a grayscale image into a JPEG2000 code stream
-*   specified in the JPEG2000 Part-1 standard (i.e., ISO/IEC 15444-1) 
-*   using JasPer Software version 1.500.4 (or 1.700.2 ) written by the 
-*   University of British Columbia, Image Power Inc, and others.
-*   JasPer is available at http://www.ece.uvic.ca/~mdadams/jasper/.
-*
-* PROGRAM HISTORY LOG:
-* 2002-12-02  Gilbert
-* 2004-12-16  Gilbert - Added retry argument/option to allow option of
-*                       increasing the maximum number of guard bits to the
-*                       JPEG2000 algorithm.
-*
-* USAGE:    int enc_jpeg2000(unsigned char *cin,g2int width,g2int height,
-*                            g2int nbits, g2int ltype, g2int ratio, 
-*                            g2int retry, char *outjpc, g2int jpclen)
-*
-*   INPUT ARGUMENTS:
-*      cin   - Packed matrix of Grayscale image values to encode.
-*     width  - width of image
-*     height - height of image
-*     nbits  - depth (in bits) of image.  i.e number of bits
-*              used to hold each data value
-*    ltype   - indicator of lossless or lossy compression
-*              = 1, for lossy compression
-*              != 1, for lossless compression
-*    ratio   - target compression ratio.  (ratio:1)
-*              Used only when ltype == 1.
-*    retry   - Pointer to option type.
-*              1 = try increasing number of guard bits
-*              otherwise, no additional options
-*    jpclen  - Number of bytes allocated for new JPEG2000 code stream in
-*              outjpc.
-*
-*   INPUT ARGUMENTS:
-*     outjpc - Output encoded JPEG2000 code stream
-*
-*   RETURN VALUES :
-*        > 0 = Length in bytes of encoded JPEG2000 code stream
-*         -3 = Error decode jpeg2000 code stream.
-*         -5 = decoded image had multiple color components.
-*              Only grayscale is expected.
-*
-* REMARKS:
-*
-*      Requires JasPer Software version 1.500.4 or 1.700.2
-*
-* ATTRIBUTES:
-*   LANGUAGE: C
-*   MACHINE:  IBM SP
-*
-*$$$*/
-{
-    int ier,rwcnt;
-    jas_image_t image;
-    jas_stream_t *jpcstream,*istream;
-    jas_image_cmpt_t cmpt,*pcmpt;
-#define MAXOPTSSIZE 1024
-    char opts[MAXOPTSSIZE];
-
-/*
-    printf(" enc_jpeg2000:width %ld\n",width);
-    printf(" enc_jpeg2000:height %ld\n",height);
-    printf(" enc_jpeg2000:nbits %ld\n",nbits);
-    printf(" enc_jpeg2000:jpclen %ld\n",jpclen);
-*/
-//    jas_init();
-
-//
-//    Set lossy compression options, if requested.
-//
-    if ( ltype != 1 ) {
-       opts[0]=(char)0;
-    }
-    else {
-#ifdef _SAGA_MSW
-       sprintf(opts,"mode=real\nrate=%f",1.0/(float)ratio);
-#else
-       snprintf(opts,MAXOPTSSIZE,"mode=real\nrate=%f",1.0/(float)ratio);
-#endif	// _SAGA_MSW
-    }
-    if ( retry == 1 ) {             // option to increase number of guard bits
-       strcat(opts,"\nnumgbits=4");
-    }
-    //printf("SAGopts: %s\n",opts);
-    
-//
-//     Initialize the JasPer image structure describing the grayscale
-//     image to encode into the JPEG2000 code stream.
-//
-    image.tlx_=0;
-    image.tly_=0;
-#ifdef JAS_1_500_4 
-    image.brx_=(uint_fast32_t)width;
-    image.bry_=(uint_fast32_t)height;
-#endif 
-#ifdef JAS_1_700_2
-    image.brx_=(jas_image_coord_t)width;
-    image.bry_=(jas_image_coord_t)height;
-#endif
-    image.numcmpts_=1;
-    image.maxcmpts_=1;
-#ifdef JAS_1_500_4
-    image.colormodel_=JAS_IMAGE_CM_GRAY;         /* grayscale Image */
-#endif
-#ifdef JAS_1_700_2
-    image.clrspc_=JAS_CLRSPC_SGRAY;         /* grayscale Image */
-    image.cmprof_=0; 
-#endif
-    image.inmem_=1;
-
-    cmpt.tlx_=0;
-    cmpt.tly_=0;
-    cmpt.hstep_=1;
-    cmpt.vstep_=1;
-#ifdef JAS_1_500_4
-    cmpt.width_=(uint_fast32_t)width;
-    cmpt.height_=(uint_fast32_t)height;
-#endif
-#ifdef JAS_1_700_2
-    cmpt.width_=(jas_image_coord_t)width;
-    cmpt.height_=(jas_image_coord_t)height;
-    cmpt.type_=JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_GRAY_Y);
-#endif
-    cmpt.prec_=nbits;
-    cmpt.sgnd_=0;
-    cmpt.cps_=(nbits+7)/8;
-
-    pcmpt=&cmpt;
-    image.cmpts_=&pcmpt;
-
-//
-//    Open a JasPer stream containing the input grayscale values
-//
-    istream=jas_stream_memopen((char *)cin,height*width*cmpt.cps_);
-    cmpt.stream_=istream;
-
-//
-//    Open an output stream that will contain the encoded jpeg2000
-//    code stream.
-//
-    jpcstream=jas_stream_memopen(outjpc,(int)jpclen);
-
-//
-//     Encode image.
-//
-    ier=jpc_encode(&image,jpcstream,opts);
-    if ( ier != 0 ) {
-       printf(" jpc_encode return = %d \n",ier);
-       return -3;
-    }
-//
-//     Clean up JasPer work structures.
-//    
-    rwcnt=jpcstream->rwcnt_;
-    ier=jas_stream_close(istream);
-    ier=jas_stream_close(jpcstream);
-//
-//      Return size of jpeg2000 code stream
-//
-    return (rwcnt);
-
-}
-
-#endif   /* USE_JPEG2000 */
diff --git a/src/modules/io/io_grid_grib2/g2clib-1.0.4/enc_png.c b/src/modules/io/io_grid_grib2/g2clib-1.0.4/enc_png.c
deleted file mode 100644
index 8fd7fde..0000000
--- a/src/modules/io/io_grid_grib2/g2clib-1.0.4/enc_png.c
+++ /dev/null
@@ -1,138 +0,0 @@
-/**********************************************************
- * Version $Id: enc_png.c 911 2011-02-14 16:38:15Z reklov_w $
- *********************************************************/
-#ifndef USE_PNG
-#include "grib2.h"
- int enc_png(char *data,g2int width,g2int height,g2int nbits,char *pngbuf)	{	return( 0 );	}
-#else   /* USE_PNG */
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <png.h>
-#include "grib2.h"
-
-
-struct png_stream {
-   unsigned char *stream_ptr;     /*  location to write PNG stream  */
-   g2int stream_len;               /*  number of bytes written       */
-};
-typedef struct png_stream png_stream;
-
-void user_write_data(png_structp ,png_bytep , png_uint_32 );
-void user_flush_data(png_structp );
-
-void user_write_data(png_structp png_ptr,png_bytep data, png_uint_32 length)
-/*
-        Custom write function used to that libpng will write
-        to memory location instead of a file on disk
-*/
-{
-     unsigned char *ptr;
-     g2int offset;
-     png_stream *mem;
-
-     mem=(png_stream *)png_get_io_ptr(png_ptr);
-     ptr=mem->stream_ptr;
-     offset=mem->stream_len;
-/*     printf("SAGwr %ld %ld %x\n",offset,length,ptr);    */
-     /*for (j=offset,k=0;k<length;j++,k++) ptr[j]=data[k];*/
-     memcpy(ptr+offset,data,length);
-     mem->stream_len += length;
-}
-
-
-void user_flush_data(png_structp png_ptr)
-/*
-        Dummy Custom flush function
-*/
-{
-   int *do_nothing;
-   do_nothing=NULL;
-}
-
-
-int enc_png(char *data,g2int width,g2int height,g2int nbits,char *pngbuf)
-{
- 
-    int color_type;
-    g2int j,bytes,pnglen,bit_depth;
-    png_structp png_ptr;
-    png_infop info_ptr;
-//    png_bytep *row_pointers[height];
-    png_bytep **row_pointers;
-    png_stream write_io_ptr;
-
-/* create and initialize png_structs  */
-
-    png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, (png_voidp)NULL, 
-                                      NULL, NULL);
-    if (!png_ptr)
-       return (-1);
-
-    info_ptr = png_create_info_struct(png_ptr);
-    if (!info_ptr)
-    {
-       png_destroy_write_struct(&png_ptr,(png_infopp)NULL);
-       return (-2);
-    }
-
-/*     Set Error callback   */
-
-    if (setjmp(png_jmpbuf(png_ptr)))
-    {
-       png_destroy_write_struct(&png_ptr, &info_ptr);
-       return (-3);
-    }
-
-/*    Initialize info for writing PNG stream to memory   */
-
-    write_io_ptr.stream_ptr=(png_voidp)pngbuf;
-    write_io_ptr.stream_len=0;
-
-/*    Set new custom write functions    */
-
-    png_set_write_fn(png_ptr,(voidp)&write_io_ptr,(png_rw_ptr)user_write_data,
-                    (png_flush_ptr)user_flush_data);
-/*    png_init_io(png_ptr, fptr);   */
-/*    png_set_compression_level(png_ptr, Z_BEST_COMPRESSION);  */
-
-/*     Set the image size, colortype, filter type, etc...      */
-
-/*    printf("SAGTsettingIHDR %d %d %d\n",width,height,bit_depth); */
-    bit_depth=nbits;
-    color_type=PNG_COLOR_TYPE_GRAY;
-    if (nbits == 24 ) {
-        bit_depth=8;
-        color_type=PNG_COLOR_TYPE_RGB;
-    }
-    else if (nbits == 32 ) {
-        bit_depth=8;
-        color_type=PNG_COLOR_TYPE_RGB_ALPHA;
-    }
-    png_set_IHDR(png_ptr, info_ptr, width, height,
-       bit_depth, color_type, PNG_INTERLACE_NONE,
-       PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
-
-/*     Put image data into the PNG info structure    */
-
-    /*bytes=bit_depth/8;*/
-    bytes=nbits/8;
-    row_pointers=malloc(height*sizeof(png_bytep));
-    for (j=0;j<height;j++) row_pointers[j]=(png_bytep *)(data+(j*width*bytes));
-    png_set_rows(png_ptr, info_ptr, (png_bytepp)row_pointers);
-
-/*     Do the PNG encoding, and write out PNG stream  */
-
-    png_write_png(png_ptr, info_ptr, PNG_TRANSFORM_IDENTITY, NULL);
-
-/*     Clean up   */
-
-    png_destroy_write_struct(&png_ptr, &info_ptr);
-    free(row_pointers);
-    pnglen=write_io_ptr.stream_len;
-    return pnglen;
-
-}
-
-#endif   /* USE_PNG */
diff --git a/src/modules/io/io_grid_grib2/g2clib-1.0.4/g2_addfield.c b/src/modules/io/io_grid_grib2/g2clib-1.0.4/g2_addfield.c
deleted file mode 100644
index 2a3ea74..0000000
--- a/src/modules/io/io_grid_grib2/g2clib-1.0.4/g2_addfield.c
+++ /dev/null
@@ -1,513 +0,0 @@
-/**********************************************************
- * Version $Id: g2_addfield.c 911 2011-02-14 16:38:15Z reklov_w $
- *********************************************************/
-#include <stdio.h>
-#include <stdlib.h>
-#include "grib2.h"
-
-g2int getdim(unsigned char *,g2int *,g2int *,g2int *);
-g2int getpoly(unsigned char *,g2int *,g2int *,g2int *);
-void simpack(g2float *, g2int, g2int *, unsigned char *, g2int *);
-void cmplxpack(g2float *, g2int, g2int, g2int *, unsigned char *, g2int *);
-void specpack(g2float *,g2int,g2int,g2int,g2int,g2int *,unsigned char *,
-              g2int *);
-#ifdef USE_PNG
-  void pngpack(g2float *,g2int,g2int,g2int *,unsigned char *,g2int *);
-#endif  /* USE_PNG */
-#ifdef USE_JPEG2000
-  void jpcpack(g2float *,g2int,g2int,g2int *,unsigned char *,g2int *);
-#endif  /* USE_JPEG2000 */
-
-
-g2int g2_addfield(unsigned char *cgrib,g2int ipdsnum,g2int *ipdstmpl,
-                g2float *coordlist,g2int numcoord,g2int idrsnum,g2int *idrstmpl,
-                g2float *fld,g2int ngrdpts,g2int ibmap,g2int *bmap)
-//$$$  SUBPROGRAM DOCUMENTATION BLOCK
-//                .      .    .                                       .
-// SUBPROGRAM:    g2_addfield 
-//   PRGMMR: Gilbert         ORG: W/NP11    DATE: 2002-11-05
-//
-// ABSTRACT: This routine packs up Sections 4 through 7 for a given field
-//   and adds them to a GRIB2 message.  They are Product Definition Section,
-//   Data Representation Section, Bit-Map Section and Data Section, 
-//   respectively.
-//   This routine is used with routines "g2_create", "g2_addlocal", 
-//   "g2_addgrid", and "g2_gribend" to create a complete GRIB2 message.  
-//   g2_create must be called first to initialize a new GRIB2 message.
-//   Also, routine g2_addgrid must be called after g2_create and
-//   before this routine to add the appropriate grid description to
-//   the GRIB2 message.   Also, a call to g2_gribend is required to complete 
-//   GRIB2 message after all fields have been added.
-//
-// PROGRAM HISTORY LOG:
-// 2002-11-05  Gilbert
-// 2002-12-23  Gilbert  -  Added complex spherical harmonic packing
-// 2003-08-27  Gilbert  - Added support for new templates using
-//                        PNG and JPEG2000 algorithms/templates.
-// 2004-11-29  Gilbert  - JPEG2000 now allowed to use WMO Template no. 5.40
-//                        PNG now allowed to use WMO Template no. 5.41
-//                      - Added check to determine if packing algorithm failed.
-// 2005-05-10  Gilbert -  Imposed minimum size on cpack, used to hold encoded
-//                        bit string.
-//
-// USAGE:    int g2_addfield(unsigned char *cgrib,g2int ipdsnum,g2int *ipdstmpl,
-//              g2float *coordlist,g2int numcoord,g2int idrsnum,g2int *idrstmpl,
-//              g2float *fld,g2int ngrdpts,g2int ibmap,g2int *bmap)
-//   INPUT ARGUMENT LIST:
-//     cgrib    - Char array that contains the GRIB2 message to which sections
-//                4 through 7 should be added.
-//     ipdsnum  - Product Definition Template Number ( see Code Table 4.0)
-//     ipdstmpl - Contains the data values for the specified Product Definition
-//                Template ( N=ipdsnum ).  Each element of this integer 
-//                array contains an entry (in the order specified) of Product
-//                Defintion Template 4.N
-//     coordlist- Array containg floating point values intended to document
-//                the vertical discretisation associated to model data
-//                on hybrid coordinate vertical levels.
-//     numcoord - number of values in array coordlist.
-//     idrsnum  - Data Representation Template Number ( see Code Table 5.0 )
-//     idrstmpl - Contains the data values for the specified Data Representation
-//                Template ( N=idrsnum ).  Each element of this integer 
-//                array contains an entry (in the order specified) of Data
-//                Representation Template 5.N
-//                Note that some values in this template (eg. reference
-//                values, number of bits, etc...) may be changed by the
-//                data packing algorithms.
-//                Use this to specify scaling factors and order of
-//                spatial differencing, if desired.
-//     fld[]    - Array of data points to pack.
-//     ngrdpts  - Number of data points in grid.
-//                i.e.  size of fld and bmap.
-//     ibmap    - Bitmap indicator ( see Code Table 6.0 )
-//                0 = bitmap applies and is included in Section 6.
-//                1-253 = Predefined bitmap applies
-//                254 = Previously defined bitmap applies to this field
-//                255 = Bit map does not apply to this product.
-//     bmap[]   - Integer array containing bitmap to be added. ( if ibmap=0 )
-//
-//   OUTPUT ARGUMENT LIST:      
-//     cgrib    - Character array to contain the updated GRIB2 message.
-//                Must be allocated large enough to store the entire
-//                GRIB2 message.
-//
-//   RETURN VALUES:
-//     ierr     - Return code.
-//              > 0 = Current size of updated GRIB2 message
-//               -1 = GRIB message was not initialized.  Need to call
-//                    routine g2_create first.
-//               -2 = GRIB message already complete.  Cannot add new section.
-//               -3 = Sum of Section byte counts doesn't add to total byte count
-//               -4 = Previous Section was not 3 or 7.
-//               -5 = Could not find requested Product Definition Template.
-//               -6 = Section 3 (GDS) not previously defined in message
-//               -7 = Tried to use unsupported Data Representationi Template
-//               -8 = Specified use of a previously defined bitmap, but one
-//                    does not exist in the GRIB message.
-//               -9 = GDT of one of 5.50 through 5.53 required to pack field
-//                    using DRT 5.51.
-//              -10 = Error packing data field.
-//
-// REMARKS: Note that the Sections 4 through 7 can only follow
-//          Section 3 or Section 7 in a GRIB2 message.
-//
-// ATTRIBUTES:
-//   LANGUAGE: C
-//   MACHINE:  
-//
-//$$$
-{
-      g2int ierr;
-      static unsigned char G=0x47;       // 'G'
-      static unsigned char R=0x52;       // 'R'
-      static unsigned char I=0x49;       // 'I'
-      static unsigned char B=0x42;       // 'B'
-      static unsigned char s7=0x37;   // '7'
-
-      unsigned char *cpack;
-      static g2int  zero=0,one=1,four=4,five=5,six=6,seven=7;
-      const g2int  minsize=50000;
-      g2int   iofst,ibeg,lencurr,len,nsize;
-      g2int   ilen,isecnum,i,nbits,temp,left;
-      g2int   ibmprev,j,lcpack,ioctet,newlen,ndpts;
-      g2int   lensec4,lensec5,lensec6,lensec7;
-      g2int   issec3,isprevbmap,lpos3=0,JJ,KK,MM;
-      g2int   *coordieee;
-      g2int   width,height,iscan,itemp;
-      g2float *pfld;
-      template  *mappds,*mapdrs;
-      unsigned int allones=4294967295u;
- 
-      ierr=0;
-//
-//  Check to see if beginning of GRIB message exists
-//
-      if ( cgrib[0]!=G || cgrib[1]!=R || cgrib[2]!=I || cgrib[3]!=B ) {
-        printf("g2_addfield: GRIB not found in given message.\n");
-        printf("g2_addfield: Call to routine g2_create required to initialize GRIB messge.\n");
-        ierr=-1;
-        return(ierr);
-      }
-//
-//  Get current length of GRIB message
-//  
-      gbit(cgrib,&lencurr,96,32);
-//
-//  Check to see if GRIB message is already complete
-//  
-      if ( cgrib[lencurr-4]==s7 && cgrib[lencurr-3]==s7 &&
-           cgrib[lencurr-2]==s7 && cgrib[lencurr-1]==s7 ) {
-        printf("g2_addfield: GRIB message already complete.  Cannot add new section.\n");
-        ierr=-2;
-        return(ierr);
-      }
-//
-//  Loop through all current sections of the GRIB message to
-//  find the last section number.
-//
-      issec3=0;
-      isprevbmap=0;
-      len=16;    // length of Section 0
-      for (;;) { 
-      //    Get number and length of next section
-        iofst=len*8;
-        gbit(cgrib,&ilen,iofst,32);
-        iofst=iofst+32;
-        gbit(cgrib,&isecnum,iofst,8);
-        iofst=iofst+8;
-      //  Check if previous Section 3 exists
-        if (isecnum == 3) {
-            issec3=1;
-            lpos3=len;
-        }
-      //  Check if a previous defined bitmap exists
-        if (isecnum == 6) {
-          gbit(cgrib,&ibmprev,iofst,8);
-          iofst=iofst+8;
-          if ((ibmprev >= 0) && (ibmprev <= 253)) isprevbmap=1;
-        }
-        len=len+ilen;
-      //    Exit loop if last section reached
-        if ( len == lencurr ) break;
-      //    If byte count for each section doesn't match current
-      //    total length, then there is a problem.
-        if ( len > lencurr ) {
-          printf("g2_addfield: Section byte counts don''t add to total.\n");
-          printf("g2_addfield: Sum of section byte counts = %ld\n",len);
-          printf("g2_addfield: Total byte count in Section 0 = %ld\n",lencurr);
-          ierr=-3;
-          return(ierr);
-        }
-      }
-//
-//  Sections 4 through 7 can only be added after section 3 or 7.
-//
-      if ( (isecnum != 3) && (isecnum != 7) ) {
-        printf("g2_addfield: Sections 4-7 can only be added after Section 3 or 7.\n");
-        printf("g2_addfield: Section ',isecnum,' was the last found in given GRIB message.\n");
-        ierr=-4;
-        return(ierr);
-//
-//  Sections 4 through 7 can only be added if section 3 was previously defined.
-//
-      }
-      else if ( ! issec3) {
-        printf("g2_addfield: Sections 4-7 can only be added if Section 3 was previously included.\n");
-        printf("g2_addfield: Section 3 was not found in given GRIB message.\n");
-        printf("g2_addfield: Call to routine addgrid required to specify Grid definition.\n");
-        ierr=-6;
-        return(ierr);
-      }
-//
-//  Add Section 4  - Product Definition Section
-//
-      ibeg=lencurr*8;        //   Calculate offset for beginning of section 4
-      iofst=ibeg+32;         //   leave space for length of section
-      sbit(cgrib,&four,iofst,8);     // Store section number ( 4 )
-      iofst=iofst+8;
-      sbit(cgrib,&numcoord,iofst,16);   // Store num of coordinate values
-      iofst=iofst+16;
-      sbit(cgrib,&ipdsnum,iofst,16);    // Store Prod Def Template num.
-      iofst=iofst+16;
-      //
-      //   Get Product Definition Template
-      //
-      mappds=getpdstemplate(ipdsnum);
-      if (mappds == 0) {          // undefined template
-        ierr=-5;
-        return(ierr);
-      }
-      //
-      //   Extend the Product Definition Template, if necessary.
-      //   The number of values in a specific template may vary
-      //   depending on data specified in the "static" part of the
-      //   template.
-      //
-      if ( mappds->needext ) {
-        free(mappds);
-        mappds=extpdstemplate(ipdsnum,ipdstmpl);
-      }
-      //
-      //   Pack up each input value in array ipdstmpl into the
-      //   the appropriate number of octets, which are specified in
-      //   corresponding entries in array mappds.
-      //
-      for (i=0;i<mappds->maplen;i++) {
-        nbits=abs(mappds->map[i])*8;
-        if ( (mappds->map[i] >= 0) || (ipdstmpl[i] >= 0) )
-          sbit(cgrib,ipdstmpl+i,iofst,nbits);
-        else {
-          sbit(cgrib,&one,iofst,1);
-          temp=abs(ipdstmpl[i]);
-          sbit(cgrib,&temp,iofst+1,nbits-1);
-        }
-        iofst=iofst+nbits;
-      }
-      //  Pack template extension, if appropriate
-      j=mappds->maplen;
-      if ( mappds->needext && (mappds->extlen > 0) ) {
-         for (i=0;i<mappds->extlen;i++) {
-           nbits=abs(mappds->ext[i])*8;
-           if ( (mappds->ext[i] >= 0) || (ipdstmpl[j] >= 0) )
-             sbit(cgrib,ipdstmpl+j,iofst,nbits);
-           else {
-             sbit(cgrib,&one,iofst,1);
-             temp=abs(ipdstmpl[j]);
-             sbit(cgrib,&temp,iofst+1,nbits-1);
-           }
-           iofst=iofst+nbits;
-           j++;
-         }
-      }
-      free(mappds);
-      //
-      //   Add Optional list of vertical coordinate values
-      //   after the Product Definition Template, if necessary.
-      //
-      if ( numcoord != 0 ) {
-        coordieee=(g2int *)calloc(numcoord,sizeof(g2int));
-        mkieee(coordlist,coordieee,numcoord);
-        sbits(cgrib,coordieee,iofst,32,0,numcoord);
-        iofst=iofst+(32*numcoord);
-        free(coordieee);
-      }
-      //
-      //   Calculate length of section 4 and store it in octets
-      //   1-4 of section 4.
-      //
-      lensec4=(iofst-ibeg)/8;
-      sbit(cgrib,&lensec4,ibeg,32);
-//
-//  Pack Data using appropriate algorithm
-//
-      //
-      //   Get Data Representation Template
-      //
-      mapdrs=getdrstemplate(idrsnum);
-      if (mapdrs == 0) {
-        ierr=-5;
-        return(ierr);
-      }
-      //
-      //  contract data field, removing data at invalid grid points,
-      //  if bit-map is provided with field.
-      //
-      if ( ibmap == 0 || ibmap==254 ) {
-         pfld=(g2float *)malloc(ngrdpts*sizeof(g2float));
-         ndpts=0;
-         for (j=0;j<ngrdpts;j++) {
-             if ( bmap[j]==1 ) pfld[ndpts++]=fld[j];
-         }
-      }
-      else {
-         ndpts=ngrdpts;
-         pfld=fld;
-      }
-      nsize=ndpts*4;
-      if ( nsize < minsize ) nsize=minsize;
-      cpack=malloc(nsize);
-      if (idrsnum == 0)           //  Simple Packing
-        simpack(pfld,ndpts,idrstmpl,cpack,&lcpack);
-      else if (idrsnum==2 || idrsnum==3)           //  Complex Packing
-        cmplxpack(pfld,ndpts,idrsnum,idrstmpl,cpack,&lcpack);
-      else if (idrsnum == 50) {         //  Sperical Harmonic Simple Packing 
-        simpack(pfld+1,ndpts-1,idrstmpl,cpack,&lcpack);
-        mkieee(pfld+0,idrstmpl+4,1);  // ensure RE(0,0) value is IEEE format
-      }
-      else if (idrsnum == 51) {         //  Sperical Harmonic Complex Packing 
-        getpoly(cgrib+lpos3,&JJ,&KK,&MM);
-        if ( JJ!=0 && KK!=0 && MM!=0 )
-           specpack(pfld,ndpts,JJ,KK,MM,idrstmpl,cpack,&lcpack);
-        else {
-           printf("g2_addfield: Cannot pack DRT 5.51.\n");
-           return (-9);
-        }
-      }
-#ifdef USE_JPEG2000
-      else if (idrsnum == 40 || idrsnum == 40000) {    /*  JPEG2000 encoding  */
-        if (ibmap == 255) {
-           getdim(cgrib+lpos3,&width,&height,&iscan);
-           if ( width==0 || height==0 ) {
-              width=ndpts;
-              height=1;
-           }
-           else if ( width==allones || height==allones ) {
-              width=ndpts;
-              height=1;
-           }
-           else if ( (iscan&32) == 32) {   /* Scanning mode: bit 3  */
-              itemp=width;
-              width=height;
-              height=itemp;
-           }
-        }
-        else {
-           width=ndpts;
-           height=1;
-        }
-        lcpack=nsize;
-        jpcpack(pfld,width,height,idrstmpl,cpack,&lcpack);
-      }
-#endif  /* USE_JPEG2000 */
-#ifdef USE_PNG
-      else if (idrsnum == 41 || idrsnum == 40010) {      /*  PNG encoding   */
-        if (ibmap == 255) {
-           getdim(cgrib+lpos3,&width,&height,&iscan);
-           if ( width==0 || height==0 ) {
-              width=ndpts;
-              height=1;
-           }
-           else if ( width==allones || height==allones ) {
-              width=ndpts;
-              height=1;
-           }
-           else if ( (iscan&32) == 32) {   /* Scanning mode: bit 3  */
-              itemp=width;
-              width=height;
-              height=itemp;
-           }
-        }
-        else {
-           width=ndpts;
-           height=1;
-        }
-        pngpack(pfld,width,height,idrstmpl,cpack,&lcpack);
-      }
-#endif  /* USE_PNG */
-      else {
-        printf("g2_addfield: Data Representation Template 5.%ld not yet implemented.\n",idrsnum);
-        ierr=-7;
-        return(ierr);
-      }
-      if ( ibmap == 0 || ibmap==254 ) {      // free temp space
-         if (fld != pfld) free(pfld);
-      }
-      if ( lcpack < 0 ) {
-        if( cpack != 0 ) free(cpack);
-        ierr=-10;
-        return(ierr);
-      }
-
-//
-//  Add Section 5  - Data Representation Section
-//
-      ibeg=iofst;            //   Calculate offset for beginning of section 5
-      iofst=ibeg+32;         //   leave space for length of section
-      sbit(cgrib,&five,iofst,8);     // Store section number ( 5 )
-      iofst=iofst+8;
-      sbit(cgrib,&ndpts,iofst,32);    // Store num of actual data points
-      iofst=iofst+32;
-      sbit(cgrib,&idrsnum,iofst,16);    // Store Data Repr. Template num.
-      iofst=iofst+16;
-      //
-      //   Pack up each input value in array idrstmpl into the
-      //   the appropriate number of octets, which are specified in
-      //   corresponding entries in array mapdrs.
-      //
-      for (i=0;i<mapdrs->maplen;i++) {
-        nbits=abs(mapdrs->map[i])*8;
-        if ( (mapdrs->map[i] >= 0) || (idrstmpl[i] >= 0) )
-          sbit(cgrib,idrstmpl+i,iofst,nbits);
-        else {
-          sbit(cgrib,&one,iofst,1);
-          temp=abs(idrstmpl[i]);
-          sbit(cgrib,&temp,iofst+1,nbits-1);
-        }
-        iofst=iofst+nbits;
-      }
-      free(mapdrs);
-      //
-      //   Calculate length of section 5 and store it in octets
-      //   1-4 of section 5.
-      //
-      lensec5=(iofst-ibeg)/8;
-      sbit(cgrib,&lensec5,ibeg,32);
-
-//
-//  Add Section 6  - Bit-Map Section
-//
-      ibeg=iofst;            //   Calculate offset for beginning of section 6
-      iofst=ibeg+32;         //   leave space for length of section
-      sbit(cgrib,&six,iofst,8);     // Store section number ( 6 )
-      iofst=iofst+8;
-      sbit(cgrib,&ibmap,iofst,8);    // Store Bit Map indicator
-      iofst=iofst+8;
-      //
-      //  Store bitmap, if supplied
-      //
-      if (ibmap == 0) {
-        sbits(cgrib,bmap,iofst,1,0,ngrdpts);    // Store BitMap
-        iofst=iofst+ngrdpts;
-      }
-      //
-      //  If specifying a previously defined bit-map, make sure
-      //  one already exists in the current GRIB message.
-      //
-      if ((ibmap==254) && ( ! isprevbmap)) {
-        printf("g2_addfield: Requested previously defined bitmap,");
-        printf(" but one does not exist in the current GRIB message.\n");
-        ierr=-8;
-        return(ierr);
-      }
-      //
-      //   Calculate length of section 6 and store it in octets
-      //   1-4 of section 6.  Pad to end of octect, if necessary.
-      //
-      left=8-(iofst%8);
-      if (left != 8) {
-        sbit(cgrib,&zero,iofst,left);     // Pad with zeros to fill Octet
-        iofst=iofst+left;
-      }
-      lensec6=(iofst-ibeg)/8;
-      sbit(cgrib,&lensec6,ibeg,32);
-
-//
-//  Add Section 7  - Data Section
-//
-      ibeg=iofst;            //   Calculate offset for beginning of section 7
-      iofst=ibeg+32;        //   leave space for length of section
-      sbit(cgrib,&seven,iofst,8);    // Store section number ( 7 )
-      iofst=iofst+8;
-      //      Store Packed Binary Data values, if non-constant field
-      if (lcpack != 0) {
-        ioctet=iofst/8;
-        //cgrib(ioctet+1:ioctet+lcpack)=cpack(1:lcpack)
-        for (j=0;j<lcpack;j++) cgrib[ioctet+j]=cpack[j];
-        iofst=iofst+(8*lcpack);
-      }
-      //
-      //   Calculate length of section 7 and store it in octets
-      //   1-4 of section 7.  
-      //
-      lensec7=(iofst-ibeg)/8;
-      sbit(cgrib,&lensec7,ibeg,32);
-
-      if( cpack != 0 ) free(cpack);
-//
-//  Update current byte total of message in Section 0
-//
-      newlen=lencurr+lensec4+lensec5+lensec6+lensec7;
-      sbit(cgrib,&newlen,96,32);
-
-      return(newlen);
-
-}
diff --git a/src/modules/io/io_grid_grib2/g2clib-1.0.4/g2_addgrid.c b/src/modules/io/io_grid_grib2/g2clib-1.0.4/g2_addgrid.c
deleted file mode 100644
index 7c8a51f..0000000
--- a/src/modules/io/io_grid_grib2/g2clib-1.0.4/g2_addgrid.c
+++ /dev/null
@@ -1,246 +0,0 @@
-/**********************************************************
- * Version $Id: g2_addgrid.c 911 2011-02-14 16:38:15Z reklov_w $
- *********************************************************/
-#include <stdio.h>
-#include <stdlib.h>
-#include "grib2.h"
-
-
-g2int g2_addgrid(unsigned char *cgrib,g2int *igds,g2int *igdstmpl,g2int *ideflist,g2int idefnum)
-//$$$  SUBPROGRAM DOCUMENTATION BLOCK
-//                .      .    .                                       .
-// SUBPROGRAM:    g2_addgrid 
-//   PRGMMR: Gilbert         ORG: W/NP11    DATE: 2002-11-01
-//
-// ABSTRACT: This routine packs up a Grid Definition Section (Section 3) 
-//   and adds it to a GRIB2 message.  It is used with routines "g2_create",
-//   "g2_addlocal", "g2_addfield",
-//   and "g2_gribend" to create a complete GRIB2 message.
-//   g2_create must be called first to initialize a new GRIB2 message.
-//
-// PROGRAM HISTORY LOG:
-// 2002-11-01  Gilbert
-//
-// USAGE:    int g2_addgrid(unsigned char *cgrib,g2int *igds,g2int *igdstmpl,
-//                          g2int *ideflist,g2int idefnum)
-//   INPUT ARGUMENTS:
-//     cgrib    - Char array that contains the GRIB2 message to which
-//                section should be added.
-//     igds     - Contains information needed for GRIB Grid Definition Section 3
-//                Must be dimensioned >= 5.
-//                igds[0]=Source of grid definition (see Code Table 3.0)
-//                igds[1]=Number of grid points in the defined grid.
-//                igds[2]=Number of octets needed for each 
-//                            additional grid points definition.  
-//                            Used to define number of
-//                            points in each row ( or column ) for
-//                            non-regular grids.  
-//                            = 0, if using regular grid.
-//                igds[3]=Interpretation of list for optional points 
-//                            definition.  (Code Table 3.11)
-//                igds[4]=Grid Definition Template Number (Code Table 3.1)
-//     igdstmpl - Contains the data values for the specified Grid Definition
-//                Template ( NN=igds[4] ).  Each element of this integer 
-//                array contains an entry (in the order specified) of Grid
-//                Defintion Template 3.NN
-//     ideflist - (Used if igds[2] != 0)  This array contains the
-//                number of grid points contained in each row ( or column )
-//      idefnum - (Used if igds[2] != 0)  The number of entries
-//                in array ideflist.  i.e. number of rows ( or columns )
-//                for which optional grid points are defined.
-//
-//   OUTPUT ARGUMENTS:      
-//     cgrib    - Char array to contain the updated GRIB2 message.
-//                Must be allocated large enough to store the entire
-//                GRIB2 message.
-//
-//   RETURN VALUES:
-//     ierr     - Return code.
-//              > 0 = Current size of updated GRIB2 message
-//               -1 = GRIB message was not initialized.  Need to call
-//                    routine gribcreate first.
-//               -2 = GRIB message already complete.  Cannot add new section.
-//               -3 = Sum of Section byte counts doesn't add to total byte count
-//               -4 = Previous Section was not 1, 2 or 7.
-//               -5 = Could not find requested Grid Definition Template.
-//
-// REMARKS: Note that the Grid Def Section ( Section 3 ) can only follow
-//          Section 1, 2 or Section 7 in a GRIB2 message.
-//
-// ATTRIBUTES:
-//   LANGUAGE: C
-//   MACHINE:  
-//
-//$$$
-{
-
-      g2int ierr;
-      static unsigned char G=0x47;       // 'G'
-      static unsigned char R=0x52;       // 'R'
-      static unsigned char I=0x49;       // 'I'
-      static unsigned char B=0x42;       // 'B'
-      static unsigned char seven=0x37;   // '7'
-
-      static g2int one=1,three=3,miss=65535;
-      g2int   lensec3,iofst,ibeg,lencurr,len;
-      g2int   i,j,temp,ilen,isecnum,nbits;
-      template *mapgrid=0;
- 
-      ierr=0;
-//
-//  Check to see if beginning of GRIB message exists
-//
-      if ( cgrib[0]!=G || cgrib[1]!=R || cgrib[2]!=I || cgrib[3]!=B ) {
-        printf("g2_addgrid: GRIB not found in given message.\n");
-        printf("g2_addgrid: Call to routine gribcreate required to initialize GRIB messge.\n");
-        ierr=-1;
-        return(ierr);
-      }
-//
-//  Get current length of GRIB message
-//  
-      gbit(cgrib,&lencurr,96,32);
-//
-//  Check to see if GRIB message is already complete
-//  
-      if ( cgrib[lencurr-4]==seven && cgrib[lencurr-3]==seven &&
-           cgrib[lencurr-2]==seven && cgrib[lencurr-1]==seven ) {
-        printf("g2_addgrid: GRIB message already complete.  Cannot add new section.\n");
-        ierr=-2;
-        return(ierr);
-      }
-//
-//  Loop through all current sections of the GRIB message to
-//  find the last section number.
-//
-      len=16;    // length of Section 0
-      for (;;) { 
-      //    Get section number and length of next section
-        iofst=len*8;
-        gbit(cgrib,&ilen,iofst,32);
-        iofst=iofst+32;
-        gbit(cgrib,&isecnum,iofst,8);
-        len=len+ilen;
-      //    Exit loop if last section reached
-        if ( len == lencurr ) break;
-      //    If byte count for each section doesn't match current
-      //    total length, then there is a problem.
-        if ( len > lencurr ) {
-          printf("g2_addgrid: Section byte counts don''t add to total.\n");
-          printf("g2_addgrid: Sum of section byte counts = %ld\n",len);
-          printf("g2_addgrid: Total byte count in Section 0 = %ld\n",lencurr);
-          ierr=-3;
-          return(ierr);
-        }
-      }
-//
-//  Section 3 can only be added after sections 1, 2 and 7.
-//
-      if ( (isecnum!=1) && (isecnum!=2) && (isecnum!=7) ) {
-        printf("g2_addgrid: Section 3 can only be added after Section 1, 2 or 7.\n");
-        printf("g2_addgrid: Section ',isecnum,' was the last found in given GRIB message.\n");
-        ierr=-4;
-        return(ierr);
-      }
-//
-//  Add Section 3  - Grid Definition Section
-//
-      ibeg=lencurr*8;        //   Calculate offset for beginning of section 3
-      iofst=ibeg+32;         //   leave space for length of section
-      sbit(cgrib,&three,iofst,8);     // Store section number ( 3 )
-      iofst=iofst+8;
-      sbit(cgrib,igds+0,iofst,8);     // Store source of Grid def.
-      iofst=iofst+8;
-      sbit(cgrib,igds+1,iofst,32);    // Store number of data pts.
-      iofst=iofst+32;
-      sbit(cgrib,igds+2,iofst,8);     // Store number of extra octets.
-      iofst=iofst+8;
-      sbit(cgrib,igds+3,iofst,8);     // Store interp. of extra octets.
-      iofst=iofst+8;
-      //   if Octet 6 is not equal to zero, Grid Definition Template may
-      //   not be supplied.
-      if ( igds[0] == 0 )
-        sbit(cgrib,igds+4,iofst,16);  // Store Grid Def Template num.
-      else
-        sbit(cgrib,&miss,iofst,16);   // Store missing value as Grid Def Template num.
-      iofst=iofst+16;
-      //
-      //   Get Grid Definition Template
-      //
-      if (igds[0] == 0) {
-        mapgrid=getgridtemplate(igds[4]);
-        if (mapgrid == 0) {       // undefined template
-          ierr=-5;
-          return(ierr);
-        }
-        //
-        //   Extend the Grid Definition Template, if necessary.
-        //   The number of values in a specific template may vary
-        //   depending on data specified in the "static" part of the
-        //   template.
-        //
-        if ( mapgrid->needext ) {
-          free(mapgrid);
-          mapgrid=extgridtemplate(igds[4],igdstmpl);
-        }
-      }
-      //
-      //   Pack up each input value in array igdstmpl into the
-      //   the appropriate number of octets, which are specified in
-      //   corresponding entries in array mapgrid.
-      //
-      for (i=0;i<mapgrid->maplen;i++) {
-        nbits=abs(mapgrid->map[i])*8;
-        if ( (mapgrid->map[i] >= 0) || (igdstmpl[i] >= 0) )
-          sbit(cgrib,igdstmpl+i,iofst,nbits);
-        else {
-          sbit(cgrib,&one,iofst,1);
-          temp=abs(igdstmpl[i]);
-          sbit(cgrib,&temp,iofst+1,nbits-1);
-        }
-        iofst=iofst+nbits;
-      }
-      //  Pack template extension, if appropriate
-      j=mapgrid->maplen;
-      if ( mapgrid->needext && (mapgrid->extlen > 0) ) {
-         for (i=0;i<mapgrid->extlen;i++) {
-           nbits=abs(mapgrid->ext[i])*8;
-           if ( (mapgrid->ext[i] >= 0) || (igdstmpl[j] >= 0) )
-             sbit(cgrib,igdstmpl+j,iofst,nbits);
-           else {
-             sbit(cgrib,&one,iofst,1);
-             temp=abs(igdstmpl[j]);
-             sbit(cgrib,&temp,iofst+1,nbits-1);
-           }
-           iofst=iofst+nbits;
-           j++;
-         }
-      }
-      free(mapgrid);
-      //
-      //   If requested,
-      //   Insert optional list of numbers defining number of points
-      //   in each row or column.  This is used for non regular
-      //   grids.
-      //
-      if ( igds[2] != 0 ) {
-         nbits=igds[2]*8;
-         sbits(cgrib,ideflist,iofst,nbits,0,idefnum);
-         iofst=iofst+(nbits*idefnum);
-      }
-      //
-      //   Calculate length of section 3 and store it in octets
-      //   1-4 of section 3.
-      //
-      lensec3=(iofst-ibeg)/8;
-      sbit(cgrib,&lensec3,ibeg,32);
-
-//
-//  Update current byte total of message in Section 0
-//
-      lencurr+=lensec3;
-      sbit(cgrib,&lencurr,96,32);
-
-      return(lencurr);
-
-}
diff --git a/src/modules/io/io_grid_grib2/g2clib-1.0.4/g2_addlocal.c b/src/modules/io/io_grid_grib2/g2clib-1.0.4/g2_addlocal.c
deleted file mode 100644
index 97b941a..0000000
--- a/src/modules/io/io_grid_grib2/g2clib-1.0.4/g2_addlocal.c
+++ /dev/null
@@ -1,150 +0,0 @@
-/**********************************************************
- * Version $Id: g2_addlocal.c 911 2011-02-14 16:38:15Z reklov_w $
- *********************************************************/
-#include <stdio.h>
-#include "grib2.h"
-
-g2int g2_addlocal(unsigned char *cgrib,unsigned char *csec2,g2int lcsec2)
-//$$$  SUBPROGRAM DOCUMENTATION BLOCK
-//                .      .    .                                       .
-// SUBPROGRAM:    g2_addlocal 
-//   PRGMMR: Gilbert         ORG: W/NP11    DATE: 2002-11-01
-//
-// ABSTRACT: This routine adds a Local Use Section (Section 2) to 
-//   a GRIB2 message.  It is used with routines "g2_create", 
-//   "g2_addgrid", "g2_addfield",
-//   and "g2_gribend" to create a complete GRIB2 message.  
-//   g2_create must be called first to initialize a new GRIB2 message.
-//
-// PROGRAM HISTORY LOG:
-// 2002-11-01  Gilbert
-//
-// USAGE:    int g2_addlocal(unsigned char *cgrib,unsigned char *csec2,
-//                           g2int lcsec2)
-//   INPUT ARGUMENTS:
-//     cgrib    - Char array that contains the GRIB2 message to which section
-//                2 should be added.
-//     csec2    - Character array containing information to be added in
-//                Section 2.
-//     lcsec2   - Number of bytes of character array csec2 to be added to
-//                Section 2.
-//
-//   OUTPUT ARGUMENT:      
-//     cgrib    - Char array to contain the updated GRIB2 message.
-//                Must be allocated large enough to store the entire
-//                GRIB2 message.
-//
-//   RETURN VALUES:
-//     ierr     - Return code.
-//              > 0 = Current size of updated GRIB2 message
-//               -1 = GRIB message was not initialized.  Need to call
-//                    routine gribcreate first.
-//               -2 = GRIB message already complete.  Cannot add new section.
-//               -3 = Sum of Section byte counts doesn't add to total byte count
-//               -4 = Previous Section was not 1 or 7.
-//
-// REMARKS: Note that the Local Use Section ( Section 2 ) can only follow
-//          Section 1 or Section 7 in a GRIB2 message.
-//
-// ATTRIBUTES:
-//   LANGUAGE: C
-//   MACHINE: 
-//
-//$$$
-{
-
-      g2int ierr; 
-      static unsigned char G=0x47;       // 'G'
-      static unsigned char R=0x52;       // 'R'
-      static unsigned char I=0x49;       // 'I'
-      static unsigned char B=0x42;       // 'B'
-      static unsigned char seven=0x37;   // '7'
-
-      static g2int two=2;
-      g2int   j,k,lensec2,iofst,ibeg,lencurr,ilen,len,istart;
-      g2int   isecnum;
- 
-      ierr=0;
-//
-//  Check to see if beginning of GRIB message exists
-//
-      if ( cgrib[0]!=G || cgrib[1]!=R || cgrib[2]!=I || cgrib[3]!=B ) {
-        printf("g2_addlocal: GRIB not found in given message.\n");
-        printf("g2_addlocal: Call to routine g2_create required to initialize GRIB messge.\n");
-        ierr=-1;
-        return(ierr);
-      }
-//
-//  Get current length of GRIB message
-//  
-      gbit(cgrib,&lencurr,96,32);
-//
-//  Check to see if GRIB message is already complete
-//  
-      if ( cgrib[lencurr-4]==seven && cgrib[lencurr-3]==seven && 
-           cgrib[lencurr-2]==seven && cgrib[lencurr-1]==seven ) {
-        printf("g2_addlocal: GRIB message already complete.  Cannot add new section.\n");
-        ierr=-2;
-        return(ierr);
-      }
-//
-//  Loop through all current sections of the GRIB message to
-//  find the last section number.
-//
-      len=16;    // length of Section 0
-      for (;;) { 
-      //    Get section number and length of next section
-        iofst=len*8;
-        gbit(cgrib,&ilen,iofst,32);
-        iofst=iofst+32;
-        gbit(cgrib,&isecnum,iofst,8);
-        len=len+ilen;
-      //    Exit loop if last section reached
-        if ( len == lencurr ) break;
-      //    If byte count for each section doesn't match current
-      //    total length, then there is a problem.
-        if ( len > lencurr ) {
-          printf("g2_addlocal: Section byte counts don't add to total.\n");
-          printf("g2_addlocal: Sum of section byte counts = %ld\n",len);
-          printf("g2_addlocal: Total byte count in Section 0 = %ld\n",lencurr);
-          ierr=-3;
-          return(ierr);
-        }
-      }
-//
-//  Section 2 can only be added after sections 1 and 7.
-//
-      if ( (isecnum!=1) && (isecnum!=7) ) {
-        printf("g2_addlocal: Section 2 can only be added after Section 1 or Section 7.\n");
-        printf("g2_addlocal: Section %ld was the last found in given GRIB message.\n",isecnum);
-        ierr=-4;
-        return(ierr);
-      }
-//
-//  Add Section 2  - Local Use Section
-//
-      ibeg=lencurr*8;        //   Calculate offset for beginning of section 2
-      iofst=ibeg+32;         //   leave space for length of section
-      sbit(cgrib,&two,iofst,8);     // Store section number ( 2 )
-      istart=lencurr+5;
-      //cgrib(istart+1:istart+lcsec2)=csec2(1:lcsec2)
-      k=0;
-      for (j=istart;j<istart+lcsec2;j++) {
-         cgrib[j]=csec2[k++];
-      }
-      //
-      //   Calculate length of section 2 and store it in octets
-      //   1-4 of section 2.
-      //
-      lensec2=lcsec2+5;      // bytes
-      sbit(cgrib,&lensec2,ibeg,32);
-
-//
-//  Update current byte total of message in Section 0
-//
-      lencurr+=lensec2;
-      sbit(cgrib,&lencurr,96,32);
-
-      return(lencurr);
-
-}
diff --git a/src/modules/io/io_grid_grib2/g2clib-1.0.4/g2_create.c b/src/modules/io/io_grid_grib2/g2clib-1.0.4/g2_create.c
deleted file mode 100644
index 6683650..0000000
--- a/src/modules/io/io_grid_grib2/g2clib-1.0.4/g2_create.c
+++ /dev/null
@@ -1,130 +0,0 @@
-/**********************************************************
- * Version $Id: g2_create.c 911 2011-02-14 16:38:15Z reklov_w $
- *********************************************************/
-#include <stdio.h>
-#include "grib2.h"
-
-#define MAPSEC1LEN 13
-
-g2int g2_create(unsigned char *cgrib,g2int *listsec0,g2int *listsec1)
-//$$$  SUBPROGRAM DOCUMENTATION BLOCK
-//                .      .    .                                       .
-// SUBPROGRAM:    g2_create 
-//   PRGMMR: Gilbert         ORG: W/NP11    DATE: 2002-10-31
-//
-// ABSTRACT: This routine initializes a new GRIB2 message and packs
-//   GRIB2 sections 0 (Indicator Section) and 1 (Identification Section).
-//   This routine is used with routines "g2_addlocal", "g2_addgrid", 
-//   "g2_addfield", and "g2_gribend" to create a complete GRIB2 message.  
-//   g2_create must be called first to initialize a new GRIB2 message.
-//   Also, a call to g2_gribend is required to complete GRIB2 message
-//   after all fields have been added.
-//
-// PROGRAM HISTORY LOG:
-// 2002-10-31  Gilbert
-//
-// USAGE:    int g2_create(unsigned char *cgrib,g2int *listsec0,g2int *listsec1)
-//   INPUT ARGUMENTS:
-//     cgrib    - Character array to contain the GRIB2 message
-//     listsec0 - Contains information needed for GRIB Indicator Section 0.
-//                Must be dimensioned >= 2.
-//                listsec0[0]=Discipline-GRIB Master Table Number
-//                            (see Code Table 0.0)
-//                listsec0[1]=GRIB Edition Number (currently 2)
-//     listsec1 - Contains information needed for GRIB Identification Section 1.
-//                Must be dimensioned >= 13.
-//                listsec1[0]=Id of orginating centre (Common Code Table C-1)
-//                listsec1[1]=Id of orginating sub-centre (local table)
-//                listsec1[2]=GRIB Master Tables Version Number (Code Table 1.0)
-//                listsec1[3]=GRIB Local Tables Version Number (Code Table 1.1)
-//                listsec1[4]=Significance of Reference Time (Code Table 1.2)
-//                listsec1[5]=Reference Time - Year (4 digits)
-//                listsec1[6]=Reference Time - Month
-//                listsec1[7]=Reference Time - Day
-//                listsec1[8]=Reference Time - Hour
-//                listsec1[9]=Reference Time - Minute
-//                listsec1[10]=Reference Time - Second
-//                listsec1[11]=Production status of data (Code Table 1.3)
-//                listsec1[12]=Type of processed data (Code Table 1.4)
-//
-//   OUTPUT ARGUMENTS:      
-//     cgrib    - Char array to contain the new GRIB2 message.
-//                Must be allocated large enough to store the entire
-//                GRIB2 message.
-//
-//   RETURN VALUES:
-//     ierr     - return code.
-//              > 0 = Current size of new GRIB2 message
-//               -1 = Tried to use for version other than GRIB Edition 2
-//
-// REMARKS: This routine is intended for use with routines "g2_addlocal", 
-//          "g2_addgrid", "g2_addfield", and "g2_gribend" to create a complete 
-//          GRIB2 message.
-//
-// ATTRIBUTES:
-//   LANGUAGE: C
-//   MACHINE:  
-//
-//$$$
-{
-
-      g2int  ierr;
-      g2int   zero=0,one=1;
-      g2int   mapsec1len=MAPSEC1LEN;
-      g2int   mapsec1[MAPSEC1LEN]={ 2,2,1,1,1,2,1,1,1,1,1,1,1 };
-      g2int   i,lensec0,lensec1,iofst,ibeg,nbits,len;
-
-      ierr=0;
-//
-//  Currently handles only GRIB Edition 2.
-//  
-      if (listsec0[1] != 2) {
-        printf("g2_create: can only code GRIB edition 2.");
-        ierr=-1;
-        return (ierr);
-      }
-//
-//  Pack Section 0 - Indicator Section 
-//  ( except for total length of GRIB message )
-//
-      cgrib[0]=0x47;   // 'G'            // Beginning of GRIB message
-      cgrib[1]=0x52;   // 'R'
-      cgrib[2]=0x49;   // 'I'
-      cgrib[3]=0x42;   // 'B'
-      sbit(cgrib,&zero,32,16);           // reserved for future use
-      sbit(cgrib,listsec0+0,48,8);       // Discipline
-      sbit(cgrib,listsec0+1,56,8);       // GRIB edition number
-      lensec0=16;      // bytes (octets)
-//
-//  Pack Section 1 - Identification Section
-//
-      ibeg=lensec0*8;        //   Calculate offset for beginning of section 1
-      iofst=ibeg+32;         //   leave space for length of section
-      sbit(cgrib,&one,iofst,8);     // Store section number ( 1 )
-      iofst=iofst+8;
-      //
-      //   Pack up each input value in array listsec1 into the
-      //   the appropriate number of octets, which are specified in
-      //   corresponding entries in array mapsec1.
-      //
-      for (i=0;i<mapsec1len;i++) {
-        nbits=mapsec1[i]*8;
-        sbit(cgrib,listsec1+i,iofst,nbits);
-        iofst=iofst+nbits;
-      }
-      //
-      //   Calculate length of section 1 and store it in octets
-      //   1-4 of section 1.
-      //
-      lensec1=(iofst-ibeg)/8;
-      sbit(cgrib,&lensec1,ibeg,32);
-//
-//  Put current byte total of message into Section 0
-//
-      sbit(cgrib,&zero,64,32);
-      len=lensec0+lensec1;
-      sbit(cgrib,&len,96,32);
-
-      return (len);
-
-}
diff --git a/src/modules/io/io_grid_grib2/g2clib-1.0.4/g2_free.c b/src/modules/io/io_grid_grib2/g2clib-1.0.4/g2_free.c
deleted file mode 100644
index 0a99e4c..0000000
--- a/src/modules/io/io_grid_grib2/g2clib-1.0.4/g2_free.c
+++ /dev/null
@@ -1,47 +0,0 @@
-/**********************************************************
- * Version $Id: g2_free.c 911 2011-02-14 16:38:15Z reklov_w $
- *********************************************************/
-#include <stdlib.h>
-#include  "grib2.h"
-
-void g2_free(gribfield *gfld)
-//$$$  SUBPROGRAM DOCUMENTATION BLOCK
-//                .      .    .                                       .
-// SUBPROGRAM:    g2_free 
-//   PRGMMR: Gilbert         ORG: W/NP11    DATE: 2002-10-28
-//
-// ABSTRACT: This routine frees up memory that was allocated for
-//   struct gribfield.
-//
-// PROGRAM HISTORY LOG:
-// 2002-10-28  Gilbert
-//
-// USAGE:    g2_free(gribfield *gfld)
-//   ARGUMENT:
-//     gfld - pointer to gribfield structure (defined in include file grib2.h)
-//            returned from routine g2_getfld.
-//
-// REMARKS:  This routine must be called to free up memory used by
-//           the decode routine, g2_getfld, when user no longer needs to
-//           reference this data.
-//
-// ATTRIBUTES:
-//   LANGUAGE: C
-//   MACHINE:  
-//
-//$$$
-{ 
-
-      if (gfld->idsect != 0 ) free(gfld->idsect);
-      if (gfld->local != 0 ) free(gfld->local);
-      if (gfld->list_opt != 0 ) free(gfld->list_opt);
-      if (gfld->igdtmpl != 0 ) free(gfld->igdtmpl);
-      if (gfld->ipdtmpl != 0 ) free(gfld->ipdtmpl);
-      if (gfld->coord_list != 0 ) free(gfld->coord_list);
-      if (gfld->idrtmpl != 0 ) free(gfld->idrtmpl);
-      if (gfld->bmap != 0 ) free(gfld->bmap);
-      if (gfld->fld != 0 ) free(gfld->fld);
-      free(gfld);
-
-      return;
-}
diff --git a/src/modules/io/io_grid_grib2/g2clib-1.0.4/g2_getfld.c b/src/modules/io/io_grid_grib2/g2clib-1.0.4/g2_getfld.c
deleted file mode 100644
index efc6897..0000000
--- a/src/modules/io/io_grid_grib2/g2clib-1.0.4/g2_getfld.c
+++ /dev/null
@@ -1,553 +0,0 @@
-/**********************************************************
- * Version $Id: g2_getfld.c 911 2011-02-14 16:38:15Z reklov_w $
- *********************************************************/
-#include <stdio.h>
-#include <stdlib.h>
-#include "grib2.h"
-
-g2int g2_unpack1(unsigned char *,g2int *,g2int **,g2int *);
-g2int g2_unpack2(unsigned char *,g2int *,g2int *,unsigned char **);
-g2int g2_unpack3(unsigned char *,g2int *,g2int **,g2int **,
-                         g2int *,g2int **,g2int *);
-g2int g2_unpack4(unsigned char *,g2int *,g2int *,g2int **,
-                         g2int *,g2float **,g2int *);
-g2int g2_unpack5(unsigned char *,g2int *,g2int *,g2int *, g2int **,g2int *);
-g2int g2_unpack6(unsigned char *,g2int *,g2int ,g2int *, g2int **);
-g2int g2_unpack7(unsigned char *,g2int *,g2int ,g2int *,
-                         g2int ,g2int *,g2int ,g2float **);
-
-g2int g2_getfld(unsigned char *cgrib,g2int ifldnum,g2int unpack,g2int expand,
-                gribfield **gfld)
-//$$$  SUBPROGRAM DOCUMENTATION BLOCK
-//                .      .    .                                       .
-// SUBPROGRAM:    g2_getfld 
-//   PRGMMR: Gilbert         ORG: W/NP11    DATE: 2002-10-28
-//
-// ABSTRACT: This subroutine returns all the metadata, template values, 
-//   Bit-map ( if applicable ), and the unpacked data for a given data
-//   field.  All of the information returned is stored in a gribfield
-//   structure, which is defined in file grib2.h.
-//   Users of this routine will need to include "grib2.h" in their source
-//   code that calls this routine.  Each component of the gribfield
-//   struct is also described in the OUTPUT ARGUMENTS section below.
-//
-//   Since there can be multiple data fields packed into a GRIB2
-//   message, the calling routine indicates which field is being requested
-//   with the ifldnum argument.
-//
-// PROGRAM HISTORY LOG:
-// 2002-10-28  Gilbert
-//
-// USAGE:    #include "grib2.h"
-//           int g2_getfld(unsigned char *cgrib,g2int ifldnum,g2int unpack,
-//                         g2int expand,gribfield **gfld)
-//   INPUT ARGUMENTS:
-//     cgrib    - Character pointer to the GRIB2 message
-//     ifldnum  - Specifies which field in the GRIB2 message to return.
-//     unpack   - Boolean value indicating whether to unpack bitmap/data field
-//                1 = unpack bitmap (if present) and data values
-//                0 = do not unpack bitmap and data values
-//     expand   - Boolean value indicating whether the data points should be 
-//                expanded to the correspond grid, if a bit-map is present.
-//                1 = if possible, expand data field to grid, inserting zero 
-//                    values at gridpoints that are bitmapped out. 
-//                    (SEE REMARKS2)
-//                0 = do not expand data field, leaving it an array of
-//                    consecutive data points for each "1" in the bitmap.
-//                This argument is ignored if unpack == 0 OR if the
-//                returned field does not contain a bit-map.
-//
-//   OUTPUT ARGUMENT:      
-//     gribfield gfld; - pointer to structure gribfield containing
-//                       all decoded data for the data field.
-// 
-//        gfld->version = GRIB edition number ( currently 2 )
-//        gfld->discipline = Message Discipline ( see Code Table 0.0 )
-//        gfld->idsect = Contains the entries in the Identification
-//                        Section ( Section 1 )
-//                        This element is a pointer to an array
-//                        that holds the data.
-//            gfld->idsect[0]  = Identification of originating Centre
-//                                    ( see Common Code Table C-1 )
-//                             7 - US National Weather Service
-//            gfld->idsect[1]  = Identification of originating Sub-centre
-//            gfld->idsect[2]  = GRIB Master Tables Version Number
-//                                    ( see Code Table 1.0 )
-//                             0 - Experimental
-//                             1 - Initial operational version number
-//            gfld->idsect[3]  = GRIB Local Tables Version Number
-//                                    ( see Code Table 1.1 )
-//                             0     - Local tables not used
-//                             1-254 - Number of local tables version used
-//            gfld->idsect[4]  = Significance of Reference Time (Code Table 1.2)
-//                             0 - Analysis
-//                             1 - Start of forecast
-//                             2 - Verifying time of forecast
-//                             3 - Observation time
-//            gfld->idsect[5]  = Year ( 4 digits )
-//            gfld->idsect[6]  = Month
-//            gfld->idsect[7)  = Day
-//            gfld->idsect[8]  = Hour
-//            gfld->idsect[9]  = Minute
-//            gfld->idsect[10]  = Second
-//            gfld->idsect[11]  = Production status of processed data
-//                                    ( see Code Table 1.3 )
-//                              0 - Operational products
-//                              1 - Operational test products
-//                              2 - Research products
-//                              3 - Re-analysis products
-//            gfld->idsect[12]  = Type of processed data ( see Code Table 1.4 )
-//                              0  - Analysis products
-//                              1  - Forecast products
-//                              2  - Analysis and forecast products
-//                              3  - Control forecast products
-//                              4  - Perturbed forecast products
-//                              5  - Control and perturbed forecast products
-//                              6  - Processed satellite observations
-//                              7  - Processed radar observations
-//        gfld->idsectlen = Number of elements in gfld->idsect[].
-//        gfld->local   = Pointer to character array containing contents
-//                       of Local Section 2, if included
-//        gfld->locallen = length of array gfld->local[]
-//        gfld->ifldnum = field number within GRIB message
-//        gfld->griddef = Source of grid definition (see Code Table 3.0)
-//                      0 - Specified in Code table 3.1
-//                      1 - Predetermined grid Defined by originating centre
-//        gfld->ngrdpts = Number of grid points in the defined grid.
-//        gfld->numoct_opt = Number of octets needed for each
-//                          additional grid points definition.
-//                          Used to define number of
-//                          points in each row ( or column ) for
-//                          non-regular grids.
-//                          = 0, if using regular grid.
-//        gfld->interp_opt = Interpretation of list for optional points
-//                          definition.  (Code Table 3.11)
-//        gfld->igdtnum = Grid Definition Template Number (Code Table 3.1)
-//        gfld->igdtmpl  = Contains the data values for the specified Grid
-//                         Definition Template ( NN=gfld->igdtnum ).  Each
-//                         element of this integer array contains an entry (in
-//                         the order specified) of Grid Defintion Template 3.NN
-//                         This element is a pointer to an array
-//                         that holds the data.
-//        gfld->igdtlen = Number of elements in gfld->igdtmpl[].  i.e. number of
-//                       entries in Grid Defintion Template 3.NN
-//                       ( NN=gfld->igdtnum ).
-//        gfld->list_opt  = (Used if gfld->numoct_opt .ne. 0)  This array
-//                          contains the number of grid points contained in
-//                          each row ( or column ).  (part of Section 3)
-//                          This element is a pointer to an array
-//                          that holds the data.  This pointer is nullified
-//                          if gfld->numoct_opt=0.
-//        gfld->num_opt = (Used if gfld->numoct_opt .ne. 0) 
-//                        The number of entries
-//                       in array ideflist.  i.e. number of rows ( or columns )
-//                       for which optional grid points are defined.  This value
-//                       is set to zero, if gfld->numoct_opt=0.
-//        gfdl->ipdtnum = Product Definition Template Number(see Code Table 4.0)
-//        gfld->ipdtmpl  = Contains the data values for the specified Product
-//                         Definition Template ( N=gfdl->ipdtnum ). Each element
-//                         of this integer array contains an entry (in the
-//                         order specified) of Product Defintion Template 4.N.
-//                         This element is a pointer to an array
-//                         that holds the data.
-//        gfld->ipdtlen = Number of elements in gfld->ipdtmpl[].  i.e. number of
-//                       entries in Product Defintion Template 4.N
-//                       ( N=gfdl->ipdtnum ).
-//        gfld->coord_list  = Real array containing floating point values
-//                            intended to document the vertical discretisation
-//                            associated to model data on hybrid coordinate
-//                            vertical levels.  (part of Section 4)
-//                            This element is a pointer to an array
-//                            that holds the data.
-//        gfld->num_coord = number of values in array gfld->coord_list[].
-//        gfld->ndpts = Number of data points unpacked and returned.
-//        gfld->idrtnum = Data Representation Template Number
-//                       ( see Code Table 5.0)
-//        gfld->idrtmpl  = Contains the data values for the specified Data
-//                         Representation Template ( N=gfld->idrtnum ).  Each
-//                         element of this integer array contains an entry
-//                         (in the order specified) of Product Defintion
-//                         Template 5.N.
-//                         This element is a pointer to an array
-//                         that holds the data.
-//        gfld->idrtlen = Number of elements in gfld->idrtmpl[].  i.e. number
-//                       of entries in Data Representation Template 5.N
-//                       ( N=gfld->idrtnum ).
-//        gfld->unpacked = logical value indicating whether the bitmap and
-//                        data values were unpacked.  If false,
-//                        gfld->bmap and gfld->fld pointers are nullified.
-//        gfld->expanded = Logical value indicating whether the data field 
-//                         was expanded to the grid in the case where a 
-//                         bit-map is present.  If true, the data points in
-//                         gfld->fld match the grid points and zeros were 
-//                         inserted at grid points where data was bit-mapped
-//                         out.  If false, the data values in gfld->fld were
-//                         not expanded to the grid and are just a consecutive
-//                         array of data points corresponding to each value of
-//                         "1" in gfld->bmap.
-//        gfld->ibmap = Bitmap indicator ( see Code Table 6.0 )
-//                     0 = bitmap applies and is included in Section 6.
-//                     1-253 = Predefined bitmap applies
-//                     254 = Previously defined bitmap applies to this field
-//                     255 = Bit map does not apply to this product.
-//        gfld->bmap  = integer array containing decoded bitmap,
-//                      if gfld->ibmap=0 or gfld->ibap=254.  Otherwise nullified
-//                      This element is a pointer to an array
-//                      that holds the data.
-//        gfld->fld  = Array of gfld->ndpts unpacked data points.
-//                     This element is a pointer to an array
-//                     that holds the data.
-//
-// 
-//   RETURN VALUES:
-//     ierr     - Error return code.
-//                0 = no error
-//                1 = Beginning characters "GRIB" not found.
-//                2 = GRIB message is not Edition 2.
-//                3 = The data field request number was not positive.
-//                4 = End string "7777" found, but not where expected.
-//                6 = GRIB message did not contain the requested number of
-//                    data fields.
-//                7 = End string "7777" not found at end of message.
-//                8 = Unrecognized Section encountered.
-//                9 = Data Representation Template 5.NN not yet implemented.
-//               15 = Error unpacking Section 1.
-//               16 = Error unpacking Section 2.
-//               10 = Error unpacking Section 3.
-//               11 = Error unpacking Section 4.
-//               12 = Error unpacking Section 5.
-//               13 = Error unpacking Section 6.
-//               14 = Error unpacking Section 7.
-//               17 = Previous bitmap specified, yet none exists.
-//
-// REMARKS: Note that struct gribfield is allocated by this routine and it
-//          also contains pointers to many arrays of data that were allocated
-//          during decoding.  Users are encouraged to free up this memory, 
-//          when it is no longer needed, by an explicit call to routine g2_free.
-//          EXAMPLE:
-//              #include "grib2.h"
-//              gribfield *gfld;
-//              ret=g2_getfld(cgrib,1,1,1,&gfld);
-//                ...
-//              g2_free(gfld);
-//
-//          Routine g2_info can be used to first determine
-//          how many data fields exist in a given GRIB message.
-//
-// REMARKS2: It may not always be possible to expand a bit-mapped data field.
-//           If a pre-defined bit-map is used and not included in the GRIB2
-//           message itself, this routine would not have the necessary 
-//           information to expand the data.  In this case, gfld->expanded would
-//           would be set to 0 (false), regardless of the value of input 
-//           argument expand.
-//
-// ATTRIBUTES:
-//   LANGUAGE: C
-//   MACHINE:  
-//
-//$$$
-{
-    
-      g2int have3,have4,have5,have6,have7,ierr,jerr;
-      g2int numfld,j,n,istart,iofst,ipos;
-      g2int disc,ver,lensec0,lengrib,lensec,isecnum;
-      g2int  *igds;
-      g2int *bmpsave;
-      g2float *newfld;
-      gribfield  *lgfld;
-
-      have3=0;
-      have4=0;
-      have5=0;
-      have6=0;
-      have7=0;
-      ierr=0;
-      numfld=0;
-
-      lgfld=(gribfield *)malloc(sizeof(gribfield));
-      *gfld=lgfld;
-
-      lgfld->locallen=0;
-      lgfld->idsect=0;
-      lgfld->local=0;
-      lgfld->list_opt=0;
-      lgfld->igdtmpl=0;
-      lgfld->ipdtmpl=0;
-      lgfld->idrtmpl=0;
-      lgfld->coord_list=0;
-      lgfld->bmap=0;
-      lgfld->fld=0;
-//
-//  Check for valid request number
-//  
-      if (ifldnum <= 0) {
-        printf("g2_getfld: Request for field number must be positive.\n");
-        ierr=3;
-        return(ierr);
-      }
-//
-//  Check for beginning of GRIB message in the first 100 bytes
-//
-      istart=-1;
-      for (j=0;j<100;j++) {
-        if (cgrib[j]=='G' && cgrib[j+1]=='R' &&cgrib[j+2]=='I' && 
-            cgrib[j+3]=='B') {
-          istart=j;
-          break;
-        }
-      }
-      if (istart == -1) {
-        printf("g2_getfld:  Beginning characters GRIB not found.\n");
-        ierr=1;
-        return(ierr);
-      }
-//
-//  Unpack Section 0 - Indicator Section 
-//
-      iofst=8*(istart+6);
-      gbit(cgrib,&disc,iofst,8);     // Discipline
-      iofst=iofst+8;
-      gbit(cgrib,&ver,iofst,8);     // GRIB edition number
-      iofst=iofst+8;
-      iofst=iofst+32;
-      gbit(cgrib,&lengrib,iofst,32);        // Length of GRIB message
-      iofst=iofst+32;
-      lensec0=16;
-      ipos=istart+lensec0;
-//
-//  Currently handles only GRIB Edition 2.
-//  
-      if (ver != 2) {
-        printf("g2_getfld: can only decode GRIB edition 2.\n");
-        ierr=2;
-        return(ierr);
-      }
-//
-//  Loop through the remaining sections keeping track of the 
-//  length of each.  Also keep the latest Grid Definition Section info.
-//  Unpack the requested field number.
-//
-      for (;;) {
-        //    Check to see if we are at end of GRIB message
-        if (cgrib[ipos]=='7' && cgrib[ipos+1]=='7' && cgrib[ipos+2]=='7' && 
-            cgrib[ipos+3]=='7') {
-          ipos=ipos+4;
-          //    If end of GRIB message not where expected, issue error
-          if (ipos != (istart+lengrib)) {
-            printf("g2_getfld: '7777' found, but not where expected.\n");
-            ierr=4;
-            return(ierr);
-          }
-          break;
-        }
-        //     Get length of Section and Section number
-        iofst=(ipos-1)*8;
-        iofst=ipos*8;
-        gbit(cgrib,&lensec,iofst,32);        // Get Length of Section
-        iofst=iofst+32;
-        gbit(cgrib,&isecnum,iofst,8);         // Get Section number
-        iofst=iofst+8;
-        //printf(" lensec= %ld    secnum= %ld \n",lensec,isecnum);
-        //
-        //  Check to see if section number is valid
-        //
-        if ( isecnum<1 || isecnum>7 ) {
-          printf("g2_getfld: Unrecognized Section Encountered=%ld\n",isecnum);
-          ierr=8;
-          return(ierr);
-        }
-        //
-        //   If found Section 1, decode elements in Identification Section
-        //
-        if (isecnum == 1) {
-          iofst=iofst-40;       // reset offset to beginning of section
-          jerr=g2_unpack1(cgrib,&iofst,&lgfld->idsect,&lgfld->idsectlen);
-          if (jerr !=0 ) {
-            ierr=15;
-            return(ierr);
-          }
-        }
-        //
-        //   If found Section 2, Grab local section
-        //   Save in case this is the latest one before the requested field.
-        //
-        if (isecnum == 2) {
-          iofst=iofst-40;       // reset offset to beginning of section
-          if (lgfld->local!=0) free(lgfld->local);
-          jerr=g2_unpack2(cgrib,&iofst,&lgfld->locallen,&lgfld->local);
-          if (jerr != 0) {
-            ierr=16;
-            return(ierr);
-          }
-        }
-        //
-        //   If found Section 3, unpack the GDS info using the 
-        //   appropriate template.  Save in case this is the latest
-        //   grid before the requested field.
-        //
-        if (isecnum == 3) {
-          iofst=iofst-40;       // reset offset to beginning of section
-          if (lgfld->igdtmpl!=0) free(lgfld->igdtmpl);
-          if (lgfld->list_opt!=0) free(lgfld->list_opt);
-          jerr=g2_unpack3(cgrib,&iofst,&igds,&lgfld->igdtmpl,
-                          &lgfld->igdtlen,&lgfld->list_opt,&lgfld->num_opt);
-          if (jerr == 0) {
-            have3=1;
-            lgfld->griddef=igds[0];
-            lgfld->ngrdpts=igds[1];
-            lgfld->numoct_opt=igds[2];
-            lgfld->interp_opt=igds[3];
-            lgfld->igdtnum=igds[4];
-          }
-          else {
-            ierr=10;
-            return(ierr);
-          }
-        }
-        //
-        //   If found Section 4, check to see if this field is the
-        //   one requested.
-        //
-        if (isecnum == 4) {
-          numfld=numfld+1;
-          if (numfld == ifldnum) {
-            lgfld->discipline=disc;
-            lgfld->version=ver;
-            lgfld->ifldnum=ifldnum;
-            lgfld->unpacked=unpack;
-            lgfld->expanded=0;
-            iofst=iofst-40;       // reset offset to beginning of section
-            jerr=g2_unpack4(cgrib,&iofst,&lgfld->ipdtnum,
-                            &lgfld->ipdtmpl,&lgfld->ipdtlen,&lgfld->coord_list,
-                            &lgfld->num_coord);
-            if (jerr == 0)
-              have4=1;
-            else {
-              ierr=11;
-              return(ierr);
-            }
-          }
-        }
-        //
-        //   If found Section 5, check to see if this field is the
-        //   one requested.
-        //
-        if (isecnum == 5 && numfld == ifldnum) {
-          iofst=iofst-40;       // reset offset to beginning of section
-          jerr=g2_unpack5(cgrib,&iofst,&lgfld->ndpts,&lgfld->idrtnum,
-                          &lgfld->idrtmpl,&lgfld->idrtlen);
-          if (jerr == 0)
-            have5=1;
-          else {
-            ierr=12;
-            return(ierr);
-          }
-        }
-        //
-        //   If found Section 6, Unpack bitmap.
-        //   Save in case this is the latest
-        //   bitmap before the requested field.
-        //
-        if (isecnum == 6) {
-          if (unpack) {   // unpack bitmap
-            iofst=iofst-40;           // reset offset to beginning of section
-            bmpsave=lgfld->bmap;      // save pointer to previous bitmap
-            jerr=g2_unpack6(cgrib,&iofst,lgfld->ngrdpts,&lgfld->ibmap,
-                         &lgfld->bmap);
-            if (jerr == 0) {
-              have6=1;
-              if (lgfld->ibmap == 254)     // use previously specified bitmap
-                 if( bmpsave!=0 ) 
-                    lgfld->bmap=bmpsave;
-                 else {
-                    printf("g2_getfld: Prev bit-map specified, but none exist.\n");
-                    ierr=17;
-                    return(ierr);
-                 }
-              else                         // get rid of it
-                 if( bmpsave!=0 ) free(bmpsave);
-            }
-            else {
-              ierr=13;
-              return(ierr);
-            }
-          }
-          else {    // do not unpack bitmap
-            gbit(cgrib,&lgfld->ibmap,iofst,8);      // Get BitMap Indicator
-            have6=1;
-          }
-        }
-        //
-        //   If found Section 7, check to see if this field is the
-        //   one requested.
-        //
-        if (isecnum==7 && numfld==ifldnum && unpack) {
-          iofst=iofst-40;       // reset offset to beginning of section
-          jerr=g2_unpack7(cgrib,&iofst,lgfld->igdtnum,lgfld->igdtmpl,
-                          lgfld->idrtnum,lgfld->idrtmpl,lgfld->ndpts,
-                          &lgfld->fld);
-          if (jerr == 0) {
-            have7=1;
-            //  If bitmap is used with this field, expand data field 
-            //  to grid, if possible.
-            if ( lgfld->ibmap != 255 && lgfld->bmap != 0 ) {
-               if ( expand == 1 ) {
-                  n=0;
-                  newfld=(g2float *)calloc(lgfld->ngrdpts,sizeof(g2float));
-                  for (j=0;j<lgfld->ngrdpts;j++) {
-                      if (lgfld->bmap[j]==1) newfld[j]=lgfld->fld[n++];
-                  }
-                  free(lgfld->fld);
-                  lgfld->fld=newfld;
-                  lgfld->expanded=1;
-               }
-               else {
-                  lgfld->expanded=0;
-               }
-            }
-            else {
-               lgfld->expanded=1;
-            }
-          }
-          else {
-            printf("g2_getfld: return from g2_unpack7 = %d \n",(int)jerr);
-            ierr=14;
-            return(ierr);
-          }
-        }
-        //
-        //   Check to see if we read pass the end of the GRIB
-        //   message and missed the terminator string '7777'.
-        //
-        ipos=ipos+lensec;                // Update beginning of section pointer
-        if (ipos > (istart+lengrib)) {
-          printf("g2_getfld: '7777'  not found at end of GRIB message.\n");
-          ierr=7;
-          return(ierr);
-        }
-        //
-        //  If unpacking requested, return when all sections have been
-        //  processed
-        //
-        if (unpack && have3 && have4 && have5 && have6 && have7)
-            return(ierr);
-        //
-        //  If unpacking is not requested, return when sections 
-        //  3 through 6 have been processed
-        //
-        if ((! unpack) && have3 && have4 && have5 && have6)
-            return(ierr);
-        
-      }
-
-//
-//  If exited from above loop, the end of the GRIB message was reached
-//  before the requested field was found.
-//
-      printf("g2_getfld: GRIB message contained %ld different fields.\n",numfld);
-      printf("g2_getfld: The request was for field %ld.\n",ifldnum);
-      ierr=6;
-
-      return(ierr);
-
-}
diff --git a/src/modules/io/io_grid_grib2/g2clib-1.0.4/g2_gribend.c b/src/modules/io/io_grid_grib2/g2clib-1.0.4/g2_gribend.c
deleted file mode 100644
index 2d4c55f..0000000
--- a/src/modules/io/io_grid_grib2/g2clib-1.0.4/g2_gribend.c
+++ /dev/null
@@ -1,125 +0,0 @@
-/**********************************************************
- * Version $Id: g2_gribend.c 911 2011-02-14 16:38:15Z reklov_w $
- *********************************************************/
-#include <stdio.h>
-#include "grib2.h"
-
-g2int g2_gribend(unsigned char *cgrib)
-//$$$  SUBPROGRAM DOCUMENTATION BLOCK
-//                .      .    .                                       .
-// SUBPROGRAM:    g2_gribend 
-//   PRGMMR: Gilbert         ORG: W/NP11    DATE: 2002-10-31
-//
-// ABSTRACT: This routine finalizes a GRIB2 message after all grids
-//   and fields have been added.  It adds the End Section ( "7777" )
-//   to the end of the GRIB message and calculates the length and stores
-//   it in the appropriate place in Section 0.
-//   This routine is used with routines "g2_create", "g2_addlocal", 
-//   "g2_addgrid", and "g2_addfield" to create a complete GRIB2 message.
-//   g2_create must be called first to initialize a new GRIB2 message.
-//
-// PROGRAM HISTORY LOG:
-// 2002-10-31  Gilbert
-//
-// USAGE:    int g2_gribend(unsigned char *cgrib)
-//   INPUT ARGUMENT:
-//     cgrib    - Char array containing all the data sections added
-//                be previous calls to g2_create, g2_addlocal, g2_addgrid,
-//                and g2_addfield.
-//
-//   OUTPUT ARGUMENTS:      
-//     cgrib    - Char array containing the finalized GRIB2 message
-//
-//   RETURN VALUES:
-//     ierr     - Return code.
-//              > 0 = Length of the final GRIB2 message in bytes.
-//               -1 = GRIB message was not initialized.  Need to call
-//                    routine g2_create first.
-//               -2 = GRIB message already complete.  
-//               -3 = Sum of Section byte counts doesn't add to total byte count
-//               -4 = Previous Section was not 7.
-//
-// REMARKS: This routine is intended for use with routines "g2_create", 
-//          "g2_addlocal", "g2_addgrid", and "g2_addfield" to create a complete 
-//          GRIB2 message.
-//
-// ATTRIBUTES:
-//   LANGUAGE: C
-//   MACHINE:
-//
-//$$$
-{
-
-      g2int iofst,lencurr,len,ilen,isecnum;
-      g2int   ierr,lengrib;
-      static unsigned char G=0x47;       // 'G'
-      static unsigned char R=0x52;       // 'R'
-      static unsigned char I=0x49;       // 'I'
-      static unsigned char B=0x42;       // 'B'
-      static unsigned char seven=0x37;   // '7'
- 
-      ierr=0;
-//
-//  Check to see if beginning of GRIB message exists
-//
-      if ( cgrib[0]!=G || cgrib[1]!=R || cgrib[2]!=I || cgrib[3]!=B ) {
-        printf("g2_gribend: GRIB not found in given message.\n");
-        ierr=-1;
-        return (ierr);
-      }
-//
-//  Get current length of GRIB message
-//  
-      gbit(cgrib,&lencurr,96,32);
-//
-//  Loop through all current sections of the GRIB message to
-//  find the last section number.
-//
-      len=16;    // Length of Section 0
-      for (;;) { 
-      //    Get number and length of next section
-        iofst=len*8;
-        gbit(cgrib,&ilen,iofst,32);
-        iofst=iofst+32;
-        gbit(cgrib,&isecnum,iofst,8);
-        len=len+ilen;
-      //    Exit loop if last section reached
-        if ( len == lencurr ) break;
-      //    If byte count for each section doesn't match current
-      //    total length, then there is a problem.
-        if ( len > lencurr ) {
-          printf("g2_gribend: Section byte counts don''t add to total.\n");
-          printf("g2_gribend: Sum of section byte counts = %d\n",(int)len);
-          printf("g2_gribend: Total byte count in Section 0 = %d\n",(int)lencurr);
-          ierr=-3;
-          return (ierr);
-        }
-      }
-//
-//  Can only add End Section (Section 8) after Section 7.
-//
-      if ( isecnum != 7 ) {
-        printf("g2_gribend: Section 8 can only be added after Section 7.\n");
-        printf("g2_gribend: Section %ld was the last found in given GRIB message.\n",isecnum);
-        ierr=-4;
-        return (ierr);
-      }
-//
-//  Add Section 8  - End Section
-//
-      //cgrib(lencurr+1:lencurr+4)=c7777
-      cgrib[lencurr]=seven;
-      cgrib[lencurr+1]=seven;
-      cgrib[lencurr+2]=seven;
-      cgrib[lencurr+3]=seven;
-
-//
-//  Update current byte total of message in Section 0
-//
-      lengrib=lencurr+4;
-      sbit(cgrib,&lengrib,96,32);
-
-      return (lengrib);
-
-}
-
diff --git a/src/modules/io/io_grid_grib2/g2clib-1.0.4/g2_info.c b/src/modules/io/io_grid_grib2/g2clib-1.0.4/g2_info.c
deleted file mode 100644
index fcbc49c..0000000
--- a/src/modules/io/io_grid_grib2/g2clib-1.0.4/g2_info.c
+++ /dev/null
@@ -1,193 +0,0 @@
-/**********************************************************
- * Version $Id: g2_info.c 911 2011-02-14 16:38:15Z reklov_w $
- *********************************************************/
-#include <stdio.h>
-#include <stdlib.h>
-#include "grib2.h"
-
-g2int g2_info(unsigned char *cgrib,g2int *listsec0,g2int *listsec1,
-            g2int *numfields,g2int *numlocal)
-//$$$  SUBPROGRAM DOCUMENTATION BLOCK
-//                .      .    .                                       .
-// SUBPROGRAM:    g2_info 
-//   PRGMMR: Gilbert         ORG: W/NP11    DATE: 2002-10-28
-//
-// ABSTRACT: This subroutine searches through a GRIB2 message and
-//   returns the number of gridded fields found in the message and
-//   the number (and maximum size) of Local Use Sections.
-//   Also various checks  are performed
-//   to see if the message is a valid GRIB2 message.
-//
-// PROGRAM HISTORY LOG:
-// 2002-10-28  Gilbert
-//
-// USAGE:   int g2_info(unsigned char *cgrib,g2int *listsec0,g2int *listsec1,
-//            g2int *numfields,g2int *numlocal)
-//   INPUT ARGUMENT:
-//     cgrib    - Character pointer to the GRIB2 message
-//
-//   OUTPUT ARGUMENTS:      
-//     listsec0 - pointer to an array containing information decoded from 
-//                GRIB Indicator Section 0.
-//                Must be allocated with >= 3 elements.
-//                listsec0[0]=Discipline-GRIB Master Table Number
-//                            (see Code Table 0.0)
-//                listsec0[1]=GRIB Edition Number (currently 2)
-//                listsec0[2]=Length of GRIB message
-//     listsec1 - pointer to an array containing information read from GRIB 
-//                Identification Section 1.
-//                Must be allocated with >= 13 elements.
-//                listsec1[0]=Id of orginating centre (Common Code Table C-1)
-//                listsec1[1]=Id of orginating sub-centre (local table)
-//                listsec1[2]=GRIB Master Tables Version Number (Code Table 1.0)
-//                listsec1[3]=GRIB Local Tables Version Number 
-//                listsec1[4]=Significance of Reference Time (Code Table 1.1)
-//                listsec1[5]=Reference Time - Year (4 digits)
-//                listsec1[6]=Reference Time - Month
-//                listsec1[7]=Reference Time - Day
-//                listsec1[8]=Reference Time - Hour
-//                listsec1[9]=Reference Time - Minute
-//                listsec1[10]=Reference Time - Second
-//                listsec1[11]=Production status of data (Code Table 1.2)
-//                listsec1[12]=Type of processed data (Code Table 1.3)
-//     numfields- The number of gridded fields found in the GRIB message.
-//                That is, the number of occurences of Sections 4 - 7.
-//     numlocal - The number of Local Use Sections ( Section 2 ) found in 
-//                the GRIB message.
-//
-//     RETURN VALUES:
-//     ierr     - Error return code.
-//                0 = no error
-//                1 = Beginning characters "GRIB" not found.
-//                2 = GRIB message is not Edition 2.
-//                3 = Could not find Section 1, where expected.
-//                4 = End string "7777" found, but not where expected.
-//                5 = End string "7777" not found at end of message.
-//                6 = Invalid section number found.
-//
-// REMARKS: None
-//
-// ATTRIBUTES:
-//   LANGUAGE: C
-//   MACHINE:  
-//
-//$$$
-{
- 
-      g2int ierr,mapsec1len=13;
-      g2int mapsec1[13]={2,2,1,1,1,2,1,1,1,1,1,1,1};
-      g2int  i,j,istart,iofst,lengrib,lensec0,lensec1;
-      g2int ipos,isecnum,nbits,lensec;
-
-      ierr=0;
-      *numlocal=0;
-      *numfields=0;
-//
-//  Check for beginning of GRIB message in the first 100 bytes
-//
-      istart=-1;
-      for (j=0;j<100;j++) {
-        if (cgrib[j]=='G' && cgrib[j+1]=='R' &&cgrib[j+2]=='I' &&
-            cgrib[j+3]=='B') {
-          istart=j;
-          break;
-        }
-      }
-      if (istart == -1) {
-        printf("g2_info:  Beginning characters GRIB not found.");
-        ierr=1;
-        return(ierr);
-      }
-//
-//  Unpack Section 0 - Indicator Section 
-//
-      iofst=8*(istart+6);
-      gbit(cgrib,listsec0+0,iofst,8);     // Discipline
-      iofst=iofst+8;
-      gbit(cgrib,listsec0+1,iofst,8);     // GRIB edition number
-      iofst=iofst+8;
-      iofst=iofst+32;
-      gbit(cgrib,&lengrib,iofst,32);        // Length of GRIB message
-      iofst=iofst+32;
-      listsec0[2]=lengrib;
-      lensec0=16;
-      ipos=istart+lensec0;
-//
-//  Currently handles only GRIB Edition 2.
-//  
-      if (listsec0[1] != 2) {
-        printf("g2_info: can only decode GRIB edition 2.");
-        ierr=2;
-        return(ierr);
-      }
-//
-//  Unpack Section 1 - Identification Section
-//
-      gbit(cgrib,&lensec1,iofst,32);        // Length of Section 1
-      iofst=iofst+32;
-      gbit(cgrib,&isecnum,iofst,8);         // Section number ( 1 )
-      iofst=iofst+8;
-      if (isecnum != 1) {
-        printf("g2_info: Could not find section 1.");
-        ierr=3;
-        return(ierr);
-      }
-      //
-      //   Unpack each input value in array listsec1 into the
-      //   the appropriate number of octets, which are specified in
-      //   corresponding entries in array mapsec1.
-      //
-      for (i=0;i<mapsec1len;i++) {
-        nbits=mapsec1[i]*8;
-        gbit(cgrib,listsec1+i,iofst,nbits);
-        iofst=iofst+nbits;
-      }
-      ipos=ipos+lensec1;
-//
-//  Loop through the remaining sections to see if they are valid.
-//  Also count the number of times Section 2
-//  and Section 4 appear.
-//
-      for (;;) {
-        if (cgrib[ipos]=='7' && cgrib[ipos+1]=='7' && cgrib[ipos+2]=='7' &&
-            cgrib[ipos+3]=='7') {
-          ipos=ipos+4;
-          if (ipos != (istart+lengrib)) {
-            printf("g2_info: '7777' found, but not where expected.\n");
-            ierr=4;
-            return(ierr);
-          }
-          break;
-        }
-        
-        iofst=ipos*8;
-        gbit(cgrib,&lensec,iofst,32);        // Get Length of Section
-        iofst=iofst+32;
-        gbit(cgrib,&isecnum,iofst,8);         // Get Section number
-        iofst=iofst+8;
-        ipos=ipos+lensec;                 // Update beginning of section pointer
-        if (ipos > (istart+lengrib)) {
-          printf("g2_info: '7777'  not found at end of GRIB message.\n");
-          ierr=5;
-          return(ierr);
-        }
-        if ( isecnum>=2 && isecnum<=7 ) {
-           if (isecnum == 2)      // Local Section 2
-              //   increment counter for total number of local sections found
-              (*numlocal)++;
-            
-           else if (isecnum == 4)
-              //   increment counter for total number of fields found
-              (*numfields)++;
-        }
-        else {
-           printf("g2_info: Invalid section number found in GRIB message: %ld\n"                   ,isecnum);
-           ierr=6;
-           return(ierr);
-        }
-        
-      }
-
-      return(0);
-
-}
diff --git a/src/modules/io/io_grid_grib2/g2clib-1.0.4/g2_miss.c b/src/modules/io/io_grid_grib2/g2clib-1.0.4/g2_miss.c
deleted file mode 100644
index 0bf5da3..0000000
--- a/src/modules/io/io_grid_grib2/g2clib-1.0.4/g2_miss.c
+++ /dev/null
@@ -1,72 +0,0 @@
-/**********************************************************
- * Version $Id: g2_miss.c 911 2011-02-14 16:38:15Z reklov_w $
- *********************************************************/
-#include "grib2.h"
-
-void g2_miss( gribfield *gfld, float *rmiss, int *nmiss )
-//$$$  SUBPROGRAM DOCUMENTATION BLOCK
-//                .      .    .                                       .
-// SUBPROGRAM:    g2_miss 
-//   PRGMMR: Gilbert         ORG: W/NP11    DATE: 2004-12-16
-//
-// ABSTRACT: This routine checks the Data Representation Template to see if
-// missing value management is used, and returns the missing value(s) 
-// in the data field.
-//
-// PROGRAM HISTORY LOG:
-// 2004-12-16  Gilbert
-//
-// USAGE:    g2_miss( gribfield *gfld, float *rmiss, int *nmiss )
-//                   
-//   INPUT ARGUMENT LIST:
-//     *gfld    - pointer to gribfield structure (defined in include file 
-//                   grib2.h)
-//
-//   OUTPUT ARGUMENT LIST:      
-//     rmiss    - List of the missing values used
-//     nmiss    - NUmber of the missing values included in the field
-//
-// REMARKS:  rmiss must be allocated in the calling program with enough space 
-//           hold all the missing values.
-//
-// ATTRIBUTES:
-//   LANGUAGE: C
-//   MACHINE:  IBM SP
-//
-//$$$
-{
-    g2int     itype;    
-
-    /*
-     *  Missing value management currnetly only used in
-     *  DRT's 5.2 and 5.3.
-     */
-    if ( gfld->idrtnum != 2  &&  gfld->idrtnum != 3 ) {
-       *nmiss=0;
-       return;
-    }
-                                                                                
-    itype = gfld->idrtmpl[4];
-    if ( gfld->idrtmpl[6] == 1 ) {
-         *nmiss=1;
-         if (itype == 0)
-            rdieee(gfld->idrtmpl+7,rmiss+0,1);
-         else
-            rmiss[0]=(float)gfld->idrtmpl[7];
-    }
-    else if ( gfld->idrtmpl[6] == 2 ) {
-         *nmiss=2;
-         if (itype == 0) {
-            rdieee(gfld->idrtmpl+7,rmiss+0,1);
-            rdieee(gfld->idrtmpl+8,rmiss+1,1);
-         }
-         else {
-            rmiss[0]=(float)gfld->idrtmpl[7];
-            rmiss[1]=(float)gfld->idrtmpl[8];
-         }
-    }
-    else {
-       *nmiss=0;
-    }
-
-}
diff --git a/src/modules/io/io_grid_grib2/g2clib-1.0.4/g2_unpack1.c b/src/modules/io/io_grid_grib2/g2clib-1.0.4/g2_unpack1.c
deleted file mode 100644
index 64332f8..0000000
--- a/src/modules/io/io_grid_grib2/g2clib-1.0.4/g2_unpack1.c
+++ /dev/null
@@ -1,102 +0,0 @@
-/**********************************************************
- * Version $Id: g2_unpack1.c 911 2011-02-14 16:38:15Z reklov_w $
- *********************************************************/
-#include <stdio.h>
-#include <stdlib.h>
-#include "grib2.h"
-
-g2int g2_unpack1(unsigned char *cgrib,g2int *iofst,g2int **ids,g2int *idslen)
-/*//$$$  SUBPROGRAM DOCUMENTATION BLOCK
-//                .      .    .                                       .
-// SUBPROGRAM:    g2_unpack1 
-//   PRGMMR: Gilbert         ORG: W/NP11    DATE: 2002-10-29
-//
-// ABSTRACT: This subroutine unpacks Section 1 (Identification Section)
-//           as defined in GRIB Edition 2.
-//
-// PROGRAM HISTORY LOG:
-// 2002-10-29  Gilbert
-//
-// USAGE:    int g2_unpack1(unsigned char *cgrib,g2int *iofst,g2int **ids,
-//                          g2int *idslen)
-//   INPUT ARGUMENTS:
-//     cgrib    - char array containing Section 1 of the GRIB2 message
-//     iofst    - Bit offset for the beginning of Section 1 in cgrib.
-//
-//   OUTPUT ARGUMENTS:      
-//     iofst    - Bit offset at the end of Section 1, returned.
-//     ids      - address of pointer to integer array containing information 
-//                read from Section 1, the Identification section.
-//            ids[0]  = Identification of originating Centre
-//                                 ( see Common Code Table C-1 )
-//            ids[1]  = Identification of originating Sub-centre
-//            ids[2]  = GRIB Master Tables Version Number
-//                                 ( see Code Table 1.0 )
-//            ids[3]  = GRIB Local Tables Version Number
-//                                 ( see Code Table 1.1 )
-//            ids[4]  = Significance of Reference Time (Code Table 1.2)
-//            ids[5]  = Year ( 4 digits )
-//            ids[6]  = Month
-//            ids[7]  = Day
-//            ids[8]  = Hour
-//            ids[9]  = Minute
-//            ids[10]  = Second
-//            ids[11]  = Production status of processed data
-//                                 ( see Code Table 1.3 )
-//            ids[12]  = Type of processed data ( see Code Table 1.4 )
-//     idslen   - Number of elements in ids[].
-//
-//   RETURN VALUES:
-//     ierr     - Error return code.
-//                0 = no error
-//                2 = Array passed is not section 1
-//                6 = memory allocation error
-//
-// REMARKS: 
-//
-// ATTRIBUTES:
-//   LANGUAGE: C
-//   MACHINE:
-//
-//$$$
-*/
-{
-
-      g2int i,lensec,nbits,ierr,isecnum;
-      g2int mapid[13]={2,2,1,1,1,2,1,1,1,1,1,1,1};
-
-      ierr=0;
-      *idslen=13;
-      *ids=0;
-
-      gbit(cgrib,&lensec,*iofst,32);        // Get Length of Section
-      *iofst=*iofst+32;
-      gbit(cgrib,&isecnum,*iofst,8);         // Get Section Number
-      *iofst=*iofst+8;
-
-      if ( isecnum != 1 ) {
-         ierr=2;
-         *idslen=13;
-         fprintf(stderr,"g2_unpack1: Not Section 1 data.\n");
-         return(ierr);
-      }
-
-      //
-      //   Unpack each value into array ids from the
-      //   the appropriate number of octets, which are specified in
-      //   corresponding entries in array mapid.
-      //
-      *ids=(g2int *)calloc(*idslen,sizeof(g2int));
-      if (*ids == 0) {
-         ierr=6;
-         return(ierr);
-      }
-      
-      for (i=0;i<*idslen;i++) {
-        nbits=mapid[i]*8;
-        gbit(cgrib,*ids+i,*iofst,nbits);
-        *iofst=*iofst+nbits;
-      }
-      
-      return(ierr);    // End of Section 1 processing
-}
diff --git a/src/modules/io/io_grid_grib2/g2clib-1.0.4/g2_unpack2.c b/src/modules/io/io_grid_grib2/g2clib-1.0.4/g2_unpack2.c
deleted file mode 100644
index b05cd52..0000000
--- a/src/modules/io/io_grid_grib2/g2clib-1.0.4/g2_unpack2.c
+++ /dev/null
@@ -1,82 +0,0 @@
-/**********************************************************
- * Version $Id: g2_unpack2.c 911 2011-02-14 16:38:15Z reklov_w $
- *********************************************************/
-#include <stdio.h>
-#include <stdlib.h>
-#include "grib2.h"
-
-g2int g2_unpack2(unsigned char *cgrib,g2int *iofst,g2int *lencsec2,unsigned char **csec2)
-////$$$  SUBPROGRAM DOCUMENTATION BLOCK
-//                .      .    .                                       .
-// SUBPROGRAM:    g2_unpack2 
-//   PRGMMR: Gilbert         ORG: W/NP11    DATE: 2002-10-31
-//
-// ABSTRACT: This subroutine unpacks Section 2 (Local Use Section)
-//           as defined in GRIB Edition 2.
-//
-// PROGRAM HISTORY LOG:
-// 2002-10-31  Gilbert
-//
-// USAGE:    int g2_unpack2(unsigned char *cgrib,g2int *iofst,g2int *lencsec2,
-//                          unsigned char **csec2)
-//   INPUT ARGUMENT LIST:
-//     cgrib    - char array containing Section 2 of the GRIB2 message
-//     iofst    - Bit offset for the beginning of Section 2 in cgrib.
-//
-//   OUTPUT ARGUMENT LIST:      
-//     iofst    - Bit offset at the end of Section 2, returned.
-//     lencsec2 - Length (in octets) of Local Use data
-//     csec2    - Pointer to a char array containing local use data
-//
-//   RETURN VALUES:
-//     ierr     - Error return code.
-//                0 = no error
-//                2 = Array passed is not section 2
-//                6 = memory allocation error
-//
-// REMARKS: None
-//
-// ATTRIBUTES:
-//   LANGUAGE: C
-//   MACHINE: 
-//
-//$$$//
-{
-
-      g2int ierr,isecnum;
-      g2int lensec,ipos,j;
-
-      ierr=0;
-      *lencsec2=0;
-      *csec2=0;    // NULL
-
-      gbit(cgrib,&lensec,*iofst,32);        // Get Length of Section
-      *iofst=*iofst+32;
-      *lencsec2=lensec-5;
-      gbit(cgrib,&isecnum,*iofst,8);         // Get Section Number
-      *iofst=*iofst+8;
-      ipos=(*iofst/8);
-
-      if ( isecnum != 2 ) {
-         ierr=2;
-         *lencsec2=0;
-         fprintf(stderr,"g2_unpack2: Not Section 2 data.\n");
-         return(ierr);
-      }
-
-      *csec2=(unsigned char *)malloc(*lencsec2);
-      if (*csec2 == 0) {
-         ierr=6;
-         *lencsec2=0;
-         return(ierr);
-      }
-      
-      //printf(" SAGIPO %d \n",(int)ipos);
-      for (j=0;j<*lencsec2;j++) {
-         *(*csec2+j)=cgrib[ipos+j];
-      }
-      *iofst=*iofst+(*lencsec2*8);
-
-      return(ierr);    // End of Section 2 processing
-
-}
diff --git a/src/modules/io/io_grid_grib2/g2clib-1.0.4/g2_unpack3.c b/src/modules/io/io_grid_grib2/g2clib-1.0.4/g2_unpack3.c
deleted file mode 100644
index aa10b92..0000000
--- a/src/modules/io/io_grid_grib2/g2clib-1.0.4/g2_unpack3.c
+++ /dev/null
@@ -1,216 +0,0 @@
-/**********************************************************
- * Version $Id: g2_unpack3.c 911 2011-02-14 16:38:15Z reklov_w $
- *********************************************************/
-#include <stdio.h>
-#include <stdlib.h>
-#include "grib2.h"
-
-
-g2int g2_unpack3(unsigned char *cgrib,g2int *iofst,g2int **igds,g2int **igdstmpl,
-                         g2int *mapgridlen,g2int **ideflist,g2int *idefnum)
-////$$$  SUBPROGRAM DOCUMENTATION BLOCK
-//                .      .    .                                       .
-// SUBPROGRAM:    g2_unpack3 
-//   PRGMMR: Gilbert         ORG: W/NP11    DATE: 2002-10-31
-//
-// ABSTRACT: This routine unpacks Section 3 (Grid Definition Section)
-//           as defined in GRIB Edition 2.
-//
-// PROGRAM HISTORY LOG:
-// 2002-10-31  Gilbert
-//
-// USAGE:    int g2_unpack3(unsigned char *cgrib,g2int *iofst,g2int **igds,
-//                          g2int **igdstmpl,g2int *mapgridlen,
-//                          g2int **ideflist,g2int *idefnum)
-//   INPUT ARGUMENTS:
-//     cgrib    - Char array ontaining Section 3 of the GRIB2 message
-//     iofst    - Bit offset for the beginning of Section 3 in cgrib.
-//
-//   OUTPUT ARGUMENTS:      
-//     iofst    - Bit offset at the end of Section 3, returned.
-//     igds     - Contains information read from the appropriate GRIB Grid 
-//                Definition Section 3 for the field being returned.
-//                igds[0]=Source of grid definition (see Code Table 3.0)
-//                igds[1]=Number of grid points in the defined grid.
-//                igds[2]=Number of octets needed for each 
-//                            additional grid points definition.  
-//                            Used to define number of
-//                            points in each row ( or column ) for
-//                            non-regular grids.  
-//                            = 0, if using regular grid.
-//                igds[3]=Interpretation of list for optional points 
-//                            definition.  (Code Table 3.11)
-//                igds[4]=Grid Definition Template Number (Code Table 3.1)
-//     igdstmpl - Pointer to integer array containing the data values for 
-//                the specified Grid Definition
-//                Template ( NN=igds[4] ).  Each element of this integer 
-//                array contains an entry (in the order specified) of Grid
-//                Defintion Template 3.NN
-//     mapgridlen- Number of elements in igdstmpl[].  i.e. number of entries
-//                in Grid Defintion Template 3.NN  ( NN=igds[4] ).
-//     ideflist - (Used if igds[2] .ne. 0)  Pointer to integer array containing
-//                the number of grid points contained in each row ( or column ).
-//                (part of Section 3)
-//     idefnum  - (Used if igds[2] .ne. 0)  The number of entries
-//                in array ideflist.  i.e. number of rows ( or columns )
-//                for which optional grid points are defined.
-//     ierr     - Error return code.
-//                0 = no error
-//                2 = Not Section 3
-//                5 = "GRIB" message contains an undefined Grid Definition
-//                    Template.
-//                6 = memory allocation error
-//
-// REMARKS: 
-//
-// ATTRIBUTES:
-//   LANGUAGE: C
-//   MACHINE:
-//
-//$$$
-
-{
-      g2int ierr,i,j,nbits,isecnum;
-      g2int lensec,ibyttem=0,isign,newlen;
-      g2int *ligds,*ligdstmpl=0,*lideflist=0;
-      template *mapgrid;
-
-      ierr=0;
-      *igds=0;       // NULL
-      *igdstmpl=0;       // NULL
-      *ideflist=0;       // NULL
-
-      gbit(cgrib,&lensec,*iofst,32);        // Get Length of Section
-      *iofst=*iofst+32;
-      gbit(cgrib,&isecnum,*iofst,8);         // Get Section Number
-      *iofst=*iofst+8;
-
-      if ( isecnum != 3 ) {
-         ierr=2;
-         *idefnum=0;
-         *mapgridlen=0;
-        // fprintf(stderr,"g2_unpack3: Not Section 3 data.\n");
-         return(ierr);
-      }
-
-      ligds=(g2int *)calloc(5,sizeof(g2int));
-      *igds=ligds;
-
-      gbit(cgrib,ligds+0,*iofst,8);     // Get source of Grid def.
-      *iofst=*iofst+8;
-      gbit(cgrib,ligds+1,*iofst,32);    // Get number of grid pts.
-      *iofst=*iofst+32;
-      gbit(cgrib,ligds+2,*iofst,8);     // Get num octets for opt. list
-      *iofst=*iofst+8;
-      gbit(cgrib,ligds+3,*iofst,8);     // Get interpret. for opt. list
-      *iofst=*iofst+8;
-      gbit(cgrib,ligds+4,*iofst,16);    // Get Grid Def Template num.
-      *iofst=*iofst+16;
-
-      if (ligds[4] != 65535) {
-        //   Get Grid Definition Template
-        mapgrid=getgridtemplate(ligds[4]);
-        if (mapgrid == 0) {         // undefined template
-          ierr=5;
-          return(ierr);
-        }
-        *mapgridlen=mapgrid->maplen;
-        //
-        //   Unpack each value into array igdstmpl from the
-        //   the appropriate number of octets, which are specified in
-        //   corresponding entries in array mapgrid.
-        //
-        if (*mapgridlen > 0) {
-           ligdstmpl=0;
-           ligdstmpl=(g2int *)calloc(*mapgridlen,sizeof(g2int));
-           if (ligdstmpl == 0) {
-              ierr=6;
-              *mapgridlen=0;
-              *igdstmpl=0;    //NULL
-              if( mapgrid != 0 ) free(mapgrid);
-              return(ierr);
-           }
-           else {
-              *igdstmpl=ligdstmpl;
-           }
-        }
-        ibyttem=0;
-        for (i=0;i<*mapgridlen;i++) {
-          nbits=abs(mapgrid->map[i])*8;
-          if ( mapgrid->map[i] >= 0 ) {
-            gbit(cgrib,ligdstmpl+i,*iofst,nbits);
-          }
-          else {
-            gbit(cgrib,&isign,*iofst,1);
-            gbit(cgrib,ligdstmpl+i,*iofst+1,nbits-1);
-            if (isign == 1) ligdstmpl[i]=-1*ligdstmpl[i];
-          }
-          *iofst=*iofst+nbits;
-          ibyttem=ibyttem+abs(mapgrid->map[i]);
-        }
-        //
-        //   Check to see if the Grid Definition Template needs to be
-        //   extended.
-        //   The number of values in a specific template may vary
-        //   depending on data specified in the "static" part of the
-        //   template.
-        //
-        if ( mapgrid->needext == 1 ) {
-          free(mapgrid);
-          mapgrid=extgridtemplate(ligds[4],ligdstmpl);
-          //   Unpack the rest of the Grid Definition Template
-          newlen=mapgrid->maplen+mapgrid->extlen;
-          ligdstmpl=(g2int *)realloc(ligdstmpl,newlen*sizeof(g2int));
-          *igdstmpl=ligdstmpl;
-          j=0;
-          for (i=*mapgridlen;i<newlen;i++) {
-            nbits=abs(mapgrid->ext[j])*8;
-            if ( mapgrid->ext[j] >= 0 ) {
-              gbit(cgrib,ligdstmpl+i,*iofst,nbits);
-            }
-            else {
-              gbit(cgrib,&isign,*iofst,1);
-              gbit(cgrib,ligdstmpl+i,*iofst+1,nbits-1);
-              if (isign == 1) ligdstmpl[i]=-1*ligdstmpl[i];
-            }
-            *iofst=*iofst+nbits;
-            ibyttem=ibyttem+abs(mapgrid->ext[j]);
-            j++;
-          }
-          *mapgridlen=newlen;
-        }
-        if( mapgrid->ext != 0 ) free(mapgrid->ext);
-        if( mapgrid != 0 ) free(mapgrid);
-      }
-      else {              // No Grid Definition Template
-        *mapgridlen=0;
-        *igdstmpl=0;
-      }
-      //
-      //   Unpack optional list of numbers defining number of points
-      //   in each row or column, if included.  This is used for non regular
-      //   grids.
-      //
-      if ( ligds[2] != 0 ) {
-         nbits=ligds[2]*8;
-         *idefnum=(lensec-14-ibyttem)/ligds[2];
-         if (*idefnum > 0) lideflist=(g2int *)calloc(*idefnum,sizeof(g2int));
-         if (lideflist == 0) {
-            ierr=6;
-            *idefnum=0;
-            *ideflist=0;   //NULL
-            return(ierr);
-         }
-         else {
-            *ideflist=lideflist;
-         }
-         gbits(cgrib,lideflist,*iofst,nbits,0,*idefnum);
-         *iofst=*iofst+(nbits*(*idefnum));
-      }
-      else {
-         *idefnum=0;
-         *ideflist=0;    // NULL
-      }
-      
-      return(ierr);    // End of Section 3 processing
-}
diff --git a/src/modules/io/io_grid_grib2/g2clib-1.0.4/g2_unpack4.c b/src/modules/io/io_grid_grib2/g2clib-1.0.4/g2_unpack4.c
deleted file mode 100644
index cc5cabf..0000000
--- a/src/modules/io/io_grid_grib2/g2clib-1.0.4/g2_unpack4.c
+++ /dev/null
@@ -1,187 +0,0 @@
-/**********************************************************
- * Version $Id: g2_unpack4.c 911 2011-02-14 16:38:15Z reklov_w $
- *********************************************************/
-#include <stdio.h>
-#include <stdlib.h>
-#include "grib2.h"
-
-
-g2int g2_unpack4(unsigned char *cgrib,g2int *iofst,g2int *ipdsnum,g2int **ipdstmpl,
-               g2int *mappdslen,g2float **coordlist,g2int *numcoord)
-////$$$  SUBPROGRAM DOCUMENTATION BLOCK
-//                .      .    .                                       .
-// SUBPROGRAM:    g2_unpack4 
-//   PRGMMR: Gilbert         ORG: W/NP11    DATE: 2002-10-31
-//
-// ABSTRACT: This subroutine unpacks Section 4 (Product Definition Section)
-//           as defined in GRIB Edition 2.
-//
-// PROGRAM HISTORY LOG:
-// 2002-10-31  Gilbert
-//
-// USAGE:    int g2_unpack4(unsigned char *cgrib,g2int *iofst,g2int *ipdsnum,
-//                          g2int **ipdstmpl,g2int *mappdslen,
-//                          g2float **coordlist,g2int *numcoord)
-//   INPUT ARGUMENTS:
-//     cgrib    - Char array containing Section 4 of the GRIB2 message
-//     iofst    - Bit offset of the beginning of Section 4 in cgrib.
-//
-//   OUTPUT ARGUMENTS:      
-//     iofst    - Bit offset of the end of Section 4, returned.
-//     ipdsnum  - Product Definition Template Number ( see Code Table 4.0)
-//     ipdstmpl - Pointer to integer array containing the data values for 
-//                the specified Product Definition
-//                Template ( N=ipdsnum ).  Each element of this integer
-//                array contains an entry (in the order specified) of Product
-//                Defintion Template 4.N
-//     mappdslen- Number of elements in ipdstmpl[].  i.e. number of entries
-//                in Product Defintion Template 4.N  ( N=ipdsnum ).
-//     coordlist- Pointer to real array containing floating point values 
-//                intended to document
-//                the vertical discretisation associated to model data
-//                on hybrid coordinate vertical levels.  (part of Section 4)
-//     numcoord - number of values in array coordlist.
-//
-//   RETURN VALUES:
-//     ierr     - Error return code.
-//                0 = no error
-//                2 = Not section 4
-//                5 = "GRIB" message contains an undefined Product Definition
-//                    Template.
-//                6 = memory allocation error
-//
-// REMARKS: 
-//
-// ATTRIBUTES:
-//   LANGUAGE: C
-//   MACHINE:  
-//
-//$$$//
-{
-
-      g2int ierr,needext,i,j,nbits,isecnum;
-      g2int lensec,isign,newlen;
-      g2int *coordieee;
-      g2int *lipdstmpl=0;
-      g2float *lcoordlist;
-      template *mappds;
-
-      ierr=0;
-      *ipdstmpl=0;    // NULL
-      *coordlist=0;    // NULL
-
-      gbit(cgrib,&lensec,*iofst,32);        // Get Length of Section
-      *iofst=*iofst+32;
-      gbit(cgrib,&isecnum,*iofst,8);         // Get Section Number
-      *iofst=*iofst+8;
-
-      if ( isecnum != 4 ) {
-         ierr=2;
-         *numcoord=0;
-         *mappdslen=0;
-        // fprintf(stderr,"g2_unpack4: Not Section 4 data.\n");
-         return(ierr);
-      }
-
-      gbit(cgrib,numcoord,*iofst,16);    // Get num of coordinate values
-      *iofst=*iofst+16;
-      gbit(cgrib,ipdsnum,*iofst,16);    // Get Prod. Def Template num.
-      *iofst=*iofst+16;
-
-      //   Get Product Definition Template
-      mappds=getpdstemplate(*ipdsnum);
-      if (mappds == 0) {       // undefine template
-        ierr=5;
-        *mappdslen=0;
-        return(ierr);
-      }
-      *mappdslen=mappds->maplen;
-      needext=mappds->needext;
-      //
-      //   Unpack each value into array ipdstmpl from the
-      //   the appropriate number of octets, which are specified in
-      //   corresponding entries in array mappds.
-      //
-      if (*mappdslen > 0) lipdstmpl=(g2int *)calloc(*mappdslen,sizeof(g2int));
-      if (lipdstmpl == 0) {
-         ierr=6;
-         *mappdslen=0;
-         *ipdstmpl=0;     //NULL
-         if ( mappds != 0 ) free(mappds);
-         return(ierr);
-      }
-      else {
-         *ipdstmpl=lipdstmpl;
-      }
-      for (i=0;i<mappds->maplen;i++) {
-        nbits=abs(mappds->map[i])*8;
-        if ( mappds->map[i] >= 0 ) {
-          gbit(cgrib,lipdstmpl+i,*iofst,nbits);
-        }
-        else {
-          gbit(cgrib,&isign,*iofst,1);
-          gbit(cgrib,lipdstmpl+i,*iofst+1,nbits-1);
-          if (isign == 1) lipdstmpl[i]=-1*lipdstmpl[i];
-        }
-        *iofst=*iofst+nbits;
-      }
-      //
-      //   Check to see if the Product Definition Template needs to be
-      //   extended.
-      //   The number of values in a specific template may vary
-      //   depending on data specified in the "static" part of the
-      //   template.
-      //
-      if ( needext ==1 ) {
-        free(mappds);
-        mappds=extpdstemplate(*ipdsnum,lipdstmpl);
-        newlen=mappds->maplen+mappds->extlen;
-        lipdstmpl=(g2int *)realloc(lipdstmpl,newlen*sizeof(g2int));
-        *ipdstmpl=lipdstmpl;
-        //   Unpack the rest of the Product Definition Template
-        j=0;
-        for (i=*mappdslen;i<newlen;i++) {
-          nbits=abs(mappds->ext[j])*8;
-          if ( mappds->ext[j] >= 0 ) {
-            gbit(cgrib,lipdstmpl+i,*iofst,nbits);
-          }
-          else {
-            gbit(cgrib,&isign,*iofst,1);
-            gbit(cgrib,lipdstmpl+i,*iofst+1,nbits-1);
-            if (isign == 1) lipdstmpl[i]=-1*lipdstmpl[i];
-          }
-          *iofst=*iofst+nbits;
-          j++;
-        }
-        *mappdslen=newlen;
-      }
-      if( mappds->ext != 0 ) free(mappds->ext);
-      if( mappds != 0 ) free(mappds);
-      //
-      //   Get Optional list of vertical coordinate values
-      //   after the Product Definition Template, if necessary.
-      //
-      *coordlist=0;    // NULL
-      if ( *numcoord != 0 ) {
-         coordieee=(g2int *)calloc(*numcoord,sizeof(g2int));
-         lcoordlist=(g2float *)calloc(*numcoord,sizeof(g2float));
-         if (coordieee == 0 || lcoordlist == 0) {
-            ierr=6;
-            *numcoord=0;
-            *coordlist=0;    // NULL
-            if( coordieee != 0 ) free(coordieee);
-            if( lcoordlist != 0 ) free(lcoordlist);
-            return(ierr);
-         }
-         else {
-            *coordlist=lcoordlist;
-         }
-        gbits(cgrib,coordieee,*iofst,32,0,*numcoord);
-        rdieee(coordieee,*coordlist,*numcoord);
-        free(coordieee);
-        *iofst=*iofst+(32*(*numcoord));
-      }
-      
-      return(ierr);    // End of Section 4 processing
-
-}
diff --git a/src/modules/io/io_grid_grib2/g2clib-1.0.4/g2_unpack5.c b/src/modules/io/io_grid_grib2/g2clib-1.0.4/g2_unpack5.c
deleted file mode 100644
index 0f2f992..0000000
--- a/src/modules/io/io_grid_grib2/g2clib-1.0.4/g2_unpack5.c
+++ /dev/null
@@ -1,154 +0,0 @@
-/**********************************************************
- * Version $Id: g2_unpack5.c 911 2011-02-14 16:38:15Z reklov_w $
- *********************************************************/
-#include <stdio.h>
-#include <stdlib.h>
-#include "grib2.h"
-
-
-g2int g2_unpack5(unsigned char *cgrib,g2int *iofst,g2int *ndpts,g2int *idrsnum,
-               g2int **idrstmpl,g2int *mapdrslen)
-////$$$  SUBPROGRAM DOCUMENTATION BLOCK
-//                .      .    .                                       .
-// SUBPROGRAM:    g2_unpack5 
-//   PRGMMR: Gilbert         ORG: W/NP11    DATE: 2002-10-31
-//
-// ABSTRACT: This subroutine unpacks Section 5 (Data Representation Section)
-//           as defined in GRIB Edition 2.
-//
-// PROGRAM HISTORY LOG:
-// 2002-10-31  Gilbert
-//
-// USAGE:    int g2_unpack5(unsigned char *cgrib,g2int *iofst,g2int *ndpts,
-//                          g2int *idrsnum,g2int **idrstmpl,g2int *mapdrslen)
-//   INPUT ARGUMENTS:
-//     cgrib    - char array containing Section 5 of the GRIB2 message
-//     iofst    - Bit offset for the beginning of Section 5 in cgrib.
-//
-//   OUTPUT ARGUMENTS:      
-//     iofst    - Bit offset at the end of Section 5, returned.
-//     ndpts    - Number of data points unpacked and returned.
-//     idrsnum  - Data Representation Template Number ( see Code Table 5.0)
-//     idrstmpl - Pointer to an integer array containing the data values for 
-//                the specified Data Representation
-//                Template ( N=idrsnum ).  Each element of this integer
-//                array contains an entry (in the order specified) of Data
-//                Representation Template 5.N
-//     mapdrslen- Number of elements in idrstmpl[].  i.e. number of entries
-//                in Data Representation Template 5.N  ( N=idrsnum ).
-//
-//   RETURN VALUES:
-//     ierr     - Error return code.
-//                0 = no error
-//                2 = Not Section 5
-//                6 = memory allocation error
-//                7 = "GRIB" message contains an undefined Data
-//                    Representation Template.
-//
-// REMARKS: None
-//
-// ATTRIBUTES:
-//   LANGUAGE: C
-//   MACHINE:  
-//
-//$$$//
-{
-      g2int ierr,needext,i,j,nbits,isecnum;
-      g2int lensec,isign,newlen;
-      g2int *lidrstmpl=0;
-      template *mapdrs;
-
-      ierr=0;
-      *idrstmpl=0;       //NULL
-
-      gbit(cgrib,&lensec,*iofst,32);        // Get Length of Section
-      *iofst=*iofst+32;
-      gbit(cgrib,&isecnum,*iofst,8);         // Get Section Number
-      *iofst=*iofst+8;
-
-      if ( isecnum != 5 ) {
-         ierr=2;
-         *ndpts=0;
-         *mapdrslen=0;
-        // fprintf(stderr,"g2_unpack5: Not Section 5 data.\n");
-         return(ierr);
-      }
-
-      gbit(cgrib,ndpts,*iofst,32);    // Get num of data points
-      *iofst=*iofst+32;
-      gbit(cgrib,idrsnum,*iofst,16);     // Get Data Rep Template Num.
-      *iofst=*iofst+16;
-
-      //   Gen Data Representation Template
-      mapdrs=getdrstemplate(*idrsnum);
-      if (mapdrs == 0) {
-        ierr=7;
-        *mapdrslen=0;
-        return(ierr);
-      }
-      *mapdrslen=mapdrs->maplen;
-      needext=mapdrs->needext;
-      //
-      //   Unpack each value into array ipdstmpl from the
-      //   the appropriate number of octets, which are specified in
-      //   corresponding entries in array mapdrs.
-      //
-      if (*mapdrslen > 0) lidrstmpl=(g2int *)calloc(*mapdrslen,sizeof(g2int));
-      if (lidrstmpl == 0) {
-         ierr=6;
-         *mapdrslen=0;
-         *idrstmpl=0;     //NULL
-         if ( mapdrs != 0 ) free(mapdrs);
-         return(ierr);
-      }
-      else {
-         *idrstmpl=lidrstmpl;
-      }
-      for (i=0;i<mapdrs->maplen;i++) {
-        nbits=abs(mapdrs->map[i])*8;
-        if ( mapdrs->map[i] >= 0 ) {
-          gbit(cgrib,lidrstmpl+i,*iofst,nbits);
-        }
-        else {
-          gbit(cgrib,&isign,*iofst,1);
-          gbit(cgrib,lidrstmpl+i,*iofst+1,nbits-1);
-          if (isign == 1) lidrstmpl[i]=-1*lidrstmpl[i];
-        }
-        *iofst=*iofst+nbits;
-      }
-      //
-      //   Check to see if the Data Representation Template needs to be
-      //   extended.
-      //   The number of values in a specific template may vary
-      //   depending on data specified in the "static" part of the
-      //   template.
-      //
-      if ( needext == 1 ) {
-        free(mapdrs);
-        mapdrs=extdrstemplate(*idrsnum,lidrstmpl);
-        newlen=mapdrs->maplen+mapdrs->extlen;
-        lidrstmpl=(g2int *)realloc(lidrstmpl,newlen*sizeof(g2int));
-        *idrstmpl=lidrstmpl;
-        //   Unpack the rest of the Data Representation Template
-        j=0;
-        for (i=*mapdrslen;i<newlen;i++) {
-          nbits=abs(mapdrs->ext[j])*8;
-          if ( mapdrs->ext[j] >= 0 ) {
-            gbit(cgrib,lidrstmpl+i,*iofst,nbits);
-          }
-          else {
-            gbit(cgrib,&isign,*iofst,1);
-            gbit(cgrib,lidrstmpl+i,*iofst+1,nbits-1);
-            if (isign == 1) lidrstmpl[i]=-1*lidrstmpl[i];
-          }
-          *iofst=*iofst+nbits;
-          j++;
-        }
-        *mapdrslen=newlen;
-      }
-      if( mapdrs->ext != 0 ) free(mapdrs->ext);
-      if( mapdrs != 0 ) free(mapdrs);
-
-      return(ierr);    // End of Section 5 processing
-
-}
diff --git a/src/modules/io/io_grid_grib2/g2clib-1.0.4/g2_unpack6.c b/src/modules/io/io_grid_grib2/g2clib-1.0.4/g2_unpack6.c
deleted file mode 100644
index d7686e0..0000000
--- a/src/modules/io/io_grid_grib2/g2clib-1.0.4/g2_unpack6.c
+++ /dev/null
@@ -1,100 +0,0 @@
-/**********************************************************
- * Version $Id: g2_unpack6.c 911 2011-02-14 16:38:15Z reklov_w $
- *********************************************************/
-#include <stdio.h>
-#include <stdlib.h>
-#include "grib2.h"
-
-g2int g2_unpack6(unsigned char *cgrib,g2int *iofst,g2int ngpts,g2int *ibmap,
-               g2int **bmap)
-//$$$  SUBPROGRAM DOCUMENTATION BLOCK
-//                .      .    .                                       .
-// SUBPROGRAM:    g2_unpack6 
-//   PRGMMR: Gilbert         ORG: W/NP11    DATE: 2002-10-31
-//
-// ABSTRACT: This subroutine unpacks Section 6 (Bit-Map Section)
-//           as defined in GRIB Edition 2.
-//
-// PROGRAM HISTORY LOG:
-// 2002-10-31  Gilbert
-//
-// USAGE:    int g2_unpack6(unsigned char *cgrib,g2int *iofst,g2int ngpts,
-//                          g2int *ibmap,g2int **bmap)
-//   INPUT ARGUMENTS:
-//     cgrib    - char array containing Section 6 of the GRIB2 message
-//     iofst    - Bit offset of the beginning of Section 6 in cgrib.
-//     ngpts    - Number of grid points specified in the bit-map
-//
-//   OUTPUT ARGUMENTS:      
-//     iofst    - Bit offset at the end of Section 6, returned.
-//     ibmap    - Bitmap indicator ( see Code Table 6.0 )
-//                0 = bitmap applies and is included in Section 6.
-//                1-253 = Predefined bitmap applies
-//                254 = Previously defined bitmap applies to this field
-//                255 = Bit map does not apply to this product.
-//     bmap     - Pointer to an integer array containing decoded bitmap. 
-//                ( if ibmap=0 )
-//
-//   RETURN VALUES:
-//     ierr     - Error return code.
-//                0 = no error
-//                2 = Not Section 6
-//                4 = Unrecognized pre-defined bit-map.
-//                6 = memory allocation error
-//
-// REMARKS: None
-//
-// ATTRIBUTES:
-//   LANGUAGE: C
-//   MACHINE:
-//
-//$$$//
-{
-      g2int j,ierr,isecnum;
-      g2int *lbmap=0;
-      g2int *intbmap;
-
-      ierr=0;
-      *bmap=0;    //NULL
-
-      *iofst=*iofst+32;    // skip Length of Section
-      gbit(cgrib,&isecnum,*iofst,8);         // Get Section Number
-      *iofst=*iofst+8; 
-
-      if ( isecnum != 6 ) {
-         ierr=2;
-         fprintf(stderr,"g2_unpack6: Not Section 6 data.\n");
-         return(ierr);
-      }
-
-      gbit(cgrib,ibmap,*iofst,8);    // Get bit-map indicator
-      *iofst=*iofst+8;
-
-      if (*ibmap == 0) {               // Unpack bitmap
-         if (ngpts > 0) lbmap=(g2int *)calloc(ngpts,sizeof(g2int));
-         if (lbmap == 0) {
-            ierr=6;
-            return(ierr);
-         }
-         else {
-            *bmap=lbmap;
-         }
-         intbmap=(g2int *)calloc(ngpts,sizeof(g2int));  
-         gbits(cgrib,intbmap,*iofst,1,0,ngpts);
-         *iofst=*iofst+ngpts;
-         for (j=0;j<ngpts;j++) {
-           lbmap[j]=(g2int)intbmap[j];
-         }
-         free(intbmap);
-//      else if (*ibmap.eq.254)               ! Use previous bitmap
-//        return(ierr);
-//      else if (*ibmap.eq.255)               ! No bitmap in message
-//        bmap(1:ngpts)=.true.
-//      else {
-//        print *,'gf_unpack6: Predefined bitmap ',*ibmap,' not recognized.'
-//        ierr=4;
-      }
-      
-      return(ierr);    // End of Section 6 processing
-
-}
diff --git a/src/modules/io/io_grid_grib2/g2clib-1.0.4/g2_unpack7.c b/src/modules/io/io_grid_grib2/g2clib-1.0.4/g2_unpack7.c
deleted file mode 100644
index a76ab99..0000000
--- a/src/modules/io/io_grid_grib2/g2clib-1.0.4/g2_unpack7.c
+++ /dev/null
@@ -1,154 +0,0 @@
-/**********************************************************
- * Version $Id: g2_unpack7.c 911 2011-02-14 16:38:15Z reklov_w $
- *********************************************************/
-#include <stdio.h>
-#include <stdlib.h>
-#include <memory.h>
-#include <string.h>
-#include "grib2.h"
-
-g2int simunpack(unsigned char *,g2int *, g2int,g2float *);
-int comunpack(unsigned char *,g2int,g2int,g2int *,g2int,g2float *);
-g2int specunpack(unsigned char *,g2int *,g2int,g2int,g2int, g2int, g2float *);
-#ifdef USE_PNG
-  g2int pngunpack(unsigned char *,g2int,g2int *,g2int, g2float *);
-#endif  /* USE_PNG */
-#ifdef USE_JPEG2000
-  g2int jpcunpack(unsigned char *,g2int,g2int *,g2int, g2float *);
-#endif  /* USE_JPEG2000 */
-
-g2int g2_unpack7(unsigned char *cgrib,g2int *iofst,g2int igdsnum,g2int *igdstmpl,
-               g2int idrsnum,g2int *idrstmpl,g2int ndpts,g2float **fld)
-//$$$  SUBPROGRAM DOCUMENTATION BLOCK
-//                .      .    .                                       .
-// SUBPROGRAM:    g2_unpack7 
-//   PRGMMR: Gilbert         ORG: W/NP11    DATE: 2002-10-31
-//
-// ABSTRACT: This subroutine unpacks Section 7 (Data Section)
-//           as defined in GRIB Edition 2.
-//
-// PROGRAM HISTORY LOG:
-// 2002-10-31  Gilbert
-// 2002-12-20  Gilbert - Added GDT info to arguments
-//                       and added 5.51 processing.
-// 2003-08-29  Gilbert  - Added support for new templates using
-//                        PNG and JPEG2000 algorithms/templates.
-// 2004-11-29  Gilbert  - JPEG2000 now allowed to use WMO Template no. 5.40
-//                        PNG now allowed to use WMO Template no. 5.41
-// 2004-12-16  Taylor   - Added check on comunpack return code.
-//
-// USAGE:    int g2_unpack7(unsigned char *cgrib,g2int *iofst,g2int igdsnum,
-//                          g2int *igdstmpl, g2int idrsnum,
-//                          g2int *idrstmpl, g2int ndpts,g2float **fld)
-//   INPUT ARGUMENTS:
-//     cgrib    - char array containing Section 7 of the GRIB2 message
-//     iofst    - Bit offset of the beginning of Section 7 in cgrib.
-//     igdsnum  - Grid Definition Template Number ( see Code Table 3.0)
-//                ( Only used for DRS Template 5.51 )
-//     igdstmpl - Pointer to an integer array containing the data values for
-//                the specified Grid Definition
-//                Template ( N=igdsnum ).  Each element of this integer
-//                array contains an entry (in the order specified) of Grid
-//                Definition Template 3.N
-//                ( Only used for DRS Template 5.51 )
-//     idrsnum  - Data Representation Template Number ( see Code Table 5.0)
-//     idrstmpl - Pointer to an integer array containing the data values for
-//                the specified Data Representation
-//                Template ( N=idrsnum ).  Each element of this integer
-//                array contains an entry (in the order specified) of Data
-//                Representation Template 5.N
-//     ndpts    - Number of data points unpacked and returned.
-//
-//   OUTPUT ARGUMENTS:      
-//     iofst    - Bit offset at the end of Section 7, returned.
-//     fld      - Pointer to a float array containing the unpacked data field.
-//
-//   RETURN VALUES:
-//     ierr     - Error return code.
-//                0 = no error
-//                2 = Not section 7
-//                4 = Unrecognized Data Representation Template
-//                5 = need one of GDT 3.50 through 3.53 to decode DRT 5.51
-//                6 = memory allocation error
-//                7 = corrupt section 7.
-//
-// REMARKS: None
-//
-// ATTRIBUTES:
-//   LANGUAGE: C
-//   MACHINE:
-//
-//$$$//
-{
-      g2int ierr,isecnum;
-      g2int ipos,lensec;
-      g2float *lfld;
-
-      ierr=0;
-      *fld=0;     //NULL
-
-      gbit(cgrib,&lensec,*iofst,32);        // Get Length of Section
-      *iofst=*iofst+32;    
-      gbit(cgrib,&isecnum,*iofst,8);         // Get Section Number
-      *iofst=*iofst+8;
-
-      if ( isecnum != 7 ) {
-         ierr=2;
-         //fprintf(stderr,"g2_unpack7: Not Section 7 data.\n");
-         return(ierr);
-      }
-
-      ipos=(*iofst/8);
-      lfld=(g2float *)calloc(ndpts,sizeof(g2float));
-      if (lfld == 0) {
-         ierr=6;
-         return(ierr);
-      }
-      else {
-         *fld=lfld;
-      }
-
-      if (idrsnum == 0) 
-        simunpack(cgrib+ipos,idrstmpl,ndpts,lfld);
-      else if (idrsnum == 2 || idrsnum == 3) {
-        if (comunpack(cgrib+ipos,lensec,idrsnum,idrstmpl,ndpts,lfld) != 0) {
-          return 7;
-        }
-      }
-      else if (idrsnum == 50) {            // Spectral Simple
-        simunpack(cgrib+ipos,idrstmpl,ndpts-1,lfld+1);
-        rdieee(idrstmpl+4,lfld+0,1);
-      }
-      else if (idrsnum == 51)              //  Spectral complex
-        if ( igdsnum>=50 && igdsnum <=53 ) 
-          specunpack(cgrib+ipos,idrstmpl,ndpts,igdstmpl[0],igdstmpl[2],igdstmpl[2],lfld);
-        else {
-          fprintf(stderr,"g2_unpack7: Cannot use GDT 3.%d to unpack Data Section 5.51.\n",(int)igdsnum);
-          ierr=5;
-          if ( lfld != 0 ) free(lfld);
-          *fld=0;     //NULL
-          return(ierr);
-        }
-#ifdef USE_JPEG2000
-      else if (idrsnum == 40 || idrsnum == 40000) {
-        jpcunpack(cgrib+ipos,lensec-5,idrstmpl,ndpts,lfld);
-        }
-#endif  /* USE_JPEG2000 */
-#ifdef USE_PNG
-      else if (idrsnum == 41 || idrsnum == 40010) {
-        pngunpack(cgrib+ipos,lensec-5,idrstmpl,ndpts,lfld);
-        }
-#endif  /* USE_PNG */
-      else {
-        fprintf(stderr,"g2_unpack7: Data Representation Template 5.%d not yet implemented.\n",(int)idrsnum);
-        ierr=4;
-        if ( lfld != 0 ) free(lfld);
-        *fld=0;     //NULL
-        return(ierr);
-      }
-
-      *iofst=*iofst+(8*lensec);
-      
-      return(ierr);    // End of Section 7 processing
-
-}
diff --git a/src/modules/io/io_grid_grib2/g2clib-1.0.4/gbits.c b/src/modules/io/io_grid_grib2/g2clib-1.0.4/gbits.c
deleted file mode 100644
index a85cace..0000000
--- a/src/modules/io/io_grid_grib2/g2clib-1.0.4/gbits.c
+++ /dev/null
@@ -1,127 +0,0 @@
-/**********************************************************
- * Version $Id: gbits.c 911 2011-02-14 16:38:15Z reklov_w $
- *********************************************************/
-#include "grib2.h"
-
-void gbit(unsigned char *in,g2int *iout,g2int iskip,g2int nbyte)
-{
-      gbits(in,iout,iskip,nbyte,(g2int)0,(g2int)1);
-}
-
-void sbit(unsigned char *out,g2int *in,g2int iskip,g2int nbyte)
-{
-      sbits(out,in,iskip,nbyte,(g2int)0,(g2int)1);
-}
-
-
-void gbits(unsigned char *in,g2int *iout,g2int iskip,g2int nbyte,g2int nskip,
-           g2int n)
-/*          Get bits - unpack bits:  Extract arbitrary size values from a
-/          packed bit string, right justifying each value in the unpacked
-/          iout array.
-/           *in    = pointer to character array input
-/           *iout  = pointer to unpacked array output
-/            iskip = initial number of bits to skip
-/            nbyte = number of bits to take
-/            nskip = additional number of bits to skip on each iteration
-/            n     = number of iterations
-/ v1.1
-*/
-{
-      g2int i,tbit,bitcnt,ibit,itmp;
-      g2int nbit,index;
-      static g2int ones[]={1,3,7,15,31,63,127,255};
-
-//     nbit is the start position of the field in bits
-      nbit = iskip;
-      for (i=0;i<n;i++) {
-         bitcnt = nbyte;
-         index=nbit/8;
-         ibit=nbit%8;
-         nbit = nbit + nbyte + nskip;
-
-//        first byte
-         tbit= ( bitcnt < (8-ibit) ) ? bitcnt : 8-ibit;  // find min
-         itmp = (int)*(in+index) & ones[7-ibit];
-         if (tbit != 8-ibit) itmp >>= (8-ibit-tbit);
-         index++;
-         bitcnt = bitcnt - tbit;
-
-//        now transfer whole bytes
-         while (bitcnt >= 8) {
-             itmp = itmp<<8 | (int)*(in+index);
-             bitcnt = bitcnt - 8;
-             index++;
-         }
-
-//        get data from last byte
-         if (bitcnt > 0) {
-             itmp = ( itmp << bitcnt ) | ( ((int)*(in+index) >> (8-bitcnt)) & ones[bitcnt-1] );
-         }
-
-         *(iout+i) = itmp;
-      }
-}
-
-
-void sbits(unsigned char *out,g2int *in,g2int iskip,g2int nbyte,g2int nskip,
-           g2int n)
-/*C          Store bits - pack bits:  Put arbitrary size values into a
-/          packed bit string, taking the low order bits from each value
-/          in the unpacked array.
-/           *iout  = pointer to packed array output
-/           *in    = pointer to unpacked array input
-/            iskip = initial number of bits to skip
-/            nbyte = number of bits to pack
-/            nskip = additional number of bits to skip on each iteration
-/            n     = number of iterations
-/ v1.1
-*/
-{
-      g2int i,bitcnt,tbit,ibit,itmp,imask,itmp2,itmp3;
-      g2int nbit,index;
-      static g2int ones[]={1,3,7,15,31,63,127,255};
-
-//     number bits from zero to ...
-//     nbit is the last bit of the field to be filled
-
-      nbit = iskip + nbyte - 1;
-      for (i=0;i<n;i++) {
-         itmp = *(in+i);
-         bitcnt = nbyte;
-         index=nbit/8;
-         ibit=nbit%8;
-         nbit = nbit + nbyte + nskip;
-
-//        make byte aligned 
-         if (ibit != 7) {
-             tbit= ( bitcnt < (ibit+1) ) ? bitcnt : ibit+1;  // find min
-             imask = ones[tbit-1] << (7-ibit);
-             itmp2 = (itmp << (7-ibit)) & imask;
-             itmp3 = (int)*(out+index) & (255-imask);
-             out[index] = (unsigned char)(itmp2 | itmp3);
-             bitcnt = bitcnt - tbit;
-             itmp = itmp >> tbit;
-             index--;
-         }
-
-//        now byte aligned
-
-//        do by bytes
-         while (bitcnt >= 8) {
-             out[index] = (unsigned char)(itmp & 255);
-             itmp = itmp >> 8;
-             bitcnt = bitcnt - 8;
-             index--;
-         }
-
-//        do last byte
-
-         if (bitcnt > 0) {
-             itmp2 = itmp & ones[bitcnt-1];
-             itmp3 = (int)*(out+index) & (255-ones[bitcnt-1]);
-             out[index] = (unsigned char)(itmp2 | itmp3);
-         }
-      }
-
-}
diff --git a/src/modules/io/io_grid_grib2/g2clib-1.0.4/getdim.c b/src/modules/io/io_grid_grib2/g2clib-1.0.4/getdim.c
deleted file mode 100644
index 7ea9246..0000000
--- a/src/modules/io/io_grid_grib2/g2clib-1.0.4/getdim.c
+++ /dev/null
@@ -1,130 +0,0 @@
-/**********************************************************
- * Version $Id: getdim.c 911 2011-02-14 16:38:15Z reklov_w $
- *********************************************************/
-#include <stdio.h>
-#include <stdlib.h>
-#include "grib2.h"
-
-g2int g2_unpack3(unsigned char *,g2int *,g2int **,g2int **,
-                         g2int *,g2int **,g2int *);
-
-g2int getdim(unsigned char *csec3,g2int *width,g2int *height,g2int *iscan)
-//$$$  SUBPROGRAM DOCUMENTATION BLOCK
-//                .      .    .                                       .
-// SUBPROGRAM:    getdim 
-//   PRGMMR: Gilbert         ORG: W/NP11    DATE: 2002-12-11
-//
-// ABSTRACT: This subroutine returns the dimensions and scanning mode of 
-//   a grid definition packed in GRIB2 Grid Definition Section 3 format.
-//
-// PROGRAM HISTORY LOG:
-// 2002-12-11  Gilbert
-//
-// USAGE:    int getdim(unsigned char *csec3,g2int *width,
-//                      g2int *height, g2int *iscan)
-//   INPUT ARGUMENT LIST:
-//     csec3    - Character array that contains the packed GRIB2 GDS
-//
-//   OUTPUT ARGUMENT LIST:      
-//     width    - x (or i) dimension of the grid.
-//     height   - y (or j) dimension of the grid.
-//     iscan    - Scanning mode ( see Code Table 3.4 )
-//
-// REMARKS:  Returns width and height set to zero, if grid template
-//           not recognized.
-//
-// ATTRIBUTES:
-//   LANGUAGE: C
-//   MACHINE:  IBM SP
-//
-//$$$
-{
-    
-      g2int  *igdstmpl,*list_opt;
-      g2int  *igds;
-      g2int  iofst,igdtlen,num_opt,jerr;
-
-      igdstmpl=0;
-      list_opt=0;
-      igds=0;
-      iofst=0;       // set offset to beginning of section
-      jerr= g2_unpack3(csec3,&iofst,&igds,&igdstmpl,
-                       &igdtlen,&list_opt,&num_opt);
-      if (jerr == 0) {
-         switch ( igds[4] )     //  Template number
-         {
-           case 0:    // Lat/Lon
-           case 1:
-           case 2:
-           case 3:
-           {
-              *width=igdstmpl[7];
-              *height=igdstmpl[8];
-              *iscan=igdstmpl[18];
-              break;
-           }
-           case 10:   // Mercator
-           {
-              *width=igdstmpl[7];
-              *height=igdstmpl[8];
-              *iscan=igdstmpl[15];
-              break;
-           }
-           case 20:   // Polar Stereographic
-           {
-              *width=igdstmpl[7];
-              *height=igdstmpl[8];
-              *iscan=igdstmpl[17];
-              break;
-           }
-           case 30:   // Lambert Conformal
-           {
-              *width=igdstmpl[7];
-              *height=igdstmpl[8];
-              *iscan=igdstmpl[17];
-              break;
-           }
-           case 40:   // Gaussian
-           case 41:
-           case 42:
-           case 43:
-           {
-              *width=igdstmpl[7];
-              *height=igdstmpl[8];
-              *iscan=igdstmpl[18];
-              break;
-           }
-           case 90:   // Space View/Orthographic
-           {
-              *width=igdstmpl[7];
-              *height=igdstmpl[8];
-              *iscan=igdstmpl[16];
-              break;
-           }
-           case 110:   // Equatorial Azimuthal
-           {
-              *width=igdstmpl[7];
-              *height=igdstmpl[8];
-              *iscan=igdstmpl[15];
-              break;
-           }
-           default:
-           {
-              *width=0;
-              *height=0;
-              *iscan=0;
-              break;
-           }
-         }  // end switch
-      }
-      else {
-         *width=0;
-         *height=0;
-      }
-
-      if (igds != 0) free(igds);
-      if (igdstmpl != 0) free(igdstmpl);
-      if (list_opt != 0) free(list_opt);
-
-      return 0;
-}
diff --git a/src/modules/io/io_grid_grib2/g2clib-1.0.4/getpoly.c b/src/modules/io/io_grid_grib2/g2clib-1.0.4/getpoly.c
deleted file mode 100644
index 53bca0c..0000000
--- a/src/modules/io/io_grid_grib2/g2clib-1.0.4/getpoly.c
+++ /dev/null
@@ -1,83 +0,0 @@
-/**********************************************************
- * Version $Id: getpoly.c 911 2011-02-14 16:38:15Z reklov_w $
- *********************************************************/
-#include <stdio.h>
-#include <stdlib.h>
-#include "grib2.h"
-
-g2int g2_unpack3(unsigned char *,g2int *,g2int **,g2int **,
-                         g2int *,g2int **,g2int *);
-
-g2int getpoly(unsigned char *csec3,g2int *jj,g2int *kk,g2int *mm)
-//$$$  SUBPROGRAM DOCUMENTATION BLOCK
-//                .      .    .                                       .
-// SUBPROGRAM:    getpoly 
-//   PRGMMR: Gilbert         ORG: W/NP11    DATE: 2002-12-11
-//
-// ABSTRACT: This subroutine returns the J, K, and M pentagonal resolution
-//   parameters specified in a GRIB Grid Definition Section used
-//   spherical harmonic coefficients using GDT 5.50 through 5.53
-//
-// PROGRAM HISTORY LOG:
-// 2002-12-11  Gilbert
-//
-// USAGE:    int getpoly(unsigned char *csec3,g2int *jj,g2int *kk,g2int *mm)
-//   INPUT ARGUMENTS:
-//     csec3    - Character array that contains the packed GRIB2 GDS
-//
-//   OUTPUT ARGUMENTS:      
-//         JJ   = J - pentagonal resolution parameter
-//         KK   = K - pentagonal resolution parameter
-//         MM   = M - pentagonal resolution parameter
-//
-// REMARKS:  Returns JJ, KK, and MM set to zero, if grid template
-//           not recognized.
-//
-// ATTRIBUTES:
-//   LANGUAGE: C
-//   MACHINE:  IBM SP
-//
-//$$$
-{
-    
-      g2int   *igdstmpl,*list_opt;
-      g2int   *igds;
-      g2int   iofst,igdtlen,num_opt,jerr;
-
-      iofst=0;       // set offset to beginning of section
-      jerr=g2_unpack3(csec3,&iofst,&igds,&igdstmpl,
-                      &igdtlen,&list_opt,&num_opt);
-      if (jerr == 0) {
-         switch ( igds[4] )     //  Template number
-         {
-           case 50:     // Spherical harmonic coefficients
-           case 51:
-           case 52:
-           case 53:
-           {
-              *jj=igdstmpl[0];
-              *kk=igdstmpl[1];
-              *mm=igdstmpl[2];
-              break;
-           }
-           default:
-           {
-              *jj=0;
-              *kk=0;
-              *mm=0;
-              break;
-           }
-         }     // end switch
-      }
-      else {
-         *jj=0;
-         *kk=0;
-         *mm=0;
-      }
-        
-      if (igds != 0) free(igds);
-      if (igdstmpl != 0) free(igdstmpl);
-      if (list_opt != 0) free(list_opt);
-
-      return 0;
-}
diff --git a/src/modules/io/io_grid_grib2/g2clib-1.0.4/grib2.h b/src/modules/io/io_grid_grib2/g2clib-1.0.4/grib2.h
deleted file mode 100644
index 592db4a..0000000
--- a/src/modules/io/io_grid_grib2/g2clib-1.0.4/grib2.h
+++ /dev/null
@@ -1,254 +0,0 @@
-/**********************************************************
- * Version $Id: grib2.h 911 2011-02-14 16:38:15Z reklov_w $
- *********************************************************/
-#ifndef _grib2_H
-#define _grib2_H
-#include<stdio.h>
-
-#ifdef _SAGA_MSW
-extern double rint(double x);
-#endif
-
-#define G2_VERSION "g2clib-1.0.4"
-/*                .      .    .                                       .
-//   PRGMMR: Gilbert         ORG: W/NP11    DATE: 2002-10-25
-//
-//   Each element of structure gribfield is defined as:
-//   
-//   gribfield gfld;
-//
-//        gfld->version = GRIB edition number ( currently 2 )
-//        gfld->discipline = Message Discipline ( see Code Table 0.0 )
-//        gfld->idsect = Contains the entries in the Identification
-//                        Section ( Section 1 )
-//                        This element is a pointer to an array
-//                        that holds the data.
-//            gfld->idsect[0]  = Identification of originating Centre
-//                                    ( see Common Code Table C-1 )
-//                             7 - US National Weather Service
-//            gfld->idsect[1]  = Identification of originating Sub-centre
-//            gfld->idsect[2]  = GRIB Master Tables Version Number
-//                                    ( see Code Table 1.0 )
-//                             0 - Experimental
-//                             1 - Initial operational version number
-//            gfld->idsect[3]  = GRIB Local Tables Version Number
-//                                    ( see Code Table 1.1 )
-//                             0     - Local tables not used
-//                             1-254 - Number of local tables version used
-//            gfld->idsect[4]  = Significance of Reference Time (Code Table 1.2)
-//                             0 - Analysis
-//                             1 - Start of forecast
-//                             2 - Verifying time of forecast
-//                             3 - Observation time
-//            gfld->idsect[5]  = Year ( 4 digits )
-//            gfld->idsect[6]  = Month
-//            gfld->idsect[7)  = Day
-//            gfld->idsect[8]  = Hour
-//            gfld->idsect[9]  = Minute
-//            gfld->idsect[10]  = Second
-//            gfld->idsect[11]  = Production status of processed data
-//                                    ( see Code Table 1.3 )
-//                              0 - Operational products
-//                              1 - Operational test products
-//                              2 - Research products
-//                              3 - Re-analysis products
-//            gfld->idsect[12]  = Type of processed data ( see Code Table 1.4 )
-//                              0  - Analysis products
-//                              1  - Forecast products
-//                              2  - Analysis and forecast products
-//                              3  - Control forecast products
-//                              4  - Perturbed forecast products
-//                              5  - Control and perturbed forecast products
-//                              6  - Processed satellite observations
-//                              7  - Processed radar observations
-//        gfld->idsectlen = Number of elements in gfld->idsect[].
-//        gfld->local   = Pointer to character array containing contents
-//                       of Local Section 2, if included
-//        gfld->locallen = length of array gfld->local[]
-//        gfld->ifldnum = field number within GRIB message
-//        gfld->griddef = Source of grid definition (see Code Table 3.0)
-//                      0 - Specified in Code table 3.1
-//                      1 - Predetermined grid Defined by originating centre
-//        gfld->ngrdpts = Number of grid points in the defined grid.
-//        gfld->numoct_opt = Number of octets needed for each
-//                          additional grid points definition.
-//                          Used to define number of
-//                          points in each row ( or column ) for
-//                          non-regular grids.
-//                          = 0, if using regular grid.
-//        gfld->interp_opt = Interpretation of list for optional points
-//                          definition.  (Code Table 3.11)
-//        gfld->igdtnum = Grid Definition Template Number (Code Table 3.1)
-//        gfld->igdtmpl  = Contains the data values for the specified Grid
-//                         Definition Template ( NN=gfld->igdtnum ).  Each
-//                         element of this integer array contains an entry (in
-//                         the order specified) of Grid Defintion Template 3.NN
-//                         This element is a pointer to an array
-//                         that holds the data.
-//        gfld->igdtlen = Number of elements in gfld->igdtmpl[].  i.e. number of
-//                       entries in Grid Defintion Template 3.NN
-//                       ( NN=gfld->igdtnum ).
-//        gfld->list_opt  = (Used if gfld->numoct_opt .ne. 0)  This array
-//                          contains the number of grid points contained in
-//                          each row ( or column ).  (part of Section 3)
-//                          This element is a pointer to an array
-//                          that holds the data.  This pointer is nullified
-//                          if gfld->numoct_opt=0.
-//        gfld->num_opt = (Used if gfld->numoct_opt .ne. 0)  The number of entries
-//                       in array ideflist.  i.e. number of rows ( or columns )
-//                       for which optional grid points are defined.  This value
-//                       is set to zero, if gfld->numoct_opt=0.
-//        gfdl->ipdtnum = Product Definition Template Number (see Code Table 4.0)
-//        gfld->ipdtmpl  = Contains the data values for the specified Product
-//                         Definition Template ( N=gfdl->ipdtnum ).  Each element
-//                         of this integer array contains an entry (in the
-//                         order specified) of Product Defintion Template 4.N.
-//                         This element is a pointer to an array
-//                         that holds the data.
-//        gfld->ipdtlen = Number of elements in gfld->ipdtmpl[].  i.e. number of
-//                       entries in Product Defintion Template 4.N
-//                       ( N=gfdl->ipdtnum ).
-//        gfld->coord_list  = Real array containing floating point values
-//                            intended to document the vertical discretisation
-//                            associated to model data on hybrid coordinate
-//                            vertical levels.  (part of Section 4)
-//                            This element is a pointer to an array
-//                            that holds the data.
-//        gfld->num_coord = number of values in array gfld->coord_list[].
-//        gfld->ndpts = Number of data points unpacked and returned.
-//        gfld->idrtnum = Data Representation Template Number
-//                       ( see Code Table 5.0)
-//        gfld->idrtmpl  = Contains the data values for the specified Data
-//                         Representation Template ( N=gfld->idrtnum ).  Each
-//                         element of this integer array contains an entry
-//                         (in the order specified) of Product Defintion
-//                         Template 5.N.
-//                         This element is a pointer to an array
-//                         that holds the data.
-//        gfld->idrtlen = Number of elements in gfld->idrtmpl[].  i.e. number
-//                       of entries in Data Representation Template 5.N
-//                       ( N=gfld->idrtnum ).
-//        gfld->unpacked = logical value indicating whether the bitmap and
-//                        data values were unpacked.  If false,
-//                        gfld->bmap and gfld->fld pointers are nullified.
-//        gfld->expanded = Logical value indicating whether the data field 
-//                         was expanded to the grid in the case where a 
-//                         bit-map is present.  If true, the data points in
-//                         gfld->fld match the grid points and zeros were 
-//                         inserted at grid points where data was bit-mapped
-//                         out.  If false, the data values in gfld->fld were
-//                         not expanded to the grid and are just a consecutive
-//                         array of data points corresponding to each value of
-//                         "1" in gfld->bmap.
-//        gfld->ibmap = Bitmap indicator ( see Code Table 6.0 )
-//                     0 = bitmap applies and is included in Section 6.
-//                     1-253 = Predefined bitmap applies
-//                     254 = Previously defined bitmap applies to this field
-//                     255 = Bit map does not apply to this product.
-//        gfld->bmap  = integer array containing decoded bitmap,
-//                      if gfld->ibmap=0 or gfld->ibap=254.  Otherwise nullified.
-//                      This element is a pointer to an array
-//                      that holds the data.
-//        gfld->fld  = Array of gfld->ndpts unpacked data points.
-//                     This element is a pointer to an array
-//                     that holds the data.
-*/
-
-#ifdef __64BIT__
-typedef int g2int;
-typedef unsigned int g2intu;
-#else
-typedef long g2int;
-typedef unsigned long g2intu;
-#endif
-typedef float g2float;
-
-struct _template {
-   g2int type;           /* 3=Grid Defintion Template.                       */
-                         /* 4=Product Defintion Template.                    */
-                         /* 5=Data Representation Template.                  */
-   g2int num;            /* template number.                                 */
-   g2int maplen;         /* number of entries in the static part             */
-                         /*                    of the template.              */
-   g2int *map;           /* num of octets of each entry in the               */
-                         /*         static part of the template.             */
-   g2int needext;        /* indicates whether or not the template needs      */
-                         /*     to be extended.                              */
-   g2int extlen;         /* number of entries in the template extension.     */
-   g2int *ext;           /* num of octets of each entry in the extension     */
-                         /*                      part of the template.       */
-};
-
-typedef struct _template _template;
-
-#define template _template
-
-struct gribfield {
-   g2int   version,discipline;
-   g2int   *idsect;
-   g2int   idsectlen;
-   unsigned char *local;
-   g2int   locallen;
-   g2int   ifldnum;
-   g2int   griddef,ngrdpts;
-   g2int   numoct_opt,interp_opt,num_opt;
-   g2int   *list_opt;
-   g2int   igdtnum,igdtlen;
-   g2int   *igdtmpl;
-   g2int   ipdtnum,ipdtlen;
-   g2int   *ipdtmpl;
-   g2int   num_coord;
-   g2float *coord_list;
-   g2int   ndpts,idrtnum,idrtlen;
-   g2int   *idrtmpl;
-   g2int   unpacked;
-   g2int   expanded;
-   g2int   ibmap;
-   g2int   *bmap;
-   g2float *fld;
-};
-
-typedef struct gribfield gribfield;
-
-
-/*  Prototypes for unpacking API  */
-void seekgb(FILE *,g2int ,g2int ,g2int *,g2int *);
-g2int g2_info(unsigned char *,g2int *,g2int *,g2int *,g2int *);
-g2int g2_getfld(unsigned char *,g2int ,g2int ,g2int ,gribfield **);
-void g2_free(gribfield *);
-
-/*  Prototypes for packing API  */
-g2int g2_create(unsigned char *,g2int *,g2int *);
-g2int g2_addlocal(unsigned char *,unsigned char *,g2int );
-g2int g2_addgrid(unsigned char *,g2int *,g2int *,g2int *,g2int ); 
-g2int g2_addfield(unsigned char *,g2int ,g2int *,
-                       g2float *,g2int ,g2int ,g2int *,
-                       g2float *,g2int ,g2int ,g2int *);
-g2int g2_gribend(unsigned char *);
-
-/*  Prototypes for supporting routines  */
-extern double int_power(double, g2int );
-extern void mkieee(g2float *,g2int *,g2int);
-void rdieee(g2int *,g2float *,g2int );
-extern _template *getpdstemplate(g2int);
-extern _template *extpdstemplate(g2int,g2int *);
-extern _template *getdrstemplate(g2int);
-extern _template *extdrstemplate(g2int,g2int *);
-extern _template *getgridtemplate(g2int);
-extern _template *extgridtemplate(g2int,g2int *);
-extern void simpack(g2float *,g2int,g2int *,unsigned char *,g2int *);
-extern void compack(g2float *,g2int,g2int,g2int *,unsigned char *,g2int *);
-void misspack(g2float *,g2int ,g2int ,g2int *, unsigned char *, g2int *);
-void gbit(unsigned char *,g2int *,g2int ,g2int );
-void sbit(unsigned char *,g2int *,g2int ,g2int );
-void gbits(unsigned char *,g2int *,g2int ,g2int ,g2int ,g2int );
-void sbits(unsigned char *,g2int *,g2int ,g2int ,g2int ,g2int );
-
-int pack_gp(g2int *, g2int *, g2int *,
-            g2int *, g2int *, g2int *, g2int *, g2int *,
-            g2int *, g2int *, g2int *, g2int *,
-            g2int *, g2int *, g2int *, g2int *, g2int *,
-            g2int *, g2int *, g2int *);
-
-#endif  /*  _grib2_H  */
-
diff --git a/src/modules/io/io_grid_grib2/g2clib-1.0.4/gridtemplates.c b/src/modules/io/io_grid_grib2/g2clib-1.0.4/gridtemplates.c
deleted file mode 100644
index bbec4ae..0000000
--- a/src/modules/io/io_grid_grib2/g2clib-1.0.4/gridtemplates.c
+++ /dev/null
@@ -1,176 +0,0 @@
-/**********************************************************
- * Version $Id: gridtemplates.c 911 2011-02-14 16:38:15Z reklov_w $
- *********************************************************/
-#include <stdlib.h>
-#include "grib2.h"
-#include "gridtemplates.h"
-
-g2int getgridindex(g2int number)
-/*!$$$  SUBPROGRAM DOCUMENTATION BLOCK
-!                .      .    .                                       .
-! SUBPROGRAM:    getgridindex
-!   PRGMMR: Gilbert         ORG: W/NP11    DATE: 2001-06-28
-!
-! ABSTRACT: This function returns the index of specified Grid
-!   Definition Template 3.NN (NN=number) in array templates.
-!
-! PROGRAM HISTORY LOG:
-! 2001-06-28  Gilbert
-!
-! USAGE:    index=getgridindex(number)
-!   INPUT ARGUMENT LIST:
-!     number   - NN, indicating the number of the Grid Definition
-!                Template 3.NN that is being requested.
-!
-! RETURNS:  Index of GDT 3.NN in array templates, if template exists.
-!           = -1, otherwise.
-!
-! REMARKS: None
-!
-! ATTRIBUTES:
-!   LANGUAGE: C
-!   MACHINE:  IBM SP
-!
-!$$$*/
-{
-           g2int j,getgridindex=-1;
-
-           for (j=0;j<MAXGRIDTEMP;j++) {
-              if (number == templatesgrid[j].template_num) {
-                 getgridindex=j;
-                 return(getgridindex);
-              }
-           }
-
-           return(getgridindex);
-}
-
-template *getgridtemplate(g2int number)
-/*!$$$  SUBPROGRAM DOCUMENTATION BLOCK
-!                .      .    .                                       .
-! SUBPROGRAM:    getgridtemplate 
-!   PRGMMR: Gilbert         ORG: W/NP11    DATE: 2000-05-09
-!
-! ABSTRACT: This subroutine returns grid template information for a 
-!   specified Grid Definition Template 3.NN.
-!   The number of entries in the template is returned along with a map
-!   of the number of octets occupied by each entry.  Also, a flag is
-!   returned to indicate whether the template would need to be extended.
-!
-! PROGRAM HISTORY LOG:
-! 2000-05-09  Gilbert
-!
-! USAGE:    template *getgridtemplate(number)
-!   INPUT ARGUMENT LIST:
-!     number   - NN, indicating the number of the Grid Definition 
-!                Template 3.NN that is being requested.
-!
-!   RETURN VALUE:
-!        - Pointer to the returned template struct.
-!          Returns NULL pointer, if template not found.
-!
-! REMARKS: None
-!
-! ATTRIBUTES:
-!   LANGUAGE: C
-!   MACHINE:  IBM SP
-!
-!$$$*/
-{
-           g2int index;
-           template *new;
-
-           index=getgridindex(number);
-
-           if (index != -1) {
-              new=(template *)malloc(sizeof(template));
-              new->type=3;
-              new->num=templatesgrid[index].template_num;
-              new->maplen=templatesgrid[index].mapgridlen;
-              new->needext=templatesgrid[index].needext;
-              new->map=(g2int *)templatesgrid[index].mapgrid;
-              new->extlen=0;
-              new->ext=0;        //NULL
-              return(new);
-           }
-           else {
-             printf("getgridtemplate: GDT Template 3.%d not defined.\n",(int)number);
-             return(0);        //NULL
-           }
-
-         return(0);        //NULL
-}
-
-
-template *extgridtemplate(g2int number,g2int *list)
-/*!$$$  SUBPROGRAM DOCUMENTATION BLOCK
-!                .      .    .                                       .
-! SUBPROGRAM:    extgridtemplate 
-!   PRGMMR: Gilbert         ORG: W/NP11    DATE: 2000-05-09
-!
-! ABSTRACT: This subroutine generates the remaining octet map for a 
-!   given Grid Definition Template, if required.  Some Templates can 
-!   vary depending on data values given in an earlier part of the 
-!   Template, and it is necessary to know some of the earlier entry
-!   values to generate the full octet map of the Template.
-!
-! PROGRAM HISTORY LOG:
-! 2000-05-09  Gilbert
-!
-! USAGE:    CALL extgridtemplate(number,list)
-!   INPUT ARGUMENT LIST:
-!     number   - NN, indicating the number of the Grid Definition 
-!                Template 3.NN that is being requested.
-!     list()   - The list of values for each entry in 
-!                the Grid Definition Template.
-!
-!   RETURN VALUE:
-!        - Pointer to the returned template struct.
-!          Returns NULL pointer, if template not found.
-!
-! ATTRIBUTES:
-!   LANGUAGE: C
-!   MACHINE:  IBM SP
-!
-!$$$*/
-{
-           template *new;
-           g2int index,i;
-
-           index=getgridindex(number);
-           if (index == -1) return(0);
-
-           new=getgridtemplate(number);
-
-           if ( ! new->needext ) return(new);
-
-           if ( number == 120 ) {
-              new->extlen=list[1]*2;
-              new->ext=(g2int *)malloc(sizeof(g2int)*new->extlen);
-              for (i=0;i<new->extlen;i++) {
-                 if ( i%2 == 0 ) {
-                    new->ext[i]=2;
-                 }
-                 else {
-                    new->ext[i]=-2;
-                 }
-              }
-           }
-           else if ( number == 1000 ) {
-              new->extlen=list[19];
-              new->ext=(g2int *)malloc(sizeof(g2int)*new->extlen);
-              for (i=0;i<new->extlen;i++) {
-                 new->ext[i]=4;
-              }
-           }
-           else if ( number == 1200 ) {
-              new->extlen=list[15];
-              new->ext=(g2int *)malloc(sizeof(g2int)*new->extlen);
-              for (i=0;i<new->extlen;i++) {
-                 new->ext[i]=4;
-              }
-           }
-
-           return(new);
-
-}
diff --git a/src/modules/io/io_grid_grib2/g2clib-1.0.4/gridtemplates.h b/src/modules/io/io_grid_grib2/g2clib-1.0.4/gridtemplates.h
deleted file mode 100644
index 7e79c1d..0000000
--- a/src/modules/io/io_grid_grib2/g2clib-1.0.4/gridtemplates.h
+++ /dev/null
@@ -1,99 +0,0 @@
-/**********************************************************
- * Version $Id: gridtemplates.h 911 2011-02-14 16:38:15Z reklov_w $
- *********************************************************/
-#ifndef _gridtemplates_H
-#define _gridtemplates_H
-#include "grib2.h"
-
-//   PRGMMR: Gilbert         ORG: W/NP11    DATE: 2001-10-26
-//
-// ABSTRACT: This Fortran Module contains info on all the available 
-//   GRIB2 Grid Definition Templates used in Section 3 (GDS).
-//   The information decribing each template is stored in the
-//   gridtemplate structure defined below.
-//
-//   Each Template has three parts: The number of entries in the template
-//   (mapgridlen);  A map of the template (mapgrid), which contains the
-//   number of octets in which to pack each of the template values; and
-//   a logical value (needext) that indicates whether the Template needs 
-//   to be extended.  In some cases the number of entries in a template 
-//   can vary depending upon values specified in the "static" part of 
-//   the template.  ( See Template 3.120 as an example )
-//
-//   NOTE:  Array mapgrid contains the number of octets in which the 
-//   corresponding template values will be stored.  A negative value in
-//   mapgrid is used to indicate that the corresponding template entry can
-//   contain negative values.  This information is used later when packing
-//   (or unpacking) the template data values.  Negative data values in GRIB
-//   are stored with the left most bit set to one, and a negative number
-//   of octets value in mapgrid[] indicates that this possibility should
-//   be considered.  The number of octets used to store the data value
-//   in this case would be the absolute value of the negative value in 
-//   mapgrid[].
-//  
-//
-////////////////////////////////////////////////////////////////////
-
-      #define MAXGRIDTEMP 23              // maximum number of templates
-      #define MAXGRIDMAPLEN 200           // maximum template map length
-
-      struct gridtemplate
-      {
-          g2int template_num;
-          g2int mapgridlen;
-          g2int needext;
-          g2int mapgrid[MAXGRIDMAPLEN];
-      };
-
-      const struct gridtemplate templatesgrid[MAXGRIDTEMP] = {
-             // 3.0: Lat/Lon grid
-         { 0, 19, 0, {1,1,4,1,4,1,4,4,4,4,4,-4,4,1,-4,4,4,4,1} },
-             // 3.1: Rotated Lat/Lon grid
-         { 1, 22, 0, {1,1,4,1,4,1,4,4,4,4,4,-4,4,1,-4,4,4,4,1,-4,4,4} },
-             // 3.2: Stretched Lat/Lon grid
-         { 2, 22, 0, {1,1,4,1,4,1,4,4,4,4,4,-4,4,1,-4,4,4,4,1,-4,4,-4} },
-             // 3.3: Stretched & Rotated Lat/Lon grid
-         { 3, 25, 0, {1,1,4,1,4,1,4,4,4,4,4,-4,4,1,-4,4,4,4,1,-4,4,4,-4,4,-4} },
-             // 3.10: Mercator
-         {10, 19, 0, {1,1,4,1,4,1,4,4,4,-4,4,1,-4,-4,4,1,4,4,4} },
-             // 3.20: Polar Stereographic Projection
-         {20, 18, 0, {1,1,4,1,4,1,4,4,4,-4,4,1,-4,4,4,4,1,1} },
-             // 3.30: Lambert Conformal
-         {30, 22, 0, {1,1,4,1,4,1,4,4,4,-4,4,1,-4,4,4,4,1,1,-4,-4,-4,4} },
-             // 3.31: Albers equal area
-         {31, 22, 0, {1,1,4,1,4,1,4,4,4,-4,4,1,-4,4,4,4,1,1,-4,-4,-4,4} },
-             // 3.40: Guassian Lat/Lon
-         {40, 19, 0, {1,1,4,1,4,1,4,4,4,4,4,-4,4,1,-4,4,4,4,1} },
-             // 3.41: Rotated Gaussian Lat/Lon
-         {41, 22, 0, {1,1,4,1,4,1,4,4,4,4,4,-4,4,1,-4,4,4,4,1,-4,4,4} },
-             // 3.42: Stretched Gaussian Lat/Lon
-         {42, 22, 0, {1,1,4,1,4,1,4,4,4,4,4,-4,4,1,-4,4,4,4,1,-4,4,-4} },
-             // 3.43: Stretched and Rotated Gaussian Lat/Lon
-         {43, 25, 0, {1,1,4,1,4,1,4,4,4,4,4,-4,4,1,-4,4,4,4,1,-4,4,4,-4,4,-4} },
-             // 3.50: Spherical Harmonic Coefficients
-         {50, 5, 0, {4,4,4,1,1} },
-             // 3.51: Rotated Spherical Harmonic Coefficients
-         {51, 8, 0, {4,4,4,1,1,-4,4,4} },
-             // 3.52: Stretched Spherical Harmonic Coefficients
-         {52, 8, 0, {4,4,4,1,1,-4,4,-4} },
-             // 3.53: Stretched and Rotated Spherical Harmonic Coefficients
-         {53, 11, 0, {4,4,4,1,1,-4,4,4,-4,4,-4} },
-             // 3.90: Space View Perspective or orthographic
-         {90, 21, 0, {1,1,4,1,4,1,4,4,4,-4,4,1,4,4,4,4,1,4,4,4,4} },
-             // 3.100: Triangular grid based on an icosahedron
-         {100, 11, 0, {1,1,2,1,-4,4,4,1,1,1,4} },
-             // 3.110: Equatorial Azimuthal equidistant
-         {110, 16, 0, {1,1,4,1,4,1,4,4,4,-4,4,1,4,4,1,1} },
-             // 3.120: Azimuth-range projection
-         {120, 7, 1, {4,4,-4,4,4,4,1} },
-             // 3.1000: Cross Section Grid
-         {1000, 20, 1, {1,1,4,1,4,1,4,4,4,4,-4,4,1,4,4,1,2,1,1,2} },
-             // 3.1100: Hovmoller Diagram Grid
-         {1100, 28, 0, {1,1,4,1,4,1,4,4,4,4,-4,4,1,-4,4,1,4,1,-4,1,1,-4,2,1,1,1,1,1} },
-             // 3.1200: Time Section Grid
-         {1200, 16, 1, {4,1,-4,1,1,-4,2,1,1,1,1,1,2,1,1,2} }
-
-      } ;
-
-
-#endif  /*  _gridtemplates_H  */
diff --git a/src/modules/io/io_grid_grib2/g2clib-1.0.4/int_power.c b/src/modules/io/io_grid_grib2/g2clib-1.0.4/int_power.c
deleted file mode 100644
index b5fed32..0000000
--- a/src/modules/io/io_grid_grib2/g2clib-1.0.4/int_power.c
+++ /dev/null
@@ -1,33 +0,0 @@
-/**********************************************************
- * Version $Id: int_power.c 911 2011-02-14 16:38:15Z reklov_w $
- *********************************************************/
-#include "grib2.h"
-/*
- * w. ebisuzaki
- *
- *  return x**y
- *
- *
- *  input: double x
- *         int y
- */
-double int_power(double x, g2int y) {
-
-        double value;
-
-        if (y < 0) {
-                y = -y;
-                x = 1.0 / x;
-        }
-        value = 1.0;
-
-        while (y) {
-                if (y & 1) {
-                        value *= x;
-                }
-                x = x * x;
-                y >>= 1;
-        }
-        return value;
-}
-
diff --git a/src/modules/io/io_grid_grib2/g2clib-1.0.4/jpcpack.c b/src/modules/io/io_grid_grib2/g2clib-1.0.4/jpcpack.c
deleted file mode 100644
index 2b42039..0000000
--- a/src/modules/io/io_grid_grib2/g2clib-1.0.4/jpcpack.c
+++ /dev/null
@@ -1,178 +0,0 @@
-/**********************************************************
- * Version $Id: jpcpack.c 911 2011-02-14 16:38:15Z reklov_w $
- *********************************************************/
-#include <stdlib.h>
-#include <math.h>
-#include "grib2.h"
-
-int enc_jpeg2000(unsigned char *,g2int ,g2int ,g2int ,
-                 g2int , g2int, g2int , char *, g2int );
-
-void jpcpack(g2float *fld,g2int width,g2int height,g2int *idrstmpl,
-             unsigned char *cpack,g2int *lcpack)
-//$$$  SUBPROGRAM DOCUMENTATION BLOCK
-//                .      .    .                                       .
-// SUBPROGRAM:    jpcpack
-//   PRGMMR: Gilbert          ORG: W/NP11    DATE: 2003-08-17
-//
-// ABSTRACT: This subroutine packs up a data field into a JPEG2000 code stream.
-//   After the data field is scaled, and the reference value is subtracted out,
-//   it is treated as a grayscale image and passed to a JPEG2000 encoder.
-//   It also fills in GRIB2 Data Representation Template 5.40 or 5.40000 with 
-//   the appropriate values.
-//
-// PROGRAM HISTORY LOG:
-// 2003-08-17  Gilbert
-// 2004-11-92  Gilbert  - Fixed bug encountered when packing a near constant
-//                        field.
-// 2004-07-19  Gilbert - Added check on whether the jpeg2000 encoding was
-//                       successful.  If not, try again with different encoder
-//                       options.
-// 2005-05-10  Gilbert - Imposed minimum size on cpack, used to hold encoded
-//                       bit string.
-//
-// USAGE:    jpcpack(g2float *fld,g2int width,g2int height,g2int *idrstmpl,
-//                   unsigned char *cpack,g2int *lcpack);
-//   INPUT ARGUMENT LIST:
-//     fld[]    - Contains the data values to pack
-//     width    - number of points in the x direction
-//     height   - number of points in the y direction
-//     idrstmpl - Contains the array of values for Data Representation
-//                Template 5.40 or 5.40000
-//                [0] = Reference value - ignored on input
-//                [1] = Binary Scale Factor
-//                [2] = Decimal Scale Factor
-//                [3] = number of bits for each data value - ignored on input
-//                [4] = Original field type - currently ignored on input
-//                      Data values assumed to be reals.
-//                [5] = 0 - use lossless compression
-//                    = 1 - use lossy compression
-//                [6] = Desired compression ratio, if idrstmpl[5]=1.
-//                      Set to 255, if idrstmpl[5]=0.
-//     lcpack   - size of array cpack[]
-//
-//   OUTPUT ARGUMENT LIST: 
-//     idrstmpl - Contains the array of values for Data Representation
-//                Template 5.0
-//                [0] = Reference value - set by jpcpack routine.
-//                [1] = Binary Scale Factor - unchanged from input
-//                [2] = Decimal Scale Factor - unchanged from input
-//                [3] = Number of bits containing each grayscale pixel value
-//                [4] = Original field type - currently set = 0 on output.
-//                      Data values assumed to be reals.
-//                [5] = 0 - use lossless compression
-//                    = 1 - use lossy compression
-//                [6] = Desired compression ratio, if idrstmpl[5]=1
-//     cpack    - The packed data field 
-//     lcpack   - length of packed field in cpack.
-//
-// REMARKS: None
-//
-// ATTRIBUTES:
-//   LANGUAGE: C
-//   MACHINE:  IBM SP
-//
-//$$$
-{
-      g2int  *ifld;
-      static g2float alog2=0.69314718;       //  ln(2.0)
-      g2int  j,nbits,imin,imax,maxdif;
-      g2int  ndpts,nbytes,nsize,retry;
-      g2float  bscale,dscale,rmax,rmin,temp;
-      unsigned char *ctemp;
-      
-      ifld=0;
-      ndpts=width*height;
-      bscale=int_power(2.0,-idrstmpl[1]);
-      dscale=int_power(10.0,idrstmpl[2]);
-//
-//  Find max and min values in the data
-//
-      rmax=fld[0];
-      rmin=fld[0];
-      for (j=1;j<ndpts;j++) {
-        if (fld[j] > rmax) rmax=fld[j];
-        if (fld[j] < rmin) rmin=fld[j];
-      }
-      if (idrstmpl[1] == 0) 
-         maxdif = (g2int) (rint(rmax*dscale) - rint(rmin*dscale));
-      else
-         maxdif = (g2int)rint( (rmax-rmin)*dscale*bscale );
-//
-//  If max and min values are not equal, pack up field.
-//  If they are equal, we have a constant field, and the reference
-//  value (rmin) is the value for each point in the field and
-//  set nbits to 0.
-//
-      if ( rmin != rmax  &&  maxdif != 0 ) {
-        ifld=(g2int *)malloc(ndpts*sizeof(g2int));
-        //
-        //  Determine which algorithm to use based on user-supplied 
-        //  binary scale factor and number of bits.
-        //
-        if (idrstmpl[1] == 0) {
-           //
-           //  No binary scaling and calculate minumum number of 
-           //  bits in which the data will fit.
-           //
-           imin=(g2int)rint(rmin*dscale);
-           imax=(g2int)rint(rmax*dscale);
-           maxdif=imax-imin;
-           temp=log((double)(maxdif+1))/alog2;
-           nbits=(g2int)ceil(temp);
-           rmin=(g2float)imin;
-           //   scale data
-           for(j=0;j<ndpts;j++)
-             ifld[j]=(g2int)rint(fld[j]*dscale)-imin;
-        }
-        else {
-           //
-           //  Use binary scaling factor and calculate minumum number of 
-           //  bits in which the data will fit.
-           //
-           rmin=rmin*dscale;
-           rmax=rmax*dscale;
-           maxdif=(g2int)rint((rmax-rmin)*bscale);
-           temp=log((double)(maxdif+1))/alog2;
-           nbits=(g2int)ceil(temp);
-           //   scale data
-           for (j=0;j<ndpts;j++)
-             ifld[j]=(g2int)rint(((fld[j]*dscale)-rmin)*bscale);
-        }
-        //
-        //  Pack data into full octets, then do JPEG 2000 encode.
-        //  and calculate the length of the packed data in bytes
-        //
-        retry=0;
-        nbytes=(nbits+7)/8;
-        nsize=*lcpack;          // needed for input to enc_jpeg2000
-        ctemp=calloc(ndpts,nbytes);
-        sbits(ctemp,ifld,0,nbytes*8,0,ndpts);
-        *lcpack=(g2int)enc_jpeg2000(ctemp,width,height,nbits,idrstmpl[5],idrstmpl[6],retry,(char *)cpack,nsize);
-        if (*lcpack <= 0) {
-           printf("jpcpack: ERROR Packing JPC = %d\n",(int)*lcpack);
-           if ( *lcpack == -3 ) {
-              retry=1;
-              *lcpack=(g2int)enc_jpeg2000(ctemp,width,height,nbits,idrstmpl[5],idrstmpl[6],retry,(char *)cpack,nsize);
-              if ( *lcpack <= 0 ) printf("jpcpack: Retry Failed.\n");
-              else printf("jpcpack: Retry Successful.\n");
-           }
-        }
-        free(ctemp);
-
-      }
-      else {
-        nbits=0;
-        *lcpack=0;
-      }
-
-//
-//  Fill in ref value and number of bits in Template 5.0
-//
-      mkieee(&rmin,idrstmpl+0,1);   // ensure reference value is IEEE format
-      idrstmpl[3]=nbits;
-      idrstmpl[4]=0;         // original data were reals
-      if (idrstmpl[5] == 0) idrstmpl[6]=255;       // lossy not used
-      if (ifld != 0) free(ifld);
-
-}
diff --git a/src/modules/io/io_grid_grib2/g2clib-1.0.4/jpcunpack.c b/src/modules/io/io_grid_grib2/g2clib-1.0.4/jpcunpack.c
deleted file mode 100644
index 7640bda..0000000
--- a/src/modules/io/io_grid_grib2/g2clib-1.0.4/jpcunpack.c
+++ /dev/null
@@ -1,75 +0,0 @@
-/**********************************************************
- * Version $Id: jpcunpack.c 911 2011-02-14 16:38:15Z reklov_w $
- *********************************************************/
-#include <stdio.h>
-#include <stdlib.h>
-#include "grib2.h"
-
-   int dec_jpeg2000(char *,g2int ,g2int *);
-
-g2int jpcunpack(unsigned char *cpack,g2int len,g2int *idrstmpl,g2int ndpts,
-                g2float *fld)
-//$$$  SUBPROGRAM DOCUMENTATION BLOCK
-//                .      .    .                                       .
-// SUBPROGRAM:    jpcunpack
-//   PRGMMR: Gilbert          ORG: W/NP11    DATE: 2003-08-27
-//
-// ABSTRACT: This subroutine unpacks a data field that was packed into a 
-//   JPEG2000 code stream
-//   using info from the GRIB2 Data Representation Template 5.40 or 5.40000.
-//
-// PROGRAM HISTORY LOG:
-// 2003-08-27  Gilbert
-//
-// USAGE:    jpcunpack(unsigned char *cpack,g2int len,g2int *idrstmpl,g2int ndpts,
-//                     g2float *fld)
-//   INPUT ARGUMENT LIST:
-//     cpack    - The packed data field (character*1 array)
-//     len      - length of packed field cpack().
-//     idrstmpl - Pointer to array of values for Data Representation
-//                Template 5.40 or 5.40000
-//     ndpts    - The number of data values to unpack
-//
-//   OUTPUT ARGUMENT LIST:
-//     fld[]    - Contains the unpacked data values
-//
-// REMARKS: None
-//
-// ATTRIBUTES:
-//   LANGUAGE: C
-//   MACHINE:  IBM SP
-//
-//$$$
-{
-
-      g2int  *ifld;
-      g2int  j,nbits,iret;
-      g2float  ref,bscale,dscale;
-
-      rdieee(idrstmpl+0,&ref,1);
-      bscale = int_power(2.0,idrstmpl[1]);
-      dscale = int_power(10.0,-idrstmpl[2]);
-      nbits = idrstmpl[3];
-//
-//  if nbits equals 0, we have a constant field where the reference value
-//  is the data value at each gridpoint
-//
-      if (nbits != 0) {
-
-         ifld=(g2int *)calloc(ndpts,sizeof(g2int));
-         if ( ifld == 0 ) {
-            fprintf(stderr,"Could not allocate space in jpcunpack.\n  Data field NOT upacked.\n");
-            return(1);
-         }
-         iret=(g2int)dec_jpeg2000(cpack,len,ifld);
-         for (j=0;j<ndpts;j++) {
-           fld[j]=(((g2float)ifld[j]*bscale)+ref)*dscale;
-         }
-         free(ifld);
-      }
-      else {
-         for (j=0;j<ndpts;j++) fld[j]=ref;
-      }
-
-      return(0);
-}
diff --git a/src/modules/io/io_grid_grib2/g2clib-1.0.4/misspack.c b/src/modules/io/io_grid_grib2/g2clib-1.0.4/misspack.c
deleted file mode 100644
index ff69fac..0000000
--- a/src/modules/io/io_grid_grib2/g2clib-1.0.4/misspack.c
+++ /dev/null
@@ -1,535 +0,0 @@
-/**********************************************************
- * Version $Id: misspack.c 911 2011-02-14 16:38:15Z reklov_w $
- *********************************************************/
-#include <stdlib.h>
-#include <math.h>
-#include "grib2.h"
-
-void misspack(g2float *fld,g2int ndpts,g2int idrsnum,g2int *idrstmpl,
-              unsigned char *cpack, g2int *lcpack)
-//$$$  SUBPROGRAM DOCUMENTATION BLOCK
-//                .      .    .                                       .
-// SUBPROGRAM:    misspack
-//   PRGMMR: Gilbert          ORG: W/NP11    DATE: 2000-06-21
-//
-// ABSTRACT: This subroutine packs up a data field using a complex
-//   packing algorithm as defined in the GRIB2 documention.  It
-//   supports GRIB2 complex packing templates with or without
-//   spatial differences (i.e. DRTs 5.2 and 5.3).
-//   It also fills in GRIB2 Data Representation Template 5.2 or 5.3 
-//   with the appropriate values.
-//   This version assumes that Missing Value Management is being used and that
-//   1 or 2 missing values appear in the data.
-//
-// PROGRAM HISTORY LOG:
-// 2000-06-21  Gilbert
-//
-// USAGE:    misspack(g2float *fld,g2int ndpts,g2int idrsnum,g2int *idrstmpl,
-//                    unsigned char *cpack, g2int *lcpack)
-//   INPUT ARGUMENT LIST:
-//     fld[]    - Contains the data values to pack
-//     ndpts    - The number of data values in array fld[]
-//     idrsnum  - Data Representation Template number 5.N
-//                Must equal 2 or 3.
-//     idrstmpl - Contains the array of values for Data Representation
-//                Template 5.2 or 5.3
-//                [0] = Reference value - ignored on input
-//                [1] = Binary Scale Factor
-//                [2] = Decimal Scale Factor
-//                    .
-//                    .
-//                [6] = Missing value management
-//                [7] = Primary missing value
-//                [8] = Secondary missing value
-//                    .
-//                    .
-//               [16] = Order of Spatial Differencing  ( 1 or 2 )
-//                    .
-//                    .
-//
-//   OUTPUT ARGUMENT LIST: 
-//     idrstmpl - Contains the array of values for Data Representation
-//                Template 5.3
-//                [0] = Reference value - set by misspack routine.
-//                [1] = Binary Scale Factor - unchanged from input
-//                [2] = Decimal Scale Factor - unchanged from input
-//                    .
-//                    .
-//     cpack    - The packed data field (character*1 array)
-//     *lcpack   - length of packed field cpack().
-//
-// REMARKS: None
-//
-// ATTRIBUTES:
-//   LANGUAGE: C
-//   MACHINE:  
-//
-//$$$
-{
-
-      g2int  *ifld, *ifldmiss, *jfld;
-      g2int  *jmin, *jmax, *lbit;
-      static g2int zero=0;
-      g2int  *gref, *gwidth, *glen;
-      g2int  glength, grpwidth;
-      g2int  i, n, iofst, imin, ival1, ival2, isd, minsd, nbitsd;
-      g2int  nbitsgref, left, iwmax, ngwidthref, nbitsgwidth, ilmax;
-      g2int  nglenref, nglenlast, nbitsglen, ij;
-      g2int  j, missopt, nonmiss, itemp, maxorig, nbitorig, miss1, miss2;
-      g2int  ngroups, ng, num0, num1, num2;
-      g2int  imax, lg, mtemp, ier, igmax;
-      g2int  kfildo, minpk, inc, maxgrps, ibit, jbit, kbit, novref, lbitref;
-      g2float  rmissp, rmisss, bscale, dscale, rmin, temp;
-      static g2int simple_alg = 0;
-      static g2float alog2=0.69314718;       //  ln(2.0)
-      static g2int one=1;
-      
-      bscale=int_power(2.0,-idrstmpl[1]);
-      dscale=int_power(10.0,idrstmpl[2]);
-      missopt=idrstmpl[6];
-      if ( missopt != 1 && missopt != 2 ) {
-         printf("misspack: Unrecognized option.\n");
-         *lcpack=-1;
-         return;
-      }
-      else {    //  Get missing values
-         rdieee(idrstmpl+7,&rmissp,1);
-         if (missopt == 2) rdieee(idrstmpl+8,&rmisss,1);
-      }
-//
-//  Find min value of non-missing values in the data,
-//  AND set up missing value mapping of the field.
-//
-      ifldmiss = calloc(ndpts,sizeof(g2int));
-      rmin=1E+37;
-      if ( missopt ==  1 ) {        // Primary missing value only
-         for ( j=0; j<ndpts; j++) {
-           if (fld[j] == rmissp) {
-              ifldmiss[j]=1;
-           }
-           else {
-              ifldmiss[j]=0;
-              if (fld[j] < rmin) rmin=fld[j];
-           }
-         }
-      }
-      if ( missopt ==  2 ) {        // Primary and secondary missing values
-         for ( j=0; j<ndpts; j++ ) {
-           if (fld[j] == rmissp) {
-              ifldmiss[j]=1;
-           }
-           else if (fld[j] == rmisss) {
-              ifldmiss[j]=2;
-           }
-           else {
-              ifldmiss[j]=0;
-              if (fld[j] < rmin) rmin=fld[j];
-           }
-         }
-      }
-//
-//  Allocate work arrays:
-//  Note: -ifldmiss[j],j=0,ndpts-1 is a map of original field indicating 
-//         which of the original data values
-//         are primary missing (1), sencondary missing (2) or non-missing (0).
-//        -jfld[j],j=0,nonmiss-1 is a subarray of just the non-missing values 
-//         from the original field.
-//
-      //if (rmin != rmax) {
-        iofst=0;
-        ifld = calloc(ndpts,sizeof(g2int));
-        jfld = calloc(ndpts,sizeof(g2int));
-        gref = calloc(ndpts,sizeof(g2int));
-        gwidth = calloc(ndpts,sizeof(g2int));
-        glen = calloc(ndpts,sizeof(g2int));
-        //
-        //  Scale original data
-        //
-        nonmiss=0;
-        if (idrstmpl[1] == 0) {        //  No binary scaling
-           imin=(g2int)rint(rmin*dscale);
-           //imax=(g2int)rint(rmax*dscale);
-           rmin=(g2float)imin;
-           for ( j=0; j<ndpts; j++) {
-              if (ifldmiss[j] == 0) {
-                jfld[nonmiss]=(g2int)rint(fld[j]*dscale)-imin;
-                nonmiss++;
-              }
-           }
-        }
-        else {                             //  Use binary scaling factor
-           rmin=rmin*dscale;
-           //rmax=rmax*dscale;
-           for ( j=0; j<ndpts; j++ ) {
-              if (ifldmiss[j] == 0) {
-                jfld[nonmiss]=(g2int)rint(((fld[j]*dscale)-rmin)*bscale);
-                nonmiss++;
-              }
-           }
-        }
-        //
-        //  Calculate Spatial differences, if using DRS Template 5.3
-        //
-        if (idrsnum == 3) {        // spatial differences
-           if (idrstmpl[16]!=1 && idrstmpl[16]!=2) idrstmpl[16]=2;
-           if (idrstmpl[16] == 1) {      // first order
-              ival1=jfld[0];
-              for ( j=nonmiss-1; j>0; j--)
-                 jfld[j]=jfld[j]-jfld[j-1];
-              jfld[0]=0;
-           }
-           else if (idrstmpl[16] == 2) {      // second order
-              ival1=jfld[0];
-              ival2=jfld[1];
-              for ( j=nonmiss-1; j>1; j--)
-                 jfld[j]=jfld[j]-(2*jfld[j-1])+jfld[j-2];
-              jfld[0]=0;
-              jfld[1]=0;
-           }
-           //
-           //  subtract min value from spatial diff field
-           //
-           isd=idrstmpl[16];
-           minsd=jfld[isd];
-           for ( j=isd; j<nonmiss; j++ ) if ( jfld[j] < minsd ) minsd=jfld[j];
-           for ( j=isd; j<nonmiss; j++ ) jfld[j]=jfld[j]-minsd;
-           //
-           //   find num of bits need to store minsd and add 1 extra bit
-           //   to indicate sign
-           //
-           temp=log((double)(abs(minsd)+1))/alog2;
-           nbitsd=(g2int)ceil(temp)+1;
-           //
-           //   find num of bits need to store ifld[0] ( and ifld[1]
-           //   if using 2nd order differencing )
-           //
-           maxorig=ival1;
-           if (idrstmpl[16]==2 && ival2>ival1) maxorig=ival2;
-           temp=log((double)(maxorig+1))/alog2;
-           nbitorig=(g2int)ceil(temp)+1;
-           if (nbitorig > nbitsd) nbitsd=nbitorig;
-           //   increase number of bits to even multiple of 8 ( octet )
-           if ( (nbitsd%8) != 0) nbitsd=nbitsd+(8-(nbitsd%8));
-           //
-           //  Store extra spatial differencing info into the packed
-           //  data section.
-           //
-           if (nbitsd != 0) {
-              //   pack first original value
-              if (ival1 >= 0) {
-                 sbit(cpack,&ival1,iofst,nbitsd);
-                 iofst=iofst+nbitsd;
-              }
-              else {
-                 sbit(cpack,&one,iofst,1);
-                 iofst=iofst+1;
-                 itemp=abs(ival1);
-                 sbit(cpack,&itemp,iofst,nbitsd-1);
-                 iofst=iofst+nbitsd-1;
-              }
-              if (idrstmpl[16] == 2) {
-               //  pack second original value
-                 if (ival2 >= 0) {
-                    sbit(cpack,&ival2,iofst,nbitsd);
-                    iofst=iofst+nbitsd;
-                 }
-                 else {
-                    sbit(cpack,&one,iofst,1);
-                    iofst=iofst+1;
-                    itemp=abs(ival2);
-                    sbit(cpack,&itemp,iofst,nbitsd-1);
-                    iofst=iofst+nbitsd-1;
-                 }
-              }
-              //  pack overall min of spatial differences
-              if (minsd >= 0) {
-                 sbit(cpack,&minsd,iofst,nbitsd);
-                 iofst=iofst+nbitsd;
-              }
-              else {
-                 sbit(cpack,&one,iofst,1);
-                 iofst=iofst+1;
-                 itemp=abs(minsd);
-                 sbit(cpack,&itemp,iofst,nbitsd-1);
-                 iofst=iofst+nbitsd-1;
-              }
-           }
-         //print *,'SDp ',ival1,ival2,minsd,nbitsd
-        }       //  end of spatial diff section
-        //
-        //  Expand non-missing data values to original grid.
-        //
-        miss1=jfld[0];
-        for ( j=0; j<nonmiss; j++) if (jfld[j] < miss1) miss1 = jfld[j];
-        miss1--;
-        miss2=miss1-1;
-        n=0;
-        for ( j=0; j<ndpts; j++) {
-           if ( ifldmiss[j] == 0 ) {
-              ifld[j]=jfld[n];
-              n++;
-           }
-           else if ( ifldmiss[j] == 1 ) {
-              ifld[j]=miss1;
-           }
-           else if ( ifldmiss[j] == 2 ) {
-              ifld[j]=miss2;
-           }
-        }
-        //
-        //   Determine Groups to be used.
-        //
-        if ( simple_alg == 1 ) {
-           //  set group length to 10 :  calculate number of groups
-           //  and length of last group
-           ngroups=ndpts/10;
-           for (j=0;j<ngroups;j++) glen[j]=10;
-           itemp=ndpts%10;
-           if (itemp != 0) {
-              ngroups++;
-              glen[ngroups-1]=itemp;
-           }
-        }
-        else {
-           // Use Dr. Glahn's algorithm for determining grouping.
-           //
-           kfildo=6;
-           minpk=10;
-           inc=1;
-           maxgrps=(ndpts/minpk)+1;
-           jmin = calloc(maxgrps,sizeof(g2int));
-           jmax = calloc(maxgrps,sizeof(g2int));
-           lbit = calloc(maxgrps,sizeof(g2int));
-           pack_gp(&kfildo,ifld,&ndpts,&missopt,&minpk,&inc,&miss1,&miss2,
-                        jmin,jmax,lbit,glen,&maxgrps,&ngroups,&ibit,&jbit,
-                        &kbit,&novref,&lbitref,&ier);
-           //printf("SAGier = %d %d %d %d %d %d\n",ier,ibit,jbit,kbit,novref,lbitref);
-           for ( ng=0; ng<ngroups; ng++) glen[ng]=glen[ng]+novref;
-           free(jmin);
-           free(jmax);
-           free(lbit);
-        }
-        //  
-        //  For each group, find the group's reference value (min)
-        //  and the number of bits needed to hold the remaining values
-        //
-        n=0;
-        for ( ng=0; ng<ngroups; ng++) {
-           //  how many of each type?
-           num0=num1=num2=0;
-           for (j=n; j<n+glen[ng]; j++) {
-               if (ifldmiss[j] == 0 ) num0++;
-               if (ifldmiss[j] == 1 ) num1++;
-               if (ifldmiss[j] == 2 ) num2++;
-           }
-           if ( num0 == 0 ) {      // all missing values
-              if ( num1 == 0 ) {       // all secondary missing
-                gref[ng]=-2;
-                gwidth[ng]=0;
-              }
-              else if ( num2 == 0 ) {       // all primary missing
-                gref[ng]=-1;
-                gwidth[ng]=0;
-              }
-              else {                          // both primary and secondary
-                gref[ng]=0;
-                gwidth[ng]=1;
-              }
-           }
-           else {                      // contains some non-missing data
-             //    find max and min values of group
-             gref[ng]=2147483647;
-             imax=-2147483647;
-             j=n;
-             for ( lg=0; lg<glen[ng]; lg++ ) {
-                if ( ifldmiss[j] == 0 ) {
-                  if (ifld[j] < gref[ng]) gref[ng]=ifld[j];
-                  if (ifld[j] > imax) imax=ifld[j]; 
-                }
-                j++;
-             }
-             if (missopt == 1) imax=imax+1;
-             if (missopt == 2) imax=imax+2;
-             //   calc num of bits needed to hold data
-             if ( gref[ng] != imax ) {
-                temp=log((double)(imax-gref[ng]+1))/alog2;
-                gwidth[ng]=(g2int)ceil(temp);
-             }
-             else {
-                gwidth[ng]=0;
-             }
-           }
-           //   Subtract min from data
-           j=n;
-           mtemp=(g2int)int_power(2.,gwidth[ng]);
-           for ( lg=0; lg<glen[ng]; lg++ ) {
-              if (ifldmiss[j] == 0)            // non-missing
-                 ifld[j]=ifld[j]-gref[ng];
-              else if (ifldmiss[j] == 1)         // primary missing
-                 ifld[j]=mtemp-1;
-              else if (ifldmiss[j] == 2)         // secondary missing
-                 ifld[j]=mtemp-2;
-              
-              j++;
-           }
-           //   increment fld array counter
-           n=n+glen[ng];
-        }
-        //  
-        //  Find max of the group references and calc num of bits needed 
-        //  to pack each groups reference value, then
-        //  pack up group reference values
-        //
-        //printf(" GREFS: ");
-        //for (j=0;j<ngroups;j++) printf(" %d",gref[j]); printf("\n");
-        igmax=gref[0];
-        for (j=1;j<ngroups;j++) if (gref[j] > igmax) igmax=gref[j];
-        if (missopt == 1) igmax=igmax+1;
-        if (missopt == 2) igmax=igmax+2;
-        if (igmax != 0) {
-           temp=log((double)(igmax+1))/alog2;
-           nbitsgref=(g2int)ceil(temp);
-           // reset the ref values of any "missing only" groups.
-           mtemp=(g2int)int_power(2.,nbitsgref);
-           for ( j=0; j<ngroups; j++ ) {
-               if (gref[j] == -1) gref[j]=mtemp-1;
-               if (gref[j] == -2) gref[j]=mtemp-2;
-           }
-           sbits(cpack,gref,iofst,nbitsgref,0,ngroups);
-           itemp=nbitsgref*ngroups;
-           iofst=iofst+itemp;
-           //         Pad last octet with Zeros, if necessary,
-           if ( (itemp%8) != 0) {
-              left=8-(itemp%8);
-              sbit(cpack,&zero,iofst,left);
-              iofst=iofst+left;
-           }
-        }
-        else {
-           nbitsgref=0;
-        }
-        //
-        //  Find max/min of the group widths and calc num of bits needed
-        //  to pack each groups width value, then
-        //  pack up group width values
-        //
-        //write(77,*)'GWIDTHS: ',(gwidth(j),j=1,ngroups)
-        iwmax=gwidth[0];
-        ngwidthref=gwidth[0];
-        for (j=1;j<ngroups;j++) {
-           if (gwidth[j] > iwmax) iwmax=gwidth[j];
-           if (gwidth[j] < ngwidthref) ngwidthref=gwidth[j];
-        }
-        if (iwmax != ngwidthref) {
-           temp=log((double)(iwmax-ngwidthref+1))/alog2;
-           nbitsgwidth=(g2int)ceil(temp);
-           for ( i=0; i<ngroups; i++) gwidth[i]=gwidth[i]-ngwidthref;
-           sbits(cpack,gwidth,iofst,nbitsgwidth,0,ngroups);
-           itemp=nbitsgwidth*ngroups;
-           iofst=iofst+itemp;
-           //         Pad last octet with Zeros, if necessary,
-           if ( (itemp%8) != 0) {
-              left=8-(itemp%8);
-              sbit(cpack,&zero,iofst,left);
-              iofst=iofst+left;
-           }
-        }
-        else {
-           nbitsgwidth=0;
-           for (i=0;i<ngroups;i++) gwidth[i]=0;
-        }
-        //
-        //  Find max/min of the group lengths and calc num of bits needed
-        //  to pack each groups length value, then
-        //  pack up group length values
-        //
-        //printf(" GLENS: ");
-        //for (j=0;j<ngroups;j++) printf(" %d",glen[j]); printf("\n");
-        ilmax=glen[0];
-        nglenref=glen[0];
-        for (j=1;j<ngroups-1;j++) {
-           if (glen[j] > ilmax) ilmax=glen[j];
-           if (glen[j] < nglenref) nglenref=glen[j];
-        }
-        nglenlast=glen[ngroups-1];
-        if (ilmax != nglenref) {
-           temp=log((double)(ilmax-nglenref+1))/alog2;
-           nbitsglen=(g2int)ceil(temp);
-           for ( i=0; i<ngroups-1; i++) glen[i]=glen[i]-nglenref;
-           sbits(cpack,glen,iofst,nbitsglen,0,ngroups);
-           itemp=nbitsglen*ngroups;
-           iofst=iofst+itemp;
-           //         Pad last octet with Zeros, if necessary,
-           if ( (itemp%8) != 0) {
-              left=8-(itemp%8);
-              sbit(cpack,&zero,iofst,left);
-              iofst=iofst+left;
-           }
-        }
-        else {
-           nbitsglen=0;
-           for (i=0;i<ngroups;i++) glen[i]=0;
-        }
-        //
-        //  For each group, pack data values
-        //
-        //write(77,*)'IFLDS: ',(ifld(j),j=1,ndpts)
-        n=0;
-        ij=0;
-        for ( ng=0; ng<ngroups; ng++) {
-           glength=glen[ng]+nglenref;
-           if (ng == (ngroups-1) ) glength=nglenlast;
-           grpwidth=gwidth[ng]+ngwidthref;
-       //write(77,*)'NGP ',ng,grpwidth,glength,gref(ng)
-           if ( grpwidth != 0 ) {
-              sbits(cpack,ifld+n,iofst,grpwidth,0,glength);
-              iofst=iofst+(grpwidth*glength);
-           }
-       //  do kk=1,glength
-       //     ij=ij+1
-       //write(77,*)'SAG ',ij,fld(ij),ifld(ij),gref(ng),bscale,rmin,dscale
-       //  enddo
-           n=n+glength;
-        }
-        //         Pad last octet with Zeros, if necessary,
-        if ( (iofst%8) != 0) {
-           left=8-(iofst%8);
-           sbit(cpack,&zero,iofst,left);
-           iofst=iofst+left;
-        }
-        *lcpack=iofst/8;
-        //
-        if ( ifld != 0 ) free(ifld);
-        if ( jfld != 0 ) free(jfld);
-        if ( ifldmiss != 0 ) free(ifldmiss);
-        if ( gref != 0 ) free(gref);
-        if ( gwidth != 0 ) free(gwidth);
-        if ( glen != 0 ) free(glen);
-      //}
-      //else {          //   Constant field ( max = min )
-      //  nbits=0;
-      //  *lcpack=0;
-      //  nbitsgref=0;
-      //  ngroups=0;
-      //}
-
-//
-//  Fill in ref value and number of bits in Template 5.2
-//
-      mkieee(&rmin,idrstmpl+0,1);   // ensure reference value is IEEE format
-      idrstmpl[3]=nbitsgref;
-      idrstmpl[4]=0;         // original data were reals
-      idrstmpl[5]=1;         // general group splitting
-      idrstmpl[9]=ngroups;          // Number of groups
-      idrstmpl[10]=ngwidthref;       // reference for group widths
-      idrstmpl[11]=nbitsgwidth;      // num bits used for group widths
-      idrstmpl[12]=nglenref;         // Reference for group lengths
-      idrstmpl[13]=1;                // length increment for group lengths
-      idrstmpl[14]=nglenlast;        // True length of last group
-      idrstmpl[15]=nbitsglen;        // num bits used for group lengths
-      if (idrsnum == 3) {
-         idrstmpl[17]=nbitsd/8;      // num bits used for extra spatial
-                                     // differencing values
-      }
-
-}
diff --git a/src/modules/io/io_grid_grib2/g2clib-1.0.4/mkieee.c b/src/modules/io/io_grid_grib2/g2clib-1.0.4/mkieee.c
deleted file mode 100644
index 37fb87b..0000000
--- a/src/modules/io/io_grid_grib2/g2clib-1.0.4/mkieee.c
+++ /dev/null
@@ -1,126 +0,0 @@
-/**********************************************************
- * Version $Id: mkieee.c 911 2011-02-14 16:38:15Z reklov_w $
- *********************************************************/
-#include <stdlib.h>
-#include <math.h>
-#include "grib2.h"
-
-
-void mkieee(g2float *a,g2int *rieee,g2int num)
-//$$$  SUBPROGRAM DOCUMENTATION BLOCK
-//                .      .    .                                       .
-// SUBPROGRAM:    mkieee 
-//   PRGMMR: Gilbert         ORG: W/NP11    DATE: 2002-10-29
-//
-// ABSTRACT: This subroutine stores a list of real values in 
-//   32-bit IEEE floating point format.
-//
-// PROGRAM HISTORY LOG:
-// 2002-10-29  Gilbert
-//
-// USAGE:    mkieee(g2float *a,g2int *rieee,g2int num);
-//   INPUT ARGUMENT LIST:
-//     a        - Input array of floating point values.
-//     num      - Number of floating point values to convert.
-//
-//   OUTPUT ARGUMENT LIST:      
-//     rieee    - Output array of data values in 32-bit IEEE format
-//                stored in g2int integer array.  rieee must be allocated
-//                with at least 4*num bytes of memory before calling this
-//                function.
-//
-// REMARKS: None
-//
-// ATTRIBUTES:
-//   LANGUAGE: C
-//   MACHINE:  
-//
-//$$$
-{
-
-      g2int  j,n,ieee,iexp,imant;
-      double  alog2,atemp;
-
-      static double  two23,two126;
-      static g2int test=0;
-    //g2intu msk1=0x80000000;        // 10000000000000000000000000000000 binary
-    //g2int msk2=0x7F800000;         // 01111111100000000000000000000000 binary
-    //g2int msk3=0x007FFFFF;         // 00000000011111111111111111111111 binary
-
-      if ( test == 0 ) {
-         two23=(double)int_power(2.0,23);
-         two126=(double)int_power(2.0,126);
-         test=1;
-      }
-
-      alog2=0.69314718;       //  ln(2.0)
-
-      for (j=0;j<num;j++) {
-      
-        ieee=0;
-
-        if (a[j] == 0.0) {
-          rieee[j]=ieee;
-          continue;
-        }
-        
-//
-//  Set Sign bit (bit 31 - leftmost bit)
-//
-        if (a[j] < 0.0) {
-          ieee= 1 << 31;
-          atemp=-1.0*a[j];
-        }
-        else {
-          ieee= 0 << 31;
-          atemp=a[j];
-        }
-        //printf("sign %ld %x \n",ieee,ieee);
-//
-//  Determine exponent n with base 2
-//
-        if ( atemp >= 1.0 ) {
-           n = 0;
-           while ( int_power(2.0,n+1) <= atemp ) {
-              n++;
-           }
-        }
-        else {
-           n = -1;
-           while ( int_power(2.0,n) > atemp ) {
-              n--;
-           }
-        }
-        //n=(g2int)floor(log(atemp)/alog2);
-        iexp=n+127;
-        if (n >  127) iexp=255;     // overflow
-        if (n < -127) iexp=0;
-        //printf("exp %ld %ld \n",iexp,n);
-        //      set exponent bits ( bits 30-23 )
-        ieee = ieee | ( iexp << 23 );
-//
-//  Determine Mantissa
-// 
-        if (iexp != 255) {
-          if (iexp != 0) 
-            atemp=(atemp/int_power(2.0,n))-1.0;
-          else
-            atemp=atemp*two126;
-          imant=(g2int)rint(atemp*two23);
-        }
-        else {
-          imant=0;
-        }
-        //printf("mant %ld %x \n",imant,imant);
-        //      set mantissa bits ( bits 22-0 )
-        ieee = ieee | imant;
-//
-//  Transfer IEEE bit string to rieee array
-//
-        rieee[j]=ieee;
-
-      }
-
-      return;
-
-}
diff --git a/src/modules/io/io_grid_grib2/g2clib-1.0.4/pack_gp.c b/src/modules/io/io_grid_grib2/g2clib-1.0.4/pack_gp.c
deleted file mode 100644
index 4cde3e2..0000000
--- a/src/modules/io/io_grid_grib2/g2clib-1.0.4/pack_gp.c
+++ /dev/null
@@ -1,1450 +0,0 @@
-/**********************************************************
- * Version $Id: pack_gp.c 911 2011-02-14 16:38:15Z reklov_w $
- *********************************************************/
-/* pack_gp.f -- translated by f2c (version 20031025).
-   You must link the resulting object file with libf2c:
-	on Microsoft Windows system, link with libf2c.lib;
-	on Linux or Unix systems, link with .../path/to/libf2c.a -lm
-	or, if you install libf2c.a in a standard place, with -lf2c -lm
-	-- in that order, at the end of the command line, as in
-		cc *.o -lf2c -lm
-	Source for libf2c is in /netlib/f2c/libf2c.zip, e.g.,
-
-		http://www.netlib.org/f2c/libf2c.zip
-*/
-
-/*#include "f2c.h"*/
-#include <stdlib.h>
-#include "grib2.h"
-typedef g2int integer;
-typedef g2int logical;
-#define TRUE_ (1)
-#define FALSE_ (0)
-
-/* Subroutine */ int pack_gp(integer *kfildo, integer *ic, integer *nxy, 
-	integer *is523, integer *minpk, integer *inc, integer *missp, integer 
-	*misss, integer *jmin, integer *jmax, integer *lbit, integer *nov, 
-	integer *ndg, integer *lx, integer *ibit, integer *jbit, integer *
-	kbit, integer *novref, integer *lbitref, integer *ier)
-{
-    /* Initialized data */
-
-    const  integer mallow = 1073741825;   /*  MALLOW=2**30+1  */
-    static integer ifeed = 12;
-    static integer ifirst = 0;
-
-    /* System generated locals */
-    integer i__1, i__2, i__3;
-
-    /* Local variables */
-    static integer j, k, l;
-    static logical adda;
-    static integer ired, kinc, mina, maxa, minb, maxb, minc, maxc, ibxx2[31];
-    static char cfeed[1];
-    static integer nenda, nendb, ibita, ibitb, minak, minbk, maxak, maxbk, 
-	    minck, maxck, nouta, lmiss, itest, nount;
-    extern /* Subroutine */ int reduce(integer *, integer *, integer *, 
-	    integer *, integer *, integer *, integer *, integer *, integer *, 
-	    integer *, integer *, integer *, integer *);
-    static integer ibitbs, mislla, misllb, misllc, iersav, lminpk, ktotal, 
-	    kounta, kountb, kstart, mstart, mintst, maxtst, 
-	    kounts, mintstk, maxtstk;
-    integer *misslx;
-
-
-/*        FEBRUARY 1994   GLAHN   TDL   MOS-2000 */
-/*        JUNE     1995   GLAHN   MODIFIED FOR LMISS ERROR. */
-/*        JULY     1996   GLAHN   ADDED MISSS */
-/*        FEBRUARY 1997   GLAHN   REMOVED 4 REDUNDANT TESTS FOR */
-/*                                MISSP.EQ.0; INSERTED A TEST TO BETTER */
-/*                                HANDLE A STRING OF 9999'S */
-/*        FEBRUARY 1997   GLAHN   ADDED LOOPS TO ELIMINATE TEST FOR */
-/*                                MISSS WHEN MISSS = 0 */
-/*        MARCH    1997   GLAHN   CORRECTED FOR SECONDARY MISSING VALUE */
-/*        MARCH    1997   GLAHN   CORRECTED FOR USE OF LOCAL VALUE */
-/*                                OF MINPK */
-/*        MARCH    1997   GLAHN   CORRECTED FOR SECONDARY MISSING VALUE */
-/*        MARCH    1997   GLAHN   CHANGED CALCULATING NUMBER OF BITS */
-/*                                THROUGH EXPONENTS TO AN ARRAY (IMPROVED */
-/*                                OVERALL PACKING PERFORMANCE BY ABOUT */
-/*                                35 PERCENT!).  ALLOWED 0 BITS FOR */
-/*                                PACKING JMIN( ), LBIT( ), AND NOV( ). */
-/*        MAY      1997   GLAHN   A NUMBER OF CHANGES FOR EFFICIENCY. */
-/*                                MOD FUNCTIONS ELIMINATED AND ONE */
-/*                                IFTHEN ADDED.  JOUNT REMOVED. */
-/*                                RECOMPUTATION OF BITS NOT MADE UNLESS */
-/*                                NECESSARY AFTER MOVING POINTS FROM */
-/*                                ONE GROUP TO ANOTHER.  NENDB ADJUSTED */
-/*                                TO ELIMINATE POSSIBILITY OF VERY */
-/*                                SMALL GROUP AT THE END. */
-/*                                ABOUT 8 PERCENT IMPROVEMENT IN */
-/*                                OVERALL PACKING.  ISKIPA REMOVED; */
-/*                                THERE IS ALWAYS A GROUP B THAT CAN */
-/*                                BECOME GROUP A.  CONTROL ON SIZE */
-/*                                OF GROUP B (STATEMENT BELOW 150) */
-/*                                ADDED.  ADDED ADDA, AND USE */
-/*                                OF GE AND LE INSTEAD OF GT AND LT */
-/*                                IN LOOPS BETWEEN 150 AND 160. */
-/*                                IBITBS ADDED TO SHORTEN TRIPS */
-/*                                THROUGH LOOP. */
-/*        MARCH    2000   GLAHN   MODIFIED FOR GRIB2; CHANGED NAME FROM */
-/*                                PACKGP */
-/*        JANUARY  2001   GLAHN   COMMENTS; IER = 706 SUBSTITUTED FOR */
-/*                                STOPS; ADDED RETURN1; REMOVED STATEMENT */
-/*                                NUMBER 110; ADDED IER AND * RETURN */
-/*        NOVEMBER 2001   GLAHN   CHANGED SOME DIAGNOSTIC FORMATS TO */
-/*                                ALLOW PRINTING LARGER NUMBERS */
-/*        NOVEMBER 2001   GLAHN   ADDED MISSLX( ) TO PUT MAXIMUM VALUE */
-/*                                INTO JMIN( ) WHEN ALL VALUES MISSING */
-/*                                TO AGREE WITH GRIB STANDARD. */
-/*        NOVEMBER 2001   GLAHN   CHANGED TWO TESTS ON MISSP AND MISSS */
-/*                                EQ 0 TO TESTS ON IS523.  HOWEVER, */
-/*                                MISSP AND MISSS CANNOT IN GENERAL BE */
-/*                                = 0. */
-/*        NOVEMBER 2001   GLAHN   ADDED CALL TO REDUCE; DEFINED ITEST */
-/*                                BEFORE LOOPS TO REDUCE COMPUTATION; */
-/*                                STARTED LARGE GROUP WHEN ALL SAME */
-/*                                VALUE */
-/*        DECEMBER 2001   GLAHN   MODIFIED AND ADDED A FEW COMMENTS */
-/*        JANUARY  2002   GLAHN   REMOVED LOOP BEFORE 150 TO DETERMINE */
-/*                                A GROUP OF ALL SAME VALUE */
-/*        JANUARY  2002   GLAHN   CHANGED MALLOW FROM 9999999 TO 2**30+1, */
-/*                                AND MADE IT A PARAMETER */
-/*        MARCH    2002   GLAHN   ADDED NON FATAL IER = 716, 717; */
-/*                                REMOVED NENDB=NXY ABOVE 150; */
-/*                                ADDED IERSAV=0; COMMENTS */
-
-/*        PURPOSE */
-/*            DETERMINES GROUPS OF VARIABLE SIZE, BUT AT LEAST OF */
-/*            SIZE MINPK, THE ASSOCIATED MAX (JMAX( )) AND MIN (JMIN( )), */
-/*            THE NUMBER OF BITS NECESSARY TO HOLD THE VALUES IN EACH */
-/*            GROUP (LBIT( )), THE NUMBER OF VALUES IN EACH GROUP */
-/*            (NOV( )), THE NUMBER OF BITS NECESSARY TO PACK THE JMIN( ) */
-/*            VALUES (IBIT), THE NUMBER OF BITS NECESSARY TO PACK THE */
-/*            LBIT( ) VALUES (JBIT), AND THE NUMBER OF BITS NECESSARY */
-/*            TO PACK THE NOV( ) VALUES (KBIT).  THE ROUTINE IS DESIGNED */
-/*            TO DETERMINE THE GROUPS SUCH THAT A SMALL NUMBER OF BITS */
-/*            IS NECESSARY TO PACK THE DATA WITHOUT EXCESSIVE */
-/*            COMPUTATIONS.  IF ALL VALUES IN THE GROUP ARE ZERO, THE */
-/*            NUMBER OF BITS TO USE IN PACKING IS DEFINED AS ZERO WHEN */
-/*            THERE CAN BE NO MISSING VALUES; WHEN THERE CAN BE MISSING */
-/*            VALUES, THE NUMBER OF BITS MUST BE AT LEAST 1 TO HAVE */
-/*            THE CAPABILITY TO RECOGNIZE THE MISSING VALUE.  HOWEVER, */
-/*            IF ALL VALUES IN A GROUP ARE MISSING, THE NUMBER OF BITS */
-/*            NEEDED IS 0, AND THE UNPACKER RECOGNIZES THIS. */
-/*            ALL VARIABLES ARE INTEGER.  EVEN THOUGH THE GROUPS ARE */
-/*            INITIALLY OF SIZE MINPK OR LARGER, AN ADJUSTMENT BETWEEN */
-/*            TWO GROUPS (THE LOOKBACK PROCEDURE) MAY MAKE A GROUP */
-/*            SMALLER THAN MINPK.  THE CONTROL ON GROUP SIZE IS THAT */
-/*            THE SUM OF THE SIZES OF THE TWO CONSECUTIVE GROUPS, EACH OF */
-/*            SIZE MINPK OR LARGER, IS NOT DECREASED.  WHEN DETERMINING */
-/*            THE NUMBER OF BITS NECESSARY FOR PACKING, THE LARGEST */
-/*            VALUE THAT CAN BE ACCOMMODATED IN, SAY, MBITS, IS */
-/*            2**MBITS-1; THIS LARGEST VALUE (AND THE NEXT SMALLEST */
-/*            VALUE) IS RESERVED FOR THE MISSING VALUE INDICATOR (ONLY) */
-/*            WHEN IS523 NE 0.  IF THE DIMENSION NDG */
-/*            IS NOT LARGE ENOUGH TO HOLD ALL THE GROUPS, THE LOCAL VALUE */
-/*            OF MINPK IS INCREASED BY 50 PERCENT.  THIS IS REPEATED */
-/*            UNTIL NDG WILL SUFFICE.  A DIAGNOSTIC IS PRINTED WHENEVER */
-/*            THIS HAPPENS, WHICH SHOULD BE VERY RARELY.  IF IT HAPPENS */
-/*            OFTEN, NDG IN SUBROUTINE PACK SHOULD BE INCREASED AND */
-/*            A CORRESPONDING INCREASE IN SUBROUTINE UNPACK MADE. */
-/*            CONSIDERABLE CODE IS PROVIDED SO THAT NO MORE CHECKING */
-/*            FOR MISSING VALUES WITHIN LOOPS IS DONE THAN NECESSARY; */
-/*            THE ADDED EFFICIENCY OF THIS IS RELATIVELY MINOR, */
-/*            BUT DOES NO HARM.  FOR GRIB2, THE REFERENCE VALUE FOR */
-/*            THE LENGTH OF GROUPS IN NOV( ) AND FOR THE NUMBER OF */
-/*            BITS NECESSARY TO PACK GROUP VALUES ARE DETERMINED, */
-/*            AND SUBTRACTED BEFORE JBIT AND KBIT ARE DETERMINED. */
-
-/*            WHEN 1 OR MORE GROUPS ARE LARGE COMPARED TO THE OTHERS, */
-/*            THE WIDTH OF ALL GROUPS MUST BE AS LARGE AS THE LARGEST. */
-/*            A SUBROUTINE REDUCE BREAKS UP LARGE GROUPS INTO 2 OR */
-/*            MORE TO REDUCE TOTAL BITS REQUIRED.  IF REDUCE SHOULD */
-/*            ABORT, PACK_GP WILL BE EXECUTED AGAIN WITHOUT THE CALL */
-/*            TO REDUCE. */
-
-/*        DATA SET USE */
-/*           KFILDO - UNIT NUMBER FOR OUTPUT (PRINT) FILE. (OUTPUT) */
-
-/*        VARIABLES IN CALL SEQUENCE */
-/*              KFILDO = UNIT NUMBER FOR OUTPUT (PRINT) FILE.  (INPUT) */
-/*               IC( ) = ARRAY TO HOLD DATA FOR PACKING.  THE VALUES */
-/*                       DO NOT HAVE TO BE POSITIVE AT THIS POINT, BUT */
-/*                       MUST BE IN THE RANGE -2**30 TO +2**30 (THE */
-/*                       THE VALUE OF MALLOW).  THESE INTEGER VALUES */
-/*                       WILL BE RETAINED EXACTLY THROUGH PACKING AND */
-/*                       UNPACKING.  (INPUT) */
-/*                 NXY = NUMBER OF VALUES IN IC( ).  ALSO TREATED */
-/*                       AS ITS DIMENSION.  (INPUT) */
-/*              IS523  = missing value management */
-/*                       0=data contains no missing values */
-/*                       1=data contains Primary missing values */
-/*                       2=data contains Primary and secondary missing values */
-/*                       (INPUT) */
-/*               MINPK = THE MINIMUM SIZE OF EACH GROUP, EXCEPT POSSIBLY */
-/*                       THE LAST ONE.  (INPUT) */
-/*                 INC = THE NUMBER OF VALUES TO ADD TO AN ALREADY */
-/*                       EXISTING GROUP IN DETERMINING WHETHER OR NOT */
-/*                       TO START A NEW GROUP.  IDEALLY, THIS WOULD BE */
-/*                       1, BUT EACH TIME INC VALUES ARE ATTEMPTED, THE */
-/*                       MAX AND MIN OF THE NEXT MINPK VALUES MUST BE */
-/*                       FOUND.  THIS IS "A LOOP WITHIN A LOOP," AND */
-/*                       A SLIGHTLY LARGER VALUE MAY GIVE ABOUT AS GOOD */
-/*                       RESULTS WITH SLIGHTLY LESS COMPUTATIONAL TIME. */
-/*                       IF INC IS LE 0, 1 IS USED, AND A DIAGNOSTIC IS */
-/*                       OUTPUT.  NOTE:  IT IS EXPECTED THAT INC WILL */
-/*                       EQUAL 1.  THE CODE USES INC PRIMARILY IN THE */
-/*                       LOOPS STARTING AT STATEMENT 180.  IF INC */
-/*                       WERE 1, THERE WOULD NOT NEED TO BE LOOPS */
-/*                       AS SUCH.  HOWEVER, KINC (THE LOCAL VALUE OF */
-/*                       INC) IS SET GE 1 WHEN NEAR THE END OF THE DATA */
-/*                       TO FORESTALL A VERY SMALL GROUP AT THE END. */
-/*                       (INPUT) */
-/*               MISSP = WHEN MISSING POINTS CAN BE PRESENT IN THE DATA, */
-/*                       THEY WILL HAVE THE VALUE MISSP OR MISSS. */
-/*                       MISSP IS THE PRIMARY MISSING VALUE AND  MISSS */
-/*                       IS THE SECONDARY MISSING VALUE .  THESE MUST */
-/*                       NOT BE VALUES THAT WOULD OCCUR WITH SUBTRACTING */
-/*                       THE MINIMUM (REFERENCE) VALUE OR SCALING. */
-/*                       FOR EXAMPLE, MISSP = 0 WOULD NOT BE ADVISABLE. */
-/*                       (INPUT) */
-/*               MISSS = SECONDARY MISSING VALUE INDICATOR (SEE MISSP). */
-/*                       (INPUT) */
-/*             JMIN(J) = THE MINIMUM OF EACH GROUP (J=1,LX).  (OUTPUT) */
-/*             JMAX(J) = THE MAXIMUM OF EACH GROUP (J=1,LX).  THIS IS */
-/*                       NOT REALLY NEEDED, BUT SINCE THE MAX OF EACH */
-/*                       GROUP MUST BE FOUND, SAVING IT HERE IS CHEAP */
-/*                       IN CASE THE USER WANTS IT.  (OUTPUT) */
-/*             LBIT(J) = THE NUMBER OF BITS NECESSARY TO PACK EACH GROUP */
-/*                       (J=1,LX).  IT IS ASSUMED THE MINIMUM OF EACH */
-/*                       GROUP WILL BE REMOVED BEFORE PACKING, AND THE */
-/*                       VALUES TO PACK WILL, THEREFORE, ALL BE POSITIVE. */
-/*                       HOWEVER, IC( ) DOES NOT NECESSARILY CONTAIN */
-/*                       ALL POSITIVE VALUES.  IF THE OVERALL MINIMUM */
-/*                       HAS BEEN REMOVED (THE USUAL CASE), THEN IC( ) */
-/*                       WILL CONTAIN ONLY POSITIVE VALUES.  (OUTPUT) */
-/*              NOV(J) = THE NUMBER OF VALUES IN EACH GROUP (J=1,LX). */
-/*                       (OUTPUT) */
-/*                 NDG = THE DIMENSION OF JMIN( ), JMAX( ), LBIT( ), AND */
-/*                       NOV( ).  (INPUT) */
-/*                  LX = THE NUMBER OF GROUPS DETERMINED.  (OUTPUT) */
-/*                IBIT = THE NUMBER OF BITS NECESSARY TO PACK THE JMIN(J) */
-/*                       VALUES, J=1,LX.  (OUTPUT) */
-/*                JBIT = THE NUMBER OF BITS NECESSARY TO PACK THE LBIT(J) */
-/*                       VALUES, J=1,LX.  (OUTPUT) */
-/*                KBIT = THE NUMBER OF BITS NECESSARY TO PACK THE NOV(J) */
-/*                       VALUES, J=1,LX.  (OUTPUT) */
-/*              NOVREF = REFERENCE VALUE FOR NOV( ).  (OUTPUT) */
-/*             LBITREF = REFERENCE VALUE FOR LBIT( ).  (OUTPUT) */
-/*                 IER = ERROR RETURN. */
-/*                       706 = VALUE WILL NOT PACK IN 30 BITS--FATAL */
-/*                       714 = ERROR IN REDUCE--NON-FATAL */
-/*                       715 = NGP NOT LARGE ENOUGH IN REDUCE--NON-FATAL */
-/*                       716 = MINPK INCEASED--NON-FATAL */
-/*                       717 = INC SET = 1--NON-FATAL */
-/*                       (OUTPUT) */
-/*                   * = ALTERNATE RETURN WHEN IER NE 0 AND FATAL ERROR. */
-
-/*        INTERNAL VARIABLES */
-/*               CFEED = CONTAINS THE CHARACTER REPRESENTATION */
-/*                       OF A PRINTER FORM FEED. */
-/*               IFEED = CONTAINS THE INTEGER VALUE OF A PRINTER */
-/*                       FORM FEED. */
-/*                KINC = WORKING COPY OF INC.  MAY BE MODIFIED. */
-/*                MINA = MINIMUM VALUE IN GROUP A. */
-/*                MAXA = MAXIMUM VALUE IN GROUP A. */
-/*               NENDA = THE PLACE IN IC( ) WHERE GROUP A ENDS. */
-/*              KSTART = THE PLACE IN IC( ) WHERE GROUP A STARTS. */
-/*               IBITA = NUMBER OF BITS NEEDED TO HOLD VALUES IN GROUP A. */
-/*                MINB = MINIMUM VALUE IN GROUP B. */
-/*                MAXB = MAXIMUM VALUE IN GROUP B. */
-/*               NENDB = THE PLACE IN IC( ) WHERE GROUP B ENDS. */
-/*               IBITB = NUMBER OF BITS NEEDED TO HOLD VALUES IN GROUP B. */
-/*                MINC = MINIMUM VALUE IN GROUP C. */
-/*                MAXC = MAXIMUM VALUE IN GROUP C. */
-/*              KTOTAL = COUNT OF NUMBER OF VALUES IN IC( ) PROCESSED. */
-/*               NOUNT = NUMBER OF VALUES ADDED TO GROUP A. */
-/*               LMISS = 0 WHEN IS523 = 0.  WHEN PACKING INTO A */
-/*                       SPECIFIC NUMBER OF BITS, SAY MBITS, */
-/*                       THE MAXIMUM VALUE THAT CAN BE HANDLED IS */
-/*                       2**MBITS-1.  WHEN IS523 = 1, INDICATING */
-/*                       PRIMARY MISSING VALUES, THIS MAXIMUM VALUE */
-/*                       IS RESERVED TO HOLD THE PRIMARY MISSING VALUE */
-/*                       INDICATOR AND LMISS = 1.  WHEN IS523 = 2, */
-/*                       THE VALUE JUST BELOW THE MAXIMUM (I.E., */
-/*                       2**MBITS-2) IS RESERVED TO HOLD THE SECONDARY */
-/*                       MISSING VALUE INDICATOR AND LMISS = 2. */
-/*              LMINPK = LOCAL VALUE OF MINPK.  THIS WILL BE ADJUSTED */
-/*                       UPWARD WHENEVER NDG IS NOT LARGE ENOUGH TO HOLD */
-/*                       ALL THE GROUPS. */
-/*              MALLOW = THE LARGEST ALLOWABLE VALUE FOR PACKING. */
-/*              MISLLA = SET TO 1 WHEN ALL VALUES IN GROUP A ARE MISSING. */
-/*                       THIS IS USED TO DISTINGUISH BETWEEN A REAL */
-/*                       MINIMUM WHEN ALL VALUES ARE NOT MISSING */
-/*                       AND A MINIMUM THAT HAS BEEN SET TO ZERO WHEN */
-/*                       ALL VALUES ARE MISSING.  0 OTHERWISE. */
-/*                       NOTE THAT THIS DOES NOT DISTINGUISH BETWEEN */
-/*                       PRIMARY AND SECONDARY MISSINGS WHEN SECONDARY */
-/*                       MISSINGS ARE PRESENT.  THIS MEANS THAT */
-/*                       LBIT( ) WILL NOT BE ZERO WITH THE RESULTING */
-/*                       COMPRESSION EFFICIENCY WHEN SECONDARY MISSINGS */
-/*                       ARE PRESENT.  ALSO NOTE THAT A CHECK HAS BEEN */
-/*                       MADE EARLIER TO DETERMINE THAT SECONDARY */
-/*                       MISSINGS ARE REALLY THERE. */
-/*              MISLLB = SET TO 1 WHEN ALL VALUES IN GROUP B ARE MISSING. */
-/*                       THIS IS USED TO DISTINGUISH BETWEEN A REAL */
-/*                       MINIMUM WHEN ALL VALUES ARE NOT MISSING */
-/*                       AND A MINIMUM THAT HAS BEEN SET TO ZERO WHEN */
-/*                       ALL VALUES ARE MISSING.  0 OTHERWISE. */
-/*              MISLLC = PERFORMS THE SAME FUNCTION FOR GROUP C THAT */
-/*                       MISLLA AND MISLLB DO FOR GROUPS B AND C, */
-/*                       RESPECTIVELY. */
-/*            IBXX2(J) = AN ARRAY THAT WHEN THIS ROUTINE IS FIRST ENTERED */
-/*                       IS SET TO 2**J, J=0,30. IBXX2(30) = 2**30, WHICH */
-/*                       IS THE LARGEST VALUE PACKABLE, BECAUSE 2**31 */
-/*                       IS LARGER THAN THE INTEGER WORD SIZE. */
-/*              IFIRST = SET BY DATA STATEMENT TO 0.  CHANGED TO 1 ON */
-/*                       FIRST */
-/*                       ENTRY WHEN IBXX2( ) IS FILLED. */
-/*               MINAK = KEEPS TRACK OF THE LOCATION IN IC( ) WHERE THE */
-/*                       MINIMUM VALUE IN GROUP A IS LOCATED. */
-/*               MAXAK = DOES THE SAME AS MINAK, EXCEPT FOR THE MAXIMUM. */
-/*               MINBK = THE SAME AS MINAK FOR GROUP B. */
-/*               MAXBK = THE SAME AS MAXAK FOR GROUP B. */
-/*               MINCK = THE SAME AS MINAK FOR GROUP C. */
-/*               MAXCK = THE SAME AS MAXAK FOR GROUP C. */
-/*                ADDA = KEEPS TRACK WHETHER OR NOT AN ATTEMPT TO ADD */
-/*                       POINTS TO GROUP A WAS MADE.  IF SO, THEN ADDA */
-/*                       KEEPS FROM TRYING TO PUT ONE BACK INTO B. */
-/*                       (LOGICAL) */
-/*              IBITBS = KEEPS CURRENT VALUE IF IBITB SO THAT LOOP */
-/*                       ENDING AT 166 DOESN'T HAVE TO START AT */
-/*                       IBITB = 0 EVERY TIME. */
-/*           MISSLX(J) = MALLOW EXCEPT WHEN A GROUP IS ALL ONE VALUE (AND */
-/*                       LBIT(J) = 0) AND THAT VALUE IS MISSING.  IN */
-/*                       THAT CASE, MISSLX(J) IS MISSP OR MISSS.  THIS */
-/*                       GETS INSERTED INTO JMIN(J) LATER AS THE */
-/*                       MISSING INDICATOR; IT CAN'T BE PUT IN UNTIL */
-/*                       THE END, BECAUSE JMIN( ) IS USED TO CALCULATE */
-/*                       THE MAXIMUM NUMBER OF BITS (IBITS) NEEDED TO */
-/*                       PACK JMIN( ). */
-/*        1         2         3         4         5         6         7 X */
-
-/*        NON SYSTEM SUBROUTINES CALLED */
-/*           NONE */
-
-
-
-/*        MISSLX( ) was AN AUTOMATIC ARRAY. */
-    misslx = (integer *)calloc(*ndg,sizeof(integer));
-
-
-    /* Parameter adjustments */
-    --ic;
-    --nov;
-    --lbit;
-    --jmax;
-    --jmin;
-
-    /* Function Body */
-
-    *ier = 0;
-    iersav = 0;
-/*     CALL TIMPR(KFILDO,KFILDO,'START PACK_GP        ') */
-    *(unsigned char *)cfeed = (char) ifeed;
-
-    ired = 0;
-/*        IRED IS A FLAG.  WHEN ZERO, REDUCE WILL BE CALLED. */
-/*        IF REDUCE ABORTS, IRED = 1 AND IS NOT CALLED.  IN */
-/*        THIS CASE PACK_GP EXECUTES AGAIN EXCEPT FOR REDUCE. */
-
-    if (*inc <= 0) {
-	iersav = 717;
-/*        WRITE(KFILDO,101)INC */
-/* 101     FORMAT(/' ****INC ='I8,' NOT CORRECT IN PACK_GP.  1 IS USED.') */
-    }
-
-/*        THERE WILL BE A RESTART OF PACK_GP IF SUBROUTINE REDUCE */
-/*        ABORTS.  THIS SHOULD NOT HAPPEN, BUT IF IT DOES, PACK_GP */
-/*        WILL COMPLETE WITHOUT SUBROUTINE REDUCE.  A NON FATAL */
-/*        DIAGNOSTIC RETURN IS PROVIDED. */
-
-L102:
-    /*kinc = max(*inc,1);*/
-    kinc = (*inc > 1) ? *inc : 1;
-    lminpk = *minpk;
-
-/*         CALCULATE THE POWERS OF 2 THE FIRST TIME ENTERED. */
-
-    if (ifirst == 0) {
-	ifirst = 1;
-	ibxx2[0] = 1;
-
-	for (j = 1; j <= 30; ++j) {
-	    ibxx2[j] = ibxx2[j - 1] << 1;
-/* L104: */
-	}
-
-    }
-
-/*        THERE WILL BE A RESTART AT 105 IS NDG IS NOT LARGE ENOUGH. */
-/*        A NON FATAL DIAGNOSTIC RETURN IS PROVIDED. */
-
-L105:
-    kstart = 1;
-    ktotal = 0;
-    *lx = 0;
-    adda = FALSE_;
-    lmiss = 0;
-    if (*is523 == 1) {
-	lmiss = 1;
-    }
-    if (*is523 == 2) {
-	lmiss = 2;
-    }
-
-/*        ************************************* */
-
-/*        THIS SECTION COMPUTES STATISTICS FOR GROUP A.  GROUP A IS */
-/*        A GROUP OF SIZE LMINPK. */
-
-/*        ************************************* */
-
-    ibita = 0;
-    mina = mallow;
-    maxa = -mallow;
-    minak = mallow;
-    maxak = -mallow;
-
-/*        FIND THE MIN AND MAX OF GROUP A.  THIS WILL INITIALLY BE OF */
-/*        SIZE LMINPK (IF THERE ARE STILL LMINPK VALUES IN IC( )), BUT */
-/*        WILL INCREASE IN SIZE IN INCREMENTS OF INC UNTIL A NEW */
-/*        GROUP IS STARTED.  THE DEFINITION OF GROUP A IS DONE HERE */
-/*        ONLY ONCE (UPON INITIAL ENTRY), BECAUSE A GROUP B CAN ALWAYS */
-/*        BECOME A NEW GROUP A AFTER A IS PACKED, EXCEPT IF LMINPK */
-/*        HAS TO BE INCREASED BECAUSE NDG IS TOO SMALL.  THEREFORE, */
-/*        THE SEPARATE LOOPS FOR MISSING AND NON-MISSING HERE BUYS */
-/*        ALMOST NOTHING. */
-
-/* Computing MIN */
-    i__1 = kstart + lminpk - 1;
-    /*nenda = min(i__1,*nxy);*/
-    nenda = (i__1 < *nxy) ? i__1 : *nxy;
-    if (*nxy - nenda <= lminpk / 2) {
-	nenda = *nxy;
-    }
-/*        ABOVE STATEMENT GUARANTEES THE LAST GROUP IS GT LMINPK/2 BY */
-/*        MAKING THE ACTUAL GROUP LARGER.  IF A PROVISION LIKE THIS IS */
-/*        NOT INCLUDED, THERE WILL MANY TIMES BE A VERY SMALL GROUP */
-/*        AT THE END.  USE SEPARATE LOOPS FOR MISSING AND NO MISSING */
-/*        VALUES FOR EFFICIENCY. */
-
-/*        DETERMINE WHETHER THERE IS A LONG STRING OF THE SAME VALUE */
-/*        UNLESS NENDA = NXY.  THIS MAY ALLOW A LARGE GROUP A TO */
-/*        START WITH, AS WITH MISSING VALUES.   SEPARATE LOOPS FOR */
-/*        MISSING OPTIONS.  THIS SECTION IS ONLY EXECUTED ONCE, */
-/*        IN DETERMINING THE FIRST GROUP.  IT HELPS FOR AN ARRAY */
-/*        OF MOSTLY MISSING VALUES OR OF ONE VALUE, SUCH AS */
-/*        RADAR OR PRECIP DATA. */
-
-    if (nenda != *nxy && ic[kstart] == ic[kstart + 1]) {
-/*           NO NEED TO EXECUTE IF FIRST TWO VALUES ARE NOT EQUAL. */
-
-	if (*is523 == 0) {
-/*              THIS LOOP IS FOR NO MISSING VALUES. */
-
-	    i__1 = *nxy;
-	    for (k = kstart + 1; k <= i__1; ++k) {
-
-		if (ic[k] != ic[kstart]) {
-/* Computing MAX */
-		    i__2 = nenda, i__3 = k - 1;
-		    /*nenda = max(i__2,i__3);*/
-		    nenda = (i__2 > i__3) ? i__2 : i__3;
-		    goto L114;
-		}
-
-/* L111: */
-	    }
-
-	    nenda = *nxy;
-/*              FALL THROUGH THE LOOP MEANS ALL VALUES ARE THE SAME. */
-
-	} else if (*is523 == 1) {
-/*              THIS LOOP IS FOR PRIMARY MISSING VALUES ONLY. */
-
-	    i__1 = *nxy;
-	    for (k = kstart + 1; k <= i__1; ++k) {
-
-		if (ic[k] != *missp) {
-
-		    if (ic[k] != ic[kstart]) {
-/* Computing MAX */
-			i__2 = nenda, i__3 = k - 1;
-			/*nenda = max(i__2,i__3);*/
-			nenda = (i__2 > i__3) ? i__2 : i__3;
-			goto L114;
-		    }
-
-		}
-
-/* L112: */
-	    }
-
-	    nenda = *nxy;
-/*              FALL THROUGH THE LOOP MEANS ALL VALUES ARE THE SAME. */
-
-	} else {
-/*              THIS LOOP IS FOR PRIMARY AND SECONDARY MISSING VALUES. */
-
-	    i__1 = *nxy;
-	    for (k = kstart + 1; k <= i__1; ++k) {
-
-		if (ic[k] != *missp && ic[k] != *misss) {
-
-		    if (ic[k] != ic[kstart]) {
-/* Computing MAX */
-			i__2 = nenda, i__3 = k - 1;
-			/*nenda = max(i__2,i__3);*/
-			nenda = (i__2 > i__3) ? i__2 : i__3;
-			goto L114;
-		    }
-
-		}
-
-/* L113: */
-	    }
-
-	    nenda = *nxy;
-/*              FALL THROUGH THE LOOP MEANS ALL VALUES ARE THE SAME. */
-	}
-
-    }
-
-L114:
-    if (*is523 == 0) {
-
-	i__1 = nenda;
-	for (k = kstart; k <= i__1; ++k) {
-	    if (ic[k] < mina) {
-		mina = ic[k];
-		minak = k;
-	    }
-	    if (ic[k] > maxa) {
-		maxa = ic[k];
-		maxak = k;
-	    }
-/* L115: */
-	}
-
-    } else if (*is523 == 1) {
-
-	i__1 = nenda;
-	for (k = kstart; k <= i__1; ++k) {
-	    if (ic[k] == *missp) {
-		goto L117;
-	    }
-	    if (ic[k] < mina) {
-		mina = ic[k];
-		minak = k;
-	    }
-	    if (ic[k] > maxa) {
-		maxa = ic[k];
-		maxak = k;
-	    }
-L117:
-	    ;
-	}
-
-    } else {
-
-	i__1 = nenda;
-	for (k = kstart; k <= i__1; ++k) {
-	    if (ic[k] == *missp || ic[k] == *misss) {
-		goto L120;
-	    }
-	    if (ic[k] < mina) {
-		mina = ic[k];
-		minak = k;
-	    }
-	    if (ic[k] > maxa) {
-		maxa = ic[k];
-		maxak = k;
-	    }
-L120:
-	    ;
-	}
-
-    }
-
-    kounta = nenda - kstart + 1;
-
-/*        INCREMENT KTOTAL AND FIND THE BITS NEEDED TO PACK THE A GROUP. */
-
-    ktotal += kounta;
-    mislla = 0;
-    if (mina != mallow) {
-	goto L125;
-    }
-/*        ALL MISSING VALUES MUST BE ACCOMMODATED. */
-    mina = 0;
-    maxa = 0;
-    mislla = 1;
-    ibitb = 0;
-    if (*is523 != 2) {
-	goto L130;
-    }
-/*        WHEN ALL VALUES ARE MISSING AND THERE ARE NO */
-/*        SECONDARY MISSING VALUES, IBITA = 0. */
-/*        OTHERWISE, IBITA MUST BE CALCULATED. */
-
-L125:
-    itest = maxa - mina + lmiss;
-
-    for (ibita = 0; ibita <= 30; ++ibita) {
-	if (itest < ibxx2[ibita]) {
-	    goto L130;
-	}
-/* ***        THIS TEST IS THE SAME AS: */
-/* ***     IF(MAXA-MINA.LT.IBXX2(IBITA)-LMISS)GO TO 130 */
-/* L126: */
-    }
-
-/*     WRITE(KFILDO,127)MAXA,MINA */
-/* 127  FORMAT(' ****ERROR IN PACK_GP.  VALUE WILL NOT PACK IN 30 BITS.', */
-/*    1       '  MAXA ='I13,'  MINA ='I13,'.  ERROR AT 127.') */
-    *ier = 706;
-    goto L900;
-
-L130:
-
-/* ***D     WRITE(KFILDO,131)KOUNTA,KTOTAL,MINA,MAXA,IBITA,MISLLA */
-/* ***D131  FORMAT(' AT 130, KOUNTA ='I8,'  KTOTAL ='I8,'  MINA ='I8, */
-/* ***D    1       '  MAXA ='I8,'  IBITA ='I3,'  MISLLA ='I3) */
-
-L133:
-    if (ktotal >= *nxy) {
-	goto L200;
-    }
-
-/*        ************************************* */
-
-/*        THIS SECTION COMPUTES STATISTICS FOR GROUP B.  GROUP B IS A */
-/*        GROUP OF SIZE LMINPK IMMEDIATELY FOLLOWING GROUP A. */
-
-/*        ************************************* */
-
-L140:
-    minb = mallow;
-    maxb = -mallow;
-    minbk = mallow;
-    maxbk = -mallow;
-    ibitbs = 0;
-    mstart = ktotal + 1;
-
-/*        DETERMINE WHETHER THERE IS A LONG STRING OF THE SAME VALUE. */
-/*        THIS WORKS WHEN THERE ARE NO MISSING VALUES. */
-
-    nendb = 1;
-
-    if (mstart < *nxy) {
-
-	if (*is523 == 0) {
-/*              THIS LOOP IS FOR NO MISSING VALUES. */
-
-	    i__1 = *nxy;
-	    for (k = mstart + 1; k <= i__1; ++k) {
-
-		if (ic[k] != ic[mstart]) {
-		    nendb = k - 1;
-		    goto L150;
-		}
-
-/* L145: */
-	    }
-
-	    nendb = *nxy;
-/*              FALL THROUGH THE LOOP MEANS ALL REMAINING VALUES */
-/*              ARE THE SAME. */
-	}
-
-    }
-
-L150:
-/* Computing MAX */
-/* Computing MIN */
-    i__3 = ktotal + lminpk;
-    /*i__1 = nendb, i__2 = min(i__3,*nxy);*/
-    i__1 = nendb, i__2 = (i__3 < *nxy) ? i__3 : *nxy;
-    /*nendb = max(i__1,i__2);*/
-    nendb = (i__1 > i__2) ? i__1 : i__2;
-/* **** 150  NENDB=MIN(KTOTAL+LMINPK,NXY) */
-
-    if (*nxy - nendb <= lminpk / 2) {
-	nendb = *nxy;
-    }
-/*        ABOVE STATEMENT GUARANTEES THE LAST GROUP IS GT LMINPK/2 BY */
-/*        MAKING THE ACTUAL GROUP LARGER.  IF A PROVISION LIKE THIS IS */
-/*        NOT INCLUDED, THERE WILL MANY TIMES BE A VERY SMALL GROUP */
-/*        AT THE END.  USE SEPARATE LOOPS FOR MISSING AND NO MISSING */
-
-/*        USE SEPARATE LOOPS FOR MISSING AND NO MISSING VALUES */
-/*        FOR EFFICIENCY. */
-
-    if (*is523 == 0) {
-
-	i__1 = nendb;
-	for (k = mstart; k <= i__1; ++k) {
-	    if (ic[k] <= minb) {
-		minb = ic[k];
-/*              NOTE LE, NOT LT.  LT COULD BE USED BUT THEN A */
-/*              RECOMPUTE OVER THE WHOLE GROUP WOULD BE NEEDED */
-/*              MORE OFTEN.  SAME REASONING FOR GE AND OTHER */
-/*              LOOPS BELOW. */
-		minbk = k;
-	    }
-	    if (ic[k] >= maxb) {
-		maxb = ic[k];
-		maxbk = k;
-	    }
-/* L155: */
-	}
-
-    } else if (*is523 == 1) {
-
-	i__1 = nendb;
-	for (k = mstart; k <= i__1; ++k) {
-	    if (ic[k] == *missp) {
-		goto L157;
-	    }
-	    if (ic[k] <= minb) {
-		minb = ic[k];
-		minbk = k;
-	    }
-	    if (ic[k] >= maxb) {
-		maxb = ic[k];
-		maxbk = k;
-	    }
-L157:
-	    ;
-	}
-
-    } else {
-
-	i__1 = nendb;
-	for (k = mstart; k <= i__1; ++k) {
-	    if (ic[k] == *missp || ic[k] == *misss) {
-		goto L160;
-	    }
-	    if (ic[k] <= minb) {
-		minb = ic[k];
-		minbk = k;
-	    }
-	    if (ic[k] >= maxb) {
-		maxb = ic[k];
-		maxbk = k;
-	    }
-L160:
-	    ;
-	}
-
-    }
-
-    kountb = nendb - ktotal;
-    misllb = 0;
-    if (minb != mallow) {
-	goto L165;
-    }
-/*        ALL MISSING VALUES MUST BE ACCOMMODATED. */
-    minb = 0;
-    maxb = 0;
-    misllb = 1;
-    ibitb = 0;
-
-    if (*is523 != 2) {
-	goto L170;
-    }
-/*        WHEN ALL VALUES ARE MISSING AND THERE ARE NO SECONDARY */
-/*        MISSING VALUES, IBITB = 0.  OTHERWISE, IBITB MUST BE */
-/*        CALCULATED. */
-
-L165:
-    for (ibitb = ibitbs; ibitb <= 30; ++ibitb) {
-	if (maxb - minb < ibxx2[ibitb] - lmiss) {
-	    goto L170;
-	}
-/* L166: */
-    }
-
-/*     WRITE(KFILDO,167)MAXB,MINB */
-/* 167  FORMAT(' ****ERROR IN PACK_GP.  VALUE WILL NOT PACK IN 30 BITS.', */
-/*    1       '  MAXB ='I13,'  MINB ='I13,'.  ERROR AT 167.') */
-    *ier = 706;
-    goto L900;
-
-/*        COMPARE THE BITS NEEDED TO PACK GROUP B WITH THOSE NEEDED */
-/*        TO PACK GROUP A.  IF IBITB GE IBITA, TRY TO ADD TO GROUP A. */
-/*        IF NOT, TRY TO ADD A'S POINTS TO B, UNLESS ADDITION TO A */
-/*        HAS BEEN DONE.  THIS LATTER IS CONTROLLED WITH ADDA. */
-
-L170:
-
-/* ***D     WRITE(KFILDO,171)KOUNTA,KTOTAL,MINA,MAXA,IBITA,MISLLA, */
-/* ***D    1                               MINB,MAXB,IBITB,MISLLB */
-/* ***D171  FORMAT(' AT 171, KOUNTA ='I8,'  KTOTAL ='I8,'  MINA ='I8, */
-/* ***D    1       '  MAXA ='I8,'  IBITA ='I3,'  MISLLA ='I3, */
-/* ***D    2       '  MINB ='I8,'  MAXB ='I8,'  IBITB ='I3,'  MISLLB ='I3) */
-
-    if (ibitb >= ibita) {
-	goto L180;
-    }
-    if (adda) {
-	goto L200;
-    }
-
-/*        ************************************* */
-
-/*        GROUP B REQUIRES LESS BITS THAN GROUP A.  PUT AS MANY OF A'S */
-/*        POINTS INTO B AS POSSIBLE WITHOUT EXCEEDING THE NUMBER OF */
-/*        BITS NECESSARY TO PACK GROUP B. */
-
-/*        ************************************* */
-
-    kounts = kounta;
-/*        KOUNTA REFERS TO THE PRESENT GROUP A. */
-    mintst = minb;
-    maxtst = maxb;
-    mintstk = minbk;
-    maxtstk = maxbk;
-
-/*        USE SEPARATE LOOPS FOR MISSING AND NO MISSING VALUES */
-/*        FOR EFFICIENCY. */
-
-    if (*is523 == 0) {
-
-	i__1 = kstart;
-	for (k = ktotal; k >= i__1; --k) {
-/*           START WITH THE END OF THE GROUP AND WORK BACKWARDS. */
-	    if (ic[k] < minb) {
-		mintst = ic[k];
-		mintstk = k;
-	    } else if (ic[k] > maxb) {
-		maxtst = ic[k];
-		maxtstk = k;
-	    }
-	    if (maxtst - mintst >= ibxx2[ibitb]) {
-		goto L174;
-	    }
-/*           NOTE THAT FOR THIS LOOP, LMISS = 0. */
-	    minb = mintst;
-	    maxb = maxtst;
-	    minbk = mintstk;
-	    maxbk = maxtstk;
-	    --kounta;
-/*           THERE IS ONE LESS POINT NOW IN A. */
-/* L1715: */
-	}
-
-    } else if (*is523 == 1) {
-
-	i__1 = kstart;
-	for (k = ktotal; k >= i__1; --k) {
-/*           START WITH THE END OF THE GROUP AND WORK BACKWARDS. */
-	    if (ic[k] == *missp) {
-		goto L1718;
-	    }
-	    if (ic[k] < minb) {
-		mintst = ic[k];
-		mintstk = k;
-	    } else if (ic[k] > maxb) {
-		maxtst = ic[k];
-		maxtstk = k;
-	    }
-	    if (maxtst - mintst >= ibxx2[ibitb] - lmiss) {
-		goto L174;
-	    }
-/*           FOR THIS LOOP, LMISS = 1. */
-	    minb = mintst;
-	    maxb = maxtst;
-	    minbk = mintstk;
-	    maxbk = maxtstk;
-	    misllb = 0;
-/*           WHEN THE POINT IS NON MISSING, MISLLB SET = 0. */
-L1718:
-	    --kounta;
-/*           THERE IS ONE LESS POINT NOW IN A. */
-/* L1719: */
-	}
-
-    } else {
-
-	i__1 = kstart;
-	for (k = ktotal; k >= i__1; --k) {
-/*           START WITH THE END OF THE GROUP AND WORK BACKWARDS. */
-	    if (ic[k] == *missp || ic[k] == *misss) {
-		goto L1729;
-	    }
-	    if (ic[k] < minb) {
-		mintst = ic[k];
-		mintstk = k;
-	    } else if (ic[k] > maxb) {
-		maxtst = ic[k];
-		maxtstk = k;
-	    }
-	    if (maxtst - mintst >= ibxx2[ibitb] - lmiss) {
-		goto L174;
-	    }
-/*           FOR THIS LOOP, LMISS = 2. */
-	    minb = mintst;
-	    maxb = maxtst;
-	    minbk = mintstk;
-	    maxbk = maxtstk;
-	    misllb = 0;
-/*           WHEN THE POINT IS NON MISSING, MISLLB SET = 0. */
-L1729:
-	    --kounta;
-/*           THERE IS ONE LESS POINT NOW IN A. */
-/* L173: */
-	}
-
-    }
-
-/*        AT THIS POINT, KOUNTA CONTAINS THE NUMBER OF POINTS TO CLOSE */
-/*        OUT GROUP A WITH.  GROUP B NOW STARTS WITH KSTART+KOUNTA AND */
-/*        ENDS WITH NENDB.  MINB AND MAXB HAVE BEEN ADJUSTED AS */
-/*        NECESSARY TO REFLECT GROUP B (EVEN THOUGH THE NUMBER OF BITS */
-/*        NEEDED TO PACK GROUP B HAVE NOT INCREASED, THE END POINTS */
-/*        OF THE RANGE MAY HAVE). */
-
-L174:
-    if (kounta == kounts) {
-	goto L200;
-    }
-/*        ON TRANSFER, GROUP A WAS NOT CHANGED.  CLOSE IT OUT. */
-
-/*        ONE OR MORE POINTS WERE TAKEN OUT OF A.  RANGE AND IBITA */
-/*        MAY HAVE TO BE RECOMPUTED; IBITA COULD BE LESS THAN */
-/*        ORIGINALLY COMPUTED.  IN FACT, GROUP A CAN NOW CONTAIN */
-/*        ONLY ONE POINT AND BE PACKED WITH ZERO BITS */
-/*        (UNLESS MISSS NE 0). */
-
-    nouta = kounts - kounta;
-    ktotal -= nouta;
-    kountb += nouta;
-    if (nenda - nouta > minak && nenda - nouta > maxak) {
-	goto L200;
-    }
-/*        WHEN THE ABOVE TEST IS MET, THE MIN AND MAX OF THE */
-/*        CURRENT GROUP A WERE WITHIN THE OLD GROUP A, SO THE */
-/*        RANGE AND IBITA DO NOT NEED TO BE RECOMPUTED. */
-/*        NOTE THAT MINAK AND MAXAK ARE NO LONGER NEEDED. */
-    ibita = 0;
-    mina = mallow;
-    maxa = -mallow;
-
-/*        USE SEPARATE LOOPS FOR MISSING AND NO MISSING VALUES */
-/*        FOR EFFICIENCY. */
-
-    if (*is523 == 0) {
-
-	i__1 = nenda - nouta;
-	for (k = kstart; k <= i__1; ++k) {
-	    if (ic[k] < mina) {
-		mina = ic[k];
-	    }
-	    if (ic[k] > maxa) {
-		maxa = ic[k];
-	    }
-/* L1742: */
-	}
-
-    } else if (*is523 == 1) {
-
-	i__1 = nenda - nouta;
-	for (k = kstart; k <= i__1; ++k) {
-	    if (ic[k] == *missp) {
-		goto L1744;
-	    }
-	    if (ic[k] < mina) {
-		mina = ic[k];
-	    }
-	    if (ic[k] > maxa) {
-		maxa = ic[k];
-	    }
-L1744:
-	    ;
-	}
-
-    } else {
-
-	i__1 = nenda - nouta;
-	for (k = kstart; k <= i__1; ++k) {
-	    if (ic[k] == *missp || ic[k] == *misss) {
-		goto L175;
-	    }
-	    if (ic[k] < mina) {
-		mina = ic[k];
-	    }
-	    if (ic[k] > maxa) {
-		maxa = ic[k];
-	    }
-L175:
-	    ;
-	}
-
-    }
-
-    mislla = 0;
-    if (mina != mallow) {
-	goto L1750;
-    }
-/*        ALL MISSING VALUES MUST BE ACCOMMODATED. */
-    mina = 0;
-    maxa = 0;
-    mislla = 1;
-    if (*is523 != 2) {
-	goto L177;
-    }
-/*        WHEN ALL VALUES ARE MISSING AND THERE ARE NO SECONDARY */
-/*        MISSING VALUES IBITA = 0 AS ORIGINALLY SET.  OTHERWISE, */
-/*        IBITA MUST BE CALCULATED. */
-
-L1750:
-    itest = maxa - mina + lmiss;
-
-    for (ibita = 0; ibita <= 30; ++ibita) {
-	if (itest < ibxx2[ibita]) {
-	    goto L177;
-	}
-/* ***        THIS TEST IS THE SAME AS: */
-/* ***         IF(MAXA-MINA.LT.IBXX2(IBITA)-LMISS)GO TO 177 */
-/* L176: */
-    }
-
-/*     WRITE(KFILDO,1760)MAXA,MINA */
-/* 1760 FORMAT(' ****ERROR IN PACK_GP.  VALUE WILL NOT PACK IN 30 BITS.', */
-/*    1       '  MAXA ='I13,'  MINA ='I13,'.  ERROR AT 1760.') */
-    *ier = 706;
-    goto L900;
-
-L177:
-    goto L200;
-
-/*        ************************************* */
-
-/*        AT THIS POINT, GROUP B REQUIRES AS MANY BITS TO PACK AS GROUPA. */
-/*        THEREFORE, TRY TO ADD INC POINTS TO GROUP A WITHOUT INCREASING */
-/*        IBITA.  THIS AUGMENTED GROUP IS CALLED GROUP C. */
-
-/*        ************************************* */
-
-L180:
-    if (mislla == 1) {
-	minc = mallow;
-	minck = mallow;
-	maxc = -mallow;
-	maxck = -mallow;
-    } else {
-	minc = mina;
-	maxc = maxa;
-	minck = minak;
-	maxck = minak;
-    }
-
-    nount = 0;
-    if (*nxy - (ktotal + kinc) <= lminpk / 2) {
-	kinc = *nxy - ktotal;
-    }
-/*        ABOVE STATEMENT CONSTRAINS THE LAST GROUP TO BE NOT LESS THAN */
-/*        LMINPK/2 IN SIZE.  IF A PROVISION LIKE THIS IS NOT INCLUDED, */
-/*        THERE WILL MANY TIMES BE A VERY SMALL GROUP AT THE END. */
-
-/*        USE SEPARATE LOOPS FOR MISSING AND NO MISSING VALUES */
-/*        FOR EFFICIENCY.  SINCE KINC IS USUALLY 1, USING SEPARATE */
-/*        LOOPS HERE DOESN'T BUY MUCH.  A MISSING VALUE WILL ALWAYS */
-/*        TRANSFER BACK TO GROUP A. */
-
-    if (*is523 == 0) {
-
-/* Computing MIN */
-	i__2 = ktotal + kinc;
-	/*i__1 = min(i__2,*nxy);*/
-	i__1 = (i__2 < *nxy) ? i__2 : *nxy;
-	for (k = ktotal + 1; k <= i__1; ++k) {
-	    if (ic[k] < minc) {
-		minc = ic[k];
-		minck = k;
-	    }
-	    if (ic[k] > maxc) {
-		maxc = ic[k];
-		maxck = k;
-	    }
-	    ++nount;
-/* L185: */
-	}
-
-    } else if (*is523 == 1) {
-
-/* Computing MIN */
-	i__2 = ktotal + kinc;
-	/*i__1 = min(i__2,*nxy);*/
-	i__1 = (i__2 < *nxy) ? i__2 : *nxy;
-	for (k = ktotal + 1; k <= i__1; ++k) {
-	    if (ic[k] == *missp) {
-		goto L186;
-	    }
-	    if (ic[k] < minc) {
-		minc = ic[k];
-		minck = k;
-	    }
-	    if (ic[k] > maxc) {
-		maxc = ic[k];
-		maxck = k;
-	    }
-L186:
-	    ++nount;
-/* L187: */
-	}
-
-    } else {
-
-/* Computing MIN */
-	i__2 = ktotal + kinc;
-	/*i__1 = min(i__2,*nxy);*/
-	i__1 = (i__2 < *nxy) ? i__2 : *nxy;
-	for (k = ktotal + 1; k <= i__1; ++k) {
-	    if (ic[k] == *missp || ic[k] == *misss) {
-		goto L189;
-	    }
-	    if (ic[k] < minc) {
-		minc = ic[k];
-		minck = k;
-	    }
-	    if (ic[k] > maxc) {
-		maxc = ic[k];
-		maxck = k;
-	    }
-L189:
-	    ++nount;
-/* L190: */
-	}
-
-    }
-
-/* ***D     WRITE(KFILDO,191)KOUNTA,KTOTAL,MINA,MAXA,IBITA,MISLLA, */
-/* ***D    1   MINC,MAXC,NOUNT,IC(KTOTAL),IC(KTOTAL+1) */
-/* ***D191  FORMAT(' AT 191, KOUNTA ='I8,'  KTOTAL ='I8,'  MINA ='I8, */
-/* ***D    1       '  MAXA ='I8,'  IBITA ='I3,'  MISLLA ='I3, */
-/* ***D    2       '  MINC ='I8,'  MAXC ='I8, */
-/* ***D    3       '  NOUNT ='I5,'  IC(KTOTAL) ='I9,'  IC(KTOTAL+1) =',I9) */
-
-/*        IF THE NUMBER OF BITS NEEDED FOR GROUP C IS GT IBITA, */
-/*        THEN THIS GROUP A IS A GROUP TO PACK. */
-
-    if (minc == mallow) {
-	minc = mina;
-	maxc = maxa;
-	minck = minak;
-	maxck = maxak;
-	misllc = 1;
-	goto L195;
-/*           WHEN THE NEW VALUE(S) ARE MISSING, THEY CAN ALWAYS */
-/*           BE ADDED. */
-
-    } else {
-	misllc = 0;
-    }
-
-    if (maxc - minc >= ibxx2[ibita] - lmiss) {
-	goto L200;
-    }
-
-/*        THE BITS NECESSARY FOR GROUP C HAS NOT INCREASED FROM THE */
-/*        BITS NECESSARY FOR GROUP A.  ADD THIS POINT(S) TO GROUP A. */
-/*        COMPUTE THE NEXT GROUP B, ETC., UNLESS ALL POINTS HAVE BEEN */
-/*        USED. */
-
-L195:
-    ktotal += nount;
-    kounta += nount;
-    mina = minc;
-    maxa = maxc;
-    minak = minck;
-    maxak = maxck;
-    mislla = misllc;
-    adda = TRUE_;
-    if (ktotal >= *nxy) {
-	goto L200;
-    }
-
-    if (minbk > ktotal && maxbk > ktotal) {
-	mstart = nendb + 1;
-/*           THE MAX AND MIN OF GROUP B WERE NOT FROM THE POINTS */
-/*           REMOVED, SO THE WHOLE GROUP DOES NOT HAVE TO BE LOOKED */
-/*           AT TO DETERMINE THE NEW MAX AND MIN.  RATHER START */
-/*           JUST BEYOND THE OLD NENDB. */
-	ibitbs = ibitb;
-	nendb = 1;
-	goto L150;
-    } else {
-	goto L140;
-    }
-
-/*        ************************************* */
-
-/*        GROUP A IS TO BE PACKED.  STORE VALUES IN JMIN( ), JMAX( ), */
-/*        LBIT( ), AND NOV( ). */
-
-/*        ************************************* */
-
-L200:
-    ++(*lx);
-    if (*lx <= *ndg) {
-	goto L205;
-    }
-    lminpk += lminpk / 2;
-/*     WRITE(KFILDO,201)NDG,LMINPK,LX */
-/* 201  FORMAT(' ****NDG ='I5,' NOT LARGE ENOUGH.', */
-/*    1       '  LMINPK IS INCREASED TO 'I3,' FOR THIS FIELD.'/ */
-/*    2       '  LX = 'I10) */
-    iersav = 716;
-    goto L105;
-
-L205:
-    jmin[*lx] = mina;
-    jmax[*lx] = maxa;
-    lbit[*lx] = ibita;
-    nov[*lx] = kounta;
-    kstart = ktotal + 1;
-
-    if (mislla == 0) {
-	misslx[*lx - 1] = mallow;
-    } else {
-	misslx[*lx - 1] = ic[ktotal];
-/*           IC(KTOTAL) WAS THE LAST VALUE PROCESSED.  IF MISLLA NE 0, */
-/*           THIS MUST BE THE MISSING VALUE FOR THIS GROUP. */
-    }
-
-/* ***D     WRITE(KFILDO,206)MISLLA,IC(KTOTAL),KTOTAL,LX,JMIN(LX),JMAX(LX), */
-/* ***D    1                 LBIT(LX),NOV(LX),MISSLX(LX) */
-/* ***D206  FORMAT(' AT 206,  MISLLA ='I2,'  IC(KTOTAL) ='I5,'  KTOTAL ='I8, */
-/* ***D    1       '  LX ='I6,'  JMIN(LX) ='I8,'  JMAX(LX) ='I8, */
-/* ***D    2       '  LBIT(LX) ='I5,'  NOV(LX) ='I8,'  MISSLX(LX) =',I7) */
-
-    if (ktotal >= *nxy) {
-	goto L209;
-    }
-
-/*        THE NEW GROUP A WILL BE THE PREVIOUS GROUP B.  SET LIMITS, ETC. */
-
-    ibita = ibitb;
-    mina = minb;
-    maxa = maxb;
-    minak = minbk;
-    maxak = maxbk;
-    mislla = misllb;
-    nenda = nendb;
-    kounta = kountb;
-    ktotal += kounta;
-    adda = FALSE_;
-    goto L133;
-
-/*        ************************************* */
-
-/*        CALCULATE IBIT, THE NUMBER OF BITS NEEDED TO HOLD THE GROUP */
-/*        MINIMUM VALUES. */
-
-/*        ************************************* */
-
-L209:
-    *ibit = 0;
-
-    i__1 = *lx;
-    for (l = 1; l <= i__1; ++l) {
-L210:
-	if (jmin[l] < ibxx2[*ibit]) {
-	    goto L220;
-	}
-	++(*ibit);
-	goto L210;
-L220:
-	;
-    }
-
-/*        INSERT THE VALUE IN JMIN( ) TO BE USED FOR ALL MISSING */
-/*        VALUES WHEN LBIT( ) = 0.  WHEN SECONDARY MISSING */
-/*        VALUES CAN BE PRESENT, LBIT(L) WILL NOT = 0. */
-
-    if (*is523 == 1) {
-
-	i__1 = *lx;
-	for (l = 1; l <= i__1; ++l) {
-
-	    if (lbit[l] == 0) {
-
-		if (misslx[l - 1] == *missp) {
-		    jmin[l] = ibxx2[*ibit] - 1;
-		}
-
-	    }
-
-/* L226: */
-	}
-
-    }
-
-/*        ************************************* */
-
-/*        CALCULATE JBIT, THE NUMBER OF BITS NEEDED TO HOLD THE BITS */
-/*        NEEDED TO PACK THE VALUES IN THE GROUPS.  BUT FIND AND */
-/*        REMOVE THE REFERENCE VALUE FIRST. */
-
-/*        ************************************* */
-
-/*     WRITE(KFILDO,228)CFEED,LX */
-/* 228  FORMAT(A1,/' *****************************************' */
-/*    1          /' THE GROUP WIDTHS LBIT( ) FOR ',I8,' GROUPS' */
-/*    2          /' *****************************************') */
-/*     WRITE(KFILDO,229) (LBIT(J),J=1,MIN(LX,100)) */
-/* 229  FORMAT(/' '20I6) */
-
-    *lbitref = lbit[1];
-
-    i__1 = *lx;
-    for (k = 1; k <= i__1; ++k) {
-	if (lbit[k] < *lbitref) {
-	    *lbitref = lbit[k];
-	}
-/* L230: */
-    }
-
-    if (*lbitref != 0) {
-
-	i__1 = *lx;
-	for (k = 1; k <= i__1; ++k) {
-	    lbit[k] -= *lbitref;
-/* L240: */
-	}
-
-    }
-
-/*     WRITE(KFILDO,241)CFEED,LBITREF */
-/* 241  FORMAT(A1,/' *****************************************' */
-/*    1          /' THE GROUP WIDTHS LBIT( ) AFTER REMOVING REFERENCE ', */
-/*    2             I8, */
-/*    3          /' *****************************************') */
-/*     WRITE(KFILDO,242) (LBIT(J),J=1,MIN(LX,100)) */
-/* 242  FORMAT(/' '20I6) */
-
-    *jbit = 0;
-
-    i__1 = *lx;
-    for (k = 1; k <= i__1; ++k) {
-L310:
-	if (lbit[k] < ibxx2[*jbit]) {
-	    goto L320;
-	}
-	++(*jbit);
-	goto L310;
-L320:
-	;
-    }
-
-/*        ************************************* */
-
-/*        CALCULATE KBIT, THE NUMBER OF BITS NEEDED TO HOLD THE NUMBER */
-/*        OF VALUES IN THE GROUPS.  BUT FIND AND REMOVE THE */
-/*        REFERENCE FIRST. */
-
-/*        ************************************* */
-
-/*     WRITE(KFILDO,321)CFEED,LX */
-/* 321  FORMAT(A1,/' *****************************************' */
-/*    1          /' THE GROUP SIZES NOV( ) FOR ',I8,' GROUPS' */
-/*    2          /' *****************************************') */
-/*     WRITE(KFILDO,322) (NOV(J),J=1,MIN(LX,100)) */
-/* 322  FORMAT(/' '20I6) */
-
-    *novref = nov[1];
-
-    i__1 = *lx;
-    for (k = 1; k <= i__1; ++k) {
-	if (nov[k] < *novref) {
-	    *novref = nov[k];
-	}
-/* L400: */
-    }
-
-    if (*novref > 0) {
-
-	i__1 = *lx;
-	for (k = 1; k <= i__1; ++k) {
-	    nov[k] -= *novref;
-/* L405: */
-	}
-
-    }
-
-/*     WRITE(KFILDO,406)CFEED,NOVREF */
-/* 406  FORMAT(A1,/' *****************************************' */
-/*    1          /' THE GROUP SIZES NOV( ) AFTER REMOVING REFERENCE ',I8, */
-/*    2          /' *****************************************') */
-/*     WRITE(KFILDO,407) (NOV(J),J=1,MIN(LX,100)) */
-/* 407  FORMAT(/' '20I6) */
-/*     WRITE(KFILDO,408)CFEED */
-/* 408  FORMAT(A1,/' *****************************************' */
-/*    1          /' THE GROUP REFERENCES JMIN( )' */
-/*    2          /' *****************************************') */
-/*     WRITE(KFILDO,409) (JMIN(J),J=1,MIN(LX,100)) */
-/* 409  FORMAT(/' '20I6) */
-
-    *kbit = 0;
-
-    i__1 = *lx;
-    for (k = 1; k <= i__1; ++k) {
-L410:
-	if (nov[k] < ibxx2[*kbit]) {
-	    goto L420;
-	}
-	++(*kbit);
-	goto L410;
-L420:
-	;
-    }
-
-/*        DETERMINE WHETHER THE GROUP SIZES SHOULD BE REDUCED */
-/*        FOR SPACE EFFICIENCY. */
-
-    if (ired == 0) {
-	reduce(kfildo, &jmin[1], &jmax[1], &lbit[1], &nov[1], lx, ndg, ibit, 
-		jbit, kbit, novref, ibxx2, ier);
-
-	if (*ier == 714 || *ier == 715) {
-/*              REDUCE HAS ABORTED.  REEXECUTE PACK_GP WITHOUT REDUCE. */
-/*              PROVIDE FOR A NON FATAL RETURN FROM REDUCE. */
-	    iersav = *ier;
-	    ired = 1;
-	    *ier = 0;
-	    goto L102;
-	}
-
-    }
-
-    if ( misslx != 0 ) {
-         free(misslx);
-         misslx=0;
-    }
-/*     CALL TIMPR(KFILDO,KFILDO,'END   PACK_GP        ') */
-    if (iersav != 0) {
-	*ier = iersav;
-	return 0;
-    }
-
-/* 900  IF(IER.NE.0)RETURN1 */
-
-L900:
-    if ( misslx != 0 ) free(misslx);
-    return 0;
-} /* pack_gp__ */
-
diff --git a/src/modules/io/io_grid_grib2/g2clib-1.0.4/pdstemplates.c b/src/modules/io/io_grid_grib2/g2clib-1.0.4/pdstemplates.c
deleted file mode 100644
index 1994206..0000000
--- a/src/modules/io/io_grid_grib2/g2clib-1.0.4/pdstemplates.c
+++ /dev/null
@@ -1,271 +0,0 @@
-/**********************************************************
- * Version $Id: pdstemplates.c 911 2011-02-14 16:38:15Z reklov_w $
- *********************************************************/
-#include <stdlib.h>
-#include "grib2.h"
-#include "pdstemplates.h"
-
-g2int getpdsindex(g2int number)
-///$$$  SUBPROGRAM DOCUMENTATION BLOCK
-//                .      .    .                                       .
-// SUBPROGRAM:    getpdsindex
-//   PRGMMR: Gilbert         ORG: W/NP11    DATE: 2001-06-28
-//
-// ABSTRACT: This function returns the index of specified Product
-//   Definition Template 4.NN (NN=number) in array templates.
-//
-// PROGRAM HISTORY LOG:
-// 2001-06-28  Gilbert
-//
-// USAGE:    index=getpdsindex(number)
-//   INPUT ARGUMENT LIST:
-//     number   - NN, indicating the number of the Product Definition
-//                Template 4.NN that is being requested.
-//
-// RETURNS:  Index of PDT 4.NN in array templates, if template exists.
-//           = -1, otherwise.
-//
-// REMARKS: None
-//
-// ATTRIBUTES:
-//   LANGUAGE: C
-//   MACHINE:  IBM SP
-//
-//$$$/
-{
-           g2int j,getpdsindex=-1;
-
-           for (j=0;j<MAXPDSTEMP;j++) {
-              if (number == templatespds[j].template_num) {
-                 getpdsindex=j;
-                 return(getpdsindex);
-              }
-           }
-
-           return(getpdsindex);
-}
-
-
-template *getpdstemplate(g2int number)
-///$$$  SUBPROGRAM DOCUMENTATION BLOCK
-//                .      .    .                                       .
-// SUBPROGRAM:    getpdstemplate 
-//   PRGMMR: Gilbert         ORG: W/NP11    DATE: 2000-05-11
-//
-// ABSTRACT: This subroutine returns PDS template information for a 
-//   specified Product Definition Template 4.NN.
-//   The number of entries in the template is returned along with a map
-//   of the number of octets occupied by each entry.  Also, a flag is
-//   returned to indicate whether the template would need to be extended.
-//
-// PROGRAM HISTORY LOG:
-// 2000-05-11  Gilbert
-//
-// USAGE:    CALL getpdstemplate(number)
-//   INPUT ARGUMENT LIST:
-//     number   - NN, indicating the number of the Product Definition 
-//                Template 4.NN that is being requested.
-//
-//   RETURN VALUE:
-//        - Pointer to the returned template struct.
-//          Returns NULL pointer, if template not found.
-//
-// REMARKS: None
-//
-// ATTRIBUTES:
-//   LANGUAGE: C
-//   MACHINE:  IBM SP
-//
-//$$$/
-{
-           g2int index;
-           template *new;
-
-           index=getpdsindex(number);
-
-           if (index != -1) {
-              new=(template *)malloc(sizeof(template));
-              new->type=4;
-              new->num=templatespds[index].template_num;
-              new->maplen=templatespds[index].mappdslen;
-              new->needext=templatespds[index].needext;
-              new->map=(g2int *)templatespds[index].mappds;
-              new->extlen=0;
-              new->ext=0;        //NULL
-              return(new);
-           }
-           else {
-             printf("getpdstemplate: PDS Template 4.%d not defined.\n",(int)number);
-             return(0);        //NULL
-           }
-
-         return(0);        //NULL
-}
-         
-        
-template *extpdstemplate(g2int number,g2int *list)
-///$$$  SUBPROGRAM DOCUMENTATION BLOCK
-//                .      .    .                                       .
-// SUBPROGRAM:    extpdstemplate 
-//   PRGMMR: Gilbert         ORG: W/NP11    DATE: 2000-05-11
-//
-// ABSTRACT: This subroutine generates the remaining octet map for a
-//   given Product Definition Template, if required.  Some Templates can
-//   vary depending on data values given in an earlier part of the 
-//   Template, and it is necessary to know some of the earlier entry
-//   values to generate the full octet map of the Template.
-//
-// PROGRAM HISTORY LOG:
-// 2000-05-11  Gilbert
-//
-// USAGE:    CALL extpdstemplate(number,list)
-//   INPUT ARGUMENT LIST:
-//     number   - NN, indicating the number of the Product Definition 
-//                Template 4.NN that is being requested.
-//     list()   - The list of values for each entry in the 
-//                the Product Definition Template 4.NN.
-//
-//   RETURN VALUE:
-//        - Pointer to the returned template struct.
-//          Returns NULL pointer, if template not found.
-//
-// ATTRIBUTES:
-//   LANGUAGE: C
-//   MACHINE:  IBM SP
-//
-//$$$
-{
-           template *new;
-           g2int index,i,j,k,l;
-
-           index=getpdsindex(number);
-           if (index == -1) return(0);
-
-           new=getpdstemplate(number);
-
-           if ( ! new->needext ) return(new);
-
-           if ( number == 3 ) {
-              new->extlen=list[26];
-              new->ext=(g2int *)malloc(sizeof(g2int)*new->extlen);
-              for (i=0;i<new->extlen;i++) {
-                 new->ext[i]=1;
-              }
-           }
-           else if ( number == 4 ) {
-              new->extlen=list[25];
-              new->ext=(g2int *)malloc(sizeof(g2int)*new->extlen);
-              for (i=0;i<new->extlen;i++) {
-                 new->ext[i]=1;
-              }
-           }
-           else if ( number == 8 ) {
-              if ( list[21] > 1 ) {
-                 new->extlen=(list[21]-1)*6;
-                 new->ext=(g2int *)malloc(sizeof(g2int)*new->extlen);
-                 for (j=2;j<=list[21];j++) {
-                    l=(j-2)*6;
-                    for (k=0;k<6;k++) {
-                       new->ext[l+k]=new->map[23+k];
-                    }
-                 }
-              }
-           }
-           else if ( number == 9 ) {
-              if ( list[28] > 1 ) {
-                 new->extlen=(list[28]-1)*6;
-                 new->ext=(g2int *)malloc(sizeof(g2int)*new->extlen);
-                 for (j=2;j<=list[28];j++) {
-                    l=(j-2)*6;
-                    for (k=0;k<6;k++) {
-                       new->ext[l+k]=new->map[30+k];
-                    }
-                 }
-              }
-           }
-           else if ( number == 10 ) {
-              if ( list[22] > 1 ) {
-                 new->extlen=(list[22]-1)*6;
-                 new->ext=(g2int *)malloc(sizeof(g2int)*new->extlen);
-                 for (j=2;j<=list[22];j++) {
-                    l=(j-2)*6;
-                    for (k=0;k<6;k++) {
-                       new->ext[l+k]=new->map[24+k];
-                    }
-                 }
-              }
-           }
-           else if ( number == 11 ) {
-              if ( list[24] > 1 ) {
-                 new->extlen=(list[24]-1)*6;
-                 new->ext=(g2int *)malloc(sizeof(g2int)*new->extlen);
-                 for (j=2;j<=list[24];j++) {
-                    l=(j-2)*6;
-                    for (k=0;k<6;k++) {
-                       new->ext[l+k]=new->map[26+k];
-                    }
-                 }
-              }
-           }
-           else if ( number == 12 ) {
-              if ( list[23] > 1 ) {
-                 new->extlen=(list[23]-1)*6;
-                 new->ext=(g2int *)malloc(sizeof(g2int)*new->extlen);
-                 for (j=2;j<=list[23];j++) {
-                    l=(j-2)*6;
-                    for (k=0;k<6;k++) {
-                       new->ext[l+k]=new->map[25+k];
-                    }
-                 }
-              }
-           }
-           else if ( number == 13 ) {
-              new->extlen=((list[37]-1)*6)+list[26];
-              new->ext=(g2int *)malloc(sizeof(g2int)*new->extlen);
-              if ( list[37] > 1 ) {
-                 for (j=2;j<=list[37];j++) {
-                    l=(j-2)*6;
-                    for (k=0;k<6;k++) {
-                       new->ext[l+k]=new->map[39+k];
-                    }
-                 }
-              }
-              l=(list[37]-1)*6;
-              if ( l<0 ) l=0;
-              for (i=0;i<list[26];i++) {
-                new->ext[l+i]=1;
-              }
-           }
-           else if ( number == 14 ) {
-              new->extlen=((list[36]-1)*6)+list[25];
-              new->ext=(g2int *)malloc(sizeof(g2int)*new->extlen);
-              if ( list[36] > 1 ) {
-                 for (j=2;j<=list[36];j++) {
-                    l=(j-2)*6;
-                    for (k=0;k<6;k++) {
-                       new->ext[l+k]=new->map[38+k];
-                    }
-                 }
-              }
-              l=(list[36]-1)*6;
-              if ( l<0 ) l=0;
-              for (i=0;i<list[25];i++) {
-                new->ext[l+i]=1;
-              }
-           }
-           else if ( number == 30 ) {
-              new->extlen=list[4]*5;
-              new->ext=(g2int *)malloc(sizeof(g2int)*new->extlen);
-              for (i=0;i<list[4];i++) {
-                 l=i*5;
-                 new->ext[l]=2;
-                 new->ext[l+1]=2;
-                 new->ext[l+2]=1;
-                 new->ext[l+3]=1;
-                 new->ext[l+4]=4;
-              }
-           }
-           return(new);
-
-}
-
diff --git a/src/modules/io/io_grid_grib2/g2clib-1.0.4/pdstemplates.h b/src/modules/io/io_grid_grib2/g2clib-1.0.4/pdstemplates.h
deleted file mode 100644
index 9c10c1e..0000000
--- a/src/modules/io/io_grid_grib2/g2clib-1.0.4/pdstemplates.h
+++ /dev/null
@@ -1,121 +0,0 @@
-/**********************************************************
- * Version $Id: pdstemplates.h 911 2011-02-14 16:38:15Z reklov_w $
- *********************************************************/
-#ifndef _pdstemplates_H
-#define _pdstemplates_H
-#include "grib2.h"
-
-//   PRGMMR: Gilbert         ORG: W/NP11    DATE: 2002-10-26
-//
-// ABSTRACT: This inculde file contains info on all the available 
-//   GRIB2 Product Definition Templates used in Section 4 (PDS).
-//   The information decribing each template is stored in the
-//   pdstemplate structure defined below.
-//
-//   Each Template has three parts: The number of entries in the template
-//   (mappdslen);  A map of the template (mappds), which contains the
-//   number of octets in which to pack each of the template values; and
-//   a logical value (needext) that indicates whether the Template needs 
-//   to be extended.  In some cases the number of entries in a template 
-//   can vary depending upon values specified in the "static" part of 
-//   the template.  ( See Template 4.3 as an example )
-//
-//   NOTE:  Array mappds contains the number of octets in which the 
-//   corresponding template values will be stored.  A negative value in
-//   mappds is used to indicate that the corresponding template entry can
-//   contain negative values.  This information is used later when packing
-//   (or unpacking) the template data values.  Negative data values in GRIB
-//   are stored with the left most bit set to one, and a negative number
-//   of octets value in mappds[] indicates that this possibility should
-//   be considered.  The number of octets used to store the data value
-//   in this case would be the absolute value of the negative value in 
-//   mappds[].
-//  
-// 2005-12-08  Gilbert  -  Allow negative scale factors and limits for
-//                         Templates 4.5 and 4.9
-//
-//$$$
-
-      #define MAXPDSTEMP 23           // maximum number of templates
-      #define MAXPDSMAPLEN 200        // maximum template map length
-
-      struct pdstemplate 
-      {
-          g2int template_num;
-          g2int mappdslen;
-          g2int needext;
-          g2int mappds[MAXPDSMAPLEN];
-      };
-
-      const struct pdstemplate templatespds[MAXPDSTEMP] = {
-             // 4.0: Analysis or Forecast at Horizontal Level/Layer
-             //      at a point in time
-         {0,15,0, {1,1,1,1,1,2,1,1,4,1,-1,-4,1,-1,-4} },
-             // 4.1: Individual Ensemble Forecast at Horizontal Level/Layer
-             //      at a point in time
-         {1,18,0, {1,1,1,1,1,2,1,1,4,1,-1,-4,1,-1,-4,1,1,1} },
-             // 4.2: Derived Fcst based on whole Ensemble at Horiz Level/Layer
-             //      at a point in time
-         {2,17,0, {1,1,1,1,1,2,1,1,4,1,-1,-4,1,-1,-4,1,1} },
-             // 4.3: Derived Fcst based on Ensemble cluster over rectangular
-             //      area at Horiz Level/Layer at a point in time
-         {3,31,1, {1,1,1,1,1,2,1,1,4,1,-1,-4,1,-1,-4,1,1,1,1,1,1,1,-4,-4,4,4,1,-1,4,-1,4} },
-             // 4.4: Derived Fcst based on Ensemble cluster over circular
-             //      area at Horiz Level/Layer at a point in time
-         {4,30,1, {1,1,1,1,1,2,1,1,4,1,-1,-4,1,-1,-4,1,1,1,1,1,1,1,-4,4,4,1,-1,4,-1,4} },
-             // 4.5: Probablility Forecast at Horiz Level/Layer
-             //      at a point in time
-         {5,22,0, {1,1,1,1,1,2,1,1,4,1,-1,-4,1,-1,-4,1,1,1,-1,-4,-1,-4} },
-             // 4.6: Percentile Forecast at Horiz Level/Layer
-             //      at a point in time
-         {6,16,0, {1,1,1,1,1,2,1,1,4,1,-1,-4,1,-1,-4,1} },
-             // 4.7: Analysis or Forecast Error at Horizontal Level/Layer
-             //      at a point in time
-         {7,15,0, {1,1,1,1,1,2,1,1,4,1,-1,-4,1,-1,-4} },
-             // 4.8: Ave/Accum/etc... at Horiz Level/Layer
-             //      in a time interval
-         {8,29,1, {1,1,1,1,1,2,1,1,4,1,-1,-4,1,-1,-4,2,1,1,1,1,1,1,4,1,1,1,4,1,4} },
-             // 4.9: Probablility Forecast at Horiz Level/Layer
-             //      in a time interval
-         {9,36,1, {1,1,1,1,1,2,1,1,4,1,-1,-4,1,-1,-4,1,1,1,-1,-4,-1,-4,2,1,1,1,1,1,1,4,1,1,1,4,1,4} },
-             // 4.10: Percentile Forecast at Horiz Level/Layer
-             //       in a time interval
-         {10,30,1, {1,1,1,1,1,2,1,1,4,1,-1,-4,1,-1,-4,1,2,1,1,1,1,1,1,4,1,1,1,4,1,4} },
-             // 4.11: Individual Ensemble Forecast at Horizontal Level/Layer
-             //       in a time interval
-         {11,32,1, {1,1,1,1,1,2,1,1,4,1,-1,-4,1,-1,-4,1,1,1,2,1,1,1,1,1,1,4,1,1,1,4,1,4} },
-             // 4.12: Derived Fcst based on whole Ensemble at Horiz Level/Layer
-             //       in a time interval
-         {12,31,1, {1,1,1,1,1,2,1,1,4,1,-1,-4,1,-1,-4,1,1,2,1,1,1,1,1,1,4,1,1,1,4,1,4} },
-             // 4.13: Derived Fcst based on Ensemble cluster over rectangular
-             //       area at Horiz Level/Layer in a time interval
-         {13,45,1, {1,1,1,1,1,2,1,1,4,1,-1,-4,1,-1,-4,1,1,1,1,1,1,1,-4,-4,4,4,1,-1,4,-1,4,2,1,1,1,1,1,1,4,1,1,1,4,1,4} },
-             // 4.14: Derived Fcst based on Ensemble cluster over circular
-             //       area at Horiz Level/Layer in a time interval
-         {14,44,1, {1,1,1,1,1,2,1,1,4,1,-1,-4,1,-1,-4,1,1,1,1,1,1,1,-4,4,4,1,-1,4,-1,4,2,1,1,1,1,1,1,4,1,1,1,4,1,4} },
-             // 4.20: Radar Product
-         {20,19,0, {1,1,1,1,1,-4,4,2,4,2,1,1,1,1,1,2,1,3,2} },
-             // 4.30: Satellite Product
-         {30,5,1, {1,1,1,1,1} },
-             // 4.254: CCITT IA5 Character String
-         {254,3,0, {1,1,4} },
-             // 4.1000: Cross section of analysis or forecast
-             //         at a point in time
-         {1000,9,0, {1,1,1,1,1,2,1,1,4} },
-             // 4.1001: Cross section of Ave/Accum/etc... analysis or forecast
-             //         in a time interval
-         {1001,16,0, {1,1,1,1,1,2,1,1,4,4,1,1,1,4,1,4} },
-             // 4.1001: Cross section of Ave/Accum/etc... analysis or forecast
-             //         over latitude or longitude
-         {1002,15,0, {1,1,1,1,1,2,1,1,4,1,1,1,4,4,2} },
-             // 4.1100: Hovmoller-type grid w/ no averaging or other
-             //         statistical processing
-         {1100,15,0, {1,1,1,1,1,2,1,1,4,1,-1,-4,1,-1,-4} },
-             // 4.1100: Hovmoller-type grid with averaging or other
-             //         statistical processing
-         {1101,22,0, {1,1,1,1,1,2,1,1,4,1,-1,-4,1,-1,-4,4,1,1,1,4,1,4} }
-
-      } ;
-
-
-#endif  /*  _pdstemplates_H  */
diff --git a/src/modules/io/io_grid_grib2/g2clib-1.0.4/pngpack.c b/src/modules/io/io_grid_grib2/g2clib-1.0.4/pngpack.c
deleted file mode 100644
index 237847c..0000000
--- a/src/modules/io/io_grid_grib2/g2clib-1.0.4/pngpack.c
+++ /dev/null
@@ -1,165 +0,0 @@
-/**********************************************************
- * Version $Id: pngpack.c 911 2011-02-14 16:38:15Z reklov_w $
- *********************************************************/
-#include <stdlib.h>
-#include <math.h>
-#include "grib2.h"
-
-int enc_png(char *,g2int ,g2int ,g2int ,char *);
-
-void pngpack(g2float *fld,g2int width,g2int height,g2int *idrstmpl,
-             unsigned char *cpack,g2int *lcpack)
-//$$$  SUBPROGRAM DOCUMENTATION BLOCK
-//                .      .    .                                       .
-// SUBPROGRAM:    pngpack
-//   PRGMMR: Gilbert          ORG: W/NP11    DATE: 2003-08-27
-//
-// ABSTRACT: This subroutine packs up a data field into PNG image format.
-//   After the data field is scaled, and the reference value is subtracted out,
-//   it is treated as a grayscale image and passed to a PNG encoder.
-//   It also fills in GRIB2 Data Representation Template 5.41 or 5.40010 with 
-//   the appropriate values.
-//
-// PROGRAM HISTORY LOG:
-// 2003-08-27  Gilbert
-//
-// USAGE:    pngpack(g2float *fld,g2int width,g2int height,g2int *idrstmpl,
-//                   unsigned char *cpack,g2int *lcpack);
-//   INPUT ARGUMENT LIST:
-//     fld[]    - Contains the data values to pack
-//     width    - number of points in the x direction
-//     height   - number of points in the y direction
-//     idrstmpl - Contains the array of values for Data Representation
-//                Template 5.41 or 5.40010
-//                [0] = Reference value - ignored on input
-//                [1] = Binary Scale Factor
-//                [2] = Decimal Scale Factor
-//                [3] = number of bits for each data value - ignored on input
-//                [4] = Original field type - currently ignored on input
-//                      Data values assumed to be reals.
-//
-//   OUTPUT ARGUMENT LIST: 
-//     idrstmpl - Contains the array of values for Data Representation
-//                Template 5.41 or 5.40010
-//                [0] = Reference value - set by pngpack routine.
-//                [1] = Binary Scale Factor - unchanged from input
-//                [2] = Decimal Scale Factor - unchanged from input
-//                [3] = Number of bits containing each grayscale pixel value
-//                [4] = Original field type - currently set = 0 on output.
-//                      Data values assumed to be reals.
-//     cpack    - The packed data field 
-//     lcpack   - length of packed field cpack.
-//
-// REMARKS: None
-//
-// ATTRIBUTES:
-//   LANGUAGE: C
-//   MACHINE:  IBM SP
-//
-//$$$
-{
-      g2int  *ifld;
-      static g2float alog2=0.69314718;       //  ln(2.0)
-      g2int  j,nbits,imin,imax,maxdif;
-      g2int  ndpts,nbytes;
-      g2float  bscale,dscale,rmax,rmin,temp;
-      unsigned char *ctemp;
-      
-      ifld=0;
-      ndpts=width*height;
-      bscale=int_power(2.0,-idrstmpl[1]);
-      dscale=int_power(10.0,idrstmpl[2]);
-//
-//  Find max and min values in the data
-//
-      rmax=fld[0];
-      rmin=fld[0];
-      for (j=1;j<ndpts;j++) {
-        if (fld[j] > rmax) rmax=fld[j];
-        if (fld[j] < rmin) rmin=fld[j];
-      }
-      maxdif = (g2int)rint( (rmax-rmin)*dscale*bscale );
-//
-//  If max and min values are not equal, pack up field.
-//  If they are equal, we have a constant field, and the reference
-//  value (rmin) is the value for each point in the field and
-//  set nbits to 0.
-//
-      if (rmin != rmax  &&  maxdif != 0 ) {
-        ifld=(g2int *)malloc(ndpts*sizeof(g2int));
-        //
-        //  Determine which algorithm to use based on user-supplied 
-        //  binary scale factor and number of bits.
-        //
-        if (idrstmpl[1] == 0) {
-           //
-           //  No binary scaling and calculate minumum number of 
-           //  bits in which the data will fit.
-           //
-           imin=(g2int)rint(rmin*dscale);
-           imax=(g2int)rint(rmax*dscale);
-           maxdif=imax-imin;
-           temp=log((double)(maxdif+1))/alog2;
-           nbits=(g2int)ceil(temp);
-           rmin=(g2float)imin;
-           //   scale data
-           for(j=0;j<ndpts;j++)
-             ifld[j]=(g2int)rint(fld[j]*dscale)-imin;
-        }
-        else {
-           //
-           //  Use binary scaling factor and calculate minumum number of 
-           //  bits in which the data will fit.
-           //
-           rmin=rmin*dscale;
-           rmax=rmax*dscale;
-           maxdif=(g2int)rint((rmax-rmin)*bscale);
-           temp=log((double)(maxdif+1))/alog2;
-           nbits=(g2int)ceil(temp);
-           //   scale data
-           for (j=0;j<ndpts;j++)
-             ifld[j]=(g2int)rint(((fld[j]*dscale)-rmin)*bscale);
-        }
-        //
-        //  Pack data into full octets, then do PNG encode.
-        //  and calculate the length of the packed data in bytes
-        //
-        if (nbits <= 8) {
-            nbits=8;
-        }
-        else if (nbits <= 16) {
-            nbits=16;
-        }
-        else if (nbits <= 24) {
-            nbits=24;
-        }
-        else {
-            nbits=32;
-        }
-        nbytes=(nbits/8)*ndpts;
-        ctemp=calloc(nbytes,1);
-        sbits(ctemp,ifld,0,nbits,0,ndpts);
-        //
-        //  Encode data into PNG Format.
-        //
-        *lcpack=(g2int)enc_png((char *)ctemp,width,height,nbits,(char *)cpack);
-        if (*lcpack <= 0) {
-           printf("pngpack: ERROR Packing PNG = %d\n",(int)*lcpack);
-        }
-        free(ctemp);
-
-      }
-      else {
-        nbits=0;
-        *lcpack=0;
-      }
-
-//
-//  Fill in ref value and number of bits in Template 5.0
-//
-      mkieee(&rmin,idrstmpl+0,1);   // ensure reference value is IEEE format
-      idrstmpl[3]=nbits;
-      idrstmpl[4]=0;         // original data were reals
-      if (ifld != 0) free(ifld);
-
-}
diff --git a/src/modules/io/io_grid_grib2/g2clib-1.0.4/pngunpack.c b/src/modules/io/io_grid_grib2/g2clib-1.0.4/pngunpack.c
deleted file mode 100644
index 22a9ed3..0000000
--- a/src/modules/io/io_grid_grib2/g2clib-1.0.4/pngunpack.c
+++ /dev/null
@@ -1,79 +0,0 @@
-/**********************************************************
- * Version $Id: pngunpack.c 911 2011-02-14 16:38:15Z reklov_w $
- *********************************************************/
-#include <stdio.h>
-#include <stdlib.h>
-#include "grib2.h"
-
-int dec_png(unsigned char *,g2int *,g2int *,char *);
-
-g2int pngunpack(unsigned char *cpack,g2int len,g2int *idrstmpl,g2int ndpts,
-                g2float *fld)
-//$$$  SUBPROGRAM DOCUMENTATION BLOCK
-//                .      .    .                                       .
-// SUBPROGRAM:    pngunpack
-//   PRGMMR: Gilbert          ORG: W/NP11    DATE: 2003-08-27
-//
-// ABSTRACT: This subroutine unpacks a data field that was packed into a 
-//   PNG image format
-//   using info from the GRIB2 Data Representation Template 5.41 or 5.40010.
-//
-// PROGRAM HISTORY LOG:
-// 2003-08-27  Gilbert
-//
-// USAGE:    pngunpack(unsigned char *cpack,g2int len,g2int *idrstmpl,g2int ndpts,
-//                     g2float *fld)
-//   INPUT ARGUMENT LIST:
-//     cpack    - The packed data field (character*1 array)
-//     len      - length of packed field cpack().
-//     idrstmpl - Pointer to array of values for Data Representation
-//                Template 5.41 or 5.40010
-//     ndpts    - The number of data values to unpack
-//
-//   OUTPUT ARGUMENT LIST:
-//     fld[]    - Contains the unpacked data values
-//
-// REMARKS: None
-//
-// ATTRIBUTES:
-//   LANGUAGE: C
-//   MACHINE:  IBM SP
-//
-//$$$
-{
-
-      g2int  *ifld;
-      g2int  j,nbits,iret,width,height;
-      g2float  ref,bscale,dscale;
-      unsigned char *ctemp;
-
-      rdieee(idrstmpl+0,&ref,1);
-      bscale = int_power(2.0,idrstmpl[1]);
-      dscale = int_power(10.0,-idrstmpl[2]);
-      nbits = idrstmpl[3];
-//
-//  if nbits equals 0, we have a constant field where the reference value
-//  is the data value at each gridpoint
-//
-      if (nbits != 0) {
-
-         ifld=(g2int *)calloc(ndpts,sizeof(g2int));
-         ctemp=(unsigned char *)calloc(ndpts*4,1);
-         if ( ifld == 0 || ctemp == 0) {
-            fprintf(stderr,"Could not allocate space in jpcunpack.\n  Data field NOT upacked.\n");
-            return(1);
-         }
-         iret=(g2int)dec_png(cpack,&width,&height,ctemp);
-         gbits(ctemp,ifld,0,nbits,0,ndpts);
-         for (j=0;j<ndpts;j++) {
-           fld[j]=(((g2float)ifld[j]*bscale)+ref)*dscale;
-         }
-         free(ctemp);
-         free(ifld);
-      }
-      else {
-         for (j=0;j<ndpts;j++) fld[j]=ref;
-      }
-
-      return(0);
-}
diff --git a/src/modules/io/io_grid_grib2/g2clib-1.0.4/rdieee.c b/src/modules/io/io_grid_grib2/g2clib-1.0.4/rdieee.c
deleted file mode 100644
index 03e3771..0000000
--- a/src/modules/io/io_grid_grib2/g2clib-1.0.4/rdieee.c
+++ /dev/null
@@ -1,81 +0,0 @@
-/**********************************************************
- * Version $Id: rdieee.c 911 2011-02-14 16:38:15Z reklov_w $
- *********************************************************/
-#include "grib2.h"
-
-void rdieee(g2int *rieee,g2float *a,g2int num)
-//$$$  SUBPROGRAM DOCUMENTATION BLOCK
-//                .      .    .                                       .
-// SUBPROGRAM:    rdieee 
-//   PRGMMR: Gilbert         ORG: W/NP11    DATE: 2002-10-25
-//
-// ABSTRACT: This subroutine reads a list of real values in 
-//   32-bit IEEE floating point format.
-//
-// PROGRAM HISTORY LOG:
-// 2002-10-25  Gilbert
-//
-// USAGE:    void rdieee(g2int *rieee,g2float *a,g2int num)
-//   INPUT ARGUMENT LIST:
-//     rieee    - g2int array of floating point values in 32-bit IEEE format.
-//     num      - Number of floating point values to convert.
-//
-//   OUTPUT ARGUMENT LIST:      
-//     a        - float array of real values.  a must be allocated with at
-//                least 4*num bytes of memory before calling this function.
-//
-// REMARKS: None
-//
-// ATTRIBUTES:
-//   LANGUAGE: C
-//   MACHINE:  IBM SP
-//
-//$$$
-{
-
-      g2int  j;
-      g2int  isign,iexp,imant;
-
-      g2float  sign,temp;
-      static g2float  two23,two126;
-      static g2int test=0;
-      g2intu msk1=0x80000000;        // 10000000000000000000000000000000 binary
-      g2int msk2=0x7F800000;         // 01111111100000000000000000000000 binary
-      g2int msk3=0x007FFFFF;         // 00000000011111111111111111111111 binary
-
-      if ( test == 0 ) {
-         two23=(g2float)int_power(2.0,-23);
-         two126=(g2float)int_power(2.0,-126);
-         test=1;
-      }
-
-      for (j=0;j<num;j++) {
-//
-//  Extract sign bit, exponent, and mantissa
-//
-        isign=(rieee[j]&msk1)>>31;
-        iexp=(rieee[j]&msk2)>>23;
-        imant=(rieee[j]&msk3);
-        //printf("SAGieee= %ld %ld %ld\n",isign,iexp,imant);
-
-        sign=1.0;
-        if (isign == 1) sign=-1.0;
-        
-        if ( (iexp > 0) && (iexp < 255) ) {
-          temp=(g2float)int_power(2.0,(iexp-127));
-          a[j]=sign*temp*(1.0+(two23*(g2float)imant));
-        }
-        else if ( iexp == 0 ) {
-          if ( imant != 0 )
-            a[j]=sign*two126*two23*(g2float)imant;
-          else
-            a[j]=sign*0.0;
-          
-        }
-        else if ( iexp == 255 )
-           a[j]=sign*(1E+37);
-
-
-      }
-
-}
diff --git a/src/modules/io/io_grid_grib2/g2clib-1.0.4/reduce.c b/src/modules/io/io_grid_grib2/g2clib-1.0.4/reduce.c
deleted file mode 100644
index aafd182..0000000
--- a/src/modules/io/io_grid_grib2/g2clib-1.0.4/reduce.c
+++ /dev/null
@@ -1,413 +0,0 @@
-/**********************************************************
- * Version $Id: reduce.c 911 2011-02-14 16:38:15Z reklov_w $
- *********************************************************/
-/* reduce.f -- translated by f2c (version 20031025).
-   You must link the resulting object file with libf2c:
-	on Microsoft Windows system, link with libf2c.lib;
-	on Linux or Unix systems, link with .../path/to/libf2c.a -lm
-	or, if you install libf2c.a in a standard place, with -lf2c -lm
-	-- in that order, at the end of the command line, as in
-		cc *.o -lf2c -lm
-	Source for libf2c is in /netlib/f2c/libf2c.zip, e.g.,
-
-		http://www.netlib.org/f2c/libf2c.zip
-*/
-
-/*#include "f2c.h"*/
-#include <stdlib.h>
-#include "grib2.h"
-typedef g2int integer;
-typedef g2float real;
-
-/* Subroutine */ int reduce(integer *kfildo, integer *jmin, integer *jmax, 
-	integer *lbit, integer *nov, integer *lx, integer *ndg, integer *ibit,
-	 integer *jbit, integer *kbit, integer *novref, integer *ibxx2, 
-	integer *ier)
-{
-    /* Initialized data */
-
-    static integer ifeed = 12;
-
-    /* System generated locals */
-    integer i__1, i__2;
-
-    /* Local variables */
-    static integer newboxtp, j, l, m, jj, lxn, left;
-    static real pimp;
-    static integer move, novl;
-    static char cfeed[1];
-    static integer nboxj[31], lxnkp, iorigb, ibxx2m1, movmin,
-	     ntotbt[31], ntotpr, newboxt;
-    integer *newbox, *newboxp;
-
-
-/*        NOVEMBER 2001   GLAHN   TDL   GRIB2 */
-/*        MARCH    2002   GLAHN   COMMENT IER = 715 */
-/*        MARCH    2002   GLAHN   MODIFIED TO ACCOMMODATE LX=1 ON ENTRY */
-
-/*        PURPOSE */
-/*            DETERMINES WHETHER THE NUMBER OF GROUPS SHOULD BE */
-/*            INCREASED IN ORDER TO REDUCE THE SIZE OF THE LARGE */
-/*            GROUPS, AND TO MAKE THAT ADJUSTMENT.  BY REDUCING THE */
-/*            SIZE OF THE LARGE GROUPS, LESS BITS MAY BE NECESSARY */
-/*            FOR PACKING THE GROUP SIZES AND ALL THE INFORMATION */
-/*            ABOUT THE GROUPS. */
-
-/*            THE REFERENCE FOR NOV( ) WAS REMOVED IN THE CALLING */
-/*            ROUTINE SO THAT KBIT COULD BE DETERMINED.  THIS */
-/*            FURNISHES A STARTING POINT FOR THE ITERATIONS IN REDUCE. */
-/*            HOWEVER, THE REFERENCE MUST BE CONSIDERED. */
-
-/*        DATA SET USE */
-/*           KFILDO - UNIT NUMBER FOR OUTPUT (PRINT) FILE. (OUTPUT) */
-
-/*        VARIABLES IN CALL SEQUENCE */
-/*              KFILDO = UNIT NUMBER FOR OUTPUT (PRINT) FILE.  (INPUT) */
-/*             JMIN(J) = THE MINIMUM OF EACH GROUP (J=1,LX).  IT IS */
-/*                       POSSIBLE AFTER SPLITTING THE GROUPS, JMIN( ) */
-/*                       WILL NOT BE THE MINIMUM OF THE NEW GROUP. */
-/*                       THIS DOESN'T MATTER; JMIN( ) IS REALLY THE */
-/*                       GROUP REFERENCE AND DOESN'T HAVE TO BE THE */
-/*                       SMALLEST VALUE.  (INPUT/OUTPUT) */
-/*             JMAX(J) = THE MAXIMUM OF EACH GROUP (J=1,LX). */
-/*                       (INPUT/OUTPUT) */
-/*             LBIT(J) = THE NUMBER OF BITS NECESSARY TO PACK EACH GROUP */
-/*                       (J=1,LX).  (INPUT/OUTPUT) */
-/*              NOV(J) = THE NUMBER OF VALUES IN EACH GROUP (J=1,LX). */
-/*                       (INPUT/OUTPUT) */
-/*                  LX = THE NUMBER OF GROUPS.  THIS WILL BE INCREASED */
-/*                       IF GROUPS ARE SPLIT.  (INPUT/OUTPUT) */
-/*                 NDG = THE DIMENSION OF JMIN( ), JMAX( ), LBIT( ), AND */
-/*                       NOV( ).  (INPUT) */
-/*                IBIT = THE NUMBER OF BITS NECESSARY TO PACK THE JMIN(J) */
-/*                       VALUES, J=1,LX.  (INPUT) */
-/*                JBIT = THE NUMBER OF BITS NECESSARY TO PACK THE LBIT(J) */
-/*                       VALUES, J=1,LX.  (INPUT) */
-/*                KBIT = THE NUMBER OF BITS NECESSARY TO PACK THE NOV(J) */
-/*                       VALUES, J=1,LX.  IF THE GROUPS ARE SPLIT, KBIT */
-/*                       IS REDUCED.  (INPUT/OUTPUT) */
-/*              NOVREF = REFERENCE VALUE FOR NOV( ).  (INPUT) */
-/*            IBXX2(J) = 2**J (J=0,30).  (INPUT) */
-/*                 IER = ERROR RETURN.  (OUTPUT) */
-/*                         0 = GOOD RETURN. */
-/*                       714 = PROBLEM IN ALGORITHM.  REDUCE ABORTED. */
-/*                       715 = NGP NOT LARGE ENOUGH.  REDUCE ABORTED. */
-/*           NTOTBT(J) = THE TOTAL BITS USED FOR THE PACKING BITS J */
-/*                       (J=1,30).  (INTERNAL) */
-/*            NBOXJ(J) = NEW BOXES NEEDED FOR THE PACKING BITS J */
-/*                       (J=1,30).  (INTERNAL) */
-/*           NEWBOX(L) = NUMBER OF NEW BOXES (GROUPS) FOR EACH ORIGINAL */
-/*                       GROUP (L=1,LX) FOR THE CURRENT J.  (AUTOMATIC) */
-/*                       (INTERNAL) */
-/*          NEWBOXP(L) = SAME AS NEWBOX( ) BUT FOR THE PREVIOUS J. */
-/*                       THIS ELIMINATES RECOMPUTATION.  (AUTOMATIC) */
-/*                       (INTERNAL) */
-/*               CFEED = CONTAINS THE CHARACTER REPRESENTATION */
-/*                       OF A PRINTER FORM FEED.  (CHARACTER) (INTERNAL) */
-/*               IFEED = CONTAINS THE INTEGER VALUE OF A PRINTER */
-/*                       FORM FEED.  (INTERNAL) */
-/*              IORIGB = THE ORIGINAL NUMBER OF BITS NECESSARY */
-/*                       FOR THE GROUP VALUES.  (INTERNAL) */
-/*        1         2         3         4         5         6         7 X */
-
-/*        NON SYSTEM SUBROUTINES CALLED */
-/*           NONE */
-
-
-/*        NEWBOX( ) AND NEWBOXP( ) were AUTOMATIC ARRAYS. */
-    newbox = (integer *)calloc(*ndg,sizeof(integer));
-    newboxp = (integer *)calloc(*ndg,sizeof(integer));
-
-    /* Parameter adjustments */
-    --nov;
-    --lbit;
-    --jmax;
-    --jmin;
-
-    /* Function Body */
-
-    *ier = 0;
-    if (*lx == 1) {
-	goto L410;
-    }
-/*        IF THERE IS ONLY ONE GROUP, RETURN. */
-
-    *(unsigned char *)cfeed = (char) ifeed;
-
-/*        INITIALIZE NUMBER OF NEW BOXES PER GROUP TO ZERO. */
-
-    i__1 = *lx;
-    for (l = 1; l <= i__1; ++l) {
-	newbox[l - 1] = 0;
-/* L110: */
-    }
-
-/*        INITIALIZE NUMBER OF TOTAL NEW BOXES PER J TO ZERO. */
-
-    for (j = 1; j <= 31; ++j) {
-	ntotbt[j - 1] = 999999999;
-	nboxj[j - 1] = 0;
-/* L112: */
-    }
-
-    iorigb = (*ibit + *jbit + *kbit) * *lx;
-/*        IBIT = BITS TO PACK THE JMIN( ). */
-/*        JBIT = BITS TO PACK THE LBIT( ). */
-/*        KBIT = BITS TO PACK THE NOV( ). */
-/*        LX = NUMBER OF GROUPS. */
-    ntotbt[*kbit - 1] = iorigb;
-/*           THIS IS THE VALUE OF TOTAL BITS FOR THE ORIGINAL LX */
-/*           GROUPS, WHICH REQUIRES KBITS TO PACK THE GROUP */
-/*           LENGHTS.  SETTING THIS HERE MAKES ONE LESS LOOPS */
-/*           NECESSARY BELOW. */
-
-/*        COMPUTE BITS NOW USED FOR THE PARAMETERS DEFINED. */
-
-/*        DETERMINE OTHER POSSIBILITES BY INCREASING LX AND DECREASING */
-/*        NOV( ) WITH VALUES GREATER THAN THRESHOLDS.  ASSUME A GROUP IS */
-/*        SPLIT INTO 2 OR MORE GROUPS SO THAT KBIT IS REDUCED WITHOUT */
-/*        CHANGING IBIT OR JBIT. */
-
-    jj = 0;
-
-/* Computing MIN */
-    i__1 = 30, i__2 = *kbit - 1;
-    /*for (j = min(i__1,i__2); j >= 2; --j) {*/
-    for (j = (i__1 < i__2) ? i__1 : i__2; j >= 2; --j) {
-/*           VALUES GE KBIT WILL NOT REQUIRE SPLITS.  ONCE THE TOTAL */
-/*           BITS START INCREASING WITH DECREASING J, STOP.  ALSO, THE */
-/*           NUMBER OF BITS REQUIRED IS KNOWN FOR KBITS = NTOTBT(KBIT). */
-
-	newboxt = 0;
-
-	i__1 = *lx;
-	for (l = 1; l <= i__1; ++l) {
-
-	    if (nov[l] < ibxx2[j]) {
-		newbox[l - 1] = 0;
-/*                 NO SPLITS OR NEW BOXES. */
-		goto L190;
-	    } else {
-		novl = nov[l];
-
-		m = (nov[l] - 1) / (ibxx2[j] - 1) + 1;
-/*                 M IS FOUND BY SOLVING THE EQUATION BELOW FOR M: */
-/*                 (NOV(L)+M-1)/M LT IBXX2(J) */
-/*                 M GT (NOV(L)-1)/(IBXX2(J)-1) */
-/*                 SET M = (NOV(L)-1)/(IBXX2(J)-1)+1 */
-L130:
-		novl = (nov[l] + m - 1) / m;
-/*                 THE +M-1 IS NECESSARY.  FOR INSTANCE, 15 WILL FIT */
-/*                 INTO A BOX 4 BITS WIDE, BUT WON'T DIVIDE INTO */
-/*                 TWO BOXES 3 BITS WIDE EACH. */
-
-		if (novl < ibxx2[j]) {
-		    goto L185;
-		} else {
-		    ++m;
-/* ***                  WRITE(KFILDO,135)L,NOV(L),NOVL,M,J,IBXX2(J) */
-/* *** 135              FORMAT(/' AT 135--L,NOV(L),NOVL,M,J,IBXX2(J)',6I10) */
-		    goto L130;
-		}
-
-/*                 THE ABOVE DO LOOP WILL NEVER COMPLETE. */
-	    }
-
-L185:
-	    newbox[l - 1] = m - 1;
-	    newboxt = newboxt + m - 1;
-L190:
-	    ;
-	}
-
-	nboxj[j - 1] = newboxt;
-	ntotpr = ntotbt[j];
-	ntotbt[j - 1] = (*ibit + *jbit) * (*lx + newboxt) + j * (*lx + 
-		newboxt);
-
-	if (ntotbt[j - 1] >= ntotpr) {
-	    jj = j + 1;
-/*              THE PLUS IS USED BECAUSE J DECREASES PER ITERATION. */
-	    goto L250;
-	} else {
-
-/*              SAVE THE TOTAL NEW BOXES AND NEWBOX( ) IN CASE THIS */
-/*              IS THE J TO USE. */
-
-	    newboxtp = newboxt;
-
-	    i__1 = *lx;
-	    for (l = 1; l <= i__1; ++l) {
-		newboxp[l - 1] = newbox[l - 1];
-/* L195: */
-	    }
-
-/*           WRITE(KFILDO,197)NEWBOXT,IBXX2(J) */
-/* 197        FORMAT(/' *****************************************' */
-/*    1             /' THE NUMBER OF NEWBOXES PER GROUP OF THE TOTAL', */
-/*    2              I10,' FOR GROUP MAXSIZE PLUS 1 ='I10 */
-/*    3             /' *****************************************') */
-/*           WRITE(KFILDO,198) (NEWBOX(L),L=1,LX) */
-/* 198        FORMAT(/' '20I6/(' '20I6)) */
-	}
-
-/* 205     WRITE(KFILDO,209)KBIT,IORIGB */
-/* 209     FORMAT(/' ORIGINAL BITS WITH KBIT OF',I5,' =',I10) */
-/*        WRITE(KFILDO,210)(N,N=2,10),(IBXX2(N),N=2,10), */
-/*    1                    (NTOTBT(N),N=2,10),(NBOXJ(N),N=2,10), */
-/*    2                    (N,N=11,20),(IBXX2(N),N=11,20), */
-/*    3                    (NTOTBT(N),N=11,20),(NBOXJ(N),N=11,20), */
-/*    4                    (N,N=21,30),(IBXX2(N),N=11,20), */
-/*    5                    (NTOTBT(N),N=21,30),(NBOXJ(N),N=21,30) */
-/* 210     FORMAT(/' THE TOTAL BYTES FOR MAXIMUM GROUP LENGTHS BY ROW'// */
-/*    1      '   J         = THE NUMBER OF BITS PER GROUP LENGTH'/ */
-/*    2      '   IBXX2(J)  = THE MAXIMUM GROUP LENGTH PLUS 1 FOR THIS J'/ */
-/*    3      '   NTOTBT(J) = THE TOTAL BITS FOR THIS J'/ */
-/*    4      '   NBOXJ(J)  = THE NEW GROUPS FOR THIS J'/ */
-/*    5      4(/10X,9I10)/4(/10I10)/4(/10I10)) */
-
-/* L200: */
-    }
-
-L250:
-    pimp = (iorigb - ntotbt[jj - 1]) / (real) iorigb * 100.f;
-/*     WRITE(KFILDO,252)PIMP,KBIT,JJ */
-/* 252  FORMAT(/' PERCENT IMPROVEMENT =',F6.1, */
-/*    1        ' BY DECREASING GROUP LENGTHS FROM',I4,' TO',I4,' BITS') */
-    if (pimp >= 2.f) {
-
-/*        WRITE(KFILDO,255)CFEED,NEWBOXTP,IBXX2(JJ) */
-/* 255     FORMAT(A1,/' *****************************************' */
-/*    1             /' THE NUMBER OF NEWBOXES PER GROUP OF THE TOTAL', */
-/*    2             I10,' FOR GROUP MAXSIZE PLUS 1 ='I10 */
-/*    2             /' *****************************************') */
-/*        WRITE(KFILDO,256) (NEWBOXP(L),L=1,LX) */
-/* 256     FORMAT(/' '20I6) */
-
-/*           ADJUST GROUP LENGTHS FOR MAXIMUM LENGTH OF JJ BITS. */
-/*           THE MIN PER GROUP AND THE NUMBER OF BITS REQUIRED */
-/*           PER GROUP ARE NOT CHANGED.  THIS MAY MEAN THAT A */
-/*           GROUP HAS A MIN (OR REFERENCE) THAT IS NOT ZERO. */
-/*           THIS SHOULD NOT MATTER TO THE UNPACKER. */
-
-	lxnkp = *lx + newboxtp;
-/*           LXNKP = THE NEW NUMBER OF BOXES */
-
-	if (lxnkp > *ndg) {
-/*              DIMENSIONS NOT LARGE ENOUGH.  PROBABLY AN ERROR */
-/*              OF SOME SORT.  ABORT. */
-/*           WRITE(KFILDO,257)NDG,LXNPK */
-/*        1         2         3         4         5         6         7 X */
-/* 257        FORMAT(/' DIMENSIONS OF JMIN, ETC. IN REDUCE =',I8, */
-/*    1              ' NOT LARGE ENOUGH FOR THE EXPANDED NUMBER OF', */
-/*    2              ' GROUPS =',I8,'.  ABORT REDUCE.') */
-	    *ier = 715;
-	    goto L410;
-/*              AN ABORT CAUSES THE CALLING PROGRAM TO REEXECUTE */
-/*              WITHOUT CALLING REDUCE. */
-	}
-
-	lxn = lxnkp;
-/*           LXN IS THE NUMBER OF THE BOX IN THE NEW SERIES BEING */
-/*           FILLED.  IT DECREASES PER ITERATION. */
-	ibxx2m1 = ibxx2[jj] - 1;
-/*           IBXX2M1 IS THE MAXIMUM NUMBER OF VALUES PER GROUP. */
-
-	for (l = *lx; l >= 1; --l) {
-
-/*              THE VALUES IS NOV( ) REPRESENT THOSE VALUES + NOVREF. */
-/*              WHEN VALUES ARE MOVED TO ANOTHER BOX, EACH VALUE */
-/*              MOVED TO A NEW BOX REPRESENTS THAT VALUE + NOVREF. */
-/*              THIS HAS TO BE CONSIDERED IN MOVING VALUES. */
-
-	    if (newboxp[l - 1] * (ibxx2m1 + *novref) + *novref > nov[l] + *
-		    novref) {
-/*                 IF THE ABOVE TEST IS MET, THEN MOVING IBXX2M1 VALUES */
-/*                 FOR ALL NEW BOXES WILL LEAVE A NEGATIVE NUMBER FOR */
-/*                 THE LAST BOX.  NOT A TOLERABLE SITUATION. */
-		movmin = (nov[l] - newboxp[l - 1] * *novref) / newboxp[l - 1];
-		left = nov[l];
-/*                 LEFT = THE NUMBER OF VALUES TO MOVE FROM THE ORIGINAL */
-/*                 BOX TO EACH NEW BOX EXCEPT THE LAST.  LEFT IS THE */
-/*                 NUMBER LEFT TO MOVE. */
-	    } else {
-		movmin = ibxx2m1;
-/*                 MOVMIN VALUES CAN BE MOVED FOR EACH NEW BOX. */
-		left = nov[l];
-/*                 LEFT IS THE NUMBER OF VALUES LEFT TO MOVE. */
-	    }
-
-	    if (newboxp[l - 1] > 0) {
-		if ((movmin + *novref) * newboxp[l - 1] + *novref <= nov[l] + 
-			*novref && (movmin + *novref) * (newboxp[l - 1] + 1) 
-			>= nov[l] + *novref) {
-		    goto L288;
-		} else {
-/* ***D                 WRITE(KFILDO,287)L,MOVMIN,NOVREF,NEWBOXP(L),NOV(L) */
-/* ***D287              FORMAT(/' AT 287 IN REDUCE--L,MOVMIN,NOVREF,', */
-/* ***D    1                    'NEWBOXP(L),NOV(L)',5I12 */
-/* ***D    2                    ' REDUCE ABORTED.') */
-/*              WRITE(KFILDO,2870) */
-/* 2870          FORMAT(/' AN ERROR IN REDUCE ALGORITHM.  ABORT REDUCE.') */
-		    *ier = 714;
-		    goto L410;
-/*                 AN ABORT CAUSES THE CALLING PROGRAM TO REEXECUTE */
-/*                 WITHOUT CALLING REDUCE. */
-		}
-
-	    }
-
-L288:
-	    i__1 = newboxp[l - 1] + 1;
-	    for (j = 1; j <= i__1; ++j) {
-		/*move = min(movmin,left);*/
-		move = (movmin < left) ? movmin : left;
-		jmin[lxn] = jmin[l];
-		jmax[lxn] = jmax[l];
-		lbit[lxn] = lbit[l];
-		nov[lxn] = move;
-		--lxn;
-		left -= move + *novref;
-/*                 THE MOVE OF MOVE VALUES REALLY REPRESENTS A MOVE OF */
-/*                 MOVE + NOVREF VALUES. */
-/* L290: */
-	    }
-
-	    if (left != -(*novref)) {
-/* ***               WRITE(KFILDO,292)L,LXN,MOVE,LXNKP,IBXX2(JJ),LEFT,NOV(L), */
-/* ***     1                          MOVMIN */
-/* *** 292           FORMAT(' AT 292 IN REDUCE--L,LXN,MOVE,LXNKP,', */
-/* ***     1                'IBXX2(JJ),LEFT,NOV(L),MOVMIN'/8I12) */
-	    }
-
-/* L300: */
-	}
-
-	*lx = lxnkp;
-/*           LX IS NOW THE NEW NUMBER OF GROUPS. */
-	*kbit = jj;
-/*           KBIT IS NOW THE NEW NUMBER OF BITS REQUIRED FOR PACKING */
-/*           GROUP LENGHTS. */
-    }
-
-/*     WRITE(KFILDO,406)CFEED,LX */
-/* 406  FORMAT(A1,/' *****************************************' */
-/*    1          /' THE GROUP SIZES NOV( ) AFTER REDUCTION IN SIZE', */
-/*    2           ' FOR'I10,' GROUPS', */
-/*    3          /' *****************************************') */
-/*     WRITE(KFILDO,407) (NOV(J),J=1,LX) */
-/* 407  FORMAT(/' '20I6) */
-/*     WRITE(KFILDO,408)CFEED,LX */
-/* 408  FORMAT(A1,/' *****************************************' */
-/*    1          /' THE GROUP MINIMA JMIN( ) AFTER REDUCTION IN SIZE', */
-/*    2           ' FOR'I10,' GROUPS', */
-/*    3          /' *****************************************') */
-/*     WRITE(KFILDO,409) (JMIN(J),J=1,LX) */
-/* 409  FORMAT(/' '20I6) */
-
-L410:
-    if ( newbox != 0 ) free(newbox);
-    if ( newboxp != 0 ) free(newboxp);
-    return 0;
-} /* reduce_ */
-
diff --git a/src/modules/io/io_grid_grib2/g2clib-1.0.4/seekgb.c b/src/modules/io/io_grid_grib2/g2clib-1.0.4/seekgb.c
deleted file mode 100644
index 61ba019..0000000
--- a/src/modules/io/io_grid_grib2/g2clib-1.0.4/seekgb.c
+++ /dev/null
@@ -1,83 +0,0 @@
-/**********************************************************
- * Version $Id: seekgb.c 911 2011-02-14 16:38:15Z reklov_w $
- *********************************************************/
-#include <stdio.h>
-#include <stdlib.h>
-#include "grib2.h"
-
-void seekgb(FILE *lugb,g2int iseek,g2int mseek,g2int *lskip,g2int *lgrib)
-//$$$  SUBPROGRAM DOCUMENTATION BLOCK
-//
-// SUBPROGRAM: seekgb         Searches a file for the next GRIB message.
-//   PRGMMR: Gilbert          ORG: W/NP11      DATE: 2002-10-28
-//
-// ABSTRACT: This subprogram searches a file for the next GRIB Message.
-//   The search is done starting at byte offset iseek of the file referenced 
-//   by lugb for mseek bytes at a time.
-//   If found, the starting position and length of the message are returned
-//   in lskip and lgrib, respectively.
-//   The search is terminated when an EOF or I/O error is encountered.
-//
-// PROGRAM HISTORY LOG:
-// 2002-10-28  GILBERT   Modified from Iredell's skgb subroutine
-//
-// USAGE:    seekgb(FILE *lugb,g2int iseek,g2int mseek,int *lskip,int *lgrib)
-//   INPUT ARGUMENTS:
-//     lugb       - FILE pointer for the file to search.  File must be
-//                  opened before this routine is called.
-//     iseek      - number of bytes in the file to skip before search
-//     mseek      - number of bytes to search at a time
-//   OUTPUT ARGUMENTS:
-//     lskip      - number of bytes to skip from the beggining of the file
-//                  to where the GRIB message starts
-//     lgrib      - number of bytes in message (set to 0, if no message found)
-//
-// ATTRIBUTES:
-//   LANGUAGE: C
-//
-//$$$
-{
-      g2int  ret;
-      g2int k,k4,ipos,nread,lim,start,vers,end,lengrib;
-      unsigned char *cbuf;
-
-// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-      *lgrib=0;
-      cbuf=(unsigned char *)malloc(mseek);
-      nread=mseek;
-      ipos=iseek;
-
-// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-//  LOOP UNTIL GRIB MESSAGE IS FOUND
-
-      while (*lgrib==0 && nread==mseek) {
-
-//  READ PARTIAL SECTION
-
-        ret=fseek(lugb,ipos,SEEK_SET);
-        nread=fread(cbuf,sizeof(unsigned char),mseek,lugb);
-        lim=nread-8;
-
-//  LOOK FOR 'GRIB...' IN PARTIAL SECTION
-
-        for (k=0;k<lim;k++) {
-          gbit(cbuf,&start,(k+0)*8,4*8);
-          gbit(cbuf,&vers,(k+7)*8,1*8);
-          if (start==1196575042 && (vers==1 || vers==2)) {
-//  LOOK FOR '7777' AT END OF GRIB MESSAGE
-            if (vers == 1) gbit(cbuf,&lengrib,(k+4)*8,3*8);
-            if (vers == 2) gbit(cbuf,&lengrib,(k+12)*8,4*8);
-            ret=fseek(lugb,ipos+k+lengrib-4,SEEK_SET);
-            k4=fread(&end,sizeof(g2int),1,lugb);
-            if (k4 == 1 && end == 926365495) {      //GRIB message found
-                *lskip=ipos+k;
-                *lgrib=lengrib;
-                break;
-            }
-          }
-        }
-        ipos=ipos+lim;
-      }
-
-      free(cbuf);
-}
diff --git a/src/modules/io/io_grid_grib2/g2clib-1.0.4/simpack.c b/src/modules/io/io_grid_grib2/g2clib-1.0.4/simpack.c
deleted file mode 100644
index 8908310..0000000
--- a/src/modules/io/io_grid_grib2/g2clib-1.0.4/simpack.c
+++ /dev/null
@@ -1,184 +0,0 @@
-/**********************************************************
- * Version $Id: simpack.c 911 2011-02-14 16:38:15Z reklov_w $
- *********************************************************/
-#include <stdlib.h>
-#include <math.h>
-#include "grib2.h"
-
-
-void simpack(g2float *fld,g2int ndpts,g2int *idrstmpl,unsigned char *cpack,g2int *lcpack)
-//$$$  SUBPROGRAM DOCUMENTATION BLOCK
-//                .      .    .                                       .
-// SUBPROGRAM:    simpack
-//   PRGMMR: Gilbert          ORG: W/NP11    DATE: 2002-11-06
-//
-// ABSTRACT: This subroutine packs up a data field using the simple
-//   packing algorithm as defined in the GRIB2 documention.  It
-//   also fills in GRIB2 Data Representation Template 5.0 with the
-//   appropriate values.
-//
-// PROGRAM HISTORY LOG:
-// 2002-11-06  Gilbert
-//
-// USAGE:    CALL simpack(fld,ndpts,idrstmpl,cpack,lcpack)
-//   INPUT ARGUMENT LIST:
-//     fld[]    - Contains the data values to pack
-//     ndpts    - The number of data values in array fld[]
-//     idrstmpl - Contains the array of values for Data Representation
-//                Template 5.0
-//                [0] = Reference value - ignored on input
-//                [1] = Binary Scale Factor
-//                [2] = Decimal Scale Factor
-//                [3] = Number of bits used to pack data, if value is
-//                      > 0 and  <= 31.
-//                      If this input value is 0 or outside above range
-//                      then the num of bits is calculated based on given 
-//                      data and scale factors.
-//                [4] = Original field type - currently ignored on input
-//                      Data values assumed to be reals.
-//
-//   OUTPUT ARGUMENT LIST: 
-//     idrstmpl - Contains the array of values for Data Representation
-//                Template 5.0
-//                [0] = Reference value - set by simpack routine.
-//                [1] = Binary Scale Factor - unchanged from input
-//                [2] = Decimal Scale Factor - unchanged from input
-//                [3] = Number of bits used to pack data, unchanged from 
-//                      input if value is between 0 and 31.
-//                      If this input value is 0 or outside above range
-//                      then the num of bits is calculated based on given 
-//                      data and scale factors.
-//                [4] = Original field type - currently set = 0 on output.
-//                      Data values assumed to be reals.
-//     cpack    - The packed data field
-//     lcpack   - length of packed field starting at cpack.
-//
-// REMARKS: None
-//
-// ATTRIBUTES:
-//   LANGUAGE: C
-//   MACHINE:  
-//
-//$$$
-{
-
-      static g2int zero=0;
-      g2int  *ifld;
-      g2int  j,nbits,imin,imax,maxdif,nbittot,left;
-      g2float  bscale,dscale,rmax,rmin,temp;
-      double maxnum;
-      static g2float alog2=0.69314718;       //  ln(2.0)
-      
-      bscale=int_power(2.0,-idrstmpl[1]);
-      dscale=int_power(10.0,idrstmpl[2]);
-      if (idrstmpl[3] <= 0 || idrstmpl[3] > 31)
-         nbits=0;
-      else
-         nbits=idrstmpl[3];
-//
-//  Find max and min values in the data
-//
-      rmax=fld[0];
-      rmin=fld[0];
-      for (j=1;j<ndpts;j++) {
-        if (fld[j] > rmax) rmax=fld[j];
-        if (fld[j] < rmin) rmin=fld[j];
-      }
-     
-      ifld=calloc(ndpts,sizeof(g2int));
-//
-//  If max and min values are not equal, pack up field.
-//  If they are equal, we have a constant field, and the reference
-//  value (rmin) is the value for each point in the field and
-//  set nbits to 0.
-//
-      if (rmin != rmax) {
-        //
-        //  Determine which algorithm to use based on user-supplied 
-        //  binary scale factor and number of bits.
-        //
-        if (nbits==0 && idrstmpl[1]==0) {
-           //
-           //  No binary scaling and calculate minumum number of 
-           //  bits in which the data will fit.
-           //
-           imin=(g2int)rint(rmin*dscale);
-           imax=(g2int)rint(rmax*dscale);
-           maxdif=imax-imin;
-           temp=log((double)(maxdif+1))/alog2;
-           nbits=(g2int)ceil(temp);
-           rmin=(g2float)imin;
-           //   scale data
-           for(j=0;j<ndpts;j++)
-             ifld[j]=(g2int)rint(fld[j]*dscale)-imin;
-        }
-        else if (nbits!=0 && idrstmpl[1]==0) {
-           //
-           //  Use minimum number of bits specified by user and
-           //  adjust binary scaling factor to accomodate data.
-           //
-           rmin=rmin*dscale;
-           rmax=rmax*dscale;
-           maxnum=int_power(2.0,nbits)-1;
-           temp=log(maxnum/(rmax-rmin))/alog2;
-           idrstmpl[1]=(g2int)ceil(-1.0*temp);
-           bscale=int_power(2.0,-idrstmpl[1]);
-           //   scale data
-           for (j=0;j<ndpts;j++)
-             ifld[j]=(g2int)rint(((fld[j]*dscale)-rmin)*bscale);
-        }
-        else if (nbits==0 && idrstmpl[1]!=0) {
-           //
-           //  Use binary scaling factor and calculate minumum number of 
-           //  bits in which the data will fit.
-           //
-           rmin=rmin*dscale;
-           rmax=rmax*dscale;
-           maxdif=(g2int)rint((rmax-rmin)*bscale);
-           temp=log((double)(maxdif+1))/alog2;
-           nbits=(g2int)ceil(temp);
-           //   scale data
-           for (j=0;j<ndpts;j++)
-             ifld[j]=(g2int)rint(((fld[j]*dscale)-rmin)*bscale);
-        }
-        else if (nbits!=0 && idrstmpl[1]!=0) {
-           //
-           //  Use binary scaling factor and use minumum number of 
-           //  bits specified by user.   Dangerous - may loose
-           //  information if binary scale factor and nbits not set
-           //  properly by user.
-           //
-           rmin=rmin*dscale;
-           //   scale data
-           for (j=0;j<ndpts;j++)
-             ifld[j]=(g2int)rint(((fld[j]*dscale)-rmin)*bscale);
-        }
-        //
-        //  Pack data, Pad last octet with Zeros, if necessary,
-        //  and calculate the length of the packed data in bytes
-        //
-        sbits(cpack,ifld+0,0,nbits,0,ndpts);
-        nbittot=nbits*ndpts;
-        left=8-(nbittot%8);
-        if (left != 8) {
-          sbit(cpack,&zero,nbittot,left);   // Pad with zeros to fill Octet
-          nbittot=nbittot+left;
-        }
-        *lcpack=nbittot/8;
-      }
-      else {
-        nbits=0;
-        *lcpack=0;
-      }
-
-//
-//  Fill in ref value and number of bits in Template 5.0
-//
-      //printf("SAGmkieee %f\n",rmin);
-      mkieee(&rmin,idrstmpl+0,1);   // ensure reference value is IEEE format
-      //printf("SAGmkieee %ld\n",idrstmpl[0]);
-      idrstmpl[3]=nbits;
-      idrstmpl[4]=0;         // original data were reals
-
-      free(ifld);
-}
diff --git a/src/modules/io/io_grid_grib2/g2clib-1.0.4/simunpack.c b/src/modules/io/io_grid_grib2/g2clib-1.0.4/simunpack.c
deleted file mode 100644
index 7582052..0000000
--- a/src/modules/io/io_grid_grib2/g2clib-1.0.4/simunpack.c
+++ /dev/null
@@ -1,79 +0,0 @@
-/**********************************************************
- * Version $Id: simunpack.c 911 2011-02-14 16:38:15Z reklov_w $
- *********************************************************/
-#include <stdio.h>
-#include <stdlib.h>
-#include "grib2.h"
-
-
-g2int simunpack(unsigned char *cpack,g2int *idrstmpl,g2int ndpts,g2float *fld)
-////$$$  SUBPROGRAM DOCUMENTATION BLOCK
-//                .      .    .                                       .
-// SUBPROGRAM:    simunpack
-//   PRGMMR: Gilbert          ORG: W/NP11    DATE: 2002-10-29
-//
-// ABSTRACT: This subroutine unpacks a data field that was packed using a 
-//   simple packing algorithm as defined in the GRIB2 documention,
-//   using info from the GRIB2 Data Representation Template 5.0.
-//
-// PROGRAM HISTORY LOG:
-// 2002-10-29  Gilbert
-//
-// USAGE:    int simunpack(unsigned char *cpack,g2int *idrstmpl,g2int ndpts,
-//                         g2float *fld)
-//   INPUT ARGUMENT LIST:
-//     cpack    - pointer to the packed data field.
-//     idrstmpl - pointer to the array of values for Data Representation
-//                Template 5.0
-//     ndpts    - The number of data values to unpack
-//
-//   OUTPUT ARGUMENT LIST:
-//     fld      - Contains the unpacked data values.  fld must be allocated
-//                with at least ndpts*sizeof(g2float) bytes before
-//                calling this routine.
-//
-// REMARKS: None
-//
-// ATTRIBUTES:
-//   LANGUAGE: C
-//   MACHINE:  
-//
-//$$$//
-{
-
-      g2int  *ifld;
-      g2int  j,nbits,itype;
-      g2float ref,bscale,dscale;
-
-      
-      rdieee(idrstmpl+0,&ref,1);
-      bscale = int_power(2.0,idrstmpl[1]);
-      dscale = int_power(10.0,-idrstmpl[2]);
-      nbits = idrstmpl[3];
-      itype = idrstmpl[4];
-
-      ifld=(g2int *)calloc(ndpts,sizeof(g2int));
-      if ( ifld == 0 ) {
-         fprintf(stderr,"Could not allocate space in simunpack.\n  Data field NOT upacked.\n");
-         return(1);
-      }
-      
-//
-//  if nbits equals 0, we have a constant field where the reference value
-//  is the data value at each gridpoint
-//
-      if (nbits != 0) {
-         gbits(cpack,ifld,0,nbits,0,ndpts);
-         for (j=0;j<ndpts;j++) {
-           fld[j]=(((g2float)ifld[j]*bscale)+ref)*dscale;
-         }
-      }
-      else {
-         for (j=0;j<ndpts;j++) {
-           fld[j]=ref;
-         }
-      }
-
-      free(ifld);
-      return(0);
-}
diff --git a/src/modules/io/io_grid_grib2/g2clib-1.0.4/specpack.c b/src/modules/io/io_grid_grib2/g2clib-1.0.4/specpack.c
deleted file mode 100644
index 317c947..0000000
--- a/src/modules/io/io_grid_grib2/g2clib-1.0.4/specpack.c
+++ /dev/null
@@ -1,131 +0,0 @@
-/**********************************************************
- * Version $Id: specpack.c 911 2011-02-14 16:38:15Z reklov_w $
- *********************************************************/
-#include <stdio.h>
-#include <stdlib.h>
-#include <math.h>
-#include "grib2.h"
-
-
-void specpack(g2float *fld,g2int ndpts,g2int JJ,g2int KK,g2int MM,
-              g2int *idrstmpl,unsigned char *cpack,g2int *lcpack)
-//$$$  SUBPROGRAM DOCUMENTATION BLOCK
-//                .      .    .                                       .
-// SUBPROGRAM:    specpack
-//   PRGMMR: Gilbert          ORG: W/NP11    DATE: 2002-12-19
-//
-// ABSTRACT: This subroutine packs a spectral data field using the complex
-//   packing algorithm for spherical harmonic data as 
-//   defined in the GRIB2 Data Representation Template 5.51.
-//
-// PROGRAM HISTORY LOG:
-// 2002-12-19  Gilbert
-//
-// USAGE:    void specpack(g2float *fld,g2int ndpts,g2int JJ,g2int KK,g2int MM,
-//                        g2int *idrstmpl,insigned char *cpack,g2int *lcpack)
-//   INPUT ARGUMENT LIST:
-//     fld[]    - Contains the packed data values
-//     ndpts    - The number of data values to pack
-//     JJ       - J - pentagonal resolution parameter
-//     KK       - K - pentagonal resolution parameter
-//     MM       - M - pentagonal resolution parameter
-//     idrstmpl - Contains the array of values for Data Representation
-//                Template 5.51
-//
-//   OUTPUT ARGUMENT LIST:
-//     cpack    - The packed data field (character*1 array)
-//     lcpack   - length of packed field cpack().
-//
-// REMARKS: None
-//
-// ATTRIBUTES:
-//   LANGUAGE: C
-//   MACHINE:  IBM SP
-//
-//$$$
-{
-
-      g2int    *ifld,tmplsim[5];
-      g2float  bscale,dscale,*unpk,*tfld;
-      g2float  *pscale,tscale;
-      g2int    Js,Ks,Ms,Ts,Ns,inc,incu,incp,n,Nm,m,ipos;
-
-      bscale = int_power(2.0,-idrstmpl[1]);
-      dscale = int_power(10.0,idrstmpl[2]);
-      Js=idrstmpl[5];
-      Ks=idrstmpl[6];
-      Ms=idrstmpl[7];
-      Ts=idrstmpl[8];
-
-//
-//   Calculate Laplacian scaling factors for each possible wave number.
-//
-      pscale=(g2float *)malloc((JJ+MM)*sizeof(g2float));
-      tscale=(g2float)idrstmpl[4]*1E-6;
-      for (n=Js;n<=JJ+MM;n++)
-           pscale[n]=pow((g2float)(n*(n+1)),tscale);
-//
-//   Separate spectral coeffs into two lists; one to contain unpacked
-//   values within the sub-spectrum Js, Ks, Ms, and the other with values 
-//   outside of the sub-spectrum to be packed.
-//
-      tfld=(g2float *)malloc(ndpts*sizeof(g2float));
-      unpk=(g2float *)malloc(ndpts*sizeof(g2float));
-      ifld=(g2int *)malloc(ndpts*sizeof(g2int));
-      inc=0;
-      incu=0;
-      incp=0;
-      for (m=0;m<=MM;m++) {
-         Nm=JJ;      // triangular or trapezoidal
-         if ( KK == JJ+MM ) Nm=JJ+m;          // rhombodial
-         Ns=Js;      // triangular or trapezoidal
-         if ( Ks == Js+Ms ) Ns=Js+m;          // rhombodial
-         for (n=m;n<=Nm;n++) {
-            if (n<=Ns && m<=Ms) {       // save unpacked value
-               unpk[incu++]=fld[inc++];         // real part
-               unpk[incu++]=fld[inc++];     // imaginary part
-            }
-            else {                       // Save value to be packed and scale
-                                         // Laplacian scale factor
-               tfld[incp++]=fld[inc++]*pscale[n];      // real part
-               tfld[incp++]=fld[inc++]*pscale[n];      // imaginary part
-            }
-         }
-      }
-
-      free(pscale);
-
-      if (incu != Ts) {
-         printf("specpack: Incorrect number of unpacked values %d given:\n",(int)Ts);
-         printf("specpack: Resetting idrstmpl[8] to %d\n",(int)incu);
-         Ts=incu;
-      }
-//
-//  Add unpacked values to the packed data array in 32-bit IEEE format
-//
-      mkieee(unpk,(g2int *)cpack,Ts);
-      ipos=4*Ts;
-//
-//  Scale and pack the rest of the coefficients
-// 
-      tmplsim[1]=idrstmpl[1];
-      tmplsim[2]=idrstmpl[2];
-      tmplsim[3]=idrstmpl[3];
-      simpack(tfld,ndpts-Ts,tmplsim,cpack+ipos,lcpack);
-      *lcpack=(*lcpack)+ipos;
-//
-//  Fill in Template 5.51
-//
-      idrstmpl[0]=tmplsim[0];
-      idrstmpl[1]=tmplsim[1];
-      idrstmpl[2]=tmplsim[2];
-      idrstmpl[3]=tmplsim[3];
-      idrstmpl[8]=Ts;
-      idrstmpl[9]=1;         // Unpacked spectral data is 32-bit IEEE
-
-      free(tfld);
-      free(unpk);
-      free(ifld);
-
-      return;
-}
diff --git a/src/modules/io/io_grid_grib2/g2clib-1.0.4/specunpack.c b/src/modules/io/io_grid_grib2/g2clib-1.0.4/specunpack.c
deleted file mode 100644
index 07d1ffa..0000000
--- a/src/modules/io/io_grid_grib2/g2clib-1.0.4/specunpack.c
+++ /dev/null
@@ -1,118 +0,0 @@
-/**********************************************************
- * Version $Id: specunpack.c 911 2011-02-14 16:38:15Z reklov_w $
- *********************************************************/
-#include <stdio.h>
-#include <stdlib.h>
-#include <math.h>
-#include "grib2.h"
-
-
-g2int specunpack(unsigned char *cpack,g2int *idrstmpl,g2int ndpts,g2int JJ,
-               g2int KK, g2int MM, g2float *fld)
-//$$$  SUBPROGRAM DOCUMENTATION BLOCK
-//                .      .    .                                       .
-// SUBPROGRAM:    specunpack
-//   PRGMMR: Gilbert          ORG: W/NP11    DATE: 2000-06-21
-//
-// ABSTRACT: This subroutine unpacks a spectral data field that was packed 
-//   using the complex packing algorithm for spherical harmonic data as 
-//   defined in the GRIB2 documention,
-//   using info from the GRIB2 Data Representation Template 5.51.
-//
-// PROGRAM HISTORY LOG:
-// 2000-06-21  Gilbert
-//
-// USAGE:    int specunpack(unsigned char *cpack,g2int *idrstmpl,
-//                          g2int ndpts,g2int JJ,g2int KK,g2int MM,g2float *fld)
-//   INPUT ARGUMENT LIST:
-//     cpack    - pointer to the packed data field.
-//     idrstmpl - pointer to the array of values for Data Representation
-//                Template 5.51
-//     ndpts    - The number of data values to unpack (real and imaginary parts)
-//     JJ       - J - pentagonal resolution parameter
-//     KK       - K - pentagonal resolution parameter
-//     MM       - M - pentagonal resolution parameter
-//
-//   OUTPUT ARGUMENT LIST:
-//     fld()    - Contains the unpacked data values.   fld must be allocated
-//                with at least ndpts*sizeof(g2float) bytes before
-//                calling this routine.
-//
-// REMARKS: None
-//
-// ATTRIBUTES:
-//   LANGUAGE: C
-//   MACHINE:  
-//
-//$$$
-{
-
-      g2int  *ifld,j,iofst,nbits;
-      g2float  ref,bscale,dscale,*unpk;
-      g2float  *pscale,tscale;
-      g2int   Js,Ks,Ms,Ts,Ns,Nm,n,m;
-      g2int   inc,incu,incp;
-
-      rdieee(idrstmpl+0,&ref,1);
-      bscale = int_power(2.0,idrstmpl[1]);
-      dscale = int_power(10.0,-idrstmpl[2]);
-      nbits = idrstmpl[3];
-      Js=idrstmpl[5];
-      Ks=idrstmpl[6];
-      Ms=idrstmpl[7];
-      Ts=idrstmpl[8];
-
-      if (idrstmpl[9] == 1) {           // unpacked floats are 32-bit IEEE
-
-         unpk=(g2float *)malloc(ndpts*sizeof(g2float));
-         ifld=(g2int *)malloc(ndpts*sizeof(g2int));
-
-         gbits(cpack,ifld,0,32,0,Ts);
-         iofst=32*Ts;
-         rdieee(ifld,unpk,Ts);          // read IEEE unpacked floats
-         gbits(cpack,ifld,iofst,nbits,0,ndpts-Ts);  // unpack scaled data
-//
-//   Calculate Laplacian scaling factors for each possible wave number.
-//
-         pscale=(g2float *)malloc((JJ+MM+1)*sizeof(g2float));
-         tscale=(g2float)idrstmpl[4]*1E-6;
-         for (n=Js;n<=JJ+MM;n++) 
-              pscale[n]=pow((g2float)(n*(n+1)),-tscale);
-//
-//   Assemble spectral coeffs back to original order.
-//
-         inc=0;
-         incu=0;
-         incp=0;
-         for (m=0;m<=MM;m++) {
-            Nm=JJ;      // triangular or trapezoidal
-            if ( KK == JJ+MM ) Nm=JJ+m;          // rhombodial
-            Ns=Js;      // triangular or trapezoidal
-            if ( Ks == Js+Ms ) Ns=Js+m;          // rhombodial
-            for (n=m;n<=Nm;n++) {
-               if (n<=Ns && m<=Ms) {    // grab unpacked value
-                  fld[inc++]=unpk[incu++];         // real part
-                  fld[inc++]=unpk[incu++];     // imaginary part
-               }
-               else {                       // Calc coeff from packed value
-                  fld[inc++]=(((g2float)ifld[incp++]*bscale)+ref)*
-                            dscale*pscale[n];          // real part
-                  fld[inc++]=(((g2float)ifld[incp++]*bscale)+ref)*
-                            dscale*pscale[n];          // imaginary part
-               }
-            }
-         }
-
-         free(pscale);
-         free(unpk);
-         free(ifld);
-
-      }
-      else {
-         printf("specunpack: Cannot handle 64 or 128-bit floats.\n");
-         for (j=0;j<ndpts;j++) fld[j]=0.0;
-         return -3;
-      }
-
-      return 0;
-}
diff --git a/src/modules/io/io_table/io_table_txt.cpp b/src/modules/io/io_table/io_table_txt.cpp
index ee7a4e9..253b31b 100644
--- a/src/modules/io/io_table/io_table_txt.cpp
+++ b/src/modules/io/io_table/io_table_txt.cpp
@@ -256,7 +256,7 @@ CTable_Text_Import::CTable_Text_Import(void)
 	pNode	= Parameters.Add_Choice(
 		NULL	, "SEPARATOR"	, _TL("Separator"),
 		_TL(""),
-		CSG_String::Format(SG_T("%s|%s|%s|%s|%s|"),
+		CSG_String::Format("%s|%s|%s|%s|%s|",
 			_TL("tabulator"),
 			SG_T(";"),
 			SG_T(","),
@@ -274,7 +274,7 @@ CTable_Text_Import::CTable_Text_Import(void)
 	Parameters.Add_FilePath(
 		NULL	, "FILENAME"	, _TL("File"),
 		_TL(""),
-		CSG_String::Format(SG_T("%s|%s|%s|%s|%s|%s"),
+		CSG_String::Format("%s|%s|%s|%s|%s|%s",
 			_TL("Text Files (*.txt)")	, SG_T("*.txt"),
 			_TL("CSV Files (*.csv)")	, SG_T("*.csv"),
 			_TL("All Files")			, SG_T("*.*")
@@ -283,20 +283,31 @@ CTable_Text_Import::CTable_Text_Import(void)
 }
 
 //---------------------------------------------------------
+int CTable_Text_Import::On_Parameters_Enable(CSG_Parameters *pParameters, CSG_Parameter *pParameter)
+{
+	if( !SG_STR_CMP(pParameter->Get_Identifier(), "SEPARATOR") )
+	{
+		pParameters->Set_Enabled("SEP_OTHER", pParameter->asInt() >= 4);
+	}
+
+	return( CSG_Module::On_Parameters_Enable(pParameters, pParameter) );
+}
+
+//---------------------------------------------------------
 bool CTable_Text_Import::On_Execute(void)
 {
 	//-----------------------------------------------------
 	CSG_Table	*pTable	= Parameters("TABLE")->asTable();
 
-	CSG_String	Separator;
+	SG_Char	Separator;
 
 	switch( Parameters("SEPARATOR")->asInt() )
 	{
-	case  0:	Separator	= "\t";	break;
-	case  1:	Separator	=  ";";	break;
-	case  2:	Separator	=  ",";	break;
-	case  3:	Separator	=  " ";	break;
-	default:	Separator	= Parameters("SEP_OTHER")->asString();	break;
+	case  0:	Separator	= '\t';	break;
+	case  1:	Separator	=  ';';	break;
+	case  2:	Separator	=  ',';	break;
+	case  3:	Separator	=  ' ';	break;
+	default:	Separator	= *Parameters("SEP_OTHER")->asString();	break;
 	}
 
 	//-----------------------------------------------------
@@ -353,7 +364,7 @@ CTable_Text_Import_Numbers::CTable_Text_Import_Numbers(void)
 	pNode	= Parameters.Add_Choice(
 		NULL	, "SEPARATOR"	, _TL("Separator"),
 		_TL(""),
-		CSG_String::Format(SG_T("%s|%s|%s|%s|%s|"),
+		CSG_String::Format("%s|%s|%s|%s|%s|",
 			_TL("tabulator"),
 			SG_T(";"),
 			SG_T(","),
@@ -371,7 +382,7 @@ CTable_Text_Import_Numbers::CTable_Text_Import_Numbers(void)
 	Parameters.Add_FilePath(
 		NULL	, "FILENAME"	, _TL("File"),
 		_TL(""),
-		CSG_String::Format(SG_T("%s|%s|%s|%s|%s|%s"),
+		CSG_String::Format("%s|%s|%s|%s|%s|%s",
 			_TL("Text Files (*.txt)")	, SG_T("*.txt"),
 			_TL("CSV Files (*.csv)")	, SG_T("*.csv"),
 			_TL("All Files")			, SG_T("*.*")
@@ -380,6 +391,17 @@ CTable_Text_Import_Numbers::CTable_Text_Import_Numbers(void)
 }
 
 //---------------------------------------------------------
+int CTable_Text_Import_Numbers::On_Parameters_Enable(CSG_Parameters *pParameters, CSG_Parameter *pParameter)
+{
+	if( !SG_STR_CMP(pParameter->Get_Identifier(), "SEPARATOR") )
+	{
+		pParameters->Set_Enabled("SEP_OTHER", pParameter->asInt() >= 4);
+	}
+
+	return( CSG_Module::On_Parameters_Enable(pParameters, pParameter) );
+}
+
+//---------------------------------------------------------
 bool CTable_Text_Import_Numbers::On_Execute(void)
 {
 	CSG_String	sHead, sLine, Separator;
diff --git a/src/modules/io/io_table/io_table_txt.h b/src/modules/io/io_table/io_table_txt.h
index f655505..c7ed610 100644
--- a/src/modules/io/io_table/io_table_txt.h
+++ b/src/modules/io/io_table/io_table_txt.h
@@ -92,10 +92,15 @@ public:
 
 protected:
 
-	virtual bool			On_Execute(void);
+	virtual bool			On_Execute				(void);
 
 };
 
+
+///////////////////////////////////////////////////////////
+//														 //
+///////////////////////////////////////////////////////////
+
 //---------------------------------------------------------
 class CTable_Text_Import : public CSG_Module  
 {
@@ -107,10 +112,17 @@ public:
 
 protected:
 
-	virtual bool			On_Execute(void);
+	virtual int				On_Parameters_Enable	(CSG_Parameters *pParameters, CSG_Parameter *pParameter);
+
+	virtual bool			On_Execute				(void);
 
 };
 
+
+///////////////////////////////////////////////////////////
+//														 //
+///////////////////////////////////////////////////////////
+
 //---------------------------------------------------------
 class CTable_Text_Import_Numbers : public CSG_Module  
 {
@@ -122,10 +134,17 @@ public:
 
 protected:
 
-	virtual bool			On_Execute(void);
+	virtual int				On_Parameters_Enable	(CSG_Parameters *pParameters, CSG_Parameter *pParameter);
+
+	virtual bool			On_Execute				(void);
 
 };
 
+
+///////////////////////////////////////////////////////////
+//														 //
+///////////////////////////////////////////////////////////
+
 //---------------------------------------------------------
 class CTable_Text_Import_Fixed_Cols : public CSG_Module  
 {
@@ -137,10 +156,10 @@ public:
 
 protected:
 
-	virtual bool			On_Execute(void);
-
 	virtual int				On_Parameters_Enable	(CSG_Parameters *pParameters, CSG_Parameter *pParameter);
 
+	virtual bool			On_Execute				(void);
+
 };
 
 
diff --git a/src/modules/shapes/shapes_polygons/Polygon_StatisticsFromPoints.cpp b/src/modules/shapes/shapes_polygons/Polygon_StatisticsFromPoints.cpp
index 8daea9e..acedd4a 100644
--- a/src/modules/shapes/shapes_polygons/Polygon_StatisticsFromPoints.cpp
+++ b/src/modules/shapes/shapes_polygons/Polygon_StatisticsFromPoints.cpp
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: Polygon_StatisticsFromPoints.cpp 2072 2014-03-31 08:50:43Z reklov_w $
+ * Version $Id: Polygon_StatisticsFromPoints.cpp 2689 2015-11-16 12:56:48Z reklov_w $
  *********************************************************/
 /*******************************************************************************
     CPolygonStatisticsFromPoints.cpp
@@ -157,17 +157,17 @@ bool CPolygonStatisticsFromPoints::On_Execute(void)
 	//-----------------------------------------------------
 	int		i, n, Offset	= pPolygons->Get_Field_Count();
 
-	for(i=0, n=0; i<pFields->Get_Count(); i++)
+	for(i=0; i<pFields->Get_Count(); i++)
 	{
 		CSG_String	sName	= pPoints->Get_Field_Name(pFields->Get_Index(i));
 
-		if( bSum )	{	pPolygons->Add_Field(Get_Field_Name("SUM", sName), SG_DATATYPE_Double);	n++;	}
-		if( bAvg )	{	pPolygons->Add_Field(Get_Field_Name("AVG", sName), SG_DATATYPE_Double);	n++;	}
-		if( bVar )	{	pPolygons->Add_Field(Get_Field_Name("VAR", sName), SG_DATATYPE_Double);	n++;	}
-		if( bDev )	{	pPolygons->Add_Field(Get_Field_Name("DEV", sName), SG_DATATYPE_Double);	n++;	}
-		if( bMin )	{	pPolygons->Add_Field(Get_Field_Name("MIN", sName), SG_DATATYPE_Double);	n++;	}
-		if( bMax )	{	pPolygons->Add_Field(Get_Field_Name("MAX", sName), SG_DATATYPE_Double);	n++;	}
-		if( bNum )	{	pPolygons->Add_Field(Get_Field_Name("NUM", sName), SG_DATATYPE_Int   );	n++;	}
+		if( bSum )	{	pPolygons->Add_Field(Get_Field_Name("SUM", sName), SG_DATATYPE_Double);	}
+		if( bAvg )	{	pPolygons->Add_Field(Get_Field_Name("AVG", sName), SG_DATATYPE_Double);	}
+		if( bVar )	{	pPolygons->Add_Field(Get_Field_Name("VAR", sName), SG_DATATYPE_Double);	}
+		if( bDev )	{	pPolygons->Add_Field(Get_Field_Name("DEV", sName), SG_DATATYPE_Double);	}
+		if( bMin )	{	pPolygons->Add_Field(Get_Field_Name("MIN", sName), SG_DATATYPE_Double);	}
+		if( bMax )	{	pPolygons->Add_Field(Get_Field_Name("MAX", sName), SG_DATATYPE_Double);	}
+		if( bNum )	{	pPolygons->Add_Field(Get_Field_Name("NUM", sName), SG_DATATYPE_Long  );	}
 	}
 
 	//-----------------------------------------------------
@@ -178,7 +178,7 @@ bool CPolygonStatisticsFromPoints::On_Execute(void)
 		CSG_Shape_Polygon	*pPolygon	= (CSG_Shape_Polygon *)pPolygons->Get_Shape(iPolygon);
 
 		//-------------------------------------------------
-		for(i=0; i<pFields->Get_Index(i); i++)
+		for(i=0; i<pFields->Get_Count(); i++)
 		{
 			Statistics[i].Invalidate();
 		}
@@ -201,17 +201,17 @@ bool CPolygonStatisticsFromPoints::On_Execute(void)
 		}
 
 		//-------------------------------------------------
-		for(i=0, n=Offset; i<pFields->Get_Index(i); i++)
+		for(i=0, n=Offset; i<pFields->Get_Count(); i++)
 		{
 			if( Statistics[i].Get_Count() > 0 )
 			{
-				if( bSum )	{	pPolygon->Set_Value (n++, Statistics[i].Get_Sum());			}
-				if( bAvg )	{	pPolygon->Set_Value (n++, Statistics[i].Get_Mean());		}
-				if( bVar )	{	pPolygon->Set_Value (n++, Statistics[i].Get_Variance());	}
-				if( bDev )	{	pPolygon->Set_Value (n++, Statistics[i].Get_StdDev());		}
-				if( bMin )	{	pPolygon->Set_Value (n++, Statistics[i].Get_Minimum());		}
-				if( bMax )	{	pPolygon->Set_Value (n++, Statistics[i].Get_Maximum());		}
-				if( bNum )	{	pPolygon->Set_Value (n++, Statistics[i].Get_Count());		}
+				if( bSum )	{	pPolygon->Set_Value (n++, Statistics[i].Get_Sum());				}
+				if( bAvg )	{	pPolygon->Set_Value (n++, Statistics[i].Get_Mean());			}
+				if( bVar )	{	pPolygon->Set_Value (n++, Statistics[i].Get_Variance());		}
+				if( bDev )	{	pPolygon->Set_Value (n++, Statistics[i].Get_StdDev());			}
+				if( bMin )	{	pPolygon->Set_Value (n++, Statistics[i].Get_Minimum());			}
+				if( bMax )	{	pPolygon->Set_Value (n++, Statistics[i].Get_Maximum());			}
+				if( bNum )	{	pPolygon->Set_Value (n++, (double)Statistics[i].Get_Count());	}
 			}
 			else
 			{
diff --git a/src/modules/shapes/shapes_tools/GraticuleBuilder.cpp b/src/modules/shapes/shapes_tools/GraticuleBuilder.cpp
index a8058e3..51cd1f6 100644
--- a/src/modules/shapes/shapes_tools/GraticuleBuilder.cpp
+++ b/src/modules/shapes/shapes_tools/GraticuleBuilder.cpp
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: GraticuleBuilder.cpp 2072 2014-03-31 08:50:43Z reklov_w $
+ * Version $Id: GraticuleBuilder.cpp 2661 2015-10-28 09:40:58Z oconrad $
  *********************************************************/
 /*******************************************************************************
     GraticuleBuilder.cpp
@@ -41,106 +41,195 @@ CGraticuleBuilder::CGraticuleBuilder(void)
 {
 	Set_Name		(_TL("Create Graticule"));
 
-	Set_Author		(SG_T("V.Olaya (c) 2004"));
+	Set_Author		("V.Olaya (c) 2004");
 
 	Set_Description	(_TW(
 		"(c) 2004 by Victor Olaya. "
 	));
 
+	//-----------------------------------------------------
 	Parameters.Add_Shapes(
-		NULL	, "GRATICULE"	, _TL("Graticule"),
+		NULL	, "GRATICULE_LINE"	, _TL("Graticule"),
 		_TL(""),
-		PARAMETER_OUTPUT
+		PARAMETER_OUTPUT, SHAPE_TYPE_Line
 	);
 
 	Parameters.Add_Shapes(
-		NULL	, "EXTENT"		, _TL("Extent"), 
+		NULL	, "GRATICULE_RECT"	, _TL("Graticule"),
+		_TL(""),
+		PARAMETER_OUTPUT, SHAPE_TYPE_Polygon
+	);
+
+	Parameters.Add_Choice(
+		NULL	, "TYPE"			, _TL("Type"),
+		_TL(""),
+		CSG_String::Format("%s|%s|",
+			_TL("Lines"),
+			_TL("Rectangles")
+		), 0
+	);
+
+	//-----------------------------------------------------
+	Parameters.Add_Shapes(
+		NULL	, "EXTENT"			, _TL("Extent"), 
 		_TL(""),
 		PARAMETER_INPUT_OPTIONAL
 	);
 				
 	Parameters.Add_Range(
-		NULL	, "X_EXTENT"	, _TL("Width"),
+		NULL	, "EXTENT_X"		, _TL("Width"),
 		_TL(""),
 		-180.0, 180.0
 	);
 
 	Parameters.Add_Range(
-		NULL	, "Y_EXTENT"	, _TL("Height"),
+		NULL	, "EXTENT_Y"		, _TL("Height"),
 		_TL(""),
 		-90.0, 90.0
 	);
 
 	Parameters.Add_Value(
-		NULL	, "DISTX"		, _TL("Division Width"),
+		NULL	, "DIVISION_X"		, _TL("Division Width"),
 		_TL(""), 
-		PARAMETER_TYPE_Double, 10
+		PARAMETER_TYPE_Double, 10.0, 0.0, true
 	);
 
 	Parameters.Add_Value(
-		NULL	, "DISTY"		, _TL("Division Height"),
+		NULL	, "DIVISION_Y"		, _TL("Division Height"),
 		_TL(""), 
-		PARAMETER_TYPE_Double, 10
+		PARAMETER_TYPE_Double, 10.0, 0.0, true
 	);
 
 	Parameters.Add_Choice(
-		NULL	, "TYPE"		, _TL("Type"),
-		_TL(""),
-		CSG_String::Format(SG_T("%s|%s|"),
-			_TL("Lines"),
-			_TL("Rectangles")
+		NULL	, "ALIGNMENT"		, _TL("Alignment"),
+		_TL("Determines how the graticule is aligned to the extent, if division sizes do not fit."), 
+		CSG_String::Format("%s|%s|%s|%s|%s|",
+			_TL("bottom-left"),
+			_TL("top-left"),
+			_TL("bottom-right"),
+			_TL("top-right"),
+			_TL("centered")
 		), 0
 	);
 }
 
+
+///////////////////////////////////////////////////////////
+//                                                       //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+int CGraticuleBuilder::On_Parameter_Changed(CSG_Parameters *pParameters, CSG_Parameter *pParameter)
+{
+	return( CSG_Module::On_Parameter_Changed(pParameters, pParameter) );
+}
+
 //---------------------------------------------------------
-CGraticuleBuilder::~CGraticuleBuilder(void)
-{}
+int CGraticuleBuilder::On_Parameters_Enable(CSG_Parameters *pParameters, CSG_Parameter *pParameter)
+{
+	if( !SG_STR_CMP(pParameter->Get_Identifier(), "TYPE") )
+	{
+		pParameters->Set_Enabled("GRATICULE_LINE", pParameter->asInt() == 0);
+		pParameters->Set_Enabled("GRATICULE_RECT", pParameter->asInt() != 0);
+	}
+
+	if( !SG_STR_CMP(pParameter->Get_Identifier(), "EXTENT") )
+	{
+		pParameters->Set_Enabled("EXTENT_X", pParameter->asShapes() == NULL);
+		pParameters->Set_Enabled("EXTENT_Y", pParameter->asShapes() == NULL);
+	}
+
+	return( CSG_Module::On_Parameters_Enable(pParameters, pParameter) );
+}
 
 
 ///////////////////////////////////////////////////////////
 //                                                       //
-//                                                       //
-//                                                       //
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
 bool CGraticuleBuilder::On_Execute(void)
 {
 	//-----------------------------------------------------
-	CSG_Rect	Extent;
+	TSG_Rect	Extent;
 	
 	if( Parameters("EXTENT")->asShapes() )
 	{
-		Extent.Assign(Parameters("EXTENT")->asShapes()->Get_Extent());
+		Extent		= Parameters("EXTENT")->asShapes()->Get_Extent();
 	}
 	else
 	{
-		Extent.Assign(
-			Parameters("X_EXTENT")->asRange()->Get_LoVal(),
-			Parameters("Y_EXTENT")->asRange()->Get_LoVal(),
-			Parameters("X_EXTENT")->asRange()->Get_HiVal(),
-			Parameters("Y_EXTENT")->asRange()->Get_HiVal()
-		);
+		Extent.xMin	= Parameters("EXTENT_X")->asRange()->Get_LoVal();
+		Extent.yMin	= Parameters("EXTENT_Y")->asRange()->Get_LoVal();
+		Extent.xMax	= Parameters("EXTENT_X")->asRange()->Get_HiVal();
+		Extent.yMax	= Parameters("EXTENT_Y")->asRange()->Get_HiVal();
 	}
 
-	//-----------------------------------------------------
-	int			id	= 0, row, col;
-	double		x, y, dx, dy;
-	CSG_Shapes	*pGraticule;
+	if( Extent.xMin >= Extent.xMax || Extent.yMin >= Extent.yMax )
+	{
+		Error_Set(_TL("invalid extent"));
 
-	pGraticule	= Parameters("GRATICULE")	->asShapes();
-	dx			= Parameters("DISTX")		->asDouble();
-	dy			= Parameters("DISTY")		->asDouble();
+		return( false );
+	}
 
 	//-----------------------------------------------------
-	if( dx <= 0.0 || dx > Extent.Get_XRange() || dy <= 0.0 || dy > Extent.Get_YRange() )
+	double	dx	= Parameters("DIVISION_X")->asDouble();
+	double	dy	= Parameters("DIVISION_Y")->asDouble();
+
+	if( dx <= 0.0 || dy <= 0.0 )
 	{
 		Error_Set(_TL("invalid division size"));
 
 		return( false );
 	}
 
+	//-----------------------------------------------------
+	int	nx	= (int)ceil((Extent.xMax - Extent.xMin) / dx);
+	int	ny	= (int)ceil((Extent.yMax - Extent.yMin) / dy);
+
+	switch( Parameters("ALIGNMENT")->asInt() )
+	{
+	default:	// bottom-left
+	//	Extent.xMax	= Extent.xMin + nx * dx;
+	//	Extent.yMax	= Extent.yMin + ny * dy;
+		break;
+
+	case  1:	// top-left
+	//	Extent.xMax	= Extent.xMin + nx * dx;
+		Extent.yMin	= Extent.yMax - ny * dy;
+		break;
+
+	case  2:	// bottom-right
+		Extent.xMin	= Extent.xMax - nx * dx;
+	//	Extent.yMax	= Extent.yMin + ny * dy;
+		break;
+
+	case  3:	// top-right
+		Extent.xMin	= Extent.xMax - nx * dx;
+		Extent.yMin	= Extent.yMax - ny * dy;
+		break;
+
+	case  4:	// centered
+		{
+			double	cx	= Extent.xMin + (Extent.xMax - Extent.xMin) / 2.0;
+			double	cy	= Extent.yMin + (Extent.yMax - Extent.yMin) / 2.0;
+
+			Extent.xMin	= cx - nx * dx / 2.0;
+			Extent.yMin	= cy - ny * dy / 2.0;
+		//	Extent.xMax	= cx + nx * dx / 2.0;
+		//	Extent.yMax	= cy + ny * dy / 2.0;
+		}
+		break;
+	}
+
+	//-----------------------------------------------------
+	CSG_Shapes	*pGraticule	= Parameters("TYPE")->asInt() == 0
+		? Parameters("GRATICULE_LINE")->asShapes()
+		: Parameters("GRATICULE_RECT")->asShapes();
+
+	int			x, y;
+	TSG_Point	p;
+
 	switch( Parameters("TYPE")->asInt() )
 	{
 	//-----------------------------------------------------
@@ -150,31 +239,29 @@ bool CGraticuleBuilder::On_Execute(void)
 
 			pGraticule->Add_Field("ID", SG_DATATYPE_Int);
 
-			for(x=Extent.Get_XMin(); x<=Extent.Get_XMax(); x+=dx)
+			for(x=0, p.x=Extent.xMin; x<=nx; x++, p.x+=dx)
 			{
-				CSG_Shape	*pShape	= pGraticule->Add_Shape();
+				CSG_Shape	*pLine	= pGraticule->Add_Shape();
 
-				pShape->Set_Value(0, ++id);
+				pLine->Set_Value(0, pGraticule->Get_Count());
 
-				for(y=Extent.Get_YMin(); y<=Extent.Get_YMax(); y+=dy)
+				for(y=0, p.y=Extent.yMin; y<=ny; y++, p.y+=dy)
 				{
-					pShape->Add_Point(x,y);
-					pShape->Add_Point(x,y);
+					pLine->Add_Point(p.x, p.y);
 				}
-			}//for
+			}
 
-			for(y=Extent.Get_YMin(); y<=Extent.Get_YMax(); y+=dy)
+			for(y=0, p.y=Extent.yMin; y<=ny; y++, p.y+=dy)
 			{
-				CSG_Shape	*pShape	= pGraticule->Add_Shape();
+				CSG_Shape	*pLine	= pGraticule->Add_Shape();
 
-				pShape->Set_Value(0, ++id);
+				pLine->Set_Value(0, pGraticule->Get_Count());
 
-				for(x=Extent.Get_XMin(); x<=Extent.Get_XMax(); x+=dx)
+				for(x=0, p.x=Extent.xMin; x<=nx; x++, p.x+=dx)
 				{
-					pShape->Add_Point(x,y);
-					pShape->Add_Point(x,y);
+					pLine->Add_Point(p.x, p.y);
 				}
-			}//for
+			}
 		}
 		break;
 
@@ -186,24 +273,24 @@ bool CGraticuleBuilder::On_Execute(void)
 			pGraticule->Add_Field("ID" , SG_DATATYPE_Int);
 			pGraticule->Add_Field("ROW", SG_DATATYPE_Int);
 			pGraticule->Add_Field("COL", SG_DATATYPE_Int);
-		//	pGraticule->Add_Field("LNK", SG_DATATYPE_String);
 
-			for(x=Extent.Get_XMin(), row=1; x<Extent.Get_XMax(); x+=dx, row++)
+			for(y=0, p.y=Extent.yMin; y<ny; y++, p.y+=dy)
 			{
-				for(y=Extent.Get_YMax(), col=1; y>Extent.Get_YMin(); y-=dy, col++)
+				p.x	= Extent.xMin;
+
+				for(x=0, p.x=Extent.xMin; x<nx; x++, p.x+=dx)
 				{
-					CSG_Shape	*pShape	= pGraticule->Add_Shape();
-
-					pShape->Set_Value(0, ++id);
-					pShape->Set_Value(1, row);
-					pShape->Set_Value(2, col);
-		//			pShape->Set_Value(3, CSG_String::Format(SG_T("ftp://xftp.jrc.it/pub/srtmV4/tiff/srtm_%02d_%02d.zip"), row, col));
-
-					pShape->Add_Point(x     , y     );
-					pShape->Add_Point(x     , y - dy);
-					pShape->Add_Point(x + dx, y - dy);
-					pShape->Add_Point(x + dx, y     );
-					pShape->Add_Point(x     , y     );
+					CSG_Shape	*pRect	= pGraticule->Add_Shape();
+
+					pRect->Set_Value(0, pGraticule->Get_Count());
+					pRect->Set_Value(1, 1 + y);
+					pRect->Set_Value(2, 1 + x);
+
+					pRect->Add_Point(p.x     , p.y     );
+					pRect->Add_Point(p.x     , p.y + dy);
+					pRect->Add_Point(p.x + dx, p.y + dy);
+					pRect->Add_Point(p.x + dx, p.y     );
+					pRect->Add_Point(p.x     , p.y     );
 				}
 			}
 		}
diff --git a/src/modules/shapes/shapes_tools/GraticuleBuilder.h b/src/modules/shapes/shapes_tools/GraticuleBuilder.h
index 199e379..bd2e8ce 100644
--- a/src/modules/shapes/shapes_tools/GraticuleBuilder.h
+++ b/src/modules/shapes/shapes_tools/GraticuleBuilder.h
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: GraticuleBuilder.h 2072 2014-03-31 08:50:43Z reklov_w $
+ * Version $Id: GraticuleBuilder.h 2661 2015-10-28 09:40:58Z oconrad $
  *********************************************************/
 /*******************************************************************************
     GraticuleBuilder.cpp
@@ -24,18 +24,44 @@
 #pragma once
 #endif // _MSC_VER > 1000
 
+
+///////////////////////////////////////////////////////////
+//                                                       //
+//                                                       //
+//                                                       //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
 #include "MLB_Interface.h"
 
-class CGraticuleBuilder : public CSG_Module {
 
+///////////////////////////////////////////////////////////
+//                                                       //
+//                                                       //
+//                                                       //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+class CGraticuleBuilder : public CSG_Module
+{
 public:
 	CGraticuleBuilder(void);
-	virtual ~CGraticuleBuilder(void);
-	virtual bool is_ProjectDependent(void) {return( false );}
-
 
 
 protected:
-	virtual bool On_Execute(void);
+
+	virtual int			On_Parameter_Changed	(CSG_Parameters *pParameters, CSG_Parameter *pParameter);
+	virtual int			On_Parameters_Enable	(CSG_Parameters *pParameters, CSG_Parameter *pParameter);
+
+	virtual bool		On_Execute				(void);
 
 };
+
+
+///////////////////////////////////////////////////////////
+//                                                       //
+//                                                       //
+//                                                       //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
diff --git a/src/modules/simulation/Makefile.am b/src/modules/simulation/Makefile.am
index 1d005e7..ac1e638 100644
--- a/src/modules/simulation/Makefile.am
+++ b/src/modules/simulation/Makefile.am
@@ -1 +1 @@
-SUBDIRS = sim_cellular_automata sim_ecosystems_hugget sim_erosion sim_fire_spreading sim_hydrology sim_ihacres sim_rivflow
+SUBDIRS = sim_cellular_automata sim_ecosystems_hugget sim_erosion sim_fire_spreading sim_hydrology sim_ihacres sim_qm_of_esp sim_rivflow
diff --git a/src/modules/simulation/Makefile.in b/src/modules/simulation/Makefile.in
index 35c2fef..b5eb7b9 100644
--- a/src/modules/simulation/Makefile.in
+++ b/src/modules/simulation/Makefile.in
@@ -322,7 +322,7 @@ target_alias = @target_alias@
 top_build_prefix = @top_build_prefix@
 top_builddir = @top_builddir@
 top_srcdir = @top_srcdir@
-SUBDIRS = sim_cellular_automata sim_ecosystems_hugget sim_erosion sim_fire_spreading sim_hydrology sim_ihacres sim_rivflow
+SUBDIRS = sim_cellular_automata sim_ecosystems_hugget sim_erosion sim_fire_spreading sim_hydrology sim_ihacres sim_qm_of_esp sim_rivflow
 all: all-recursive
 
 .SUFFIXES:
diff --git a/src/modules/simulation/sim_fire_spreading/Forecasting.cpp b/src/modules/simulation/sim_fire_spreading/Forecasting.cpp
deleted file mode 100644
index 82ed1f9..0000000
--- a/src/modules/simulation/sim_fire_spreading/Forecasting.cpp
+++ /dev/null
@@ -1,666 +0,0 @@
-/**********************************************************
- * Version $Id: Forecasting.cpp 911 2011-02-14 16:38:15Z reklov_w $
- *********************************************************/
-/*******************************************************************************
-    Forecasting.cpp
-    Copyright (C) Victor Olaya
-    
-    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 2 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, write to the Free Software
-    Foundation, Inc., 51 Franklin Street, 5th Floor, Boston, MA 02110-1301, USA
-*******************************************************************************/ 
-
-//#include "../../../modules/grid/grid_tools/Grid_Gaps.h"
-
-#include "Forecasting.h"
-
-#include <time.h>
-
-#define MS2FTMIN (60.0 / 0.3048)
-#define FTMIN2MMIN 0.3048
-#define MIN_RATIO_BURNT_AREA 2.
-
-CForecasting::CForecasting(void){
-
-	Set_Name		(_TL("Fire Risk Analysis"));
-	Set_Author		(SG_T("(c) 2004 Victor Olaya"));
-	Set_Description	(_TW(
-		"Fire risk analysis based on the BEHAVE fire modeling system "
-		"supported by the U.S. Forest Service, Fire and Aviation Management. "
-		"Find more information on BEHAVE at the <i>Public Domain Software for the Wildland Fire Community</i> at "
-		"<a target=\"_blank\" href=\"http://fire.org\">http://fire.org</a>\n"
-		"\n"
-		"Reference:\n"
-		"Andrews, P.L. (1986): BEHAVE: Fire Behavior Prediction and Fuel Modeling System - "
-		"Burn Subsystem, Part 1. U.S. Department of Agriculture, Forest Service General, Technical Report INT-194. "
-	));
-
-	Parameters.Add_Grid(NULL, 
-						"DEM", 
-						_TL("DEM"), 
-						_TL(""), 
-						PARAMETER_INPUT);
-
-	Parameters.Add_Grid(NULL, 
-						"FUEL", 
-						_TL("Fuel Model"), 
-						_TL(""), 
-						PARAMETER_INPUT);
-
-	Parameters.Add_Grid(NULL, 
-						"WINDSPD", 
-						_TL("Wind Speed"),
-						_TL("Wind Speed (m/s)"), 
-						PARAMETER_INPUT);
-	
-	Parameters.Add_Grid(NULL, 
-						"WINDDIR", 
-						_TL("Wind Direction"), 
-						_TL("Wind Direction (degrees clockwise from north)"),
-						PARAMETER_INPUT);
-
-	Parameters.Add_Grid(NULL, 
-						"M1H", 
-						_TL("Dead Fuel Moisture 1H"), 
-						_TL(""), 
-						PARAMETER_INPUT);
-
-	Parameters.Add_Grid(NULL, 
-						"M10H", 
-						_TL("Dead Fuel Moisture 10H"),
-						_TL(""), 
-						PARAMETER_INPUT);
-
-	Parameters.Add_Grid(NULL, 
-						"M100H", 
-						_TL("Dead Fuel Moisture 100H"),
-						_TL(""), 
-						PARAMETER_INPUT);
-
-	Parameters.Add_Grid(NULL, 
-						"MHERB", 
-						_TL("Herbaceous Fuel Moisture"),
-						_TL(""), 
-						PARAMETER_INPUT);
-
-	Parameters.Add_Grid(NULL, 
-						"MWOOD", 
-						_TL("Wood Fuel Moisture"), 
-						_TL(""), 
-						PARAMETER_INPUT);
-
-	Parameters.Add_Grid(NULL, 
-						"VALUE", 
-						_TL("Value"), 
-						_TL(""), 
-						PARAMETER_INPUT_OPTIONAL);
-	
-	Parameters.Add_Grid(NULL, 
-						"BASEPROB", 
-						_TL("Base Probability"), 
-						_TL(""), 
-						PARAMETER_INPUT_OPTIONAL);	
-	
-	Parameters.Add_Grid(NULL, 
-						"DANGER", 
-						_TL("Danger"), 
-						_TL(""), 
-						PARAMETER_OUTPUT);
-	
-	Parameters.Add_Grid(NULL, 
-						"COMPPROB", 
-						_TL("Compound Probability"), 
-						_TL(""), 
-						PARAMETER_OUTPUT);
-
-	Parameters.Add_Grid(NULL, 
-						"PRIORITY", 
-						_TL("Priority Index"), 
-						_TL(""), 
-						PARAMETER_OUTPUT);
-
-	Parameters.Add_Value(NULL,
-						"MONTECARLO",
-						_TL("Number of Events"),
-						_TL("N\xc3\xbamero of Monte-Carlo events"),
-						PARAMETER_TYPE_Int,
-						1000,
-						1.,
-						true);
-
-	Parameters.Add_Value(NULL,
-						"INTERVAL",
-						_TL("Fire Length"),
-						_TL("Fire Length (min)"),
-						PARAMETER_TYPE_Double,
-						100,
-						1.,
-						true);
-
-
-}//constructor
-
-CForecasting::~CForecasting(void)
-{
-}//destructor
-
-bool CForecasting::On_Execute(void){
-
-	AssignParameters();
-	CalculateGrids();
-
-	delete m_pSlopeGrid;
-	delete m_pAspectGrid;
-
-	return true;
-
-}//method
-
-bool CForecasting::AssignParameters(){
-
-	int x,y;
-
-	m_pDEM = Parameters("DEM")->asGrid();
-	m_pFuelGrid = Parameters("FUEL")->asGrid();
-	m_pWindDirGrid = Parameters("WINDDIR")->asGrid();
-	m_pWindSpdGrid = Parameters("WINDSPD")->asGrid();
-	m_pM1Grid = Parameters("M1H")->asGrid();
-	m_pM10Grid = Parameters("M10H")->asGrid();
-	m_pM100Grid = Parameters("M100H")->asGrid();
-	m_pMHerbGrid = Parameters("MHERB")->asGrid();
-	m_pMWoodGrid = Parameters("MWOOD")->asGrid();
-	m_pDangerGrid = Parameters("DANGER")->asGrid();
-	m_pValueGrid = Parameters("VALUE")->asGrid();
-	m_pBaseProbabilityGrid = Parameters("BASEPROB")->asGrid();
-	m_pCompoundProbabilityGrid = Parameters("COMPPROB")->asGrid();
-	m_pPriorityIndexGrid = Parameters("PRIORITY")->asGrid();
-	m_iInterval = Parameters("INTERVAL")->asInt();
-	m_iNumEvents = Parameters("MONTECARLO")->asInt();
-
-	/* create a standard fuel model catalog and a flame length table. */
-    m_Catalog = Fire_FuelCatalogCreateStandard("Standard", 13);
-    Fire_FlameLengthTable(m_Catalog, 500, 0.1);
-
-	if (!m_pBaseProbabilityGrid){
-		m_pBaseProbabilityGrid = SG_Create_Grid(m_pDEM, SG_DATATYPE_Double);
-		m_pBaseProbabilityGrid->Assign(1);
-	}//if
-	if (!m_pValueGrid){
-		m_pValueGrid = SG_Create_Grid(m_pDEM, SG_DATATYPE_Double);
-		m_pValueGrid->Assign(1);
-	}//if
-
-	//substitute no-data values
-	for(y=0; y<Get_NY() && Set_Progress(y); y++){		
-		for(x=0; x<Get_NX(); x++){
-
-			if (m_pWindSpdGrid->is_NoData(x, y)){
-				m_pWindSpdGrid->Set_Value(x, y, 0.);
-			}//if
-			if (m_pWindDirGrid->is_NoData(x, y)){
-				m_pWindDirGrid->Set_Value(x, y, 0.);
-			}//if
-			if (m_pM1Grid->is_NoData(x, y)){
-				m_pM1Grid->Set_Value(x, y, 0.);
-			}//if
-			if (m_pM10Grid->is_NoData(x, y)){
-				m_pM10Grid->Set_Value(x, y, 0.);
-			}//if
-			if (m_pM100Grid->is_NoData(x, y)){
-				m_pM100Grid->Set_Value(x, y, 0.);
-			}//if
-			if (m_pMHerbGrid->is_NoData(x, y)){
-				m_pMHerbGrid->Set_Value(x, y, 0.);
-			}//if
-			if (m_pMWoodGrid->is_NoData(x, y)){
-				m_pMWoodGrid->Set_Value(x, y, 0.);
-			}//if
-			if (m_pBaseProbabilityGrid->is_NoData(x, y)){
-				m_pBaseProbabilityGrid->Set_Value(x, y, 0.);
-			}//if
-
-		}//for
-	}//for
-
-
-	//-----------------------------------------------------
-	// calculate slope and aspect using CSG_Grid class'
-	// built-in function (after Zevenbergen & Thorne)...
-
-	m_pSlopeGrid	= SG_Create_Grid(m_pDEM, SG_DATATYPE_Double);
-	m_pAspectGrid	= SG_Create_Grid(m_pDEM, SG_DATATYPE_Double);
-
-	for(y=0; y<Get_NY() && Set_Progress(y); y++)
-	{		
-		for(x=0; x<Get_NX(); x++)
-		{
-			double	slope, aspect;
-
-			if( m_pDEM->Get_Gradient(x, y, slope, aspect) )
-			{
-				m_pSlopeGrid	->Set_Value(x, y, slope);
-				m_pAspectGrid	->Set_Value(x, y, aspect);
-			}
-			else
-			{
-				m_pSlopeGrid	->Set_NoData(x, y);
-				m_pAspectGrid	->Set_NoData(x, y);
-			}
-		}
-	}
-
-
-	//-----------------------------------------------------
-	m_pTimeGrid = SG_Create_Grid(m_pDEM, SG_DATATYPE_Double);
-
-	m_pTimeGrid->Assign((double)0);
-	m_pDangerGrid->Assign((double)0);
-	m_pCompoundProbabilityGrid->Assign((double)0);	
-	
-	//m_pPriorityIndexGrid = Get_SafeNew_Grid(m_pDEM, SG_DATATYPE_Double);
-
-	return true;
-
-}//method
-
-
-void CForecasting::CalculateGrids(){
-	
-	int x,y;
-	int i;
-	int iRecommendedNumFires;
-	double dDanger;
-	double dTotalBurntArea = 0;
-	CSG_String sMessage;
-
-	m_CentralPoints	.Clear();
-	m_AdjPoints		.Clear();
-
-	srand((unsigned int)time(NULL));
-
-	Process_Set_Text(_TL("Calculating danger..."));
-	for(i=0; i<m_iNumEvents && Set_Progress(i, m_iNumEvents); i++){
-		x = rand() % (m_pDEM->Get_NX()-1);
-		y = rand() % (m_pDEM->Get_NY()-1);
-		m_CentralPoints.Clear();
-		m_CentralPoints.Add(x,y);
-		m_pTimeGrid->Set_Value(x,y,0.0);	
-		dDanger = CalculateFireSpreading();
-		dTotalBurntArea += dDanger;
-		m_pDangerGrid->Set_Value(x, y, dDanger);		
-	}//for
-
-	m_CentralPoints	.Clear();
-	m_AdjPoints		.Clear();
-
-	m_pDangerGrid->Set_NoData_Value(0.0);
-	m_pDangerGrid->Set_Unit(_TL("m2/h"));
-	
-	Process_Set_Text(_TL("Closing Gaps..."));
-
-	if(	!Gaps_Close(m_pDangerGrid) )
-	{
-		return;
-	}//if
-
-	for (y=0; y<Get_NY(); y++){
-		for (x=0; x<Get_NX(); x++){
-			m_pCompoundProbabilityGrid->Set_Value(x,y, 
-				m_pCompoundProbabilityGrid->asFloat(x,y) / (float)m_iNumEvents);
-			m_pPriorityIndexGrid->Set_Value(x, y, m_pCompoundProbabilityGrid->asFloat(x,y)*
-				m_pDangerGrid->asFloat(x,y));
-		}//for
-	}//for
-
-	float dRatio = (float)(dTotalBurntArea / (m_pDEM->Get_Cellsize() * m_pDEM->Get_Cellsize()));
-	if (dRatio < MIN_RATIO_BURNT_AREA){
-		iRecommendedNumFires =(int)((float) m_iNumEvents / dRatio * (float) MIN_RATIO_BURNT_AREA);
-		sMessage.Printf(
-			_TL("** Warning : Number of events might not be representative.\nMinimum number recommended: ")
-		);
-		sMessage	+= SG_Get_String(iRecommendedNumFires, 0);
-		sMessage	+= SG_T("\n");
-		Message_Add(sMessage.c_str());
-	}//if
-
-}//method
-
-double CForecasting::CalculateFireSpreading(){
-
-	int x,y;
-	int x2,y2;
-	int n;
-	bool bReturn = false;
-	/* neighbor's address*/   /* N  NE   E  SE   S  SW   W  NW */
-	static int nX[8] =        {  0,  1,  1,  1,  0, -1, -1, -1};
-    static int nY[8] =        {  1,  1,  0, -1, -1, -1,  0,  1};
-	double nDist[8];          /* distance to each neighbor */
-    double nAzm[8];           /* compass azimuth to each neighbor (0=N) */	
-	size_t modelNumber;       /* fuel model number at current cell */
-    double moisture[6];       /* fuel moisture content at current cell */
-    double dSpreadRate;       /* spread rate in direction of neighbor */
-    double dSpreadTime;       /* time to spread from cell to neighbor */
-    double dIgnTime;          /* time neighbor is ignited by current cell */
-	double dWindSpd;
-	double dBurntValue = 0;
-	double dProbability;
-
-	m_pTimeGrid->Assign(0.0);
-	
-    for (n=0; n<8; n++){
-        nDist[n] = sqrt ( nX[n] * m_pDEM->Get_Cellsize() * nX[n] * m_pDEM->Get_Cellsize()
-                        + nY[n] * m_pDEM->Get_Cellsize() * nY[n] * m_pDEM->Get_Cellsize() );
-        nAzm[n] = n * 45.;
-    }//for
-
-	x = m_CentralPoints.Get_X(0);
-	y = m_CentralPoints.Get_Y(0);
-	dProbability = (float)(rand()) / (float)(RAND_MAX); 
-
-	if (m_pBaseProbabilityGrid->asFloat(x,y) < dProbability){
-		return 0;
-	}//if
-
-	while (m_CentralPoints.Get_Count()!=0){
-
-		for (int iPt=0; iPt<m_CentralPoints.Get_Count();iPt++){
-
-			x = m_CentralPoints.Get_X(iPt);
-			y = m_CentralPoints.Get_Y(iPt);
-
-			if (!m_pDEM->is_NoData(x,y) && !m_pFuelGrid->is_NoData(x,y)){
-
-				modelNumber = (size_t) m_pFuelGrid->asInt(x, y);
-				moisture[0] = m_pM1Grid->asFloat(x, y);
-				moisture[1] = m_pM10Grid->asFloat(x, y);
-				moisture[2] = m_pM100Grid->asFloat(x, y);
-				moisture[3] = m_pM100Grid->asFloat(x, y);
-				moisture[4] = m_pMHerbGrid->asFloat(x, y);;
-				moisture[5] = m_pMWoodGrid->asFloat(x, y);
-				dWindSpd = m_pWindSpdGrid->asFloat(x,y)  * MS2FTMIN; 
-				Fire_SpreadNoWindNoSlope(m_Catalog, modelNumber, moisture);
-				Fire_SpreadWindSlopeMax(m_Catalog, modelNumber, dWindSpd,
-										 m_pWindDirGrid->asFloat(x,y), tan(m_pSlopeGrid->asFloat(x,y)),
-										 m_pAspectGrid->asFloat(x,y));
-
-				for (n=0; n<8; n++){
-					x2 = x + nX[n];
-					y2 = y + nY[n];
-					if (m_pTimeGrid->is_InGrid(x2,y2,false)){
-						Fire_SpreadAtAzimuth(m_Catalog, modelNumber, nAzm[n], FIRE_NONE);
-						dSpreadRate = Fuel_SpreadAny(m_Catalog, modelNumber); // in ft/min (awkward...)					
-						dSpreadRate *= FTMIN2MMIN; //a bit better...
-						if (dSpreadRate > Smidgen){
-							dSpreadTime = nDist[n] / dSpreadRate;
-							dIgnTime = 	m_pTimeGrid->asDouble(x,y) + dSpreadTime;												
-							if (dIgnTime < m_iInterval){
-								if (m_pTimeGrid->asDouble(x2,y2) == 0.0 
-										|| m_pTimeGrid->asDouble(x2, y2)>dIgnTime){
-									if (m_pTimeGrid->asDouble(x2, y2)==0.0){
-										dBurntValue += m_pValueGrid->asDouble(x2, y2);
-										m_pCompoundProbabilityGrid->Set_Value(x2,y2,
-											m_pCompoundProbabilityGrid->asFloat(x2,y2) + 1);
-									}//if
-									m_pTimeGrid->Set_Value(x2, y2, dIgnTime);
-									m_AdjPoints.Add(x2,y2);									
-								}//if							
-							}//if
-						}//if					
-					}//if
-				}//for
-			}//if
-		}//for
-
-		m_CentralPoints.Clear();
-		for (int i=0; i<m_AdjPoints.Get_Count(); i++){
-			x= m_AdjPoints.Get_X(i);
-			y = m_AdjPoints.Get_Y(i);
-			m_CentralPoints.Add(x, y);
-		}//for
-		m_AdjPoints.Clear();
-
-	}//while
-
-	return dBurntValue;
-
-}//method
-
-
-///////////////////////////////////////////////////////////
-//														 //
-//														 //
-//														 //
-///////////////////////////////////////////////////////////
-
-//---------------------------------------------------------
-bool CForecasting::Gaps_Close(CSG_Grid *pInput)
-{
-	int			iStep, iStart, n;
-	double		max, Threshold;
-	CSG_Grid	*pResult, *pTension_Keep, *pTension_Temp;
-
-	//-----------------------------------------------------
-	pResult		= pInput;
-	pInput		= SG_Create_Grid(pInput);
-	pInput->Assign(pResult);
-
-	//-----------------------------------------------------
-	Threshold	= 0.1;
-
-	n			= Get_NX() > Get_NY() ? Get_NX() : Get_NY();
-	iStep		= 0;
-	do	{	iStep++;	}	while( pow(2.0, iStep + 1) < n );
-	iStart		= (int)pow(2.0, iStep);
-
-	pTension_Keep		= new CSG_Grid(pResult, SG_DATATYPE_Byte);
-	pTension_Temp		= new CSG_Grid(pResult);
-
-	pResult->Assign_NoData();
-
-	for(iStep=iStart; iStep>=1; iStep/=2)
-	{
-		Gaps_Tension_Init(iStep, pTension_Temp, pTension_Keep, pResult, pInput);
-
-		do
-		{
-			max		= Gaps_Tension_Step(iStep, pTension_Temp, pTension_Keep, pResult);
-		}
-		while( max > Threshold && Process_Get_Okay(true) );
-	}
-
-	//-----------------------------------------------------
-	delete(pTension_Keep);
-	delete(pTension_Temp);
-	delete(pInput);
-
-	return( true );
-}
-
-//---------------------------------------------------------
-void CForecasting::Gaps_Tension_Init(int iStep, CSG_Grid *pTension_Temp, CSG_Grid *pTension_Keep, CSG_Grid *pResult, CSG_Grid *pInput)
-{
-	int		x, y, i, ix, iy, nx, ny, nz;
-	double	z;
-
-	//-----------------------------------------------------
-	// 1. Channels...
-
-	pTension_Temp->Assign_NoData();
-	pTension_Keep->Assign();
-
-	for(y=0; y<Get_NY(); y+=iStep)
-	{
-		ny	= y + iStep < Get_NY() ? y + iStep : Get_NY();
-
-		for(x=0; x<Get_NX(); x+=iStep)
-		{
-			if( !pInput->is_NoData(x, y) )
-			{
-				pTension_Temp->Set_Value(x, y, pInput->asDouble(x, y) );
-				pTension_Keep->Set_Value(x, y, 1.0);
-			}
-			else
-			{
-				nx	= x + iStep < Get_NX() ? x + iStep : Get_NX();
-				nz	= 0;
-				z	= 0.0;
-
-				for(iy=y; iy<ny; iy++)
-				{
-					for(ix=x; ix<nx; ix++)
-					{
-						if( pInput->is_InGrid(ix, iy) )
-						{
-							z	+= pInput->asDouble(ix, iy);
-							nz++;
-						}
-					}
-				}
-
-				if( nz > 0 )
-				{
-					pTension_Temp->Set_Value(x, y, z / (double)nz );
-					pTension_Keep->Set_Value(x, y, 1.0);
-				}
-			}
-		}
-	}
-
-	//-----------------------------------------------------
-	// 2. Previous Iteration...
-
-	for(y=0; y<Get_NY(); y+=iStep)
-	{
-		for(x=0; x<Get_NX(); x+=iStep)
-		{
-			if( pTension_Keep->asByte(x, y) == false )
-			{
-				if( !pResult->is_NoData(x, y) )
-				{
-					pTension_Temp->Set_Value(x, y, pResult->asDouble(x, y));
-				}
-				else
-				{
-					nz	= 0;
-					z	= 0.0;
-
-					for(i=0; i<8; i++)
-					{
-						ix	= x + iStep * Get_System()->Get_xTo(i);
-						iy	= y + iStep * Get_System()->Get_yTo(i);
-
-						if( pResult->is_InGrid(ix, iy) )
-						{
-							z	+= pResult->asDouble(ix, iy);
-							nz++;
-						}
-					}
-
-					if( nz > 0.0 )
-					{
-						pTension_Temp->Set_Value(x, y, z / (double)nz);
-					}
-					else
-					{
-						pTension_Temp->Set_Value(x, y, pInput->asDouble(x, y));
-					}
-				}
-			}
-		}
-	}
-
-	//-----------------------------------------------------
-	// 3. ...
-
-	pResult->Assign(pTension_Temp);
-}
-
-//---------------------------------------------------------
-double CForecasting::Gaps_Tension_Step(int iStep, CSG_Grid *pTension_Temp, CSG_Grid *pTension_Keep, CSG_Grid *pResult)
-{
-	int		x, y;
-	double	d, dMax;
-
-	dMax	= 0.0;
-
-	for(y=0; y<Get_NY(); y+=iStep)
-	{
-		for(x=0; x<Get_NX(); x+=iStep)
-		{
-			if( pTension_Keep->asByte(x, y) == false )
-			{
-				d	= Gaps_Tension_Change(x, y, iStep, pResult);
-
-				pTension_Temp->Set_Value(x, y, d);
-
-				d	= fabs(d - pResult->asDouble(x, y));
-
-				if( d > dMax )
-				{
-					dMax	= d;
-				}
-			}
-		}
-	}
-
-	for(y=0; y<Get_NY(); y+=iStep)
-	{
-		for(x=0; x<Get_NX(); x+=iStep)
-		{
-			if( pTension_Keep->asByte(x, y) == false )
-			{
-				pResult->Set_Value(x, y, pTension_Temp->asDouble(x, y));
-			}
-		}
-	}
-
-	return( dMax );
-}
-
-//---------------------------------------------------------
-double CForecasting::Gaps_Tension_Change(int x, int y, int iStep, CSG_Grid *pResult)
-{
-	int		i, ix, iy;
-	double	n, d, dz;
-
-	for(i=0, d=0.0, n=0.0; i<8; i++)
-	{
-		ix	= x + iStep * Get_System()->Get_xTo(i);
-		iy	= y + iStep * Get_System()->Get_yTo(i);
-
-		if( pResult->is_InGrid(ix, iy) )
-		{
-			dz	= 1.0 / Get_System()->Get_UnitLength(i);
-			d	+= dz * pResult->asDouble(ix, iy);
-			n	+= dz;
-		}
-	}
-
-	if( n > 0.0 )
-	{
-		d	/= n;
-
-		return( d );
-	}
-
-	return( pResult->asDouble(x, y) );
-}
-
-
-///////////////////////////////////////////////////////////
-//														 //
-//														 //
-//														 //
-///////////////////////////////////////////////////////////
-
-//---------------------------------------------------------
diff --git a/src/modules/simulation/sim_fire_spreading/Forecasting.h b/src/modules/simulation/sim_fire_spreading/Forecasting.h
deleted file mode 100644
index 728d56a..0000000
--- a/src/modules/simulation/sim_fire_spreading/Forecasting.h
+++ /dev/null
@@ -1,84 +0,0 @@
-/**********************************************************
- * Version $Id: Forecasting.h 911 2011-02-14 16:38:15Z reklov_w $
- *********************************************************/
-/*******************************************************************************
-    Forecasting.h
-    Copyright (C) Victor Olaya
-    
-    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 2 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, write to the Free Software
-    Foundation, Inc., 51 Franklin Street, 5th Floor, Boston, MA 02110-1301, USA
-*******************************************************************************/ 
-
-#if _MSC_VER > 1000
-#pragma once
-#endif // _MSC_VER > 1000
-
-#include "MLB_Interface.h"
-#include "fireLib.h"
-
-class CForecasting : public CSG_Module_Grid {
-
-private:
-
-	CSG_Grid *m_pDEM;    
-    CSG_Grid *m_pWindSpdGrid;       /* ptr to wind speed map (m/s) */
-    CSG_Grid *m_pWindDirGrid;       /* ptr to wind direction map (deg from north) */
-    CSG_Grid *m_pM1Grid;            /* ptr to 1-hr dead fuel moisture map */
-    CSG_Grid *m_pM10Grid;           /* ptr to 10-hr dead fuel moisture map */
-    CSG_Grid *m_pM100Grid;          /* ptr to 100-hr dead fuel moisture map */
-    CSG_Grid *m_pMHerbGrid;         /* ptr to live herbaceous fuel moisture map */
-    CSG_Grid *m_pMWoodGrid;         /* ptr to live stem fuel moisture map */
-	CSG_Grid *m_pFuelGrid;          /* ptr to fuel model map */
-	CSG_Grid *m_pValueGrid;		 /* ptr to cell value map */
-
-	CSG_Grid *m_pDangerGrid;       /* ptr to danger map (in burnt m2 / h) */
-	CSG_Grid *m_pBaseProbabilityGrid; 
-	CSG_Grid *m_pCompoundProbabilityGrid;
-
-	CSG_Grid *m_pPriorityIndexGrid;
-
-    CSG_Grid *m_pSlopeGrid;         /* ptr to slope map (rise/reach) */
-    CSG_Grid *m_pAspectGrid;        /* ptr to aspect map (degrees from north) */
-
-	CSG_Grid *m_pTimeGrid;
-	
-	FuelCatalogPtr m_Catalog;    /* fuel catalog handle */
-
-	CSG_Points_Int	m_CentralPoints;
-	CSG_Points_Int	m_AdjPoints;
-
-	int m_iInterval;
-	int m_iNumEvents;
-
-	bool AssignParameters();
-	void CalculateGrids();	
-	double CalculateFireSpreading();
-
-	bool	Gaps_Close			(CSG_Grid *pInput);
-	void	Gaps_Tension_Init	(int iStep, CSG_Grid *pTension_Temp, CSG_Grid *pTension_Keep, CSG_Grid *pResult, CSG_Grid *pInput);
-	double	Gaps_Tension_Step	(int iStep, CSG_Grid *pTension_Temp, CSG_Grid *pTension_Keep, CSG_Grid *pResult);
-	double	Gaps_Tension_Change	(int x, int y, int iStep, CSG_Grid *pResult);
-
-
-public:
-
-	CForecasting(void);
-	virtual ~CForecasting(void);
-
-protected:
-
-	virtual bool On_Execute(void);
-
-};
-
diff --git a/src/modules/simulation/sim_fire_spreading/MLB_Interface.cpp b/src/modules/simulation/sim_fire_spreading/MLB_Interface.cpp
deleted file mode 100644
index 142dba6..0000000
--- a/src/modules/simulation/sim_fire_spreading/MLB_Interface.cpp
+++ /dev/null
@@ -1,130 +0,0 @@
-/**********************************************************
- * Version $Id: MLB_Interface.cpp 1921 2014-01-09 10:24:11Z oconrad $
- *********************************************************/
-
-///////////////////////////////////////////////////////////
-//                                                       //
-//                         SAGA                          //
-//                                                       //
-//    System for an Automated Geo-Scientific Analysis    //
-//                                                       //
-//                    Module Library:                    //
-//                      Fire_Spreading                   //
-//                                                       //
-//-------------------------------------------------------//
-//                                                       //
-//                   MLB_Interface.cpp                   //
-//                                                       //
-//                 Copyright (C) 2003 by                 //
-//                      Olaf Conrad                      //
-//                                                       //
-//-------------------------------------------------------//
-//                                                       //
-// This file is part of 'SAGA - System for an Automated  //
-// Geo-Scientific Analysis'. SAGA 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; version 2 of the License.   //
-//                                                       //
-// SAGA 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,       //
-// write to the Free Software Foundation, Inc.,          //
-// 51 Franklin Street, 5th Floor, Boston, MA 02110-1301, //
-// USA.                                                  //
-//                                                       //
-//-------------------------------------------------------//
-//                                                       //
-//    e-mail:     volaya at saga-gis.org                    //
-//                                                       //
-//    contact:    Victor Olaya                           //
-//                Spain                                  //
-//                                                       //
-///////////////////////////////////////////////////////////
-
-
-///////////////////////////////////////////////////////////
-//														 //
-//			The Module Link Library Interface			 //
-//														 //
-///////////////////////////////////////////////////////////
-
-#include "MLB_Interface.h"
-
-CSG_String Get_Info(int i)
-{
-	switch( i )
-	{
-	case MLB_INFO_Name:	default:
-		return( _TL("Fire Spreading Analysis") );
-
-	case MLB_INFO_Category:
-		return( _TL("Simulation") );
-
-	case MLB_INFO_Author:
-		return( SG_T("Victor Olaya (c) 2004") );
-
-	case MLB_INFO_Description:
-		return( _TW(
-			"Fire spreading analyses based on the BEHAVE fire modeling system "
-			"supported by the U.S. Forest Service, Fire and Aviation Management. "
-			"Find more information on BEHAVE at the <i>Public Domain Software for the Wildland Fire Community</i> at "
-			"<a target=\"_blank\" href=\"http://fire.org\">http://fire.org</a>\n"
-			"\n"
-			"Reference:\n"
-			"Andrews, P.L. (1986): BEHAVE: Fire Behavior Prediction and Fuel Modeling System - "
-			"Burn Subsystem, Part 1. U.S. Department of Agriculture, Forest Service General, Technical Report INT-194. "
-		));
-
-	case MLB_INFO_Version:
-		return( SG_T("1.0") );
-
-	case MLB_INFO_Menu_Path:
-		return( _TL("Simulation|Fire Spreading") );
-	}
-}
-
-#include "Simulate.h"
-#include "Forecasting.h"
-
-CSG_Module *		Create_Module(int i)
-{
-
-	CSG_Module	*pModule;
-
-	switch( i )
-	{
-	case 0:
-		pModule	= new CForecasting;
-		break;
-
-	case 1:
-		pModule	= new CSimulate;
-		break;
-
-	default:
-		pModule	= NULL;
-		break;
-	}
-
-	return( pModule );
-}
-
-
-///////////////////////////////////////////////////////////
-//														 //
-//														 //
-//														 //
-///////////////////////////////////////////////////////////
-
-//---------------------------------------------------------
-//{{AFX_SAGA
-
-	MLB_INTERFACE
-
-//}}AFX_SAGA
diff --git a/src/modules/simulation/sim_fire_spreading/MLB_Interface.h b/src/modules/simulation/sim_fire_spreading/MLB_Interface.h
deleted file mode 100644
index f8c09f4..0000000
--- a/src/modules/simulation/sim_fire_spreading/MLB_Interface.h
+++ /dev/null
@@ -1,72 +0,0 @@
-/**********************************************************
- * Version $Id: MLB_Interface.h 1922 2014-01-09 10:28:46Z oconrad $
- *********************************************************/
-
-///////////////////////////////////////////////////////////
-//                                                       //
-//                         SAGA                          //
-//                                                       //
-//      System for Automated Geoscientific Analyses      //
-//                                                       //
-//                    Module Library:                    //
-//                   Terrain_Analysis                    //
-//                                                       //
-//-------------------------------------------------------//
-//                                                       //
-//                    MLB_Interface.h                    //
-//                                                       //
-//                 Copyright (C) 2003 by                 //
-//                      Olaf Conrad                      //
-//                                                       //
-//-------------------------------------------------------//
-//                                                       //
-// This file is part of 'SAGA - System for Automated     //
-// Geoscientific Analyses'. SAGA 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; version 2 of the License.   //
-//                                                       //
-// SAGA 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,       //
-// write to the Free Software Foundation, Inc.,          //
-// 51 Franklin Street, 5th Floor, Boston, MA 02110-1301, //
-// USA.                                                  //
-//                                                       //
-//-------------------------------------------------------//
-//                                                       //
-//    contact:    Olaf Conrad                            //
-//                Institute of Geography                 //
-//                University of Goettingen               //
-//                Goldschmidtstr. 5                      //
-//                37077 Goettingen                       //
-//                Germany                                //
-//                                                       //
-//    e-mail:     oconrad at saga-gis.org                   //
-//                                                       //
-///////////////////////////////////////////////////////////
-
-//---------------------------------------------------------
-
-
-///////////////////////////////////////////////////////////
-//														 //
-//				Include the SAGA-API here				 //
-//														 //
-///////////////////////////////////////////////////////////
-
-//---------------------------------------------------------
-#ifndef HEADER_INCLUDED__MLB_INTERFACE_H
-#define HEADER_INCLUDED__MLB_INTERFACE_H
-
-//---------------------------------------------------------
-#include <saga_api/saga_api.h>
-
-
-//---------------------------------------------------------
-#endif // #ifndef HEADER_INCLUDED__MLB_INTERFACE_H
diff --git a/src/modules/simulation/sim_fire_spreading/Makefile.am b/src/modules/simulation/sim_fire_spreading/Makefile.am
deleted file mode 100644
index 08acfe5..0000000
--- a/src/modules/simulation/sim_fire_spreading/Makefile.am
+++ /dev/null
@@ -1,26 +0,0 @@
-#
-# $Id: Makefile.am 1277 2011-12-22 15:48:59Z reklov_w $
-#
-if DEBUG
-DBGFLAGS = -g -DDEBUG
-endif
-if SAGA_UNICODE
-UC_DEFS = -D_SAGA_UNICODE
-endif
-DEF_SAGA           = -D_SAGA_LINUX -D_TYPEDEF_BYTE -D_TYPEDEF_WORD
-CXX_INCS           = -I$(top_srcdir)/src/saga_core -I$(top_srcdir)/src/modules/grid/grid_tools
-AM_CXXFLAGS        = -fPIC $(CXX_INCS) $(DEF_SAGA) $(UC_DEFS) $(DBGFLAGS) $(GOMPFLAGS)
-AM_LDFLAGS         = -fPIC -shared -avoid-version
-pkglib_LTLIBRARIES = libsim_fire_spreading.la
-libsim_fire_spreading_la_SOURCES =\
-fireLib.c\
-Forecasting.cpp\
-MLB_Interface.cpp\
-Simulate.cpp\
-fireLib.h\
-Forecasting.h\
-MLB_Interface.h\
-Simulate.h
-
-libsim_fire_spreading_la_LIBADD = $(top_srcdir)/src/saga_core/saga_api/libsaga_api.la
-
diff --git a/src/modules/simulation/sim_fire_spreading/Simulate.cpp b/src/modules/simulation/sim_fire_spreading/Simulate.cpp
deleted file mode 100644
index 9a305d5..0000000
--- a/src/modules/simulation/sim_fire_spreading/Simulate.cpp
+++ /dev/null
@@ -1,363 +0,0 @@
-/**********************************************************
- * Version $Id: Simulate.cpp 911 2011-02-14 16:38:15Z reklov_w $
- *********************************************************/
-/*******************************************************************************
-    Simulate.cpp
-    Copyright (C) Victor Olaya
-    
-    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 2 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, write to the Free Software
-    Foundation, Inc., 51 Franklin Street, 5th Floor, Boston, MA 02110-1301, USA
-*******************************************************************************/ 
-
-#include "Simulate.h"
-
-#define MS2FTMIN (60.0 / 0.3048)
-#define FTMIN2MMIN 0.3048
-#define BTU2KCAL 0.252164401
-#define FT2M 0.3048
-#define NO_TIME_LIMIT -1
-#define THRESHOLD_FOR_DIFFERENCE 0.1
-
-CSimulate::CSimulate(void){
-	
-	Set_Name		(_TL("Simulation"));
-	Set_Author		(SG_T("(c) 2004 Victor Olaya"));
-	Set_Description	(_TW(
-		"Fire simulation based on the BEHAVE fire modeling system "
-		"supported by the U.S. Forest Service, Fire and Aviation Management. "
-		"Find more information on BEHAVE at the <i>Public Domain Software for the Wildland Fire Community</i> at "
-		"<a target=\"_blank\" href=\"http://fire.org\">http://fire.org</a>\n"
-		"\n"
-		"Reference:\n"
-		"Andrews, P.L. (1986): BEHAVE: Fire Behavior Prediction and Fuel Modeling System - "
-		"Burn Subsystem, Part 1. U.S. Department of Agriculture, Forest Service General, Technical Report INT-194. "
-	));
-
-	Parameters.Add_Grid(NULL, 
-						"DEM", 
-						_TL("DEM"), 
-						_TL(""), 
-						PARAMETER_INPUT);
-	
-	Parameters.Add_Grid(NULL, 
-						"FUEL", 
-						_TL("Fuel Model"), 
-						_TL(""), 
-						PARAMETER_INPUT);
-
-	Parameters.Add_Grid(NULL, 
-						"WINDSPD", 
-						_TL("Wind Speed"),
-						_TL("Wind speed (m/s)"), 
-						PARAMETER_INPUT);
-	
-	Parameters.Add_Grid(NULL, 
-						"WINDDIR", 
-						_TL("Wind Direction"), 
-						_TL("Wind direction (degrees clockwise from north)"),
-						PARAMETER_INPUT);
-
-	Parameters.Add_Grid(NULL, 
-						"M1H", 
-						_TL("Dead Fuel Moisture 1H"), 
-						_TL(""), 
-						PARAMETER_INPUT);
-
-	Parameters.Add_Grid(NULL, 
-						"M10H", 
-						_TL("Dead Fuel Moisture 10H"), 
-						_TL(""), 
-						PARAMETER_INPUT);
-
-	Parameters.Add_Grid(NULL, 
-						"M100H", 
-						_TL("Dead Fuel Moisture 100H"), 
-						_TL(""), 
-						PARAMETER_INPUT);
-
-	Parameters.Add_Grid(NULL, 
-						"MHERB", 
-						_TL("Herbaceous Fuel Moisture"), 
-						_TL(""), 
-						PARAMETER_INPUT);
-
-	Parameters.Add_Grid(NULL, 
-						"MWOOD", 
-						_TL("Wood Fuel Moisture"), 
-						_TL(""), 
-						PARAMETER_INPUT);
-
-	Parameters.Add_Grid(NULL, 
-						"IGNITION", 
-						_TL("Ignition Points"), 
-						_TL(""), 
-						PARAMETER_INPUT);
-	
-	Parameters.Add_Grid(NULL, 
-						"TIME", 
-						_TL("Time"), 
-						_TL(""), 
-						PARAMETER_OUTPUT);
-
-	Parameters.Add_Grid(NULL, 
-						"FLAME", 
-						_TL("Flame Length"), 
-						_TL("Flame Length (m)"), 
-						PARAMETER_OUTPUT);
-
-	Parameters.Add_Grid(NULL, 
-						"INTENSITY", 
-						_TL("Intensity"), 
-						_TL("Intensity (Kcal/m)"), 
-						PARAMETER_OUTPUT);
-
-	Parameters.Add_Value(NULL, 
-						"UPDATEVIEW", 
-						_TL("Update View"),
-						_TL("Update view during simulation."),
-						PARAMETER_TYPE_Bool, 
-						true);
-
-}//constructor
-
-CSimulate::~CSimulate(void){}
-
-bool CSimulate::On_Execute(void){
-
-	AssignParameters();
-	CalculateFire();
-	
-	DeleteObjects();
-	return true;
-
-}//method
-
-void CSimulate::DeleteObjects(){
-
-	delete m_pAspectGrid;
-	delete m_pSlopeGrid;
-
-	m_CentralPoints	.Clear();
-	m_AdjPoints		.Clear();
-
-}//method
-
-bool CSimulate::AssignParameters(){
-
-	int x,y;
-
-	m_pDEM = Parameters("DEM")->asGrid();
-	m_pFuelGrid = Parameters("FUEL")->asGrid();
-	m_pIgnGrid = Parameters("IGNITION")->asGrid();
-	m_pWindDirGrid = Parameters("WINDDIR")->asGrid();
-	m_pWindSpdGrid = Parameters("WINDSPD")->asGrid();
-	m_pM1Grid = Parameters("M1H")->asGrid();
-	m_pM10Grid = Parameters("M10H")->asGrid();
-	m_pM100Grid = Parameters("M100H")->asGrid();
-	m_pMHerbGrid = Parameters("MHERB")->asGrid();
-	m_pMWoodGrid = Parameters("MWOOD")->asGrid();
-	m_pTimeGrid = Parameters("TIME")->asGrid();
-	m_pFlameGrid = Parameters("FLAME")->asGrid();
-	m_pIntensityGrid = Parameters("INTENSITY")->asGrid();
-
-    m_Catalog = Fire_FuelCatalogCreateStandard("Standard", 13);
-    Fire_FlameLengthTable(m_Catalog, 500, 0.1);
-
-	//substitute no-data values
-	for(y=0; y<Get_NY() && Set_Progress(y); y++){		
-		for(x=0; x<Get_NX(); x++){
-
-			if (m_pWindSpdGrid->is_NoData(x, y)){
-				m_pWindSpdGrid->Set_Value(x, y, 0.);
-			}//if
-			if (m_pWindDirGrid->is_NoData(x, y)){
-				m_pWindDirGrid->Set_Value(x, y, 0.);
-			}//if
-			if (m_pM1Grid->is_NoData(x, y)){
-				m_pM1Grid->Set_Value(x, y, 0.);
-			}//if
-			if (m_pM10Grid->is_NoData(x, y)){
-				m_pM10Grid->Set_Value(x, y, 0.);
-			}//if
-			if (m_pM100Grid->is_NoData(x, y)){
-				m_pM100Grid->Set_Value(x, y, 0.);
-			}//if
-			if (m_pMHerbGrid->is_NoData(x, y)){
-				m_pMHerbGrid->Set_Value(x, y, 0.);
-			}//if
-			if (m_pMWoodGrid->is_NoData(x, y)){
-				m_pMWoodGrid->Set_Value(x, y, 0.);
-			}//if
-
-		}//for
-	}//for
-
-
-	//-----------------------------------------------------
-	// calculate slope and aspect using CSG_Grid class'
-	// built-in function (after Zevenbergen & Thorne)...
-
-	m_pSlopeGrid	= SG_Create_Grid(m_pDEM, SG_DATATYPE_Double);
-	m_pAspectGrid	= SG_Create_Grid(m_pDEM, SG_DATATYPE_Double);
-
-	for(y=0; y<Get_NY() && Set_Progress(y); y++)
-	{		
-		for(x=0; x<Get_NX(); x++)
-		{
-			double	slope, aspect;
-
-			if( m_pDEM->Get_Gradient(x, y, slope, aspect) )
-			{
-				m_pSlopeGrid	->Set_Value(x, y, slope);
-				m_pAspectGrid	->Set_Value(x, y, aspect);
-			}
-			else
-			{
-				m_pSlopeGrid	->Set_NoData(x, y);
-				m_pAspectGrid	->Set_NoData(x, y);
-			}
-		}
-	}
-
-
-	//-----------------------------------------------------
-	m_pTimeGrid->Assign((double)0);
-
-	return true;
-
-}//method
-
-void CSimulate::CalculateFire(){
-	
-	int x,y;
-
-	Process_Set_Text(_TL("Simulating..."));
-	m_CentralPoints	.Clear();
-	m_AdjPoints		.Clear();
-
-	m_CentralPoints.Clear();
-	for(y=0; y<Get_NY(); y++){
-		for(x=0; x<Get_NX(); x++){
-			if (!m_pIgnGrid->is_NoData(x,y)){
-				m_CentralPoints.Add(x,y);
-				m_pTimeGrid->Set_Value(x,y,0.0);				
-			}//if
-		}//for
-	}//for
-	CalculateFireSpreading(NO_TIME_LIMIT);
-
-	m_pTimeGrid->Set_NoData_Value(0.);
-
-
-}//method
-
-
-int CSimulate::CalculateFireSpreading(float fTimeLimit){
-
-	int x,y;
-	int x2,y2;
-	int n;
-	bool bReturn = false;
-	/* neighbor's address*/   /* N  NE   E  SE   S  SW   W  NW */
-	static int nX[8] =        {  0,  1,  1,  1,  0, -1, -1, -1};
-    static int nY[8] =        {  1,  1,  0, -1, -1, -1,  0,  1};
-	double nDist[8];          /* distance to each neighbor */
-    double nAzm[8];           /* compass azimuth to each neighbor (0=N) */	
-	size_t modelNumber;       /* fuel model number at current cell */
-    double moisture[6];       /* fuel moisture content at current cell */
-    double dSpreadRate;       /* spread rate in direction of neighbor */
-    double dSpreadTime;       /* time to spread from cell to neighbor */
-    double dIgnTime;          /* time neighbor is ignited by current cell */
-	double dWindSpd;
-	int iBurntCells = 0;
-
-	bool bUpdate = Parameters("UPDATEVIEW")->asBool();
-
-    for (n=0; n<8; n++){
-        nDist[n] = sqrt ( nX[n] * m_pDEM->Get_Cellsize() * nX[n] * m_pDEM->Get_Cellsize()
-                        + nY[n] * m_pDEM->Get_Cellsize() * nY[n] * m_pDEM->Get_Cellsize() );
-        nAzm[n] = n * 45.;
-    }//for
-
-	while (m_CentralPoints.Get_Count()!=0){
-
-		for (int iPt=0; iPt<m_CentralPoints.Get_Count();iPt++){
-
-			x = m_CentralPoints.Get_X(iPt);
-			y = m_CentralPoints.Get_Y(iPt);
-
-			if (!m_pDEM->is_NoData(x,y) && !m_pFuelGrid->is_NoData(x,y)){
-
-				modelNumber = (size_t) m_pFuelGrid->asInt(x, y);
-				moisture[0] = m_pM1Grid->asFloat(x, y);
-				moisture[1] = m_pM10Grid->asFloat(x, y);
-				moisture[2] = m_pM100Grid->asFloat(x, y);
-				moisture[3] = m_pM100Grid->asFloat(x, y);
-				moisture[4] = m_pMHerbGrid->asFloat(x, y);;
-				moisture[5] = m_pMWoodGrid->asFloat(x, y);
-				dWindSpd = m_pWindSpdGrid->asFloat(x,y)  * MS2FTMIN; 
-				Fire_SpreadNoWindNoSlope(m_Catalog, modelNumber, moisture);
-				Fire_SpreadWindSlopeMax(m_Catalog, modelNumber, dWindSpd,
-										 m_pWindDirGrid->asFloat(x,y), tan(m_pSlopeGrid->asFloat(x,y)),
-										 m_pAspectGrid->asFloat(x,y));
-
-				for (n=0; n<8; n++){
-					x2 = x + nX[n];
-					y2 = y + nY[n];
-					if (m_pTimeGrid->is_InGrid(x2,y2,false)){
-						Fire_SpreadAtAzimuth(m_Catalog, modelNumber, nAzm[n], FIRE_BYRAMS);
-						dSpreadRate = Fuel_SpreadAny(m_Catalog, modelNumber); // in ft/min (awkward...)					
-						dSpreadRate *= FTMIN2MMIN; //a bit better...
-						if (dSpreadRate > Smidgen){
-							dSpreadTime = nDist[n] / dSpreadRate;							
-							if (fTimeLimit == NO_TIME_LIMIT){
-								dIgnTime = 	m_pTimeGrid->asDouble(x,y) + dSpreadTime;
-								if (m_pTimeGrid->asDouble(x2,y2) == 0.0 
-										|| m_pTimeGrid->asDouble(x2, y2) > dIgnTime + THRESHOLD_FOR_DIFFERENCE ){
-									m_pTimeGrid->Set_Value(x2, y2, dIgnTime);
-									m_AdjPoints.Add(x2,y2);
-									Fire_FlameScorch(m_Catalog, modelNumber, FIRE_FLAME);
-									m_pFlameGrid->Set_Value(x2, y2, Fuel_FlameLength(m_Catalog, modelNumber) * FT2M);									
-									m_pIntensityGrid->Set_Value(x2, y2, Fuel_ByramsIntensity(m_Catalog, modelNumber)
-																* BTU2KCAL / FT2M );									
-								}//if
-							}//if
-						}//if					
-					}//if
-				}//for
-			}//if
-		}//for
-
-		m_CentralPoints.Clear();
-		for (int i=0; i<m_AdjPoints.Get_Count(); i++){
-			x= m_AdjPoints.Get_X(i);
-			y = m_AdjPoints.Get_Y(i);
-			m_CentralPoints.Add(x, y);
-		}//for
-		m_AdjPoints.Clear();
-
-		if (fTimeLimit == NO_TIME_LIMIT){
-			Process_Get_Okay(true);
-		}//if	
-		
-		if (bUpdate){
-			DataObject_Update(m_pTimeGrid, true);
-		}
-
-	}//while
-
-	return iBurntCells;
-
-}//method
-
diff --git a/src/modules/simulation/sim_fire_spreading/Simulate.h b/src/modules/simulation/sim_fire_spreading/Simulate.h
deleted file mode 100644
index ed2ff06..0000000
--- a/src/modules/simulation/sim_fire_spreading/Simulate.h
+++ /dev/null
@@ -1,81 +0,0 @@
-/**********************************************************
- * Version $Id: Simulate.h 911 2011-02-14 16:38:15Z reklov_w $
- *********************************************************/
-/*******************************************************************************
-    Simulate.h
-    Copyright (C) Victor Olaya
-    
-    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 2 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, write to the Free Software
-    Foundation, Inc., 51 Franklin Street, 5th Floor, Boston, MA 02110-1301, USA
-*******************************************************************************/ 
-
-#if _MSC_VER > 1000
-#pragma once
-#endif // _MSC_VER > 1000
-
-#include "MLB_Interface.h"
-#include "fireLib.h"
-
-class CSimulate : public CSG_Module_Grid {
-
-private:
-
-	CSG_Grid *m_pDEM;    
-    CSG_Grid *m_pIgnGrid;           /* ptr to ignition time map (minutes) */
-    CSG_Grid *m_pWindSpdGrid;       /* ptr to wind speed map (m/s) */
-    CSG_Grid *m_pWindDirGrid;       /* ptr to wind direction map (deg from north) */
-    CSG_Grid *m_pM1Grid;            /* ptr to 1-hr dead fuel moisture map */
-    CSG_Grid *m_pM10Grid;           /* ptr to 10-hr dead fuel moisture map */
-    CSG_Grid *m_pM100Grid;          /* ptr to 100-hr dead fuel moisture map */
-    CSG_Grid *m_pMHerbGrid;         /* ptr to live herbaceous fuel moisture map */
-    CSG_Grid *m_pMWoodGrid;         /* ptr to live stem fuel moisture map */
-	CSG_Grid *m_pFuelGrid;          /* ptr to fuel model map */
-	CSG_Grid *m_pValueGrid;
-
-	CSG_Grid *m_pFlameGrid;         /* ptr to flame length map (m) */
-	CSG_Grid *m_pIntensityGrid;     
-
-    CSG_Grid *m_pSlopeGrid;         /* ptr to slope map (rise/reach) */
-    CSG_Grid *m_pAspectGrid;        /* ptr to aspect map (degrees from north) */
-
-	CSG_Grid *m_pTimeGrid;
-	//CSG_Grid *m_pVolatileTimeGrid;
-	
-	FuelCatalogPtr m_Catalog;    /* fuel catalog handle */
-
-	int m_iLength;
-
-	CSG_Points_Int	m_CentralPoints;
-	CSG_Points_Int	m_AdjPoints;
-
-	int *m_pLength; 
-	int m_iMaxTime; //in s
-	int m_iTimeInterval; //in s
-
-	bool AssignParameters();
-	void CalculateFire();
-	int CalculateFireSpreading(float);
-	void DeleteObjects();
-
-public:
-
-	CSimulate(void);
-	virtual ~CSimulate(void);
-
-protected:
-
-	virtual bool On_Execute(void);
-
-};
-
diff --git a/src/modules/simulation/sim_fire_spreading/fireLib.c b/src/modules/simulation/sim_fire_spreading/fireLib.c
deleted file mode 100644
index 53b16a0..0000000
--- a/src/modules/simulation/sim_fire_spreading/fireLib.c
+++ /dev/null
@@ -1,1817 +0,0 @@
-/**********************************************************
- * Version $Id: fireLib.c 911 2011-02-14 16:38:15Z reklov_w $
- *********************************************************/
-/*
- *******************************************************************************
- *
- *  fireLib.c
- *
- *  Description
- *      Library of BEHAVE (Andrews 1986) fire behavior algorithms
- *      encapsulated and optimized for fire behavior simulation.
- *
- *  Legalities
- *      Copyright (c) 1996 Collin D. Bevins.
- *      See the file "license.txt" for information on usage and
- *      redistribution of this file, and for a DISCLAIMER OF ALL WARRANTIES.
- *
- *  Naming Conventions
- *      All function names begin with "Fire_".
- *      All fuel model and behavior parameter access macros begin with "Fuel_".
- *      All fuel catalog parameter access macros begin with "FuelCat_".
- *
- *  Functions
- *      There are 8 functions to create and destroy fuel models and catalogs:
- *
- *          Fire_FuelCatalogCreate(name, maxModels)
- *              Creates a new fuel catalog capable of holding maxModels.
- *
- *          Fire_FuelCatalogCreateStandard(name, maxModels)
- *              Creates a new fuel catalog capable of holding maxModels,
- *              and fills models 0-13 with standard fire behavior models.
- *
- *          Fire_FuelModelCreate(catalog, model, name, desc, depth, mext,
- *                  adjust, maxParticles)
- *              Adds or replaces a fuel model in the catalog.  The model will
- *              accept up to maxParticles particles.
- *
- *          Fire_FuelModelExists(catalog, model)
- *              Returns 1 if model exists within the catalog.
- *
- *          Fire_FuelParticleAdd(catalog, model, live, load, savr, dens, heat,
- *                  stot, seff)
- *              Adds a fuel particle to a fuel model.
- *
- *          Fire_FlameLengthTable ( catalog, flameClasses, flameStep )
- *              Creates a flame length look-up table containing flameClasses
- *              number of classes, with each class spanning "flameStep"
- *              feet of flame length.  Creating a flame length table can
- *              significantly improve performance at the expense of user
- *              specified precision.
- *
- *          Fire_FuelModelDestroy(catalog, model)
- *              Destroys the model within the catalog.
- *
- *          Fire_FuelCatalogDestroy(catalog)
- *              Destroys the catalog and all models within it.
- *
- *      There are 5 functions to process data within fuel models:
- *
- *          Fire_FuelCombustion(catalog, model)
- *              Computes all the fuel-dependent model variables.
- *              Called only once for each fuel model.
- *              Called automatically by Fire_SpreadNoWindNoSlope().
- *
- *          Fire_SpreadNoWindNoSlope(catalog, model, moisture[6])
- *              Determines reaction intensity, heat per unit area, and the
- *              no-wind no-slope spread rate.
- *
- *          Fire_SpreadWindSlopeMax(catalog, model, windFpm, windDeg, slope,
- *                  aspectDeg)
- *              Determines maximum spread rate and azimuth of maximum spread
- *              based upon input parameters and results of the most recent
- *              call to Fire_SpreadNoWindNoSlope() for this model.
- *
- *          Fire_SpreadAtAzimuth(catalog, model, azimuth, doWhich)
- *              Determines the spread rate in the specified azimuth based
- *              upon the results of the most recent call to
- *              Fire_SpreadWindSlopeMax() for this model.  The "doWhich"
- *              parameter is the result of ORing the constants FIRE_BYRAMS,
- *              FIRE_FLAME, and FIRE_SCORCH to request computation of the
- *              associated fire variables.
- *
- *          Fire_FlameScorch(catalog, model, doWhich)
- *              Determines the flame length and/or scorch height based upon
- *              the most recent call to Fire_SpreadAtAzimuth().
- *
- *  History
- *      1996/09/04  Version 1.0.0 release.
- *      1999/03/05  Fixed NNFL07 live SAVR from 1500 to 1550.
- *
- *******************************************************************************
- */
-
-#include "fireLib.h"
-
-#ifndef M_PI
-#define M_PI 3.14159
-#endif
-
-/*
- *******************************************************************************
- *
- *  Fire_FuelCombustion()
- *
- *  Description
- *      Calculates and stores all the fuel-dependent combustion variables.
- *
- *  Side Effects
- *      All combustion varaiables are reclaculated for the model.
- *      All behavior and environment variables are reset to zero.
- *
- *  Function Returns
- *      FIRE_STATUS_OK or FIRE_STATUS_ERROR.
- *      Return status and error text are stored in the Fire Catalog's buffers.
- *
- *******************************************************************************
- */
-
-int
-Fire_FuelCombustion (FuelCatalogPtr catalog, size_t model )
-    //FuelCatalogPtr catalog;     /* FuelCatalogData instance pointer           */
-    //size_t         model;       /* fuel model id number         [0-maxModels] */
-{
-    size_t particle, size, life;
-
-    double sizeClassAreaWtg[FIRE_LIFE_CATS][FIRE_SIZE_CLASSES];
-    double lifeLoad[FIRE_LIFE_CATS];
-    double lifeArea[FIRE_LIFE_CATS];
-    double lifeSavr[FIRE_LIFE_CATS];
-    double lifeHeat[FIRE_LIFE_CATS];
-    double lifeSeff[FIRE_LIFE_CATS];
-    double lifeEtaS[FIRE_LIFE_CATS];
-
-    double totalArea;
-    double fineLive;
-    double beta;
-    double betaOpt;
-    double sigma;
-    double ratio;
-    double aa;
-    double sigma15;
-    double gammaMax;
-    double gamma;
-    double c;
-    double e;
-
-    /* Validate catalog and fuel model existence. */
-    assert(catalog!= NULL && FuelCat_MagicCookie(catalog)==FIRE_CATALOG_MAGIC);
-    if ( ! Fire_FuelModelExists(catalog,model) )
-    {
-        sprintf(FuelCat_Error(catalog),
-            "Fire_FuelCombustion(): el modelo de combustible %d no existe en el cat�logo de combuestibles \"%s\".",
-            model, FuelCat_Name(catalog));
-        return (FuelCat_Status(catalog) = FIRE_STATUS_ERROR);
-    }
-
-    /* Initialize the model's fuel particle dependent variables. */
-    for ( particle=0; particle<Fuel_Particles(catalog,model); particle++ )
-    {
-        Fuel_AreaWtg(catalog,model,particle)     = 0.;
-        Fuel_SizeAreaWtg(catalog,model,particle) = 0.;
-        Fuel_Moisture(catalog,model,particle)    = 0.;
-    }
-
-    /* Initialize the model's fuel combustion variables. */
-    /* The following are calculated by this function. */
-    Fuel_FineDead(catalog,model)        = 0.0;
-    Fuel_LiveMextFactor(catalog,model)  = 0.0;
-    Fuel_BulkDensity(catalog,model)     = 0.0;
-    Fuel_ResidenceTime(catalog,model)   = 0.0;
-    Fuel_PropFlux(catalog,model)        = 0.0;
-    Fuel_SlopeK(catalog,model)          = 0.0;
-    Fuel_WindB(catalog,model)           = 0.0;
-    Fuel_WindE(catalog,model)           = 0.0;
-    Fuel_WindK(catalog,model)           = 0.0;
-
-    for (life=0; life<FIRE_LIFE_CATS; life++)
-    {
-        Fuel_LifeAreaWtg(catalog,model,life) = 0.;
-        Fuel_LifeRxFactor(catalog,model,life) = 0.;
-        lifeLoad[life] = 0.;
-        lifeArea[life] = 0.;
-        lifeSavr[life] = 0.;
-        lifeHeat[life] = 0.;
-        lifeEtaS[life] = 0.;
-        lifeSeff[life] = 0.;
-        for ( size=0; size<FIRE_SIZE_CLASSES; size++ )
-            sizeClassAreaWtg[life][size] = 0.;
-    }
-
-    /* Initialize the model's fire behavior variables. */
-    /* These are calculated by Fire_SpreadNoWindNoSlope(). */
-    Fuel_Spread0(catalog,model)         = 0.;
-    Fuel_RxIntensity(catalog,model)     = 0.;
-    Fuel_HeatPerUnitArea(catalog,model) = 0.;
-
-    /* Initialize the model's fire behavior variables. */
-    /* These are calculated by Fire_SpreadWindSlopeMax(). */
-    Fuel_SpreadMax(catalog,model)       = 0.;
-    Fuel_AzimuthMax(catalog,model)      = 0.;
-    Fuel_EffectiveWind(catalog,model)   = 0.;
-    Fuel_PhiSlope(catalog,model)        = 0.;
-    Fuel_PhiWind(catalog,model)         = 0.;
-    Fuel_PhiEffWind(catalog,model)      = 0.;
-    Fuel_LwRatio(catalog,model)         = 1.;
-    Fuel_Eccentricity(catalog,model)    = 0.;
-    Fuel_WindLimit(catalog,model)       = 0;
-
-    /* Initialize the model's fire behavior variables. */
-    /* These are calculated by Fire_SpreadAtAzimuth(). */
-    Fuel_SpreadAny(catalog,model)       = 0.;
-    Fuel_AzimuthAny(catalog,model)      = 0.;
-    Fuel_ByramsIntensity(catalog,model) = 0.;
-    Fuel_FlameLength(catalog,model)     = 0.;
-    Fuel_ScorchHeight(catalog,model)    = 0.;
-
-    /* Initialize the model's environmental variables. */
-    Fuel_WindSpeed(catalog,model) = 0.;
-    Fuel_WindDir(catalog,model)   = 0.;
-    Fuel_Slope(catalog,model)     = 0.;
-    Fuel_Aspect(catalog,model)    = 0.;
-    for ( size=0; size<FIRE_MCLASSES; size++ )
-        Fuel_EnvMoisture(catalog,model,size) = 0.;
-
-    /* Initialize the model's combustion flag. */
-    Fuel_CombustionFlag(catalog,model) = 1;
-
-    /* If the model has no particles, we're all done. */
-    if ( Fuel_Particles(catalog,model) <= 0 )
-        return (FuelCat_Status(catalog) = FIRE_STATUS_OK);
-
-    /* Initialize local fuel bed and combustion variables. */
-    beta = betaOpt = sigma = ratio = aa = sigma15 = 0.;
-    gamma = gammaMax = c = e = fineLive = totalArea = 0.;
-
-    /* Accumulate surface areas by life category for the entire fuel bed. */
-    for ( particle=0; particle<Fuel_Particles(catalog,model); particle++ )
-    {
-        life = Fuel_Live(catalog,model,particle);
-        lifeArea[life] += Fuel_SurfaceArea(catalog,model,particle);
-        totalArea      += Fuel_SurfaceArea(catalog,model,particle);
-    }
-
-    /* If no surface area, we're all done. */
-    if ( totalArea <= Smidgen )
-        return (FuelCat_Status(catalog) = FIRE_STATUS_OK);
-
-    /* Surface area wtg factor for each particle within its life category */
-    /* and within its size class category (used to weight loading). */
-    for ( particle=0; particle<Fuel_Particles(catalog,model); particle++ )
-    {
-        life = Fuel_Live(catalog,model,particle);
-        if ( lifeArea[life] > Smidgen )
-        {
-            Fuel_AreaWtg(catalog,model,particle) =
-                Fuel_SurfaceArea(catalog,model,particle) / lifeArea[life];
-
-            size = Fuel_SizeClass(catalog,model,particle);
-            sizeClassAreaWtg[life][size] +=
-                Fuel_AreaWtg(catalog,model,particle);
-        }
-    }
-
-    /* Assign size class surface area weights to each particle. */
-    for ( particle=0; particle<Fuel_Particles(catalog,model); particle++ )
-    {
-        life = Fuel_Live(catalog,model,particle);
-        size = Fuel_SizeClass(catalog,model,particle);
-        Fuel_SizeAreaWtg(catalog,model,particle) = sizeClassAreaWtg[life][size];
-    }
-
-    /* Derive life category surface area weighting factors. */
-    for ( life=0; life<FIRE_LIFE_CATS; life++ )
-        Fuel_LifeAreaWtg(catalog,model,life) = lifeArea[life] / totalArea;
-
-    /* Accumulate life category weighted load, heat, savr, and seff. */
-    for ( particle=0; particle<Fuel_Particles(catalog,model); particle++ )
-    {
-        life = Fuel_Live(catalog,model,particle);
-
-        lifeLoad[life] += Fuel_SizeAreaWtg(catalog,model,particle)
-                        * Fuel_Load(catalog,model,particle)
-                        * (1. - Fuel_SiTotal(catalog,model,particle));
-
-        lifeSavr[life] += Fuel_AreaWtg(catalog,model,particle)
-                        * Fuel_Savr(catalog,model,particle);
-
-        lifeHeat[life] += Fuel_AreaWtg(catalog,model,particle)
-                        * Fuel_Heat(catalog,model,particle);
-
-        lifeSeff[life] += Fuel_AreaWtg(catalog,model,particle)
-                        * Fuel_SiEffective(catalog,model,particle);
-
-        Fuel_BulkDensity(catalog,model) += Fuel_Load(catalog,model,particle);
-
-        if ( Fuel_Density(catalog,model,particle) > Smidgen )
-            beta += Fuel_Load(catalog,model,particle)
-                  / Fuel_Density(catalog,model,particle);
-    }
-
-    /* Accumulate life category contribution to reaction intensity. */
-    for ( life=0; life<FIRE_LIFE_CATS; life++ )
-    {
-        sigma += Fuel_LifeAreaWtg(catalog,model,life) * lifeSavr[life];
-
-        lifeEtaS[life] = 1.;
-        if (lifeSeff[life] > 0.)
-        {
-            if ( (lifeEtaS[life] = 0.174 / pow(lifeSeff[life], 0.19)) > 1.0 )
-                lifeEtaS[life] = 1.0;
-        }
-
-        Fuel_LifeRxFactor(catalog,model,life) =
-            lifeLoad[life] * lifeHeat[life] * lifeEtaS[life];
-    }
-
-    /* Fuel model residence time */
-    Fuel_ResidenceTime(catalog,model) = 384. / sigma;
-
-    /* Fuel model bulk density */
-    if ( Fuel_Depth(catalog,model) > Smidgen )
-    {
-        Fuel_BulkDensity(catalog,model) /= Fuel_Depth(catalog,model);
-        beta /= Fuel_Depth(catalog,model);
-    }
-
-    /* Propagating flux depends upon sigma and beta only. */
-    Fuel_PropFlux(catalog,model) =
-        exp((0.792 + 0.681*sqrt(sigma)) * (beta+0.1)) / (192.+0.2595*sigma);
-
-    /* Gamma */
-    betaOpt   = 3.348 / (pow(sigma, 0.8189));
-    ratio     = beta / betaOpt;
-    aa        = 133. / (pow(sigma, 0.7913));
-    sigma15   = pow(sigma, 1.5);
-    gammaMax  = sigma15 / (495. + 0.0594*sigma15);
-    gamma     = gammaMax * pow(ratio, aa) * exp(aa * (1.-ratio));
-
-    /* Factor gamma into life category reaction intensity contribution. */
-    for ( life=0; life<FIRE_LIFE_CATS; life++ )
-        Fuel_LifeRxFactor(catalog,model,life) *= gamma;
-
-    /* Slope and wind intermediates constants for the fuel model. */
-    Fuel_SlopeK(catalog,model) = 5.275 * pow(beta, -0.3);
-    Fuel_WindB(catalog,model)  = 0.02526 * pow(sigma, 0.54);
-
-    c = 7.47 * exp(-0.133 * pow(sigma, 0.55));
-    e = 0.715 * exp(-0.000359 * sigma);
-    Fuel_WindK(catalog,model) = c * pow(ratio, -e);
-    Fuel_WindE(catalog,model) = pow(ratio, e) / c;
-
-    /* If no live fuel, we're done. */
-    if ( lifeLoad[FIRE_LIFE_LIVE] < Smidgen )
-        return (FuelCat_Status(catalog) = FIRE_STATUS_OK);
-
-    /*  Fine dead fuel and fine live fuel factors. */
-    for ( particle=0; particle<Fuel_Particles(catalog,model); particle++ )
-    {
-        if ( Fuel_Live(catalog,model,particle) )
-            fineLive
-                  += Fuel_Load(catalog,model,particle)
-                   * exp(-500. / Fuel_Savr(catalog,model,particle));
-        else
-            Fuel_FineDead(catalog,model)
-                  += Fuel_Load(catalog,model,particle)
-                   * Fuel_SigmaFactor(catalog,model,particle);
-    }
-
-    /* Live fuel extinction moisture factor. */
-    if ( fineLive > Smidgen )
-        Fuel_LiveMextFactor(catalog,model)
-            = 2.9 * Fuel_FineDead(catalog,model) / fineLive;
-
-    /* That's all, folks!. */
-    return (FuelCat_Status(catalog) = FIRE_STATUS_OK);
-}
-
-/*
- *******************************************************************************
- *
- *  Fire_SpreadNoWindNoSlope()
- *
- *  Description
- *      Calculates the fire reaction intensity and no-wind, no-slope spread
- *      rate given the fuel model, combustion, and moisture regime inputs.
- *
- *  Side Effects
- *      Updates the following fire behavior variables:
- *          Fuel_RxIntensity(catalog,model).
- *          Fuel_HeatPerUnitArea(catalog,model).
- *          Fuel_Spread0(catalog,model).
- *          Fuel_SpreadMax(catalog,model)  = Fuel_Spread0(catalog,model)
- *          Fuel_SpreadAny(catalog,model)  = Fuel_Spread0(catalog,model)
- *          Fuel_AzimuthAny(catalog,model) = 0.
- *          Fuel_AzimuthMax(catalog,model) = 0.
- *
- *  Function Returns
- *      FIRE_STATUS_OK or FIRE_STATUS_ERROR.
- *      Return status and error text are stored in the Fire Catalog's buffers.
- *
- *******************************************************************************
- */
-
-int
-Fire_SpreadNoWindNoSlope ( FuelCatalogPtr catalog, size_t model, double moisture[FIRE_MCLASSES] )
-   // FuelCatalogPtr catalog;     /* FuelCatalogData instance pointer           */
-   // size_t  model;              /* fuel model number            [0-maxModels] */
-   // double  moisture[FIRE_MCLASSES]; /* array of fuel moistures   (fractions) */
-{
-    size_t mclass, particle, life, nlive;
-    double wfmd;
-    double rbQig;
-    double fdmois;
-    double qig;
-    double ratio;
-    double lifeMoisture[FIRE_LIFE_CATS];
-    double lifeEtaM[FIRE_LIFE_CATS];
-    double lifeMext[FIRE_LIFE_CATS];
-
-    static size_t TimeLagClass[FIRE_SIZE_CLASSES] = {0, 0, 1, 1, 2, 2};
-
-    /* Validate the catalog and fuel model. */
-    assert(catalog!= NULL && FuelCat_MagicCookie(catalog)==FIRE_CATALOG_MAGIC);
-    if ( ! Fire_FuelModelExists(catalog,model) )
-    {
-        sprintf(FuelCat_Error(catalog),
-            "Fire_SpreadNoWindNoSlope(): el modelo de combustible %d no existe en el cat�logo de combustibles \"%s\".",
-            model, FuelCat_Name(catalog));
-        return (FuelCat_Status(catalog) = FIRE_STATUS_ERROR);
-    }
-
-    /*  Check if we must recalculate combustion intermediates. */
-    if ( ! Fuel_CombustionFlag(catalog,model) )
-    {
-        Fire_FuelCombustion(catalog,model);
-    }
-
-    /* Otherwise check if the moisture environment has changed. */
-    else
-    {
-        for ( mclass=0; mclass<FIRE_MCLASSES; mclass++ )
-            if ( ! Equal(moisture[mclass],Fuel_EnvMoisture(catalog,model,mclass)) )
-                break;
-
-        /* If no change in fuel moisture, no more computation is needed. */
-        if ( mclass == FIRE_MCLASSES )
-            return (FuelCat_Status(catalog) = FIRE_STATUS_OK);
-    }
-
-    /* Store the new moistures in the fuel's environmental moisture array. */
-    for ( mclass=0; mclass<FIRE_MCLASSES; mclass++ )
-        Fuel_EnvMoisture(catalog,model,mclass) = moisture[mclass];
-
-    /* Initialize the model's fire behavior variables. */
-    /* These are calculated by this function. */
-    Fuel_Spread0(catalog,model)         = 0.;
-    Fuel_RxIntensity(catalog,model)     = 0.;
-    Fuel_HeatPerUnitArea(catalog,model) = 0.;
-
-    /* Initialize the model's fire behavior variables. */
-    /* These are calculated by Fire_SpreadWindSlopeMax(). */
-    Fuel_SpreadMax(catalog,model)       = 0.;
-    Fuel_AzimuthMax(catalog,model)      = 0.;
-
-    /* Initialize the model's fire behavior variables. */
-    /* These are calculated by Fire_SpreadAtAzimuth(). */
-    Fuel_SpreadAny(catalog,model)       = 0.;
-    Fuel_AzimuthAny(catalog,model)      = 0.;
-    Fuel_ByramsIntensity(catalog,model) = 0.;
-    Fuel_FlameLength(catalog,model)     = 0.;
-    Fuel_ScorchHeight(catalog,model)    = 0.;
-
-    /* If no fuel particles, return. */
-    if (Fuel_Particles(catalog,model) <= 0)
-        return (FuelCat_Status(catalog) = FIRE_STATUS_OK);
-
-    /* Initialize local variables. */
-    wfmd = fdmois = rbQig = 0.;
-    for ( life=0; life<FIRE_LIFE_CATS; life++ )
-    {
-        lifeMoisture[life] = 0.;
-        lifeEtaM[life] = 0.;
-        lifeMext[life] = 0.;
-    }
-
-    /* Assign particle moistures based upon their size class. */
-    nlive = 0;
-    for ( particle=0; particle<Fuel_Particles(catalog,model); particle++ )
-    {
-        /* if this is a dead fuel, accumulate its wtd fuel moisture. */
-        if ( Fuel_Live(catalog,model,particle) == FIRE_LIFE_DEAD )
-        {
-            mclass = TimeLagClass[Fuel_SizeClass(catalog,model,particle)];
-            wfmd += moisture[mclass]
-                  * Fuel_SigmaFactor(catalog,model,particle)
-                  * Fuel_Load(catalog,model,particle);
-        }
-        else
-        {
-            nlive++;
-            mclass = (Fuel_Type(catalog,model,particle) == FIRE_TYPE_HERB) ?
-                FIRE_MCLASS_HERB : FIRE_MCLASS_WOOD;
-        }
-
-        /* Assign this particle the fuel moisture for its size class. */
-        Fuel_Moisture(catalog,model,particle) = moisture[mclass];
-    }
-
-    /* Compute live fuel extinction moisture. */
-    if ( nlive )
-    {
-        fdmois = ( Fuel_FineDead(catalog,model) > Smidgen ) ?
-            (wfmd / Fuel_FineDead(catalog,model)) : 0.;
-
-        lifeMext[FIRE_LIFE_LIVE]
-            = ((Fuel_LiveMextFactor(catalog,model)
-            * (1.0 - fdmois/Fuel_Mext(catalog,model))) - 0.226);
-
-        if ( lifeMext[FIRE_LIFE_LIVE] < Fuel_Mext(catalog,model) )
-            lifeMext[FIRE_LIFE_LIVE] = Fuel_Mext(catalog,model);
-    }
-
-    /* Dead fuel extinction moisture is a fuel model input. */
-    lifeMext[FIRE_LIFE_DEAD] = Fuel_Mext(catalog,model);
-
-    /* Compute category weighted moisture and accumulate the rbQig. */
-    for (particle=0; particle<Fuel_Particles(catalog,model); particle++)
-    {
-        qig = 250. + 1116. * Fuel_Moisture(catalog,model,particle);
-
-        life = Fuel_Live(catalog,model,particle);
-
-        lifeMoisture[life] += Fuel_AreaWtg(catalog,model,particle)
-                            * Fuel_Moisture(catalog,model,particle);
-
-        rbQig += qig
-               * Fuel_AreaWtg(catalog,model,particle)
-               * Fuel_LifeAreaWtg(catalog,model,life)
-               * Fuel_SigmaFactor(catalog,model,particle);
-    }
-
-    /* Complete the rbQig calculation. */
-    rbQig *= Fuel_BulkDensity(catalog,model);
-
-    /*  Compute moisture damping coeff by life class, and combine with the */
-    /*  life class's rx factor to get the total reaction intensity. */
-    for (life=0; life<FIRE_LIFE_CATS; life++)
-    {
-        ratio = 0.;
-        if ( lifeMext[life] > Smidgen )
-        {
-            ratio = lifeMoisture[life] / lifeMext[life];
-            lifeEtaM[life] =
-                1.0 - 2.59*ratio + 5.11*ratio*ratio - 3.52*ratio*ratio*ratio;
-        }
-
-        /* If category moisture exceeds category extinction moisture, */
-        /* the damping coefficient is zero. */
-        if ( lifeMoisture[life] >= lifeMext[life] )
-            lifeEtaM[life] = 0.;
-
-        /* Accumulate total reaction intensity. */
-        Fuel_RxIntensity(catalog,model)
-            += Fuel_LifeRxFactor(catalog,model,life)
-             * lifeEtaM[life];
-    }
-
-    /* Calculate heat per unit area from rx intensity and residence time. */
-    Fuel_HeatPerUnitArea(catalog,model)
-        = Fuel_RxIntensity(catalog,model)
-        * Fuel_ResidenceTime(catalog,model);
-
-    /* Calculate no-wind, no-slope spread rate. */
-    Fuel_Spread0(catalog,model)
-        = (rbQig > Smidgen)
-        ? Fuel_RxIntensity(catalog,model) * Fuel_PropFlux(catalog,model) / rbQig
-        : 0.;
-
-    /* Re-initialize spread in maximum and any azimuth to no wind-no slope. */
-    Fuel_SpreadMax(catalog,model) = Fuel_Spread0(catalog,model);
-    Fuel_SpreadAny(catalog,model) = Fuel_Spread0(catalog,model);
-    Fuel_AzimuthMax(catalog,model) = Fuel_AzimuthAny(catalog,model) = 0.;
-
-    return (FuelCat_Status(catalog) = FIRE_STATUS_OK);
-}
-
-/*
- *******************************************************************************
- *
- *  Fire_SpreadWindSlopeMax()
- *
- *  Description
- *      Calculates maximum fire spread rate and direction under the given
- *      wind-slope conditions.  Results depend only upon:
- *      - no wind-slope spread rate
- *      - wind speed and direction
- *      - aspect and slope
- *
- *  Side Effects
- *      Updates the following variables:
- *          Fuel_Slope()                      = slope;
- *          Fuel_PhiSlope().
- *          Fuel_Wind()                       = windFpm;
- *          Fuel_PhiWind().
- *          Fuel_Aspect(catalog,model)        = aspect;
- *          Fuel_WindDir(catalog,model)       = windDeg;
- *          Fuel_PhiEffWind(catalog,model)    = phiEw;
- *          Fuel_EffectiveWind(catalog,model) = effectiveWind;
- *          Fuel_WindLimit(catalog,model)     = windLimit;
- *          Fuel_SpreadMax(catalog,model)     = spreadMax;
- *          Fuel_AzimuthMax(catalog,model)    = azimuthMax;
- *          Fuel_LwRatio(catalog,model)       = lwRatio;
- *          Fuel_Eccentricity(catalog,model)  = eccentricity;
- *
- *      Resets Fire_SpreadAtAzimuth() variables:
- *          Fuel_SpreadAny(catalog,model)       = spreadMax;
- *          Fuel_AzimuthAny(catalog,model)      = azimuthMax;
- *          Fuel_ByramsIntensity(catalog,model) = 0.;
- *          Fuel_FlameLength(catalog,model)     = 0.;
- *          Fuel_ScorchHeight(catalog,model)    = 0.;
- *
- *      Previous Fire_SpreadAtAzimiuth() results become obsolete for this model.
- *
- *  Function Returns
- *      FIRE_STATUS_OK or FIRE_STATUS_ERROR.
- *      Return status and error text are stored in the Fire Catalog's buffers.
- *
- *******************************************************************************
- */
-
-int
-Fire_SpreadWindSlopeMax ( FuelCatalogPtr catalog, size_t model, double windFpm, double windDeg, double slope, double aspect )
-   // FuelCatalogPtr catalog;     /* FuelCatalogData instance pointer           */
-   // size_t  model;              /* fuel model number            [0-maxModels] */
-   // double  windFpm;            /* wind speed                        (ft/min) */
-   // double  windDeg;            /* wind bearing vector      (compass degrees) */
-   // double  slope;              /* slope                         (rise/reach) */
-   // double  aspect;             /* aspect (downslope)   azimuth (compass deg) */
-{
-    double upslope, azimuthMax, phiEw;
-    double splitDeg, splitRad;
-    double slpRate, wndRate, rv, spreadMax;
-    double x, y, al, a;
-    double maxWind, effectiveWind, lwRatio, eccentricity;
-    size_t doEffectiveWind, checkWindLimit, windLimit;
-
-    /* Validate the catalog and fuel model. */
-    assert(catalog!= NULL && FuelCat_MagicCookie(catalog)==FIRE_CATALOG_MAGIC);
-    if ( ! Fire_FuelModelExists(catalog,model) )
-    {
-        sprintf(FuelCat_Error(catalog),
-            "Fire_SpreadMax(): el modelo de combustible %d no existe en el cat�logo de combustibles \"%s\".",
-            model, FuelCat_Name(catalog));
-        return (FuelCat_Status(catalog) = FIRE_STATUS_ERROR);
-    }
-
-    /* Recalculate slope factors ONLY if different from previous model input. */
-    if ( ! Equal(Fuel_Slope(catalog,model),slope) )
-    {
-        Fuel_PhiSlope(catalog,model) =
-            Fuel_SlopeK(catalog,model) * slope * slope;
-        Fuel_Slope(catalog,model) = slope;
-    }
-
-    /* Recalculate wind factors ONLY if different from previous model input. */
-    if ( ! Equal(Fuel_WindSpeed(catalog,model),windFpm) )
-    {
-        Fuel_PhiWind(catalog,model) = (windFpm < Smidgen) ? 0. :
-            Fuel_WindK(catalog,model) * pow(windFpm, Fuel_WindB(catalog,model));
-        Fuel_WindSpeed(catalog,model) = windFpm;
-    }
-
-    /* Combine wind and slope factors. */
-    phiEw = Fuel_PhiSlope(catalog,model) + Fuel_PhiWind(catalog,model);
-    windLimit = 0;
-    lwRatio = 1.;
-    eccentricity = 0.;
-    upslope = (aspect>=180.) ? aspect-180. : aspect+180.;
-
-    /* Situation 1: no fire spread or reaction intensity. */
-    if ( Fuel_Spread0(catalog,model) < Smidgen )
-    {
-        spreadMax = 0.;
-        azimuthMax = 0;
-        /* There IS an effective wind even if there is no fire. */
-        doEffectiveWind = 1;
-        /* But since BEHAVE doesn't calculate effective wind when no spread. */
-        /* we wont either. */
-        effectiveWind = 0.;
-        doEffectiveWind = 0;
-        checkWindLimit = 0;
-    }
-
-    /* Situation 2: no wind and no wind */
-    else if ( phiEw < Smidgen )
-    {
-        phiEw = 0.;
-        effectiveWind = 0.;
-        doEffectiveWind = 0;
-        spreadMax = Fuel_Spread0(catalog,model);
-        azimuthMax = 0;
-        checkWindLimit = 0;
-    }
-
-    /* Situation 3: wind with no slope. */
-    else if ( slope < Smidgen )
-    {
-        effectiveWind = windFpm;
-        doEffectiveWind = 0;
-        spreadMax = Fuel_Spread0(catalog,model) * (1. + phiEw);
-        azimuthMax = windDeg;
-        checkWindLimit = 1;
-    }
-
-    /* Situation 4: slope with no wind. */
-    else if ( windFpm < Smidgen )
-    {
-        doEffectiveWind = 1;
-        spreadMax = Fuel_Spread0(catalog,model) * (1. + phiEw);
-        azimuthMax = upslope;
-        checkWindLimit = 1;
-    }
-
-    /* Situation 5: wind blows upslope. */
-    else if ( Equal(upslope,windDeg) )
-    {
-        doEffectiveWind = 1;
-        spreadMax = Fuel_Spread0(catalog,model) * (1. + phiEw);
-        azimuthMax = upslope;
-        checkWindLimit = 1;
-    }
-
-    /* Situation 6: wind blows cross slope. */
-    else
-    {
-        /* Recalculate spread rate in the optimal direction. */
-        splitDeg = (upslope<=windDeg) ? windDeg-upslope : 360.-upslope+windDeg;
-        splitRad = DegreesToRadians(splitDeg);
-        slpRate  = Fuel_Spread0(catalog,model) * Fuel_PhiSlope(catalog,model);
-        wndRate  = Fuel_Spread0(catalog,model) * Fuel_PhiWind(catalog,model);
-        x        = slpRate + wndRate * cos(splitRad);
-        y        = wndRate * sin(splitRad);
-        rv       = sqrt(x*x + y*y);
-        spreadMax= Fuel_Spread0(catalog,model) + rv;
-
-        /* Recalculate phiEw in the optimal direction. */
-        phiEw    = spreadMax / Fuel_Spread0(catalog,model) - 1.0;
-        doEffectiveWind = (phiEw > Smidgen) ? 1 : 0;
-        checkWindLimit = 1;
-
-        /* Recalculate direction of maximum spread in azimuth degrees. */
-        al = asin(fabs(y) / rv);
-        if ( x >= 0. )
-            a = (y >= 0.) ? al          : M_PI + M_PI - al;
-        else
-            a = (y >= 0.) ? (M_PI - al) : (M_PI + al);
-
-        splitDeg = RadiansToDegrees(a);
-        if ( (azimuthMax = upslope + splitDeg) > 360. )
-            azimuthMax -= 360.;
-    }
-
-    /* Recalculate effective wind speed based upon phiEw. */
-    if ( doEffectiveWind )
-        effectiveWind = pow( (phiEw * Fuel_WindE(catalog,model)),
-                             (1. / Fuel_WindB(catalog,model)) );
-
-    /* If effective wind exceeds maximum wind, scale back spread & phiEw. */
-    if ( checkWindLimit )
-    {
-        maxWind = 0.9 * Fuel_RxIntensity(catalog,model);
-        if ( effectiveWind > maxWind )
-        {
-            phiEw = (maxWind < Smidgen) ? 0. :
-                Fuel_WindK(catalog,model) * pow(maxWind, Fuel_WindB(catalog,model));
-
-            spreadMax = Fuel_Spread0(catalog,model) * (1. + phiEw);
-            effectiveWind = maxWind;
-            windLimit = 1;
-        }
-    }
-
-    /* Determine fire ellipse parameters from the effective wind speed. */
-    /* = 1. + 0.25 * (Fuel_EffectiveWind(catalog,model) / 88.0); */
-    if ( effectiveWind > Smidgen )
-    {
-        lwRatio = 1. + 0.002840909 * effectiveWind;
-        eccentricity = sqrt(lwRatio * lwRatio - 1.0) / lwRatio;
-    }
-
-    /* Store the results. */
-    Fuel_Aspect(catalog,model)       = aspect;
-    Fuel_WindDir(catalog,model)      = windDeg;
-    Fuel_PhiEffWind(catalog,model)   = phiEw;
-    Fuel_EffectiveWind(catalog,model)= effectiveWind;
-    Fuel_WindLimit(catalog,model)    = windLimit;
-    Fuel_SpreadMax(catalog,model)    = Fuel_SpreadAny(catalog,model)  = spreadMax;
-    Fuel_AzimuthMax(catalog,model)   = Fuel_AzimuthAny(catalog,model) = azimuthMax;
-    Fuel_LwRatio(catalog,model)      = lwRatio;
-    Fuel_Eccentricity(catalog,model) = eccentricity;
-
-    /* Initialize behavior variables updated by Fire_SpreadAtAzimuth(). */
-    Fuel_ByramsIntensity(catalog,model) = 0.;
-    Fuel_FlameLength(catalog,model)     = 0.;
-    Fuel_ScorchHeight(catalog,model)    = 0.;
-
-    return (FuelCat_Status(catalog) = FIRE_STATUS_OK);
-}
-
-/*
- *******************************************************************************
- *
- *  Fire_SpreadAtAzimuth()
- *
- *  Description
- *      Calculates fire spread rate in a specified direction and optionally
- *      calculates the fireline intensity, flame length, and scorch height
- *      along the fire spread vector.
- *
- *  Side Effects
- *      The following variables are updated:
- *          Fuel_SpreadAny(catalog,model)
- *          Fuel_AzimuthAny(catalog,model) == azimuth;
- *          Fuel_ByramsIntensity(catalog,model) is updated if FIRE_BYRAMS.
- *          Fuel_FlameLength(catalog,model) is updated if FIRE_FLAME.
- *          Fuel_ScorchHeight(catalog,model) is updated if FIRE_SCORCH.
- *  Notes
- *      The calculations depend upon the most recent calls to
- *      Fire_SpreadNoWindNoSlope() and Fire_SpreadWindSlopeMax() for this model.
- *
- *      The input azimuth is the degrees clockwise from north.
- *
- *  Function Returns
- *      FIRE_STATUS_OK or FIRE_STATUS_ERROR.
- *      Return status and error text are stored in the Fire Catalog's buffers.
- *
- *******************************************************************************
- */
-
-int
-Fire_SpreadAtAzimuth ( FuelCatalogPtr catalog, size_t model, double azimuth, size_t which )
-   // FuelCatalogPtr catalog;     /* FuelCatalogData instance pointer           */
-   // size_t  model;              /* fuel model number            [0-maxModels] */
-   // double  azimuth;            /* fire spread azimuth     (deg from upslope) */
-   // size_t  which;      /* FIRE_NONE | FIRE_BYRAMS | FIRE_FLAME | FIRE_SCORCH */
-{
-    double dir;
-    double radians;
-    double byrams;
-    double mph;
-    size_t lo, hi, mid, n;
-
-    /* Validate catalog and the fuel model. */
-    assert(catalog!= NULL && FuelCat_MagicCookie(catalog)==FIRE_CATALOG_MAGIC);
-    if ( ! Fire_FuelModelExists(catalog,model) )
-    {
-        sprintf(FuelCat_Error(catalog),
-            "Fire_SpreadAtAzimuth(): el modelo de combustible %d no existe en el cat�logo de combustibles \"%s\".",
-            model, FuelCat_Name(catalog));
-        return (FuelCat_Status(catalog) = FIRE_STATUS_ERROR);
-    }
-
-    /* Situation 1: no fire or reaction intensity, so no Byrams or flame. */
-    if ( Fuel_SpreadMax(catalog,model) < Smidgen )
-        return (FuelCat_Status(catalog) = FIRE_STATUS_OK);
-
-    /* Situation 2: phiEw is zero OR azimuth is in the max spread direction */
-    if ( Fuel_PhiEffWind(catalog,model) < Smidgen
-      || Equal(Fuel_AzimuthMax(catalog,model),azimuth) )
-    {
-        Fuel_SpreadAny(catalog,model) = Fuel_SpreadMax(catalog,model);
-    }
-
-    /* Situation 3: wind and/or slope and azimuth not in max spread direction */
-    else
-    {
-        /* Angle between maximum spread azimuth and requested azimuth. */
-        if ( (dir = fabs(Fuel_AzimuthMax(catalog,model) - azimuth)) > 180. )
-            dir = 360. - dir;
-        radians = DegreesToRadians(dir);
-
-        /* Calculate the fire spread rate in this azimuth. */
-        Fuel_SpreadAny(catalog,model)
-            = Fuel_SpreadMax(catalog,model)
-            * (1. - Fuel_Eccentricity(catalog,model))
-            / (1. - Fuel_Eccentricity(catalog,model) * cos(radians));
-    }
-    Fuel_AzimuthAny(catalog,model) = azimuth;
-
-    /* Additional fire behavior outputs. */
-    if ( which )
-    {
-        /* Must compute Byram's if any of the three are requested. */
-        byrams = Fuel_ResidenceTime(catalog,model)
-               * Fuel_SpreadAny(catalog,model)
-               * Fuel_RxIntensity(catalog,model)
-               / 60.;
-
-        /* Byrams intensity is requested. */
-        if ( which & FIRE_BYRAMS )
-            Fuel_ByramsIntensity(catalog,model) = byrams;
-
-        /* Flame length is requested. */
-        if ( (which & FIRE_FLAME) )
-        {
-            if ( byrams < Smidgen )
-            {
-                Fuel_FlameLength(catalog,model) = 0.;
-            }
-            else
-            {
-                /* Use lookup table if it exists & includes this intensity. */
-                if ( (n = FuelCat_FlameClasses(catalog)) > 0
-                  && FuelCat_FlameArray(catalog)[n-1] > byrams )
-                {
-                    hi = n-1;
-                    lo = 0;
-                    do {
-                        mid = lo + (hi-lo)/2;
-                        if ( FuelCat_FlameArray(catalog)[mid] > byrams )
-                            hi = mid;
-                        else
-                            lo = mid + 1;
-                    } while (lo != hi);
-                    Fuel_FlameLength(catalog,model) =
-                        FuelCat_FlameStep(catalog) * (lo+1);
-                }
-                /* otherwise compute flame length from scratch. */
-                else
-                {
-                    Fuel_FlameLength(catalog,model) = 0.45 * pow(byrams, 0.46);
-                }
-            }
-        }
-
-        /* Scorch height is requested. */
-        if ( (which & FIRE_SCORCH) )
-        {
-            if ( byrams < Smidgen )
-            {
-                Fuel_ScorchHeight(catalog,model) = 0.;
-            }
-            else
-            {
-                mph = Fuel_WindSpeed(catalog,model) / 88.;
-                Fuel_ScorchHeight(catalog,model) =
-                    pow(byrams, 1.166667) / sqrt(byrams + (mph * mph * mph));
-            /*  Fuel_ScorchHeight(catalog,model) *= (63. / (140. - temp_f) ); */
-            }
-        }
-    }
-
-    return (FuelCat_Status(catalog) = FIRE_STATUS_OK);
-}
-
-/*
- *******************************************************************************
- *
- *  Fire_FlameScorch()
- *
- *  Description
- *      Calculates the flame length and/or scorch height for the current
- *      Byram's intensity and azimuth (as determined by the most recent
- *      call to Fire_SpreadAtAzimuth()).
- *      Uses the Flame Length Table if it exists.
- *      Offers a method of getting flame length if Fire_SpreadAtAzimuth()
- *      is not calculating it.
- *
- *  Side Effects
- *      The following variables are updated:
- *          Fuel_FlameLength(catalog,model) is updated.
- *          Fuel_ScorchHeight(catalog,model)
- *  Notes
- *      The calculations depend upon the most recent calls to
- *      Fire_SpreadNoWindNoSlope(), Fire_SpreadWindSlopeMax(), and
- *      Fire_SpreadAtAzimuth() for this model.
- *
- *  Function Returns
- *      FIRE_STATUS_OK or FIRE_STATUS_ERROR.
- *      Return status and error text are stored in the Fire Catalog's buffers.
- *
- *******************************************************************************
- */
-
-int
-Fire_FlameScorch ( FuelCatalogPtr catalog, size_t model, size_t which )
-   // FuelCatalogPtr catalog;     /* FuelCatalogData instance pointer           */
-   // size_t  model;              /* fuel model number            [0-maxModels] */
-   // size_t  which;      /* FIRE_NONE | FIRE_BYRAMS | FIRE_FLAME | FIRE_SCORCH */
-{
-    double byrams;
-    double mph;
-    size_t lo, hi, mid, n;
-
-    /* Validate catalog and the fuel model. */
-    assert(catalog!= NULL && FuelCat_MagicCookie(catalog)==FIRE_CATALOG_MAGIC);
-    if ( ! Fire_FuelModelExists(catalog,model) )
-    {
-        sprintf(FuelCat_Error(catalog),
-            "Fire_FlameScorch(): el modelo de combustible %d no existe en el cat�logo de combustibles \"%s\".",
-            model, FuelCat_Name(catalog));
-        return (FuelCat_Status(catalog) = FIRE_STATUS_ERROR);
-    }
-
-    byrams = Fuel_ResidenceTime(catalog,model)
-           * Fuel_SpreadAny(catalog,model)
-           * Fuel_RxIntensity(catalog,model)
-           / 60.;
-
-    /* Flame length is requested. */
-    if ( (which & FIRE_FLAME) )
-    {
-        if ( byrams < Smidgen )
-        {
-            Fuel_FlameLength(catalog,model) = 0.;
-        }
-        else
-        {
-            /* Use lookup table if it exists & includes this intensity. */
-            if ( (n = FuelCat_FlameClasses(catalog)) > 0
-              && FuelCat_FlameArray(catalog)[n-1] > byrams )
-            {
-                hi = n-1;
-                lo = 0;
-                do {
-                    mid = lo + (hi-lo)/2;
-                    if ( FuelCat_FlameArray(catalog)[mid] > byrams )
-                        hi = mid;
-                    else
-                        lo = mid + 1;
-                } while (lo != hi);
-                Fuel_FlameLength(catalog,model) =
-                    FuelCat_FlameStep(catalog) * (lo+1);
-            }
-            /* otherwise compute flame length from scratch. */
-            else
-            {
-                Fuel_FlameLength(catalog,model) = 0.45 * pow(byrams, 0.46);
-            }
-        }
-    }
-
-    /* Scorch height is requested. */
-    if ( (which & FIRE_SCORCH) )
-    {
-        if ( byrams < Smidgen )
-        {
-            Fuel_ScorchHeight(catalog,model) = 0.;
-        }
-        else
-        {
-            mph = Fuel_WindSpeed(catalog,model) / 88.;
-            Fuel_ScorchHeight(catalog,model) =
-                pow(byrams, 1.166667) / sqrt(byrams + (mph * mph * mph));
-        /*  Fuel_ScorchHeight(catalog,model) *= (63. / (140. - temp_f) ); */
-        }
-    }
-
-    return (FuelCat_Status(catalog) = FIRE_STATUS_OK);
-}
-
-/*
- *******************************************************************************
- *
- *  Fire_FlameLengthTable()
- *
- *  Description
- *      Creates a flame length lookup table containing "flameClasses" classes
- *      with each class spanning "flameStep" feet.
- *
- *  Discussion
- *      Since flame length is strictly an output variable (e.g., it is never
- *      used as the basis for subsequent computations), we can usually afford
- *      to round it to some precision that makes sense to fire managers.
- *      Usually this will be in 1 foot or perhaps 6 inch increments.  The call
- *
- *
- *      creates a flame length table for flame lengths of 1 through 500 feet.
- *
- *      Fire_SpreadAtAzimuth() uses the flame table (if one is defined for the
- *      catalog) to avoid using the costly pow() function for highly iterative
- *      flame length calculations, saving a considerable amount of processing
- *      time.  Fire_SpreadAtAzimuth() will still use the pow() function to
- *      compute flame length if (1) a flame length table is not defined,
- *      (2) the fireline intensity exceeds the upper limit of the currently
- *      defined flame length table, or (3) the flame length table becomes
- *      undefined by a Fire_FlameLengthTable(catalog, 0, 0.) call.
- *
- *
- *  Examples
- *      Fire_FlameLengthTable(catalog, 200, 1.0);
- *          Creates a table for flame lengths of 1 through 200 feet in 1-foot
- *          intervals.  Any previously defined flame length table for this
- *          fuel catalog is destroyed.
- *
- *      Fire_FlameLengthTable(catalog, 500, 0.5);
- *          Creates a table for flame lengths of 0.5 through 250 feet in 6-inch
- *          intervals.  ANy previously defined flame length table for this
- *          fuel catalog is destroyed.
- *
- *      Fire_FlameLengthTable(catalog, 0, 0.);
- *          Destroys any existing flame length table for this catalog, and
- *          forces actual flame length computation using pow() function.
- *
- *  Side Effects
- *      If a flame length table currently exists, it is destroyed, and the
- *      FuelCat_FlameArray(), FuelCat_FlameClasses(), and
- *      FuelCat_FlameStep() are set to NULL, 0, and 0.0, respectively.
- *
- *      If fireClasses > 0, allocates a flame length table and fills it with
- *      the fireline intensity associated with the upper limit of each flame
- *      length class.  The FuelCat_FlameArray(), FuelCat_FlameClasses(), and
- *      FuelCat_FlameStep() are then updated.
- *
- *  Function Returns
- *      FIRE_STATUS_OK or FIRE_STATUS_ERROR.
- *      Return status and error text are stored in the Fire Catalog's buffers.
- *
- *******************************************************************************
- */
-
-int
-Fire_FlameLengthTable ( FuelCatalogPtr catalog, size_t flameClasses, double flameStep )
-   // FuelCatalogPtr catalog;     /* FuelCatalogData instance pointer           */
-   // size_t  flameClasses;       /* number of flame length classes             */
-   // double  flameStep;          /* flame length step value per class          */
-{
-    double power, flame;
-    size_t i;
-
-    /* Validate the catalog. */
-    assert(catalog!= NULL && FuelCat_MagicCookie(catalog)==FIRE_CATALOG_MAGIC);
-
-    /* If a flame table already exists, destroy it. */
-    if ( FuelCat_FlameArray(catalog) )
-    {
-        free(FuelCat_FlameArray(catalog));
-        FuelCat_FlameArray(catalog)   = NULL;
-        FuelCat_FlameClasses(catalog) = 0;
-        FuelCat_FlameStep(catalog)    = 0.0;
-    }
-
-    /* If flameClasses is zero, simply return. */
-    if ( flameClasses == 0 )
-        return (FuelCat_Status(catalog) = FIRE_STATUS_OK);
-
-    /* Otherwise create a new flame table. */
-    if ( (FuelCat_FlameArray(catalog) = (double *)
-        calloc(flameClasses, sizeof(double))) == NULL )
-    {
-        sprintf(FuelCat_Error(catalog),
-            "Fire_FlameLengthTable(): imposible asignar tabla de longitud de llama con %d clases de %f pies.",
-            flameClasses, flameStep);
-        return (FuelCat_Status(catalog) = FIRE_STATUS_ERROR);
-    }
-
-    /* Fill the array. */
-    power = 1. / .46;
-    for ( i=0; i<flameClasses; i++ )
-    {
-        flame = flameStep * (i+1);
-        FuelCat_FlameArray(catalog)[i] = pow((flame / .45), power);
-    }
-    FuelCat_FlameClasses(catalog) = flameClasses;
-    FuelCat_FlameStep(catalog)    = flameStep;
-
-    return (FuelCat_Status(catalog) = FIRE_STATUS_OK);
-}
-
-/*
- *******************************************************************************
- *
- *  Fire_FuelCatalogCreate()
- *
- *  Description
- *      Creates a new fuel model catalog capable of holding fuel models with
- *      id's in the range [0..maxModel].
- *      The catalog is filled by subsequent calls to Fire_FuelModelCreate().
- *
- *  Side Effects
- *      Allocates a new FuelCatalogData structure.
- *      Allocates an error text buffer for the catalog.
- *      Allocates a name for the catalog.
- *      Allocates an array of pointers to FuelData structures (the FuelData
- *      structures themselves are allocated by Fire_FuelModelCreate() and
- *      their pointers are stored here).
- *
- *  Notes
- *      The FuelCatalog contains a dynamically-allocated array of pointers
- *      to FuelData blocks.  These pointers are initially NULL and are
- *      subsequently assigned by Fire_FuelModelCreate().  The array provides
- *      the programmer with a means of directly accessing fuel models via
- *      their model number, which is handy when simulating fire growth.
- *
- *  Function Returns
- *      While most FireLib functions return a status code, this one returns
- *      a pointer to the new FuelCatalogData on success or NULL if unable
- *      to allocate any of the dynamic structures.
- *
- *******************************************************************************
- */
-
-FuelCatalogPtr
-Fire_FuelCatalogCreate ( char *name, size_t maxModels )
-   // char  *name;                /* FuelCatalogData instance name */
-   // size_t maxModels;           /* maximum modelId allowed in this catalog */
-{
-    FuelCatalogPtr catalog;
-    static char *blank = {""};
-
-    /* Catch a NULL name. */
-    if ( name == NULL )
-        name = blank;
-
-    /* Allocate the FireCatalogData structure. */
-    if ( (catalog = (FuelCatalogPtr) malloc(sizeof(FuelCatalogData))) == NULL )
-    {
-        fprintf(stderr,
-            "Fire_FuelCatalogCreate(): imposible asignar el objeto \"%s\" del cat�logo de combustibles.\n",
-            name);
-        return (NULL);
-    }
-
-    /* Assign the magic cookie right away. */
-    FuelCat_MagicCookie(catalog) = FIRE_CATALOG_MAGIC;
-
-    /* Allocate and store the catalog instance name. */
-    if ( (FuelCat_Name(catalog) = strdup(name)) == NULL )
-    {
-        fprintf(stderr,
-            "Fire_FuelCatalogCreate(): imposible duplicar el nombre \"%s\" del cat�logo de combustibles.\n",
-            name);
-        free(catalog);
-        return (NULL);
-    }
-
-    /* Allocate the FireCatalogData error message buffer. */
-    if ( (FuelCat_Error(catalog) =
-        (char *) calloc(FIRE_ERROR_BUFFER_SIZE, sizeof(char))) == NULL )
-    {
-        fprintf(stderr,
-            "Fire_FuelCatalogCreate(): imposible asignar el bufer de error  \"%s\" del cat�logo de combustibles.\n",
-            name);
-        free(FuelCat_Name(catalog));
-        free(catalog);
-        return (NULL);
-    }
-    FuelCat_Status(catalog) = FIRE_STATUS_ERROR;
-
-    /* Allocate a FuelModelPtr array to handle models [0..maxModels]. */
-    maxModels++;
-    FuelCat_MaxModels(catalog) = maxModels;
-    if ( (FuelCat_ModelArray(catalog) = (FuelModelPtr *)
-        calloc(FuelCat_MaxModels(catalog), sizeof(FuelModelPtr))) == NULL )
-    {
-        fprintf(stderr,
-            "Fire_FuelCatalogCreate(): imposible asignar \"%s\" con %d modelos de combustible del cat�logo de combustibles.\n",
-            name, maxModels);
-        free(FuelCat_Error(catalog));
-        free(FuelCat_Name(catalog));
-        free(catalog);
-        return (NULL);
-    }
-
-    /* Initialize variables and return ptr to this instance. */
-    FuelCat_FlameArray(catalog)   = NULL;
-    FuelCat_FlameClasses(catalog) = 0;
-    FuelCat_FlameStep(catalog)    = 0.0;
-    FuelCat_Status(catalog)       = FIRE_STATUS_OK;
-    return (catalog);
-}
-
-/*
- *******************************************************************************
- *
- *  Fire_FuelCatalogCreateStandard()
- *
- *  Description
- *      Creates a new fuel model catalog capable of holding fuel models with
- *      id's in the range [0..maxModel].
- *      The catalog is then filled with the 13 standard fire behavior fuel
- *      models.  Other models may be added by subsequent calls to
- *      Fire_FuelModelCreate().
- *
- *  Side Effects
- *      Allocates a new FuelCatalogData structure.
- *      Fills the catalog with standard fuels models 0-13.
- *
- *  Function Returns
- *      While most FireLib functions return a status code, this one returns
- *      a pointer to the new FuelCatalogData on success, or NULL if unable
- *      to allocate any of the dynamic structures.
- *
- *******************************************************************************
- */
-
-FuelCatalogPtr
-Fire_FuelCatalogCreateStandard (char *name, size_t maxModels )
-   // char  *name;                /* FuelCatalogData instance name */
-   // size_t maxModels;           /* maximum modelId allowed in this catalog */
-{
-    FuelCatalogPtr catalog;
-    double stot, seff, heat, dens, adjust;
-    size_t m, p;
-
-    /* Fuel model definitions. */
-    typedef struct {
-        char *name; double depth; double mext; size_t maxParticles; char *desc;
-    } StandardModels;
-
-    StandardModels M[14] = {
-        {"NoFuel", 0.1, 0.01, 0, "No Combustible Fuel" },
-        {"NFFL01", 1.0, 0.12, 1, "Short Grass (1 ft)" },
-        {"NFFL02", 1.0, 0.15, 4, "Timber (grass & understory)" },
-        {"NFFL03", 2.5, 0.25, 1, "Tall Grass (2.5 ft)" },
-        {"NFFL04", 6.0, 0.20, 4, "Chaparral (6 ft)" },
-        {"NFFL05", 2.0, 0.20, 3, "Brush (2 ft)" },
-        {"NFFL06", 2.5, 0.25, 3, "Dormant Brush & Hardwood Slash" },
-        {"NFFL07", 2.5, 0.40, 4, "Southern Rough" },
-        {"NFFL08", 0.2, 0.30, 3, "Closed Timber Litter" },
-        {"NFFL09", 0.2, 0.25, 3, "Hardwood Litter" },
-        {"NFFL10", 1.0, 0.25, 4, "Timber (litter & understory)" },
-        {"NFFL11", 1.0, 0.15, 3, "Light Logging Slash" },
-        {"NFFL12", 2.3, 0.20, 3, "Medium Logging Slash" },
-        {"NFFL13", 3.0, 0.25, 3, "Heavy Logging Slash" }
-    };
-
-    /* Fuel particle definitions. */
-    typedef struct {
-        size_t model; size_t type; double load; double savr;
-    } StandardParticle;
-
-    static StandardParticle P[39] = {
-        { 1, FIRE_TYPE_DEAD, 0.0340, 3500.},
-        { 2, FIRE_TYPE_DEAD, 0.0920, 3000.},
-        { 2, FIRE_TYPE_DEAD, 0.0460, 109.},
-        { 2, FIRE_TYPE_DEAD, 0.0230, 30.},
-        { 2, FIRE_TYPE_HERB, 0.0230, 1500.},
-        { 3, FIRE_TYPE_DEAD, 0.1380, 1500.},
-        { 4, FIRE_TYPE_DEAD, 0.2300, 2000.},
-        { 4, FIRE_TYPE_DEAD, 0.1840, 109.},
-        { 4, FIRE_TYPE_DEAD, 0.0920, 30.},
-        { 4, FIRE_TYPE_WOOD, 0.2300, 1500.},
-        { 5, FIRE_TYPE_DEAD, 0.0460, 2000.},
-        { 5, FIRE_TYPE_DEAD, 0.0230, 109.},
-        { 5, FIRE_TYPE_WOOD, 0.0920, 1500.},
-        { 6, FIRE_TYPE_DEAD, 0.0690, 1750.},
-        { 6, FIRE_TYPE_DEAD, 0.1150, 109.},
-        { 6, FIRE_TYPE_DEAD, 0.0920, 30.},
-        { 7, FIRE_TYPE_DEAD, 0.0520, 1750.},
-        { 7, FIRE_TYPE_DEAD, 0.0860, 109.},
-        { 7, FIRE_TYPE_DEAD, 0.0690, 30.},
-        { 7, FIRE_TYPE_WOOD, 0.0170, 1550.},
-        { 8, FIRE_TYPE_DEAD, 0.0690, 2000.},
-        { 8, FIRE_TYPE_DEAD, 0.0460, 109.},
-        { 8, FIRE_TYPE_DEAD, 0.1150, 30.},
-        { 9, FIRE_TYPE_DEAD, 0.1340, 2500.},
-        { 9, FIRE_TYPE_DEAD, 0.0190, 109.},
-        { 9, FIRE_TYPE_DEAD, 0.0070, 30.},
-        {10, FIRE_TYPE_DEAD, 0.1380, 2000.},
-        {10, FIRE_TYPE_DEAD, 0.0920, 109.},
-        {10, FIRE_TYPE_DEAD, 0.2300, 30.},
-        {10, FIRE_TYPE_WOOD, 0.0920, 1500.},
-        {11, FIRE_TYPE_DEAD, 0.0690, 1500.},
-        {11, FIRE_TYPE_DEAD, 0.2070, 109.},
-        {11, FIRE_TYPE_DEAD, 0.2530, 30.},
-        {12, FIRE_TYPE_DEAD, 0.1840, 1500.},
-        {12, FIRE_TYPE_DEAD, 0.6440, 109.},
-        {12, FIRE_TYPE_DEAD, 0.7590, 30.},
-        {13, FIRE_TYPE_DEAD, 0.3220, 1500.},
-        {13, FIRE_TYPE_DEAD, 1.0580, 109.},
-        {13, FIRE_TYPE_DEAD, 1.2880, 30.},
-    };
-
-    /* First, create the catalog. */
-    if ( maxModels < 13 )
-        maxModels = 13;
-    if ( (catalog = Fire_FuelCatalogCreate(name, maxModels)) == NULL )
-        return (NULL);
-
-    /* Second, create all 14 models. */
-    adjust = 1.0;
-    for ( m=0; m<14; m++ )
-    {
-        if ( Fire_FuelModelCreate(catalog, m, M[m].name, M[m].desc, M[m].depth,
-            M[m].mext, adjust, M[m].maxParticles) != FIRE_STATUS_OK )
-        {
-            fprintf(stderr, "%s\n", FuelCat_Error(catalog));
-            Fire_FuelCatalogDestroy(catalog);
-            return (NULL);
-        }
-    }
-
-    /* Finally, add all the fuel particles. */
-    stot   = 0.0555;
-    seff   = 0.0100;
-    heat   = 8000.0;
-    dens   = 32.0;
-    for ( p=0; p<39; p++ )
-    {
-        if ( Fire_FuelParticleAdd(catalog, P[p].model, P[p].type, P[p].load,
-            P[p].savr, dens, heat, stot, seff) != FIRE_STATUS_OK )
-        {
-            fprintf(stderr, "%s\n", FuelCat_Error(catalog));
-            Fire_FuelCatalogDestroy(catalog);
-            return (NULL);
-        }
-    }
-
-    return (catalog);
-}
-
-/*
- *******************************************************************************
- *
- *  Fire_FuelCatalogDestroy()
- *
- *  Description
- *      Destroys the fuel catalog and all its associated models and particles.
- *
- *  Side Effects
- *      Destroys all FuelData instances belonging to the catalog.
- *      Frees the array of pointers to FuelData structures.
- *      Frees the catalog name.
- *      Frees the catalog error text buffer.
- *      Frees the FuelCatalog instance.
- *
- *  Function Returns
- *      FIRE_STATUS_OK or FIRE_STATUS_ERROR.
- *      Return status and error text are stored in the Fire Catalog's buffers.
- *
- *******************************************************************************
- */
-
-int
-Fire_FuelCatalogDestroy ( FuelCatalogPtr catalog )
-   // FuelCatalogPtr catalog;     /* FuelCatalogData instance to destroy. */
-{
-    size_t model;
-
-    /* Validate the catalog. */
-    assert(catalog!=NULL && FuelCat_MagicCookie(catalog)==FIRE_CATALOG_MAGIC);
-
-    /* First destroy all the fuel models in this catalog. */
-    /* The free the catalog's array of FuelData pointers. */
-    if ( FuelCat_ModelArray(catalog) )
-    {
-        for ( model=0; model <= FuelCat_MaxModels(catalog); model++ )
-        {
-            if ( FuelCat_ModelPtr(catalog,model) )
-                Fire_FuelModelDestroy(catalog, model);
-        }
-        free(FuelCat_ModelArray(catalog));
-        FuelCat_ModelArray(catalog) = NULL;
-    }
-
-    /* Next destroy the flame length table. */
-    if ( FuelCat_FlameArray(catalog) )
-    {
-        free(FuelCat_FlameArray(catalog));
-        FuelCat_FlameArray(catalog)   = NULL;
-        FuelCat_FlameClasses(catalog) = 0;
-        FuelCat_FlameStep(catalog)    = 0.0;
-    }
-
-    /* Then free the name and error buffer for this FuelCatalogData instance. */
-    if ( FuelCat_Error(catalog) )
-    {
-        free(FuelCat_Error(catalog));
-        FuelCat_Error(catalog) = NULL;
-    }
-
-    if ( FuelCat_Name(catalog) )
-    {
-        free(FuelCat_Name(catalog));
-        FuelCat_Name(catalog) = NULL;
-    }
-
-    /* Finally,free the FuelCatalogData instance and return. */
-    free(catalog);
-
-    return (FuelCat_Status(catalog) = FIRE_STATUS_OK);
-}
-
-/*
- *******************************************************************************
- *
- *  Fire_FuelModelCreate()
- *
- *  Description
- *      Creates a new fuel model able to hold maxParticles fuel particles.
- *      Fuel particles are subsequently added by Fire_FuelParticleAdd().
- *
- *  Side Effects
- *      Any existing fuel model with modelId in the Fuel Catalog is destroyed.
- *      Allocates the fuel model's FuelData block.
- *      Allocates the fuel model's name string.
- *      Allocates the fuel model's description string.
- *      Allocates the fuel model's fuel particle pointer array of maxParticles
- *      (the FuelParticleData blocks are actually allocated within
- *      Fire_FuelparticleAdd() and thier pointers stored in this array).
- *      The fuel model's address is stored in the fuel catalog's pointer array.
- *
- *  Function Returns
- *      FIRE_STATUS_OK or FIRE_STATUS_ERROR.
- *      Return status and error text are stored in the Fire Catalog's buffers.
- *
- *******************************************************************************
- */
-
-int
-Fire_FuelModelCreate (FuelCatalogPtr catalog, size_t model, char *name, char *desc, double depth, double mext, double adjust, size_t maxParticles)
-   // FuelCatalogPtr catalog;     /* FuelCatalogData instance */
-   // size_t  model;              /* fuel model number            [0-maxModels] */
-   // char   *name;               /* short name */
-   // char   *desc;               /* longer description */
-   // double  depth;              /* bed depth                             (ft) */
-   // double  mext;               /* moisture of extinction                (dl) */
-   // double  adjust;             /* spread adjustment factor              (dl) */
-   // size_t  maxParticles;       /* maximum number of fuel model particles     */
-{
-    static char *blank = {""};
-    size_t particle;
-
-    /* Validate the catalog. */
-    assert(catalog!= NULL && FuelCat_MagicCookie(catalog)==FIRE_CATALOG_MAGIC);
-
-    /* Make sure model id is within range. */
-    if ( model > FuelCat_MaxModels(catalog) )
-    {
-        sprintf(FuelCat_Error(catalog),
-            "Fire_FuelModelCreate(): fuel model \"%s\" number %d exceeds fuel catalog \"%s\" range [0..%d].",
-            name, model, FuelCat_Name(catalog), FuelCat_MaxModels(catalog));
-        return (FuelCat_Status(catalog) = FIRE_STATUS_ERROR);
-    }
-
-    /* Validate depth and mext. */
-    if ( depth < Smidgen )
-    {
-        sprintf(FuelCat_Error(catalog),
-            "Fire_FuelModelCreate(): el modelo de combustible \"%s\" n�mero %d de ancho %5.4f es demasiado peque�o.",
-            name, model, depth);
-        return (FuelCat_Status(catalog) = FIRE_STATUS_ERROR);
-    }
-
-    if ( mext < Smidgen )
-    {
-        sprintf(FuelCat_Error(catalog),
-            "Fire_FuelModelCreate(): el modelo de combustible \"%s\" n�mero %d de humedad de extinci�n %5.4f es demasiado peque�o.",
-            name, model, mext);
-        return (FuelCat_Status(catalog) = FIRE_STATUS_ERROR);
-    }
-
-    /* If this model already exists, delete it. */
-    if ( FuelCat_ModelPtr(catalog,model) )
-        Fire_FuelModelDestroy(catalog, model);
-
-    /* Allocate the model's FuelData structure. */
-    if ( maxParticles < 1 )
-        maxParticles = 1;
-    if ( (FuelCat_ModelPtr(catalog,model) =
-                (FuelModelPtr) calloc(1, sizeof(FuelModelData))) == NULL
-      || (Fuel_ParticleArray(catalog,model) =
-                (PartPtr *) calloc(maxParticles, sizeof(PartPtr))) == NULL )
-    {
-        Fire_FuelModelDestroy(catalog, model);
-        sprintf(FuelCat_Error(catalog),
-            "Fire_FuelModelCreate(): imposible asignar el modelos de combustible \"%s\" n�mero %d para el cat�logo de combustibles \"%s\".",
-            name, model, FuelCat_Name(catalog));
-        return (FuelCat_Status(catalog) = FIRE_STATUS_ERROR);
-    }
-
-    /* Catch NULL names and descriptions. */
-    if ( name == NULL )
-        name = blank;
-    if ( desc == NULL )
-        desc = blank;
-
-    /* Store remaining attributes. */
-    Fuel_Model(catalog,model)            = model;
-    Fuel_Depth(catalog,model)            = depth;
-    Fuel_Mext(catalog,model)             = mext;
-    Fuel_SpreadAdjustment(catalog,model) = adjust;
-    Fuel_Name(catalog,model)             = strdup(name);
-    Fuel_Desc(catalog,model)             = strdup(desc);
-    Fuel_CombustionFlag(catalog,model)   = 0;
-    Fuel_MaxParticles(catalog,model)     = maxParticles;
-    Fuel_Particles(catalog,model)        = 0;
-    for ( particle=0; particle<Fuel_MaxParticles(catalog,model); particle++ )
-        Fuel_ParticlePtr(catalog,model,particle) = NULL;
-
-    return (FuelCat_Status(catalog) = FIRE_STATUS_OK);
-}
-
-/*
- *******************************************************************************
- *
- *  Fire_FuelModelDestroy()
- *
- *  Description
- *      Deletes the specified fuel model.
- *      Note: this is one of only 3 functions that use the modelId instead
- *      of a FuelData pointer to identify the model.
- *
- *  Side Effects
- *      Free's all fuel particles added to the fuel model.
- *      Free's the fuel particle pointer array.
- *      Free's the fuel model's name.
- *      Free's the fuel model's description.
- *      Free's the fuel model's FuelData block.
- *      Sets the Fuel Catalog's pointer for this fuel model to NULL.
- *
- *  Function Returns
- *      FIRE_STATUS_OK or FIRE_STATUS_ERROR.
- *      Return status and error text are stored in the Fire Catalog's buffers.
- *
- *******************************************************************************
- */
-
-int
-Fire_FuelModelDestroy ( FuelCatalogPtr catalog, size_t model )
-   // FuelCatalogPtr catalog;     /* FuelCatalogData instance pointer           */
-   // size_t         model;       /* fuel model id number         [0-maxModels] */
-{
-    size_t particle;
-
-    /* Validate the catalog. */
-    assert(catalog!= NULL && FuelCat_MagicCookie(catalog)==FIRE_CATALOG_MAGIC);
-
-    /* Make sure model id is within range and exists. */
-    if ( ! Fire_FuelModelExists(catalog,model) )
-    {
-        sprintf(FuelCat_Error(catalog),
-            "Fire_FuelModelDestroy(): el modelo de combustible %d no existe en el cat�logo de combustibles \"%s\".",
-            model, FuelCat_Name(catalog));
-        return (FuelCat_Status(catalog) = FIRE_STATUS_ERROR);
-    }
-
-    /* Free all the fuel model particles and their pointer array. */
-    if ( Fuel_ParticleArray(catalog,model) )
-    {
-        for (particle=0; particle<Fuel_MaxParticles(catalog,model); particle++)
-        {
-            if ( Fuel_ParticlePtr(catalog,model,particle) )
-            {
-                free(Fuel_ParticlePtr(catalog,model,particle));
-                Fuel_ParticlePtr(catalog,model,particle) = NULL;
-            }
-        }
-        free(Fuel_ParticleArray(catalog,model));
-        Fuel_ParticleArray(catalog,model) = NULL;
-    }
-
-    /* Free the fuel model name and description. */
-    if ( Fuel_Name(catalog,model) )
-    {
-        free(Fuel_Name(catalog,model));
-        Fuel_Name(catalog,model) = NULL;
-    }
-
-    if ( Fuel_Desc(catalog,model) )
-    {
-        free(Fuel_Desc(catalog,model));
-        Fuel_Desc(catalog,model) = NULL;
-    }
-
-    /* Now free the FuelData instance and reset its catalog entry. */
-    free(FuelCat_ModelPtr(catalog,model));
-    FuelCat_ModelPtr(catalog,model) = NULL;
-
-    return (FuelCat_Status(catalog) = FIRE_STATUS_OK);
-}
-
-/*
- *******************************************************************************
- *
- *  Fire_FuelModelExists()
- *
- *  Description
- *      Performs a sanity check to make sure the catalog pointer is valid
- *      and the fuel model number is within range and exists.
- *
- *  Side Effects
- *      None.
- *
- *  Function Returns
- *      1 if "model" exists, 0 if it is undefined.
- *
- *******************************************************************************
- */
-
-int
-Fire_FuelModelExists ( FuelCatalogPtr catalog, size_t model )
-   // FuelCatalogPtr catalog;     /* FuelCatalogData instance pointer           */
-   // size_t         model;       /* fuel model id number         [0-maxModels] */
-{
-    /* Validate the model number. */
-    if ( model > FuelCat_MaxModels(catalog)
-      || ! FuelCat_ModelPtr(catalog,model) )
-        return (int) 0;
-
-    return (int) 1;
-}
-
-/*
- *******************************************************************************
- *
- *  Fire_FuelParticleAdd()
- *
- *  Description
- *      Adds a fuel particle to the specified fuel model.
- *
- *  Side Effects
- *      A FuelParticleData is allocated and appended to the model's array.
- *      The fuel model's particle counter is incremented.
- *      The fuel model's combustion flag set to 0.
- *
- *  Function Returns
- *      FIRE_STATUS_OK or FIRE_STATUS_ERROR.
- *      Return status and error text are stored in the Fire Catalog's buffers.
- *
- *******************************************************************************
- */
-
-int
-Fire_FuelParticleAdd ( FuelCatalogPtr catalog, size_t model, size_t type, double load, double savr, double dens, double heat, double stot, double seff )
-   // FuelCatalogPtr catalog;     /* FuelCatalogData instance pointer           */
-   // size_t  model;              /* fuel model id number         [0-maxModels] */
-   // size_t  type;               /* FIRE_TYPE_DEAD, _TYPE_HERB, or _TYPE_WOOD  */
-   // double  load;               /* fuel load                        (lbs/ft2) */
-   // double  savr;               /* surface-area-to-volume ratio     (ft2/ft3) */
-   // double  dens;               /* density                          (lbs/ft3) */
-   // double  heat;               /* heat of combustion               (btus/lb) */
-   // double  stot;               /* total silica content               (lb/lb) */
-   // double  seff;               /* effective silica content           (lb/lb) */
-{
-    static double Size_boundary[FIRE_SIZE_CLASSES] =
-        {1200., 192., 96., 48., 16., 0.};
-    size_t particle, size;
-
-    /* Validate the catalog. */
-    assert(catalog!= NULL && FuelCat_MagicCookie(catalog)==FIRE_CATALOG_MAGIC);
-
-    /* Validate the fuel model. */
-    if ( ! Fire_FuelModelExists(catalog,model) )
-    {
-        sprintf(FuelCat_Error(catalog),
-            "Fire_FuelParticleAdd(): el modelo de combustible %d no existe en el cat�logo de combustibles \"%s\".",
-            model, FuelCat_Name(catalog));
-        return (FuelCat_Status(catalog) = FIRE_STATUS_ERROR);
-    }
-
-    /* Validate the "type" parameter. */
-    if ( type != FIRE_TYPE_DEAD
-      && type != FIRE_TYPE_HERB
-      && type != FIRE_TYPE_WOOD )
-    {
-        sprintf(FuelCat_Error(catalog),
-            "Fire_FuelParticleAdd(): el modelo de combustible %d de tipo de valor (arg #3) no es FIRE_TYPE_DEAD, FIRE_TYPE_HERB, o FIRE_TYPE_WOOD.",
-            model);
-        return (FuelCat_Status(catalog) = FIRE_STATUS_ERROR);
-    }
-
-    /* Allocate a new FuelParticle */
-    particle = Fuel_Particles(catalog,model);
-    if ( (Fuel_ParticlePtr(catalog,model,particle) =
-        (PartPtr) calloc(1, sizeof(FuelParticleData))) == NULL )
-    {
-        sprintf(FuelCat_Error(catalog),
-            "Fire_FuelParticleAdd(): imposible asignar la part�cula de combustible al modelo de combustible \"%s\" n�mero %d en el cat�logo de combustibles \"%s\".",
-            Fuel_Name(catalog,model), model, FuelCat_Name(catalog));
-        return (FuelCat_Status(catalog) = FIRE_STATUS_ERROR);
-    }
-
-    /* Store the input particle attributes. */
-    Fuel_Type(catalog,model,particle)       = type;
-    Fuel_Load(catalog,model,particle)       = load;
-    Fuel_Savr(catalog,model,particle)       = savr;
-    Fuel_Density(catalog,model,particle)    = dens;
-    Fuel_Heat(catalog,model,particle)       = heat;
-    Fuel_SiTotal(catalog,model,particle)    = stot;
-    Fuel_SiEffective(catalog,model,particle)= seff;
-
-    /* Fuel life category. */
-    Fuel_Live(catalog,model,particle) =
-        (type==FIRE_TYPE_DEAD) ? FIRE_LIFE_DEAD : FIRE_LIFE_LIVE;
-
-    /* Fuel particle surface area. */
-    Fuel_SurfaceArea(catalog,model,particle) =
-        (dens > Smidgen) ? load * savr / dens : 0.;
-
-    /* Particle SAVR exponent factor. */
-    Fuel_SigmaFactor(catalog,model,particle) =
-        (savr > Smidgen) ? exp(-138. / savr) : 0.;
-
-    /* Particle size class. */
-    for ( size=0; savr < Size_boundary[size]; size++ )
-        /* NOTHING */ ;
-    Fuel_SizeClass(catalog,model,particle) = size;
-
-    /* Initialize particle attributes that are bed & environ dependent. */
-    Fuel_AreaWtg(catalog,model,particle)     = 0.;
-    Fuel_SizeAreaWtg(catalog,model,particle) = 0.;
-    Fuel_Moisture(catalog,model,particle)    = 0.;
-
-    /* Increment the fuel model's particle counter and reset it flag. */
-    Fuel_Particles(catalog,model)++;
-    Fuel_CombustionFlag(catalog,model) = 0;
-
-    return (FuelCat_Status(catalog) = FIRE_STATUS_OK);
-}
-
-/*
- *******************************************************************************
- * End of fireLib.c
- *******************************************************************************
- */
diff --git a/src/modules/simulation/sim_fire_spreading/fireLib.h b/src/modules/simulation/sim_fire_spreading/fireLib.h
deleted file mode 100644
index 8effef1..0000000
--- a/src/modules/simulation/sim_fire_spreading/fireLib.h
+++ /dev/null
@@ -1,551 +0,0 @@
-/**********************************************************
- * Version $Id: fireLib.h 911 2011-02-14 16:38:15Z reklov_w $
- *********************************************************/
-/*
- *******************************************************************************
- *
- *  fireLib.h
- *
- *  Description
- *      Library of BEHAVE (Andrews 1986) fire behavior algorithms
- *      encapsulated and optimized for fire behavior simulation.
- *
- *  Legalities
- *      Copyright (c) 1996 Collin D. Bevins.
- *      See the file "license.txt" for information on usage and
- *      redistribution of this file, and for a DISCLAIMER OF ALL WARRANTIES.
- *
- *  Description
- *      This header file describes the externally-visible facilities of
- *      the Fire Behavior Library C API.
- *
- *      This file really needs to be split into public and private portions.
- *
- *  History
- *      1996/09/04  Version 1.0.0 release.
- *      1999/03/05  Fixed NNFL07 live SAVR from 1500 to 1550.
- *
- *******************************************************************************
- */
-
-#include <stdlib.h>
-#include <stdio.h>
-#include <string.h>
-#include <math.h>
-#include <assert.h>
-
-#ifndef _FIRE_LIB
-#define _FIRE_LIB 1
-
-#define FIRELIB_VERSION "1.0"
-#define FIRELIB_MAJOR_VERSION 1
-#define FIRELIB_MINOR_VERSION 0
-#define FIRELIB_PATCH_LEVEL   1
-
-/*
- *------------------------------------------------------------------------------
- * Definitions that allow this header file to be used either with or
- * without ANSI C features like function prototypes.
- *------------------------------------------------------------------------------
- */
-
-#undef _ANSI_ARGS_
-#undef CONST
-#if ((defined(__STDC__) || defined(SABER)) && !defined(NO_PROTOTYPE)) || defined(__cplusplus)
-#   define _USING_PROTOTYPES_ 1
-#   define _ANSI_ARGS_(x)       x
-#   define CONST const
-#   ifdef __cplusplus
-#       define VARARGS(first) (first, ...)
-#   else
-#       define VARARGS(first) ()
-#   endif
-#else
-#   define _ANSI_ARGS_(x)       ()
-#   define CONST
-#endif
-
-#ifdef __cplusplus
-#   define EXTERN extern "C"
-#else
-#   define EXTERN extern
-#endif
-
-/*
- *------------------------------------------------------------------------------
- * Macro to use instead of "void" for arguments that must have type "void *"
- * in ANSI C;  maps them to type "char *" in non-ANSI systems.
- *------------------------------------------------------------------------------
- */
-
-#ifndef VOID
-#   ifdef __STDC__
-#       define VOID void
-#   else
-#       define VOID char
-#   endif
-#endif
-
-/*
- *------------------------------------------------------------------------------
- *  Macro pseudo functions.
- *------------------------------------------------------------------------------
- */
-
-#define Smidgen                 (0.000001)
-#define DegreesToRadians(x)     ((x)*0.017453293)
-#define RadiansToDegrees(x)     ((x)*57.29577951)
-#define IsZero(x)               (fabs(x)<Smidgen)
-#define Equal(x,y)              (fabs((x)-(y))<Smidgen)
-
-/*
- *------------------------------------------------------------------------------
- * Firelib return status codes.
- *------------------------------------------------------------------------------
- */
-
-#define  FIRE_STATUS_OK         (0)
-#define  FIRE_STATUS_ERROR      (-1)
-#define  FIRE_STATUS_EOF        (1)
-
-/*
- *------------------------------------------------------------------------------
- *  Fuel moisture and mass weighting classes.
- *------------------------------------------------------------------------------
- */
-
-#define  FIRE_LIFE_CATS     (2) /* Number of fuel particle life categories */
-#define  FIRE_LIFE_DEAD     (0)
-#define  FIRE_LIFE_LIVE     (1)
-
-#define  FIRE_SIZE_CLASSES  (6) /* Number of mass weighting classes. */
-
-#define  FIRE_MCLASSES      (6) /* Number of fuel moisture classes. */
-#define  FIRE_MCLASS_1HR    (0)
-#define  FIRE_MCLASS_10HR   (1)
-#define  FIRE_MCLASS_100HR  (2)
-#define  FIRE_MCLASS_1000HR (3)
-#define  FIRE_MCLASS_HERB   (4)
-#define  FIRE_MCLASS_WOOD   (5)
-

-/*
- *------------------------------------------------------------------------------
- *  FuelParticleData structure: fuel particle input and intermediate attributes.
- *------------------------------------------------------------------------------
- */
-
-typedef struct fuelParticleDataStruct
-{
-    /* INPUT */
-    double load;                /* fuel loading                     (lb/sqft) */
-    double savr;                /* surface area-to-volume ratio        (1/ft) */
-    double dens;                /* particle density                 (lb/cuft) */
-    double heat;                /* heat of combustion                (BTU/lb) */
-    double stot;                /* total silica content        (fraction odw) */
-    double seff;                /* effective silica content    (fraction odw) */
-    /* PARTICLE_DEPENDENT */
-    double area;                /* surface area */
-    double sigma;               /* exp(-138./sigma)                      (dl) */
-    /* MODEL-DEPENDENT */
-    double awtg;                /* surface area derived weighting factor (dl) */
-    double gwtg;                /* size class area weighting factor */
-    /* ENVIRONMENT-DEPENDENT */
-    double mois;                /* particle moisture content       (fraction) */
-    size_t live;                /* life category 0=dead, 1=live               */
-    size_t type;                /* type category 0=dead, 1=herb, 2=live woody */
-    size_t sizeClass;           /* fuel moisture size class                   */
-} FuelParticleData, *FuelParticlePtr, *PartPtr;
-
-#define FIRE_TYPE_DEAD   (1)
-#define FIRE_TYPE_HERB   (2)
-#define FIRE_TYPE_WOOD   (3)
-
-/* FuelParticleData structure access macros. */
-
-#define Fuel_Live(catalog,model,particle) \
-                ((catalog)->modelPtr[(model)]->partPtr[(particle)]->live)
-
-#define Fuel_Type(catalog,model,particle) \
-                ((catalog)->modelPtr[(model)]->partPtr[(particle)]->type)
-
-#define Fuel_SizeClass(catalog,model,particle) \
-                ((catalog)->modelPtr[(model)]->partPtr[(particle)]->sizeClass)
-
-#define Fuel_Load(catalog,model,particle) \
-                ((catalog)->modelPtr[(model)]->partPtr[(particle)]->load)
-
-#define Fuel_Savr(catalog,model,particle) \
-                ((catalog)->modelPtr[(model)]->partPtr[(particle)]->savr)
-
-#define Fuel_Heat(catalog,model,particle) \
-                ((catalog)->modelPtr[(model)]->partPtr[(particle)]->heat)
-
-#define Fuel_Density(catalog,model,particle) \
-                ((catalog)->modelPtr[(model)]->partPtr[(particle)]->dens)
-
-#define Fuel_SiTotal(catalog,model,particle) \
-                ((catalog)->modelPtr[(model)]->partPtr[(particle)]->stot)
-
-#define Fuel_SiEffective(catalog,model,particle) \
-                ((catalog)->modelPtr[(model)]->partPtr[(particle)]->seff)
-
-#define Fuel_SurfaceArea(catalog,model,particle) \
-                ((catalog)->modelPtr[(model)]->partPtr[(particle)]->area)
-
-#define Fuel_AreaWtg(catalog,model,particle) \
-                ((catalog)->modelPtr[(model)]->partPtr[(particle)]->awtg)
-
-#define Fuel_SizeAreaWtg(catalog,model,particle) \
-                ((catalog)->modelPtr[(model)]->partPtr[(particle)]->gwtg)
-
-#define Fuel_SigmaFactor(catalog,model,particle) \
-                ((catalog)->modelPtr[(model)]->partPtr[(particle)]->sigma)
-
-#define Fuel_Moisture(catalog,model,particle) \
-                ((catalog)->modelPtr[(model)]->partPtr[(particle)]->mois)
-

-/*
- *------------------------------------------------------------------------------
- *  FuelModelData structure: fuel model bed input attributes.
- *------------------------------------------------------------------------------
- */
-
-typedef struct fuelModelDataStruct
-{
-    /* Input variables. */
-    size_t modelId;             /* fuel model number                          */
-    size_t combustion;          /* 0 if combustion not yet calculated         */
-    size_t maxParticles;        /* maximum number of FuelParticles            */
-    size_t particles;           /* current number of FuelParticles            */
-    PartPtr *partPtr;           /* array of pointers to Fuel Particles        */
-    char  *name;                /* fuel model short name                      */
-    char  *desc;                /* fuel model description text                */
-    char  *reserved1;           /* used for alignment                         */
-    double depth;               /* fuel bed depth                        (ft) */
-    double mext;                /* dead fuel extinction moisture   (fraction) */
-    double adjust;              /* spread rate adjustment factor         (dl) */
-    /* Combustion intermediates. */
-    double awtg[2];             /* dead & live fuel area weighting factors    */
-    double rxFactor[2];         /* dead and live fuel rx factors              */
-    double fineDead;            /* fine dead fuel ratio                       */
-    double liveFactor;          /* live fuel moisture extinction factor       */
-    double rhob;                /* fuel bed bulk density                      */
-    double taur;                /* residence time                       (min) */
-    double propFlux;            /* propagating flux ratio                     */
-    double slopeK;              /* slope parameter 'k'                        */
-    double windB;               /* wind parameter 'b'                         */
-    double windE;               /* wind parameter (ratio**e/c)                */
-    double windK;               /* wind parameter (c * ratio**-e)             */
-    /* Current environment. */
-    double moisture[FIRE_MCLASSES]; /* array of fuel moistures (fraction odw) */
-    double windFpm;             /* wind speed                        (ft/min) */
-    double windDeg;             /* wind vector         (degrees from upslope) */
-    double slope;               /* slope                         (rise/reach) */
-    double aspect;              /* aspect (downslope) azimuth  (compass degs) */
-    /* Updated by Fire_SpreadNoWindNoSlope() */
-    double rxInt;               /* reaction intensity          (BTU/sqft/min) */
-    double spread0;             /* no-wind, no-slope spread rate     (ft/min) */
-    double hpua;                /* heat per unit area              (BTU/sqft) */
-    /* Updated by Fire_SpreadWindSlopeMax() */
-    double spreadMax;           /* spread in direction of max spread (ft/min) */
-    double azimuthMax;          /* direction of maximum spread      (degrees) */
-    double effWind;             /* effective windspeed                        */
-    double lwRatio;             /* length-to-width ratio for eff windspeed    */
-    double eccentricity;        /* eccentricity of ellipse for eff windspeed  */
-    double phiW;                /* wind factor                                */
-    double phiS;                /* slope factor                               */
-    double phiEw;               /* combined wind-slope factor                 */
-    size_t wLimit;              /* wind limit 0=not reached, 1=reached        */
-    size_t reserved2;           /* used for alignment                         */
-    /* Updated by Fire_SpreadAtAzimuth() */
-    double spreadAny;           /* spread rate at arbitrary azimuth  (ft/min) */
-    double azimuthAny;          /* direction of arbitrary spread    (degrees) */
-    double byrams;              /* fireline intensity              (BTU/ft/s) */
-    double flame;               /* flame length                          (ft) */
-    double scorch;              /* scorch height                         (ft) */
-} FuelModelData, *FuelModelPtr;
-
-/* Fuel model input variable macros. */
-#define Fuel_Model(catalog,model) \
-                    ((catalog)->modelPtr[(model)]->modelId)
-
-#define Fuel_Name(catalog,model) \
-                    ((catalog)->modelPtr[(model)]->name)
-
-#define Fuel_Desc(catalog,model) \
-                    ((catalog)->modelPtr[(model)]->desc)
-
-#define Fuel_Depth(catalog,model) \
-                    ((catalog)->modelPtr[(model)]->depth)
-
-#define Fuel_Mext(catalog,model) \
-                    ((catalog)->modelPtr[(model)]->mext)
-
-#define Fuel_SpreadAdjustment(catalog,model) \
-                    ((catalog)->modelPtr[(model)]->adjust)
-
-#define Fuel_CombustionFlag(catalog,model) \
-                    ((catalog)->modelPtr[(model)]->combustion)
-
-#define Fuel_MaxParticles(catalog,model) \
-                    ((catalog)->modelPtr[(model)]->maxParticles)
-
-#define Fuel_Particles(catalog,model) \
-                    ((catalog)->modelPtr[(model)]->particles)
-
-#define Fuel_ParticleArray(catalog,model) \
-                    ((catalog)->modelPtr[(model)]->partPtr)
-
-#define Fuel_ParticlePtr(catalog,model,particle) \
-                    ((catalog)->modelPtr[(model)]->partPtr[(particle)])
-
-/* Fuel model combustion intermediates macros. */
-#define Fuel_LifeAreaWtg(catalog,model,life) \
-                    ((catalog)->modelPtr[(model)]->awtg[(life)])
-
-#define Fuel_LifeRxFactor(catalog,model,life) \
-                    ((catalog)->modelPtr[(model)]->rxFactor[(life)])
-
-#define Fuel_FineDead(catalog,model) \
-                    ((catalog)->modelPtr[(model)]->fineDead)
-
-#define Fuel_LiveMextFactor(catalog,model) \
-                    ((catalog)->modelPtr[(model)]->liveFactor)
-
-#define Fuel_BulkDensity(catalog,model) \
-                    ((catalog)->modelPtr[(model)]->rhob)
-
-#define Fuel_ResidenceTime(catalog,model) \
-                    ((catalog)->modelPtr[(model)]->taur)
-
-#define Fuel_PropFlux(catalog,model) \
-                    ((catalog)->modelPtr[(model)]->propFlux)
-
-#define Fuel_SlopeK(catalog,model) \
-                    ((catalog)->modelPtr[(model)]->slopeK)
-
-#define Fuel_WindB(catalog,model) \
-                    ((catalog)->modelPtr[(model)]->windB)
-
-#define Fuel_WindE(catalog,model) \
-                    ((catalog)->modelPtr[(model)]->windE)
-
-#define Fuel_WindK(catalog,model) \
-                    ((catalog)->modelPtr[(model)]->windK)
-
-/* Fuel model fire behavior variable macros. */
-#define Fuel_RxIntensity(catalog,model) \
-                    ((catalog)->modelPtr[(model)]->rxInt)
-
-#define Fuel_Spread0(catalog,model) \
-                    ((catalog)->modelPtr[(model)]->spread0)
-
-#define Fuel_HeatPerUnitArea(catalog,model) \
-                    ((catalog)->modelPtr[(model)]->hpua)
-
-#define Fuel_SpreadMax(catalog,model) \
-                    ((catalog)->modelPtr[(model)]->spreadMax)
-
-#define Fuel_AzimuthMax(catalog,model) \
-                    ((catalog)->modelPtr[(model)]->azimuthMax)
-
-#define Fuel_SpreadAny(catalog,model) \
-                    ((catalog)->modelPtr[(model)]->spreadAny)
-
-#define Fuel_AzimuthAny(catalog,model) \
-                    ((catalog)->modelPtr[(model)]->azimuthAny)
-
-#define Fuel_EffectiveWind(catalog,model) \
-                    ((catalog)->modelPtr[(model)]->effWind)
-
-#define Fuel_LwRatio(catalog,model) \
-                    ((catalog)->modelPtr[(model)]->lwRatio)
-
-#define Fuel_Eccentricity(catalog,model) \
-                    ((catalog)->modelPtr[(model)]->eccentricity)
-
-#define Fuel_PhiWind(catalog,model) \
-                    ((catalog)->modelPtr[(model)]->phiW)
-
-#define Fuel_PhiSlope(catalog,model) \
-                    ((catalog)->modelPtr[(model)]->phiS)
-
-#define Fuel_PhiEffWind(catalog,model) \
-                    ((catalog)->modelPtr[(model)]->phiEw)
-
-#define Fuel_WindLimit(catalog,model) \
-                    ((catalog)->modelPtr[(model)]->wLimit)
-
-#define Fuel_ByramsIntensity(catalog,model) \
-                    ((catalog)->modelPtr[(model)]->byrams)
-
-#define Fuel_FlameLength(catalog,model) \
-                    ((catalog)->modelPtr[(model)]->flame)
-
-#define Fuel_ScorchHeight(catalog,model) \
-                    ((catalog)->modelPtr[(model)]->scorch)
-
-/* Fuel model environment variable macros. */
-#define Fuel_EnvMoisture(catalog,model,mclass) \
-                    ((catalog)->modelPtr[(model)]->moisture[(mclass)])
-
-#define Fuel_WindSpeed(catalog,model) \
-                    ((catalog)->modelPtr[(model)]->windFpm)
-
-#define Fuel_WindDir(catalog,model) \
-                    ((catalog)->modelPtr[(model)]->windDeg)
-
-#define Fuel_Slope(catalog,model) \
-                    ((catalog)->modelPtr[(model)]->slope)
-
-#define Fuel_Aspect(catalog,model) \
-                    ((catalog)->modelPtr[(model)]->aspect)
-

-/*
- *------------------------------------------------------------------------------
- *  FuelCatData structure; provides a complete fuel catalog.
- *------------------------------------------------------------------------------
- */
-
-#define FIRE_CATALOG_MAGIC      (19520904L)
-#define FIRE_ERROR_BUFFER_SIZE  (1024)
-
-typedef struct fuelCatalogStruct
-{
-    long      magicCookie;      /* magic cookie for sanity checking           */
-    int       status;           /* return status of most recent call          */
-    size_t    maxModels;        /* maximum number of models in this catalog   */
-    size_t    flameClasses;     /* size of the flame length array             */
-    char         *name;         /* name for this catalog instance             */
-    char         *error;        /* error message buffer                       */
-    FuelModelPtr *modelPtr;     /* array of ModelPtr[maxModels+1]             */
-    double       *flamePtr;     /* flame length lookup array                  */
-    double        flameStep;    /* size of each flame length table class (ft) */
-} FuelCatalogData, *FuelCatalogPtr;
-
-#define FuelCat_MagicCookie(catalog)    (catalog->magicCookie)
-#define FuelCat_MaxModels(catalog)      (catalog->maxModels)
-#define FuelCat_Status(catalog)         (catalog->status)
-#define FuelCat_FlameClasses(catalog)   (catalog->flameClasses)
-#define FuelCat_FlameStep(catalog)      (catalog->flameStep)
-#define FuelCat_FlameArray(catalog)     (catalog->flamePtr)
-#define FuelCat_Name(catalog)           (catalog->name)
-#define FuelCat_Error(catalog)          (catalog->error)
-#define FuelCat_ModelArray(catalog)     (catalog->modelPtr)
-#define FuelCat_ModelPtr(catalog,model) (catalog->modelPtr[model])
-

-/*
- *------------------------------------------------------------------------------
- *  Function prototypes for fire behavior computations.
- *------------------------------------------------------------------------------
- */
-
-#define FIRE_NONE       (0)
-#define FIRE_BYRAMS     (1)
-#define FIRE_FLAME      (2)
-#define FIRE_SCORCH     (4)
-
-EXTERN int Fire_FlameScorch _ANSI_ARGS_((
-    FuelCatalogPtr catalog,     /* FuelCatalogData instance pointer           */
-    size_t  model,              /* fuel model number            [0-maxModels] */
-    size_t  doWhich     /* FIRE_NONE | FIRE_BYRAMS | FIRE_FLAME | FIRE_SCORCH */
-    )) ;
-
-EXTERN int Fire_FuelCombustion _ANSI_ARGS_((
-    FuelCatalogPtr catalog,     /* FuelCatalogData instance pointer           */
-    size_t  model               /* fuel model number            [0-maxModels] */
-    )) ;
-
-EXTERN int Fire_SpreadNoWindNoSlope _ANSI_ARGS_((
-    FuelCatalogPtr catalog,     /* FuelCatalogData instance pointer           */
-    size_t  model,              /* fuel model number            [0-maxModels] */
-    double  moisture[FIRE_MCLASSES]  /* array of fuel moistures   (fractions) */
-    )) ;
-
-EXTERN int Fire_SpreadWindSlopeMax _ANSI_ARGS_((
-    FuelCatalogPtr catalog,     /* FuelCatalogData instance pointer           */
-    size_t  model,              /* fuel model number            [0-maxModels] */
-    double  windFpm,            /* wind speed                        (ft/min) */
-    double  windDeg,            /* wind bearing vector         (compass degs) */
-    double  slope,              /* slope                         (rise/reach) */
-    double  aspect              /* aspect (downslope) azimuth  (compass degs) */
-    )) ;
-
-EXTERN int Fire_SpreadAtAzimuth _ANSI_ARGS_((
-    FuelCatalogPtr catalog,     /* FuelCatalogData instance pointer           */
-    size_t  model,              /* fuel model number            [0-maxModels] */
-    double  azimuth,            /* fire spread azimuth     (deg from upslope) */
-    size_t  doWhich     /* FIRE_NONE | FIRE_BYRAMS | FIRE_FLAME | FIRE_SCORCH */
-    )) ;
-
-/*
- *------------------------------------------------------------------------------
- *  Function prototypes for creating and destroying fuel catalogs, fuel models,
- *  fuel particles, and flame length tables.
- *------------------------------------------------------------------------------
- */
-
-EXTERN int Fire_FlameLengthTable _ANSI_ARGS_((
-    FuelCatalogPtr catalog,     /* FuelCatalogData instance pointer           */
-    size_t  flameClasses,       /* number of flame length classes             */
-    double  flameStep           /* flame length step value per class          */
-    )) ;
-
-EXTERN FuelCatalogPtr Fire_FuelCatalogCreate _ANSI_ARGS_((
-    char  *name,                /* FuelCatalogData instance name              */
-    size_t maxModels            /* maximum modelId allowed in this catalog    */
-    )) ;
-
-EXTERN FuelCatalogPtr Fire_FuelCatalogCreateStandard _ANSI_ARGS_((
-    char  *name,                /* FuelCatalogData instance name              */
-    size_t maxModels            /* maximum modelId allowed in this catalog    */
-    )) ;
-
-EXTERN int Fire_FuelCatalogDestroy _ANSI_ARGS_((
-    FuelCatalogPtr catalog      /* FuelCatalogData instance pointer           */
-    )) ;
-
-EXTERN int Fire_FuelModelCreate _ANSI_ARGS_((
-    FuelCatalogPtr catalog,     /* FuelCatalogData instance                   */
-    size_t  model,              /* fuel model number            [0-maxModels] */
-    char   *name,               /* short name                                 */
-    char   *desc,               /* longer description                         */
-    double  depth,              /* bed depth                             (ft) */
-    double  mext,               /* moisture of extinction                (dl) */
-    double  adjust,             /* spread adjustment factor              (dl) */
-    size_t  maxParticles        /* maximum number of fuel model particles     */
-    )) ;
-
-EXTERN int Fire_FuelModelDestroy _ANSI_ARGS_((
-    FuelCatalogPtr catalog,     /* FuelCatalogData instance pointer           */
-    size_t         model        /* fuel model id number         [0-maxModels] */
-    )) ;
-
-EXTERN int Fire_FuelModelExists _ANSI_ARGS_((
-    FuelCatalogPtr catalog,     /* FuelCatalogData instance pointer           */
-    size_t         model        /* fuel model id number         [0-maxModels] */
-    )) ;
-
-EXTERN int Fire_FuelParticleAdd _ANSI_ARGS_((
-    FuelCatalogPtr catalog,     /* FuelCatalogData instance pointer           */
-    size_t  model,              /* fuel model id number         [0-maxModels] */
-    size_t  type,               /* FIRE_TYPE_DEAD, _TYPE_HERB, or _TYPE_WOOD  */
-    double  load,               /* fuel load                        (lbs/ft2) */
-    double  savr,               /* surface-area-to-volume ratio     (ft2/ft3) */
-    double  dens,               /* density                          (lbs/ft3) */
-    double  heat,               /* heat of combustion               (btus/lb) */
-    double  stot,               /* total silica content               (lb/lb) */
-    double  seff                /* effective silica content           (lb/lb) */
-    )) ;
-
-#ifdef NEED_STRDUP
-char *strdup ( const char *str ) ;
-#endif
-
-#endif
-
-/*
- *******************************************************************************
- * End of fireLib.h
- *******************************************************************************
- */
diff --git a/src/modules/io/io_gdal/MLB_Interface.cpp b/src/modules/simulation/sim_qm_of_esp/MLB_Interface.cpp
similarity index 68%
copy from src/modules/io/io_gdal/MLB_Interface.cpp
copy to src/modules/simulation/sim_qm_of_esp/MLB_Interface.cpp
index a940115..858f310 100644
--- a/src/modules/io/io_gdal/MLB_Interface.cpp
+++ b/src/modules/simulation/sim_qm_of_esp/MLB_Interface.cpp
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: MLB_Interface.cpp 1921 2014-01-09 10:24:11Z oconrad $
+ * Version $Id: MLB_Interface.cpp 911 2011-11-11 11:11:11Z oconrad $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -9,14 +9,14 @@
 //      System for Automated Geoscientific Analyses      //
 //                                                       //
 //                    Module Library:                    //
-//                     Grid_IO_GDAL                      //
+//                      qm_of_esp                        //
 //                                                       //
 //-------------------------------------------------------//
 //                                                       //
 //                   MLB_Interface.cpp                   //
 //                                                       //
-//                 Copyright (C) 2003 by                 //
-//                        Author                         //
+//                 Copyright (C) 2013 by                 //
+//                     Olaf Conrad                       //
 //                                                       //
 //-------------------------------------------------------//
 //                                                       //
@@ -40,15 +40,17 @@
 //                                                       //
 //-------------------------------------------------------//
 //                                                       //
-//    e-mail:     author at email.de                        //
+//    e-mail:     oconrad at saga-gis.de                    //
 //                                                       //
-//    contact:    Author                                 //
-//                Sesame Street 7                        //
-//                12345 Metropolis                       //
-//                Nirwana                                //
+//    contact:    Olaf Conrad                            //
+//                Institute of Geography                 //
+//                University of Hamburg                  //
+//                Germany                                //
 //                                                       //
 ///////////////////////////////////////////////////////////
 
+//---------------------------------------------------------
+
 
 ///////////////////////////////////////////////////////////
 //														 //
@@ -59,7 +61,7 @@
 //---------------------------------------------------------
 // 1. Include the appropriate SAGA-API header...
 
-#include "gdal_driver.h"
+#include "MLB_Interface.h"
 
 
 //---------------------------------------------------------
@@ -70,26 +72,26 @@ CSG_String Get_Info(int i)
 	switch( i )
 	{
 	case MLB_INFO_Name:	default:
-		return( _TL("GDAL/OGR") );
+		return( _TL("QM of ESP") );
 
 	case MLB_INFO_Category:
-		return( _TL("Import/Export") );
+		return( _TL("Simulation") );
 
 	case MLB_INFO_Author:
-		return( _TL("SAGA User Group Associaton (c) 2008" ));
+		return( SG_T("O. Conrad (c) 2013") );
 
 	case MLB_INFO_Description:
-		return( CSG_String::Format(SG_T("%s\n%s %s\n%s: %s"),
-			_TL("Interface to Frank Warmerdam's Geospatial Data Abstraction Library (GDAL)."),
-			_TL("Version"), SG_Get_GDAL_Drivers().Get_Version().c_str(),
-			_TL("Homepage"), SG_T("<a target=\"_blank\" href=\"http://www.gdal.org/\">www.gdal.org</a>\n")
+		return( _TW(
+			"Quantitative Modeling of Earth Surface Processes.\n"
+			"SAGA implementations following the examples from the text book:\n"
+			"Pelletier, J.D. (2008): Quantitative Modeling of Earth Surface Processes. Cambridge, 295p.\n"
 		));
 
 	case MLB_INFO_Version:
-		return( SG_T("2.0") );
+		return( SG_T("1.0") );
 
 	case MLB_INFO_Menu_Path:
-		return( _TL("File|GDAL/OGR") );
+		return( _TL("Simulation|Quantitative Modeling of Earth Surface Processes") );
 	}
 }
 
@@ -97,14 +99,11 @@ CSG_String Get_Info(int i)
 //---------------------------------------------------------
 // 3. Include the headers of your modules here...
 
-#include "gdal_import.h"
-#include "gdal_export.h"
-#include "gdal_export_geotiff.h"
-#include "gdal_import_netcdf.h"
-
-#include "ogr_import.h"
-#include "ogr_export.h"
-#include "ogr_export_kml.h"
+#include "hillslope_evolution_ftcs.h"
+#include "fill_sinks.h"
+#include "flow_routing.h"
+#include "successive_flow_routing.h"
+#include "hillslope_evolution_adi.h"
 
 
 //---------------------------------------------------------
@@ -114,23 +113,15 @@ CSG_Module *		Create_Module(int i)
 {
 	switch( i )
 	{
-	case  0:	return( new CGDAL_Import );
-	case  1:	return( new CGDAL_Export );
-	case  2:	return( new CGDAL_Export_GeoTIFF );
-
-	case  3:	return( new COGR_Import );
-	case  4:	return( new COGR_Export );
+	case  0:	return( new CHillslope_Evolution_FTCS );
+	case  1:	return( new CFill_Sinks );
+	case  2:	return( new CFlow_Routing );
+	case  3:	return( new CSuccessive_Flow_Routing );
+	case  4:	return( new CHillslope_Evolution_ADI );
 
-	case  5:	return( new COGR_Export_KML );
-
-	case  6:	return( SG_Get_GDAL_Drivers().Get_Driver("netCDF") ? new CGDAL_Import_NetCDF : NULL );
-
-	//-----------------------------------------------------
-	case  9:	return( NULL );
+	case 11:	return( NULL );
 	default:	return( MLB_INTERFACE_SKIP_MODULE );
 	}
-
-	return( NULL );
 }
 
 
diff --git a/src/modules/io/io_gdal/ogr_export.h b/src/modules/simulation/sim_qm_of_esp/MLB_Interface.h
similarity index 76%
copy from src/modules/io/io_gdal/ogr_export.h
copy to src/modules/simulation/sim_qm_of_esp/MLB_Interface.h
index 473bdbb..8d6fc88 100644
--- a/src/modules/io/io_gdal/ogr_export.h
+++ b/src/modules/simulation/sim_qm_of_esp/MLB_Interface.h
@@ -1,94 +1,83 @@
-/**********************************************************
- * Version $Id: ogr_export.h 1921 2014-01-09 10:24:11Z oconrad $
- *********************************************************/
-
-///////////////////////////////////////////////////////////
-//                                                       //
-//                         SAGA                          //
-//                                                       //
-//      System for Automated Geoscientific Analyses      //
-//                                                       //
-//                    Module Library                     //
-//                                                       //
-//                       io_gdal                         //
-//                                                       //
-//-------------------------------------------------------//
-//                                                       //
-//                     ogr_export.h                      //
-//                                                       //
-//            Copyright (C) 2008 O. Conrad               //
-//                                                       //
-//-------------------------------------------------------//
-//                                                       //
-// This file is part of 'SAGA - System for Automated     //
-// Geoscientific Analyses'. SAGA 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; version 2 of the License.   //
-//                                                       //
-// SAGA 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,       //
-// write to the Free Software Foundation, Inc.,          //
-// 51 Franklin Street, 5th Floor, Boston, MA 02110-1301, //
-// USA.                                                  //
-//                                                       //
-//-------------------------------------------------------//
-//                                                       //
-//    e-mail:     oconrad at saga-gis.de                    //
-//                                                       //
-//    contact:    Olaf Conrad                            //
-//                Bundesstr. 55                          //
-//                D-20146 Hamburg                        //
-//                Germany                                //
-//                                                       //
-///////////////////////////////////////////////////////////
-
-
-///////////////////////////////////////////////////////////
-//														 //
-//														 //
-//														 //
-///////////////////////////////////////////////////////////
-
-//---------------------------------------------------------
-#ifndef HEADER_INCLUDED__ogr_export_H
-#define HEADER_INCLUDED__ogr_export_H
-
-//---------------------------------------------------------
-#include "ogr_driver.h"
-
-
-///////////////////////////////////////////////////////////
-//														 //
-//														 //
-//														 //
-///////////////////////////////////////////////////////////
-
-//---------------------------------------------------------
-class COGR_Export : public CSG_Module
-{
-public:
-	COGR_Export(void);
-
-
-protected:
-
-	virtual bool		On_Execute		(void);
-
-};
-
-
-///////////////////////////////////////////////////////////
-//														 //
-//														 //
-//														 //
-///////////////////////////////////////////////////////////
-
-//---------------------------------------------------------
-#endif // #ifndef HEADER_INCLUDED__ogr_export_H
+/**********************************************************
+ * Version $Id: MLB_Interface.cpp 911 2011-11-11 11:11:11Z oconrad $
+ *********************************************************/
+
+///////////////////////////////////////////////////////////
+//                                                       //
+//                         SAGA                          //
+//                                                       //
+//      System for Automated Geoscientific Analyses      //
+//                                                       //
+//                    Module Library:                    //
+//                      qm_of_esp                        //
+//                                                       //
+//-------------------------------------------------------//
+//                                                       //
+//                    MLB_Interface.h                    //
+//                                                       //
+//                 Copyright (C) 2013 by                 //
+//                     Olaf Conrad                       //
+//                                                       //
+//-------------------------------------------------------//
+//                                                       //
+// This file is part of 'SAGA - System for Automated     //
+// Geoscientific Analyses'. SAGA 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; version 2 of the License.   //
+//                                                       //
+// SAGA 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,       //
+// write to the Free Software Foundation, Inc.,          //
+// 51 Franklin Street, 5th Floor, Boston, MA 02110-1301, //
+// USA.                                                  //
+//                                                       //
+//-------------------------------------------------------//
+//                                                       //
+//    e-mail:     oconrad at saga-gis.de                    //
+//                                                       //
+//    contact:    Olaf Conrad                            //
+//                Institute of Geography                 //
+//                University of Hamburg                  //
+//                Germany                                //
+//                                                       //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+
+
+///////////////////////////////////////////////////////////
+//														 //
+//														 //
+//														 //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+#ifndef HEADER_INCLUDED__qm_of_esp_MLB_Interface_H
+#define HEADER_INCLUDED__qm_of_esp_MLB_Interface_H
+
+//---------------------------------------------------------
+#include <saga_api/saga_api.h>
+
+//---------------------------------------------------------
+#ifdef qm_of_esp_EXPORTS
+	#define	qm_of_esp_EXPORT	_SAGA_DLL_EXPORT
+#else
+	#define	qm_of_esp_EXPORT	_SAGA_DLL_IMPORT
+#endif
+
+
+///////////////////////////////////////////////////////////
+//														 //
+//														 //
+//														 //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+#endif // #ifndef HEADER_INCLUDED__qm_of_esp_MLB_Interface_H
diff --git a/src/modules/simulation/sim_qm_of_esp/Makefile.am b/src/modules/simulation/sim_qm_of_esp/Makefile.am
new file mode 100644
index 0000000..d4eaf90
--- /dev/null
+++ b/src/modules/simulation/sim_qm_of_esp/Makefile.am
@@ -0,0 +1,30 @@
+#
+# $Id: Makefile.am 1537 2012-11-19 20:05:19Z reklov_w $
+#
+if DEBUG
+DBGFLAGS = -g -DDEBUG
+endif
+if SAGA_UNICODE
+UC_DEFS = -D_SAGA_UNICODE
+endif
+DEF_SAGA           = -D_SAGA_LINUX -D_TYPEDEF_BYTE -D_TYPEDEF_WORD
+CXX_INCS           = -I$(top_srcdir)/src/saga_core
+AM_CXXFLAGS        = -fPIC $(CXX_INCS) $(DEF_SAGA) $(UC_DEFS) $(DBGFLAGS) $(GOMPFLAGS)
+AM_LDFLAGS         = -fPIC -shared -avoid-version
+pkglib_LTLIBRARIES = libsim_qm_of_esp.la
+libsim_qm_of_esp_la_SOURCES =\
+fill_sinks.cpp\
+flow_routing.cpp\
+hillslope_evolution_adi.cpp\
+hillslope_evolution_ftcs.cpp\
+MLB_Interface.cpp\
+successive_flow_routing.cpp\
+fill_sinks.h\
+flow_routing.h\
+hillslope_evolution_adi.h\
+hillslope_evolution_ftcs.h\
+MLB_Interface.h\
+successive_flow_routing.h
+
+libsim_qm_of_esp_la_LIBADD = $(top_srcdir)/src/saga_core/saga_api/libsaga_api.la
+
diff --git a/src/modules/simulation/sim_fire_spreading/Makefile.in b/src/modules/simulation/sim_qm_of_esp/Makefile.in
similarity index 88%
rename from src/modules/simulation/sim_fire_spreading/Makefile.in
rename to src/modules/simulation/sim_qm_of_esp/Makefile.in
index 5512c8d..cfd0f15 100644
--- a/src/modules/simulation/sim_fire_spreading/Makefile.in
+++ b/src/modules/simulation/sim_qm_of_esp/Makefile.in
@@ -78,7 +78,7 @@ PRE_UNINSTALL = :
 POST_UNINSTALL = :
 build_triplet = @build@
 host_triplet = @host@
-subdir = src/modules/simulation/sim_fire_spreading
+subdir = src/modules/simulation/sim_qm_of_esp
 DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \
 	$(top_srcdir)/depcomp
 ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
@@ -125,12 +125,12 @@ am__uninstall_files_from_dir = { \
   }
 am__installdirs = "$(DESTDIR)$(pkglibdir)"
 LTLIBRARIES = $(pkglib_LTLIBRARIES)
-libsim_fire_spreading_la_DEPENDENCIES =  \
+libsim_qm_of_esp_la_DEPENDENCIES =  \
 	$(top_srcdir)/src/saga_core/saga_api/libsaga_api.la
-am_libsim_fire_spreading_la_OBJECTS = fireLib.lo Forecasting.lo \
-	MLB_Interface.lo Simulate.lo
-libsim_fire_spreading_la_OBJECTS =  \
-	$(am_libsim_fire_spreading_la_OBJECTS)
+am_libsim_qm_of_esp_la_OBJECTS = fill_sinks.lo flow_routing.lo \
+	hillslope_evolution_adi.lo hillslope_evolution_ftcs.lo \
+	MLB_Interface.lo successive_flow_routing.lo
+libsim_qm_of_esp_la_OBJECTS = $(am_libsim_qm_of_esp_la_OBJECTS)
 AM_V_lt = $(am__v_lt_ at AM_V@)
 am__v_lt_ = $(am__v_lt_ at AM_DEFAULT_V@)
 am__v_lt_0 = --silent
@@ -151,24 +151,6 @@ DEFAULT_INCLUDES = -I. at am__isrc@ -I$(top_builddir)
 depcomp = $(SHELL) $(top_srcdir)/depcomp
 am__depfiles_maybe = depfiles
 am__mv = mv -f
-COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
-	$(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
-LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \
-	$(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \
-	$(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \
-	$(AM_CFLAGS) $(CFLAGS)
-AM_V_CC = $(am__v_CC_ at AM_V@)
-am__v_CC_ = $(am__v_CC_ at AM_DEFAULT_V@)
-am__v_CC_0 = @echo "  CC      " $@;
-am__v_CC_1 = 
-CCLD = $(CC)
-LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \
-	$(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \
-	$(AM_LDFLAGS) $(LDFLAGS) -o $@
-AM_V_CCLD = $(am__v_CCLD_ at AM_V@)
-am__v_CCLD_ = $(am__v_CCLD_ at AM_DEFAULT_V@)
-am__v_CCLD_0 = @echo "  CCLD    " $@;
-am__v_CCLD_1 = 
 CXXCOMPILE = $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \
 	$(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS)
 LTCXXCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CXX $(AM_LIBTOOLFLAGS) \
@@ -187,8 +169,26 @@ AM_V_CXXLD = $(am__v_CXXLD_ at AM_V@)
 am__v_CXXLD_ = $(am__v_CXXLD_ at AM_DEFAULT_V@)
 am__v_CXXLD_0 = @echo "  CXXLD   " $@;
 am__v_CXXLD_1 = 
-SOURCES = $(libsim_fire_spreading_la_SOURCES)
-DIST_SOURCES = $(libsim_fire_spreading_la_SOURCES)
+COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
+	$(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
+LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \
+	$(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \
+	$(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \
+	$(AM_CFLAGS) $(CFLAGS)
+AM_V_CC = $(am__v_CC_ at AM_V@)
+am__v_CC_ = $(am__v_CC_ at AM_DEFAULT_V@)
+am__v_CC_0 = @echo "  CC      " $@;
+am__v_CC_1 = 
+CCLD = $(CC)
+LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \
+	$(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \
+	$(AM_LDFLAGS) $(LDFLAGS) -o $@
+AM_V_CCLD = $(am__v_CCLD_ at AM_V@)
+am__v_CCLD_ = $(am__v_CCLD_ at AM_DEFAULT_V@)
+am__v_CCLD_0 = @echo "  CCLD    " $@;
+am__v_CCLD_1 = 
+SOURCES = $(libsim_qm_of_esp_la_SOURCES)
+DIST_SOURCES = $(libsim_qm_of_esp_la_SOURCES)
 am__can_run_installinfo = \
   case $$AM_UPDATE_INFO_DIR in \
     n|no|NO) false;; \
@@ -363,30 +363,34 @@ top_builddir = @top_builddir@
 top_srcdir = @top_srcdir@
 
 #
-# $Id: Makefile.am 1277 2011-12-22 15:48:59Z reklov_w $
+# $Id: Makefile.am 1537 2012-11-19 20:05:19Z reklov_w $
 #
 @DEBUG_TRUE at DBGFLAGS = -g -DDEBUG
 @SAGA_UNICODE_TRUE at UC_DEFS = -D_SAGA_UNICODE
 DEF_SAGA = -D_SAGA_LINUX -D_TYPEDEF_BYTE -D_TYPEDEF_WORD
-CXX_INCS = -I$(top_srcdir)/src/saga_core -I$(top_srcdir)/src/modules/grid/grid_tools
+CXX_INCS = -I$(top_srcdir)/src/saga_core
 AM_CXXFLAGS = -fPIC $(CXX_INCS) $(DEF_SAGA) $(UC_DEFS) $(DBGFLAGS) $(GOMPFLAGS)
 AM_LDFLAGS = -fPIC -shared -avoid-version
-pkglib_LTLIBRARIES = libsim_fire_spreading.la
-libsim_fire_spreading_la_SOURCES = \
-fireLib.c\
-Forecasting.cpp\
+pkglib_LTLIBRARIES = libsim_qm_of_esp.la
+libsim_qm_of_esp_la_SOURCES = \
+fill_sinks.cpp\
+flow_routing.cpp\
+hillslope_evolution_adi.cpp\
+hillslope_evolution_ftcs.cpp\
 MLB_Interface.cpp\
-Simulate.cpp\
-fireLib.h\
-Forecasting.h\
+successive_flow_routing.cpp\
+fill_sinks.h\
+flow_routing.h\
+hillslope_evolution_adi.h\
+hillslope_evolution_ftcs.h\
 MLB_Interface.h\
-Simulate.h
+successive_flow_routing.h
 
-libsim_fire_spreading_la_LIBADD = $(top_srcdir)/src/saga_core/saga_api/libsaga_api.la
+libsim_qm_of_esp_la_LIBADD = $(top_srcdir)/src/saga_core/saga_api/libsaga_api.la
 all: all-am
 
 .SUFFIXES:
-.SUFFIXES: .c .cpp .lo .o .obj
+.SUFFIXES: .cpp .lo .o .obj
 $(srcdir)/Makefile.in:  $(srcdir)/Makefile.am  $(am__configure_deps)
 	@for dep in $?; do \
 	  case '$(am__configure_deps)' in \
@@ -396,9 +400,9 @@ $(srcdir)/Makefile.in:  $(srcdir)/Makefile.am  $(am__configure_deps)
 	      exit 1;; \
 	  esac; \
 	done; \
-	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/modules/simulation/sim_fire_spreading/Makefile'; \
+	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/modules/simulation/sim_qm_of_esp/Makefile'; \
 	$(am__cd) $(top_srcdir) && \
-	  $(AUTOMAKE) --foreign src/modules/simulation/sim_fire_spreading/Makefile
+	  $(AUTOMAKE) --foreign src/modules/simulation/sim_qm_of_esp/Makefile
 .PRECIOUS: Makefile
 Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
 	@case '$?' in \
@@ -453,8 +457,8 @@ clean-pkglibLTLIBRARIES:
 	  rm -f $${locs}; \
 	}
 
-libsim_fire_spreading.la: $(libsim_fire_spreading_la_OBJECTS) $(libsim_fire_spreading_la_DEPENDENCIES) $(EXTRA_libsim_fire_spreading_la_DEPENDENCIES) 
-	$(AM_V_CXXLD)$(CXXLINK) -rpath $(pkglibdir) $(libsim_fire_spreading_la_OBJECTS) $(libsim_fire_spreading_la_LIBADD) $(LIBS)
+libsim_qm_of_esp.la: $(libsim_qm_of_esp_la_OBJECTS) $(libsim_qm_of_esp_la_DEPENDENCIES) $(EXTRA_libsim_qm_of_esp_la_DEPENDENCIES) 
+	$(AM_V_CXXLD)$(CXXLINK) -rpath $(pkglibdir) $(libsim_qm_of_esp_la_OBJECTS) $(libsim_qm_of_esp_la_LIBADD) $(LIBS)
 
 mostlyclean-compile:
 	-rm -f *.$(OBJEXT)
@@ -462,34 +466,12 @@ mostlyclean-compile:
 distclean-compile:
 	-rm -f *.tab.c
 
- at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/Forecasting.Plo at am__quote@
 @AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/MLB_Interface.Plo at am__quote@
- at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/Simulate.Plo at am__quote@
- at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/fireLib.Plo at am__quote@
-
-.c.o:
- at am__fastdepCC_TRUE@	$(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.o$$||'`;\
- at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\
- at am__fastdepCC_TRUE@	$(am__mv) $$depbase.Tpo $$depbase.Po
- at AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
- at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
- at am__fastdepCC_FALSE@	$(AM_V_CC at am__nodep@)$(COMPILE) -c -o $@ $<
-
-.c.obj:
- at am__fastdepCC_TRUE@	$(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.obj$$||'`;\
- at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ `$(CYGPATH_W) '$<'` &&\
- at am__fastdepCC_TRUE@	$(am__mv) $$depbase.Tpo $$depbase.Po
- at AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
- at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
- at am__fastdepCC_FALSE@	$(AM_V_CC at am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'`
-
-.c.lo:
- at am__fastdepCC_TRUE@	$(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.lo$$||'`;\
- at am__fastdepCC_TRUE@	$(LTCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\
- at am__fastdepCC_TRUE@	$(am__mv) $$depbase.Tpo $$depbase.Plo
- at AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@
- at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
- at am__fastdepCC_FALSE@	$(AM_V_CC at am__nodep@)$(LTCOMPILE) -c -o $@ $<
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/fill_sinks.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/flow_routing.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/hillslope_evolution_adi.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/hillslope_evolution_ftcs.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/successive_flow_routing.Plo at am__quote@
 
 .cpp.o:
 @am__fastdepCXX_TRUE@	$(AM_V_CXX)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.o$$||'`;\
diff --git a/src/saga_core/saga_gui/data_source.cpp b/src/modules/simulation/sim_qm_of_esp/fill_sinks.cpp
similarity index 52%
copy from src/saga_core/saga_gui/data_source.cpp
copy to src/modules/simulation/sim_qm_of_esp/fill_sinks.cpp
index 7148d75..e15bd02 100644
--- a/src/saga_core/saga_gui/data_source.cpp
+++ b/src/modules/simulation/sim_qm_of_esp/fill_sinks.cpp
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: Data_Source.cpp 911 2011-02-14 16:38:15Z reklov_w $
+ * Version $Id: fill_sinks.cpp 911 2011-02-14 16:38:15Z reklov_w $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -8,15 +8,15 @@
 //                                                       //
 //      System for Automated Geoscientific Analyses      //
 //                                                       //
-//                    User Interface                     //
-//                                                       //
-//                    Program: SAGA                      //
+//                    Module Library:                    //
+//                      qm_of_esp                        //
 //                                                       //
 //-------------------------------------------------------//
 //                                                       //
-//                   data_source.cpp                     //
+//                    fill_sinks.cpp                     //
 //                                                       //
-//          Copyright (C) 2011 by Olaf Conrad            //
+//                 Copyright (C) 2013 by                 //
+//                      Olaf Conrad                      //
 //                                                       //
 //-------------------------------------------------------//
 //                                                       //
@@ -40,13 +40,13 @@
 //                                                       //
 //-------------------------------------------------------//
 //                                                       //
+//    e-mail:     oconrad at saga-gis.org                   //
+//                                                       //
 //    contact:    Olaf Conrad                            //
 //                Institute of Geography                 //
 //                University of Hamburg                  //
 //                Germany                                //
 //                                                       //
-//    e-mail:     oconrad at saga-gis.org                   //
-//                                                       //
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
@@ -59,31 +59,7 @@
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
-#include <wx/wx.h>
-#include <wx/treectrl.h>
-#include <wx/imaglist.h>
-
-#include <saga_api/saga_api.h>
-
-#include "res_controls.h"
-#include "res_images.h"
-
-#include "helper.h"
-
-#include "data_source.h"
-#include "data_source_files.h"
-#include "data_source_odbc.h"
-#include "data_source_pgsql.h"
-
-#include "wksp_layer.h"
-#include "wksp_map_layer.h"
-
-#include "wksp_data_manager.h"
-#include "wksp_data_layers.h"
-#include "wksp_table.h"
-
-#include "wksp_module_library.h"
-#include "wksp_module.h"
+#include "fill_sinks.h"
 
 
 ///////////////////////////////////////////////////////////
@@ -93,33 +69,46 @@
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
-enum
+class CStack : public CSG_Stack
 {
-	IMG_FILES	= 0,
-	IMG_DATABASE,
-	IMG_WEBSERVICE
-};
+public:
+	CStack(void) : CSG_Stack(3 * sizeof(int))	{}
 
+	//-----------------------------------------------------
+	virtual bool			Push			(int  x, int  y, int  i)
+	{
+		int	*Data	= (int *)Get_Record_Push();
 
-///////////////////////////////////////////////////////////
-//														 //
-//														 //
-//														 //
-///////////////////////////////////////////////////////////
+		if( Data )
+		{
+			Data[0]	= x;
+			Data[1]	= y;
+			Data[2]	= i;
 
-//---------------------------------------------------------
-CData_Source	*g_pData_Source	= NULL;
+			return( true );
+		}
 
+		return( false );
+	}
 
-///////////////////////////////////////////////////////////
-//														 //
-//														 //
-//														 //
-///////////////////////////////////////////////////////////
+	//-----------------------------------------------------
+	virtual bool			Pop				(int &x, int &y, int &i)
+	{
+		int	*Data	= (int *)Get_Record_Pop();
 
-//---------------------------------------------------------
-BEGIN_EVENT_TABLE(CData_Source, wxNotebook)
-END_EVENT_TABLE()
+		if( Data )
+		{
+			x	= Data[0];
+			y	= Data[1];
+			i	= Data[2];
+
+			return( true );
+		}
+
+		return( false );
+	}
+
+};
 
 
 ///////////////////////////////////////////////////////////
@@ -129,121 +118,198 @@ END_EVENT_TABLE()
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
-CData_Source::CData_Source(wxWindow *pParent)
-	: wxNotebook(pParent, ID_WND_DATA_SOURCE, wxDefaultPosition, wxDefaultSize, wxNB_TOP|wxNB_MULTILINE, _TL("Data Source"))
+CFill_Sinks::CFill_Sinks(void)
 {
-	g_pData_Source	= this;
-
 	//-----------------------------------------------------
-	AssignImageList(new wxImageList(IMG_SIZE_NOTEBOOK, IMG_SIZE_NOTEBOOK, true, 0));
+	Set_Name	(_TL("Fill Sinks (QM of ESP)"));
 
-	IMG_ADD_TO_NOTEBOOK(ID_IMG_NB_DATA_SOURCE_FILES);
-	IMG_ADD_TO_NOTEBOOK(ID_IMG_NB_DATA_SOURCE_DATABASE);
-	IMG_ADD_TO_NOTEBOOK(ID_IMG_NB_DATA_SOURCE_WEBSERVICE);
+	Set_Author	("O.Conrad (c) 2013");
+
+	Set_Description	(_TW(
+		"Filling in pits and flats in a DEM.\n"
+		"\nReferences:\n"
+		"Pelletier, J.D. (2008): Quantitative Modeling of Earth Surface Processes. Cambridge, 295p.\n"
+	));
 
 	//-----------------------------------------------------
-	m_pFiles	= new CData_Source_Files(this);	m_pFiles->SetName(_TL("File System"));
-	m_pODBC		= new CData_Source_ODBC (this);	m_pODBC ->SetName(_TL("ODBC"));
-	m_pPgSQL	= new CData_Source_PgSQL(this);	m_pPgSQL->SetName(_TL("PostgreSQL"));
-
-#if defined(_SAGA_MSW)
-	m_pFiles->Hide();
-	m_pODBC ->Hide();
-	m_pPgSQL->Hide();
-#endif
+	Parameters.Add_Grid(
+		NULL	, "DEM"			, _TL("DEM"),
+		_TL(""),
+		PARAMETER_INPUT
+	);
+
+	Parameters.Add_Grid(
+		NULL	, "FILLED"		, _TL("DEM without Sinks"),
+		_TL(""),
+		PARAMETER_OUTPUT
+	);
+
+	Parameters.Add_Grid(
+		NULL	, "SINKS"		, _TL("Sinks"),
+		_TL(""),
+		PARAMETER_OUTPUT_OPTIONAL
+	);
+
+	Parameters.Add_Value(
+		NULL	, "DZFILL"		, _TL("Fill Increment"),
+		_TL(""),
+		PARAMETER_TYPE_Double, 0.01, 0.0000001, true
+	);
 }
 
+
+///////////////////////////////////////////////////////////
+//														 //
+///////////////////////////////////////////////////////////
+
 //---------------------------------------------------------
-void CData_Source::Add_Pages(void)
+bool CFill_Sinks::On_Execute(void)
 {
-	_Show_Page(m_pFiles);
-	_Show_Page(m_pODBC);
-	_Show_Page(m_pPgSQL);
+	CSG_Grid	*pDEM, *pSinks;
 
-	long	lValue;
+	pDEM		= Parameters("DEM"   )->asGrid();
+	m_pDEM		= Parameters("FILLED")->asGrid();
+	pSinks		= Parameters("SINKS" )->asGrid();
+	m_dzFill	= Parameters("DZFILL")->asDouble();
 
-	if( CONFIG_Read("/DATA/SOURCE", "TAB", lValue) )
+	m_pDEM->Assign(pDEM);
+	m_pDEM->Set_Name(CSG_String::Format(SG_T("%s [%s]"), pDEM->Get_Name(), _TL("No Sinks")));
+
+	if( !Fill_Sinks() )
 	{
-		SetSelection((size_t)lValue);
+		return( false );
 	}
+
+	if( pSinks )
+	{
+		pSinks->Assign(m_pDEM);
+		pSinks->Subtract(*pDEM);
+		pSinks->Set_NoData_Value(0.0);
+	}
+
+	return( true );
 }
 
 //---------------------------------------------------------
-CData_Source::~CData_Source(void)
+bool CFill_Sinks::Fill_Sinks(CSG_Grid *pDEM, CSG_Grid *pFilled, double dzFill)
 {
-	CONFIG_Write("/DATA/SOURCE", "TAB", (long)GetSelection());
+	if( is_Executing() || !pDEM || (pFilled && !pDEM->is_Compatible(pFilled)) || !Get_System()->Assign(pDEM->Get_System()) )
+	{
+		return( false );
+	}
+
+	//-----------------------------------------------------
+	if( pFilled )
+	{
+		m_pDEM	= pFilled;
+		m_pDEM->Assign(pDEM);
+	}
+	else
+	{
+		m_pDEM	= pDEM;
+	}
 
-	g_pData_Source		= NULL;
+	m_dzFill	= dzFill;
+
+
+	return( Fill_Sinks() );
 }
 
 
 ///////////////////////////////////////////////////////////
 //														 //
-//														 //
-//														 //
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
-void CData_Source::Autoconnect_DB(void)
+bool CFill_Sinks::Fill_Sinks(void)
 {
-	m_pPgSQL->Autoconnect();
-}
-
-//---------------------------------------------------------
-bool CData_Source::Set_Data_Source(CWKSP_Base_Item *pItem)
-{
-	if( pItem == NULL )
+	if( m_dzFill <= 0.0 )
 	{
-		return( true );
+		return( false );
 	}
 
-	//-----------------------------------------------------
-	switch( pItem->Get_Type() )
+	Process_Set_Text(_TL("Processing Sinks and Flats"));
+
+	for(int y=0; y<Get_NY() && Set_Progress(y); y++)
 	{
-	default:
-		break;
-
-	case WKSP_ITEM_Map_Layer:
-		m_pFiles->SetPath(((CWKSP_Map_Layer      *)pItem)->Get_Layer()->Get_Object()->Get_File_Name());
-		break;
-
-	case WKSP_ITEM_Table:
-		m_pFiles->SetPath(((CWKSP_Table          *)pItem)->Get_Table()->Get_File_Name());
-		break;
-
-	case WKSP_ITEM_Shapes:
-	case WKSP_ITEM_TIN:
-	case WKSP_ITEM_PointCloud:
-	case WKSP_ITEM_Grid:
-		m_pFiles->SetPath(((CWKSP_Layer          *)pItem)->Get_Object()->Get_File_Name(false));
-		break;
-
-	case WKSP_ITEM_Module_Library:
-	//	m_pFiles->SetPath(((CWKSP_Module_Library *)pItem)->Get_File_Name());
-		break;
-
-	case WKSP_ITEM_Module:
-		m_pFiles->SetPath(((CWKSP_Module         *)pItem)->Get_File_Name());
-		break;
+		for(int x=0; x<Get_NX(); x++)
+		{
+			Fill_Sink(x, y);
+		}
 	}
 
 	return( true );
 }
 
+//---------------------------------------------------------
+bool CFill_Sinks::Fill_Sink(int x, int y)
+{
+	int		i;
+	CStack	Stack;
 
-///////////////////////////////////////////////////////////
-//														 //
-//														 //
-//														 //
-///////////////////////////////////////////////////////////
+	do
+	{
+		if( Fill_Cell(x, y) )
+		{
+			Stack.Push(x, y, 1);
+
+			x	= Get_xTo(0, x);
+			y	= Get_yTo(0, y);
+		}
+		else if( Stack.Pop(x, y, i) && i < 8 )
+		{
+			Stack.Push(x, y, 1 + i);
+
+			x	= Get_xTo(i, x);
+			y	= Get_yTo(i, y);
+		}
+	}
+	while( Stack.Get_Size() > 0 );
+
+	return( true );
+}
 
 //---------------------------------------------------------
-bool CData_Source::Update_ODBC_Source(const wxString &Server)
+bool CFill_Sinks::Fill_Cell(int x, int y)
 {
-	m_pODBC ->Update_Source(Server);
-	m_pPgSQL->Update_Source(Server);
+	if( x > 0 && x < Get_NX() - 1 && y > 0 && y < Get_NY() - 1 && !m_pDEM->is_NoData(x, y) )
+	{
+		for(bool bFilled=false, bSingle=true; ; )
+		{
+			bool	bPit	= true;
+			double	zMin	= m_pDEM->asDouble(x, y);
 
-	return( true );
+			for(int i=0; i<8; i++)
+			{
+				int	ix	= Get_xTo(i, x);
+				int	iy	= Get_yTo(i, y);
+
+				if( m_pDEM->is_InGrid(ix, iy) )
+				{
+					bSingle	= false;
+
+					if( m_pDEM->asDouble(ix, iy) < zMin )
+					{
+						zMin	= m_pDEM->asDouble(ix, iy);
+						bPit	= false;
+					}
+				}
+			}
+
+			if( !bSingle && bPit )
+			{
+				m_pDEM->Set_Value(x, y, zMin + m_dzFill);
+
+				bFilled	= true;
+			}
+			else
+			{
+				return( bFilled );
+			}
+		}
+	}
+
+	return( false );
 }
 
 
@@ -253,55 +319,50 @@ bool CData_Source::Update_ODBC_Source(const wxString &Server)
 //														 //
 ///////////////////////////////////////////////////////////
 
-//---------------------------------------------------------
-bool CData_Source::_Show_Page(wxWindow *pPage)
+/*/---------------------------------------------------------
+void CFill_Sinks::Fill_Sinks(int x, int y)
 {
-	int		Image_ID	= -1;
-
-	//-----------------------------------------------------
-	if( pPage == m_pFiles )	Image_ID	= IMG_FILES;
-	if( pPage == m_pODBC  )	Image_ID	= IMG_DATABASE;
-	if( pPage == m_pPgSQL )	Image_ID	= IMG_DATABASE;
-
-	//-----------------------------------------------------
-	if( pPage )
+	if( Fill_Cell(x, y) )
 	{
-		for(int i=0; i<(int)GetPageCount(); i++)
+		for(int i=0; i<8; i++)
 		{
-			if( GetPage(i) == pPage )
-			{
-				return( true );
-			}
+			Fill_Sinks(Get_xTo(i, x), Get_yTo(i, y));
 		}
-
-		AddPage(pPage, pPage->GetName(), false, Image_ID);
-
-		return( true );
 	}
+}/**/
 
-	return( false );
-}
-
-//---------------------------------------------------------
-bool CData_Source::_Hide_Page(wxWindow *pPage)
+/*/---------------------------------------------------------
+void CFill_Sinks::Fill_Sinks(int x, int y)
 {
-	for(int i=0; i<(int)GetPageCount(); i++)
+	if( x > 0 && x < Get_NX() - 1 && y > 0 && y < Get_NY() - 1 && !m_pDEM->is_NoData(x, y) )
 	{
-		if( GetPage(i) == pPage )
+		int		i;
+		double	zMin;
+
+		for(i=0, zMin=m_pDEM->asDouble(x, y); i<8; i++)
 		{
-			if( i == GetSelection() )
+			int	ix	= Get_xTo(i, x);
+			int	iy	= Get_yTo(i, y);
+
+			if( m_pDEM->is_InGrid(ix, iy) && m_pDEM->asDouble(ix, iy) < zMin )
 			{
-				SetSelection(i - 1);
+				zMin	= m_pDEM->asDouble(ix, iy);
 			}
+		}
 
-			RemovePage(i);
+		if( m_pDEM->asDouble(x, y) <= zMin )
+		{
+			m_pDEM->Set_Value(x, y, zMin + m_dzFill);
 
-			return( true );
+			Fill_Sinks(x, y);
+
+			for(i=0; i<8; i++)
+			{
+				Fill_Sinks(Get_xTo(i, x), Get_yTo(i, y));
+			}
 		}
 	}
-
-	return( false );
-}
+}/**/
 
 
 ///////////////////////////////////////////////////////////
diff --git a/src/modules/grid/grid_analysis/diversity_analysis.h b/src/modules/simulation/sim_qm_of_esp/fill_sinks.h
similarity index 73%
copy from src/modules/grid/grid_analysis/diversity_analysis.h
copy to src/modules/simulation/sim_qm_of_esp/fill_sinks.h
index c03ea9e..78a32bb 100644
--- a/src/modules/grid/grid_analysis/diversity_analysis.h
+++ b/src/modules/simulation/sim_qm_of_esp/fill_sinks.h
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: diversity_analysis.h 2476 2015-04-22 18:41:38Z oconrad $
+ * Version $Id: fill_sinks.h 911 2011-02-14 16:38:15Z reklov_w $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -9,13 +9,13 @@
 //      System for Automated Geoscientific Analyses      //
 //                                                       //
 //                    Module Library:                    //
-//                     grid_analysis                     //
+//                      qm_of_esp                        //
 //                                                       //
 //-------------------------------------------------------//
 //                                                       //
-//                 diversity_analysis.h                  //
+//                     fill_sinks.h                      //
 //                                                       //
-//                 Copyright (C) 2015 by                 //
+//                 Copyright (C) 2013 by                 //
 //                      Olaf Conrad                      //
 //                                                       //
 //-------------------------------------------------------//
@@ -53,20 +53,19 @@
 
 
 ///////////////////////////////////////////////////////////
-//														 //
+//                                                       //												
+//                                                       //												
 //                                                       //
-//														 //
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
-#ifndef HEADER_INCLUDED__diversity_analysis_H
-#define HEADER_INCLUDED__diversity_analysis_H
-
+#ifndef HEADER_INCLUDED__fill_sinks_H
+#define HEADER_INCLUDED__fill_sinks_H
 
 ///////////////////////////////////////////////////////////
-//														 //
+//                                                       //												
+//                                                       //												
 //                                                       //
-//														 //
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
@@ -74,46 +73,47 @@
 
 
 ///////////////////////////////////////////////////////////
-//														 //
+//                                                       //												
+//                                                       //												
 //                                                       //
-//														 //
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
-class CDiversity_Analysis : public CSG_Module_Grid
+class CFill_Sinks : public CSG_Module_Grid
 {
 public:
-	CDiversity_Analysis(void);
 
+	CFill_Sinks(void);
 
-protected:
+	virtual CSG_String	Get_MenuPath			(void)	{	return( _TL("A:Terrain Analysis|Preprocessing" ));	}
 
-	virtual int					On_Parameters_Enable	(CSG_Parameters *pParameters, CSG_Parameter *pParameter);
+	bool				Fill_Sinks				(CSG_Grid *pDEM, CSG_Grid *pFilled=NULL, double dzFill=0.01);
 
-	virtual bool				On_Execute				(void);
 
+protected:
 
-private:
+	virtual bool		On_Execute				(void);
 
-	bool						m_bWeighted;
 
-	int							m_NB_Step;
+private:
 
-	CSG_Grid					*m_pClasses, *m_pDiversity, *m_pSize_Mean, *m_pSize_Skew, *m_pConnectivity;
+	double				m_dzFill;
 
-	CSG_Grid_Cell_Addressor		m_Search;
+	CSG_Grid			*m_pDEM;
 
 
-	bool						Get_Diversity			(int x, int y);
+	bool				Fill_Sinks				(void);
+	bool				Fill_Sink				(int x, int y);
+	bool				Fill_Cell				(int x, int y);
 
 };
 
 
 ///////////////////////////////////////////////////////////
-//														 //
+//                                                       //												
+//                                                       //												
 //                                                       //
-//														 //
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
-#endif // #ifndef HEADER_INCLUDED__diversity_analysis_H
+#endif // #ifndef HEADER_INCLUDED__fill_sinks_H
diff --git a/src/saga_core/saga_gui/res_controls.h b/src/modules/simulation/sim_qm_of_esp/flow_routing.cpp
similarity index 51%
copy from src/saga_core/saga_gui/res_controls.h
copy to src/modules/simulation/sim_qm_of_esp/flow_routing.cpp
index bc21d13..df769a7 100644
--- a/src/saga_core/saga_gui/res_controls.h
+++ b/src/modules/simulation/sim_qm_of_esp/flow_routing.cpp
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: res_controls.h 1939 2014-01-14 16:48:06Z oconrad $
+ * Version $Id: flow_routing.cpp 911 2011-02-14 16:38:15Z reklov_w $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -8,15 +8,15 @@
 //                                                       //
 //      System for Automated Geoscientific Analyses      //
 //                                                       //
-//                    User Interface                     //
-//                                                       //
-//                    Program: SAGA                      //
+//                    Module Library:                    //
+//                      qm_of_esp                        //
 //                                                       //
 //-------------------------------------------------------//
 //                                                       //
-//                    RES_Controls.h                     //
+//                   flow_routing.cpp                    //
 //                                                       //
-//          Copyright (C) 2005 by Olaf Conrad            //
+//                 Copyright (C) 2013 by                 //
+//                      Olaf Conrad                      //
 //                                                       //
 //-------------------------------------------------------//
 //                                                       //
@@ -40,15 +40,13 @@
 //                                                       //
 //-------------------------------------------------------//
 //                                                       //
+//    e-mail:     oconrad at saga-gis.org                   //
+//                                                       //
 //    contact:    Olaf Conrad                            //
 //                Institute of Geography                 //
-//                University of Goettingen               //
-//                Goldschmidtstr. 5                      //
-//                37077 Goettingen                       //
+//                University of Hamburg                  //
 //                Germany                                //
 //                                                       //
-//    e-mail:     oconrad at saga-gis.org                   //
-//                                                       //
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
@@ -61,8 +59,7 @@
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
-#ifndef _HEADER_INCLUDED__SAGA_GUI__RES_Controls_H
-#define _HEADER_INCLUDED__SAGA_GUI__RES_Controls_H
+#include "flow_routing.h"
 
 
 ///////////////////////////////////////////////////////////
@@ -72,119 +69,182 @@
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
-#include <wx/wx.h>
-#include <wx/event.h>
+CFlow_Routing::CFlow_Routing(void)
+{
+	//-----------------------------------------------------
+	Set_Name	(_TL("Flow Accumulation (QM of ESP)"));
 
-//---------------------------------------------------------
-#include <saga_api/saga_api.h>
+	Set_Author	("O.Conrad (c) 2013");
+
+	Set_Description	(_TW(
+		"Calculation of flow accumulation, aka upslope contributing area, with the "
+		"multiple flow direction method after Freeman (1991).\n"
+		"\nReferences:\n"
+		"Freeman, G.T. (1991): Calculating catchment area with divergent flow based on a rectangular grid. Computers & Geosciences, 17, pp.413-422.\n"
+		"Pelletier, J.D. (2008): Quantitative Modeling of Earth Surface Processes. Cambridge, 295p.\n"
+	));
+
+	//-----------------------------------------------------
+	Parameters.Add_Grid(
+		NULL	, "DEM"			, _TL("DEM"),
+		_TL(""),
+		PARAMETER_INPUT
+	);
+
+	Parameters.Add_Grid(
+		NULL	, "FLOW"		, _TL("Contributing Area"),
+		_TL(""),
+		PARAMETER_OUTPUT
+	);
+
+	Parameters.Add_Choice(
+		NULL	, "PREPROC"		, _TL("Preprocessing"),
+		_TL(""),
+		CSG_String::Format(SG_T("%s|%s|%s|"),
+			_TL("none"),
+			_TL("fill sinks temporarily"),
+			_TL("fill sinks permanently")
+		), 1
+	);
+
+	Parameters.Add_Value(
+		NULL	, "DZFILL"		, _TL("Fill Increment"),
+		_TL(""),
+		PARAMETER_TYPE_Double, 0.01, 0.0000001, true
+	);
+}
 
 
 ///////////////////////////////////////////////////////////
 //														 //
-//														 //
-//														 //
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
-enum ID_CONTROLS
+int CFlow_Routing::On_Parameters_Enable(CSG_Parameters *pParameters, CSG_Parameter *pParameter)
 {
-	ID_WND_START				= wxID_HIGHEST,
+	if( !SG_STR_CMP(pParameter->Get_Identifier(), "PREPROC") )
+	{
+		pParameters->Get_Parameter("DZFILL")->Set_Enabled(pParameter->asInt() != 0);
+	}
 
-	ID_WND_MAIN,
+	return( 1 );
+}
 
-	ID_WND_INFO,
-	ID_WND_INFO_MESSAGES,
-	ID_WND_INFO_DESCRIPTION,
-	ID_WND_INFO_ATTRIBUTES,
 
-	ID_WND_ACTIVE,
-	ID_WND_ACTIVE_PARAMETERS,
-	ID_WND_ACTIVE_DESCRIPTION,
-	ID_WND_ACTIVE_HISTORY,
-	ID_WND_ACTIVE_ATTRIBUTES,
-	ID_WND_ACTIVE_LEGEND,
-	ID_WND_ACTIVE_HTMLEXTRAINFO,
-
-	ID_WND_DATA_SOURCE,
-	ID_WND_DATA_SOURCE_FILES,
-	ID_WND_DATA_SOURCE_DATABASE,
-	ID_WND_DATA_SOURCE_WEBSERVICE,
+///////////////////////////////////////////////////////////
+//														 //
+///////////////////////////////////////////////////////////
 
-	ID_WND_PARM,
+//---------------------------------------------------------
+bool CFlow_Routing::On_Execute(void)
+{
+	m_pDEM	= Parameters("DEM" )->asGrid();
+	m_pFlow	= Parameters("FLOW")->asGrid();
 
-	ID_WND_WKSP,
-	ID_WND_WKSP_MODULES,
-	ID_WND_WKSP_DATA,
-	ID_WND_WKSP_MAPS,
+	return( Set_Flow(Parameters("PREPROC")->asInt(), Parameters("DZFILL")->asDouble()) );
+}
 
-	ID_WND_PROGRESSBAR,
+//---------------------------------------------------------
+bool CFlow_Routing::Set_Flow(CSG_Grid *pDEM, CSG_Grid *pFlow, int Preprocess, double dzFill)
+{
+	if( is_Executing() || !pDEM || !pFlow || !pDEM->is_Compatible(pFlow) || !Get_System()->Assign(pDEM->Get_System()) )
+	{
+		return( false );
+	}
 
-	//-----------------------------------------------------
-	ID_VIEW_TABLE,
-	ID_VIEW_TABLE_DIAGRAM,
-	ID_VIEW_MAP,
-	ID_VIEW_MAP_3D,
-	ID_VIEW_HISTOGRAM,
-	ID_VIEW_SCATTERPLOT,
-	ID_VIEW_LAYOUT,
+	m_pDEM	= pDEM;
+	m_pFlow	= pFlow;
 
-	//-----------------------------------------------------
-	ID_TB_MAIN,
+	return( Set_Flow(Preprocess, dzFill) );
+}
 
-	ID_TB_VIEW_TABLE,
-	ID_TB_VIEW_TABLE_DIAGRAM,
-	ID_TB_VIEW_MAP,
-	ID_TB_VIEW_MAP_3D,
-	ID_TB_VIEW_HISTOGRAM,
-	ID_TB_VIEW_SCATTERPLOT,
-	ID_TB_VIEW_LAYOUT,
 
-	//-----------------------------------------------------
-	ID_LISTBOX_SELECT,
-	ID_LISTBOX_ADD,
+///////////////////////////////////////////////////////////
+//														 //
+///////////////////////////////////////////////////////////
 
-	ID_COMBOBOX_SELECT,
+//---------------------------------------------------------
+bool CFlow_Routing::Set_Flow(int Preprocess, double dzFill)
+{
+	CSG_Grid	DEM;
 
-	//-----------------------------------------------------
-	ID_BTN_OK,
-	ID_BTN_CANCEL,
+	switch( Preprocess )
+	{
+	case 1:
+		DEM.Create(*m_pDEM);	m_pDEM	= &DEM;
 
-	ID_BTN_APPLY,
-	ID_BTN_RESTORE,
+	case 2:
+		{
+			CFill_Sinks	Preprocessor;
 
-	ID_BTN_ADD,
-	ID_BTN_ADD_ALL,
-	ID_BTN_INSERT,
-	ID_BTN_DELETE,
-	ID_BTN_DELETE_ALL,
+			Preprocessor.Fill_Sinks(m_pDEM, NULL, dzFill);
+		}
+		break;
+	}
 
-	ID_BTN_UP,
-	ID_BTN_DOWN,
+	//-----------------------------------------------------
+	int	i, x, y;
 
-	ID_BTN_EXECUTE,
+	m_pFlow->Assign(0.0);
 
-	ID_BTN_LOAD,
-	ID_BTN_SAVE,
+	m_pDEM->Get_Sorted(0, x, y);
 
-	ID_BTN_DEFAULTS,
+	Process_Set_Text(_TL("Calculating Contributing Area"));
 
-	ID_BTN_COLORS,
-	ID_BTN_COLORS_MIRROR,
-	ID_BTN_COLORS_INVERT,
-	ID_BTN_COLORS_RANDOM,
-	ID_BTN_COLORS_PRESET,
-	ID_BTN_COLORS_COUNT
-};
+	for(i=0; i<Get_NCells() && Set_Progress(i, Get_NCells()); i++)
+	{
+		if( m_pDEM->Get_Sorted(i, x, y) )
+		{
+			Set_Flow(x, y);
+		}
+	}
 
+	//-----------------------------------------------------
+	if( Preprocess == 2 )
+	{
+		DataObject_Update(m_pDEM);
+	}
 
-///////////////////////////////////////////////////////////
-//														 //
-//														 //
-//														 //
-///////////////////////////////////////////////////////////
+	return( true );
+}
 
 //---------------------------------------------------------
-const wxString	CTRL_Get_Name		(int ID_CTRL);
+void CFlow_Routing::Set_Flow(int x, int y)
+{
+	if( !m_pDEM->is_NoData(x, y) )
+	{
+		m_pFlow->Add_Value(x, y, Get_Cellarea());
+
+		int		i;
+		double	z, dz[8], dzSum;
+
+		for(i=0, dzSum=0.0, z=m_pDEM->asDouble(x, y); i<8; i++)
+		{
+			int	ix	= Get_xTo(i, x);
+			int	iy	= Get_yTo(i, y);
+
+			if( m_pDEM->is_InGrid(ix, iy) && (dz[i] = z - m_pDEM->asDouble(ix, iy)) > 0.0 )
+			{
+				dzSum	+= (dz[i] = pow(dz[i] / Get_Length(i), 1.1));
+			}
+			else
+			{
+				dz[i]	= 0.0;
+			}
+		}
+
+		if( dzSum > 0.0 )
+		{
+			for(i=0, z=m_pFlow->asDouble(x, y)/dzSum; i<8; i++)
+			{
+				if( dz[i] > 0.0 )
+				{
+					m_pFlow->Add_Value(Get_xTo(i, x), Get_yTo(i, y), z * dz[i]);
+				}
+			}
+		}
+	}
+}
 
 
 ///////////////////////////////////////////////////////////
@@ -194,4 +254,3 @@ const wxString	CTRL_Get_Name		(int ID_CTRL);
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
-#endif // #ifndef _HEADER_INCLUDED__SAGA_GUI__RES_Controls_H
diff --git a/src/modules/grid/grid_analysis/diversity_analysis.h b/src/modules/simulation/sim_qm_of_esp/flow_routing.h
similarity index 71%
copy from src/modules/grid/grid_analysis/diversity_analysis.h
copy to src/modules/simulation/sim_qm_of_esp/flow_routing.h
index c03ea9e..49196ef 100644
--- a/src/modules/grid/grid_analysis/diversity_analysis.h
+++ b/src/modules/simulation/sim_qm_of_esp/flow_routing.h
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: diversity_analysis.h 2476 2015-04-22 18:41:38Z oconrad $
+ * Version $Id: flow_routing.h 911 2011-02-14 16:38:15Z reklov_w $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -9,13 +9,13 @@
 //      System for Automated Geoscientific Analyses      //
 //                                                       //
 //                    Module Library:                    //
-//                     grid_analysis                     //
+//                      qm_of_esp                        //
 //                                                       //
 //-------------------------------------------------------//
 //                                                       //
-//                 diversity_analysis.h                  //
+//                    flow_routing.h                     //
 //                                                       //
-//                 Copyright (C) 2015 by                 //
+//                 Copyright (C) 2013 by                 //
 //                      Olaf Conrad                      //
 //                                                       //
 //-------------------------------------------------------//
@@ -53,67 +53,66 @@
 
 
 ///////////////////////////////////////////////////////////
-//														 //
+//                                                       //												
+//                                                       //												
 //                                                       //
-//														 //
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
-#ifndef HEADER_INCLUDED__diversity_analysis_H
-#define HEADER_INCLUDED__diversity_analysis_H
-
+#ifndef HEADER_INCLUDED__flow_routing_H
+#define HEADER_INCLUDED__flow_routing_H
 
 ///////////////////////////////////////////////////////////
-//														 //
+//                                                       //												
+//                                                       //												
 //                                                       //
-//														 //
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
-#include "MLB_Interface.h"
+#include "fill_sinks.h"
 
 
 ///////////////////////////////////////////////////////////
-//														 //
+//                                                       //												
+//                                                       //												
 //                                                       //
-//														 //
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
-class CDiversity_Analysis : public CSG_Module_Grid
+class CFlow_Routing : public CSG_Module_Grid
 {
 public:
-	CDiversity_Analysis(void);
 
+	CFlow_Routing(void);
 
-protected:
+	virtual CSG_String	Get_MenuPath			(void)	{	return( _TL("A:Terrain Analysis|Hydrology|Flow Accumulation" ));	}
 
-	virtual int					On_Parameters_Enable	(CSG_Parameters *pParameters, CSG_Parameter *pParameter);
+	bool				Set_Flow				(CSG_Grid *pDEM, CSG_Grid *pFlow, int Preprocess = 0, double dzFill = 0.01);
 
-	virtual bool				On_Execute				(void);
 
+protected:
 
-private:
+	virtual int			On_Parameters_Enable	(CSG_Parameters *pParameters, CSG_Parameter *pParameter);
 
-	bool						m_bWeighted;
+	virtual bool		On_Execute				(void);
 
-	int							m_NB_Step;
 
-	CSG_Grid					*m_pClasses, *m_pDiversity, *m_pSize_Mean, *m_pSize_Skew, *m_pConnectivity;
+private:
 
-	CSG_Grid_Cell_Addressor		m_Search;
+	CSG_Grid			*m_pDEM, *m_pFlow;
 
 
-	bool						Get_Diversity			(int x, int y);
+	bool				Set_Flow				(int Preprocess, double dzFill);
+	void				Set_Flow				(int x, int y);
 
 };
 
 
 ///////////////////////////////////////////////////////////
-//														 //
+//                                                       //												
+//                                                       //												
 //                                                       //
-//														 //
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
-#endif // #ifndef HEADER_INCLUDED__diversity_analysis_H
+#endif // #ifndef HEADER_INCLUDED__flow_routing_H
diff --git a/src/modules/simulation/sim_qm_of_esp/hillslope_evolution_adi.cpp b/src/modules/simulation/sim_qm_of_esp/hillslope_evolution_adi.cpp
new file mode 100644
index 0000000..26e2a17
--- /dev/null
+++ b/src/modules/simulation/sim_qm_of_esp/hillslope_evolution_adi.cpp
@@ -0,0 +1,541 @@
+/**********************************************************
+ * Version $Id: hillslope_evolution_adi.cpp 911 2011-02-14 16:38:15Z reklov_w $
+ *********************************************************/
+
+///////////////////////////////////////////////////////////
+//                                                       //
+//                         SAGA                          //
+//                                                       //
+//      System for Automated Geoscientific Analyses      //
+//                                                       //
+//                    Module Library:                    //
+//                      qm_of_esp                        //
+//                                                       //
+//-------------------------------------------------------//
+//                                                       //
+//               hillslope_evolution_adi.cpp             //
+//                                                       //
+//                 Copyright (C) 2013 by                 //
+//                      Olaf Conrad                      //
+//                                                       //
+//-------------------------------------------------------//
+//                                                       //
+// This file is part of 'SAGA - System for Automated     //
+// Geoscientific Analyses'. SAGA 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; version 2 of the License.   //
+//                                                       //
+// SAGA 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,       //
+// write to the Free Software Foundation, Inc.,          //
+// 51 Franklin Street, 5th Floor, Boston, MA 02110-1301, //
+// USA.                                                  //
+//                                                       //
+//-------------------------------------------------------//
+//                                                       //
+//    e-mail:     oconrad at saga-gis.org                   //
+//                                                       //
+//    contact:    Olaf Conrad                            //
+//                Institute of Geography                 //
+//                University of Hamburg                  //
+//                Germany                                //
+//                                                       //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+
+
+///////////////////////////////////////////////////////////
+//														 //
+//														 //
+//														 //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+#include "hillslope_evolution_adi.h"
+
+
+///////////////////////////////////////////////////////////
+//														 //
+//														 //
+//														 //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+bool tridag(const CSG_Vector &a, const CSG_Vector &b, const CSG_Vector &c, const CSG_Vector &r, CSG_Vector &u)
+{
+	int			i, n = a.Get_N();
+	double		beta;
+	CSG_Vector	gamma(n);
+
+	if( n < 2 || n != b.Get_N() || n != c.Get_N() || n != r.Get_N() || b[0] == 0.0 )
+	{
+		return( false );
+	}
+
+	u.Create(n);
+
+	u[0]	= r[0] / (beta = b[0]);
+
+	for(i=1; i<n; i++)
+	{
+		gamma[i]	= c[i - 1] / beta;
+		beta		= b[i] - a[i] * gamma[i];
+
+		if( beta == 0.0 )
+		{
+			return( false );
+		}
+
+		u[i]	= (r[i] - a[i] * u[i - 1]) / beta;
+	}
+
+	for(i=n-2; i>=0; i--)
+	{
+		u[i]	-= gamma[i + 1] * u[i + 1];
+	}
+
+	return( true );
+}
+
+
+///////////////////////////////////////////////////////////
+//														 //
+//														 //
+//														 //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+CHillslope_Evolution_ADI::CHillslope_Evolution_ADI(void)
+{
+	CSG_Parameter	*pNode;
+
+	//-----------------------------------------------------
+	Set_Name	(_TL("Diffusive Hillslope Evolution (ADI)"));
+
+	Set_Author	("O.Conrad (c) 2013");
+
+	Set_Description	(_TW(
+		"Simulation of diffusive hillslope evolution using an Alternating-Direction-Implicit (ADI) method.\n"
+		"\nReferences:\n"
+		"Pelletier, J.D. (2008): Quantitative Modeling of Earth Surface Processes. Cambridge, 295p.\n"
+	));
+
+	//-----------------------------------------------------
+	Parameters.Add_Grid(
+		NULL	, "DEM"			, _TL("Elevation"),
+		_TL(""),
+		PARAMETER_INPUT
+	);
+
+	Parameters.Add_Grid(
+		NULL	, "CHANNELS"	, _TL("Channel Mask"),
+		_TL("use a zero value for hillslopes, any other value for channel cells."),
+		PARAMETER_INPUT_OPTIONAL
+	);
+
+	Parameters.Add_Grid(
+		NULL	, "MODEL"		, _TL("Modelled Elevation"),
+		_TL(""),
+		PARAMETER_OUTPUT
+	);
+
+	pNode	= Parameters.Add_Grid(
+		NULL	, "DIFF"		, _TL("Elevation Difference"),
+		_TL(""),
+		PARAMETER_OUTPUT_OPTIONAL
+	);
+
+	Parameters.Add_Value(
+		pNode	, "UPDATE"		, _TL("Update"),
+		_TL(""),
+		PARAMETER_TYPE_Bool, true
+	);
+
+	Parameters.Add_Value(
+		NULL	, "KAPPA"		, _TL("Diffusivity [m2 / kyr]"),
+		_TL(""),
+		PARAMETER_TYPE_Double, 10.0, 0.0, true
+	);
+
+	Parameters.Add_Value(
+		NULL	, "DURATION"	, _TL("Simulation Time [kyr]"),
+		_TL(""),
+		PARAMETER_TYPE_Double, 10000.0, 0.0, true
+	);
+
+	pNode	= Parameters.Add_Choice(
+		NULL	, "TIMESTEP"	, _TL("Time Step"),
+		_TL(""),
+		CSG_String::Format(SG_T("%s|%s|"),
+			_TL("user defined"),
+			_TL("automatically")
+		), 0
+	);
+
+	Parameters.Add_Value(
+		pNode	, "DTIME"		, _TL("Time Step [kyr]"),
+		_TL(""),
+		PARAMETER_TYPE_Double, 1000.0, 0.0, true
+	);
+}
+
+
+///////////////////////////////////////////////////////////
+//														 //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+int CHillslope_Evolution_ADI::On_Parameters_Enable(CSG_Parameters *pParameters, CSG_Parameter *pParameter)
+{
+	if( !SG_STR_CMP(pParameter->Get_Identifier(), "TIMESTEP") )
+	{
+		pParameters->Get_Parameter("DTIME")->Set_Enabled(pParameter->asInt() == 0);
+	}
+
+	if( !SG_STR_CMP(pParameter->Get_Identifier(), "DIFF") )
+	{
+		pParameters->Get_Parameter("UPDATE")->Set_Enabled(pParameter->asGrid() != NULL);
+	}
+
+	return( 1 );
+}
+
+
+///////////////////////////////////////////////////////////
+//														 //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+bool CHillslope_Evolution_ADI::On_Execute(void)
+{
+	//-----------------------------------------------------
+	CSG_Grid	DEM(*Get_System()), Channels(*Get_System(), SG_DATATYPE_Byte);
+
+	m_pDEM_Old	= &DEM;
+
+	m_pDEM		= Parameters("MODEL"   )->asGrid();
+	m_pChannels	= Parameters("CHANNELS")->asGrid();
+
+	m_pDEM->Assign(Parameters("DEM")->asGrid());
+
+	DataObject_Set_Colors(Parameters("DIFF")->asGrid(), 10, SG_COLORS_RED_GREY_BLUE, true);
+
+	//-----------------------------------------------------
+	double	k, dTime, nTime;
+
+	k		= Parameters("KAPPA"   )->asDouble();
+	nTime	= Parameters("DURATION")->asDouble();
+
+	if( Parameters("TIMESTEP")->asInt() == 0 )
+	{
+		dTime	= Parameters("DTIME")->asDouble();
+	}
+	else
+	{
+		dTime	= 0.5 * Get_Cellarea() / (2.0 * k);
+	}
+
+	if( dTime > nTime )
+	{
+		Message_Add(CSG_String::Format(SG_T("\n%s: %s [%f]"), _TL("Warning"), _TL("Time step exceeds duration"), dTime), false);
+
+		dTime	= nTime;
+	}
+
+	Message_Add(CSG_String::Format(SG_T("\n%s: %f"), _TL("Time Step"), dTime), false);
+	Message_Add(CSG_String::Format(SG_T("\n%s: %d"), _TL("Steps"), (int)(nTime / dTime)), false);
+
+	//-----------------------------------------------------
+	for(double iTime=dTime; iTime<=nTime && Set_Progress(iTime, nTime); iTime+=dTime)
+	{
+		Process_Set_Text(CSG_String::Format(SG_T("%s: %.2f [%.2f]"), _TL("Simulation Time"), iTime, nTime));
+
+		SG_UI_Progress_Lock(true);
+
+		Set_Diffusion(dTime * k / Get_Cellarea());
+
+		Set_Difference();
+
+		SG_UI_Progress_Lock(false);
+	}
+
+	//-----------------------------------------------------
+	return( true );
+}
+
+
+///////////////////////////////////////////////////////////
+//														 //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+void CHillslope_Evolution_ADI::Set_Difference(void)
+{
+	CSG_Grid	*pDiff	= Parameters("DIFF")->asGrid();
+
+	if( pDiff )
+	{
+		CSG_Grid	*pDEM	= Parameters("DEM")->asGrid();
+
+		#pragma omp parallel for
+		for(int i=0; i<Get_NCells(); i++)
+		{
+			if( m_pDEM->is_NoData(i) )
+			{
+				pDiff->Set_NoData(i);
+			}
+			else
+			{
+				pDiff->Set_Value(i, m_pDEM->asDouble(i) - pDEM->asDouble(i));
+			}
+		}
+
+		if( Parameters("UPDATE")->asBool() )
+		{
+			DataObject_Update(pDiff, SG_UI_DATAOBJECT_SHOW);
+		}
+	}
+}
+
+
+///////////////////////////////////////////////////////////
+//														 //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+inline bool CHillslope_Evolution_ADI::is_Channel(int x, int y)
+{
+	return( m_pChannels ? m_pChannels->asDouble(x, y) != 0.0 : false );
+}
+
+//---------------------------------------------------------
+inline double CHillslope_Evolution_ADI::Get_Elevation(int x, int y)
+{
+	if( x < 0 ) x = 0; else if( x >= Get_NX() ) x = Get_NX() - 1;
+	if( y < 0 ) y = 0; else if( y >= Get_NY() ) y = Get_NY() - 1;
+
+	return( m_pDEM->asDouble(x, y) );
+}
+
+//---------------------------------------------------------
+void CHillslope_Evolution_ADI::Set_Diffusion(double dFactor)
+{
+	int		x, y;
+
+	for(int i=0; i<5 && Process_Get_Okay(); i++)
+	{
+		m_pDEM_Old->Assign(m_pDEM);
+
+		#pragma omp parallel for private(x, y)
+		for(x=0; x<Get_NX(); x++)
+		{
+			CSG_Vector	a(Get_NY()), b(Get_NY()), c(Get_NY()), u(Get_NY()), r(Get_NY());
+
+			for(y=0; y<Get_NY(); y++)
+			{
+				if( y == 0 )
+				{
+					a[y]	= is_Channel(x, y) ? 0 : -dFactor;
+					b[y]	= 1;
+					c[y]	= 0;
+					r[y]	= m_pDEM_Old->asDouble(x, y);
+				}
+				else if( y == Get_NY() - 1 )
+				{
+					a[y]	= 0;
+					b[y]	= 1;
+					c[y]	= is_Channel(x, y) ? 0 : -dFactor;
+					r[y]	= m_pDEM_Old->asDouble(x, y);
+				}
+				else if( is_Channel(x, y) )
+				{
+					b[y]	= 1;
+					a[y]	= 0;
+					c[y]	= 0;
+					r[y]	= m_pDEM_Old->asDouble(x, y);
+				}
+				else // if( !is_Channel(x, y) )
+				{
+					a[y]	= -dFactor;
+					c[y]	= -dFactor;
+					b[y]	= 4 * dFactor + 1;
+					r[y]	= m_pDEM_Old->asDouble(x, y) + dFactor * (Get_Elevation(x - 1, y) + Get_Elevation(x + 1, y));
+				}
+			}
+
+			tridag(a, b, c, r, u);
+
+			for(y=0; y<Get_NY(); y++)
+			{
+				m_pDEM->Set_Value(x, y, u[y]);
+			}
+		}
+
+		//-------------------------------------------------
+		m_pDEM_Old->Assign(m_pDEM);
+
+		#pragma omp parallel for private(x, y)
+		for(y=0; y<Get_NY(); y++)
+		{
+			CSG_Vector	a(Get_NX()), b(Get_NX()), c(Get_NX()), u(Get_NX()), r(Get_NX());
+
+			for(x=0; x<Get_NX(); x++)
+			{
+				if( x == 0 )
+				{
+					a[x]	= is_Channel(x, y) ? 0 : -dFactor;
+					b[x]	= 1;
+					c[x]	= 0;
+					r[x]	= m_pDEM_Old->asDouble(x, y);
+				}
+				else if( x == Get_NX() - 1 )
+				{
+					a[x]	= 0;
+					b[x]	= 1;
+					c[x]	= is_Channel(x, y) ? 0 : -dFactor;
+					r[x]	= m_pDEM_Old->asDouble(x, y);
+				}
+				else if( is_Channel(x, y) )
+				{
+					a[x]	= 0;
+					b[x]	= 1;
+					c[x]	= 0;
+					r[x]	= m_pDEM_Old->asDouble(x, y);
+				}
+				else // if( !is_Channel(x, y) )
+				{
+					a[x]	= -dFactor;
+					c[x]	= -dFactor;
+					b[x]	= 4 * dFactor + 1;
+					r[x]	= m_pDEM_Old->asDouble(x, y) + dFactor * (Get_Elevation(x, y - 1) + Get_Elevation(x, y + 1));
+				}
+			}
+
+			tridag(a, b, c, r, u);
+
+			for(x=0; x<Get_NX(); x++)
+			{
+				m_pDEM->Set_Value(x, y, u[x]);
+			}
+		}
+	}
+}
+
+/*/---------------------------------------------------------
+void CHillslope_Evolution_ADI::Set_Diffusion(double dFactor)
+{
+	int		x, y;
+
+	for(int i=0; i<5 && Process_Get_Okay(); i++)
+	{
+		m_pDEM_Old->Assign(m_pDEM);
+
+		#pragma omp parallel for private(x, y)
+		for(x=0; x<Get_NX(); x++)
+		{
+			CSG_Vector	a(Get_NY()), b(Get_NY()), c(Get_NY()), u(Get_NY()), r(Get_NY());
+
+			for(y=0; y<Get_NY(); y++)
+			{
+				if( !is_Channel(x, y) )
+				{
+					a[y]	= -dFactor;
+					c[y]	= -dFactor;
+					b[y]	= 4 * dFactor + 1;
+					r[y]	= m_pDEM_Old->asDouble(x, y) + dFactor * (Get_Elevation(x - 1, y) + Get_Elevation(x + 1, y));
+				}
+				else
+				{
+					b[y]	= 1;
+					a[y]	= 0;
+					c[y]	= 0;
+					r[y]	= m_pDEM_Old->asDouble(x, y);
+				}
+
+				if( y == 0 )
+				{
+					b[y]	= 1;
+					c[y]	= 0;
+					r[y]	= m_pDEM_Old->asDouble(x, y);
+				}
+				else if( y == Get_NY() - 1 )
+				{
+					b[y]	= 1;
+					a[y]	= 0;
+					r[y]	= m_pDEM_Old->asDouble(x, y);
+				}
+			}
+
+			tridag(a, b, c, r, u);
+
+			for(y=0; y<Get_NY(); y++)
+			{
+				m_pDEM->Set_Value(x, y, u[y]);
+			}
+		}
+
+		//-------------------------------------------------
+		m_pDEM_Old->Assign(m_pDEM);
+
+		#pragma omp parallel for private(x, y)
+		for(y=0; y<Get_NY(); y++)
+		{
+			CSG_Vector	a(Get_NX()), b(Get_NX()), c(Get_NX()), u(Get_NX()), r(Get_NX());
+
+			for(x=0; x<Get_NX(); x++)
+			{
+				if( !is_Channel(x, y) )
+				{
+					a[x]	= -dFactor;
+					c[x]	= -dFactor;
+					b[x]	= 4 * dFactor + 1;
+					r[x]	= m_pDEM_Old->asDouble(x, y) + dFactor * (Get_Elevation(x, y - 1) + Get_Elevation(x, y + 1));
+				}
+				else
+				{
+					b[x]	= 1;
+					a[x]	= 0;
+					c[x]	= 0;
+					r[x]	= m_pDEM_Old->asDouble(x, y);
+				}
+
+				if( x == 0 )
+				{
+					b[x]	= 1;
+					c[x]	= 0;
+					r[x]	= m_pDEM_Old->asDouble(x, y);
+				}
+				else if( x == Get_NX() - 1 )
+				{
+					b[x]	= 1;
+					a[x]	= 0;
+					r[x]	= m_pDEM_Old->asDouble(x, y);
+				}
+			}
+
+			tridag(a, b, c, r, u);
+
+			for(x=0; x<Get_NX(); x++)
+			{
+				m_pDEM->Set_Value(x, y, u[x]);
+			}
+		}
+	}
+}/**/
+
+
+///////////////////////////////////////////////////////////
+//														 //
+//														 //
+//														 //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
diff --git a/src/modules/grid/grid_analysis/diversity_analysis.h b/src/modules/simulation/sim_qm_of_esp/hillslope_evolution_adi.h
similarity index 71%
copy from src/modules/grid/grid_analysis/diversity_analysis.h
copy to src/modules/simulation/sim_qm_of_esp/hillslope_evolution_adi.h
index c03ea9e..bb4957b 100644
--- a/src/modules/grid/grid_analysis/diversity_analysis.h
+++ b/src/modules/simulation/sim_qm_of_esp/hillslope_evolution_adi.h
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: diversity_analysis.h 2476 2015-04-22 18:41:38Z oconrad $
+ * Version $Id: hillslope_evolution_adi.h 911 2011-02-14 16:38:15Z reklov_w $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -9,13 +9,13 @@
 //      System for Automated Geoscientific Analyses      //
 //                                                       //
 //                    Module Library:                    //
-//                     grid_analysis                     //
+//                      qm_of_esp                        //
 //                                                       //
 //-------------------------------------------------------//
 //                                                       //
-//                 diversity_analysis.h                  //
+//                hillslope_evolution_adi.h              //
 //                                                       //
-//                 Copyright (C) 2015 by                 //
+//                 Copyright (C) 2013 by                 //
 //                      Olaf Conrad                      //
 //                                                       //
 //-------------------------------------------------------//
@@ -53,20 +53,19 @@
 
 
 ///////////////////////////////////////////////////////////
-//														 //
+//                                                       //												
+//                                                       //												
 //                                                       //
-//														 //
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
-#ifndef HEADER_INCLUDED__diversity_analysis_H
-#define HEADER_INCLUDED__diversity_analysis_H
-
+#ifndef HEADER_INCLUDED__hillslope_evolution_adi_H
+#define HEADER_INCLUDED__hillslope_evolution_adi_H
 
 ///////////////////////////////////////////////////////////
-//														 //
+//                                                       //												
+//                                                       //												
 //                                                       //
-//														 //
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
@@ -74,46 +73,48 @@
 
 
 ///////////////////////////////////////////////////////////
-//														 //
+//                                                       //												
+//                                                       //												
 //                                                       //
-//														 //
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
-class CDiversity_Analysis : public CSG_Module_Grid
+class CHillslope_Evolution_ADI : public CSG_Module_Grid
 {
 public:
-	CDiversity_Analysis(void);
+
+	CHillslope_Evolution_ADI(void);
+
+	virtual CSG_String	Get_MenuPath			(void)	{	return( _TL("A:Simulation|Hillslope Evolution" ));	}
 
 
 protected:
 
-	virtual int					On_Parameters_Enable	(CSG_Parameters *pParameters, CSG_Parameter *pParameter);
+	virtual int			On_Parameters_Enable	(CSG_Parameters *pParameters, CSG_Parameter *pParameter);
 
-	virtual bool				On_Execute				(void);
+	virtual bool		On_Execute				(void);
 
 
 private:
 
-	bool						m_bWeighted;
-
-	int							m_NB_Step;
+	CSG_Grid			*m_pDEM, *m_pDEM_Old, *m_pChannels;
 
-	CSG_Grid					*m_pClasses, *m_pDiversity, *m_pSize_Mean, *m_pSize_Skew, *m_pConnectivity;
 
-	CSG_Grid_Cell_Addressor		m_Search;
+	void				Set_Difference			(void);
 
+	void				Set_Diffusion			(double dFactor);
 
-	bool						Get_Diversity			(int x, int y);
+	bool				is_Channel				(int x, int y);
+	double				Get_Elevation			(int x, int y);
 
 };
 
 
 ///////////////////////////////////////////////////////////
-//														 //
+//                                                       //												
+//                                                       //												
 //                                                       //
-//														 //
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
-#endif // #ifndef HEADER_INCLUDED__diversity_analysis_H
+#endif // #ifndef HEADER_INCLUDED__hillslope_evolution_adi_H
diff --git a/src/modules/simulation/sim_qm_of_esp/hillslope_evolution_ftcs.cpp b/src/modules/simulation/sim_qm_of_esp/hillslope_evolution_ftcs.cpp
new file mode 100644
index 0000000..6b525d5
--- /dev/null
+++ b/src/modules/simulation/sim_qm_of_esp/hillslope_evolution_ftcs.cpp
@@ -0,0 +1,348 @@
+/**********************************************************
+ * Version $Id: hillslope_evolution_ftcs.cpp 911 2011-02-14 16:38:15Z reklov_w $
+ *********************************************************/
+
+///////////////////////////////////////////////////////////
+//                                                       //
+//                         SAGA                          //
+//                                                       //
+//      System for Automated Geoscientific Analyses      //
+//                                                       //
+//                    Module Library:                    //
+//                      qm_of_esp                        //
+//                                                       //
+//-------------------------------------------------------//
+//                                                       //
+//               hillslope_evolution_ftcs.cpp            //
+//                                                       //
+//                 Copyright (C) 2013 by                 //
+//                      Olaf Conrad                      //
+//                                                       //
+//-------------------------------------------------------//
+//                                                       //
+// This file is part of 'SAGA - System for Automated     //
+// Geoscientific Analyses'. SAGA 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; version 2 of the License.   //
+//                                                       //
+// SAGA 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,       //
+// write to the Free Software Foundation, Inc.,          //
+// 51 Franklin Street, 5th Floor, Boston, MA 02110-1301, //
+// USA.                                                  //
+//                                                       //
+//-------------------------------------------------------//
+//                                                       //
+//    e-mail:     oconrad at saga-gis.org                   //
+//                                                       //
+//    contact:    Olaf Conrad                            //
+//                Institute of Geography                 //
+//                University of Hamburg                  //
+//                Germany                                //
+//                                                       //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+
+
+///////////////////////////////////////////////////////////
+//														 //
+//														 //
+//														 //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+#include "hillslope_evolution_ftcs.h"
+
+
+///////////////////////////////////////////////////////////
+//														 //
+//														 //
+//														 //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+CHillslope_Evolution_FTCS::CHillslope_Evolution_FTCS(void)
+{
+	CSG_Parameter	*pNode;
+
+	//-----------------------------------------------------
+	Set_Name	(_TL("Diffusive Hillslope Evolution (FTCS)"));
+
+	Set_Author	("O.Conrad (c) 2013");
+
+	Set_Description	(_TW(
+		"Simulation of diffusive hillslope evolution using a Forward-Time-Centered-Space (FTCS) method.\n"
+		"\nReferences:\n"
+		"Pelletier, J.D. (2008): Quantitative Modeling of Earth Surface Processes. Cambridge, 295p.\n"
+	));
+
+	//-----------------------------------------------------
+	Parameters.Add_Grid(
+		NULL	, "DEM"			, _TL("Elevation"),
+		_TL(""),
+		PARAMETER_INPUT
+	);
+
+	Parameters.Add_Grid(
+		NULL	, "MODEL"		, _TL("Modelled Elevation"),
+		_TL(""),
+		PARAMETER_OUTPUT
+	);
+
+	pNode	= Parameters.Add_Grid(
+		NULL	, "DIFF"		, _TL("Elevation Difference"),
+		_TL(""),
+		PARAMETER_OUTPUT_OPTIONAL
+	);
+
+	Parameters.Add_Value(
+		pNode	, "UPDATE"		, _TL("Update"),
+		_TL(""),
+		PARAMETER_TYPE_Bool, true
+	);
+
+	Parameters.Add_Value(
+		NULL	, "KAPPA"		, _TL("Diffusivity [m2 / kyr]"),
+		_TL(""),
+		PARAMETER_TYPE_Double, 1.0, 0.0, true
+	);
+
+	Parameters.Add_Value(
+		NULL	, "DURATION"	, _TL("Simulation Time [kyr]"),
+		_TL(""),
+		PARAMETER_TYPE_Double, 100.0, 0.0, true
+	);
+
+	pNode	= Parameters.Add_Choice(
+		NULL	, "TIMESTEP"	, _TL("Time Step"),
+		_TL(""),
+		CSG_String::Format(SG_T("%s|%s|"),
+			_TL("user defined"),
+			_TL("automatically")
+		), 1
+	);
+
+	Parameters.Add_Value(
+		pNode	, "DTIME"		, _TL("Time Step [kyr]"),
+		_TL(""),
+		PARAMETER_TYPE_Double, 10.0, 0.0, true
+	);
+
+	Parameters.Add_Choice(
+		NULL	, "NEIGHBOURS"	, _TL("Neighbourhood"),
+		_TL(""),
+		CSG_String::Format(SG_T("%s|%s|"),
+			_TL("Neumann"),
+			_TL("Moore")
+		), 1
+	);
+}
+
+
+///////////////////////////////////////////////////////////
+//														 //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+int CHillslope_Evolution_FTCS::On_Parameters_Enable(CSG_Parameters *pParameters, CSG_Parameter *pParameter)
+{
+	if( !SG_STR_CMP(pParameter->Get_Identifier(), "TIMESTEP") )
+	{
+		pParameters->Get_Parameter("DTIME")->Set_Enabled(pParameter->asInt() == 0);
+	}
+
+	if( !SG_STR_CMP(pParameter->Get_Identifier(), "DIFF") )
+	{
+		pParameters->Get_Parameter("UPDATE")->Set_Enabled(pParameter->asGrid() != NULL);
+	}
+
+	return( 1 );
+}
+
+
+///////////////////////////////////////////////////////////
+//														 //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+bool CHillslope_Evolution_FTCS::On_Execute(void)
+{
+	//-----------------------------------------------------
+	CSG_Grid	DEM(*Get_System());
+
+	m_pDEM_Old	= &DEM;
+
+	m_pDEM		= Parameters("MODEL")->asGrid();
+
+	m_pDEM->Assign(Parameters("DEM")->asGrid());
+
+	DataObject_Set_Colors(Parameters("DIFF")->asGrid(), 10, SG_COLORS_RED_GREY_BLUE, true);
+
+	//-----------------------------------------------------
+	double	k, dTime, nTime;
+
+	k		= Parameters("KAPPA"   )->asDouble();
+	nTime	= Parameters("DURATION")->asDouble();
+
+	if( Parameters("TIMESTEP")->asInt() == 0 )
+	{
+		dTime	= Parameters("DTIME")->asDouble();
+	}
+	else
+	{
+		dTime	= 0.5 * Get_Cellarea() / (2.0 * k);
+
+		if( Parameters("NEIGHBOURS")->asInt() == 1 )
+		{
+			dTime	/= sqrt(2.0);
+		}
+	}
+
+	if( dTime > nTime )
+	{
+		Message_Add(CSG_String::Format(SG_T("\n%s: %s [%f]"), _TL("Warning"), _TL("Time step exceeds duration"), dTime), false);
+
+		dTime	= nTime;
+	}
+
+	Message_Add(CSG_String::Format(SG_T("\n%s: %f"), _TL("Time Step"), dTime), false);
+	Message_Add(CSG_String::Format(SG_T("\n%s: %d"), _TL("Steps"), (int)(nTime / dTime)), false);
+
+	//-----------------------------------------------------
+	for(double iTime=dTime; iTime<=nTime && Set_Progress(iTime, nTime); iTime+=dTime)
+	{
+		Process_Set_Text(CSG_String::Format(SG_T("%s: %.2f [%.2f]"), _TL("Simulation Time"), iTime, nTime));
+
+		SG_UI_Progress_Lock(true);
+
+		Set_Diffusion(dTime * k / Get_Cellarea());
+
+		Set_Difference();
+
+		SG_UI_Progress_Lock(false);
+	}
+
+	//-----------------------------------------------------
+	return( true );
+}
+
+
+///////////////////////////////////////////////////////////
+//														 //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+void CHillslope_Evolution_FTCS::Set_Difference(void)
+{
+	CSG_Grid	*pDiff	= Parameters("DIFF")->asGrid();
+
+	if( pDiff )
+	{
+		CSG_Grid	*pDEM	= Parameters("DEM")->asGrid();
+
+		#pragma omp parallel for
+		for(int i=0; i<Get_NCells(); i++)
+		{
+			if( pDEM->is_NoData(i) )
+			{
+				pDiff->Set_NoData(i);
+			}
+			else
+			{
+				pDiff->Set_Value(i, m_pDEM->asDouble(i) - pDEM->asDouble(i));
+			}
+		}
+
+		if( Parameters("UPDATE")->asBool() )
+		{
+			DataObject_Update(pDiff, SG_UI_DATAOBJECT_SHOW);
+		}
+	}
+}
+
+
+///////////////////////////////////////////////////////////
+//														 //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+void CHillslope_Evolution_FTCS::Set_Diffusion(double dFactor)
+{
+	int	iStep	= Parameters("NEIGHBOURS")->asInt() == 1 ? 1 : 2;
+
+	m_pDEM_Old->Assign(m_pDEM);
+
+	#pragma omp parallel for
+	for(int y=0; y<Get_NY(); y++)
+	{
+		for(int x=0; x<Get_NX(); x++)
+		{
+			if( !m_pDEM_Old->is_NoData(x, y) )
+			{
+				double	z	= m_pDEM_Old->asDouble(x, y);
+				double	dz	= 0.0;
+
+				for(int i=0; i<8; i+=iStep)
+				{
+					int	ix	= Get_xTo(i, x);
+					int	iy	= Get_yTo(i, y);
+
+					if( m_pDEM_Old->is_InGrid(ix, iy) )
+					{
+						dz	+= (m_pDEM_Old->asDouble(ix, iy) - z) / Get_UnitLength(i);
+					}
+				}
+
+				m_pDEM->Add_Value(x, y, dFactor * dz);
+			}
+		}
+	}
+}
+
+/*/---------------------------------------------------------
+void CHillslope_Evolution_FTCS::Set_Diffusion(double dFactor)
+{
+	m_pDEM_Old->Assign(m_pDEM);
+
+	#pragma omp parallel for
+	for(int y=0; y<Get_NY(); y++)
+	{
+		for(int x=0; x<Get_NX(); x++)
+		{
+			if( !m_pDEM_Old->is_NoData(x, y) )
+			{
+				double	z, dz;
+
+				z	= m_pDEM_Old->asDouble(x, y);
+				dz	= -4.0 * z;
+
+				for(int i=0; i<8; i+=2)
+				{
+					int	ix	= Get_xTo(i, x);
+					int	iy	= Get_yTo(i, y);
+
+					dz	+= m_pDEM_Old->is_InGrid(ix, iy) ? m_pDEM_Old->asDouble(ix, iy) : z;
+				}
+
+				m_pDEM->Add_Value(x, y, dFactor * dz);
+			}
+		}
+	}
+}/**/
+
+
+///////////////////////////////////////////////////////////
+//														 //
+//														 //
+//														 //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
diff --git a/src/modules/grid/grid_analysis/diversity_analysis.h b/src/modules/simulation/sim_qm_of_esp/hillslope_evolution_ftcs.h
similarity index 72%
copy from src/modules/grid/grid_analysis/diversity_analysis.h
copy to src/modules/simulation/sim_qm_of_esp/hillslope_evolution_ftcs.h
index c03ea9e..2f6ad1e 100644
--- a/src/modules/grid/grid_analysis/diversity_analysis.h
+++ b/src/modules/simulation/sim_qm_of_esp/hillslope_evolution_ftcs.h
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: diversity_analysis.h 2476 2015-04-22 18:41:38Z oconrad $
+ * Version $Id: hillslope_evolution_ftcs.h 911 2011-02-14 16:38:15Z reklov_w $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -9,13 +9,13 @@
 //      System for Automated Geoscientific Analyses      //
 //                                                       //
 //                    Module Library:                    //
-//                     grid_analysis                     //
+//                      qm_of_esp                        //
 //                                                       //
 //-------------------------------------------------------//
 //                                                       //
-//                 diversity_analysis.h                  //
+//               hillslope_evolution_ftcs.h              //
 //                                                       //
-//                 Copyright (C) 2015 by                 //
+//                 Copyright (C) 2013 by                 //
 //                      Olaf Conrad                      //
 //                                                       //
 //-------------------------------------------------------//
@@ -53,20 +53,19 @@
 
 
 ///////////////////////////////////////////////////////////
-//														 //
+//                                                       //												
+//                                                       //												
 //                                                       //
-//														 //
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
-#ifndef HEADER_INCLUDED__diversity_analysis_H
-#define HEADER_INCLUDED__diversity_analysis_H
-
+#ifndef HEADER_INCLUDED__hillslope_evolution_ftcs_H
+#define HEADER_INCLUDED__hillslope_evolution_ftcs_H
 
 ///////////////////////////////////////////////////////////
-//														 //
+//                                                       //												
+//                                                       //												
 //                                                       //
-//														 //
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
@@ -74,46 +73,45 @@
 
 
 ///////////////////////////////////////////////////////////
-//														 //
+//                                                       //												
+//                                                       //												
 //                                                       //
-//														 //
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
-class CDiversity_Analysis : public CSG_Module_Grid
+class CHillslope_Evolution_FTCS : public CSG_Module_Grid
 {
 public:
-	CDiversity_Analysis(void);
 
+	CHillslope_Evolution_FTCS(void);
 
-protected:
+	virtual CSG_String	Get_MenuPath			(void)	{	return( _TL("A:Simulation|Hillslope Evolution" ));	}
 
-	virtual int					On_Parameters_Enable	(CSG_Parameters *pParameters, CSG_Parameter *pParameter);
 
-	virtual bool				On_Execute				(void);
+protected:
 
+	virtual int			On_Parameters_Enable	(CSG_Parameters *pParameters, CSG_Parameter *pParameter);
 
-private:
+	virtual bool		On_Execute				(void);
 
-	bool						m_bWeighted;
 
-	int							m_NB_Step;
+private:
 
-	CSG_Grid					*m_pClasses, *m_pDiversity, *m_pSize_Mean, *m_pSize_Skew, *m_pConnectivity;
+	CSG_Grid			*m_pDEM, *m_pDEM_Old;
 
-	CSG_Grid_Cell_Addressor		m_Search;
 
+	void				Set_Difference			(void);
 
-	bool						Get_Diversity			(int x, int y);
+	void				Set_Diffusion			(double dFactor);
 
 };
 
 
 ///////////////////////////////////////////////////////////
-//														 //
+//                                                       //												
+//                                                       //												
 //                                                       //
-//														 //
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
-#endif // #ifndef HEADER_INCLUDED__diversity_analysis_H
+#endif // #ifndef HEADER_INCLUDED__hillslope_evolution_ftcs_H
diff --git a/src/modules/simulation/sim_qm_of_esp/successive_flow_routing.cpp b/src/modules/simulation/sim_qm_of_esp/successive_flow_routing.cpp
new file mode 100644
index 0000000..3eff75a
--- /dev/null
+++ b/src/modules/simulation/sim_qm_of_esp/successive_flow_routing.cpp
@@ -0,0 +1,313 @@
+/**********************************************************
+ * Version $Id: successive_flow_routing.cpp 911 2011-02-14 16:38:15Z reklov_w $
+ *********************************************************/
+
+///////////////////////////////////////////////////////////
+//                                                       //
+//                         SAGA                          //
+//                                                       //
+//      System for Automated Geoscientific Analyses      //
+//                                                       //
+//                    Module Library:                    //
+//                      qm_of_esp                        //
+//                                                       //
+//-------------------------------------------------------//
+//                                                       //
+//               successive_flow_routing.cpp             //
+//                                                       //
+//                 Copyright (C) 2013 by                 //
+//                      Olaf Conrad                      //
+//                                                       //
+//-------------------------------------------------------//
+//                                                       //
+// This file is part of 'SAGA - System for Automated     //
+// Geoscientific Analyses'. SAGA 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; version 2 of the License.   //
+//                                                       //
+// SAGA 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,       //
+// write to the Free Software Foundation, Inc.,          //
+// 51 Franklin Street, 5th Floor, Boston, MA 02110-1301, //
+// USA.                                                  //
+//                                                       //
+//-------------------------------------------------------//
+//                                                       //
+//    e-mail:     oconrad at saga-gis.org                   //
+//                                                       //
+//    contact:    Olaf Conrad                            //
+//                Institute of Geography                 //
+//                University of Hamburg                  //
+//                Germany                                //
+//                                                       //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+
+
+///////////////////////////////////////////////////////////
+//														 //
+//														 //
+//														 //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+#include "successive_flow_routing.h"
+
+
+///////////////////////////////////////////////////////////
+//														 //
+//														 //
+//														 //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+CSuccessive_Flow_Routing::CSuccessive_Flow_Routing(void)
+{
+	//-----------------------------------------------------
+	Set_Name	(_TL("Successive Flow Routing"));
+
+	Set_Author	("O.Conrad (c) 2013");
+
+	Set_Description	(_TW(
+		"Calculation of flow accumulation, aka upslope contributing area, with the "
+		"multiple flow direction method after Freeman (1991).\n"
+		"\nReferences:\n"
+		"Freeman, G.T. (1991): Calculating catchment area with divergent flow based on a rectangular grid. "
+		"Computers & Geosciences, 17, pp.413-422.\n"
+		"Pelletier, J.D. (2008): Quantitative Modeling of Earth Surface Processes. Cambridge, 295p.\n"
+	));
+
+	//-----------------------------------------------------
+	Parameters.Add_Grid(
+		NULL	, "DEM"			, _TL("DEM"),
+		_TL(""),
+		PARAMETER_INPUT
+	);
+
+	Parameters.Add_Grid(
+		NULL	, "FLOW"		, _TL("Flow"),
+		_TL(""),
+		PARAMETER_OUTPUT
+	);
+
+	Parameters.Add_Value(
+		NULL	, "ITERATIONS"	, _TL("Iterations"),
+		_TL(""),
+		PARAMETER_TYPE_Int, 100, 1, true
+	);
+
+	Parameters.Add_Value(
+		NULL	, "RUNOFF"		, _TL("Runoff"),
+		_TL(""),
+		PARAMETER_TYPE_Double, 1.0
+	);
+
+	Parameters.Add_Value(
+		NULL	, "MANNING"		, _TL("Manning's Roughness"),
+		_TL(""),
+		PARAMETER_TYPE_Double, 0.2
+	);
+}
+
+
+///////////////////////////////////////////////////////////
+//														 //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+bool CSuccessive_Flow_Routing::On_Execute(void)
+{
+	int			x, y, nIterations;
+	double		Runoff;
+	CSG_Grid	*pDEM, DEM, Slope;
+
+	nIterations	= Parameters("ITERATIONS")->asInt();
+	Runoff		= Parameters("RUNOFF"    )->asDouble();
+	m_Manning	= Parameters("MANNING"   )->asDouble();
+
+	pDEM		= Parameters("DEM"  )->asGrid();
+	m_pFlow		= Parameters("FLOW" )->asGrid();
+
+	m_pDEM		= &DEM;
+	m_pSlope	= &Slope;
+
+	DEM			.Create(*pDEM);
+	Slope		.Create(*Get_System());
+
+	CSG_Colors	Colors(11, SG_COLORS_WHITE_BLUE);
+	Colors[0]	= SG_GET_RGB(255, 255, 200);
+	DataObject_Set_Colors(m_pFlow, Colors);
+	DataObject_Update(m_pFlow, SG_UI_DATAOBJECT_SHOW);
+
+	Fill_Sinks();
+
+	#pragma omp parallel for private(x, y)
+	for(y=0; y<Get_NY(); y++)
+	{
+		for(x=0; x<Get_NX(); x++)
+		{
+			Set_Channel_Slope(x, y);
+		}
+	}
+
+	//-----------------------------------------------------
+	for(int Iteration=1; Iteration<=nIterations && Process_Get_Okay(); Iteration++)
+	{
+		Process_Set_Text(CSG_String::Format(SG_T("%s: %d [%d]"), _TL("Iteration"), Iteration, nIterations));
+
+		SG_UI_Progress_Lock(true);
+
+		Fill_Sinks();
+
+		#pragma omp parallel for private(x, y)
+		for(y=0; y<Get_NY(); y++)
+		{
+			for(x=0; x<Get_NX(); x++)
+			{
+				m_pFlow->Set_Value(x, y, pow(Runoff, 1.66667) * m_pSlope->asDouble(x, y));
+			}
+		}
+
+		for(int i=0; i<Get_NCells() && Process_Get_Okay(); i++)
+		{
+			if( m_pDEM->Get_Sorted(i, x, y) )
+			{
+				Set_Flow(x, y);
+			}
+		}
+
+		#pragma omp parallel for private(x, y)
+		for(y=0; y<Get_NY(); y++)
+		{
+			for(x=0; x<Get_NX(); x++)
+			{
+				if( m_pDEM->is_NoData(x, y) )
+				{
+					m_pFlow->Set_NoData(x, y);
+				}
+				else
+				{
+					double	Depth	= pow(m_pFlow->asDouble(x, y) / m_pSlope->asDouble(x, y), 0.6);
+
+					if( m_pDEM->asDouble(x, y) < pDEM->asDouble(x, y) + Depth )
+					{
+						m_pDEM->Set_Value(x, y, pDEM->asDouble(x, y) + Depth / nIterations);
+					}
+
+					m_pFlow->Set_Value(x, y, m_pDEM->asDouble(x, y) - pDEM->asDouble(x, y));
+				}
+			}
+		}
+
+		DataObject_Update(m_pFlow);
+
+		SG_UI_Progress_Lock(false);
+	}
+
+	//-----------------------------------------------------
+	return( true );
+}
+
+
+///////////////////////////////////////////////////////////
+//														 //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+#define RUN_MODULE(LIBRARY, MODULE, CONDITION)	{\
+	bool	bResult;\
+	SG_RUN_MODULE(bResult, LIBRARY, MODULE, CONDITION)\
+}
+
+#define SET_PARAMETER(IDENTIFIER, VALUE)	pModule->Get_Parameters()->Set_Parameter(SG_T(IDENTIFIER), VALUE)
+
+void CSuccessive_Flow_Routing::Fill_Sinks(void)
+{
+	RUN_MODULE("ta_preprocessor", 2,	// CPit_Eliminator
+			SET_PARAMETER("DEM"	, m_pDEM)
+	)
+}
+
+
+///////////////////////////////////////////////////////////
+//														 //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+void CSuccessive_Flow_Routing::Set_Flow(int x, int y)
+{
+	if( !m_pDEM->is_NoData(x, y) )
+	{
+		int		i;
+		double	z, dz[8], dzSum;
+
+		for(i=0, dzSum=0.0, z=m_pDEM->asDouble(x, y); i<8; i++)
+		{
+			int	ix	= Get_xTo(i, x);
+			int	iy	= Get_yTo(i, y);
+
+			if( m_pDEM->is_InGrid(ix, iy) && (dz[i] = z - m_pDEM->asDouble(ix, iy)) > 0.0 )
+			{
+				dzSum	+= (dz[i] = pow(dz[i] / Get_Length(i), 1.1));
+			}
+			else
+			{
+				dz[i]	= 0.0;
+			}
+		}
+
+		if( dzSum > 0.0 )
+		{
+			for(i=0, z=m_pFlow->asDouble(x, y)/dzSum; i<8; i++)
+			{
+				if( dz[i] > 0.0 )
+				{
+					m_pFlow->Add_Value(Get_xTo(i, x), Get_yTo(i, y), z * dz[i]);
+				}
+			}
+		}
+	}
+}
+
+//---------------------------------------------------------
+void CSuccessive_Flow_Routing::Set_Channel_Slope(int x, int y)
+{
+	if( m_pDEM->is_NoData(x, y) )
+	{
+		m_pSlope->Set_NoData(x, y);
+	}
+	else
+	{
+		int		i;
+		double	z, dz, Slope;
+
+		for(i=0, Slope=0.0, z=m_pDEM->asDouble(x, y); i<8; i++)
+		{
+			int	ix	= Get_xTo(i, x);
+			int	iy	= Get_yTo(i, y);
+
+			if( m_pDEM->is_InGrid(ix, iy) && (dz = (z - m_pDEM->asDouble(ix, iy)) / Get_Length(i)) > Slope )
+			{
+				Slope	= dz;
+			}
+		}
+
+		m_pSlope->Set_Value(x, y, sqrt(Slope > 0.01 ? Slope : 0.01) * Get_Cellsize() / m_Manning);
+	}
+}
+
+///////////////////////////////////////////////////////////
+//														 //
+//														 //
+//														 //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
diff --git a/src/modules/grid/grid_analysis/diversity_analysis.h b/src/modules/simulation/sim_qm_of_esp/successive_flow_routing.h
similarity index 72%
copy from src/modules/grid/grid_analysis/diversity_analysis.h
copy to src/modules/simulation/sim_qm_of_esp/successive_flow_routing.h
index c03ea9e..c681d17 100644
--- a/src/modules/grid/grid_analysis/diversity_analysis.h
+++ b/src/modules/simulation/sim_qm_of_esp/successive_flow_routing.h
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: diversity_analysis.h 2476 2015-04-22 18:41:38Z oconrad $
+ * Version $Id: successive_flow_routing.h 911 2011-02-14 16:38:15Z reklov_w $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -9,13 +9,13 @@
 //      System for Automated Geoscientific Analyses      //
 //                                                       //
 //                    Module Library:                    //
-//                     grid_analysis                     //
+//                      qm_of_esp                        //
 //                                                       //
 //-------------------------------------------------------//
 //                                                       //
-//                 diversity_analysis.h                  //
+//                successive_flow_routing.h              //
 //                                                       //
-//                 Copyright (C) 2015 by                 //
+//                 Copyright (C) 2013 by                 //
 //                      Olaf Conrad                      //
 //                                                       //
 //-------------------------------------------------------//
@@ -53,67 +53,66 @@
 
 
 ///////////////////////////////////////////////////////////
-//														 //
+//                                                       //												
+//                                                       //												
 //                                                       //
-//														 //
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
-#ifndef HEADER_INCLUDED__diversity_analysis_H
-#define HEADER_INCLUDED__diversity_analysis_H
-
+#ifndef HEADER_INCLUDED__successive_flow_routing_H
+#define HEADER_INCLUDED__successive_flow_routing_H
 
 ///////////////////////////////////////////////////////////
-//														 //
+//                                                       //												
+//                                                       //												
 //                                                       //
-//														 //
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
-#include "MLB_Interface.h"
+#include "flow_routing.h"
 
 
 ///////////////////////////////////////////////////////////
-//														 //
+//                                                       //												
+//                                                       //												
 //                                                       //
-//														 //
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
-class CDiversity_Analysis : public CSG_Module_Grid
+class CSuccessive_Flow_Routing : public CSG_Module_Grid
 {
 public:
-	CDiversity_Analysis(void);
 
+	CSuccessive_Flow_Routing(void);
 
-protected:
+	virtual CSG_String	Get_MenuPath			(void)	{	return( _TL("A:Simulation|Hydrology" ));	}
 
-	virtual int					On_Parameters_Enable	(CSG_Parameters *pParameters, CSG_Parameter *pParameter);
 
-	virtual bool				On_Execute				(void);
+protected:
 
+	virtual bool		On_Execute				(void);
 
-private:
 
-	bool						m_bWeighted;
+private:
 
-	int							m_NB_Step;
+	double				m_Manning;
 
-	CSG_Grid					*m_pClasses, *m_pDiversity, *m_pSize_Mean, *m_pSize_Skew, *m_pConnectivity;
+	CSG_Grid			*m_pDEM, *m_pFlow, *m_pSlope;
 
-	CSG_Grid_Cell_Addressor		m_Search;
 
+	void				Fill_Sinks				(void);
 
-	bool						Get_Diversity			(int x, int y);
+	void				Set_Flow				(int x, int y);
+	void				Set_Channel_Slope		(int x, int y);
 
 };
 
 
 ///////////////////////////////////////////////////////////
-//														 //
+//                                                       //												
+//                                                       //												
 //                                                       //
-//														 //
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
-#endif // #ifndef HEADER_INCLUDED__diversity_analysis_H
+#endif // #ifndef HEADER_INCLUDED__successive_flow_routing_H
diff --git a/src/modules/statistics/statistics_grid/GSGrid_Residuals.cpp b/src/modules/statistics/statistics_grid/GSGrid_Residuals.cpp
index dcccef0..8fba55f 100644
--- a/src/modules/statistics/statistics_grid/GSGrid_Residuals.cpp
+++ b/src/modules/statistics/statistics_grid/GSGrid_Residuals.cpp
@@ -104,6 +104,13 @@ CGSGrid_Residuals::CGSGrid_Residuals(void)
 	Parameters.Add_Grid(	NULL, "DEVMEAN"	, _TL("Deviation from Mean Value")	, _TL(""), PARAMETER_OUTPUT);
 	Parameters.Add_Grid(	NULL, "PERCENT"	, _TL("Percentile")					, _TL(""), PARAMETER_OUTPUT);
 
+	Parameters.Add_Choice(	NULL, "MODE"	, _TL("Search Mode")				, _TL(""),
+		CSG_String::Format(SG_T("%s|%s|"),
+			_TL("Square"),
+			_TL("Circle")
+		), 1
+	);
+
 	Parameters.Add_Value(	NULL, "RADIUS"	, _TL("Radius (Cells)")				, _TL(""), PARAMETER_TYPE_Int, 7, 1, true);
 
 	Parameters.Add_Value(	NULL, "BCENTER"	, _TL("Include Center Cell")		, _TL(""), PARAMETER_TYPE_Bool, true);
@@ -144,9 +151,11 @@ bool CGSGrid_Residuals::On_Execute(void)
 	DataObject_Set_Colors(m_pPercent, 100, SG_COLORS_RED_GREY_BLUE, true);
 
 	//-----------------------------------------------------
+	bool	bSquare = Parameters("MODE")->asBool() ? false : true;
+
 	m_Cells.Get_Weighting().Set_Parameters(Parameters("WEIGHTING")->asParameters());
 
-	if( !m_Cells.Set_Radius(Parameters("RADIUS")->asInt()) )
+	if( !m_Cells.Set_Radius(Parameters("RADIUS")->asInt(), bSquare) )
 	{
 		return( false );
 	}
diff --git a/src/modules/table/table_calculus/table_field_statistics.cpp b/src/modules/table/table_calculus/table_field_statistics.cpp
index 1c44e23..ac16ccc 100644
--- a/src/modules/table/table_calculus/table_field_statistics.cpp
+++ b/src/modules/table/table_calculus/table_field_statistics.cpp
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: table_field_statistics.cpp 2345 2014-11-27 11:27:59Z reklov_w $
+ * Version $Id: table_field_statistics.cpp 2704 2015-11-26 14:46:25Z reklov_w $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -149,23 +149,23 @@ bool CTable_Field_Statistics::On_Execute(void)
 	//-----------------------------------------------------
 	for(int iFeature=0; iFeature<nFeatures; iFeature++)
 	{
-		if( SG_Data_Type_is_Numeric(pTab_in->Get_Field_Type(iFeature)) )
+		if( SG_Data_Type_is_Numeric(pTab_in->Get_Field_Type(Features[iFeature])) )
 		{
 			CSG_Table_Record *pRecord = pTab_out->Add_Record();
 
-			pRecord->Set_Value(0, pTab_in->Get_Field_Name(iFeature));
-			pRecord->Set_Value(1, pTab_in->Get_N(iFeature));
-			pRecord->Set_Value(2, pTab_in->Get_Minimum(iFeature));
-			pRecord->Set_Value(3, pTab_in->Get_Maximum(iFeature));
-			pRecord->Set_Value(4, pTab_in->Get_Range(iFeature));
-			pRecord->Set_Value(5, pTab_in->Get_Sum(iFeature));
-			pRecord->Set_Value(6, pTab_in->Get_Mean(iFeature));
-			pRecord->Set_Value(7, pTab_in->Get_Variance(iFeature));
-			pRecord->Set_Value(8, pTab_in->Get_StdDev(iFeature));
+			pRecord->Set_Value(0, pTab_in->Get_Field_Name(Features[iFeature]));
+			pRecord->Set_Value(1, pTab_in->Get_N(Features[iFeature]));
+			pRecord->Set_Value(2, pTab_in->Get_Minimum(Features[iFeature]));
+			pRecord->Set_Value(3, pTab_in->Get_Maximum(Features[iFeature]));
+			pRecord->Set_Value(4, pTab_in->Get_Range(Features[iFeature]));
+			pRecord->Set_Value(5, pTab_in->Get_Sum(Features[iFeature]));
+			pRecord->Set_Value(6, pTab_in->Get_Mean(Features[iFeature]));
+			pRecord->Set_Value(7, pTab_in->Get_Variance(Features[iFeature]));
+			pRecord->Set_Value(8, pTab_in->Get_StdDev(Features[iFeature]));
 		}
 		else
 		{
-			SG_UI_Msg_Add(CSG_String::Format(_TL("WARNING: skipping non-numeric field '%s'!"), pTab_in->Get_Field_Name(iFeature)), true);
+			SG_UI_Msg_Add(CSG_String::Format(_TL("WARNING: skipping non-numeric field '%s'!"), pTab_in->Get_Field_Name(Features[iFeature])), true);
 		}
 	}
 
diff --git a/src/saga_core/saga_api/api_callback.cpp b/src/saga_core/saga_api/api_callback.cpp
index 45b99bd..961b608 100644
--- a/src/saga_core/saga_api/api_callback.cpp
+++ b/src/saga_core/saga_api/api_callback.cpp
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: api_callback.cpp 2640 2015-10-07 17:29:38Z oconrad $
+ * Version $Id: api_callback.cpp 2715 2015-12-04 11:54:03Z oconrad $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -137,7 +137,7 @@ bool		SG_UI_Process_Get_Okay(bool bBlink)
 {
 	if( gSG_UI_Callback )
 	{
-		CSG_UI_Parameter	p1(gSG_UI_Progress_Lock && bBlink), p2;
+		CSG_UI_Parameter	p1(gSG_UI_Progress_Lock == 0 && bBlink), p2;
 
 		return( gSG_UI_Callback(CALLBACK_PROCESS_GET_OKAY, p1, p2) != 0 );
 	}
diff --git a/src/saga_core/saga_api/api_core.h b/src/saga_core/saga_api/api_core.h
index 4d83058..661846c 100644
--- a/src/saga_core/saga_api/api_core.h
+++ b/src/saga_core/saga_api/api_core.h
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: api_core.h 2640 2015-10-07 17:29:38Z oconrad $
+ * Version $Id: api_core.h 2710 2015-12-02 12:33:39Z oconrad $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -963,6 +963,8 @@ SAGA_API_DLL_EXPORT bool			SG_Dir_Exists				(const SG_Char *Directory);
 SAGA_API_DLL_EXPORT bool			SG_Dir_Create				(const SG_Char *Directory);
 SAGA_API_DLL_EXPORT CSG_String		SG_Dir_Get_Current			(void);
 SAGA_API_DLL_EXPORT CSG_String		SG_Dir_Get_Temp				(void);
+SAGA_API_DLL_EXPORT bool			SG_Dir_List_Subdirectories	(CSG_Strings &List, const CSG_String &Directory);
+SAGA_API_DLL_EXPORT bool			SG_Dir_List_Files			(CSG_Strings &List, const CSG_String &Directory, const SG_Char *Extension = NULL);
 
 SAGA_API_DLL_EXPORT bool			SG_File_Exists				(const SG_Char *FileName);
 SAGA_API_DLL_EXPORT bool			SG_File_Delete				(const SG_Char *FileName);
diff --git a/src/saga_core/saga_api/api_file.cpp b/src/saga_core/saga_api/api_file.cpp
index 2d71599..04e4749 100644
--- a/src/saga_core/saga_api/api_file.cpp
+++ b/src/saga_core/saga_api/api_file.cpp
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: api_file.cpp 2497 2015-06-02 14:30:08Z oconrad $
+ * Version $Id: api_file.cpp 2711 2015-12-02 16:12:16Z oconrad $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -65,6 +65,7 @@
 //---------------------------------------------------------
 #include <wx/utils.h>
 #include <wx/filename.h>
+#include <wx/dir.h>
 
 #include "api_core.h"
 
@@ -477,16 +478,69 @@ bool			SG_Dir_Create(const SG_Char *Directory)
 CSG_String		SG_Dir_Get_Current(void)
 {
 	wxString cwd = wxFileName::GetCwd();
+
 	return( CSG_String(&cwd) );
 }
 
 //---------------------------------------------------------
 CSG_String		SG_Dir_Get_Temp(void)
 {
-        wxString fname = wxFileName::GetTempDir();
+	wxString fname = wxFileName::GetTempDir();
+
 	return( CSG_String(&fname) );
 }
 
+//---------------------------------------------------------
+bool			SG_Dir_List_Subdirectories	(CSG_Strings &List, const CSG_String &Directory)
+{
+	List.Clear();
+
+	wxDir	Dir;
+
+	if( Dir.Open(Directory.c_str()) )
+	{
+		wxString	FileName;
+
+		if( Dir.GetFirst(&FileName, wxEmptyString, wxDIR_DIRS) )
+		{
+			do
+			{
+				List	+= SG_File_Make_Path(Directory, FileName);
+			}
+			while( Dir.GetNext(&FileName) );
+		}
+	}
+
+	return( List.Get_Count() > 0 );
+}
+
+//---------------------------------------------------------
+bool			SG_Dir_List_Files			(CSG_Strings &List, const CSG_String &Directory, const SG_Char *Extension)
+{
+	List.Clear();
+
+	wxDir	Dir;
+
+	if( Dir.Open(Directory.c_str()) )
+	{
+		wxString	FileName;
+
+		if( Dir.GetFirst(&FileName, wxEmptyString, wxDIR_FILES) )
+		{
+			do
+			{
+				if( !Extension || !*Extension || SG_File_Cmp_Extension(FileName, Extension) )
+				{
+					List	+= SG_File_Make_Path(Directory, FileName);
+				}
+			}
+			while( Dir.GetNext(&FileName) );
+		}
+	}
+
+	return( List.Get_Count() > 0 );
+}
+
 
 ///////////////////////////////////////////////////////////
 //														 //
diff --git a/src/saga_core/saga_api/data_manager.cpp b/src/saga_core/saga_api/data_manager.cpp
index d4c5a52..03ef02c 100644
--- a/src/saga_core/saga_api/data_manager.cpp
+++ b/src/saga_core/saga_api/data_manager.cpp
@@ -521,8 +521,18 @@ bool CSG_Data_Manager::_Add_External(const CSG_String &File)
 	}
 
 	//-----------------------------------------------------
+	// LAS Import
 
+	if( !bResult && SG_File_Cmp_Extension(File, SG_T("las"))
+	&&  (pImport = SG_Get_Module_Library_Manager().Get_Module("io_shapes_las", 1)) != NULL
+	&&   pImport->Set_Parameter("FILES", File, PARAMETER_TYPE_FilePath) )
+	{
+		pImport->Set_Manager(this);
+		bResult	= pImport->Execute();
+		pImport->Set_Manager(&g_Data_Manager);
+	}
 
+	//-----------------------------------------------------
 	return( bResult );
 }
 
diff --git a/src/saga_core/saga_api/grid_io.cpp b/src/saga_core/saga_api/grid_io.cpp
index 0197346..39b89b3 100644
--- a/src/saga_core/saga_api/grid_io.cpp
+++ b/src/saga_core/saga_api/grid_io.cpp
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: grid_io.cpp 2630 2015-10-01 10:01:07Z oconrad $
+ * Version $Id: grid_io.cpp 2728 2015-12-14 08:52:14Z oconrad $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -1050,9 +1050,9 @@ bool CSG_Grid_File_Info::Save(const CSG_String &File_Name, int xStart, int yStar
 		Stream.Printf("%s\t= %s\n"   , gSG_Grid_File_Key_Names[GRID_FILE_KEY_DATAFORMAT     ], bBinary ? gSG_Data_Type_Identifier[m_Type] : SG_T("ASCII") );
 		Stream.Printf("%s\t= %d\n"   , gSG_Grid_File_Key_Names[GRID_FILE_KEY_DATAFILE_OFFSET], 0                       );
 #ifdef WORDS_BIGENDIAN
-		Stream.Printf("%s\t= %s\n"   , gSG_Grid_File_Key_Names[GRID_FILE_KEY_BYTEORDER_BIG  ], true                    );
+		Stream.Printf("%s\t= %s\n"   , gSG_Grid_File_Key_Names[GRID_FILE_KEY_BYTEORDER_BIG  ], GRID_FILE_KEY_TRUE      );
 #else
-		Stream.Printf("%s\t= %s\n"   , gSG_Grid_File_Key_Names[GRID_FILE_KEY_BYTEORDER_BIG  ], false                   );
+		Stream.Printf("%s\t= %s\n"   , gSG_Grid_File_Key_Names[GRID_FILE_KEY_BYTEORDER_BIG  ], GRID_FILE_KEY_FALSE     );
 #endif
 		Stream.Printf("%s\t= %s\n"   , gSG_Grid_File_Key_Names[GRID_FILE_KEY_TOPTOBOTTOM    ], GRID_FILE_KEY_FALSE     );
 		Stream.Printf("%s\t= %.10f\n", gSG_Grid_File_Key_Names[GRID_FILE_KEY_POSITION_XMIN  ], xStart * m_System.Get_Cellsize() + m_System.Get_XMin() );
diff --git a/src/saga_core/saga_api/grid_operation.cpp b/src/saga_core/saga_api/grid_operation.cpp
index bf6fc96..a63b4bb 100644
--- a/src/saga_core/saga_api/grid_operation.cpp
+++ b/src/saga_core/saga_api/grid_operation.cpp
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: grid_operation.cpp 2632 2015-10-01 14:12:13Z oconrad $
+ * Version $Id: grid_operation.cpp 2708 2015-12-01 16:16:14Z oconrad $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -87,16 +87,23 @@ bool CSG_Grid::Assign(double Value)
 	{
 		if( Value == 0.0 && m_Memory_Type == GRID_MEMORY_Normal )
 		{
-			for(int n=0, m=_Get_nLineBytes(); n<Get_NY(); n++)
+			int	n	= _Get_nLineBytes();
+
+			#pragma omp parallel for
+			for(int y=0; y<Get_NY(); y++)
 			{
-				memset(m_Values[n], 0, m);
+				memset(m_Values[y], 0, n);
 			}
 		}
 		else
 		{
-			for(sLong n=0; n<Get_NCells(); n++)
+			#pragma omp parallel for
+			for(int y=0; y<Get_NY(); y++)
 			{
-				Set_Value(n, Value);
+				for(int x=0; x<Get_NX(); x++)
+				{
+					Set_Value(x, y, Value);
+				}
 			}
 		}
 
diff --git a/src/saga_core/saga_api/grid_system.cpp b/src/saga_core/saga_api/grid_system.cpp
index b442794..f169c1d 100644
--- a/src/saga_core/saga_api/grid_system.cpp
+++ b/src/saga_core/saga_api/grid_system.cpp
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: grid_system.cpp 2494 2015-05-21 14:09:38Z oconrad $
+ * Version $Id: grid_system.cpp 2677 2015-11-05 08:59:28Z oconrad $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -75,6 +75,22 @@
 #define GRID_SYSTEM_PRECISION 10000000000	// 10 decimal digits, precision used for storing cellsize and extent
 
 //---------------------------------------------------------
+double SG_Get_Limited_Precision(double Value, double Precision)
+{
+	if( Precision > 0.0 )
+	{
+		return( floor(Value * Precision + 0.5) / Precision );
+	}
+
+	return( Value );
+}
+
+
+///////////////////////////////////////////////////////////
+//														 //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
 CSG_Grid_System::CSG_Grid_System(void)
 {
 	Assign(0.0, 0.0, 0.0, 0, 0);
@@ -221,9 +237,9 @@ bool CSG_Grid_System::Assign(double Cellsize, double xMin, double yMin, int NX,
 {
 	if( Cellsize > 0.0 && NX > 0 && NY > 0 )
 	{
-		Cellsize	= (sLong)(Cellsize * GRID_SYSTEM_PRECISION) / (double)GRID_SYSTEM_PRECISION;
-		xMin		= (sLong)(xMin     * GRID_SYSTEM_PRECISION) / (double)GRID_SYSTEM_PRECISION;
-		yMin		= (sLong)(yMin     * GRID_SYSTEM_PRECISION) / (double)GRID_SYSTEM_PRECISION;
+		Cellsize	= SG_Get_Limited_Precision(Cellsize, GRID_SYSTEM_PRECISION);
+		xMin		= SG_Get_Limited_Precision(xMin    , GRID_SYSTEM_PRECISION);
+		yMin		= SG_Get_Limited_Precision(yMin    , GRID_SYSTEM_PRECISION);
 
 		if( Cellsize > 0.0 )
 		{
diff --git a/src/saga_core/saga_api/module.cpp b/src/saga_core/saga_api/module.cpp
index d3b1ea8..3850c94 100644
--- a/src/saga_core/saga_api/module.cpp
+++ b/src/saga_core/saga_api/module.cpp
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: module.cpp 2624 2015-09-30 15:33:53Z oconrad $
+ * Version $Id: module.cpp 2670 2015-11-02 15:36:08Z oconrad $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -596,6 +596,8 @@ bool CSG_Module::Set_Progress(double Position, double Range)
 //---------------------------------------------------------
 bool CSG_Module::Stop_Execution(bool bDialog)
 {
+	m_bExecutes	= false;
+
 	return( SG_UI_Stop_Execution(bDialog) );
 }
 
diff --git a/src/saga_core/saga_api/module_library.h b/src/saga_core/saga_api/module_library.h
index cba3261..0261a1a 100644
--- a/src/saga_core/saga_api/module_library.h
+++ b/src/saga_core/saga_api/module_library.h
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: module_library.h 2640 2015-10-07 17:29:38Z oconrad $
+ * Version $Id: module_library.h 2680 2015-11-06 12:27:37Z oconrad $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -235,21 +235,21 @@ SAGA_API_DLL_EXPORT CSG_Module_Library_Manager &	SG_Get_Module_Library_Manager	(
 	\
 	if(	pModule == NULL )\
 	{\
-		Error_Set(CSG_String::Format(SG_T("%s [%s]"), _TL("could not find tool"), SG_T(LIBRARY)));\
+		SG_UI_Msg_Add_Error(CSG_String::Format(SG_T("%s [%s]"), _TL("could not find tool"), SG_T(LIBRARY)));\
 	}\
 	else\
 	{\
-		Process_Set_Text(pModule->Get_Name());\
+		SG_UI_Process_Set_Text(pModule->Get_Name());\
 		\
 		pModule->Settings_Push();\
 		\
 		if( !pModule->On_Before_Execution() || !(CONDITION) )\
 		{\
-			Error_Set(CSG_String::Format(SG_T("%s [%s].[%s]"), _TL("could not initialize tool"), SG_T(LIBRARY), pModule->Get_Name().c_str()));\
+			SG_UI_Msg_Add_Error(CSG_String::Format(SG_T("%s [%s].[%s]"), _TL("could not initialize tool"), SG_T(LIBRARY), pModule->Get_Name().c_str()));\
 		}\
 		else if( !pModule->Execute() )\
 		{\
-			Error_Set(CSG_String::Format(SG_T("%s [%s].[%s]"), _TL("could not execute tool"   ), SG_T(LIBRARY), pModule->Get_Name().c_str()));\
+			SG_UI_Msg_Add_Error(CSG_String::Format(SG_T("%s [%s].[%s]"), _TL("could not execute tool"   ), SG_T(LIBRARY), pModule->Get_Name().c_str()));\
 		}\
 		else\
 		{\
diff --git a/src/saga_core/saga_api/parameter_data.cpp b/src/saga_core/saga_api/parameter_data.cpp
index cabee01..0900248 100644
--- a/src/saga_core/saga_api/parameter_data.cpp
+++ b/src/saga_core/saga_api/parameter_data.cpp
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: parameter_data.cpp 2640 2015-10-07 17:29:38Z oconrad $
+ * Version $Id: parameter_data.cpp 2727 2015-12-13 16:02:55Z reklov_w $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -1752,6 +1752,31 @@ void CSG_Parameter_Table_Field::On_Assign(CSG_Parameter_Data *pSource)
 	m_Default	= ((CSG_Parameter_Table_Field *)pSource)->m_Default;
 }
 
+//---------------------------------------------------------
+bool CSG_Parameter_Table_Field::On_Serialize(CSG_MetaData &Entry, bool bSave)
+{
+	if( bSave )
+	{
+		Entry.Set_Property("index", asInt());
+		Entry.Set_Content(asString());
+	}
+	else
+	{
+		int	idx;
+
+		if( Entry.Get_Property("index", idx) )	// we require this check for backward compatibility, "index" was first introduced with SAGA 2.2.3 (r2671)
+		{
+			return( Set_Value(idx) );
+		}
+		else
+		{
+			return( Set_Value(Entry.Get_Content()) );
+		}
+	}
+
+	return( true );
+}
+
 
 ///////////////////////////////////////////////////////////
 //														 //
@@ -1807,7 +1832,7 @@ bool CSG_Parameter_Table_Fields::Set_Value(const CSG_String &Value)
 		else if( sValue.Length() > 0 )
 		{
 			sValue.Trim();
-			
+
 			if( sValue[0] == '[' )
 			{
 				sValue	= sValue.AfterFirst('[').BeforeLast(']');
diff --git a/src/saga_core/saga_api/parameters.cpp b/src/saga_core/saga_api/parameters.cpp
index 7aaa87c..9a66dd7 100644
--- a/src/saga_core/saga_api/parameters.cpp
+++ b/src/saga_core/saga_api/parameters.cpp
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: parameters.cpp 2604 2015-09-25 16:18:14Z oconrad $
+ * Version $Id: parameters.cpp 2676 2015-11-04 18:39:37Z oconrad $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -1303,19 +1303,26 @@ bool CSG_Parameters::DataObjects_Create(void)
 
 			if( pDataObject )
 			{
-				pDataObject->Set_Name(p->Get_Name());
+				if( p->Set_Value(pDataObject) )
+				{
+					pDataObject->Set_Name(p->Get_Name());
 
-				if( m_pManager )
+					if( m_pManager )
+					{
+						m_pManager->Add(pDataObject);
+					}
+				}
+				else
 				{
-					m_pManager->Add(pDataObject);
+					delete(pDataObject);
+
+					bResult	= false;
 				}
 			}
 			else
 			{
 				bResult	= p->is_Optional();
 			}
-
-			p->Set_Value(pDataObject);
 		}
 	}
 
diff --git a/src/saga_core/saga_api/parameters.h b/src/saga_core/saga_api/parameters.h
index 139a783..62bee96 100644
--- a/src/saga_core/saga_api/parameters.h
+++ b/src/saga_core/saga_api/parameters.h
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: parameters.h 2619 2015-09-29 13:51:55Z oconrad $
+ * Version $Id: parameters.h 2671 2015-11-02 15:38:07Z oconrad $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -783,6 +783,7 @@ protected:
 
 
 	virtual void				On_Assign				(CSG_Parameter_Data *pSource);
+	virtual bool				On_Serialize			(CSG_MetaData &Entry, bool bSave);
 
 };
 
diff --git a/src/saga_core/saga_api/pointcloud.cpp b/src/saga_core/saga_api/pointcloud.cpp
index d4f5856..4983040 100644
--- a/src/saga_core/saga_api/pointcloud.cpp
+++ b/src/saga_core/saga_api/pointcloud.cpp
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: pointcloud.cpp 2566 2015-09-01 13:35:09Z oconrad $
+ * Version $Id: pointcloud.cpp 2700 2015-11-24 17:18:29Z oconrad $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -214,9 +214,6 @@ void CSG_PointCloud::_On_Construction(void)
 	m_Cursor		= NULL;
 	m_bXYZPrecDbl	= true;
 
-	m_Selected		= NULL;
-	m_nSelected		= 0;
-
 	Set_NoData_Value(-999999);
 
 	Set_Update_Flag();
@@ -225,8 +222,7 @@ void CSG_PointCloud::_On_Construction(void)
 	m_Shapes.Add_Shape();
 	m_Shapes_Index	= -1;
 
-	m_Array_Points  .Create(sizeof(char *), 0, SG_ARRAY_GROWTH_3);
-	m_Array_Selected.Create(sizeof(int   ), 0, SG_ARRAY_GROWTH_3);
+	m_Array_Points.Create(sizeof(char *), 0, SG_ARRAY_GROWTH_3);
 }
 
 //---------------------------------------------------------
@@ -439,6 +435,8 @@ bool CSG_PointCloud::_Save(const CSG_String &File_Name)
 
 	SG_UI_Msg_Add(_TL("okay"), false, SG_UI_MSG_STYLE_SUCCESS);
 
+	SG_UI_Process_Set_Ready();
+
 	return( true );
 }
 
@@ -867,15 +865,13 @@ bool CSG_PointCloud::Del_Points(void)
 		SG_Free(m_Points[iPoint]);
 	}
 
-	m_Array_Points  .Destroy();
-	m_Array_Selected.Destroy();
+	m_Array_Points.Destroy();
 
 	m_nRecords	= 0;
 	m_Points	= NULL;
 	m_Cursor	= NULL;
 
-	m_nSelected	= 0;
-	m_Selected	= NULL;
+	m_Selection.Set_Array(0);
 
 	return( true );
 }
@@ -1013,7 +1009,7 @@ CSG_Shape * CSG_PointCloud::_Set_Shape(int iPoint)
 
 	if( iPoint >= 0 && iPoint < Get_Count() )
 	{
-		if( iPoint != m_Shapes_Index )
+		if(1|| iPoint != m_Shapes_Index )
 		{
 			m_Cursor	= m_Points[iPoint];
 
@@ -1034,7 +1030,7 @@ CSG_Shape * CSG_PointCloud::_Set_Shape(int iPoint)
 						CSG_String	s;
 
 						Get_Value(i, s);
-					
+
 						pShape->Set_Value(i, s);
 					}
 					break;
@@ -1042,6 +1038,8 @@ CSG_Shape * CSG_PointCloud::_Set_Shape(int iPoint)
 			}
 
 			m_Shapes_Index	= iPoint;
+			pShape->m_Index	= iPoint;
+			pShape->Set_Selected(is_Selected(iPoint));
 		}
 
 		m_Shapes.Set_Modified(false);
@@ -1145,51 +1143,35 @@ CSG_Shape * CSG_PointCloud::Add_Shape(CSG_Table_Record *pCopy, TSG_ADD_Shape_Cop
 //---------------------------------------------------------
 bool CSG_PointCloud::Select(int iRecord, bool bInvert)
 {
-	if( !bInvert )
+	if( !bInvert && Get_Selection_Count() > 0 )
 	{
-		for(int i=0; i<m_nSelected; i++)
+		for(size_t i=0; i<Get_Selection_Count(); i++)
 		{
-			m_Points[m_Selected[i]][0]	&= ~SG_TABLE_REC_FLAG_Selected;
+			m_Points[Get_Selection_Index(i)][0]	&= ~SG_TABLE_REC_FLAG_Selected;
 		}
 
-		m_Array_Selected.Destroy();
-		m_Selected	= NULL;
-		m_nSelected	= 0;
+		m_Selection.Destroy();
 	}
 
 	if( Set_Cursor(iRecord) )
 	{
 		if( (m_Cursor[0] & SG_TABLE_REC_FLAG_Selected) == 0 )	// select
 		{
-			if( m_Array_Selected.Set_Array(m_nSelected + 1, (void **)&m_Selected) )
+			if( _Add_Selection(iRecord) )
 			{
 				m_Cursor[0]	|= SG_TABLE_REC_FLAG_Selected;
 
-				m_Selected[m_nSelected++]	= iRecord;
-
 				return( true );
 			}
 		}
 		else													// deselect
 		{
-			m_Cursor[0]	&= ~SG_TABLE_REC_FLAG_Selected;
-
-			m_nSelected--;
-
-			for(int i=0; i<m_nSelected; i++)
+			if( _Del_Selection(iRecord) )
 			{
-				if( m_Points[iRecord] == m_Points[m_Selected[i]] )
-				{
-					for(; i<m_nSelected; i++)
-					{
-						m_Selected[i]	= m_Selected[i + 1];
-					}
-				}
-			}
-
-			m_Array_Selected.Set_Array(m_nSelected, (void **)&m_Selected);
+				m_Cursor[0]	&= ~SG_TABLE_REC_FLAG_Selected;
 
-			return( true );
+				return( true );
+			}
 		}
 	}
 
@@ -1224,7 +1206,7 @@ bool CSG_PointCloud::Select(TSG_Rect Extent, bool bInvert)
 		}
 	}
 
-	return( m_nSelected > 0 );
+	return( Get_Selection_Count() > 0 );
 }
 
 //---------------------------------------------------------
@@ -1252,24 +1234,24 @@ bool CSG_PointCloud::is_Selected(int iRecord)	const
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
-CSG_Shape * CSG_PointCloud::Get_Selection(int Index)
+CSG_Shape * CSG_PointCloud::Get_Selection(size_t Index)
 {
-	return( Index >= 0 && Index < m_nSelected ? _Set_Shape(m_Selected[Index]) : NULL );
+	return( Index < Get_Selection_Count() ? _Set_Shape(Get_Selection_Index(Index)) : NULL );
 }
 
 //---------------------------------------------------------
 const CSG_Rect & CSG_PointCloud::Get_Selection_Extent(void)
 {
-	if( m_nSelected > 0 && Set_Cursor(m_Selected[0]) )
+	if( Get_Selection_Count() > 0 && Set_Cursor(Get_Selection_Index(0)) )
 	{
 		TSG_Rect	r;
 
 		r.xMin	= r.xMax	= Get_X();
 		r.yMin	= r.yMax	= Get_Y();
 
-		for(int i=1; i<m_nSelected; i++)
+		for(size_t i=1; i<Get_Selection_Count(); i++)
 		{
-			if( Set_Cursor(m_Selected[i]) )
+			if( Set_Cursor(Get_Selection_Index(i)) )
 			{
 				if( Get_X() < r.xMin )	r.xMin	= Get_X();	else if( Get_X() > r.xMax )	r.xMax	= Get_X();
 				if( Get_Y() < r.yMin )	r.yMin	= Get_Y();	else if( Get_Y() > r.yMax )	r.yMax	= Get_Y();
@@ -1294,36 +1276,33 @@ const CSG_Rect & CSG_PointCloud::Get_Selection_Extent(void)
 //---------------------------------------------------------
 int CSG_PointCloud::Del_Selection(void)
 {
-	if( m_nSelected <= 0 )
-	{
-		return( 0 );
-	}
+	int	n	= 0;
 
-	//-----------------------------------------------------
-	int		i, n;
+	if( Get_Selection_Count() > 0 )
+	{
+		m_Selection.Set_Array(0);
 
-	m_Array_Selected.Set_Array(0, (void **)&m_Selected);
-	m_nSelected	= 0;
-	m_Cursor	= NULL;
+		m_Cursor	= NULL;
 
-	for(i=0, n=0; i<m_nRecords; i++)
-	{
-		if( (m_Points[i][0] & SG_TABLE_REC_FLAG_Selected) != 0 )
+		for(int i=0; i<m_nRecords; i++)
 		{
-			SG_Free(m_Points[i]);
-		}
-		else
-		{
-			if( n < i )
+			if( (m_Points[i][0] & SG_TABLE_REC_FLAG_Selected) != 0 )
 			{
-				m_Points[n]	= m_Points[i];
+				SG_Free(m_Points[i]);
 			}
+			else
+			{
+				if( n < i )
+				{
+					m_Points[n]	= m_Points[i];
+				}
 
-			n++;
+				n++;
+			}
 		}
-	}
 
-	m_Array_Points.Set_Array(m_nRecords = n, (void **)&m_Points);
+		m_Array_Points.Set_Array(m_nRecords = n, (void **)&m_Points);
+	}
 
 	return( n );
 }
@@ -1331,29 +1310,26 @@ int CSG_PointCloud::Del_Selection(void)
 //---------------------------------------------------------
 int CSG_PointCloud::Inv_Selection(void)
 {
-	char	**pPoint;
-	int		i, n;
-
-	n	= m_nRecords - m_nSelected;
-
-	if( m_Array_Selected.Set_Array(n, (void **)&m_Selected) )
+	if( m_Selection.Set_Array((size_t)m_nRecords - Get_Selection_Count()) )
 	{
-		for(i=0, m_nSelected=0, pPoint=m_Points; i<m_nRecords; i++, pPoint++)
+		char	**pPoint	= m_Points;
+
+		for(size_t i=0, n=0; i<(size_t)m_nRecords && n<Get_Selection_Count(); i++, pPoint++)
 		{
-			if( ((*pPoint)[0] & SG_TABLE_REC_FLAG_Selected) == 0 && m_nSelected < n )
+			if( ((*pPoint)[0] & SG_TABLE_REC_FLAG_Selected) != 0 )
 			{
-				m_Selected[m_nSelected++]	= i;
-
-				(*pPoint)[0]	|= SG_TABLE_REC_FLAG_Selected;
+				(*pPoint)[0]	&= ~SG_TABLE_REC_FLAG_Selected;
 			}
 			else
 			{
-				(*pPoint)[0]	&= ~SG_TABLE_REC_FLAG_Selected;
+				(*pPoint)[0]	|= SG_TABLE_REC_FLAG_Selected;
+
+				_Set_Selection(i, n++);
 			}
 		}
 	}
 
-	return( m_nSelected );
+	return( Get_Selection_Count() );
 }
 
 
diff --git a/src/saga_core/saga_api/pointcloud.h b/src/saga_core/saga_api/pointcloud.h
index 704ede7..cb4de04 100644
--- a/src/saga_core/saga_api/pointcloud.h
+++ b/src/saga_core/saga_api/pointcloud.h
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: pointcloud.h 2566 2015-09-01 13:35:09Z oconrad $
+ * Version $Id: pointcloud.h 2700 2015-11-24 17:18:29Z oconrad $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -189,7 +189,7 @@ public:
 
 	virtual int						Del_Selection		(void);
 	virtual int						Inv_Selection		(void);
-	virtual CSG_Shape *				Get_Selection		(int Index = 0);
+	virtual CSG_Shape *				Get_Selection		(size_t Index = 0);
 	virtual const CSG_Rect &		Get_Selection_Extent(void);
 
 
@@ -210,9 +210,9 @@ private:
 
 	char							**m_Points, *m_Cursor;
 
-	int								m_nPointBytes, *m_Field_Offset, m_Shapes_Index, *m_Selected;
+	int								m_nPointBytes, *m_Field_Offset, m_Shapes_Index;
 
-	CSG_Array						m_Array_Points, m_Array_Selected;
+	CSG_Array						m_Array_Points;
 
 	CSG_Shapes						m_Shapes;
 
diff --git a/src/saga_core/saga_api/projections.cpp b/src/saga_core/saga_api/projections.cpp
index ead09bf..7da0228 100644
--- a/src/saga_core/saga_api/projections.cpp
+++ b/src/saga_core/saga_api/projections.cpp
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: projections.cpp 2059 2014-03-19 18:02:00Z oconrad $
+ * Version $Id: projections.cpp 2714 2015-12-04 11:51:33Z oconrad $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -321,6 +321,11 @@ bool CSG_Projection::Assign(const CSG_String &Projection, TSG_Projection_Format
 
 	Destroy();
 
+	if( Projection.is_Empty() )
+	{
+		return( false );
+	}
+
 	//-----------------------------------------------------
 	switch( Format )
 	{
@@ -485,9 +490,12 @@ bool CSG_Projection::Save(CSG_MetaData &Projection) const
 //---------------------------------------------------------
 bool CSG_Projection::is_Equal(const CSG_Projection &Projection)	const
 {
-	return(	(!m_Authority.CmpNoCase(Projection.m_Authority) && m_Authority_ID == Projection.m_Authority_ID)
-		||	(!m_Proj4    .CmpNoCase(Projection.m_Proj4))
-	);
+	if( !m_Authority.is_Empty() && !Projection.m_Authority.is_Empty() )
+	{
+		return(	m_Authority.CmpNoCase(Projection.m_Authority) == 0 && m_Authority_ID == Projection.m_Authority_ID );
+	}
+
+	return( m_Proj4.CmpNoCase(Projection.m_Proj4) == 0 );
 }
 
 //---------------------------------------------------------
@@ -1825,29 +1833,30 @@ bool CSG_Projections::_Set_Dictionary(CSG_Table &Dictionary, int Direction)
 	};
 
 	//-----------------------------------------------------
-	Dictionary.Create(SG_T("Proj.4-WKT Dictionary"));
+	Dictionary.Destroy();
+	Dictionary.Set_Name("Proj.4-WKT Dictionary");
 
 	if( Direction == 0 )
 	{
-		Dictionary.Add_Field(SG_T("PROJ4"), SG_DATATYPE_String);
-		Dictionary.Add_Field(SG_T("DIR")  , SG_DATATYPE_String);
-		Dictionary.Add_Field(SG_T("WKT")  , SG_DATATYPE_String);
-		Dictionary.Add_Field(SG_T("DESC") , SG_DATATYPE_String);
+		Dictionary.Add_Field("PROJ4", SG_DATATYPE_String);
+		Dictionary.Add_Field("DIR"  , SG_DATATYPE_String);
+		Dictionary.Add_Field("WKT"  , SG_DATATYPE_String);
+		Dictionary.Add_Field("DESC" , SG_DATATYPE_String);
 
 		for(int i=0; i<n; i++)
 		{
 			CSG_Table_Record	*pRecord	= Dictionary.Add_Record();
 
-			pRecord->Set_Value(0, SG_STR_MBTOSG(Translation[i][0]));
-			pRecord->Set_Value(1, SG_STR_MBTOSG(Translation[i][1]));
-			pRecord->Set_Value(2, SG_STR_MBTOSG(Translation[i][2]));
-			pRecord->Set_Value(3, SG_STR_MBTOSG(Translation[i][3]));
+			pRecord->Set_Value(0, Translation[i][0]);
+			pRecord->Set_Value(1, Translation[i][1]);
+			pRecord->Set_Value(2, Translation[i][2]);
+			pRecord->Set_Value(3, Translation[i][3]);
 		}
 	}
 	else if( Direction > 0 )	// Proj4 to WKT
 	{
-		Dictionary.Add_Field(SG_T("PROJ4"), SG_DATATYPE_String);
-		Dictionary.Add_Field(SG_T("WKT")  , SG_DATATYPE_String);
+		Dictionary.Add_Field("PROJ4", SG_DATATYPE_String);
+		Dictionary.Add_Field("WKT"  , SG_DATATYPE_String);
 
 		for(int i=0; i<n; i++)
 		{
@@ -1855,15 +1864,15 @@ bool CSG_Projections::_Set_Dictionary(CSG_Table &Dictionary, int Direction)
 			{
 				CSG_Table_Record	*pRecord	= Dictionary.Add_Record();
 
-				pRecord->Set_Value(0, SG_STR_MBTOSG(Translation[i][0]));
-				pRecord->Set_Value(1, SG_STR_MBTOSG(Translation[i][2]));
+				pRecord->Set_Value(0, Translation[i][0]);
+				pRecord->Set_Value(1, Translation[i][2]);
 			}
 		}
 	}
 	else if( Direction < 0 )	// WKT to Proj4
 	{
-		Dictionary.Add_Field(SG_T("WKT")  , SG_DATATYPE_String);
-		Dictionary.Add_Field(SG_T("PROJ4"), SG_DATATYPE_String);
+		Dictionary.Add_Field("WKT"  , SG_DATATYPE_String);
+		Dictionary.Add_Field("PROJ4", SG_DATATYPE_String);
 
 		for(int i=0; i<n; i++)
 		{
@@ -1871,8 +1880,8 @@ bool CSG_Projections::_Set_Dictionary(CSG_Table &Dictionary, int Direction)
 			{
 				CSG_Table_Record	*pRecord	= Dictionary.Add_Record();
 
-				pRecord->Set_Value(0, SG_STR_MBTOSG(Translation[i][2]));
-				pRecord->Set_Value(1, SG_STR_MBTOSG(Translation[i][0]));
+				pRecord->Set_Value(0, Translation[i][2]);
+				pRecord->Set_Value(1, Translation[i][0]);
 			}
 		}
 	}
diff --git a/src/saga_core/saga_api/saga_api.h b/src/saga_core/saga_api/saga_api.h
index 38de08b..c26299e 100644
--- a/src/saga_core/saga_api/saga_api.h
+++ b/src/saga_core/saga_api/saga_api.h
@@ -128,8 +128,8 @@
 //---------------------------------------------------------
 #define SAGA_MAJOR_VERSION		2
 #define SAGA_MINOR_VERSION		2
-#define SAGA_RELEASE_NUMBER		2
-#define SAGA_VERSION			SG_T("2.2.2")
+#define SAGA_RELEASE_NUMBER		3
+#define SAGA_VERSION			SG_T("2.2.3")
 
 
 ///////////////////////////////////////////////////////////
diff --git a/src/saga_core/saga_api/shapes.cpp b/src/saga_core/saga_api/shapes.cpp
index 37868de..00bd931 100644
--- a/src/saga_core/saga_api/shapes.cpp
+++ b/src/saga_core/saga_api/shapes.cpp
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: shapes.cpp 2641 2015-10-08 10:00:15Z oconrad $
+ * Version $Id: shapes.cpp 2706 2015-12-01 14:22:12Z oconrad $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -296,6 +296,7 @@ bool CSG_Shapes::Create(const CSG_String &File_Name)
 		Set_Modified(false);
 		Set_Update_Flag();
 
+		SG_UI_Process_Set_Ready();
 		SG_UI_Msg_Add(_TL("okay"), false, SG_UI_MSG_STYLE_SUCCESS);
 
 		return( true );
@@ -314,6 +315,7 @@ bool CSG_Shapes::Create(const CSG_String &File_Name)
 		Destroy();
 	}
 
+	SG_UI_Process_Set_Ready();
 	SG_UI_Msg_Add(_TL("failed"), false, SG_UI_MSG_STYLE_FAILURE);
 
 	return( false );
@@ -412,11 +414,13 @@ bool CSG_Shapes::Save(const CSG_String &File_Name, int Format)
 
 		Save_MetaData(File_Name);
 
+		SG_UI_Process_Set_Ready();
 		SG_UI_Msg_Add(_TL("okay"), false, SG_UI_MSG_STYLE_SUCCESS);
 
 		return( true );
 	}
 
+	SG_UI_Process_Set_Ready();
 	SG_UI_Msg_Add(_TL("failed"), false, SG_UI_MSG_STYLE_FAILURE);
 
 	return( false );
diff --git a/src/saga_core/saga_api/shapes_io.cpp b/src/saga_core/saga_api/shapes_io.cpp
index 6390910..783d16e 100644
--- a/src/saga_core/saga_api/shapes_io.cpp
+++ b/src/saga_core/saga_api/shapes_io.cpp
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: shapes_io.cpp 1921 2014-01-09 10:24:11Z oconrad $
+ * Version $Id: shapes_io.cpp 2706 2015-12-01 14:22:12Z oconrad $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -338,8 +338,6 @@ bool CSG_Shapes::_Load_ESRI(const CSG_String &File_Name)
 	}
 
 	//-----------------------------------------------------
-	SG_UI_Process_Set_Ready();
-
 	Get_Projection().Load(SG_File_Make_Path(NULL, File_Name, SG_T("prj")), SG_PROJ_FMT_WKT);
 
 	return( true );
@@ -632,8 +630,6 @@ bool CSG_Shapes::_Save_ESRI(const CSG_String &File_Name)
 	fSHX.Write_Int(fSHX_Size, true);
 
 	//-----------------------------------------------------
-	SG_UI_Process_Set_Ready();
-
 	Get_Projection().Save(SG_File_Make_Path(NULL, File_Name, SG_T("prj")), SG_PROJ_FMT_WKT);
 
 	return( true );
diff --git a/src/saga_core/saga_api/table.cpp b/src/saga_core/saga_api/table.cpp
index d3a5752..6a03943 100644
--- a/src/saga_core/saga_api/table.cpp
+++ b/src/saga_core/saga_api/table.cpp
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: table.cpp 2641 2015-10-08 10:00:15Z oconrad $
+ * Version $Id: table.cpp 2700 2015-11-24 17:18:29Z oconrad $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -175,7 +175,7 @@ bool CSG_Table::Create(const CSG_String &File_Name, TSG_Table_File_Type Format)
 	SG_UI_Msg_Add(CSG_String::Format("%s: %s...", _TL("Load table"), File_Name.c_str()), true);
 
 	//-----------------------------------------------------
-	bool	bResult	= File_Name.BeforeFirst(':').Cmp("PGSQL") && SG_File_Exists(File_Name) && _Load(File_Name, Format, NULL);
+	bool	bResult	= File_Name.BeforeFirst(':').Cmp("PGSQL") && SG_File_Exists(File_Name) && Load(File_Name, (int)Format, NULL);
 
 	if( bResult )
 	{
@@ -255,7 +255,7 @@ bool CSG_Table::Create(const CSG_String &File_Name, TSG_Table_File_Type Format)
 }
 
 //---------------------------------------------------------
-CSG_Table::CSG_Table(const CSG_String &File_Name, TSG_Table_File_Type Format, const SG_Char *Separator)
+CSG_Table::CSG_Table(const CSG_String &File_Name, TSG_Table_File_Type Format, const SG_Char Separator)
 	: CSG_Data_Object()
 {
 	_On_Construction();
@@ -263,9 +263,9 @@ CSG_Table::CSG_Table(const CSG_String &File_Name, TSG_Table_File_Type Format, co
 	Create(File_Name, Format, Separator);
 }
 
-bool CSG_Table::Create(const CSG_String &File_Name, TSG_Table_File_Type Format, const SG_Char *Separator)
+bool CSG_Table::Create(const CSG_String &File_Name, TSG_Table_File_Type Format, const SG_Char Separator)
 {
-	return( _Load(File_Name, Format, Separator) );
+	return( Load(File_Name, (int)Format, Separator) );
 }
 
 //---------------------------------------------------------
@@ -313,11 +313,10 @@ void CSG_Table::_On_Construction(void)
 	m_nRecords		= 0;
 	m_nBuffer		= 0;
 
-	m_nSelected		= 0;
-	m_Selected		= NULL;
-
 	m_Index			= NULL;
 
+	m_Selection.Create(sizeof(size_t), 0, SG_ARRAY_GROWTH_3);
+
 	Set_Update_Flag();
 }
 
@@ -819,7 +818,7 @@ CSG_Table_Record * CSG_Table::Ins_Record(int iRecord, CSG_Table_Record *pCopy)
 		{
 			if( is_Indexed() )
 			{
-				m_Index[i]		= m_Index[i - 1];
+				m_Index[i]	= m_Index[i - 1];
 			}
 
 			m_Records[i]			= m_Records[i - 1];
@@ -831,7 +830,8 @@ CSG_Table_Record * CSG_Table::Ins_Record(int iRecord, CSG_Table_Record *pCopy)
 			m_Index[iRecord]	= iRecord;
 		}
 
-		m_Records[iRecord]		= pRecord;
+		pRecord->m_Index	= iRecord;
+		m_Records[iRecord]	= pRecord;
 		m_nRecords++;
 
 		Set_Modified();
@@ -1110,6 +1110,20 @@ bool CSG_Table::Set_Index(int Field_1, TSG_Table_Index_Order Order_1, int Field_
 		_Index_Destroy();
 	}
 
+	//-----------------------------------------------------
+	if( Get_Selection_Count() > 0 )
+	{
+		for(size_t i=0, n=0; i<(size_t)m_nRecords && n<Get_Selection_Count(); i++)
+		{
+			CSG_Table_Record	*pRecord	= Get_Record_byIndex(i);
+
+			if( pRecord && pRecord->is_Selected() )
+			{
+				_Set_Selection(n++, pRecord->Get_Index());
+			}
+		}
+	}
+
 	return( is_Indexed() );
 }
 
diff --git a/src/saga_core/saga_api/table.h b/src/saga_core/saga_api/table.h
index 1284806..d296243 100644
--- a/src/saga_core/saga_api/table.h
+++ b/src/saga_core/saga_api/table.h
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: table.h 2431 2015-03-03 17:21:59Z oconrad $
+ * Version $Id: table.h 2713 2015-12-04 11:50:53Z oconrad $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -125,6 +125,7 @@ TSG_Table_Index_Order;
 class SAGA_API_DLL_EXPORT CSG_Table_Record
 {
 	friend class CSG_Table;
+	friend class CSG_PointCloud;
 
 public:
 
@@ -223,8 +224,8 @@ public:
 									CSG_Table			(const CSG_String &File_Name, TSG_Table_File_Type Format = TABLE_FILETYPE_Undefined);
 	bool							Create				(const CSG_String &File_Name, TSG_Table_File_Type Format = TABLE_FILETYPE_Undefined);
 
-									CSG_Table			(const CSG_String &File_Name, TSG_Table_File_Type Format, const SG_Char *Separator);
-	bool							Create				(const CSG_String &File_Name, TSG_Table_File_Type Format, const SG_Char *Separator);
+									CSG_Table			(const CSG_String &File_Name, TSG_Table_File_Type Format, const SG_Char Separator);
+	bool							Create				(const CSG_String &File_Name, TSG_Table_File_Type Format, const SG_Char Separator);
 
 									CSG_Table			(CSG_Table *pTemplate);
 	bool							Create				(CSG_Table *pTemplate);
@@ -239,8 +240,9 @@ public:
 	virtual bool					Assign				(CSG_Data_Object *pSource);
 	bool							Assign_Values		(CSG_Table *pTable);
 
+	bool							Load				(const CSG_String &File_Name, int Format, SG_Char Separator);
 	virtual bool					Save				(const CSG_String &File_Name, int Format = 0);
-	virtual bool					Save				(const CSG_String &File_Name, int Format, const SG_Char *Separator);
+	virtual bool					Save				(const CSG_String &File_Name, int Format, SG_Char Separator);
 	bool							Serialize			(CSG_File &Stream, bool bSave);
 
 	//-----------------------------------------------------
@@ -308,8 +310,9 @@ public:
 	virtual void					Set_Modified		(bool bModified = true);
 
 	//-----------------------------------------------------
-	int								Get_Selection_Count	(void)			const	{	return( m_nSelected );	}
-	virtual CSG_Table_Record *		Get_Selection		(int Index = 0)	const	{	return( Index >= 0 && Index < m_nSelected ? Get_Record(m_Selected[Index]) : NULL );	}
+	size_t							Get_Selection_Count	(void)				const	{	return( m_Selection.Get_Size() );	}
+	size_t							Get_Selection_Index	(size_t Index = 0)	const	{	return( Index < m_Selection.Get_Size() ? *((size_t *)m_Selection.Get_Entry(Index)) : (size_t)Get_Count() );	}
+	virtual CSG_Table_Record *		Get_Selection		(size_t Index = 0)	const	{	return( Index < m_Selection.Get_Size() ? Get_Record((int)Get_Selection_Index(Index)) : NULL );	}
 
 	virtual bool					is_Selected			(int iRecord)	const	{	return( iRecord >= 0 && iRecord < m_nRecords ? m_Records[iRecord]->is_Selected() : false );	}
 
@@ -332,7 +335,7 @@ public:
 
 protected:
 
-	int								m_nFields, m_nRecords, m_nBuffer, m_nSelected;
+	int								m_nFields, m_nRecords, m_nBuffer;
 
 	TSG_Data_Type					*m_Field_Type;
 
@@ -340,11 +343,17 @@ protected:
 
 	CSG_Simple_Statistics			**m_Field_Stats;
 
+	CSG_Array						m_Selection;
+
 
 	virtual void					_On_Construction	(void);
 
 	virtual CSG_Table_Record *		_Get_New_Record		(int Index);
 
+	bool							_Add_Selection		(size_t iRecord);
+	bool							_Set_Selection		(size_t iRecord, size_t Index);
+	bool							_Del_Selection		(size_t iRecord);
+
 	bool							_Stats_Invalidate	(void)			const;
 	bool							_Stats_Invalidate	(int iField)	const;
 	virtual bool					_Stats_Update		(int iField)	const;
@@ -352,7 +361,7 @@ protected:
 
 private:
 
-	int								*m_Index, m_Index_Field[3], *m_Selected;
+	int								*m_Index, m_Index_Field[3];
 
 	TSG_Table_Index_Order			m_Index_Order[3];
 
@@ -364,9 +373,11 @@ private:
 	bool							_Inc_Array			(void);
 	bool							_Dec_Array			(void);
 
-	bool							_Load				(const CSG_String &File_Name, TSG_Table_File_Type Format, const SG_Char *Separator);
-	bool							_Load_Text			(const CSG_String &File_Name, bool bHeadline, const SG_Char *Separator);
-	bool							_Save_Text			(const CSG_String &File_Name, bool bHeadline, const SG_Char *Separator);
+	int								_Load_Text_Trim		(CSG_String &Text, const SG_Char Separator);
+
+	bool							_Load_Text			(const CSG_String &File_Name, bool bHeadline, const SG_Char Separator);
+	bool							_Save_Text			(const CSG_String &File_Name, bool bHeadline, const SG_Char Separator);
+
 	bool							_Load_DBase			(const CSG_String &File_Name);
 	bool							_Save_DBase			(const CSG_String &File_Name);
 
diff --git a/src/saga_core/saga_api/table_io.cpp b/src/saga_core/saga_api/table_io.cpp
index 79fa6bb..a6507e7 100644
--- a/src/saga_core/saga_api/table_io.cpp
+++ b/src/saga_core/saga_api/table_io.cpp
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: table_io.cpp 2633 2015-10-02 16:24:33Z oconrad $
+ * Version $Id: table_io.cpp 2690 2015-11-17 12:08:15Z oconrad $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -74,7 +74,7 @@
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
-bool CSG_Table::_Load(const CSG_String &File_Name, TSG_Table_File_Type Format, const SG_Char *Separator)
+bool CSG_Table::Load(const CSG_String &File_Name, int Format, SG_Char Separator)
 {
 	if( !SG_File_Exists(File_Name) )
 	{
@@ -82,21 +82,19 @@ bool CSG_Table::_Load(const CSG_String &File_Name, TSG_Table_File_Type Format, c
 	}
 
 	//-----------------------------------------------------
-	CSG_String	sSeparator(Separator && *Separator ? Separator : SG_T("\t"));
-
 	if( Format == TABLE_FILETYPE_Undefined )
 	{
 		if( SG_File_Cmp_Extension(File_Name, SG_T("dbf")) )
 		{
 			Format	= TABLE_FILETYPE_DBase;
 		}
-		else if( SG_File_Cmp_Extension(File_Name, SG_T("csv")) )
+		else
 		{
 			Format	= TABLE_FILETYPE_Text;
 
-			if( !Separator || *Separator == '\0' )
+			if( Separator == '\0' )
 			{
-				sSeparator	= ",";	// comma separated values
+				Separator	= SG_File_Cmp_Extension(File_Name, SG_T("csv")) ? ',' : '\t';	// comma separated values or tab spaced text
 			}
 		}
 	}
@@ -105,10 +103,10 @@ bool CSG_Table::_Load(const CSG_String &File_Name, TSG_Table_File_Type Format, c
 	switch( Format )
 	{
 	case TABLE_FILETYPE_Text: default:
-		return( _Load_Text (File_Name, true , sSeparator) );
+		return( _Load_Text (File_Name, true , Separator) );
 
 	case TABLE_FILETYPE_Text_NoHeadLine:
-		return( _Load_Text (File_Name, false, sSeparator) );
+		return( _Load_Text (File_Name, false, Separator) );
 
 	case TABLE_FILETYPE_DBase:
 		return( _Load_DBase(File_Name) );
@@ -124,12 +122,9 @@ bool CSG_Table::Save(const CSG_String &File_Name, int Format)
 }
 
 //---------------------------------------------------------
-bool CSG_Table::Save(const CSG_String &File_Name, int Format, const SG_Char *Separator)
+bool CSG_Table::Save(const CSG_String &File_Name, int Format, SG_Char Separator)
 {
-	bool		bResult;
-	CSG_String	sSeparator(Separator && *Separator ? Separator : SG_T("\t"));
-
-	SG_UI_Msg_Add(CSG_String::Format(SG_T("%s: %s..."), _TL("Save table"), File_Name.c_str()), true);
+	SG_UI_Msg_Add(CSG_String::Format("%s: %s...", _TL("Save table"), File_Name.c_str()), true);
 
 	//-----------------------------------------------------
 	if( Format <= TABLE_FILETYPE_Undefined || Format > TABLE_FILETYPE_DBase )
@@ -138,30 +133,28 @@ bool CSG_Table::Save(const CSG_String &File_Name, int Format, const SG_Char *Sep
 		{
 			Format	= TABLE_FILETYPE_DBase;
 		}
-		else if( SG_File_Cmp_Extension(File_Name, SG_T("csv")) )
+		else
 		{
 			Format	= TABLE_FILETYPE_Text;
 
-			if( Separator == NULL || *Separator == '\0' )
+			if( Separator == '\0' )
 			{
-				sSeparator	= SG_T(",");	// comma separated values
+				Separator	= SG_File_Cmp_Extension(File_Name, SG_T("csv")) ? ',' : '\t';	// comma separated values or tab spaced text
 			}
 		}
-		else //if( SG_File_Cmp_Extension(File_Name, SG_T("txt")) )
-		{
-			Format	= TABLE_FILETYPE_Text;
-		}
 	}
 
 	//-----------------------------------------------------
+	bool	bResult	= false;
+
 	switch( Format )
 	{
 	case TABLE_FILETYPE_Text:
-		bResult	= _Save_Text (File_Name, true , sSeparator);
+		bResult	= _Save_Text (File_Name, true , Separator);
 		break;
 
 	case TABLE_FILETYPE_Text_NoHeadLine:
-		bResult	= _Save_Text (File_Name, false, sSeparator);
+		bResult	= _Save_Text (File_Name, false, Separator);
 		break;
 
 	case TABLE_FILETYPE_DBase:
@@ -200,10 +193,31 @@ bool CSG_Table::Save(const CSG_String &File_Name, int Format, const SG_Char *Sep
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
-bool CSG_Table::_Load_Text(const CSG_String &File_Name, bool bHeadline, const SG_Char *Separator)
+int CSG_Table::_Load_Text_Trim(CSG_String &String, const SG_Char Separator)
 {
-	int			i, iField;
-	long		fLength;
+	for(size_t i=0; i<String.Length(); i++)
+	{
+		SG_Char	c	= String[i];
+
+		if( c == Separator || (c != ' ' && c != '\t' && c != '\n' && c != '\v' && c != '\f' && c != '\r') )
+		{
+			if( i > 0 )
+			{
+				String	= String.Right(String.Length() - i);
+			}
+
+			return( i );
+		}
+	}
+
+	return( 0 );
+}
+
+//---------------------------------------------------------
+bool CSG_Table::_Load_Text(const CSG_String &File_Name, bool bHeadline, const SG_Char Separator)
+{
+	int			iField;
+	sLong		fLength;
 	CSG_String	sLine, sField;
 	CSG_File	Stream;
 	CSG_Table	Table;
@@ -225,30 +239,28 @@ bool CSG_Table::_Load_Text(const CSG_String &File_Name, bool bHeadline, const SG
 	}
 
 	//-----------------------------------------------------
-	sLine	+= Separator;
+	_Load_Text_Trim(sLine, Separator);
 
-	while( (i = sLine.Find(Separator)) >= 0 )
+	while( !sLine.is_Empty() )
 	{
-		sField.Clear();
-
-		if( bHeadline )
+		if( sLine[0] == '\"' )	// value in quotas
 		{
-			sField	= sLine.Left(i);
-
-			if( sField[0] == SG_T('\"') && sField[(int)(sField.Length() - 1)] == SG_T('\"') )	// remove quota
-			{
-				sField	= sField.AfterFirst('\"').BeforeLast('\"');
-			}
+			sField	= sLine.AfterFirst('\"').BeforeFirst('\"');
+			sLine	= sLine.AfterFirst('\"').AfterFirst ('\"');
+		}
+		else
+		{
+			sField	= sLine.BeforeFirst(Separator);
 		}
 
-		if( sField.Length() == 0 )
+		sLine	= sLine.AfterFirst(Separator);	_Load_Text_Trim(sLine, Separator);
+
+		if( !bHeadline || sField.Length() == 0 )
 		{
-			sField.Printf(SG_T("F%02d"), Table.Get_Field_Count() + 1);
+			sField.Printf("F%02d", Table.Get_Field_Count() + 1);
 		}
 
 		Table.Add_Field(sField, SG_DATATYPE_String);
-
-		sLine.Remove(0, i + 1);
 	}
 
 	//-----------------------------------------------------
@@ -264,47 +276,44 @@ bool CSG_Table::_Load_Text(const CSG_String &File_Name, bool bHeadline, const SG
 		Stream.Seek_Start();
 	}
 
-	while( Stream.Read_Line(sLine) && sLine.Length() > 0 && SG_UI_Process_Set_Progress(Stream.Tell(), fLength) )
+	while( Stream.Read_Line(sLine) && sLine.Length() > 0 && SG_UI_Process_Set_Progress((double)Stream.Tell(), (double)fLength) )
 	{
 		CSG_Table_Record	*pRecord	= Table.Add_Record();
 
-		sLine	+= Separator;
+		_Load_Text_Trim(sLine, Separator);
 
-		for(iField=0; iField<Table.Get_Field_Count(); iField++)
+		for(iField=0; iField<Table.Get_Field_Count() && !sLine.is_Empty(); iField++)
 		{
-			if( (i = sLine.Find(Separator)) >= 0 )
+			if( sLine[0] == '\"' )	// value in quotas
 			{
-				sField	= sLine.Left(i);
+				sField	= sLine.AfterFirst('\"').BeforeFirst('\"');
+				sLine	= sLine.AfterFirst('\"').AfterFirst ('\"');
 
-				if( sField[0] == SG_T('\"') && sField[(int)(sField.Length() - 1)] == SG_T('\"') )	// remove quota
-				{
-					sField	= sField.AfterFirst('\"').BeforeLast('\"');
+				Type[iField]	= SG_DATATYPE_String;
+			}
+			else
+			{
+				sField	= sLine.BeforeFirst(Separator);
+			}
+
+			sLine	= sLine.AfterFirst(Separator);	_Load_Text_Trim(sLine, Separator);
 
+			//---------------------------------------------
+			if( Type[iField] != SG_DATATYPE_String && !sField.is_Empty() )
+			{
+				double	Value;
+
+				if( sField.asDouble(Value) == false )
+				{
 					Type[iField]	= SG_DATATYPE_String;
 				}
-
-				if( Type[iField] != SG_DATATYPE_String && sField.Length() > 0 )
+				else if( Type[iField] != SG_DATATYPE_Double && Value - (int)Value != 0.0 )
 				{
-					double	Value;
-
-					if( SG_SSCANF(sField, SG_T("%lf"), &Value) != 1 )
-					{
-						Type[iField]	= SG_DATATYPE_String;
-					}
-					else if( Type[iField] != SG_DATATYPE_Double && Value - (int)Value != 0.0 )
-					{
-						Type[iField]	= SG_DATATYPE_Double;
-					}
+					Type[iField]	= SG_DATATYPE_Double;
 				}
-
-				pRecord->Set_Value(iField, sField);
-
-				sLine.Remove(0, i + 1);
-			}
-			else
-			{
-				break;
 			}
+
+			pRecord->Set_Value(iField, sField);
 		}
 	}
 
@@ -347,7 +356,7 @@ bool CSG_Table::_Load_Text(const CSG_String &File_Name, bool bHeadline, const SG
 }
 
 //---------------------------------------------------------
-bool CSG_Table::_Save_Text(const CSG_String &File_Name, bool bHeadline, const SG_Char *Separator)
+bool CSG_Table::_Save_Text(const CSG_String &File_Name, bool bHeadline, const SG_Char Separator)
 {
 	int			iField, iRecord;
 	CSG_File	Stream;
@@ -358,7 +367,7 @@ bool CSG_Table::_Save_Text(const CSG_String &File_Name, bool bHeadline, const SG
 		{
 			for(iField=0; iField<Get_Field_Count(); iField++)
 			{
-				Stream.Printf(SG_T("%s%s"), Get_Field_Name(iField), iField < Get_Field_Count() - 1 ? Separator : SG_T("\n"));
+				Stream.Printf(SG_T("%s%c"), Get_Field_Name(iField), iField < Get_Field_Count() - 1 ? Separator : '\n');
 			}
 
 			for(iRecord=0; iRecord<Get_Record_Count() && SG_UI_Process_Set_Progress(iRecord, Get_Record_Count()); iRecord++)
@@ -380,7 +389,7 @@ bool CSG_Table::_Save_Text(const CSG_String &File_Name, bool bHeadline, const SG
 						}
 					}
 
-					Stream.Printf(SG_T("%s"), iField < Get_Field_Count() - 1 ? Separator : SG_T("\n"));
+					Stream.Printf(SG_T("%c"), iField < Get_Field_Count() - 1 ? Separator : '\n');
 				}
 			}
 
diff --git a/src/saga_core/saga_api/table_selection.cpp b/src/saga_core/saga_api/table_selection.cpp
index 81371bf..4461126 100644
--- a/src/saga_core/saga_api/table_selection.cpp
+++ b/src/saga_core/saga_api/table_selection.cpp
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: table_selection.cpp 1921 2014-01-09 10:24:11Z oconrad $
+ * Version $Id: table_selection.cpp 2700 2015-11-24 17:18:29Z oconrad $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -73,17 +73,75 @@
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
+bool CSG_Table::_Add_Selection(size_t iRecord)
+{
+	if( m_Selection.Inc_Array() )
+	{
+		return( _Set_Selection(iRecord, m_Selection.Get_Size() - 1) );
+	}
+
+	return( false );
+}
+
+//---------------------------------------------------------
+bool CSG_Table::_Set_Selection(size_t iRecord, size_t Index)
+{
+	if( Index < m_Selection.Get_Size() )
+	{
+		*((size_t *)m_Selection.Get_Entry(Index))	= iRecord;
+
+		return( true );
+	}
+
+	return( false );
+}
+
+//---------------------------------------------------------
+bool CSG_Table::_Del_Selection(size_t iRecord)
+{
+	for(size_t i=0; i<Get_Selection_Count(); i++)
+	{
+		if( iRecord == Get_Selection_Index(i) )
+		{
+			size_t	*Selection	= (size_t *)m_Selection.Get_Array();
+
+			for(size_t j=i+1; j<Get_Selection_Count(); i++, j++)
+			{
+				Selection[i]	= Selection[j];
+			}
+
+			m_Selection.Dec_Array();
+
+			return( true );
+		}
+	}
+
+	return( false );
+}
+
+
+///////////////////////////////////////////////////////////
+//														 //
+//														 //
+//														 //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
 bool CSG_Table::_Destroy_Selection(void)
 {
-	if( m_nSelected > 0 )
+	if( Get_Selection_Count() > 0 )
 	{
-		for(int iRecord=0; iRecord<m_nSelected; iRecord++)
+		for(size_t iRecord=0; iRecord<Get_Selection_Count(); iRecord++)
 		{
-			m_Records[m_Selected[iRecord]]->Set_Selected(false);
+			CSG_Table_Record	*pRecord	= Get_Selection(iRecord);
+
+			if( pRecord )
+			{
+				pRecord->Set_Selected(false);
+			}
 		}
 
-		SG_FREE_SAFE(m_Selected);
-		m_nSelected	= 0;
+		m_Selection.Set_Array(0);
 	}
 
 	return( true );
@@ -115,27 +173,13 @@ bool CSG_Table::Select(int iRecord, bool bInvert)
 	{
 		pRecord->Set_Selected(true);
 
-		m_Selected	= (int *)SG_Realloc(m_Selected, (m_nSelected + 1) * sizeof(int));
-		m_Selected[m_nSelected++]	= iRecord;
+		_Add_Selection(iRecord);
 	}
-	else
+	else // if( pRecord->is_Selected() == true )
 	{
 		pRecord->Set_Selected(false);
 
-		m_nSelected--;
-
-		for(int i=0; i<m_nSelected; i++)
-		{
-			if( iRecord == m_Selected[i] )
-			{
-				for(; i<m_nSelected; i++)
-				{
-					m_Selected[i]	= m_Selected[i + 1];
-				}
-			}
-		}
-
-		m_Selected	= (int *)SG_Realloc(m_Selected, m_nSelected * sizeof(int));
+		_Del_Selection(iRecord);
 	}
 
 	return( true );
@@ -157,24 +201,24 @@ bool CSG_Table::Select(CSG_Table_Record *pRecord, bool bInvert)
 //---------------------------------------------------------
 int CSG_Table::Del_Selection(void)
 {
-	if( m_nSelected <= 0 )
-	{
-		return( 0 );
-	}
+	int	n	= 0;
 
-	int		i, n	= 0;
-
-	for(i=m_nRecords-1; i>=0; i--)
+	if( Get_Selection_Count() > 0 )
 	{
-		if( m_Records[i]->is_Selected() && Del_Record(i) )
+		for(int i=m_nRecords-1; i>=0; i--)
 		{
-			n++;
-		}
-	}
+			if( m_Records[i]->is_Selected() )
+			{
+				m_Records[i]->Set_Selected(false);
 
-	SG_FREE_SAFE(m_Selected);
+				Del_Record(i);
 
-	m_nSelected	= 0;
+				n++;
+			}
+		}
+
+		m_Selection.Set_Array(0);
+	}
 
 	return( n );
 }
@@ -182,14 +226,13 @@ int CSG_Table::Del_Selection(void)
 //---------------------------------------------------------
 int CSG_Table::Inv_Selection(void)
 {
-	CSG_Table_Record	**pRecord	= m_Records + 0;
-
 	if( Get_Record_Count() > 0 )
 	{
-		m_nSelected	= m_nRecords - m_nSelected;
-		m_Selected	= (int *)SG_Realloc(m_Selected, m_nSelected * sizeof(int));
+		m_Selection.Set_Array((size_t)m_nRecords - m_Selection.Get_Size());
+
+		CSG_Table_Record	**pRecord	= m_Records + 0;
 
-		for(int i=0, j=0; i<m_nRecords; i++, pRecord++)
+		for(size_t i=0, n=0; i<(size_t)m_nRecords && n<Get_Selection_Count(); i++, pRecord++)
 		{
 			if( (*pRecord)->is_Selected() )
 			{
@@ -199,7 +242,7 @@ int CSG_Table::Inv_Selection(void)
 			{
 				(*pRecord)->Set_Selected(true);
 
-				m_Selected[j++]	= i;
+				_Set_Selection(i, n++);
 			}
 		}
 	}
diff --git a/src/saga_core/saga_cmd/module_library.cpp b/src/saga_core/saga_cmd/module_library.cpp
index 790b943..49fd3cd 100644
--- a/src/saga_core/saga_cmd/module_library.cpp
+++ b/src/saga_core/saga_cmd/module_library.cpp
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: module_library.cpp 2624 2015-09-30 15:33:53Z oconrad $
+ * Version $Id: module_library.cpp 2708 2015-12-01 16:16:14Z oconrad $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -386,9 +386,16 @@ bool CCMD_Module::_Get_Parameters(CSG_Parameters *pParameters, bool bInitialize)
 	}
 
 	//-----------------------------------------------------
-	int		i;
+	return( _Get_Options(pParameters, bInitialize)	// options might 'disable' some input, so check all options before the input is checked!
+		&&  _Get_Input  (pParameters)
+		&&  _Get_Options(pParameters, false)		// setting input might have reset some options, so check options one more time!
+	);
+}
 
-	for(i=0; i<pParameters->Get_Count(); i++)
+//---------------------------------------------------------
+bool CCMD_Module::_Get_Options(CSG_Parameters *pParameters, bool bInitialize)
+{
+	for(int i=0; i<pParameters->Get_Count(); i++)
 	{
 		CSG_Parameter	*pParameter	= pParameters->Get_Parameter(i);
 
@@ -554,10 +561,16 @@ bool CCMD_Module::_Get_Parameters(CSG_Parameters *pParameters, bool bInitialize)
 		}
 	}
 
+	//-----------------------------------------------------
 	m_pModule->Update_Parameter_States();
 
-	//-----------------------------------------------------
-	for(i=0; i<pParameters->Get_Count(); i++)
+	return( true );
+}
+
+//---------------------------------------------------------
+bool CCMD_Module::_Get_Input(CSG_Parameters *pParameters)
+{
+	for(int i=0; i<pParameters->Get_Count(); i++)
 	{
 		CSG_Parameter	*pParameter	= pParameters->Get_Parameter(i);
 
@@ -668,6 +681,8 @@ bool CCMD_Module::_Load_Input(CSG_Parameter *pParameter)
 			pParameter->asList()->Add_Item(SG_Get_Data_Manager().Find(&FileName, false));
 		}
 		while( FileNames.Length() > 0 );
+
+		pParameter->has_Changed();
 	}
 
 	return( true );
diff --git a/src/saga_core/saga_cmd/module_library.h b/src/saga_core/saga_cmd/module_library.h
index 388112d..a8ca282 100644
--- a/src/saga_core/saga_cmd/module_library.h
+++ b/src/saga_core/saga_cmd/module_library.h
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: module_library.h 2598 2015-09-23 14:12:34Z oconrad $
+ * Version $Id: module_library.h 2708 2015-12-01 16:16:14Z oconrad $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -113,7 +113,10 @@ private:
 	wxString					_Get_ID					(CSG_Parameter  *pParameter, const wxString &Modifier = "");
 
 	bool						_Set_Parameters			(CSG_Parameters *pParameters);
+
 	bool						_Get_Parameters			(CSG_Parameters *pParameters, bool bInitialize);
+	bool						_Get_Options			(CSG_Parameters *pParameters, bool bInitialize);
+	bool						_Get_Input				(CSG_Parameters *pParameters);
 
 	bool						_Load_Input				(CSG_Parameter  *pParameter);
 	bool						_Save_Output			(CSG_Parameters *pParameters);
diff --git a/src/saga_core/saga_cmd/saga_cmd.cpp b/src/saga_core/saga_cmd/saga_cmd.cpp
index 383c0ba..916411f 100644
--- a/src/saga_core/saga_cmd/saga_cmd.cpp
+++ b/src/saga_core/saga_cmd/saga_cmd.cpp
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: saga_cmd.cpp 2418 2015-02-19 20:58:24Z oconrad $
+ * Version $Id: saga_cmd.cpp 2675 2015-11-04 10:39:23Z oconrad $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -678,7 +678,8 @@ void		Print_Help		(void)
 	CMD_Print(
 		"under GNU General Public License (GPL)\n"
 		"\n"
-		"____________________________\n"
+		"_____________________________________________________________________________\n"
+		"\n"
 		"Usage:\n"
 		"\n"
 		"saga_cmd [-h, --help]\n"
@@ -686,11 +687,15 @@ void		Print_Help		(void)
 		"saga_cmd [-b, --batch]\n"
 		"saga_cmd [-d, --docs]\n"
 #ifdef _OPENMP
-		"saga_cmd [-f, --flags][=qrsilpxo][-s, --story][=#][-c, --cores][=#] <LIBRARY> <MODULE> <OPTIONS>\n"
-		"saga_cmd [-f, --flags][=qrsilpxo][-s, --story][=#][-c, --cores][=#] <SCRIPT>\n"
+		"saga_cmd [-f, --flags][=qrsilpxo][-s, --story][=#][-c, --cores][=#]\n"
+		"  <LIBRARY> <MODULE> <OPTIONS>\n"
+		"saga_cmd [-f, --flags][=qrsilpxo][-s, --story][=#][-c, --cores][=#]\n"
+		"  <SCRIPT>\n"
 #else
-		"saga_cmd [-f, --flags][=qrsilpxo][-s, --story][=#] <LIBRARY> <MODULE> <module specific options...>\n"
-		"saga_cmd [-f, --flags][=qrsilpxo][-s, --story][=#] <SCRIPT>\n"
+		"saga_cmd [-f, --flags][=qrsilpxo][-s, --story][=#]\n"
+		"  <LIBRARY> <MODULE> <OPTIONS>\n"
+		"saga_cmd [-f, --flags][=qrsilpxo][-s, --story][=#]\n"
+		"  <SCRIPT>\n"
 #endif
 		"\n"
 		"[-h], [--help]   : help on usage\n"
@@ -710,18 +715,19 @@ void		Print_Help		(void)
 		"  p              : load projections dictionary\n"
 		"  x              : use XML markups for synopses and messages\n"
 		"  o              : load old style naming\n"
-		"\n"
 		"<LIBRARY>        : name of the library\n"
 		"<MODULE>         : either name or index of the tool\n"
 		"<OPTIONS>        : tool specific options\n"
 		"<SCRIPT>         : saga cmd script file with one or more tool calls\n"
 		"\n"
-		"____________________________\n"
+		"_____________________________________________________________________________\n"
+		"\n"
 		"Example:\n"
 		"\n"
 		"  saga_cmd -f=s ta_lighting 0 -ELEVATION=c:\\dem.sgrd -SHADE=c:\\shade.sgrd\n"
 		"\n"
-		"____________________________\n"
+		"_____________________________________________________________________________\n"
+		"\n"
 		"Tool libraries in the \'modules\' subdirectory of the SAGA installation\n"
 		"will be loaded automatically. Additional directories can be specified\n"
 		"by adding the environment variable \'SAGA_MLB\' and let it point to one\n"
@@ -732,7 +738,19 @@ void		Print_Help		(void)
 		"script file. Calling saga_cmd with the option \'-b\' or \'--batch\' will\n"
 		"create an example of a DOS batch script file, which might be a good starting\n"
 		"point for the implementation of your own specific work flows.\n"
-		"____________________________\n"
+		"\n"
+		"_____________________________________________________________________________\n"
+		"\n"
+		"Please provide the following reference in your work if you are using SAGA:\n"
+		"\n"
+		"Conrad, O., Bechtel, B., Bock, M., Dietrich, H., Fischer, E., Gerlitz, L.,\n"
+		"  Wehberg, J., Wichmann, V., and Boehner, J. (2015):\n"
+		"  System for Automated Geoscientific Analyses (SAGA) v. 2.1.4.\n"
+		"  Geosci. Model Dev., 8, 1991-2007, doi:10.5194/gmd-8-1991-2015.\n"
+		"\n"
+		"  http://www.geosci-model-dev.net/8/1991/2015/gmd-8-1991-2015.html\n"
+		"\n"
+		"_____________________________________________________________________________\n"
 	);
 }
 
diff --git a/src/saga_core/saga_gui/Makefile.am b/src/saga_core/saga_gui/Makefile.am
index 4d1b793..f7b23ec 100644
--- a/src/saga_core/saga_gui/Makefile.am
+++ b/src/saga_core/saga_gui/Makefile.am
@@ -1,5 +1,5 @@
 #
-# $Id: Makefile.am 2138 2014-06-05 16:21:45Z manfred-e $
+# $Id: Makefile.am 2696 2015-11-23 18:35:08Z oconrad $
 #
 INCS = -I.. -I.
 if DEBUG
@@ -22,6 +22,7 @@ bin_PROGRAMS = saga_gui
 saga_gui_SOURCES =\
 active.cpp\
 active_attributes.cpp\
+active_attributes_control.cpp\
 active_description.cpp\
 active_history.cpp\
 active_HTMLExtraInfo.cpp\
@@ -46,6 +47,7 @@ dlg_list_table.cpp\
 dlg_list_tin.cpp\
 dlg_parameters.cpp\
 dlg_table.cpp\
+dlg_table_control.cpp\
 dlg_text.cpp\
 helper.cpp\
 info.cpp\
@@ -119,6 +121,7 @@ wksp_tin.cpp\
 wksp_tin_manager.cpp\
 active.h\
 active_attributes.h\
+active_attributes_control.h\
 active_description.h\
 active_history.h\
 active_HTMLExtraInfo.h\
@@ -143,6 +146,7 @@ dlg_list_table.h\
 dlg_list_tin.h\
 dlg_parameters.h\
 dlg_table.h\
+dlg_table_control.h\
 dlg_text.h\
 helper.h\
 info.h\
diff --git a/src/saga_core/saga_gui/Makefile.in b/src/saga_core/saga_gui/Makefile.in
index ffb1340..1c22bee 100644
--- a/src/saga_core/saga_gui/Makefile.in
+++ b/src/saga_core/saga_gui/Makefile.in
@@ -105,6 +105,7 @@ am__installdirs = "$(DESTDIR)$(bindir)" "$(DESTDIR)$(appdatadir)" \
 	"$(DESTDIR)$(pkgdatadir)"
 PROGRAMS = $(bin_PROGRAMS)
 am_saga_gui_OBJECTS = active.$(OBJEXT) active_attributes.$(OBJEXT) \
+	active_attributes_control.$(OBJEXT) \
 	active_description.$(OBJEXT) active_history.$(OBJEXT) \
 	active_HTMLExtraInfo.$(OBJEXT) active_legend.$(OBJEXT) \
 	active_parameters.$(OBJEXT) callback.$(OBJEXT) \
@@ -117,41 +118,41 @@ am_saga_gui_OBJECTS = active.$(OBJEXT) active_attributes.$(OBJEXT) \
 	dlg_list_pointcloud.$(OBJEXT) dlg_list_shapes.$(OBJEXT) \
 	dlg_list_table.$(OBJEXT) dlg_list_tin.$(OBJEXT) \
 	dlg_parameters.$(OBJEXT) dlg_table.$(OBJEXT) \
-	dlg_text.$(OBJEXT) helper.$(OBJEXT) info.$(OBJEXT) \
-	info_messages.$(OBJEXT) parameters_control.$(OBJEXT) \
-	parameters_properties.$(OBJEXT) project.$(OBJEXT) \
-	res_commands.$(OBJEXT) res_controls.$(OBJEXT) \
-	res_dialogs.$(OBJEXT) res_images.$(OBJEXT) saga.$(OBJEXT) \
-	saga_frame.$(OBJEXT) saga_frame_droptarget.$(OBJEXT) \
-	view_base.$(OBJEXT) view_histogram.$(OBJEXT) \
-	view_layout.$(OBJEXT) view_layout_control.$(OBJEXT) \
-	view_layout_info.$(OBJEXT) view_layout_printout.$(OBJEXT) \
-	view_map.$(OBJEXT) view_map_3d.$(OBJEXT) \
-	view_map_3d_panel.$(OBJEXT) view_map_control.$(OBJEXT) \
-	view_ruler.$(OBJEXT) view_scatterplot.$(OBJEXT) \
-	view_table.$(OBJEXT) view_table_control.$(OBJEXT) \
-	view_table_diagram.$(OBJEXT) wksp.$(OBJEXT) \
-	wksp_base_control.$(OBJEXT) wksp_base_item.$(OBJEXT) \
-	wksp_base_manager.$(OBJEXT) wksp_data_control.$(OBJEXT) \
-	wksp_data_item.$(OBJEXT) wksp_data_layers.$(OBJEXT) \
-	wksp_data_manager.$(OBJEXT) wksp_data_menu_file.$(OBJEXT) \
-	wksp_data_menu_files.$(OBJEXT) wksp_grid.$(OBJEXT) \
-	wksp_grid_manager.$(OBJEXT) wksp_grid_system.$(OBJEXT) \
-	wksp_layer.$(OBJEXT) wksp_layer_classify.$(OBJEXT) \
-	wksp_layer_legend.$(OBJEXT) wksp_map.$(OBJEXT) \
-	wksp_map_buttons.$(OBJEXT) wksp_map_control.$(OBJEXT) \
-	wksp_map_dc.$(OBJEXT) wksp_map_graticule.$(OBJEXT) \
-	wksp_map_layer.$(OBJEXT) wksp_map_manager.$(OBJEXT) \
-	wksp_module.$(OBJEXT) wksp_module_control.$(OBJEXT) \
-	wksp_module_library.$(OBJEXT) wksp_module_manager.$(OBJEXT) \
-	wksp_module_menu.$(OBJEXT) wksp_pointcloud.$(OBJEXT) \
-	wksp_pointcloud_manager.$(OBJEXT) wksp_shapes.$(OBJEXT) \
-	wksp_shapes_edit.$(OBJEXT) wksp_shapes_line.$(OBJEXT) \
-	wksp_shapes_manager.$(OBJEXT) wksp_shapes_point.$(OBJEXT) \
-	wksp_shapes_points.$(OBJEXT) wksp_shapes_polygon.$(OBJEXT) \
-	wksp_shapes_type.$(OBJEXT) wksp_table.$(OBJEXT) \
-	wksp_table_manager.$(OBJEXT) wksp_tin.$(OBJEXT) \
-	wksp_tin_manager.$(OBJEXT)
+	dlg_table_control.$(OBJEXT) dlg_text.$(OBJEXT) \
+	helper.$(OBJEXT) info.$(OBJEXT) info_messages.$(OBJEXT) \
+	parameters_control.$(OBJEXT) parameters_properties.$(OBJEXT) \
+	project.$(OBJEXT) res_commands.$(OBJEXT) \
+	res_controls.$(OBJEXT) res_dialogs.$(OBJEXT) \
+	res_images.$(OBJEXT) saga.$(OBJEXT) saga_frame.$(OBJEXT) \
+	saga_frame_droptarget.$(OBJEXT) view_base.$(OBJEXT) \
+	view_histogram.$(OBJEXT) view_layout.$(OBJEXT) \
+	view_layout_control.$(OBJEXT) view_layout_info.$(OBJEXT) \
+	view_layout_printout.$(OBJEXT) view_map.$(OBJEXT) \
+	view_map_3d.$(OBJEXT) view_map_3d_panel.$(OBJEXT) \
+	view_map_control.$(OBJEXT) view_ruler.$(OBJEXT) \
+	view_scatterplot.$(OBJEXT) view_table.$(OBJEXT) \
+	view_table_control.$(OBJEXT) view_table_diagram.$(OBJEXT) \
+	wksp.$(OBJEXT) wksp_base_control.$(OBJEXT) \
+	wksp_base_item.$(OBJEXT) wksp_base_manager.$(OBJEXT) \
+	wksp_data_control.$(OBJEXT) wksp_data_item.$(OBJEXT) \
+	wksp_data_layers.$(OBJEXT) wksp_data_manager.$(OBJEXT) \
+	wksp_data_menu_file.$(OBJEXT) wksp_data_menu_files.$(OBJEXT) \
+	wksp_grid.$(OBJEXT) wksp_grid_manager.$(OBJEXT) \
+	wksp_grid_system.$(OBJEXT) wksp_layer.$(OBJEXT) \
+	wksp_layer_classify.$(OBJEXT) wksp_layer_legend.$(OBJEXT) \
+	wksp_map.$(OBJEXT) wksp_map_buttons.$(OBJEXT) \
+	wksp_map_control.$(OBJEXT) wksp_map_dc.$(OBJEXT) \
+	wksp_map_graticule.$(OBJEXT) wksp_map_layer.$(OBJEXT) \
+	wksp_map_manager.$(OBJEXT) wksp_module.$(OBJEXT) \
+	wksp_module_control.$(OBJEXT) wksp_module_library.$(OBJEXT) \
+	wksp_module_manager.$(OBJEXT) wksp_module_menu.$(OBJEXT) \
+	wksp_pointcloud.$(OBJEXT) wksp_pointcloud_manager.$(OBJEXT) \
+	wksp_shapes.$(OBJEXT) wksp_shapes_edit.$(OBJEXT) \
+	wksp_shapes_line.$(OBJEXT) wksp_shapes_manager.$(OBJEXT) \
+	wksp_shapes_point.$(OBJEXT) wksp_shapes_points.$(OBJEXT) \
+	wksp_shapes_polygon.$(OBJEXT) wksp_shapes_type.$(OBJEXT) \
+	wksp_table.$(OBJEXT) wksp_table_manager.$(OBJEXT) \
+	wksp_tin.$(OBJEXT) wksp_tin_manager.$(OBJEXT)
 saga_gui_OBJECTS = $(am_saga_gui_OBJECTS)
 saga_gui_DEPENDENCIES = ../saga_api/libsaga_api.la \
 	../saga_gdi/libsaga_gdi.la
@@ -458,7 +459,7 @@ top_builddir = @top_builddir@
 top_srcdir = @top_srcdir@
 
 #
-# $Id: Makefile.am 2138 2014-06-05 16:21:45Z manfred-e $
+# $Id: Makefile.am 2696 2015-11-23 18:35:08Z oconrad $
 #
 INCS = -I.. -I.
 @DEBUG_TRUE at DBGFLAGS = -g -DDEBUG
@@ -472,6 +473,7 @@ BASEFLAGS = -fPIC -D_SAGA_LINUX -D_TYPEDEF_BYTE -D_TYPEDEF_WORD -D_SAGA_DONOTUSE
 saga_gui_SOURCES = \
 active.cpp\
 active_attributes.cpp\
+active_attributes_control.cpp\
 active_description.cpp\
 active_history.cpp\
 active_HTMLExtraInfo.cpp\
@@ -496,6 +498,7 @@ dlg_list_table.cpp\
 dlg_list_tin.cpp\
 dlg_parameters.cpp\
 dlg_table.cpp\
+dlg_table_control.cpp\
 dlg_text.cpp\
 helper.cpp\
 info.cpp\
@@ -569,6 +572,7 @@ wksp_tin.cpp\
 wksp_tin_manager.cpp\
 active.h\
 active_attributes.h\
+active_attributes_control.h\
 active_description.h\
 active_history.h\
 active_HTMLExtraInfo.h\
@@ -593,6 +597,7 @@ dlg_list_table.h\
 dlg_list_tin.h\
 dlg_parameters.h\
 dlg_table.h\
+dlg_table_control.h\
 dlg_text.h\
 helper.h\
 info.h\
@@ -770,6 +775,7 @@ distclean-compile:
 @AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/active.Po at am__quote@
 @AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/active_HTMLExtraInfo.Po at am__quote@
 @AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/active_attributes.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/active_attributes_control.Po at am__quote@
 @AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/active_description.Po at am__quote@
 @AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/active_history.Po at am__quote@
 @AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/active_legend.Po at am__quote@
@@ -793,6 +799,7 @@ distclean-compile:
 @AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/dlg_list_tin.Po at am__quote@
 @AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/dlg_parameters.Po at am__quote@
 @AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/dlg_table.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/dlg_table_control.Po at am__quote@
 @AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/dlg_text.Po at am__quote@
 @AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/helper.Po at am__quote@
 @AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/info.Po at am__quote@
diff --git a/src/saga_core/saga_gui/active_attributes.cpp b/src/saga_core/saga_gui/active_attributes.cpp
index 68d1e7f..e19edbc 100644
--- a/src/saga_core/saga_gui/active_attributes.cpp
+++ b/src/saga_core/saga_gui/active_attributes.cpp
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: active_attributes.cpp 2074 2014-03-31 10:32:12Z oconrad $
+ * Version $Id: active_attributes.cpp 2709 2015-12-01 16:39:59Z oconrad $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -70,9 +70,9 @@
 #include "res_dialogs.h"
 
 #include "wksp_layer.h"
-#include "view_table_control.h"
 
 #include "active_attributes.h"
+#include "active_attributes_control.h"
 
 
 ///////////////////////////////////////////////////////////
@@ -105,45 +105,30 @@ END_EVENT_TABLE()
 
 //---------------------------------------------------------
 CACTIVE_Attributes::CACTIVE_Attributes(wxWindow *pParent)
-	: wxPanel(pParent, ID_WND_INFO_ATTRIBUTES)//, wxDefaultPosition, wxDefaultSize, wxSUNKEN_BORDER)
+	: wxPanel(pParent, ID_WND_INFO_ATTRIBUTES, wxDefaultPosition, wxDefaultSize, wxSUNKEN_BORDER)
 {
-	m_pAttributes	= new CSG_Table;
-	m_pControl		= new CVIEW_Table_Control(this, m_pAttributes, TABLE_CTRL_FIXED_TABLE|TABLE_CTRL_COL1ISLABEL);
-
 	m_pItem			= NULL;
 
-	//-----------------------------------------------------
+	m_pControl		= new CActive_Attributes_Control(this);
+
 	m_Btn_Apply		= new wxButton(this, ID_BTN_APPLY	, CTRL_Get_Name(ID_BTN_APPLY)	, wxPoint(0, 0));
 	m_Btn_Restore	= new wxButton(this, ID_BTN_RESTORE	, CTRL_Get_Name(ID_BTN_RESTORE)	, wxPoint(0, 0));
 
-	m_btn_height	= m_Btn_Apply->GetDefaultSize().y;
+	m_Btn_Height	= m_Btn_Apply->GetDefaultSize().y;
 
 	m_pSelections	= new wxChoice(this, ID_COMBOBOX_SELECT, wxDefaultPosition, wxDefaultSize, 0, NULL, 0);
-
-	//-----------------------------------------------------
-	m_pAttributes->Set_Modified(false);
 }
 
 //---------------------------------------------------------
 CACTIVE_Attributes::~CACTIVE_Attributes(void)
-{
-	delete(m_pAttributes);
-}
+{}
 
 
 ///////////////////////////////////////////////////////////
 //														 //
-//														 //
-//														 //
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
-void CACTIVE_Attributes::On_Size(wxSizeEvent &WXUNUSED(event))
-{
-	_Set_Positions();
-}
-
-//---------------------------------------------------------
 #define BUTTON_DIST			1
 #define BUTTON_DIST2		2 * BUTTON_DIST
 
@@ -153,24 +138,24 @@ void CACTIVE_Attributes::On_Size(wxSizeEvent &WXUNUSED(event))
 void CACTIVE_Attributes::_Set_Positions(void)
 {
 	int		nButtons	= 2;
-	wxRect	r(wxPoint(0, 0), GetSize());
+	wxRect	r(GetClientSize());
 
 	if( m_pSelections->GetCount() > 0 )
 	{
-		m_pSelections->SetSize(0, 0, r.GetWidth(), m_btn_height - BUTTON_DIST);
+		m_pSelections->SetSize(0, 0, r.GetWidth(), m_Btn_Height - BUTTON_DIST);
 
-		r.SetTop(m_btn_height);
-		r.SetHeight(r.GetHeight() - m_btn_height * 2);
+		r.SetTop(m_Btn_Height);
+		r.SetHeight(r.GetHeight() - m_Btn_Height * 2);
 	}
 	else
 	{
-		r.SetHeight(r.GetHeight() - m_btn_height);
+		r.SetHeight(r.GetHeight() - m_Btn_Height);
 	}
 
 	m_pControl->SetSize(r);
 
 	r.SetTop(r.GetBottom() + BUTTON_DIST2);
-	r.SetHeight(m_btn_height - BUTTON_DIST);
+	r.SetHeight(m_Btn_Height - BUTTON_DIST);
 	r.SetWidth(r.GetWidth() / nButtons - BUTTON_DIST2);
 	r.SetLeft(BUTTON_DIST);
 
@@ -178,11 +163,15 @@ void CACTIVE_Attributes::_Set_Positions(void)
 	SET_BTN_POS(m_Btn_Restore);
 }
 
+//---------------------------------------------------------
+void CACTIVE_Attributes::On_Size(wxSizeEvent &WXUNUSED(event))
+{
+	_Set_Positions();
+}
+
 
 ///////////////////////////////////////////////////////////
 //														 //
-//														 //
-//														 //
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
@@ -193,7 +182,7 @@ void CACTIVE_Attributes::On_Apply(wxCommandEvent &event)
 
 void CACTIVE_Attributes::On_Apply_UI(wxUpdateUIEvent &event)
 {
-	event.Enable(m_pAttributes->is_Modified());
+	event.Enable(m_pControl->Get_Table()->is_Modified());
 }
 
 //---------------------------------------------------------
@@ -204,14 +193,12 @@ void CACTIVE_Attributes::On_Restore(wxCommandEvent &event)
 
 void CACTIVE_Attributes::On_Restore_UI(wxUpdateUIEvent &event)
 {
-	event.Enable(m_pAttributes->is_Modified());
+	event.Enable(m_pControl->Get_Table()->is_Modified());
 }
 
 
 ///////////////////////////////////////////////////////////
 //														 //
-//														 //
-//														 //
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
@@ -229,8 +216,6 @@ void CACTIVE_Attributes::On_Choice(wxCommandEvent &event)
 
 ///////////////////////////////////////////////////////////
 //														 //
-//														 //
-//														 //
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
@@ -269,8 +254,8 @@ void CACTIVE_Attributes::Set_Attributes(void)
 
 	if( m_pItem && m_pItem->Edit_Get_Attributes()->is_Valid() )
 	{
-		m_pAttributes->Assign(m_pItem->Edit_Get_Attributes());
-		m_pAttributes->Set_Modified(false);
+		m_pControl->Get_Table()->Assign(m_pItem->Edit_Get_Attributes());
+		m_pControl->Get_Table()->Set_Modified(false);
 
 		if( _Get_Table() && _Get_Table()->Get_Selection_Count() > 1 )
 		{
@@ -284,13 +269,10 @@ void CACTIVE_Attributes::Set_Attributes(void)
 	}
 	else
 	{
-		m_pAttributes->Destroy();
+		m_pControl->Get_Table()->Destroy();
 	}
 
-	m_pAttributes->Set_Modified(false);
-
-	m_pControl->Set_Labeling(_Get_Table() != NULL);
-
+	m_pControl->Set_Row_Labeling(_Get_Table() != NULL);
 	m_pControl->Update_Table();
 
 	m_pSelections->Show(m_pSelections->GetCount() > 1);
@@ -303,16 +285,14 @@ void CACTIVE_Attributes::Set_Attributes(void)
 
 ///////////////////////////////////////////////////////////
 //														 //
-//														 //
-//														 //
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
 void CACTIVE_Attributes::Save_Changes(bool bConfirm)
 {
-	if( m_pItem && m_pAttributes->is_Modified() && (!bConfirm || DLG_Message_Confirm(_TL("Save changes?"), _TL("Attributes"))) )
+	if( m_pItem && m_pControl->Get_Table()->is_Modified() && (!bConfirm || DLG_Message_Confirm(_TL("Save changes?"), _TL("Attributes"))) )
 	{
-		m_pItem->Edit_Get_Attributes()->Assign_Values(m_pAttributes);
+		m_pItem->Edit_Get_Attributes()->Assign_Values(m_pControl->Get_Table());
 		m_pItem->Edit_Set_Attributes();
 
 		Set_Attributes();
diff --git a/src/saga_core/saga_gui/active_attributes.h b/src/saga_core/saga_gui/active_attributes.h
index 7e8576b..6f1f2c6 100644
--- a/src/saga_core/saga_gui/active_attributes.h
+++ b/src/saga_core/saga_gui/active_attributes.h
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: active_attributes.h 2014 2014-02-24 14:47:32Z oconrad $
+ * Version $Id: active_attributes.h 2694 2015-11-20 16:43:15Z oconrad $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -90,40 +90,38 @@ public:
 	CACTIVE_Attributes(wxWindow *pParent);
 	virtual ~CACTIVE_Attributes(void);
 
-	void						On_Size				(wxSizeEvent     &event);
+	void								On_Size				(wxSizeEvent     &event);
 
-	void						On_Choice			(wxCommandEvent  &event);
+	void								On_Choice			(wxCommandEvent  &event);
 
-	void						On_Apply			(wxCommandEvent  &event);
-	void						On_Apply_UI			(wxUpdateUIEvent &event);
-	void						On_Restore			(wxCommandEvent  &event);
-	void						On_Restore_UI		(wxUpdateUIEvent &event);
+	void								On_Apply			(wxCommandEvent  &event);
+	void								On_Apply_UI			(wxUpdateUIEvent &event);
+	void								On_Restore			(wxCommandEvent  &event);
+	void								On_Restore_UI		(wxUpdateUIEvent &event);
 
-	void						Set_Item			(class CWKSP_Layer *pItem);
+	void								Set_Item			(class CWKSP_Layer *pItem);
 
-	void						Set_Attributes		(void);
+	void								Set_Attributes		(void);
 
-	void						Save_Changes		(bool bConfirm);
+	void								Save_Changes		(bool bConfirm);
 
 
 protected:
 
-	int							m_btn_height;
+	int									m_Btn_Height;
 
-	class wxButton				*m_Btn_Restore, *m_Btn_Apply;
+	class wxButton						*m_Btn_Restore, *m_Btn_Apply;
 
-	class wxChoice				*m_pSelections;
+	class wxChoice						*m_pSelections;
 
-	class CSG_Table				*m_pAttributes;
-	
-	class CVIEW_Table_Control	*m_pControl;
+	class CActive_Attributes_Control	*m_pControl;
 
-	class CWKSP_Layer			*m_pItem;
+	class CWKSP_Layer					*m_pItem;
 
 
-	void						_Set_Positions		(void);
+	void								_Set_Positions		(void);
 
-	class CSG_Table *			_Get_Table			(void);
+	class CSG_Table *					_Get_Table			(void);
 
 
 //---------------------------------------------------------
diff --git a/src/saga_core/saga_gui/active_attributes_control.cpp b/src/saga_core/saga_gui/active_attributes_control.cpp
new file mode 100644
index 0000000..06d834c
--- /dev/null
+++ b/src/saga_core/saga_gui/active_attributes_control.cpp
@@ -0,0 +1,560 @@
+/**********************************************************
+ * Version $Id: active_attributes_control.cpp 2665 2015-10-28 12:55:25Z oconrad $
+ *********************************************************/
+
+///////////////////////////////////////////////////////////
+//                                                       //
+//                         SAGA                          //
+//                                                       //
+//      System for Automated Geoscientific Analyses      //
+//                                                       //
+//                    User Interface                     //
+//                                                       //
+//                    Program: SAGA                      //
+//                                                       //
+//-------------------------------------------------------//
+//                                                       //
+//            active_attributes_control.cpp              //
+//                                                       //
+//          Copyright (C) 2015 by Olaf Conrad            //
+//                                                       //
+//-------------------------------------------------------//
+//                                                       //
+// This file is part of 'SAGA - System for Automated     //
+// Geoscientific Analyses'. SAGA 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; version 2 of the License.   //
+//                                                       //
+// SAGA 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,       //
+// write to the Free Software Foundation, Inc.,          //
+// 51 Franklin Street, 5th Floor, Boston, MA 02110-1301, //
+// USA.                                                  //
+//                                                       //
+//-------------------------------------------------------//
+//                                                       //
+//    contact:    Olaf Conrad                            //
+//                Institute of Geography                 //
+//                University of Hamburg                  //
+//                Germany                                //
+//                                                       //
+//    e-mail:     oconrad at saga-gis.org                   //
+//                                                       //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+
+
+///////////////////////////////////////////////////////////
+//														 //
+//														 //
+//														 //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+#include <wx/window.h>
+#include <wx/filename.h>
+
+#include <saga_api/saga_api.h>
+
+#include "res_commands.h"
+#include "res_dialogs.h"
+
+#include "active.h"
+#include "active_attributes.h"
+#include "active_attributes_control.h"
+
+#include "helper.h"
+
+#include "wksp_data_manager.h"
+#include "wksp_data_item.h"
+
+
+///////////////////////////////////////////////////////////
+//														 //
+//														 //
+//														 //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+IMPLEMENT_CLASS(CActive_Attributes_Control, wxGrid)
+
+//---------------------------------------------------------
+BEGIN_EVENT_TABLE(CActive_Attributes_Control, wxGrid)
+	EVT_SIZE					(CActive_Attributes_Control::On_Size)
+	EVT_KEY_DOWN				(CActive_Attributes_Control::On_Key)
+
+	EVT_GRID_EDITOR_SHOWN		(CActive_Attributes_Control::On_Edit_Start)
+	EVT_GRID_EDITOR_HIDDEN		(CActive_Attributes_Control::On_Edit_Stop)
+	EVT_GRID_CELL_CHANGED		(CActive_Attributes_Control::On_Changed)
+	EVT_GRID_CELL_LEFT_CLICK	(CActive_Attributes_Control::On_LClick)
+	EVT_GRID_CELL_RIGHT_CLICK	(CActive_Attributes_Control::On_RClick)
+	EVT_GRID_LABEL_LEFT_CLICK	(CActive_Attributes_Control::On_LClick_Label)
+	EVT_GRID_LABEL_RIGHT_CLICK	(CActive_Attributes_Control::On_RClick_Label)
+
+	EVT_MENU					(ID_CMD_TABLE_FIELD_OPEN_APP	, CActive_Attributes_Control::On_Field_Open)
+	EVT_MENU					(ID_CMD_TABLE_FIELD_OPEN_DATA	, CActive_Attributes_Control::On_Field_Open)
+
+	EVT_MENU					(ID_CMD_TABLE_AUTOSIZE_COLS		, CActive_Attributes_Control::On_Autosize_Cols)
+	EVT_MENU					(ID_CMD_TABLE_AUTOSIZE_ROWS		, CActive_Attributes_Control::On_Autosize_Rows)
+END_EVENT_TABLE()
+
+
+///////////////////////////////////////////////////////////
+//														 //
+//														 //
+//														 //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+CActive_Attributes_Control::CActive_Attributes_Control(wxWindow *pParent)
+	: wxGrid(pParent, -1, wxDefaultPosition, wxDefaultSize, wxWANTS_CHARS)
+{
+	m_pTable	= new CSG_Table;
+	m_bEditing	= false;
+
+	SetRowLabelAlignment(wxALIGN_RIGHT, wxALIGN_CENTRE);
+
+	Set_Row_Labeling(false);
+
+	CreateGrid(0, m_pTable->Get_Field_Count());
+
+	Update_Table();
+}
+
+//---------------------------------------------------------
+CActive_Attributes_Control::~CActive_Attributes_Control(void)
+{
+	delete(m_pTable);
+}
+
+
+///////////////////////////////////////////////////////////
+//														 //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+void CActive_Attributes_Control::Set_Row_Labeling(bool bOn)
+{
+	if( bOn && m_Field_Offset == 0 )
+	{
+		m_Field_Offset	= 1;	// feature attributes
+	}
+	else if( !bOn && m_Field_Offset != 0 )
+	{
+		m_Field_Offset	= 0;	// grid cell values
+	}
+}
+
+
+///////////////////////////////////////////////////////////
+//														 //
+//														 //
+//														 //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+bool CActive_Attributes_Control::Update_Table(void)
+{
+	if( GetBatchCount() > 0 )
+	{
+		return( false );
+	}
+
+	BeginBatch();
+
+	//-----------------------------------------------------
+	int	Difference	= (m_pTable->Get_Field_Count() - m_Field_Offset) - GetNumberCols();
+
+	if( Difference > 0 )
+	{
+		AppendCols(Difference);
+	}
+	else if( (Difference = -Difference < GetNumberCols() ? -Difference : GetNumberCols()) > 0 )
+	{	// here is (or was!?) a memory leak - solution: use own wxGridTableBase derived grid table class
+		DeleteCols(0, Difference);
+	}
+
+	//-----------------------------------------------------
+	for(int iCol=0, iField=m_Field_Offset; iField<m_pTable->Get_Field_Count(); iCol++, iField++)
+	{
+		SetColLabelValue(iCol, m_pTable->Get_Field_Name(iField));
+
+		switch( m_pTable->Get_Field_Type(iField) )
+		{
+		default:
+		case SG_DATATYPE_Byte:
+		case SG_DATATYPE_Char:
+		case SG_DATATYPE_String:
+		case SG_DATATYPE_Date:
+		case SG_DATATYPE_Binary:
+			SetColFormatCustom(iCol, wxGRID_VALUE_STRING);
+			break;
+
+		case SG_DATATYPE_Bit:
+		case SG_DATATYPE_Word:
+		case SG_DATATYPE_Short:
+		case SG_DATATYPE_DWord:
+		case SG_DATATYPE_Int:
+		case SG_DATATYPE_ULong:
+		case SG_DATATYPE_Long:
+		case SG_DATATYPE_Color:
+			SetColFormatNumber(iCol);
+			break;
+
+		case SG_DATATYPE_Float:
+		case SG_DATATYPE_Double:
+			SetColFormatFloat(iCol);
+			break;
+		}
+	}
+
+	//-----------------------------------------------------
+	if( (Difference = m_pTable->Get_Count() - GetNumberRows()) > 0 )
+	{
+		AppendRows(Difference);
+	}
+	else if( Difference < 0 && (Difference = -Difference < GetNumberRows() ? -Difference : GetNumberRows()) > 0 )
+	{
+		DeleteRows(0, Difference);
+	}
+
+	//-------------------------------------------------
+	for(int iRecord=0; iRecord<m_pTable->Get_Count(); iRecord++)
+	{
+		_Set_Record(iRecord);
+	}
+
+	//-----------------------------------------------------
+	if( GetNumberCols() > 0 && GetNumberRows() > 0 )
+	{
+		SetRowLabelSize(wxGRID_AUTOSIZE);
+
+		if( m_Field_Offset )	// feature attributes
+		{
+			if( GetClientSize().x > GetRowLabelSize() )
+			{
+				SetColSize(0, GetClientSize().x - GetRowLabelSize());
+			}
+		}
+		else					// grid cell values
+		{
+			AutoSizeColumns();
+		}
+	}
+
+	Show(GetNumberRows() > 0);
+
+	m_pTable->Set_Modified(false);
+
+	//-----------------------------------------------------
+	EndBatch();
+
+	return( true );
+}
+
+//---------------------------------------------------------
+bool CActive_Attributes_Control::_Set_Record(int iRecord)
+{
+	CSG_Table_Record *pRecord	= m_pTable->Get_Record(iRecord);
+
+	if( m_Field_Offset )	// feature attributes
+	{
+		SetRowLabelValue(iRecord, pRecord->asString(0));
+	}
+	else					// grid cell values
+	{
+		SetRowLabelValue(iRecord, wxString::Format("%d", 1 + iRecord));
+	}
+
+	for(int iCol=0, iField=m_Field_Offset; iField<m_pTable->Get_Field_Count(); iCol++, iField++)
+	{
+		switch( m_pTable->Get_Field_Type(iField) )
+		{
+		default:
+			SetCellValue(iRecord, iCol, pRecord->is_NoData(iField) ? SG_T("") : pRecord->asString(iField));
+			break;
+
+		case SG_DATATYPE_Color:
+			SetCellBackgroundColour(iRecord, iCol, Get_Color_asWX(pRecord->asInt(iField)));
+			break;
+		}
+	}
+
+	if( pRecord->is_Selected() )
+	{
+		SelectRow(iRecord, true);
+	}
+
+	return( true );
+}
+
+
+///////////////////////////////////////////////////////////
+//														 //
+//														 //
+//														 //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+void CActive_Attributes_Control::On_Size(wxSizeEvent &event)//&WXUNUSED(event))
+{
+	if( m_Field_Offset )	// feature attributes
+	{
+		if( GetNumberCols() > 0 && GetClientSize().x > GetRowLabelSize() )
+		{
+			SetColSize(0, GetClientSize().x - GetRowLabelSize());
+		}
+	}
+
+	event.Skip();
+}
+
+//---------------------------------------------------------
+void CActive_Attributes_Control::On_Key(wxKeyEvent &event)
+{
+	event.Skip(true);
+
+	if( event.GetKeyCode() == WXK_RETURN && !m_bEditing )
+	{
+		event.Skip(false);
+
+		g_pACTIVE->Get_Attributes()->Save_Changes(false);
+	}
+}
+
+//---------------------------------------------------------
+void CActive_Attributes_Control::On_Edit_Start(wxGridEvent &event)
+{
+	m_bEditing	= true;
+
+	event.Skip();
+}
+
+//---------------------------------------------------------
+void CActive_Attributes_Control::On_Edit_Stop(wxGridEvent &event)
+{
+	m_bEditing	= false;
+
+	event.Skip();
+}
+
+//---------------------------------------------------------
+void CActive_Attributes_Control::On_Changed(wxGridEvent &event)
+{
+	CSG_Table_Record	*pRecord	= m_pTable->Get_Record(event.GetRow());
+
+	if( pRecord )
+	{
+		int	iField	= m_Field_Offset + event.GetCol();
+
+		if( iField >= m_Field_Offset && iField < m_pTable->Get_Field_Count() )
+		{
+			pRecord->Set_Value(iField, GetCellValue(event.GetRow(), event.GetCol()).wx_str());
+
+			SetCellValue(event.GetRow(), event.GetCol(), pRecord->asString(iField));
+		}
+	}
+}
+
+
+///////////////////////////////////////////////////////////
+//														 //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+void CActive_Attributes_Control::On_Autosize_Cols(wxCommandEvent &event)
+{
+	AutoSizeColumns(false);
+}
+
+//---------------------------------------------------------
+void CActive_Attributes_Control::On_Autosize_Rows(wxCommandEvent &event)
+{
+	AutoSizeRows(false);
+}
+
+
+///////////////////////////////////////////////////////////
+//														 //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+void CActive_Attributes_Control::On_LClick(wxGridEvent &event)
+{
+	int					iField		= m_Field_Offset + event.GetCol();
+	CSG_Table_Record	*pRecord	= m_pTable->Get_Record(event.GetRow());
+
+	//-----------------------------------------------------
+	if( event.AltDown() )
+	{
+		if( m_pTable->Get_Field_Type(iField) == SG_DATATYPE_String )
+		{
+			Open_Application(pRecord->asString(iField));
+		}
+	}
+
+	//-----------------------------------------------------
+	if( event.ControlDown() )
+	{
+		if( m_pTable->Get_Field_Type(iField) == SG_DATATYPE_String )
+		{
+			g_pData->Open   (pRecord->asString(iField));
+		}
+	}
+
+	//-----------------------------------------------------
+	else
+	{
+		if( pRecord && iField >= m_Field_Offset && iField < m_pTable->Get_Field_Count() && m_pTable->Get_Field_Type(iField) == SG_DATATYPE_Color )
+		{
+			long	lValue;
+
+			if( DLG_Color(lValue = pRecord->asInt(iField)) )
+			{
+				pRecord->Set_Value(iField, lValue);
+
+				SetCellBackgroundColour(event.GetRow(), event.GetCol(), Get_Color_asWX(pRecord->asInt(iField)));
+
+				ForceRefresh();
+			}
+		}
+	}
+
+	//-----------------------------------------------------
+	SetGridCursor(event.GetRow(), event.GetCol());
+}
+
+//---------------------------------------------------------
+void CActive_Attributes_Control::On_RClick(wxGridEvent &event)
+{
+	SetGridCursor(event.GetRow(), event.GetCol());
+
+	int					iField		= m_Field_Offset + event.GetCol();
+	CSG_Table_Record	*pRecord	= m_pTable->Get_Record(event.GetRow());
+
+	//-----------------------------------------------------
+	if( m_pTable->Get_Field_Type(iField) == SG_DATATYPE_String )
+	{
+		wxMenu	Menu;
+
+		CMD_Menu_Add_Item(&Menu, false, ID_CMD_TABLE_FIELD_OPEN_APP);
+
+		wxString	Value	= GetCellValue(event.GetRow(), event.GetCol());
+
+		if( _Get_DataSource(Value) )
+		{
+			CMD_Menu_Add_Item(&Menu, false, ID_CMD_TABLE_FIELD_OPEN_DATA);
+		}
+
+		PopupMenu(&Menu, event.GetPosition());
+	}
+}
+
+//---------------------------------------------------------
+void CActive_Attributes_Control::On_Field_Open(wxCommandEvent &event)
+{
+	int	iField	= m_Field_Offset + GetGridCursorCol();
+	int	iRecord	=                  GetGridCursorRow();
+
+	if( iField >= 0 && iField<m_pTable->Get_Field_Count() && iRecord >= 0 && iRecord < m_pTable->Get_Count() )
+	{
+		CSG_Table_Record	*pRecord	= m_pTable->Get_Record(iRecord);
+
+		if( event.GetId() == ID_CMD_TABLE_FIELD_OPEN_APP )
+		{
+			Open_Application(pRecord->asString(iField));
+		}
+
+		if( event.GetId() == ID_CMD_TABLE_FIELD_OPEN_DATA )
+		{
+			wxString	Value	= pRecord->asString(iField);
+
+			if( _Get_DataSource(Value) )
+			{
+				g_pData->Open   (Value);
+			}
+		}
+	}
+}
+
+//---------------------------------------------------------
+bool CActive_Attributes_Control::_Get_DataSource(wxString &Source)
+{
+	if( Source.Find("PGSQL:") == 0 || wxFileExists(Source) )
+	{
+		return( true );
+	}
+
+	if( g_pACTIVE->Get_Active_Data_Item() && g_pACTIVE->Get_Active_Data_Item()->Get_Object()->Get_File_Name(false) )
+	{
+		wxFileName	fn(Source), dir(g_pACTIVE->Get_Active_Data_Item()->Get_Object()->Get_File_Name(false));
+
+		if( fn.MakeAbsolute(dir.GetPath()) && fn.Exists() )
+		{
+			Source	= fn.GetFullPath();
+
+			return( true );
+		}
+	}
+
+	return( false );
+}
+
+
+///////////////////////////////////////////////////////////
+//														 //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+void CActive_Attributes_Control::On_LClick_Label(wxGridEvent &event)
+{
+	if( event.GetCol() >= 0 )
+	{
+		SetGridCursor(GetGridCursorRow(), event.GetCol());
+	}
+	else if( event.GetRow() >= 0 )
+	{
+		SetGridCursor(event.GetRow(), GetGridCursorCol());
+	}
+}
+
+//---------------------------------------------------------
+void CActive_Attributes_Control::On_RClick_Label(wxGridEvent &event)
+{
+	//-----------------------------------------------------
+	if( event.GetCol() != -1 )
+	{
+		wxMenu	Menu(_TL("Columns"));
+
+		CMD_Menu_Add_Item(&Menu, false, ID_CMD_TABLE_AUTOSIZE_COLS);
+
+		PopupMenu(&Menu, event.GetPosition().x, event.GetPosition().y - GetColLabelSize());
+	}
+
+	//-----------------------------------------------------
+	else if( event.GetRow() != -1 )
+	{
+		wxMenu	Menu(_TL("Rows"));
+
+		CMD_Menu_Add_Item(&Menu, false, ID_CMD_TABLE_AUTOSIZE_ROWS);
+
+		PopupMenu(&Menu, event.GetPosition().x - GetRowLabelSize(), event.GetPosition().y);
+	}
+}
+
+
+///////////////////////////////////////////////////////////
+//														 //
+//														 //
+//														 //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
diff --git a/src/saga_core/saga_gui/active_attributes.h b/src/saga_core/saga_gui/active_attributes_control.h
similarity index 71%
copy from src/saga_core/saga_gui/active_attributes.h
copy to src/saga_core/saga_gui/active_attributes_control.h
index 7e8576b..b64c0bf 100644
--- a/src/saga_core/saga_gui/active_attributes.h
+++ b/src/saga_core/saga_gui/active_attributes_control.h
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: active_attributes.h 2014 2014-02-24 14:47:32Z oconrad $
+ * Version $Id: active_attributes_control.h 2665 2015-10-28 12:55:25Z oconrad $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -14,9 +14,9 @@
 //                                                       //
 //-------------------------------------------------------//
 //                                                       //
-//                 ACTIVE_Attributes.h                   //
+//              active_attributes_control.h              //
 //                                                       //
-//          Copyright (C) 2005 by Olaf Conrad            //
+//          Copyright (C) 2015 by Olaf Conrad            //
 //                                                       //
 //-------------------------------------------------------//
 //                                                       //
@@ -42,9 +42,7 @@
 //                                                       //
 //    contact:    Olaf Conrad                            //
 //                Institute of Geography                 //
-//                University of Goettingen               //
-//                Goldschmidtstr. 5                      //
-//                37077 Goettingen                       //
+//                University of Hamburg                  //
 //                Germany                                //
 //                                                       //
 //    e-mail:     oconrad at saga-gis.org                   //
@@ -61,8 +59,8 @@
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
-#ifndef _HEADER_INCLUDED__SAGA_GUI__ACTIVE_Attributes_H
-#define _HEADER_INCLUDED__SAGA_GUI__ACTIVE_Attributes_H
+#ifndef _HEADER_INCLUDED__SAGA_GUI__active_attributes_control_H
+#define _HEADER_INCLUDED__SAGA_GUI__active_attributes_control_H
 
 
 ///////////////////////////////////////////////////////////
@@ -72,7 +70,7 @@
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
-#include <wx/panel.h>
+#include <wx/grid.h>
 
 
 ///////////////////////////////////////////////////////////
@@ -82,48 +80,49 @@
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
-class CACTIVE_Attributes : public wxPanel
+class CActive_Attributes_Control : public wxGrid
 {
-	DECLARE_CLASS(CACTIVE_Attributes)
+	DECLARE_CLASS(CActive_Attributes_Control)
 
 public:
-	CACTIVE_Attributes(wxWindow *pParent);
-	virtual ~CACTIVE_Attributes(void);
+	CActive_Attributes_Control(wxWindow *pParent);
+	virtual ~CActive_Attributes_Control(void);
 
-	void						On_Size				(wxSizeEvent     &event);
-
-	void						On_Choice			(wxCommandEvent  &event);
+	void						On_Field_Open		(wxCommandEvent  &event);
 
-	void						On_Apply			(wxCommandEvent  &event);
-	void						On_Apply_UI			(wxUpdateUIEvent &event);
-	void						On_Restore			(wxCommandEvent  &event);
-	void						On_Restore_UI		(wxUpdateUIEvent &event);
+	void						On_Autosize_Cols	(wxCommandEvent  &event);
+	void						On_Autosize_Rows	(wxCommandEvent  &event);
 
-	void						Set_Item			(class CWKSP_Layer *pItem);
+	void						On_Size				(wxSizeEvent     &event);
+	void						On_Key				(wxKeyEvent      &event);
 
-	void						Set_Attributes		(void);
+	void						On_Edit_Start		(wxGridEvent     &event);
+	void						On_Edit_Stop		(wxGridEvent     &event);
+	void						On_Changed			(wxGridEvent     &event);
+	void						On_LClick			(wxGridEvent     &event);
+	void						On_RClick			(wxGridEvent     &event);
+	void						On_LClick_Label		(wxGridEvent     &event);
+	void						On_RClick_Label		(wxGridEvent     &event);
 
-	void						Save_Changes		(bool bConfirm);
+	void						Set_Row_Labeling	(bool bOn);
 
+	class CSG_Table *			Get_Table			(void)	{	return( m_pTable );	}
 
-protected:
+	bool						Update_Table		(void);
 
-	int							m_btn_height;
 
-	class wxButton				*m_Btn_Restore, *m_Btn_Apply;
+private:
 
-	class wxChoice				*m_pSelections;
+	bool						m_bEditing;
 
-	class CSG_Table				*m_pAttributes;
-	
-	class CVIEW_Table_Control	*m_pControl;
+	int							m_Field_Offset;
 
-	class CWKSP_Layer			*m_pItem;
+	class CSG_Table				*m_pTable;
 
 
-	void						_Set_Positions		(void);
+	bool						_Set_Record			(int iRecord);
 
-	class CSG_Table *			_Get_Table			(void);
+	bool						_Get_DataSource		(wxString &Source);
 
 
 //---------------------------------------------------------
@@ -138,4 +137,4 @@ DECLARE_EVENT_TABLE()
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
-#endif // #ifndef _HEADER_INCLUDED__SAGA_GUI__ACTIVE_Attributes_H
+#endif // #ifndef _HEADER_INCLUDED__SAGA_GUI__active_attributes_control_H
diff --git a/src/saga_core/saga_gui/data_source.cpp b/src/saga_core/saga_gui/data_source.cpp
index 7148d75..a3031f5 100644
--- a/src/saga_core/saga_gui/data_source.cpp
+++ b/src/saga_core/saga_gui/data_source.cpp
@@ -130,7 +130,7 @@ END_EVENT_TABLE()
 
 //---------------------------------------------------------
 CData_Source::CData_Source(wxWindow *pParent)
-	: wxNotebook(pParent, ID_WND_DATA_SOURCE, wxDefaultPosition, wxDefaultSize, wxNB_TOP|wxNB_MULTILINE, _TL("Data Source"))
+	: wxNotebook(pParent, ID_WND_DATA_SOURCE, wxDefaultPosition, wxDefaultSize, wxNB_TOP|wxNB_MULTILINE, _TL("Data Sources"))
 {
 	g_pData_Source	= this;
 
@@ -142,14 +142,24 @@ CData_Source::CData_Source(wxWindow *pParent)
 	IMG_ADD_TO_NOTEBOOK(ID_IMG_NB_DATA_SOURCE_WEBSERVICE);
 
 	//-----------------------------------------------------
-	m_pFiles	= new CData_Source_Files(this);	m_pFiles->SetName(_TL("File System"));
+	bool	bFiles;
+
+	if( CONFIG_Read("/DATA", "SHOW_FILE_SOURCES", bFiles) && !bFiles )
+	{
+		m_pFiles	= NULL;
+	}
+	else
+	{
+		m_pFiles	= new CData_Source_Files(this);	m_pFiles->SetName(_TL("File System"));
+	}
+
 	m_pODBC		= new CData_Source_ODBC (this);	m_pODBC ->SetName(_TL("ODBC"));
 	m_pPgSQL	= new CData_Source_PgSQL(this);	m_pPgSQL->SetName(_TL("PostgreSQL"));
 
 #if defined(_SAGA_MSW)
-	m_pFiles->Hide();
-	m_pODBC ->Hide();
-	m_pPgSQL->Hide();
+	if( m_pFiles )	m_pFiles->Hide();
+	if( m_pODBC  )	m_pODBC ->Hide();
+	if( m_pPgSQL )	m_pPgSQL->Hide();
 #endif
 }
 
@@ -198,33 +208,36 @@ bool CData_Source::Set_Data_Source(CWKSP_Base_Item *pItem)
 	}
 
 	//-----------------------------------------------------
-	switch( pItem->Get_Type() )
+	if( m_pFiles )
 	{
-	default:
-		break;
-
-	case WKSP_ITEM_Map_Layer:
-		m_pFiles->SetPath(((CWKSP_Map_Layer      *)pItem)->Get_Layer()->Get_Object()->Get_File_Name());
-		break;
-
-	case WKSP_ITEM_Table:
-		m_pFiles->SetPath(((CWKSP_Table          *)pItem)->Get_Table()->Get_File_Name());
-		break;
-
-	case WKSP_ITEM_Shapes:
-	case WKSP_ITEM_TIN:
-	case WKSP_ITEM_PointCloud:
-	case WKSP_ITEM_Grid:
-		m_pFiles->SetPath(((CWKSP_Layer          *)pItem)->Get_Object()->Get_File_Name(false));
-		break;
-
-	case WKSP_ITEM_Module_Library:
-	//	m_pFiles->SetPath(((CWKSP_Module_Library *)pItem)->Get_File_Name());
-		break;
-
-	case WKSP_ITEM_Module:
-		m_pFiles->SetPath(((CWKSP_Module         *)pItem)->Get_File_Name());
-		break;
+		switch( pItem->Get_Type() )
+		{
+		case WKSP_ITEM_Table:
+			m_pFiles->SetPath(((CWKSP_Table          *)pItem)->Get_Table()->Get_File_Name());
+			break;
+
+		case WKSP_ITEM_Shapes:
+		case WKSP_ITEM_TIN:
+		case WKSP_ITEM_PointCloud:
+		case WKSP_ITEM_Grid:
+			m_pFiles->SetPath(((CWKSP_Layer          *)pItem)->Get_Object()->Get_File_Name(false));
+			break;
+
+		case WKSP_ITEM_Map_Layer:
+			m_pFiles->SetPath(((CWKSP_Map_Layer      *)pItem)->Get_Layer()->Get_Object()->Get_File_Name(false));
+			break;
+
+		case WKSP_ITEM_Module_Library:
+		//	m_pFiles->SetPath(((CWKSP_Module_Library *)pItem)->Get_File_Name());
+			break;
+
+		case WKSP_ITEM_Module:
+		//	m_pFiles->SetPath(((CWKSP_Module         *)pItem)->Get_File_Name());
+			break;
+
+		default:
+			break;
+		}
 	}
 
 	return( true );
@@ -256,6 +269,11 @@ bool CData_Source::Update_ODBC_Source(const wxString &Server)
 //---------------------------------------------------------
 bool CData_Source::_Show_Page(wxWindow *pPage)
 {
+	if( !pPage )
+	{
+		return( false );
+	}
+
 	int		Image_ID	= -1;
 
 	//-----------------------------------------------------
diff --git a/src/saga_core/saga_gui/data_source_pgsql.cpp b/src/saga_core/saga_gui/data_source_pgsql.cpp
index 56a0322..4983a10 100644
--- a/src/saga_core/saga_gui/data_source_pgsql.cpp
+++ b/src/saga_core/saga_gui/data_source_pgsql.cpp
@@ -170,6 +170,38 @@ enum
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
+bool	PGSQL_Connect			(const CSG_String &Host, const CSG_String &Port, const CSG_String &DBName)
+{
+	if( PGSQL_is_Connected(Host, Port, DBName) )
+	{
+		return( true );
+	}
+
+	wxString	Username = "postgres", Password = "postgres";
+
+	if( !DLG_Login(Username, Password, wxString::Format("%s: %s [%s:%s]", _TL("Connect to Database"), DBName.c_str(), Host.c_str(), Port.c_str())) )
+	{
+		return( false );
+	}
+
+	RUN_MODULE(DB_PGSQL_Get_Connection, false,	// CGet_Connection
+			SET_PARAMETER("PG_HOST", Host    )
+		&&	SET_PARAMETER("PG_PORT", Port    )
+		&&	SET_PARAMETER("PG_NAME", DBName  )
+		&&	SET_PARAMETER("PG_USER", Username)
+		&&	SET_PARAMETER("PG_PWD" , Password)
+	);
+
+	return( bResult );
+}
+
+//---------------------------------------------------------
+bool	PGSQL_is_Connected		(const CSG_String &Host, const CSG_String &Port, const CSG_String &DBName)
+{
+	return( PGSQL_is_Connected(DBName + " [" + Host + ":" + Port + "]") );
+}
+
+//---------------------------------------------------------
 bool	PGSQL_is_Connected		(const CSG_String &Server)
 {
 	CSG_Table	Connections;
diff --git a/src/saga_core/saga_gui/data_source_pgsql.h b/src/saga_core/saga_gui/data_source_pgsql.h
index fbbf961..9a57fa8 100644
--- a/src/saga_core/saga_gui/data_source_pgsql.h
+++ b/src/saga_core/saga_gui/data_source_pgsql.h
@@ -20,13 +20,13 @@
 //                                                       //
 //-------------------------------------------------------//
 //                                                       //
-// This file is part of 'MicroCity: Spatial Analysis and //
-// Simulation Framework'. MicroCity is free software;you //
+// This file is part of 'SAGA - System for Automated     //
+// Geoscientific Analyses'. SAGA 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; version 2 of the License.   //
 //                                                       //
-// MicroCity is distributed in the hope that it will be  //
+// SAGA 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        //
@@ -80,7 +80,9 @@
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
-bool	PGSQL_is_Connected		(const CSG_String  &Server);
+bool	PGSQL_Connect			(const CSG_String &Host, const CSG_String &Port, const CSG_String &DBName);
+bool	PGSQL_is_Connected		(const CSG_String &Host, const CSG_String &Port, const CSG_String &DBName);
+bool	PGSQL_is_Connected		(const CSG_String &Server);
 
 bool	PGSQL_has_Connections	(double vPostGIS = 0.0);
 bool	PGSQL_Get_Connections	(CSG_Strings &Servers, double vPostGIS = 0.0);
diff --git a/src/saga_core/saga_gui/dlg_about.cpp b/src/saga_core/saga_gui/dlg_about.cpp
index f0bdc9d..4132b11 100644
--- a/src/saga_core/saga_gui/dlg_about.cpp
+++ b/src/saga_core/saga_gui/dlg_about.cpp
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: dlg_about.cpp 2471 2015-04-19 09:32:08Z reklov_w $
+ * Version $Id: dlg_about.cpp 2693 2015-11-17 16:17:12Z oconrad $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -93,8 +93,6 @@ END_EVENT_TABLE()
 
 ///////////////////////////////////////////////////////////
 //														 //
-//														 //
-//														 //
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
@@ -106,29 +104,39 @@ CDLG_About::CDLG_About(void)
 	m_pControl	= new wxNotebook(this, -1, wxDefaultPosition, wxDefaultSize, wxNB_TOP|wxNB_MULTILINE);
 
 	//-----------------------------------------------------
-	m_pVersion	=
 	pText		= new wxTextCtrl(m_pControl, -1, wxT(""), wxDefaultPosition, wxDefaultSize, wxTE_MULTILINE|wxTE_READONLY|wxTE_CENTRE|wxTE_RICH|wxTE_AUTO_URL|wxBORDER_SUNKEN);
 	pText->AppendText(_Get_Version());
 	m_pControl->AddPage(pText, _TL("Version"), false, -1);
 	pText->ShowPosition(0);
 
 	//-----------------------------------------------------
+	pText		= new wxTextCtrl(m_pControl, -1, wxT(""), wxDefaultPosition, wxDefaultSize, wxTE_MULTILINE|wxTE_READONLY|wxTE_CENTRE|wxTE_RICH|wxTE_AUTO_URL|wxBORDER_SUNKEN);
+	pText->AppendText(_Get_Citation());
+	m_pControl->AddPage(pText, _TL("Citation"), false, -1);
+	pText->ShowPosition(0);
+
+	//-----------------------------------------------------
 	m_pControl->AddPage(new CDLG_About_Logo(m_pControl), _TL("Logo"), false, -1);
 
 	//-----------------------------------------------------
-	pText		= new wxTextCtrl(m_pControl, -1, wxT(""), wxDefaultPosition, wxDefaultSize, wxTE_MULTILINE|wxTE_READONLY|wxTE_CENTRE);
-	pText->AppendText(_Get_Acknowledgements());
-	m_pControl->AddPage(pText, _TL("Acknowledgements"), false, -1);
-	pText->ShowPosition(0);
+//	pText		= new wxTextCtrl(m_pControl, -1, wxT(""), wxDefaultPosition, wxDefaultSize, wxTE_MULTILINE|wxTE_READONLY|wxTE_CENTRE|wxTE_RICH|wxTE_AUTO_URL|wxBORDER_SUNKEN);
+//	pText->AppendText(_Get_Acknowledgements());
+//	m_pControl->AddPage(pText, _TL("Acknowledgements"), false, -1);
+//	pText->ShowPosition(0);
+
+//	acknowledgements tab has not been updated since ages.
+//	we remove it now, because we think it is not possible
+//	to pay adequate tribute to all contributors and supporters
+//	through this list. thanks a lot...
 
 	//-----------------------------------------------------
-	pText		= new wxTextCtrl(m_pControl, -1, wxT(""), wxDefaultPosition, wxDefaultSize, wxTE_MULTILINE|wxTE_READONLY|wxTE_CENTRE);
+	pText		= new wxTextCtrl(m_pControl, -1, wxT(""), wxDefaultPosition, wxDefaultSize, wxTE_MULTILINE|wxTE_READONLY|wxTE_CENTRE|wxTE_RICH|wxTE_AUTO_URL|wxBORDER_SUNKEN);
 	pText->AppendText(_Get_GPL());
 	m_pControl->AddPage(pText, SG_T("GPL"), false, -1);
 	pText->ShowPosition(0);
 
 	//-----------------------------------------------------
-	pText		= new wxTextCtrl(m_pControl, -1, wxT(""), wxDefaultPosition, wxDefaultSize, wxTE_MULTILINE|wxTE_READONLY|wxTE_CENTRE);
+	pText		= new wxTextCtrl(m_pControl, -1, wxT(""), wxDefaultPosition, wxDefaultSize, wxTE_MULTILINE|wxTE_READONLY|wxTE_CENTRE|wxTE_RICH|wxTE_AUTO_URL|wxBORDER_SUNKEN);
 	pText->AppendText(_Get_LGPL());
 	m_pControl->AddPage(pText, SG_T("LGPL"), false, -1);
 	pText->ShowPosition(0);
@@ -137,15 +145,9 @@ CDLG_About::CDLG_About(void)
 	Set_Positions();
 }
 
-//---------------------------------------------------------
-CDLG_About::~CDLG_About(void)
-{}
-
 
 ///////////////////////////////////////////////////////////
 //														 //
-//														 //
-//														 //
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
@@ -157,24 +159,22 @@ void CDLG_About::Set_Position(wxRect r)
 
 ///////////////////////////////////////////////////////////
 //														 //
-//														 //
-//														 //
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
 void CDLG_About::On_URL_Version(wxTextUrlEvent &event)
 {
-	if( !event.GetMouseEvent().Moving() )
+	if( event.GetMouseEvent().LeftDown() && !event.GetMouseEvent().Moving() )
 	{
-		Open_WebBrowser(m_pVersion->GetValue().Mid(event.GetURLStart(), event.GetURLEnd() - event.GetURLStart()));
+		wxString	Text	= ((wxTextCtrl *)event.GetEventObject())->GetValue();
+
+		Open_WebBrowser(Text.Mid(event.GetURLStart(), event.GetURLEnd() - event.GetURLStart()));
 	}
 }
 
 
 ///////////////////////////////////////////////////////////
 //														 //
-//														 //
-//														 //
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
@@ -241,20 +241,30 @@ wxString CDLG_About::_Get_Version(void)
 			"DJGPP"
 		#elif	defined(__DIGITALMARS__)
 			"Digital Mars"
-		#elif	defined(__MINGW32__)
-			"MinGW"
-		#elif	defined(__GNUWIN32__)
-			"Gnu-Win32 compiler"
-		#elif	defined(__GNUG__)
-			"Gnu C++"
 		#elif	defined(__MWERKS__)
 			"CodeWarrior MetroWerks compiler"
 		#elif	defined(__SUNCC__)
 			"Sun CC"
+		#elif	defined(__SUNPRO_CC)
+			"Oracle Solaris Studio"
 		#elif	defined(__SYMANTECC__)
 			"Symantec C++"
 		#elif	defined(__VISAGECPP__)
 			"IBM Visual Age (OS/2)"
+		#elif	defined(__IBMCPP__)
+			"IBM XL C/C++"
+		#elif	defined(__INTEL_COMPILER) || defined(__ICC)
+			"Intel ICC/ICPC"
+		#elif	defined(__PGI)
+			"Portland PGCC/PGCPP"
+		#elif	defined(__clang__)
+			"Clang/LLVM"
+		#elif	defined(__MINGW32__)
+			"MinGW"
+		#elif	defined(__GNUWIN32__)
+			"Gnu-Win32 compiler"
+		#elif	defined(__GNUG__)
+			"Gnu C++"
 		#elif	defined(__VISUALC__)	// The value of this macro corresponds to the compiler version: 1020 for 4.2 (the first supported version), 1100 for 5.0, 1200 for 6.0 and so on
 			#if   __VISUALC__ == 1020
 				"Microsoft Visual C++ 4.2"
@@ -291,6 +301,31 @@ wxString CDLG_About::_Get_Version(void)
 	return( s );
 }
 
+
+///////////////////////////////////////////////////////////
+//														 //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+wxString CDLG_About::_Get_Citation(void)
+{
+	return(
+		"\n"
+		"Please provide the following reference in your work if you are using SAGA:\n"
+		"\n_______________________\n\n"
+		"Conrad, O., Bechtel, B., Bock, M., Dietrich, H., Fischer, E., Gerlitz, L., Wehberg, J., Wichmann, V., and Boehner, J. (2015):\n"
+		"System for Automated Geoscientific Analyses (SAGA) v. 2.1.4.\n"
+		"Geosci. Model Dev., 8, 1991-2007, doi:10.5194/gmd-8-1991-2015.\n"
+		"\n_______________________\n\n"
+		"http://www.geosci-model-dev.net/8/1991/2015/gmd-8-1991-2015.html"
+	);
+}
+
+
+///////////////////////////////////////////////////////////
+//														 //
+///////////////////////////////////////////////////////////
+
 //---------------------------------------------------------
 wxString CDLG_About::_Get_Acknowledgements(void)
 {
diff --git a/src/saga_core/saga_gui/dlg_about.h b/src/saga_core/saga_gui/dlg_about.h
index 2e5dc6a..34ca91d 100644
--- a/src/saga_core/saga_gui/dlg_about.h
+++ b/src/saga_core/saga_gui/dlg_about.h
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: dlg_about.h 1921 2014-01-09 10:24:11Z oconrad $
+ * Version $Id: dlg_about.h 2675 2015-11-04 10:39:23Z oconrad $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -88,7 +88,6 @@ class CDLG_About : public CDLG_Base
 
 public:
 	CDLG_About(void);
-	virtual ~CDLG_About(void);
 
 	void						On_URL_Version			(wxTextUrlEvent &event);
 
@@ -102,10 +101,9 @@ private:
 
 	class wxNotebook			*m_pControl;
 
-	class wxTextCtrl			*m_pVersion;
-
 
 	wxString					_Get_Version			(void);
+	wxString					_Get_Citation			(void);
 	wxString					_Get_Acknowledgements	(void);
 
 	wxString					_Get_GPL				(void);
diff --git a/src/saga_core/saga_gui/dlg_table.cpp b/src/saga_core/saga_gui/dlg_table.cpp
index 660d056..e7f4b06 100644
--- a/src/saga_core/saga_gui/dlg_table.cpp
+++ b/src/saga_core/saga_gui/dlg_table.cpp
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: dlg_table.cpp 2041 2014-03-05 15:08:03Z oconrad $
+ * Version $Id: dlg_table.cpp 2694 2015-11-20 16:43:15Z oconrad $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -69,7 +69,7 @@
 #include "helper.h"
 
 #include "dlg_table.h"
-#include "view_table_control.h"
+#include "dlg_table_control.h"
 
 
 ///////////////////////////////////////////////////////////
@@ -88,6 +88,8 @@ BEGIN_EVENT_TABLE(CDLG_Table, CDLG_Base)
 	EVT_BUTTON			(ID_BTN_LOAD			, CDLG_Table::On_Load)
 	EVT_BUTTON			(ID_BTN_SAVE			, CDLG_Table::On_Save)
 	EVT_BUTTON			(ID_BTN_ADD				, CDLG_Table::On_Add)
+	EVT_BUTTON			(ID_BTN_TABLE_FROM_WKSP	, CDLG_Table::On_WKSP_Load)
+	EVT_BUTTON			(ID_BTN_TABLE_TO_WKSP	, CDLG_Table::On_WKSP_Save)
 	EVT_BUTTON			(ID_BTN_INSERT			, CDLG_Table::On_Insert)
 	EVT_BUTTON			(ID_BTN_DELETE			, CDLG_Table::On_Delete)
 	EVT_BUTTON			(ID_BTN_DELETE_ALL		, CDLG_Table::On_Delete_All)
@@ -105,12 +107,14 @@ END_EVENT_TABLE()
 CDLG_Table::CDLG_Table(CSG_Table *pTable, wxString Caption)
 	: CDLG_Base(-1, Caption)
 {
-	m_pTable_Orig	= pTable;
-	m_pTable		= new CSG_Table(*m_pTable_Orig);
-	m_pControl		= new CVIEW_Table_Control(this, m_pTable, TABLE_CTRL_FIXED_COLS);
+	m_pTable	= pTable;
+	m_pControl	= new CDLG_Table_Control(this, m_pTable);
 
 	Add_Button(ID_BTN_LOAD);
+	Add_Button(ID_BTN_TABLE_FROM_WKSP);
+	Add_Button(-1);
 	Add_Button(ID_BTN_SAVE);
+	Add_Button(ID_BTN_TABLE_TO_WKSP);
 	Add_Button(-1);
 	Add_Button(ID_BTN_ADD);
 	Add_Button(ID_BTN_INSERT);
@@ -128,9 +132,7 @@ CDLG_Table::CDLG_Table(CSG_Table *pTable, wxString Caption)
 
 //---------------------------------------------------------
 CDLG_Table::~CDLG_Table(void)
-{
-	delete(m_pTable);
-}
+{}
 
 
 ///////////////////////////////////////////////////////////
@@ -171,7 +173,7 @@ void CDLG_Table::Set_Position(wxRect r)
 //---------------------------------------------------------
 void CDLG_Table::Save_Changes(void)
 {
-	m_pTable_Orig->Assign(m_pTable);
+	m_pTable->Assign(m_pControl->Get_Table());
 }
 
 
@@ -208,6 +210,66 @@ void CDLG_Table::On_Save(wxCommandEvent &event)
 }
 
 //---------------------------------------------------------
+void CDLG_Table::On_WKSP_Load(wxCommandEvent &event)
+{
+	CSG_Data_Collection	*pTables	= SG_Get_Data_Manager().Get_Table();
+
+	if( pTables )
+	{
+		wxArrayString	Names;
+		CSG_Table		Index;
+
+		Index.Add_Field("INDEX", SG_DATATYPE_Int);
+
+		for(size_t i=0; i<pTables->Count(); i++)
+		{
+			CSG_Table	*pTable	= (CSG_Table *)pTables->Get(i);
+
+			if( pTable->is_Compatible(m_pTable) && pTable->Get_Count() > 0 )
+			{
+				Names.Add(pTable->Get_Name());
+
+				Index.Add_Record()->Set_Value(0, i);
+			}
+		}
+
+		if( Names.Count() > 0 )
+		{
+			wxSingleChoiceDialog	dlg(MDI_Get_Top_Window(), _TL("Tables"), _TL("Load from Workspace"), Names);
+
+			if( dlg.ShowModal() == wxID_OK )
+			{
+				m_pControl->Get_Table()->Assign_Values((CSG_Table *)pTables->Get(Index[dlg.GetSelection()].asInt(0)));
+				m_pControl->Update_Table();
+
+				Refresh();
+			}
+
+			return;
+		}
+	}
+
+	DLG_Message_Show(_TL("No compatible table has been found."), CTRL_Get_Name(ID_BTN_TABLE_FROM_WKSP));
+}
+
+//---------------------------------------------------------
+void CDLG_Table::On_WKSP_Save(wxCommandEvent &event)
+{
+	wxTextEntryDialog	dlg(MDI_Get_Top_Window(), _TL("Table Name"), _TL("Save to Workspace"), _TL("Table"));
+
+	if( dlg.ShowModal() == wxID_OK && !dlg.GetValue().IsEmpty() )
+	{
+		CSG_Table	*pTable	= SG_Create_Table(*m_pControl->Get_Table());
+
+		wxString	Name(dlg.GetValue());
+
+		pTable->Set_Name(&Name);
+
+		SG_Get_Data_Manager().Add(pTable);
+	}
+}
+
+//---------------------------------------------------------
 void CDLG_Table::On_Add(wxCommandEvent &event)
 {
 	m_pControl->Add_Record();
@@ -234,24 +296,26 @@ void CDLG_Table::On_Delete_All(wxCommandEvent &event)
 //---------------------------------------------------------
 void CDLG_Table::On_Colors(wxCommandEvent &event)
 {
-	if( m_pTable->Get_Count() > 0 )
+	if( m_pControl->Get_Table()->Get_Count() > 0 )
 	{
 		int		i;
 
-		CSG_Colors	Colors(m_pTable->Get_Count());
+		CSG_Table	*pTable	= m_pControl->Get_Table();
+
+		CSG_Colors	Colors(pTable->Get_Count());
 
-		for(i=0; i<m_pTable->Get_Count(); i++)
+		for(i=0; i<pTable->Get_Count(); i++)
 		{
-			Colors[i]	= m_pTable->Get_Record(i)->asInt(0);
+			Colors[i]	= pTable->Get_Record(i)->asInt(0);
 		}
 
 		if( DLG_Colors(&Colors) )
 		{
-			Colors.Set_Count(m_pTable->Get_Count());
+			Colors.Set_Count(pTable->Get_Count());
 
-			for(i=0; i<m_pTable->Get_Count(); i++)
+			for(i=0; i<pTable->Get_Count(); i++)
 			{
-				m_pTable->Get_Record(i)->Set_Value(0, Colors[i]);
+				pTable->Get_Record(i)->Set_Value(0, Colors[i]);
 			}
 
 			m_pControl->Update_Table();
diff --git a/src/saga_core/saga_gui/dlg_table.h b/src/saga_core/saga_gui/dlg_table.h
index 6d97cbd..b315886 100644
--- a/src/saga_core/saga_gui/dlg_table.h
+++ b/src/saga_core/saga_gui/dlg_table.h
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: dlg_table.h 2041 2014-03-05 15:08:03Z oconrad $
+ * Version $Id: dlg_table.h 2694 2015-11-20 16:43:15Z oconrad $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -93,9 +93,9 @@ public:
 
 protected:
 
-	class CSG_Table				*m_pTable, *m_pTable_Orig;
+	class CSG_Table				*m_pTable;
 
-	class CVIEW_Table_Control	*m_pControl;
+	class CDLG_Table_Control	*m_pControl;
 
 
 	void						On_Key			(wxKeyEvent     &event);
@@ -103,6 +103,9 @@ protected:
 	void						On_Load			(wxCommandEvent &event);
 	void						On_Save			(wxCommandEvent &event);
 
+	void						On_WKSP_Load	(wxCommandEvent &event);
+	void						On_WKSP_Save	(wxCommandEvent &event);
+
 	void						On_Add			(wxCommandEvent &event);
 	void						On_Insert		(wxCommandEvent &event);
 	void						On_Delete		(wxCommandEvent &event);
diff --git a/src/saga_core/saga_gui/dlg_table_control.cpp b/src/saga_core/saga_gui/dlg_table_control.cpp
new file mode 100644
index 0000000..d53323a
--- /dev/null
+++ b/src/saga_core/saga_gui/dlg_table_control.cpp
@@ -0,0 +1,772 @@
+/**********************************************************
+ * Version $Id: dlg_table_control.cpp 2665 2015-10-28 12:55:25Z oconrad $
+ *********************************************************/
+
+///////////////////////////////////////////////////////////
+//                                                       //
+//                         SAGA                          //
+//                                                       //
+//      System for Automated Geoscientific Analyses      //
+//                                                       //
+//                    User Interface                     //
+//                                                       //
+//                    Program: SAGA                      //
+//                                                       //
+//-------------------------------------------------------//
+//                                                       //
+//                 dlg_table_control.cpp                 //
+//                                                       //
+//          Copyright (C) 2015 by Olaf Conrad            //
+//                                                       //
+//-------------------------------------------------------//
+//                                                       //
+// This file is part of 'SAGA - System for Automated     //
+// Geoscientific Analyses'. SAGA 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; version 2 of the License.   //
+//                                                       //
+// SAGA 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,       //
+// write to the Free Software Foundation, Inc.,          //
+// 51 Franklin Street, 5th Floor, Boston, MA 02110-1301, //
+// USA.                                                  //
+//                                                       //
+//-------------------------------------------------------//
+//                                                       //
+//    contact:    Olaf Conrad                            //
+//                Institute of Geography                 //
+//                University of Hamburg                  //
+//                Germany                                //
+//                                                       //
+//    e-mail:     oconrad at saga-gis.org                   //
+//                                                       //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+
+
+///////////////////////////////////////////////////////////
+//														 //
+//														 //
+//														 //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+#include <wx/window.h>
+
+#include <saga_api/saga_api.h>
+
+#include "res_commands.h"
+#include "res_dialogs.h"
+
+#include "helper.h"
+
+#include "wksp_data_manager.h"
+
+#include "dlg_table_control.h"
+
+
+///////////////////////////////////////////////////////////
+//														 //
+//														 //
+//														 //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+IMPLEMENT_CLASS(CDLG_Table_Control, wxGrid)
+
+//---------------------------------------------------------
+BEGIN_EVENT_TABLE(CDLG_Table_Control, wxGrid)
+	EVT_SIZE					(CDLG_Table_Control::On_Size)
+	EVT_KEY_DOWN				(CDLG_Table_Control::On_Key)
+
+	EVT_GRID_EDITOR_SHOWN		(CDLG_Table_Control::On_Edit_Start)
+	EVT_GRID_EDITOR_HIDDEN		(CDLG_Table_Control::On_Edit_Stop)
+	EVT_GRID_CELL_CHANGED		(CDLG_Table_Control::On_Changed)
+	EVT_GRID_CELL_LEFT_CLICK	(CDLG_Table_Control::On_LClick)
+	EVT_GRID_CELL_RIGHT_CLICK	(CDLG_Table_Control::On_RClick)
+	EVT_GRID_LABEL_LEFT_CLICK	(CDLG_Table_Control::On_LClick_Label)
+	EVT_GRID_LABEL_LEFT_DCLICK	(CDLG_Table_Control::On_LDClick_Label)
+	EVT_GRID_LABEL_RIGHT_CLICK	(CDLG_Table_Control::On_RClick_Label)
+	EVT_GRID_RANGE_SELECT		(CDLG_Table_Control::On_Select)
+
+	EVT_MENU					(ID_CMD_TABLE_FIELD_SORT		, CDLG_Table_Control::On_Field_Sort)
+	EVT_UPDATE_UI				(ID_CMD_TABLE_FIELD_SORT		, CDLG_Table_Control::On_Field_Sort_UI)
+
+	EVT_MENU					(ID_CMD_TABLE_FIELD_OPEN_APP	, CDLG_Table_Control::On_Field_Open)
+	EVT_MENU					(ID_CMD_TABLE_FIELD_OPEN_DATA	, CDLG_Table_Control::On_Field_Open)
+
+	EVT_MENU					(ID_CMD_TABLE_RECORD_ADD		, CDLG_Table_Control::On_Record_Add)
+	EVT_UPDATE_UI				(ID_CMD_TABLE_RECORD_ADD		, CDLG_Table_Control::On_Record_Add_UI)
+	EVT_MENU					(ID_CMD_TABLE_RECORD_INS		, CDLG_Table_Control::On_Record_Ins)
+	EVT_UPDATE_UI				(ID_CMD_TABLE_RECORD_INS		, CDLG_Table_Control::On_Record_Ins_UI)
+	EVT_MENU					(ID_CMD_TABLE_RECORD_DEL		, CDLG_Table_Control::On_Record_Del)
+	EVT_UPDATE_UI				(ID_CMD_TABLE_RECORD_DEL		, CDLG_Table_Control::On_Record_Del_UI)
+	EVT_MENU					(ID_CMD_TABLE_RECORD_DEL_ALL	, CDLG_Table_Control::On_Record_Clr)
+
+	EVT_MENU					(ID_CMD_TABLE_AUTOSIZE_COLS		, CDLG_Table_Control::On_Autosize_Cols)
+	EVT_MENU					(ID_CMD_TABLE_AUTOSIZE_ROWS		, CDLG_Table_Control::On_Autosize_Rows)
+END_EVENT_TABLE()
+
+
+///////////////////////////////////////////////////////////
+//														 //
+//														 //
+//														 //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+CDLG_Table_Control::CDLG_Table_Control(wxWindow *pParent, CSG_Table *pTable)
+	: wxGrid(pParent, -1, wxDefaultPosition, wxDefaultSize, wxWANTS_CHARS|wxSUNKEN_BORDER)
+{
+	m_pTable	= new CSG_Table(*pTable);
+	m_bEditing	= false;
+
+	CreateGrid(0, m_pTable->Get_Field_Count(), wxGrid::wxGridSelectRows);
+
+	Update_Table();
+}
+
+//---------------------------------------------------------
+CDLG_Table_Control::~CDLG_Table_Control(void)
+{
+	delete(m_pTable);
+}
+
+
+///////////////////////////////////////////////////////////
+//														 //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+bool CDLG_Table_Control::Update_Table(void)
+{
+	if( GetBatchCount() > 0 )
+	{
+		return( false );
+	}
+
+	BeginBatch();
+
+	//-----------------------------------------------------
+	int	Difference	= (m_pTable->Get_Field_Count()) - GetNumberCols();
+
+	if( Difference > 0 )
+	{
+		AppendCols(Difference);
+	}
+	else if( (Difference = -Difference < GetNumberCols() ? -Difference : GetNumberCols()) > 0 )
+	{	// here is (or was!?) a memory leak - solution: use own wxGridTableBase derived grid table class
+		DeleteCols(0, Difference);
+	}
+
+	//-----------------------------------------------------
+	for(int iField=0; iField<m_pTable->Get_Field_Count(); iField++)
+	{
+		SetColLabelValue(iField, m_pTable->Get_Field_Name(iField));
+
+		switch( m_pTable->Get_Field_Type(iField) )
+		{
+		default:
+		case SG_DATATYPE_Byte:
+		case SG_DATATYPE_Char:
+		case SG_DATATYPE_String:
+		case SG_DATATYPE_Date:
+		case SG_DATATYPE_Binary:
+			SetColFormatCustom(iField, wxGRID_VALUE_STRING);
+			break;
+
+		case SG_DATATYPE_Bit:
+		case SG_DATATYPE_Word:
+		case SG_DATATYPE_Short:
+		case SG_DATATYPE_DWord:
+		case SG_DATATYPE_Int:
+		case SG_DATATYPE_ULong:
+		case SG_DATATYPE_Long:
+		case SG_DATATYPE_Color:
+			SetColFormatNumber(iField);
+			break;
+
+		case SG_DATATYPE_Float:
+		case SG_DATATYPE_Double:
+			SetColFormatFloat(iField);
+			break;
+		}
+	}
+
+	//-----------------------------------------------------
+	EndBatch();
+
+	return( _Set_Records() );
+}
+
+//---------------------------------------------------------
+bool CDLG_Table_Control::_Set_Records(void)
+{
+	BeginBatch();
+
+	ClearSelection();
+
+	//-----------------------------------------------------
+	int	Difference, nRecords	= m_pTable->Get_Count();
+
+	if( (Difference = nRecords - GetNumberRows()) > 0 )
+	{
+		AppendRows(Difference);
+	}
+	else if( Difference < 0 && (Difference = -Difference < GetNumberRows() ? -Difference : GetNumberRows()) > 0 )
+	{
+		DeleteRows(0, Difference);
+	}
+
+	//-----------------------------------------------------
+//	#pragma omp parallel for
+	for(int iRecord=0; iRecord<nRecords; iRecord++)
+	{
+		_Set_Record(iRecord, m_pTable->Get_Record_byIndex(iRecord));
+	}
+
+	//-----------------------------------------------------
+	EndBatch();
+
+	return( true );
+}
+
+//---------------------------------------------------------
+bool CDLG_Table_Control::_Set_Record(int iRecord, CSG_Table_Record *pRecord)
+{
+	SetRowLabelValue(iRecord, wxString::Format("%d", 1 + iRecord));
+
+	for(int iField=0; iField<m_pTable->Get_Field_Count(); iField++)
+	{
+		switch( m_pTable->Get_Field_Type(iField) )
+		{
+		default:
+			SetCellValue(iRecord, iField, pRecord->is_NoData(iField) ? SG_T("") : pRecord->asString(iField));
+			break;
+
+		case SG_DATATYPE_Color:
+			SetCellBackgroundColour(iRecord, iField, Get_Color_asWX(pRecord->asInt(iField)));
+			break;
+		}
+	}
+
+	if( pRecord->is_Selected() )
+	{
+		SelectRow(iRecord, true);
+	}
+
+	return( true );
+}
+
+
+///////////////////////////////////////////////////////////
+//														 //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+bool CDLG_Table_Control::Update_Sorting(int iField, int Direction)
+{
+	if( iField >= 0 && iField < m_pTable->Get_Field_Count() )
+	{
+		switch( Direction )
+		{
+		default:	m_pTable->Toggle_Index(iField);	break;
+		case 0:		m_pTable->Set_Index(iField, TABLE_INDEX_None      );	break;
+		case 1:		m_pTable->Set_Index(iField, TABLE_INDEX_Ascending );	break;
+		case 2:		m_pTable->Set_Index(iField, TABLE_INDEX_Descending);	break;
+		}
+
+		return( _Set_Records() );
+	}
+
+	return( false );
+}
+
+
+///////////////////////////////////////////////////////////
+//														 //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+bool CDLG_Table_Control::Add_Record(void)
+{
+	CSG_Table_Record	*pRecord	= m_pTable->Add_Record();
+
+	if( pRecord && AppendRows(1) )
+	{
+		_Set_Record(GetNumberRows() - 1, pRecord);
+
+		return( true );
+	}
+
+	return( false );
+}
+
+//---------------------------------------------------------
+bool CDLG_Table_Control::Ins_Record(void)
+{
+	int		iRecord	= GetGridCursorRow();
+
+	if( iRecord >= 0 && iRecord < GetNumberRows() )
+	{
+		InsertRows(iRecord);
+
+		_Set_Record(iRecord, m_pTable->Ins_Record(iRecord));
+
+		return( true );
+	}
+
+	return( false );
+}
+
+//---------------------------------------------------------
+bool CDLG_Table_Control::Del_Record(void)
+{
+	return( m_pTable->Del_Selection() && Update_Table() );
+}
+
+//---------------------------------------------------------
+bool CDLG_Table_Control::Del_Records(void)
+{
+	return( m_pTable->Del_Records() && Update_Table() );
+}
+
+
+///////////////////////////////////////////////////////////
+//														 //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+bool CDLG_Table_Control::Load(const wxString &File_Name)
+{
+	CSG_Table	Table(&File_Name);
+
+	bool	bResult	= Table.Get_Count() > 0
+		&& Table.Get_Field_Count() == m_pTable->Get_Field_Count()
+		&& m_pTable->Assign_Values(&Table)
+		&& Update_Table();
+
+	PROCESS_Set_Okay();
+
+	return( bResult );
+}
+
+//---------------------------------------------------------
+bool CDLG_Table_Control::Save(const wxString &File_Name, int Format)
+{
+	bool	bResult	= m_pTable->Save(&File_Name);
+
+	PROCESS_Set_Okay();
+
+	return( bResult );
+}
+
+
+///////////////////////////////////////////////////////////
+//														 //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+void CDLG_Table_Control::On_Size(wxSizeEvent &event)//&WXUNUSED(event))
+{
+	event.Skip();
+}
+
+//---------------------------------------------------------
+void CDLG_Table_Control::On_Key(wxKeyEvent &event)
+{
+	event.Skip(true);
+
+	if( event.GetKeyCode() == WXK_RETURN )
+	{
+		// nop
+	}
+}
+
+//---------------------------------------------------------
+void CDLG_Table_Control::On_Edit_Start(wxGridEvent &event)
+{
+	m_bEditing	= true;
+
+	event.Skip();
+}
+
+//---------------------------------------------------------
+void CDLG_Table_Control::On_Edit_Stop(wxGridEvent &event)
+{
+	m_bEditing	= false;
+
+	event.Skip();
+}
+
+//---------------------------------------------------------
+void CDLG_Table_Control::On_Changed(wxGridEvent &event)
+{
+	CSG_Table_Record	*pRecord	= m_pTable->Get_Record_byIndex(event.GetRow());
+
+	if( pRecord )
+	{
+		int	iField	= event.GetCol();
+
+		if( iField >= 0 && iField < m_pTable->Get_Field_Count() )
+		{
+			pRecord->Set_Value(iField, GetCellValue(event.GetRow(), event.GetCol()).wx_str());
+
+			SetCellValue(event.GetRow(), event.GetCol(), pRecord->asString(iField));
+		}
+	}
+}
+
+
+///////////////////////////////////////////////////////////
+//														 //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+void CDLG_Table_Control::On_Field_Sort(wxCommandEvent &event)
+{
+	CSG_String		sFields, sOrder;
+	CSG_Parameter	*pNode;
+	CSG_Parameters	P;
+
+	//-----------------------------------------------------
+	for(int i=0; i<m_pTable->Get_Field_Count(); i++)
+	{
+		sFields.Append(m_pTable->Get_Field_Name(i));	sFields.Append('|');
+	}
+
+	sOrder.Printf(SG_T("%s|%s|%s|"),
+		_TL("unsorted"),
+		_TL("ascending"),
+		_TL("descending")
+	);
+
+	//-----------------------------------------------------
+	P.Set_Name(_TL("Sort Table"));
+
+	pNode	= P.Add_Choice(NULL , "FIELD_1"	, _TL("Sort first by")	,	_TL(""),	sFields	, !m_pTable->is_Indexed() ? 0 : m_pTable->Get_Index_Field(0));
+	pNode	= P.Add_Choice(pNode, "ORDER_1"	, _TL("Direction")		,	_TL(""),	sOrder	, !m_pTable->is_Indexed() ? 1 : m_pTable->Get_Index_Order(0));
+
+	pNode	= P.Add_Choice(NULL , "FIELD_2"	, _TL("Sort second by")	,	_TL(""),	sFields	, !m_pTable->is_Indexed() ? 0 : m_pTable->Get_Index_Field(1));
+	pNode	= P.Add_Choice(pNode, "ORDER_2"	, _TL("Direction")		,	_TL(""),	sOrder	, !m_pTable->is_Indexed() ? 0 : m_pTable->Get_Index_Order(1));
+
+	pNode	= P.Add_Choice(NULL , "FIELD_3"	, _TL("Sort third by")	,	_TL(""),	sFields	, !m_pTable->is_Indexed() ? 0 : m_pTable->Get_Index_Field(2));
+	pNode	= P.Add_Choice(pNode, "ORDER_3"	, _TL("Direction")		,	_TL(""),	sOrder	, !m_pTable->is_Indexed() ? 0 : m_pTable->Get_Index_Order(2));
+
+	//-----------------------------------------------------
+	if( DLG_Parameters(&P) )
+	{
+		m_pTable->Set_Index(
+			P("FIELD_1")->asInt(), P("ORDER_1")->asInt() == 1 ? TABLE_INDEX_Ascending : P("ORDER_1")->asInt() == 2 ? TABLE_INDEX_Descending : TABLE_INDEX_None,
+			P("FIELD_2")->asInt(), P("ORDER_2")->asInt() == 1 ? TABLE_INDEX_Ascending : P("ORDER_2")->asInt() == 2 ? TABLE_INDEX_Descending : TABLE_INDEX_None,
+			P("FIELD_3")->asInt(), P("ORDER_3")->asInt() == 1 ? TABLE_INDEX_Ascending : P("ORDER_3")->asInt() == 2 ? TABLE_INDEX_Descending : TABLE_INDEX_None
+		);
+
+		_Set_Records();
+	}
+}
+
+void CDLG_Table_Control::On_Field_Sort_UI(wxUpdateUIEvent &event)
+{
+	event.Enable(m_pTable->Get_Field_Count() > 0 && m_pTable->Get_Record_Count() > 1);
+}
+
+
+///////////////////////////////////////////////////////////
+//														 //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+void CDLG_Table_Control::On_Record_Add(wxCommandEvent &event)
+{
+	Add_Record();
+}
+
+void CDLG_Table_Control::On_Record_Add_UI(wxUpdateUIEvent &event)
+{
+	event.Enable(!m_pTable->is_Indexed() && m_pTable->Get_ObjectType() == DATAOBJECT_TYPE_Table);
+}
+
+//---------------------------------------------------------
+void CDLG_Table_Control::On_Record_Ins(wxCommandEvent &event)
+{
+	Ins_Record();
+}
+
+void CDLG_Table_Control::On_Record_Ins_UI(wxUpdateUIEvent &event)
+{
+	event.Enable(!m_pTable->is_Indexed());
+}
+
+//---------------------------------------------------------
+void CDLG_Table_Control::On_Record_Del(wxCommandEvent &event)
+{
+	Del_Record();
+}
+
+void CDLG_Table_Control::On_Record_Del_UI(wxUpdateUIEvent &event)
+{
+	event.Enable(!m_pTable->is_Indexed() && m_pTable->Get_Selection_Count() > 0);
+}
+
+//---------------------------------------------------------
+void CDLG_Table_Control::On_Record_Clr(wxCommandEvent &event)
+{
+	Del_Records();
+}
+
+
+///////////////////////////////////////////////////////////
+//														 //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+void CDLG_Table_Control::On_Autosize_Cols(wxCommandEvent &event)
+{
+	AutoSizeColumns(false);
+}
+
+//---------------------------------------------------------
+void CDLG_Table_Control::On_Autosize_Rows(wxCommandEvent &event)
+{
+	AutoSizeRows(false);
+}
+
+
+///////////////////////////////////////////////////////////
+//														 //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+void CDLG_Table_Control::On_LClick(wxGridEvent &event)
+{
+	SetGridCursor(event.GetRow(), event.GetCol());
+
+	//-----------------------------------------------------
+	if( event.AltDown() )
+	{
+		if( m_pTable->Get_Field_Type(event.GetCol()) == SG_DATATYPE_String )
+		{
+			Open_Application(GetCellValue(event.GetRow(), event.GetCol()));
+		}
+	}
+
+	//-----------------------------------------------------
+	else if( event.ControlDown() )
+	{
+		if( m_pTable->Get_Field_Type(event.GetCol()) == SG_DATATYPE_String )
+		{
+			g_pData->Open   (GetCellValue(event.GetRow(), event.GetCol()));
+		}
+	}
+
+	//-----------------------------------------------------
+	else if( m_pTable->Get_Field_Type(event.GetCol()) == SG_DATATYPE_Color )
+	{
+		CSG_Table_Record	*pRecord	= m_pTable->Get_Record_byIndex(event.GetRow());
+
+		long	lValue;
+
+		if( DLG_Color(lValue = pRecord->asInt(event.GetCol())) )
+		{
+			pRecord->Set_Value(event.GetCol(), lValue);
+
+			SetCellBackgroundColour(event.GetRow(), event.GetCol(), Get_Color_asWX(pRecord->asInt(event.GetCol())));
+
+			ForceRefresh();
+		}
+	}
+}
+
+//---------------------------------------------------------
+void CDLG_Table_Control::On_RClick(wxGridEvent &event)
+{
+	SetGridCursor(event.GetRow(), event.GetCol());
+
+	//-----------------------------------------------------
+	if( m_pTable->Get_Field_Type(event.GetCol()) == SG_DATATYPE_String )
+	{
+		wxMenu	Menu;
+
+		CMD_Menu_Add_Item(&Menu, false, ID_CMD_TABLE_FIELD_OPEN_APP);
+
+		if( GetCellValue(event.GetRow(), event.GetCol()).Find("PGSQL:") == 0 || wxFileExists(GetCellValue(event.GetRow(), event.GetCol())) )
+		{
+			CMD_Menu_Add_Item(&Menu, false, ID_CMD_TABLE_FIELD_OPEN_DATA);
+		}
+
+		PopupMenu(&Menu, event.GetPosition());
+	}
+}
+
+//---------------------------------------------------------
+void CDLG_Table_Control::On_Field_Open(wxCommandEvent &event)
+{
+	if( event.GetId() == ID_CMD_TABLE_FIELD_OPEN_APP )
+	{
+		Open_Application(GetCellValue(GetGridCursorRow(), GetGridCursorCol()));
+	}
+
+	if( event.GetId() == ID_CMD_TABLE_FIELD_OPEN_DATA )
+	{
+		g_pData->Open   (GetCellValue(GetGridCursorRow(), GetGridCursorCol()));
+	}
+}
+
+
+///////////////////////////////////////////////////////////
+//														 //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+void CDLG_Table_Control::On_LClick_Label(wxGridEvent &event)
+{
+	if( event.GetRow() != -1 )	// select records
+	{
+		if( event.ControlDown() )
+		{
+			m_pTable->Select(m_pTable->Get_Record_byIndex(event.GetRow()), true);
+
+			Update_Selection();
+		}
+		else if( event.ShiftDown() )
+		{
+			SelectBlock(event.GetRow(), 0, GetGridCursorRow(), GetNumberCols(), false);
+		}
+		else
+		{
+			SelectRow(event.GetRow(), false);
+		}
+
+		SetGridCursor(event.GetRow(), GetGridCursorCol());
+	}
+	else if( event.GetCol() < 0 )
+	{
+		ClearSelection();
+	}
+}
+
+//---------------------------------------------------------
+void CDLG_Table_Control::On_RClick_Label(wxGridEvent &event)
+{
+	//-----------------------------------------------------
+	if( event.GetCol() != -1 )
+	{
+		wxMenu	Menu(_TL("Columns"));
+
+		CMD_Menu_Add_Item(&Menu, false, ID_CMD_TABLE_AUTOSIZE_COLS);
+		CMD_Menu_Add_Item(&Menu, false, ID_CMD_TABLE_FIELD_SORT);
+		CMD_Menu_Add_Item(&Menu, false, ID_CMD_TABLE_FIELD_RENAME);
+
+		PopupMenu(&Menu, event.GetPosition().x, event.GetPosition().y - GetColLabelSize());
+	}
+
+	//-----------------------------------------------------
+	else if( event.GetRow() != -1 )
+	{
+		wxMenu	Menu(_TL("Rows"));
+
+		CMD_Menu_Add_Item(&Menu, false, ID_CMD_TABLE_RECORD_ADD);
+		CMD_Menu_Add_Item(&Menu, false, ID_CMD_TABLE_RECORD_INS);
+		CMD_Menu_Add_Item(&Menu, false, ID_CMD_TABLE_RECORD_DEL);
+		CMD_Menu_Add_Item(&Menu, false, ID_CMD_TABLE_RECORD_DEL_ALL);
+
+		Menu.AppendSeparator();
+		CMD_Menu_Add_Item(&Menu, false, ID_CMD_TABLE_AUTOSIZE_ROWS);
+
+		PopupMenu(&Menu, event.GetPosition().x - GetRowLabelSize(), event.GetPosition().y);
+	}
+
+	//-----------------------------------------------------
+	else
+	{
+		ClearSelection();
+	}
+}
+
+//---------------------------------------------------------
+void CDLG_Table_Control::On_LDClick_Label(wxGridEvent &event)
+{
+	Update_Sorting(event.GetCol(), -1);
+}
+
+
+///////////////////////////////////////////////////////////
+//														 //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+bool CDLG_Table_Control::Update_Selection(void)
+{
+	if( GetBatchCount() == 0 )
+	{
+		BeginBatch();
+
+		if( m_pTable->Get_Selection_Count() >= m_pTable->Get_Count() )
+		{
+			SelectAll();
+		}
+		else
+		{
+			ClearSelection();
+
+			if( m_pTable->Get_Selection_Count() > 0 )
+			{
+				#pragma omp parallel for
+				for(int iRecord=0; iRecord<GetNumberRows(); iRecord++)
+				{
+					if( m_pTable->Get_Record_byIndex(iRecord)->is_Selected() )
+					{
+						SelectRow(iRecord, true);
+					}
+				}
+			}
+		}
+
+		EndBatch();
+
+		return( true );
+	}
+
+	return( false );
+}
+
+//---------------------------------------------------------
+void CDLG_Table_Control::On_Select(wxGridRangeSelectEvent &event)
+{
+	if( GetBatchCount() == 0 )
+	{
+		BeginBatch();
+
+		for(int iRow=event.GetTopRow(); iRow<=event.GetBottomRow(); iRow++)
+		{
+			CSG_Table_Record	*pRecord	= m_pTable->Get_Record_byIndex(iRow);
+
+			if( pRecord->is_Selected() != event.Selecting() )
+			{
+				m_pTable->Select(pRecord, true);
+			}
+		}
+
+		EndBatch();
+	}
+
+	event.Skip();
+}
+
+
+///////////////////////////////////////////////////////////
+//														 //
+//														 //
+//														 //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
diff --git a/src/saga_core/saga_gui/view_table_control.h b/src/saga_core/saga_gui/dlg_table_control.h
similarity index 72%
copy from src/saga_core/saga_gui/view_table_control.h
copy to src/saga_core/saga_gui/dlg_table_control.h
index 32b51bf..c133369 100644
--- a/src/saga_core/saga_gui/view_table_control.h
+++ b/src/saga_core/saga_gui/dlg_table_control.h
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: view_table_control.h 2074 2014-03-31 10:32:12Z oconrad $
+ * Version $Id: dlg_table_control.h 2665 2015-10-28 12:55:25Z oconrad $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -14,9 +14,9 @@
 //                                                       //
 //-------------------------------------------------------//
 //                                                       //
-//                 VIEW_Table_Control.h                  //
+//                  dlg_table_control.h                  //
 //                                                       //
-//          Copyright (C) 2005 by Olaf Conrad            //
+//          Copyright (C) 2015 by Olaf Conrad            //
 //                                                       //
 //-------------------------------------------------------//
 //                                                       //
@@ -42,9 +42,7 @@
 //                                                       //
 //    contact:    Olaf Conrad                            //
 //                Institute of Geography                 //
-//                University of Goettingen               //
-//                Goldschmidtstr. 5                      //
-//                37077 Goettingen                       //
+//                University of Hamburg                  //
 //                Germany                                //
 //                                                       //
 //    e-mail:     oconrad at saga-gis.org                   //
@@ -61,8 +59,8 @@
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
-#ifndef _HEADER_INCLUDED__SAGA_GUI__VIEW_Table_Control_H
-#define _HEADER_INCLUDED__SAGA_GUI__VIEW_Table_Control_H
+#ifndef _HEADER_INCLUDED__SAGA_GUI__dlg_table_control_H
+#define _HEADER_INCLUDED__SAGA_GUI__dlg_table_control_H
 
 
 ///////////////////////////////////////////////////////////
@@ -82,37 +80,18 @@
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
-#define TABLE_CTRL_FIXED_COLS	0x01
-#define TABLE_CTRL_FIXED_ROWS	0x02
-#define TABLE_CTRL_FIXED_TABLE	(TABLE_CTRL_FIXED_ROWS|TABLE_CTRL_FIXED_COLS)
-#define TABLE_CTRL_COL1ISLABEL	0x04
-
-
-///////////////////////////////////////////////////////////
-//														 //
-//														 //
-//														 //
-///////////////////////////////////////////////////////////
-
-//---------------------------------------------------------
-class CVIEW_Table_Control : public wxGrid
+class CDLG_Table_Control : public wxGrid
 {
-	DECLARE_CLASS(CVIEW_Table_Control)
+	DECLARE_CLASS(CDLG_Table_Control)
 
 public:
-	CVIEW_Table_Control(wxWindow *pParent, class CSG_Table *pTable, int Constraint);
-	virtual ~CVIEW_Table_Control(void);
+	CDLG_Table_Control(wxWindow *pParent, class CSG_Table *pTable);
+	virtual ~CDLG_Table_Control(void);
 
-	void						On_Field_Add		(wxCommandEvent  &event);
-	void						On_Field_Add_UI		(wxUpdateUIEvent &event);
-	void						On_Field_Del		(wxCommandEvent  &event);
-	void						On_Field_Del_UI		(wxUpdateUIEvent &event);
 	void						On_Field_Sort		(wxCommandEvent  &event);
 	void						On_Field_Sort_UI	(wxUpdateUIEvent &event);
-	void						On_Field_Rename		(wxCommandEvent  &event);
-	void						On_Field_Rename_UI	(wxUpdateUIEvent &event);
-	void						On_Field_Type		(wxCommandEvent  &event);
-	void						On_Field_Type_UI	(wxUpdateUIEvent &event);
+
+	void						On_Field_Open		(wxCommandEvent  &event);
 
 	void						On_Record_Add		(wxCommandEvent  &event);
 	void						On_Record_Add_UI	(wxUpdateUIEvent &event);
@@ -121,13 +100,6 @@ public:
 	void						On_Record_Del		(wxCommandEvent  &event);
 	void						On_Record_Del_UI	(wxUpdateUIEvent &event);
 	void						On_Record_Clr		(wxCommandEvent  &event);
-	void						On_Record_Clr_UI	(wxUpdateUIEvent &event);
-
-	void						On_Sel_To_Top		(wxCommandEvent  &event);
-	void						On_Sel_To_Top_UI	(wxUpdateUIEvent &event);
-
-	void						On_Sel_Only			(wxCommandEvent  &event);
-	void						On_Sel_Only_UI		(wxUpdateUIEvent &event);
 
 	void						On_Autosize_Cols	(wxCommandEvent  &event);
 	void						On_Autosize_Rows	(wxCommandEvent  &event);
@@ -139,13 +111,12 @@ public:
 	void						On_Edit_Stop		(wxGridEvent     &event);
 	void						On_Changed			(wxGridEvent     &event);
 	void						On_LClick			(wxGridEvent     &event);
+	void						On_RClick			(wxGridEvent     &event);
 	void						On_LClick_Label		(wxGridEvent     &event);
 	void						On_RClick_Label		(wxGridEvent     &event);
 	void						On_LDClick_Label	(wxGridEvent     &event);
 	void						On_Select			(wxGridRangeSelectEvent &event);
 
-	void						Set_Labeling		(bool bOn);
-
 	bool						Update_Table		(void);
 	bool						Update_Selection	(void);
 	bool						Update_Sorting		(int iField, int Direction);
@@ -158,21 +129,17 @@ public:
 	bool						Load				(const wxString &File_Name);
 	bool						Save				(const wxString &File_Name, int Format = 0);
 
+	class CSG_Table *			Get_Table			(void)	{	return( m_pTable );	}
 
-private:
-
-	bool						m_bSelOnly, m_bEditing;
 
-	int							m_Constraint, m_Field_Offset;
+private:
 
-	class CSG_Table_Record		**m_pRecords;
+	bool						m_bEditing;
 
 	class CSG_Table				*m_pTable;
 
 
-	void						_Update_Views		(void);
-
-	bool						_Set_Records		(bool bSelection_To_Top = false);
+	bool						_Set_Records		(void);
 	bool						_Set_Record			(int iRecord, class CSG_Table_Record *pRecord);
 
 
@@ -188,4 +155,4 @@ DECLARE_EVENT_TABLE()
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
-#endif // #ifndef _HEADER_INCLUDED__SAGA_GUI__VIEW_Table_Control_H
+#endif // #ifndef _HEADER_INCLUDED__SAGA_GUI__dlg_table_control_H
diff --git a/src/saga_core/saga_gui/project.cpp b/src/saga_core/saga_gui/project.cpp
index b7ba7d8..6da9e85 100644
--- a/src/saga_core/saga_gui/project.cpp
+++ b/src/saga_core/saga_gui/project.cpp
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: project.cpp 2640 2015-10-07 17:29:38Z oconrad $
+ * Version $Id: project.cpp 2674 2015-11-03 17:03:58Z oconrad $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -97,6 +97,8 @@
 #include "wksp_map_graticule.h"
 #include "wksp_layer.h"
 
+#include "data_source_pgsql.h"
+
 #include "project.h"
 
 
@@ -213,6 +215,115 @@ bool CWKSP_Project::Save(const wxString &FileName, bool bSaveModified)
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
+bool CWKSP_Project::Copy(void)
+{
+	wxString	FileName;
+
+	if( !DLG_Save(FileName, ID_DLG_PROJECT_SAVE) )
+	{
+		return( false );
+	}
+
+	wxFileName	Directory(FileName);
+
+	Directory.AppendDir(Directory.GetFullName());
+
+	if( !Directory.DirExists() )
+	{
+		Directory.Mkdir(wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL);
+	}
+
+	size_t	i, j;
+
+	for(j=0; j<SG_Get_Data_Manager().Grid_System_Count(); j++)
+	{
+		for(i=0; i<SG_Get_Data_Manager().Get_Grid_System(j)->Count(); i++)
+		{
+			_Copy_To_File(g_pData->Get(SG_Get_Data_Manager().Get_Grid_System(j)->Get(i)), Directory.GetFullPath());
+		}
+	}
+
+	for(i=0; i<SG_Get_Data_Manager().Get_Point_Cloud()->Count(); i++)
+	{
+		_Copy_To_File(g_pData->Get(SG_Get_Data_Manager().Get_Point_Cloud()->Get(i)), Directory.GetFullPath());
+	}
+
+	for(i=0; i<SG_Get_Data_Manager().Get_Shapes()->Count(); i++)
+	{
+		_Copy_To_File(g_pData->Get(SG_Get_Data_Manager().Get_Shapes()->Get(i)), Directory.GetFullPath());
+	}
+
+	for(i=0; i<SG_Get_Data_Manager().Get_Table()->Count(); i++)
+	{
+		_Copy_To_File(g_pData->Get(SG_Get_Data_Manager().Get_Shapes()->Get(i)), Directory.GetFullPath());
+	}
+
+	for(i=0; i<SG_Get_Data_Manager().Get_TIN()->Count(); i++)
+	{
+		_Copy_To_File(g_pData->Get(SG_Get_Data_Manager().Get_TIN()->Get(i)), Directory.GetFullPath());
+	}
+
+	return( _Save(Directory.GetFullPath(), false, true) );
+}
+
+//---------------------------------------------------------
+bool CWKSP_Project::_Copy_To_File(CWKSP_Data_Item *pItem, const wxString &Directory)
+{
+	wxFileName	Path(Directory);
+
+	switch( pItem->Get_Type() )
+	{
+	case WKSP_ITEM_Table     :	Path.SetExt("txt" );	break;
+	case WKSP_ITEM_Shapes    :	Path.SetExt("shp" );	break;
+	case WKSP_ITEM_TIN       :	Path.SetExt("shp" );	break;
+	case WKSP_ITEM_PointCloud:	Path.SetExt("spc" );	break;
+	case WKSP_ITEM_Grid      :	Path.SetExt("sgrd");	break;
+	default:	return( false );
+	}
+
+	//-----------------------------------------------------
+	wxString	Name(pItem->Get_Object()->Get_Name());
+
+	Name.Replace(".", "-");
+	Name.Replace(":", "-");
+
+	Path.SetName(Name);
+
+	for(int i=1; Path.FileExists(); i++)
+	{
+		Path.SetName(Name + wxString::Format("_%d", i));
+	}
+
+	Name	= Path.GetFullPath();
+
+	return( pItem->Get_Object()->Save(&Name) );
+}
+
+
+///////////////////////////////////////////////////////////
+//														 //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+bool CWKSP_Project::CopyToDB(void)
+{
+	return( true );
+}
+
+//---------------------------------------------------------
+bool CWKSP_Project::_Copy_To_Database(CWKSP_Data_Item *pItem, const wxString &Connection)
+{
+	return( true );
+}
+
+
+///////////////////////////////////////////////////////////
+//														 //
+//														 //
+//														 //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
 bool CWKSP_Project::_Load(const wxString &FileName, bool bAdd, bool bUpdateMenu)
 {
 	if( wxFileExists(FileName) && !bAdd && g_pData->Get_Count() > 0 )
@@ -244,23 +355,27 @@ bool CWKSP_Project::_Load(const wxString &FileName, bool bAdd, bool bUpdateMenu)
 	}
 	else if( !wxFileExists(FileName) )
 	{
-		MSG_Error_Add(_TL("file does not exist.")            , true, true, SG_UI_MSG_STYLE_FAILURE);
+		MSG_Error_Add(_TL("file does not exist."            ), true, true, SG_UI_MSG_STYLE_FAILURE);
 	}
 	else if( !Project.Load(&FileName) )
 	{
-		MSG_Error_Add(_TL("could not read project file.")    , true, true, SG_UI_MSG_STYLE_FAILURE);
+		MSG_Error_Add(_TL("could not read project file."    ), true, true, SG_UI_MSG_STYLE_FAILURE);
 	}
 	else if( Project.Get_Name().Cmp(SG_T("SAGA_PROJECT")) )
 	{
-		MSG_Error_Add(_TL("invalid project file.")           , true, true, SG_UI_MSG_STYLE_FAILURE);
+		MSG_Error_Add(_TL("invalid project file."           ), true, true, SG_UI_MSG_STYLE_FAILURE);
 	}
 	else if( (pNode = Project.Get_Child(SG_T("DATA"))) == NULL || pNode->Get_Children_Count() <= 0 )
 	{
 		MSG_Error_Add(_TL("no data entries in project file."), true, true, SG_UI_MSG_STYLE_FAILURE);
 	}
+	else if( !_Load_DBConnections(*pNode) )
+	{
+		MSG_Error_Add(_TL("could not connect to database."  ), true, true, SG_UI_MSG_STYLE_FAILURE);
+	}
 	else
 	{
-		int			i;
+		int		i;
 
 		CSG_String	Version(Project.Get_Property("VERSION"));
 
@@ -468,6 +583,63 @@ bool CWKSP_Project::_Save(const wxString &FileName, bool bSaveModified, bool bUp
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
+bool CWKSP_Project::_Load_DBConnections(CSG_MetaData &Data)
+{
+	int			i;
+	CSG_Strings	Connections;
+
+	for(i=0; i<Data.Get_Children_Count(); i++)
+	{
+		CSG_String	Connection(Data[i].Get_Child("FILE") ? Data[i].Get_Child("FILE")->Get_Content() : "");
+
+		if( !Connection.BeforeFirst(':').Cmp("PGSQL") )
+		{
+			Connection	= Connection.AfterFirst(':');	CSG_String	Host  (Connection.BeforeFirst(':'));
+			Connection	= Connection.AfterFirst(':');	CSG_String	Port  (Connection.BeforeFirst(':'));
+			Connection	= Connection.AfterFirst(':');	CSG_String	DBName(Connection.BeforeFirst(':'));
+
+			Connection	= Host + ":" + Port + ":" + DBName;
+
+			bool	bAdd	= true;
+
+			for(int j=0; j<Connections.Get_Count() && bAdd; j++)
+			{
+				if( !Connection.Cmp(Connections[j]) )
+				{
+					bAdd	= false;
+				}
+			}
+
+			if( bAdd )
+			{
+				Connections	+= Connection;
+			}
+		}
+	}
+
+	for(i=0; i<Connections.Get_Count(); i++)
+	{
+		CSG_String	Host  (Connections[i].BeforeFirst(':'));
+		CSG_String	Port  (Connections[i].AfterFirst (':').BeforeLast(':'));
+		CSG_String	DBName(Connections[i].AfterLast  (':'));
+
+		if( !PGSQL_Connect(Host, Port, DBName) )
+		{
+			return( false );
+		}
+	}
+
+	return( true );
+}
+
+
+///////////////////////////////////////////////////////////
+//														 //
+//														 //
+//														 //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
 bool CWKSP_Project::_Load_Data(CSG_MetaData &Entry, const wxString &ProjectDir, bool bLoad, const CSG_String &Version)
 {
 	if( Entry.Get_Name().Cmp("DATASET") || !Entry.Get_Child("FILE") || Entry.Get_Child("FILE")->Get_Content().is_Empty() )
@@ -563,9 +735,7 @@ bool CWKSP_Project::_Save_Data(CSG_MetaData &Entry, const wxString &ProjectDir,
 
 	if( wxFileExists(pDataObject->Get_File_Name(false)) )
 	{
-		wxString	s(Get_FilePath_Relative(ProjectDir, pDataObject->Get_File_Name(false)));
-
-		pEntry->Add_Child("FILE", &s);
+		pEntry->Add_Child("FILE", SG_File_Get_Path_Relative(ProjectDir, pDataObject->Get_File_Name(false)));
 	}
 	else if( pDataObject->Get_MetaData_DB().Get_Children_Count() > 0 )
 	{
@@ -593,9 +763,7 @@ bool CWKSP_Project::_Save_Data(CSG_MetaData &Entry, const wxString &ProjectDir,
 
 				if( File.BeforeFirst(':').Cmp("PGSQL") && SG_File_Exists(File) )
 				{
-					wxString	s(Get_FilePath_Relative(ProjectDir, File.w_str()));
-
-					pEntry->Get_Child(i)->Set_Content(&s);
+					pEntry->Get_Child(i)->Set_Content(SG_File_Get_Path_Relative(ProjectDir, File.w_str()));
 				}
 			}
 		}
@@ -738,10 +906,14 @@ bool CWKSP_Project::_Save_Map(CSG_MetaData &Entry, const wxString &ProjectDir, C
 			{
 				wxString	FileName(pObject->Get_File_Name(false));
 
-				if( FileName.Find("PGSQL") == 0 || wxFileExists(FileName = Get_FilePath_Relative(ProjectDir, FileName)) )
+				if( FileName.Find("PGSQL") == 0 )
 				{
 					pEntry->Add_Child("FILE", &FileName);
 				}
+				else if( wxFileExists(FileName) )
+				{
+					pEntry->Add_Child("FILE", SG_File_Get_Path_Relative(ProjectDir, FileName));
+				}
 			}
 		}
 
diff --git a/src/saga_core/saga_gui/project.h b/src/saga_core/saga_gui/project.h
index dedf504..26a3895 100644
--- a/src/saga_core/saga_gui/project.h
+++ b/src/saga_core/saga_gui/project.h
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: project.h 1955 2014-01-23 13:49:11Z oconrad $
+ * Version $Id: project.h 2674 2015-11-03 17:03:58Z oconrad $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -89,6 +89,9 @@ public:
 	bool					Save				(bool bSaveAsOnError);
 	bool					Save				(const wxString &FileName, bool bSaveModified);
 
+	bool					Copy				(void);
+	bool					CopyToDB			(void);
+
 
 private:
 
@@ -99,6 +102,8 @@ private:
 	bool					_Load				(const wxString &FileName, bool bAdd, bool bUpdateMenu);
 	bool					_Save				(const wxString &FileName, bool bSaveModified, bool bUpdateMenu);
 
+	bool					_Load_DBConnections	(CSG_MetaData &Data);
+
 	bool					_Load_Data			(CSG_MetaData &Entry, const wxString &ProjectDir, bool bLoad, const CSG_String &Version);
 	bool					_Save_Data			(CSG_MetaData &Entry, const wxString &ProjectDir, class CSG_Data_Object *pDataObject, class CSG_Parameters *pParameters);
 
@@ -107,6 +112,8 @@ private:
 
 	class CWKSP_Base_Item *	_Get_byFileName		(const wxString &FileName);
 
+	bool					_Copy_To_File		(class CWKSP_Data_Item *pData, const wxString &Directory);
+	bool					_Copy_To_Database	(class CWKSP_Data_Item *pData, const wxString &Connection);
 
 	//-----------------------------------------------------
 	bool	_Compatibility_Data			(TSG_Data_Type Type, class CSG_Parameters *pParameters, const CSG_String &Version);
diff --git a/src/saga_core/saga_gui/res/saga.ger.txt b/src/saga_core/saga_gui/res/saga.ger.txt
index fc83786..8335527 100644
--- a/src/saga_core/saga_gui/res/saga.ger.txt
+++ b/src/saga_core/saga_gui/res/saga.ger.txt
@@ -46,7 +46,6 @@ TEXT	TRANSLATION
 "  Total Points:\t%ld"	""
 "  Total Pulses:\t%ld"	""
 "  Version:\t\t\t%d.%d"	""
-" Bed_shear_stress"	""
 "%.0f points from %d dataset(s) written to output grid %s."	""
 "%d points from %d dataset(s) written to output point cloud %s."	""
 "%d points from %s written to output %s."	""
@@ -68,7 +67,6 @@ TEXT	TRANSLATION
 "(b)"	""
 "(b) [lower bound]"	"(b) [untere Grenze]"
 "(b) [upper bound]"	"(b) [obere Grenze]"
-"(c) 2007 by O.Conrad, R.Heinrich"	""
 "(c) Parameter [lower bound]"	"(c) Parameter [untere Grenze]"
 "(c) Parameter [upper bound]"	"(c) Parameter [obere Grenz]"
 "(f) Temperature Modulation Factor [lower bound]"	"(f) Temperaturregulierungs Faktor [untere Grenze]"
@@ -160,6 +158,7 @@ TEXT	TRANSLATION
 "20 seconds"	"20 Sekunden"
 "200-400 mm/day"	""
 "256x256"	""
+"2nd Date (End of Range)"	""
 "2nd Order Polynomial"	""
 "2nd Std. Parallel"	""
 "3"	""
@@ -240,7 +239,6 @@ TEXT	TRANSLATION
 "A3 Portrait"	"A3 Hochformat"
 "A4 Landscape"	"A4 Querformat"
 "A4 Portrait"	"A4 Hochformat"
-"A:Garden"	""
 "A:Garden|Imagery"	""
 "A:Grid|Analysis|Macroecology"	""
 "A:Grid|Distances"	""
@@ -253,18 +251,21 @@ TEXT	TRANSLATION
 "A:Imagery|Fourier Analysis"	""
 "A:Imagery|Segmentation"	""
 "A:Imagery|Tools"	"A:Bildverarbeitung|Werkzeuge"
-"A:Jan Hohlbein"	""
 "A:Shapes|Construction"	"A:Vektoren|Konstruktion"
 "A:Shapes|Conversion"	"A:Vektoren|Umwandlung"
 "A:Shapes|Selection"	"A:Vektoren|Auswahl"
 "A:Shapes|Table"	"A:Vektoren|Tabelle"
 "A:Shapes|Tools"	"A:Vektoren|Werkzeuge"
+"A:Simulation|Hillslope Evolution"	""
+"A:Simulation|Hydrology"	""
 "A:Spatial and Geostatistics|Geographically Weighted Regression"	""
 "A:Spatial and Geostatistics|Points"	"A:Raum und Geostatistik|Punkte"
 "A:Table|Construction"	"A:Tabelle|Konstruktion"
 "A:Table|Selection"	"Tabelle|Auswahl"
 "A:Table|Tools"	"Tabelle|Werkzeuge"
 "A:Terrain Analysis|Climate and Weather"	"A:Reliefanalyse|Klima und Wetter"
+"A:Terrain Analysis|Hydrology|Flow Accumulation"	""
+"A:Terrain Analysis|Preprocessing"	""
 "A:Terrain Analysis|Terrain Classification"	"A:Reliefanalyse|Gel�ndeklassifikation"
 "ADDR"	""
 "AFAC("	""
@@ -333,7 +334,6 @@ TEXT	TRANSLATION
 "Add Field"	"Feld hinzuf�gen"
 "Add Frame"	"F�ge Rahmen hinzu"
 "Add Graticule"	""
-"Add Grid Name Field"	""
 "Add Grid Values to Points"	"Weise Rasterwerte Punkten zu"
 "Add Grid Values to Shapes"	"F�ge Rasterwerte in Vektor ein"
 "Add Identifier"	""
@@ -345,7 +345,6 @@ TEXT	TRANSLATION
 "Add Point Attributes to Polygons"	""
 "Add Point Order"	""
 "Add Polygon Attributes to Points"	"F�ge Polygonattribute Punkten hinzu"
-"Add Position [A]"	""
 "Add Position [Ctrl + A]"	""
 "Add Project"	""
 "Add Record"	""
@@ -357,9 +356,11 @@ TEXT	TRANSLATION
 "Add overlap to AOI"	""
 "Add point order as additional attribute."	""
 "Add to Map"	""
+"Add to Table"	""
 "Add unique identifier attribute field to output, ID resembles processing order."	""
 "Added"	""
 "Addition"	"Addierung"
+"Additional Output"	""
 "Additional Point Clouds"	"Zus�tzliche Punktwolken"
 "Additional Values"	"Zus�tzliche Werte"
 "Additional point clouds to merge with main point cloud."	""
@@ -380,7 +381,6 @@ TEXT	TRANSLATION
 "Aggregation"	"Vereinigung"
 "Aggregation Index"	"Zusammenf�hrungsindex"
 "Aggregation Size"	"Anh�ufung Gr��e"
-"Air Flow"	""
 "Air Humidity (2pm) [%%]"	"Luftfeuchte (2pm) [%%]"
 "Air Pressure, Water and Dust Content"	"Luftdruck, Wasser und Staub Inhalt"
 "Albedo"	""
@@ -388,6 +388,7 @@ TEXT	TRANSLATION
 "Alessandro Perego"	""
 "Algorithm"	""
 "Algorithm for the detection of Surface Specific Points"	"Algorithmus f�r die Erfassung charakteristischer Oberfl�chenpunkte"
+"Alignment"	""
 "All"	""
 "All Files"	"Alle Dateien"
 "All Files|*.*|"	"Alle Dateien|*.*|"
@@ -400,8 +401,6 @@ TEXT	TRANSLATION
 "Allgemeine Parameter"	""
 "Allocation"	"Zuweisung"
 "Allocation Grid"	"Zuweisungsraster"
-"Allochthone Input"	""
-"Allochthoner Eintrag"	""
 "Allow Edge Pixels to be Seeds"	"Erlaube Kantenpixel Keime zu sein"
 "Allow longitudes outside -180 to 180 Range"	"Ber�cksichtige L�ngen au�erhalb -180 bis 180 Bereich"
 "Allow multiple observer positions."	""
@@ -432,10 +431,9 @@ TEXT	TRANSLATION
 "Angle in degrees, clockwise around z axis"	""
 "Angle in degrees, counting clockwise from north"	"Winkel in Grad, Z�hlung im Uhrzeigersinn von Nord"
 "Angular Distance Weighted"	""
+"Angular Step Size (Degree)"	""
 "Annual"	""
-"Annual Climate"	""
 "Annual Course of Daily Insolation"	""
-"Answer"	""
 "Append Fields from another Table"	""
 "Append Rows from ..."	""
 "Applies also to the binary format header file."	"Anwendbar ebenfalls f�r die bin�re Formatkopfdatei"
@@ -462,7 +460,6 @@ TEXT	TRANSLATION
 "Area Conversion"	""
 "Area [km2]"	"Fl�che [km�]"
 "Area [km2] Subbasin("	"Fl�che [km�] Teilbecken("
-"Area of an active channel within a cell"	""
 "Area of the Watershed in [km2]"	"Fl�che des Wassereinzugsgebietes in [km�]"
 "Area of the Watershed in [km2] used for unit conversion"	"Fl�che des Wassereinzugsgebietes [km�] die f�r Bereichsanpassung genutzt wird"
 "Area to Length Conversion"	"Fl�che f�r L�ngenanpassung"
@@ -490,7 +487,6 @@ TEXT	TRANSLATION
 "Atlas Boundary Files (*.bna)"	""
 "Atmospheric Correction"	""
 "Atmospheric Effects"	"Atmospherische Effekte"
-"Atmospheric Pressure [mbar]"	"Atmospherischer Druck [mbar]"
 "Attribute"	"Attribut"
 "Attribute (Size)"	"Attribut (Gr��e)"
 "Attribute Field"	""
@@ -510,7 +506,6 @@ TEXT	TRANSLATION
 "Attributes to import besides x,y,z ..."	"Zu importierende Attribute au�er x,y,z..."
 "August"	"August"
 "Ausgabedaten"	""
-"Ausgangsgestein Layer"	""
 "Ausgangsrasterzelle Flusseinzugsgebiet [Default: Elbe5000]"	""
 "Auswahl der Art der anteiligen Flaechenwasserwasserentnahme."	""
 "Auswahl der Art der dynamischen Flaechenwasserwassernutzung (WUse). ACHTUNG: Funktioniert ggf. nur bei bereits initiierten Systemen bzw. nach Vorlauf"	""
@@ -578,7 +573,6 @@ TEXT	TRANSLATION
 "Backward Diagonal"	"R�ckw�rts diagonal"
 "Backward [Page Down]"	""
 "Backward diagonal hatch"	"Diagonal r�ckwarts schraffiert"
-"Bagnold"	""
 "Band"	""
 "Band 1"	""
 "Band 2"	""
@@ -589,9 +583,11 @@ TEXT	TRANSLATION
 "Band 62"	""
 "Band 7"	""
 "Band 8"	""
+"Band Name Field"	""
 "Bands"	"Banden"
 "Bandwidth (Cells)"	"Bandbreite (Zellen)"
 "Bare Earth"	"kahle Erde"
+"Barometric Pressure [mbar]"	""
 "Bars"	"Balken"
 "Base Level"	"Ausgangsniveau"
 "Base Name"	""
@@ -600,10 +596,8 @@ TEXT	TRANSLATION
 "Basic measures for spatial point patterns."	"wesentliche Ma�einheiten f�r r�umliche Punktmuster"
 "Basin Type (Gravelius)"	"Becken Typ (Gravelius)"
 "Basins"	"Becken"
-"Bed_shear_stress"	""
 "Beep when finished"	""
 "Begin Transaction"	""
-"Begin with Year..."	""
 "Below this threshold precipitation will fall as snow"	"Unterhalb dieses Schwellenwertes f�llt  Niederschlag als Schnee"
 "Beruecksichtigung der Hauptgerinnerasterzellen?"	""
 "Beta"	""
@@ -637,10 +631,8 @@ TEXT	TRANSLATION
 "Borders"	"Grenzen"
 "Bottom"	"Basis"
 "Bottom to Top"	"Unten bis Oben"
-"Boundary"	""
 "Boundary Effect"	""
 "Boundary Effect Color"	""
-"Boundery"	""
 "Bounding Box"	"Rahmen"
 "Bounding Box [B]"	""
 "Branches"	"Fachgebiete"
@@ -677,7 +669,6 @@ TEXT	TRANSLATION
 "CENTER"	"MITTE"
 "CFAC("	""
 "CFit\n(created by SAGA Wizard)."	"CPassend\n(durch SAGA Wizard erzeugt)."
-"CHELSA"	""
 "CLASS"	"KLASSE"
 "CLASS_ID"	""
 "CLASS_NR"	""
@@ -753,12 +744,10 @@ TEXT	TRANSLATION
 "Centroid Y"	"Schwerpunkt Y"
 "Centroids"	"Schwerpunkt"
 "Centroids for each part"	"Schwerpunkt f�r jeden Teil"
-"Change"	""
 "Change Cell Values"	"�ndere Zellwerte"
 "Change Color Format"	""
 "Change Data Storage"	""
 "Change Date Format"	"�ndere Datenformat"
-"Change Detection"	"Wechsle Erkennung"
 "Change Field Type"	"�ndere Feldtyp"
 "Change Grid Values"	"�ndere Rasterwerte"
 "Change Grid Values - Flood Fill"	"�ndere Rasterwerte - Fl�chenf�llung"
@@ -769,11 +758,9 @@ TEXT	TRANSLATION
 "Change all values within radius."	""
 "Changed"	""
 "Changed Grid"	"Ge�ndertes Raster"
-"Changes"	"Ver�nderungen"
 "Channel"	""
 "Channel Definition Threshold (ha)"	"Gew�ssernetz Definition Schwellenwert (ha) "
 "Channel Density"	""
-"Channel Depth"	""
 "Channel Direction"	"Gew�sser Richtung"
 "Channel Initiation Threshold"	""
 "Channel Mask"	""
@@ -788,16 +775,9 @@ TEXT	TRANSLATION
 "Channel Network: Pass 5"	"Gew�ssernetz: Durchlauf 5"
 "Channel Network: Pass 6"	"Gew�ssernetz: Durchlauf 6"
 "Channel Skeleton"	"Gew�sserger�st"
-"Channel Type"	""
 "Channel definition threshold"	"Gew�ssernetz Definition Schwellenwert"
-"Channel depth constant"	""
-"Channel depth exponent (depth = KDP * AREA^MDP)"	""
 "Channel network, all other cells NoData"	""
 "Channel side slope(m/m)"	"Gew�sserseite Neigung (m/m)"
-"Channel width constant ((s/m)^1/2"	""
-"Channel width constant [(s/m)^0.5]"	""
-"Channel_depth"	""
-"Channel_type"	""
 "Channels"	"Gew�sser"
 "Channels (Raster)"	"Gew�sser (Raster)"
 "Channels (Vector)"	"Gew�sser (Vektor)"
@@ -809,7 +789,6 @@ TEXT	TRANSLATION
 "Check Point Validity"	"Kontrollpunkt G�ltigkeit"
 "Check Vertices"	""
 "Check for Building Parts"	""
-"Check the attributes to drop"	""
 "Check the fields to export"	""
 "Check this in order to include NoData cells in the calculation."	""
 "Check this in order to include NoData points in the calculation."	""
@@ -821,6 +800,7 @@ TEXT	TRANSLATION
 "Chip size of reference chip to be found in search chip"	""
 "Chip size of search chip, used to find correlating reference chip"	""
 "Choice"	"Auswahl"
+"Choose 'slim' to trace grid node's shadow, 'fat' to trace the whole cell's shadow, or ignore shadowing effects. The first is slightly faster but might show some artifacts."	""
 "Choose 'slim' to trace grid node's shadow, 'fat' to trace the whole cell's shadow. The first is slightly faster but might show some artifacts."	""
 "Choose Cut from ..."	"W�hle Zuschnitt von.."
 "Choose Directory"	"Wechsle Verzeichnis"
@@ -851,6 +831,7 @@ TEXT	TRANSLATION
 "Circle Point Distance [Degree]"	"Entfernung der Kreislinienpunkte [in Grad]"
 "Circles"	"Kreise"
 "Circular"	"Kreisf�rmig"
+"Citation"	""
 "CityGML file import failed"	""
 "CityGML import failed"	""
 "Class"	"Klasse"
@@ -859,8 +840,11 @@ TEXT	TRANSLATION
 "Class Identifier"	"Klassenidentifizierer"
 "Class Name"	""
 "Class Selection"	"Klassenauswahl"
+"Class Values"	""
 "Classes"	"Klassen"
 "Classification"	"Klassifizierung"
+"Classification 1"	""
+"Classification 2"	""
 "Classification Constant"	"Klassifizierung Konstant"
 "Classification Method"	""
 "Classification Quality"	"Klassifizierungsqualit�t"
@@ -878,10 +862,7 @@ TEXT	TRANSLATION
 "Clear Selection"	""
 "Climate"	"Klima"
 "Climate Data"	"Klimadaten"
-"Climate and Weather Data"	""
-"Climate data regionalisation."	""
 "Climate parameters"	"Klima Parameter"
-"Climate|Climate Data"	""
 "Climatic Precession"	""
 "Clip Features"	""
 "Clip Grid with Polygon"	"Schneide Rasterdaten mit Polygon zu"
@@ -899,6 +880,7 @@ TEXT	TRANSLATION
 "Close Gaps with Spline"	"Schlie�e L�cken mit Spline"
 "Close Gaps with Stepwise Resampling"	""
 "Close One Cell Gaps"	"Schlie�e Einzellenl�cken"
+"Close Project"	""
 "Close all data sets"	""
 "Closed Depressions"	""
 "Closed Gaps Grid"	"Raster mit geschlossenen L�cken"
@@ -916,9 +898,6 @@ TEXT	TRANSLATION
 "ClusterID"	"Cluster ID"
 "Clusters"	"Cluster"
 "Coefficient of Determination"	"Bestimmtheitsma�"
-"Cold Air Height"	""
-"Cold Air Surface"	""
-"Cold Air Temperature [�C]"	""
 "Cold Cloud"	""
 "Collect values"	"Sammele Werte"
 "Collpase Options"	""
@@ -945,9 +924,11 @@ TEXT	TRANSLATION
 "Colours"	""
 "Colours Palette"	""
 "Columns"	"Spalten"
+"Combination"	""
 "Combination A"	"Kombination A"
 "Combination B"	"Kombination B"
 "Combine Grids"	"Verbinde Raster"
+"Combined Classes"	""
 "Combined Minimum Distance / Hillclimbing"	"kombinierte Minimalentfernung / Bergsteigeralgorithmus"
 "Combined Shading"	"Kombinationsschummerung"
 "Comma Separated Values"	"durch Kommata getrennte Werte"
@@ -970,17 +951,19 @@ TEXT	TRANSLATION
 "CompuServe Graphics Interchange"	"CompuServe Graphics Interchange"
 "CompuServe Graphics Interchange (*.gif)"	"CompuServe Graphics Interchange (*.gif)"
 "Computed flow directions, 0=N, 1=NE, 2=E, ... 7=NW"	"Berechnete Flie�richtung. 0=N, 1=NE, 2=E, ... 7=NW"
-"Concentration"	""
-"Concentration Approximation Threshold"	""
 "Concentration time (h)"	"Sammlungszeit (h)"
-"Conceptualization of Spatial Relationships"	""
 "Condition"	"Bedingung"
 "Cone (Down)"	"Kegel (abw�rts)"
 "Cone (Up)"	"Kegel (aufw�rts)"
 "Cone (down)"	"Kegel (abw�rts)"
 "Cone (up)"	"Kegel (aufw�rts)"
 "Confirm file caching"	"Dateipufferaktivierung jedesmal best�tigen"
+"Confusion"	""
 "Confusion Index"	""
+"Confusion Matrix"	""
+"Confusion Matrix (Polygons / Grid)"	""
+"Confusion Matrix (Two Grids)"	""
+"Connect to Database"	""
 "Connect to ODBC Source"	""
 "Connect to PostgreSQL"	""
 "Connected"	""
@@ -992,8 +975,8 @@ TEXT	TRANSLATION
 "Connectivity Neighbourhood"	""
 "Connectivity Weighting"	"Konnektivit�t Gewichtung"
 "Connectivity [Percent]"	"Konnektivit�t [Prozent]"
-"Conrad"	""
 "Constant Grid"	""
+"Constant Histogram Stretch"	""
 "Constant Value"	""
 "Constant Variation Range [Degree]"	"konstanter Streubereich [Grad]"
 "Constant Wind Direction"	""
@@ -1059,6 +1042,8 @@ TEXT	TRANSLATION
 "Copy Legend to Clipboard [Ctrl+L]"	""
 "Copy Legend to Clipboard..."	""
 "Copy Map to Clipboard [Ctrl+C]"	""
+"Copy Project to Database"	""
+"Copy Project to..."	""
 "Copy Selection"	""
 "Copy Selection to New Shapes Layer"	"Kopiere Auswahl zu Neuer Vektorebene"
 "Copy Settings from other Layer"	""
@@ -1066,7 +1051,7 @@ TEXT	TRANSLATION
 "Copy attributes from input to output point cloud."	""
 "Copy existing Attributes"	""
 "Copy to Clipboard"	""
-"Copying original data..."	"Kopiere Originaldaten�"
+"Copying original data..."	"Kopiere Originaldaten?"
 "Copyright (c) 2007 by Thomas Schorr"	""
 "Copyrights (c) 2003 by Andre Ringeler"	""
 "Copyrights (c) 2003 by Olaf Conrad"	""
@@ -1102,12 +1087,12 @@ TEXT	TRANSLATION
 "Count Only Above Base Level"	"Z�hle nur �ber Ausgangsniveau"
 "Count Only Below Base Level"	"Z�hle nur unter Ausgangsniveau"
 "Count Points in Polygons"	"Anzahl Punkte in Polygonen"
-"Counter for function calls greater 0"	""
 "Covariance"	"Kovarianz"
 "Covariance Surface"	"Kovarianz Oberfl�che"
 "Covered Distance"	"zur�ckgelegte Entfernung"
 "Create 3D Image"	"Erzeuge 3D Bild"
 "Create Chart Layer (bars/sectors)"	"Erzeuge Diagrammebene (Balken/Sektoren)"
+"Create Database"	""
 "Create Graticule"	""
 "Create Grid System"	"Erzeuge Rastersystem"
 "Create KML File"	"Erzeuge KML Datei"
@@ -1120,7 +1105,8 @@ TEXT	TRANSLATION
 "Create PDF Documents"	"Erzeuge PDF Dokumente"
 "Create Point Grid"	"Erzeuge Punktraster"
 "Create Propabilities"	""
-"Create Reference Data"	""
+"Create Raster Catalogue from Files"	""
+"Create Raster Catalogues from Directory"	""
 "Create Reference Points"	"Erzeuge Referenzpunkte"
 "Create Script Command File"	""
 "Create Single Multipart Polygon"	""
@@ -1182,6 +1168,7 @@ TEXT	TRANSLATION
 "D/sqrt(A)"	"D/Quadratwurzel (A)"
 "D8"	""
 "DATA_CELLS"	""
+"DBMS"	""
 "DBase"	"DBase"
 "DBase file could not be opened."	""
 "DBase file does not contain any records."	""
@@ -1199,12 +1186,10 @@ TEXT	TRANSLATION
 "DIFF_MEAN"	"DIFFERENZ_DURCHSCHNITT"
 "DN"	""
 "DSN"	"Datenbank Server Name (DSN)"
-"DT Time step size (yrs)"	""
 "DTM 1"	""
 "DTM 2"	""
 "DTM Filter (slope-based)"	"DGM Filter (Neigungsbasiert)"
 "DTM, digital terrain model [m]"	"DTM, digitales Gel�ndemodell [m]"
-"DTMIN Minimum sub-time"	""
 "DXF"	""
 "DXF Files (*.dxf)|*.dxf|All Files|*.*"	"DXF Dateien (*.dxf)|*.dxf|Alle Dateien|*.*"
 "Daily Data"	""
@@ -1214,23 +1199,21 @@ TEXT	TRANSLATION
 "Dark Object Subtraction"	""
 "Darkness Digital Number (DN)"	""
 "Data"	""
-"Data Directory"	""
 "Data History"	""
 "Data Manager"	"Datenverwaltung"
 "Data Object"	""
 "Data Objects"	""
 "Data Offset (Bytes)"	"Daten Versatz (Bytes)"
-"Data Source"	"Datenquelle"
 "Data Source Name"	"Name Datenquelle"
+"Data Sources"	""
 "Data Storage Type"	"Datenspeichertyp"
 "Data Table"	"Datentabelle"
 "Data Type"	"Datentyp"
-"Data completion..."	"Daten ausf�hren�"
+"Data completion..."	"Daten ausf�hren?"
 "Data options"	""
 "Data storage type"	"Datenspeichertyp"
 "Data type"	""
 "Database"	"Datenbank"
-"Database Connection Error"	"Datenbank Verbindungs Fehler"
 "Database Name"	""
 "Database access through the libmysql.lib interface."	"Datenbank-Zugriff durch das libmysql.lib Interface."
 "Database with Coordinate Reference System (CRS) definitions. A restart of SAGA is required to have the changes take effect!"	""
@@ -1248,9 +1231,9 @@ TEXT	TRANSLATION
 "Datums (3 Parameters)"	"Bezugspunkt (3 Parameter)"
 "Datums (7 Parameters)"	"Bezugspunkt (7 Parameter)"
 "Day"	"Tag"
+"Day Length"	""
 "Day of Month"	"Monatstag"
 "Day of Year"	"Tag des Jahres"
-"Day of Year (End of Range)"	"Tag des Jahres (Ende des Bereichs)"
 "Day-Degree Factor"	"Day-Degree Faktor"
 "Day-Degree Factor (lower bound)"	"Day-Degree Faktor (untere Grenze) "
 "Day-Degree Factor (upper bound)"	"Day-Degree Faktor (obere Grenze)"
@@ -1279,7 +1262,6 @@ TEXT	TRANSLATION
 "Default Reference Height"	""
 "Default Rotation"	""
 "Default Size"	"Vorgegebene Gr��e"
-"Default Weathering Formula"	""
 "Defaults"	"Vorgaben"
 "Defaults for New Maps"	""
 "Define AOI by ..."	"Definiere AOI durch.. "
@@ -1287,7 +1269,6 @@ TEXT	TRANSLATION
 "Definition"	""
 "Degree"	"Grad"
 "Dekang Lin"	""
-"Delay"	""
 "Delete"	"Entfernen"
 "Delete All Positions"	""
 "Delete All Positions [Ctrl + X]"	""
@@ -1295,19 +1276,16 @@ TEXT	TRANSLATION
 "Delete Fields"	"Felder l�schen"
 "Delete History Entries"	""
 "Delete Last Position [Ctrl + D]"	""
-"Delete Last Position [D]"	"Entferne letzten Punkt [D]"
 "Delete Selected Part"	"Entferne ausgew�hlten Teil"
 "Delete Selected Point"	"Entferne ausgew�hlte Punkte"
-"Delete Selected Record(s)"	"Entferne ausgew�hlte Datens�tze"
-"Delete Selected Shape(s)"	"Entferne ausgew�hlte Vektoren"
 "Delete Selection"	""
 "Delete Selection from Shapes Layer"	"Entferne Auswahl aus Vektorebene"
 "Delete selected point(s)."	"Entferne ausgew�hlte Punkte."
 "Delete selected shape(s)."	"Entferne ausgew�hlte(n) Vektor(en)."
+"Deleting raster band"	""
 "Deleting table"	"Entferne Tabelle"
 "Delineated watershed basins"	"eingezeichnete Wassereinzugsgebiete"
 "Delivery Index"	""
-"Dem"	""
 "Denoised"	""
 "Denoised Grid"	""
 "Denormalisation"	"Denormalisierung"
@@ -1324,7 +1302,6 @@ TEXT	TRANSLATION
 "Depression-free digital elevation model"	"Senkenfreies digitales H�henmodell"
 "Depth"	"Tiefe"
 "Depth to which data history is stored. Set -1 keeps all history entries (default), 0 switches history option off."	"Tiefe bis zu der die Datengeschichte gespeichert wird. -1 beh�lt alle Eintr�ge (Voreinstellung), 0 schaltet die Funktion ab."
-"Depth_base_rock"	""
 "Der Gerinne- bzw. Hauptgerinneabfluss kann mit dieser Methode fuer Rasterzelle 1 manipuliert werden. "	""
 "Der Gerinne- bzw. Hauptgerinneabfluss kann mit dieser Methode fuer Rasterzelle 2 manipuliert werden. "	""
 "Derivation of slope lengths from catchment areas. These are rough approximations! Applies not to Desmet & Govers' method."	"Abweichung der Hangl�nge vom Einzugsgebiet. Dieses sind grobe Absch�tzungen! Entspricht nicht der Methode von Desmet & Govers."
@@ -1344,6 +1321,7 @@ TEXT	TRANSLATION
 "Detector type"	"Detectortyp"
 "Determination"	""
 "Determination Coefficients"	""
+"Determines how the graticule is aligned to the extent, if division sizes do not fit."	""
 "Deterministic 8"	"Deterministisch 8"
 "Deterministic 8 (D8)"	"Deterministisch 8 (D8)"
 "Deterministic Infinity"	"deterministische Unendlichkeit"
@@ -1372,11 +1350,7 @@ TEXT	TRANSLATION
 "Diffusive Hillslope Evolution (ADI)"	""
 "Diffusive Hillslope Evolution (FTCS)"	""
 "Diffusivity [m2 / kyr]"	""
-"Diffusivity coefficient Kd (m^2/yr"	""
-"Diffusivity coefficient Kd (m^2/yr)"	""
-"Diffusivity coefficient Kd [m^2/a]"	""
 "Difuse Pollution Risk"	""
-"Digital Elevation Model"	""
 "Digital Elevation Model that has to be processed"	"Digitales Gel�ndemodell dass berechnet werden soll"
 "Digital Terrain Model"	"Digitales Gel�ndemodell"
 "Digital elevation model"	"Digitales H�henmodell"
@@ -1393,6 +1367,7 @@ TEXT	TRANSLATION
 "Direct Insolation"	"Direkte Sonneneinstrahlung"
 "Direct to Diffuse Ratio"	"Direkt zu diffus Verh�ltnis"
 "Direction"	"Richtung"
+"Direction Difference"	""
 "Direction [Degree]"	"Richtung [Grad]"
 "Direction into which the wind blows, starting with 0 for North and increasing clockwise."	""
 "Direction of Minimum Standard Deviation"	"Richtung der minimalen Standardabweichung"
@@ -1405,10 +1380,7 @@ TEXT	TRANSLATION
 "Directional Statistics for Points"	"Gerichtete Statistik f�r Punkte"
 "Directional Statistics for Single Grid"	"Gerichtete Statistik f�r Einzelraster"
 "Directory"	"Verzeichnis"
-"Directory with NCAR Grib Files"	""
 "Directory, where temporary cache files shall be saved."	"Verzeichnis, in dem tempor�re Dateipuffer gespeichert werden sollen."
-"Discharge exponent Mb for bedrock channel erosion"	""
-"Discharge exponent Mf for fluvial sediment transport"	""
 "Disconnect All"	""
 "Disconnect from ODBC Source"	""
 "Disconnect from PostgreSQL"	""
@@ -1419,9 +1391,6 @@ TEXT	TRANSLATION
 "Displacement Vector"	""
 "Displacement vectors between correlated points"	""
 "Display"	"Anzeige"
-"Display Maximun"	""
-"Display Minimum"	""
-"Display Minimun"	""
 "Display Resolution"	"Aufl�sung Anzeige"
 "Display Type"	"Anzeige Typ"
 "Dissolve Buffers"	"Aufgel�ste Puffer"
@@ -1441,14 +1410,10 @@ TEXT	TRANSLATION
 "Distance Weighting"	"Entfernungs Gewichtung"
 "Distance Weighting Exponent"	""
 "Distance between points (grid units)."	"Entfernung zwischen Punkten (in Rastereinheiten)"
-"Distance to the Channel"	""
-"Distance to the Crest"	""
 "Distances"	""
 "Distinct"	"Deutlich"
 "Diurnal Anisotropic Heating"	"T�gliche anisotrope Erw�rmung"
 "Divergence"	"Abweichung"
-"Divergent Flow Accumulation / Object Update"	""
-"Divergent Upslope Curvature"	""
 "Diversity"	"Diversit�t"
 "Diversity of Categories"	""
 "Dividend"	""
@@ -1458,6 +1423,7 @@ TEXT	TRANSLATION
 "Division by zero is not allowed !!!"	"Division durch null ist nicht zul�ssig !!!"
 "Divisor"	""
 "Do you really want to delete the table"	"Wollen Sie die Tabelle wirklich l�schen"
+"Do you really want to delete this raster band"	""
 "Do you want to delete the selection?"	"Soll die Auswahl entfernt werden?"
 "Do you want to exit SAGA?"	"Wollen Sie SAGA beenden?"
 "Do you wish to estimate Principal Point Offsets?"	""
@@ -1478,11 +1444,8 @@ TEXT	TRANSLATION
 "Downslope Basins"	"Hangfl�chenbecken"
 "Downslope Curvature"	""
 "Downslope Distance Gradient"	"Hangfl�chendistanz Gradient"
-"Downstream weighting factor (between zero and ~1/2)"	""
-"Drainage Area"	""
 "Drainage Basins"	""
 "Drainage Network"	"Entw�sserungsnetzwerk"
-"Drainage_area"	""
 "Drape Map"	""
 "Draw Box"	""
 "Draw Faces"	""
@@ -1492,6 +1455,8 @@ TEXT	TRANSLATION
 "Draw a section each n points"	"Zeichne einen Streckenanschnitt f�r jeden n-ten Punkt"
 "Driver"	""
 "Driver does not support file creation."	"Der Treiber unterst�tzt nicht die Dateierstellung."
+"Drop"	""
+"Drop Database"	""
 "Drop Point Cloud Attributes"	""
 "Drop Table"	""
 "Dummy Grid"	"Attrappenraster"
@@ -1500,7 +1465,6 @@ TEXT	TRANSLATION
 "Duration of Insolation"	"Dauer der Sonneneinstrahlung"
 "Dust [ppm]"	"Staub [ppm]"
 "Dust factor: 100 ppm (standard)"	"Staubfaktor: 100 ppm (standard)"
-"Dynamics"	""
 "Dynamische Flaechenwassernutzung und Abflussreduktion"	""
 "Dynamische Flaechenwassernutzung..."	""
 "EDGES"	"KANTEN"
@@ -1527,6 +1491,8 @@ TEXT	TRANSLATION
 "Eccentricity (e)"	"Exzentrizit�t (e)"
 "Eckert IV/VI"	""
 "Edge"	"Rahmen"
+"Edge Cells"	""
+"Edge Connectivity"	""
 "Edge Contamination"	"Flankenkontamination"
 "Edge Detection (ViGrA)"	""
 "Edge Points"	""
@@ -1537,16 +1503,13 @@ TEXT	TRANSLATION
 "Edit 3D-View Sequencer Positions"	""
 "Edit Point Cloud"	"Bearbeite Punktwolke"
 "Edit Positions"	"Positionen bearbeiten"
-"Edit Selected Shape"	"Ausgew�hlte Vektoren bearbeiten"
+"Edit Selection"	""
 "Edit Shapes"	"Vektoren bearbeiten"
 "Efective friction = stated friction ^f , where f = cos(DifAngle)^k."	"effektive Reibung = vorgegebene Reibung ^f , wobei f = cos(DifWinkel)^k. "
-"Eff. Precipitation Rate"	""
 "Effective Air Flow Heights"	"Effektive Luftflussh�hen"
 "Effective Flow Length"	""
 "Effective Rainfall"	""
 "Effective hydrological depth"	""
-"Effective precipitation rate (m/yr, or m/s for MPM)"	""
-"Effective precipitation rate, [m/a] or [m/s] for MPM"	""
 "Eigen Vectors"	""
 "Eigen reduction failed"	"Eigen Reduktion fehlgeschlagen"
 "Eigenvalue"	"Eigenwert"
@@ -1566,7 +1529,6 @@ TEXT	TRANSLATION
 "Elevation at Reference Station [m]"	"H�he an Referenzstation [m]"
 "Elevation grid"	"H�henraster"
 "Elevation range (zMax (%.2f) - zMin (%.2f)) is equal or lower than zero!"	""
-"Elevations"	""
 "Ellipsoid Definition"	"Ellipsoid Definition"
 "Ellipsoid Height [m]"	"Ellipsoid H�he [m]"
 "Ellipsoids"	"Ellipsoide"
@@ -1574,8 +1536,6 @@ TEXT	TRANSLATION
 "Encountered invalid path description in *.spcvf_tile_info file!"	""
 "End Latitude"	""
 "End Longitude"	""
-"End Time"	""
-"End with Year..."	""
 "Enforce True Color"	"Erzwinge Echtfarben"
 "Enhanced Vegetation Index"	""
 "Entropy"	""
@@ -1611,7 +1571,6 @@ TEXT	TRANSLATION
 "Estimated noise relative to mean standard deviation"	"abgesch�tztes Rauschen relativ zur mittleren Standardabweichung"
 "Et/Eo, ratio of actual to potential evapotranspiration"	""
 "Euclidean"	"Euklidisch"
-"Euclidian Distance"	""
 "EvP1 Name"	""
 "EvP2 Name"	""
 "EvP3 Name"	""
@@ -1624,7 +1583,6 @@ TEXT	TRANSLATION
 "Exaggeration"	"�berh�hung"
 "Exaggeration Factor"	"�berh�hung"
 "Exaggeration Z"	""
-"Excess shear stress exponent"	""
 "Exclude No-Data Area"	""
 "Exclude NoData Cells"	"Zellen ohne Wert ausschlie�en"
 "Execute"	"Ausf�hren"
@@ -1645,14 +1603,18 @@ TEXT	TRANSLATION
 "Export ESRI Arc/Info Grid"	"Export ESRI Arc/Info Rasterdaten"
 "Export GPX"	"Export GPX"
 "Export GStat Shapes"	"Export GStat Vektordaten"
+"Export GeoTIFF"	""
 "Export Grid to KML"	""
 "Export Grid to XYZ"	"Export Raster zu XYZ"
 "Export Image (bmp, jpg, pcx, png, tif)"	"Export Bild (bmp, jpg, pcx, png, tif)"
 "Export LAS Files"	"Export LAS Dateien"
 "Export Point Cloud to Text File"	""
+"Export Raster"	""
 "Export Raster to PostGIS"	""
 "Export Scalable Vector Graphics (SVG) File"	"Export Scalable Vector Graphics (SVG) Dateien"
+"Export Shapes"	""
 "Export Shapes to Generate"	"Export Vektoren die zu erzeugen sind"
+"Export Shapes to KML"	""
 "Export Shapes to PostGIS"	""
 "Export Shapes to XYZ"	"Export Vektoren als XYZ"
 "Export Simple Features to Well Known Text"	""
@@ -1667,6 +1629,7 @@ TEXT	TRANSLATION
 "Export to File"	""
 "Expression"	"Ausdruck"
 "Extended Neighourhood"	"erweiterte Nachbarschaft"
+"Extensions"	""
 "Extent"	"Umfang"
 "Extent [Cut]"	"Umfang [Zuschneiden]"
 "Extent to CellSize"	"Abh�ngig von Zellgr��e"
@@ -1705,7 +1668,7 @@ TEXT	TRANSLATION
 "Feigenbaum's Bifurcation"	"Feigenbaum�s Verzweigung"
 "Ferhat Bing�l (c) 2009"	""
 "Field"	"Feld"
-"Field %d: Name=\"%s\" "	""
+"Field %d: Name=\"	""
 "Field (ID)"	"Feld (ID)"
 "Field (Name)"	"Feld (Name)"
 "Field Capacity [mm]"	"Feldkapazit�t [mm]"
@@ -1750,7 +1713,6 @@ TEXT	TRANSLATION
 "Filepath"	""
 "Files"	"Dateien"
 "File|ESRI E00"	"Datei|ESRI E00"
-"File|GDAL/OGR"	"Datei|GDAL/OGR"
 "File|GPS Import"	"Datei|GPS Import"
 "File|Grid"	"Datei|Raster"
 "File|Reports"	"Datei|Berichte"
@@ -1761,12 +1723,12 @@ TEXT	TRANSLATION
 "Fill Color"	"F�llfarbe"
 "Fill Color 1"	""
 "Fill Color 2"	""
-"Fill Gaps (Mean Value Cellular Automat)"	""
 "Fill Gaps in Records"	""
 "Fill Increment"	""
 "Fill NoData"	"F�llen der NoData-Zellen"
 "Fill Sinks"	"F�lle Senken"
 "Fill Sinks (Planchon/Darboux, 2001)"	"F�lle Senken (Planchon/Darboux, 2001)"
+"Fill Sinks (QM of ESP)"	""
 "Fill Sinks (Wang & Liu)"	"F�lle Senken (Wang & Liu)"
 "Fill Sinks XXL (Wang & Liu)"	"F�lle Senken XXL (Wang & Liu)"
 "Fill Style"	"F�llstil"
@@ -1836,18 +1798,13 @@ TEXT	TRANSLATION
 "Floating Point (4 byte)"	"Flie�kommazahl (4 Byte)"
 "Floating Point (8 byte)"	"Flie�kommazahl (8 Byte)"
 "Floating point"	""
-"Flood Depth"	""
-"Flood Height"	""
-"Flooded"	""
-"Flooded Surface"	""
 "Flooded digital elevation model"	"�berflutetes Digitales H�henmodell"
-"Flooding Status"	""
-"Flooding_status"	""
 "Flow"	""
 "Flow Accumulation"	"Str�mung Akkumulierung"
 "Flow Accumulation (Flow Tracing)"	""
 "Flow Accumulation (Mass-Flux Method)"	""
 "Flow Accumulation (Parallel)"	"Str�mung Akkumulierung (Parallel)"
+"Flow Accumulation (QM of ESP)"	""
 "Flow Accumulation (Recursive)"	""
 "Flow Accumulation (Top-Down)"	""
 "Flow Accumulation (Trace)"	"Str�mung Akkumulierung (Spur)"
@@ -1877,8 +1834,6 @@ TEXT	TRANSLATION
 "Flow Width and Specific Catchment Area"	""
 "Flow at Gauges"	"Str�mung an Messlehren"
 "Flow threshold, given as amount of cells, above which flow transport is unlimited. Ignored if range equals zero."	""
-"Fluvial Transport"	""
-"Fluvial sediment transport coefficient Kf"	""
 "Flux"	""
 "Flux out of each cell, i.e. everything accumulated so far."	""
 "Flying Height"	""
@@ -1924,7 +1879,6 @@ TEXT	TRANSLATION
 "Fuel Model"	"Treibstoff Modell"
 "Full path to the directory for the output grids of each model step"	""
 "Function"	"Funktion"
-"Function Calls > 0"	""
 "Function Fit"	"Funktionsanpassung"
 "Function Fitting Range"	"Funktionsanpassungsbereich"
 "Function Parameters"	"Funktionsparameter"
@@ -1939,10 +1893,6 @@ TEXT	TRANSLATION
 "G"	""
 "GC, Ground cover expressed as a portion [between 0-1] of the soil surface protected by vegetation or crop cover on the ground"	""
 "GDAL/OGR"	""
-"GDAL: Export Raster"	"GDAL: Export Raster"
-"GDAL: Export Raster to GeoTIFF"	"GDAL: Export Raster zu GeoTIFF"
-"GDAL: Import NetCDF"	""
-"GDAL: Import Raster"	"GDAL: Import Raster"
 "GE / GR"	""
 "GE / V"	""
 "GE / X"	""
@@ -1954,7 +1904,6 @@ TEXT	TRANSLATION
 "GPX file"	"GPX Datei"
 "GPX files (*.gpx)|*.gpx|All Files|*.*"	"GPX Datei (*.gpx)|*.gpx|Alle Dateien|*.*"
 "GPX to shapefile"	"GPX zu Vektordatei"
-"GRAD * MFD"	""
 "GREEN_BLUE"	"GR�N_BLAU"
 "GREEN_GREY_BLUE"	"GR�N_GRAU_BLAU"
 "GREEN_RED_BLUE"	"GR�N_ROT_BLAU"
@@ -1980,7 +1929,6 @@ TEXT	TRANSLATION
 "Games"	"Spiele"
 "Gamma"	""
 "Garden"	""
-"Garden|Dynamics"	""
 "Garden|Introducing Module Programming"	"Testversionen|Einf�hrung in die Modulprogrammierung"
 "Garden|Recreations|Fractals"	"Testversionen|Erholung|Fraktale"
 "Garden|Recreations|Games"	"Testversionen|Erholung|Spiele"
@@ -1993,7 +1941,6 @@ TEXT	TRANSLATION
 "Gaussian Landscapes"	"Gaussche Landschaften"
 "Gaussian and Exponential Weighting Bandwidth"	"Gaussche und exponentiale gewichtete Bandbreite"
 "Gc"	""
-"Geary's C"	""
 "General"	"Allgemein"
 "General Curvature"	""
 "General Settings"	"Allgemeine Einstellungen"
@@ -2001,7 +1948,6 @@ TEXT	TRANSLATION
 "Generalized Surface"	""
 "Generate Shapes"	"Erzeuge Vektoren"
 "Generated Shapefile."	"Erzeuge Vektordatei."
-"Generic"	""
 "Geo-Reference"	"Georeferenz"
 "GeoTIFF (*.tif)"	""
 "GeoTIFF Files"	""
@@ -2021,7 +1967,6 @@ TEXT	TRANSLATION
 "Geoid"	"Geoid"
 "Geometric Figures"	"Geometrische Figur"
 "Geometry Type"	""
-"Geopotential Height"	""
 "Geoprocessing"	"Geoverarbeitung"
 "Georeferencing"	""
 "Get CRS Definition from..."	"Hole CRS-Definitionen von...."
@@ -2037,10 +1982,6 @@ TEXT	TRANSLATION
 "Globe Viewer for Grids"	""
 "Gnomonic"	"Gnomonisch"
 "Gpx2shp path"	"Gpx2shp Pfad"
-"GraD"	""
-"Grad"	""
-"Grad Norm"	""
-"Grad_Poss"	""
 "Gradient"	"Gradient"
 "Gradient Calculation"	"Gradientkalkulation"
 "Gradient Difference"	"Gradient Differenz"
@@ -2051,7 +1992,7 @@ TEXT	TRANSLATION
 "Gradient Vectors from Directional Components"	""
 "Gradient Vectors from Surface"	""
 "Gradient threshold"	"Gradient Schwellenwert"
-"Gradient_Tangs"	""
+"Gradients"	""
 "Graduated"	""
 "Graduated Colors"	""
 "Graduated Colours"	""
@@ -2062,7 +2003,6 @@ TEXT	TRANSLATION
 "Green (TM 3)"	"Gr�n (TM 3)"
 "Green-Ampt Infiltration"	"Gr�n-ampt Infiltration"
 "Greenness"	""
-"Grib Files (*.grb)"	""
 "Grid"	"Raster"
 "Grid 1"	"Raster 1"
 "Grid 2"	"Raster 2"
@@ -2104,7 +2044,6 @@ TEXT	TRANSLATION
 "Grid describing the AOI."	""
 "Grid describing the state of each cell at timestep t + 1."	""
 "Grid describing the state of each cell at timestep t."	""
-"Grid file could not be opened."	"Rasterdatei konnte nicht ge�ffnet werden."
 "Grid file could not be saved."	"Rasterdatei konnte nicht gespeichert werden."
 "Grid list"	"Rasterliste"
 "Grid range"	"Raster Bereich"
@@ -2116,8 +2055,6 @@ TEXT	TRANSLATION
 "Grid to filter"	"zu filterndes Raster"
 "Grid to reclassify"	"neueinzuteilendes Raster"
 "Grid value equals low value"	"Rasterwert ist gleich zu niedrigem Wert"
-"Grid with Gaps"	""
-"Grid with Gaps Filled"	""
 "Grid with category of nearest source cell [Category]"	"Raster mit Gruppen n�chster Ausgangszellen [Kategorie]"
 "Grid with euclidian distance to nearest source cell [grid units]"	"Raster mit euklidischer Entfernung zu n�chsten Ausgangszellen [Rastereinheiten]"
 "Grid with features to be buffered [Category/NoData]"	"Raster mit Merkmalen die zu puffern sind [Kategorie/NoData]"
@@ -2137,8 +2074,10 @@ TEXT	TRANSLATION
 "Grids with continuous data, statistics are calculated for each grid. Coding: NoData / continuous values."	""
 "Grid|Analysis"	"Raster|Auswertung"
 "Grid|Calculus"	"Raster|Berechnung"
+"Grid|Export"	""
 "Grid|Filter"	"Raster|Filter"
 "Grid|Gridding"	"Raster|Rastern"
+"Grid|Import"	""
 "Grid|Tools"	"Raster|Werkzeuge"
 "Ground cover"	""
 "Group A"	"Gruppe A"
@@ -2183,7 +2122,6 @@ TEXT	TRANSLATION
 "Hill Radius"	""
 "Hill-Climbing (Rubin 1967)"	"Bergsteigeralgorithmus (Rubin 1967)"
 "Hillslope Index"	""
-"Hillslope_reservoir"	""
 "Histogram"	"Histogramm"
 "Histogram Stretch"	""
 "Histogram Stretch Dialog"	""
@@ -2194,8 +2132,7 @@ TEXT	TRANSLATION
 "Histogram cloud signature:"	""
 "History"	"Entstehung"
 "History Depth"	"Stufen der Entstehung"
-"Hodge-Podge"	""
-"Hodge-Podge Machine"	""
+"Hofierka and Suri"	""
 "Hollow"	""
 "Homepage"	""
 "Homogenous"	"Homogen"
@@ -2205,13 +2142,11 @@ TEXT	TRANSLATION
 "Horizontal Offset"	""
 "Horizontal Overland Flow Distance"	"Horizontale �ber Land Str�mungsdistanz"
 "Horizontal Range"	"Horizontaler Bereich"
-"Horizontal Tracer Density"	""
 "Horizontal hatch"	"horizontale Schraffur"
 "Horizontally mirrored"	"horizontal gespiegelt"
 "Host"	""
 "Hourly Data"	"St�ndliche Daten"
 "How many trees to create?"	""
-"Html Extra Info"	""
 "Hull Construction"	"H�llenkonstruktion"
 "Humedad del combustible herb�ceo vivo"	""
 "Humedad del combustible le�oso vivo"	""
@@ -2220,10 +2155,6 @@ TEXT	TRANSLATION
 "Humedad del combustible muerto en 100-horas"	""
 "Humification Factor"	"Humifizierungsfaktor"
 "Humus to Charcoal"	"Humus zu Kohle"
-"Hydro CA"	""
-"Hydro CA 2"	""
-"Hydro CA 3"	""
-"Hydro CA 4"	""
 "Hydrology"	""
 "Hydrology: IHACRES"	""
 "Hypsometric Curve"	"Hypsometriekurve"
@@ -2257,7 +2188,6 @@ TEXT	TRANSLATION
 "Ice"	"Eis"
 "Identifier"	"Bezeichner"
 "Identity"	""
-"If Table exists..."	""
 "If checked the snow module is active"	"Wenn abgehakt ist das Schneemodul aktiv"
 "If checked, it means there is no external inflow to the subbasin"	"Wenn abgehakt, gibt es keinen externen Zustrom zu dem Teilbecken"
 "If checked, snow-melt module is used."	"Wenn abgehakt wird das Schneeschmelzmodul benutzt."
@@ -2313,8 +2243,6 @@ TEXT	TRANSLATION
 "Import Filter"	"Import Filter"
 "Import GPX"	"Import GPX"
 "Import GRIB2 record"	"Import GRIB2 Datensatz"
-"Import GSOD Stations to Data Base"	""
-"Import GSOD to Data Base"	""
 "Import GStat Shapes"	"Import GStat Vektoren"
 "Import Grid from Table"	"Import Raster von Tabelle"
 "Import Grid from XYZ"	"Import Raster von XYZ"
@@ -2325,12 +2253,15 @@ TEXT	TRANSLATION
 "Import NetCDF"	""
 "Import Point Cloud from Shape File"	""
 "Import Point Cloud from Text File"	"Import Punktwolken von Textdateien"
+"Import Raster"	""
 "Import Raster from PostGIS"	""
 "Import SRTM30 DEM"	"Import SRTM30 DGM"
 "Import Scalable Vector Graphics (SVG) File"	"Import Scalable Vektor Graphics (SVG) Dateien"
+"Import Shapes"	""
 "Import Shapes from PostGIS"	""
 "Import Shapes from XYZ"	"Import Vektoren von XYZ"
 "Import Simple Features from Well Known Text"	""
+"Import Single Raster Band from PostGIS"	""
 "Import Stereo Lithography File (STL)"	"Import Stereo Lithography Dateien (STL)"
 "Import Surfer Blanking Files"	"Import Surfer Blanking Dateien"
 "Import Surfer Grid"	"Import Surfer Rasterdateien"
@@ -2355,7 +2286,6 @@ TEXT	TRANSLATION
 "In this section you can define the topology of the neural network."	""
 "In/Out"	"Eingabe/Ausgabe"
 "Include Center Cell"	""
-"Include Planetery Bending"	""
 "Include X Coordinate"	""
 "Include Y Coordinate"	""
 "Include a category for cloud shadows"	""
@@ -2374,7 +2304,6 @@ TEXT	TRANSLATION
 "Index"	""
 "Indicatrix"	""
 "Indices"	""
-"Infection Speed"	""
 "Infiltration excess runoff [m/dt]"	"Versickerungs�berschuss Abfluss [m/dt]"
 "Infiltration rate [m/dt]"	"Versickerungsrate"
 "Informe"	"Benachrichtigen"
@@ -2386,24 +2315,19 @@ TEXT	TRANSLATION
 "Initial Number of Fishes [%]"	"Anfangsanzahl von Fischen [%]"
 "Initial Number of Sharks [%]"	"Anfangsanzahl von Haien [%]"
 "Initial State"	"Anfangszustand"
-"Initial Surface"	""
 "Initial Threshold for Slope"	"Anfangsschwellenwert f�r das Gef�lle"
 "Initial root zone storage deficit [m]"	"Anfangswurzelzonen Speicher Defizit [m]"
-"Initial sediment cover (m)"	""
-"Initial sediment cover thickness (m)"	""
 "Initial subsurface flow per unit area [m/h]"	"Anf�ngliche unterirdische Str�mung pro Fl�cheneinheit [m/h]"
 "Initial update value"	""
 "Initial value delta_0 of update-values delta_ij."	""
 "Initialisation"	"Initialisierung"
 "Initialization Value"	"Initialisierungswert"
-"Initialize"	""
 "Initializing ..."	"Initialisierend..."
 "Initializing Fields"	""
 "Initializing direction matrix..."	"Initialisere Richtungsmatrix..."
 "Initiation Grid"	"Startraster"
 "Initiation Threshold"	"Anfangsschwellenwert"
 "Initiation Type"	"Anfangs Typ"
-"Inlet Concentration"	""
 "Inner Buffer"	""
 "Input"	"Eingabe"
 "Input Binary Grid"	""
@@ -2527,10 +2451,10 @@ TEXT	TRANSLATION
 "K2"	""
 "K3"	""
 "KE"	""
-"KF Fluvial sediment transport coefficien"	""
 "KML files (*.kml)"	""
 "KML/KMZ File"	""
 "KML/KMZ Files"	""
+"KMZ Files"	""
 "Kappa"	""
 "Kappa Offset [degree]"	""
 "Kappa [degree]"	""
@@ -2560,7 +2484,6 @@ TEXT	TRANSLATION
 "LAS Info"	"LAS Info"
 "LAS header exception: %s"	""
 "LAS reader exception: %s"	""
-"LEM 2013-02-21"	""
 "LFAC("	"LFAC("
 "LP, Saturated lateral permeability of the soil [m/day]"	""
 "LS"	""
@@ -2605,19 +2528,14 @@ TEXT	TRANSLATION
 "Landsat-5 TM"	""
 "Landsat-7 ETM+"	""
 "Landsat-8 OLI/TIRS"	""
-"Landscape Evolution"	""
-"Landscape Evolution Model"	""
-"Landscape Evolution Modelling"	""
 "Language Translations"	"Sprach�bersetzungen"
 "Laplace Filter"	"Laplace Filter"
 "Laplacian Filter"	"Laplace Filter"
 "Laplacian Filter Kernel"	""
 "Last Day"	"Letzter Tag"
-"Last RingeLEM"	""
 "Lat"	""
 "Lat. of True Scale"	"Breitengrad des genauen Massstabs"
 "Latitude"	"Breitengrad"
-"Latitude (user defined reference)"	"Breitengrad (Nutzer definierte Referenz)"
 "Latitude / Longitude Increment"	""
 "Latitude 1"	"Breitengrad 1"
 "Latitude 2"	"Breitengrad 2"
@@ -2626,8 +2544,6 @@ TEXT	TRANSLATION
 "Latitude Increment [Degree]"	""
 "Latitude Pole"	"Breitengrad Pol"
 "Latitude [Degree]"	""
-"Latitude [degree]"	"Breitengrad [Grad]"
-"Latitude relates to grid's..."	"Breitengrad verkn�pft mit Rastern..."
 "Latitude/Longitude Graticule"	""
 "Latitudinal Statistics"	""
 "Layer A"	"Ebene A"
@@ -2670,7 +2586,6 @@ TEXT	TRANSLATION
 "Level Heights"	""
 "Level of Detail"	"Detaillierungsgrad"
 "Level of Generalisation"	"Stufe der Generalisierung"
-"Levels"	""
 "Library"	"Bibliothek"
 "Life"	"Leben"
 "Life Cycle"	"Lebenszyklus"
@@ -2708,6 +2623,7 @@ TEXT	TRANSLATION
 "Lines (extended)"	""
 "Lines and Points"	"Linien und Punkte"
 "Lines with Property Attributes"	""
+"Linke Turbidity Coefficient"	""
 "List"	"Liste"
 "List ODBC Servers"	""
 "List PostgreSQL Connections"	""
@@ -2717,8 +2633,6 @@ TEXT	TRANSLATION
 "List of Measured Points as PC"	""
 "List of Shapes Layers"	"Vektordatens�tze"
 "Listing"	""
-"Lithology"	""
-"Lithology_of_uppermost_rock_layer"	""
 "Litter to Humus"	"Abfall zu Humus"
 "Litterfall Rate [g/m\xb2/a]"	""
 "Little Endian (Intel)"	""
@@ -2737,6 +2651,7 @@ TEXT	TRANSLATION
 "Load Tool Library"	"Lade Werkzeugbibliothek"
 "Load all bands"	""
 "Load from File..."	""
+"Load from Workspace"	""
 "Load grid"	"Lade Raster"
 "Load library"	"Lade Bibliothek"
 "Load point cloud"	"Lade Punktwolke"
@@ -2745,7 +2660,6 @@ TEXT	TRANSLATION
 "Load shapefile after conversion"	"Lade Vektordatei nach Umwandlung"
 "Load shapes"	"Lade Vektoren"
 "Load table"	"Lade Tabelle"
-"Load to Memory"	""
 "Load tool chain"	""
 "Loaded Grid"	""
 "Loaded Shapes"	""
@@ -2753,23 +2667,17 @@ TEXT	TRANSLATION
 "Loam"	"Lehm"
 "Loamy Sand"	"lehmiger Sand"
 "Local Cartesian"	"�rtlich Kartesisch"
-"Local Correlation"	""
 "Local Curvature"	""
 "Local Downslope Curvature"	""
-"Local Geary's C"	""
 "Local Maxima"	"Lokales Maximum"
 "Local Minima"	"Lokales Minimum"
 "Local Minima and Maxima"	"Lokale Minima und Maxima"
-"Local Moran's I"	""
 "Local Ridges"	""
 "Local Ridges, Hills in Valleys"	""
 "Local Rotation Base Level"	"Lokale Rotation der Grundlinie"
 "Local Rotation [Degree]"	"Lokale Rotation [Grad]"
 "Local Sky View Factor"	"Lokaler Himmelsblickfaktor"
-"Local Spatial Autocorrelation"	""
-"Local Time (user defined reference)"	"Ortszeit (Benutzerdefinierte Referenz)"
 "Local Upslope Curvature"	""
-"Local time relates to grid's..."	"Ortszeit bezieht sich auf Raster.."
 "Locate STRM30 Data File"	"Lokalisiere STRM30 Datendateien"
 "Locate..."	"Lokalisiere..."
 "Location"	"Position"
@@ -2792,7 +2700,6 @@ TEXT	TRANSLATION
 "Longitude 2"	"L�ngengrad 2"
 "Longitude 3"	"L�ngengrad 3"
 "Longitude Pole"	"L�ngengrad Pol"
-"Longitude [degree]"	"L�ngengrad [Grad]"
 "Longitudinal Curvature"	""
 "Longitudinal Grid Statistics"	""
 "Longitudinal Profile"	"l�ngslaufendes Profil"
@@ -2801,8 +2708,8 @@ TEXT	TRANSLATION
 "Look-up Table"	"Nachschlagetabelle"
 "LookUp Table"	"Nachschlagetabelle"
 "Lookup Table"	"Nachschlagetabelle"
-"Lookup table used in method \"table\""	"Nachschlagetabelle benutzt bei der Methode \"Tabelle\""
-"Lookup table used in method \"user supplied table\""	"Nachschlagetabelle benutzt bei der Methode \"durch Nutzer erstellte Tabelle\""
+"Lookup table used in method \"	"Nachschlagetabelle benutzt bei der Methode \"
+"Lookup table used in method \"	"Nachschlagetabelle benutzt bei der Methode \"
 "Lookup table."	"Nachschlagetabelle."
 "Loop"	""
 "Lotsa"	"Viele"
@@ -2831,7 +2738,6 @@ TEXT	TRANSLATION
 "MDE"	""
 "MEAN"	"MITTELWERT"
 "MFD"	""
-"MFD * Gradient"	""
 "MIN"	"MIN"
 "MINIMUM"	"MINIMUM"
 "MLRA Coefficients"	""
@@ -2840,13 +2746,13 @@ TEXT	TRANSLATION
 "MMF-SAGA Soil Erosion Model"	""
 "MOLA Grids (*.img)|*.img|All Files|*.*"	"MOLA Raster (*.img)|*.img|Alle Dateien|*.*"
 "MORAN_I"	""
-"MPM"	""
 "MRRTF"	""
 "MRVBF"	""
 "MS Windows Bitmap (*.bmp)|*.bmp|All Files|*.*"	"MS Windows Bitmap (*.bmp)|*.bmp|Alle Dateien|*.*"
 "MS, Soil moisture at field capacity [% w/w]"	""
 "MSL Height [m]"	"MSL H�he [m]"
 "Maehweide"	"M�hweide"
+"Magnitude"	""
 "Mahalanobis Distance"	"Mahalanobis Entfernung"
 "Main"	""
 "Main Basin ID"	"Hauptbecken ID"
@@ -2910,7 +2816,6 @@ TEXT	TRANSLATION
 "Maximum"	"Maximum"
 "Maximum Angle"	""
 "Maximum Cells (C Correction Analysis)"	"Maximum Zellen (C Korrekturanalyse)"
-"Maximum Change"	""
 "Maximum Contour Value"	"Maximaler Isolinienwert"
 "Maximum Curvature"	""
 "Maximum Deviation between estimated excess rainfall and observed streamflow volumes"	"Maximale Abwewichung zwischen abgesch�tzten Niederschlagsereignissen und beobachteten Abflussvolumina"
@@ -2937,7 +2842,6 @@ TEXT	TRANSLATION
 "Maximum Selection"	""
 "Maximum Sum of overestimated ExcessRain to total ExcessRain in [%]"	"Maximale Summe von �bereingesch�tztem �berschussregen zu totalem �berschussregen in [%]"
 "Maximum Temperature"	""
-"Maximum Thickness"	""
 "Maximum Time Span (Seconds)"	""
 "Maximum Total Order"	"Maximale Gesamtanordnung"
 "Maximum Value"	"Maximaler Wert"
@@ -2971,7 +2875,6 @@ TEXT	TRANSLATION
 "Mean Temperature"	""
 "Mean Value"	"Mittlerer Wert"
 "Mean Value (cell area weighted)"	"Mittlerer Wert (Zellbereich gewichtet)"
-"Mean annual flow per unit area (m/s for MPM)"	""
 "Mean less Standard Deviation"	"Mittelwert abz�glich Standardabweichung"
 "Mean over Catchment"	""
 "Mean plus Standard Deviation"	"Mittelwert zuz�glich Standardabweichung"
@@ -2979,7 +2882,6 @@ TEXT	TRANSLATION
 "Mean saturation deficit (in watershed) [m]"	"Mittleres S�ttigungsdefizit (im Einzugsgebiet) [m]"
 "Mean soil loss"	""
 "Mean temperature"	""
-"Mean_elevation"	""
 "Measure Distance"	""
 "Measured Points (PC)"	""
 "Median"	"Medianwert"
@@ -3041,15 +2943,14 @@ TEXT	TRANSLATION
 "Minimum Distance"	"Minimaldistanz"
 "Minimum Distance Analysis"	"Minimale Entfernung Analyse"
 "Minimum Exaggeration [%]"	"Minimale �berh�hung [%]"
-"Minimum Gradient"	""
 "Minimum Height"	""
 "Minimum Magnitude"	""
 "Minimum Nash-Sutcliffe Efficiency"	"Minimale Nash-Sutcliffe Effizienz"
 "Minimum Nash-Sutcliffe Efficiency required to print simulation to calibration table"	"Minimale Nash-Sutcliffe Effizienz erfordert, dass die Simulation in die Kalibrierungstabelle �bertragen wird"
+"Minimum Neighbours"	""
 "Minimum Node Split Size"	""
 "Minimum Number of Dark Object Cells"	""
 "Minimum Number of Points"	"Minimale Anzahl von Punkten"
-"Minimum Pressure Level [mb]"	""
 "Minimum Probability"	""
 "Minimum Redundancy Feature Selection"	""
 "Minimum Resolution (Degree)"	""
@@ -3058,18 +2959,15 @@ TEXT	TRANSLATION
 "Minimum Slope"	""
 "Minimum Slope [Degree]"	"Minimale Neigung [Grad]"
 "Minimum Standard Deviation"	"Minimale Standardabweichung"
-"Minimum Step Size"	""
 "Minimum Temperature"	""
-"Minimum Thickness"	""
 "Minimum Threshold"	""
-"Minimum Time Step [a]"	""
-"Minimum Time Step [years]"	""
 "Minimum Value"	"minimaler Wert"
 "Minimum and maximum of attribute range []."	""
 "Minimum and maximum x-coordinate of AOI."	""
 "Minimum and maximum y-coordinate of AOI."	""
 "Minimum magnitude as percentile."	""
 "Minimum number of cells in a group of adjacent cells."	""
+"Minimum number of neighbouring potential edge cells with similar direction."	""
 "Minimum of Darkness DN Cells"	""
 "Minimum pixels to consider digital number as dark object"	""
 "Minimum probability to accept a classification result for a cell."	""
@@ -3077,7 +2975,6 @@ TEXT	TRANSLATION
 "Minimum size"	"Minimalgr��e"
 "Minimum size of basin (cells)"	"Minimale Gr��e des Becken (Zellen)"
 "Minimum slope gradient to preserve from cell to cell; with a value of zero sinks are filled up to the spill elevation (which results in flat areas). Unit [Degree]"	"Minimaler Neigungsgradient der von Zelle zu Zelle eingehalten werden soll [Grad]"
-"Minimum sub-time step size (yrs)"	""
 "Minimum value of the range to be reclassified."	"Minimaler Wert des neueinzuteilenden Bereichs"
 "Minimum/Maximum"	"Minimum/Maximum"
 "Minimun"	"Minimum"
@@ -3102,7 +2999,6 @@ TEXT	TRANSLATION
 "Model parameter [m]"	"Modelparameter [m]"
 "Model parameters"	""
 "Model step %d/%d ..."	""
-"Modelled DEM"	""
 "Modelled Elevation"	""
 "Modelling erosion processes."	""
 "Modelling hydrological processes."	"Modellierung hydrologischer Prozesse."
@@ -3122,8 +3018,6 @@ TEXT	TRANSLATION
 "Monthly Global by Latitude"	""
 "Moore"	""
 "Moore & Nieber 1989"	""
-"Moore (8)"	""
-"Moore Contiguity"	""
 "Moore et al. 1991"	""
 "Moran's I"	""
 "Morphological Filter"	"Morphologischer Filter"
@@ -3164,7 +3058,6 @@ TEXT	TRANSLATION
 "Multiple Maximum Downslope Gradient Based Flow Directon"	""
 "Multiple Observer"	""
 "Multiple R-squared"	""
-"Multiple Regression Analysis"	""
 "Multiple Regression Analysis (Grid and Predictor Grids)"	""
 "Multiple Regression Analysis (Points and Predictor Grids)"	""
 "Multiple Triangular Flow Directon"	"Multiple Triangulare Str�mungsrichtung"
@@ -3180,9 +3073,6 @@ TEXT	TRANSLATION
 "MySQL Data"	"MySQL Daten"
 "My_Module Module Sub Menu"	""
 "NAME"	"NAME"
-"NBR_X"	""
-"NBR_Y"	""
-"NCAR Climate Import"	""
 "NCELLS"	"NZELLEN"
 "NCache einlesen"	""
 "NEIGHBORS"	"NACHBARN"
@@ -3220,12 +3110,10 @@ TEXT	TRANSLATION
 "Neighborhood"	"Umgebung"
 "Neighborhood Type"	"Umgebungstyp"
 "Neighbourhood"	"Umgebung"
-"Neighbourhood (Radius)"	""
 "Net Primary Production [Gt Carbon / a]"	"Netz Prim�r Produktion [Gt Kohlenstoff / a]"
 "NetCDF Files (*.nc)"	""
 "Network topology"	""
 "Neumann"	""
-"Neumann Contiguity"	""
 "Neumann: the four horizontally and vertically neighboured cells; Moore: all eight adjacent cells"	""
 "Neural Networks (OpenCV)"	""
 "New"	"Neu"
@@ -3262,16 +3150,17 @@ TEXT	TRANSLATION
 "No Sinks"	""
 "No attribute fields selected!"	""
 "No attribute fields specified!"	""
+"No compatible table has been found."	""
 "No data"	""
 "No data loaded."	"Keine Daten geladen."
 "No description available"	"Keine Beschreibung verf�gbar"
 "No duplicates found."	"Keine Duplikate gefunden."
-"No grid in list"	""
 "No objects"	""
 "No parameters available."	"Keine Parameter verf�gbar."
 "No path for output files specified!"	""
 "No pen is used"	"Kein Stift im Gebrauch"
 "No projects in directory"	""
+"No raster files have been found in directory."	""
 "No shapes in selection"	"Keine Vektoren ausgew�hlt"
 "No sinks have been detected."	"Keine Senken gefunden."
 "No translation set by user"	"Keine �bersetzung durch den Nutzer ausgew�hlt"
@@ -3304,14 +3193,12 @@ TEXT	TRANSLATION
 "North|South|"	"Nord|S�d|"
 "Not Named"	""
 "Not Null"	"Nicht null"
-"Not a valid PostGIS database!"	"Kein g�ltiger PostGIS Datenbestand!"
 "Nothing to do be done. Raster splitting is not supported."	""
 "Nothing to do! Merging needs more than one input data set."	""
 "Nothing to do. Raster is already within target range."	""
 "Nothing to do: there is no intersection with additonal grid."	"Nichts zu tun: es gibt keine Schnittmenge mit zus�tzlichem Raster."
 "November"	"November"
 "No|Yes|"	"Nein|Ja|"
-"Number Of Shapes"	"Anzahl der Vektoren"
 "Number in Latitudinal Direction"	""
 "Number in Meridional Direction"	""
 "Number of Attributes"	"Anzahl der Attribute"
@@ -3336,7 +3223,6 @@ TEXT	TRANSLATION
 "Number of Fields"	"Anzahl der Felder"
 "Number of Grid Cells"	"Anzahl der Rasterzellen"
 "Number of Grids"	"Anzahl der Raster"
-"Number of Infection States"	""
 "Number of Intervals"	""
 "Number of Iterations"	""
 "Number of Iterations for Normal Updating"	""
@@ -3352,6 +3238,7 @@ TEXT	TRANSLATION
 "Number of Row Cells"	"Anzahl der Reihenzellen"
 "Number of Rows"	"Anzahl der Reihen"
 "Number of Sectors"	"Anzahl der Sektoren"
+"Number of Shapes"	""
 "Number of Simulations"	"Anzahl der Simulationen"
 "Number of Simulations for Calibration"	"Anzahl der Simulationen f�r die Kalibrierung"
 "Number of Steps"	"Anzahl der Schritte"
@@ -3381,6 +3268,7 @@ TEXT	TRANSLATION
 "Number of points on each side of the section"	"Anzahl der Punkte auf jeder Seite der Sektion"
 "Number of points per return:"	"Anzahl der Punkte pro R�ckgabe:"
 "Number of raindays is greater than model timespan!"	""
+"Number of raster files found in directory"	""
 "Number of sub-basins"	"Anzahl der Teilbecken"
 "Number of the last x Iteration to be plotted."	"Anzahl der letzten X Iterationen die gezeichnet werden sollen."
 "Number of vertical tiles"	"Anzahl vertikaler Kacheln"
@@ -3392,7 +3280,6 @@ TEXT	TRANSLATION
 "Numerical Precision"	"Numerische Pr�zision"
 "O. Conrad (c) 2009"	""
 "O. Conrad (c) 2011"	""
-"O.C.'s Tests"	""
 "O.Conrad (c) 2010"	""
 "O.Conrad (c) 2011"	""
 "O.Conrad (c) 2013"	""
@@ -3403,9 +3290,6 @@ TEXT	TRANSLATION
 "ODBC source connected"	"ODBC mit Quelle Verbunden"
 "ODBC source disconnected"	""
 "ODBC/OTL"	""
-"OGR: Export Shapes to KML"	""
-"OGR: Export Vector Data"	"OGR: Export Vektordaten"
-"OGR: Import Vector Data"	"OGR: Import Vektordaten"
 "OID"	""
 "OSM Areas"	""
 "OSM Locations"	""
@@ -3415,7 +3299,6 @@ TEXT	TRANSLATION
 "OUTPUT certainty"	""
 "OUTPUT classes"	""
 "Object Grid"	""
-"Object Update"	""
 "Objective Function"	"Objektive Funktion"
 "Objects removed from input grid"	"Objekte die aus dem Eingaberaster entfernt wurden"
 "Oblique Mercator"	"schiefer Merkator"
@@ -3445,15 +3328,15 @@ TEXT	TRANSLATION
 "Only Header Info"	"Nur Kopfzeilen Info"
 "Only List Connected Servers"	""
 "Only Process Gaps with Less Cells"	"Nur Bearbeitung von L�cken mit wenigen Zellen"
-"Only Show Selection"	"Nur die Auswahl anzeigen"
 "Only Z-Direction Position is Updated"	""
 "Opaque"	""
 "Open"	"�ffnen"
 "Open Database Connection"	""
 "Open Project"	""
 "Open Slopes"	""
+"Open as data set"	""
+"Open with external application"	""
 "OpenCV"	""
-"OpenMP: Slope, Aspect"	""
 "Opening"	"Er�ffnung"
 "Openness"	""
 "Operation"	"Operation"
@@ -3461,7 +3344,6 @@ TEXT	TRANSLATION
 "Operator Type"	"Operatortyp"
 "Operator scale"	"Operator Umfang"
 "Opposite Neighbours"	"entgegengesetzte Nachbarn"
-"Optimised"	""
 "Optional Output Filepath"	""
 "Optional Target Grids"	""
 "Optional Tile Info Filename"	""
@@ -3473,7 +3355,6 @@ TEXT	TRANSLATION
 "Order"	"Reihenfolge"
 "Order by"	"Sortiert nach"
 "Order by..."	"Sortiert nach.."
-"Order of Polynomial Function"	""
 "Ordered Weighted Averaging (OWA)"	"Sortierter gewichteter Durchschnitt (OWA)"
 "Ordern in den alle Ausgabedaten gespeichert werden sollen"	""
 "Ordinary Kriging"	"Ordinary Kriging"
@@ -3485,18 +3366,13 @@ TEXT	TRANSLATION
 "Origin Latitude"	"Original Breitengrad"
 "Original"	""
 "Original Channels"	""
-"Original DEM"	""
-"Original Grid"	""
 "Original Image"	"Original Bild"
-"Original River Elevations"	""
 "Orographic Coefficient"	"Orografischer Koeffizient"
 "Orthoclinal slope"	""
 "Orthodromes"	""
 "Orthographic"	"Orthografisch"
 "Ouput"	"Ausgabe"
-"Outflow"	""
 "Outlet"	""
-"Outlet Concentration"	""
 "Outlet Hydrographs"	"Abflussganglinien"
 "Outlet X"	"Auslass X"
 "Outlet Y"	"Auslass Y"
@@ -3510,8 +3386,6 @@ TEXT	TRANSLATION
 "Output Filepath"	""
 "Output Format"	"Ausgabeformat"
 "Output Grid"	"Ausgabe Raster"
-"Output Grid Down"	""
-"Output Grid Up"	""
 "Output Lod"	"Ausgabe Erfassungsgrenze"
 "Output Seeds"	"Ausgabe Samen"
 "Output Text File"	""
@@ -3524,20 +3398,17 @@ TEXT	TRANSLATION
 "Output file path"	""
 "Output format"	"Ausgabe Format"
 "Output grid"	"Ausgabe Raster"
-"Output interval"	""
-"Output interval (time steps)"	""
 "Output of Change Vector"	""
-"Output of Grids"	""
-"Output of Level Data"	""
+"Output of Gradients"	""
 "Output of Model Parameters"	""
 "Output of Regression Parameters"	"Ausgabe Regressionsparameter"
-"Output of Trend Data"	""
 "Output of module calculations."	"Ausgabe der Modulberechnungen."
 "Output of..."	""
 "Output parameters"	""
 "Output shapes with field(s) deleted"	""
 "Output table with field(s) deleted"	""
 "Output will inherit shape type and table structure from the first layer in this list."	""
+"Overall Accuracy"	""
 "Overall Bounding Box:"	""
 "Overdip slope"	""
 "Overland"	""
@@ -3551,8 +3422,8 @@ TEXT	TRANSLATION
 "Overlay Image"	"Overlaybild"
 "Override"	"�bergehen"
 "Overview"	"�berblick"
+"Overview Content"	""
 "Overwrite"	""
-"P"	""
 "P/A"	""
 "P/sqrt(A)"	"P/Quadratwurzel(A)"
 "PATB"	""
@@ -3584,7 +3455,6 @@ TEXT	TRANSLATION
 "Panchromatic Channel Matching"	""
 "Panorama"	"Panorama"
 "Panorama Break [%]"	"Panoramaunterbrechung [%]"
-"Paolo"	""
 "Paper Format"	"Papierformat"
 "Parallelepiped"	"Parallelfl�chner"
 "Parameter"	"Parameter"
@@ -3664,15 +3534,11 @@ TEXT	TRANSLATION
 "Planar"	""
 "Plane"	"Fl�che"
 "Plane (%.2fDegree)"	"Fl�che (%.2fGrad)"
-"Planetary Bending"	""
-"Planetary Radius"	"unsteter Radius"
 "Plant Height"	""
 "Platform"	""
-"Play And Save As Images..."	""
+"Play And Save as Images..."	""
 "Play Loop [Ctrl + L]"	""
-"Play Loop [L]"	""
 "Play Once [Ctrl + P]"	""
-"Play Once [P]"	""
 "Play and Save to Image"	""
 "Please choose a method of module operation."	"Bitte w�hle eine Methode der Moduloperation."
 "Please enter a numeric value:"	"Bitte einen numerischen Wert eingeben:"
@@ -3712,7 +3578,6 @@ TEXT	TRANSLATION
 "Point Cloud to Shapes"	"Punktwolken zu Vektoren"
 "Point Cloud to drop attribute from."	"Punktwolken als Ziel f�r Attribute von.."
 "Point Cloud to reclassify/extract"	"Punktwolken zu reklassifizieren / Auszug"
-"Point Cloud with attribute dropped."	"Punktwolke mit zugewiesenen Attributen."
 "Point Clouds"	"Punktwolken"
 "Point Clouds Viewer"	""
 "Point Data Record Format"	"Punktdaten Datensatzformat"
@@ -3724,6 +3589,8 @@ TEXT	TRANSLATION
 "Point Size: Scaling"	"Punktgr��e: Ma�stab"
 "Point Statistics for Polygons"	"Punkt Statistik f�r Polygone"
 "Point View Settings"	""
+"Point cloud to drop attribute(s) from."	""
+"Point cloud with attribute(s) dropped."	""
 "Point clouds viewer."	"Punktwolkenbetrachter."
 "Point insertion distance [map units]."	""
 "Point shapefile with source point(s)"	"Punkt Vektordatei mit Ausgangspunkten"
@@ -3780,17 +3647,19 @@ TEXT	TRANSLATION
 "Positive values result in a shift in N direction."	"Positive Werte resultieren in einem Verschieben in Nord-Richtung"
 "Possible error"	"m�glicher Fehler"
 "PostGIS"	""
+"PostGIS extension added"	""
+"PostGIS extension missing or too old"	""
 "PostgreSQL"	""
 "PostgreSQL Connections"	""
 "PostgreSQL Database Connection Error"	""
 "PostgreSQL Sources"	""
+"PostgreSQL database is already connected"	""
 "PostgreSQL source connected"	""
 "PostgreSQL source disconnected"	""
 "PostgreSQL source is already connected"	""
 "Potential Evapotranspiration"	""
 "Potential Incoming Solar Radiation"	"potentiell ankommende Sonneneinstrahlung"
 "Power"	"Power"
-"Power (Distance Weighting)"	""
 "Power on soil (p)"	"Power am Boden (p)"
 "Power on soil (p) [lower bound]"	"Power am Boden (p) [untere Grenze]"
 "Power on soil (p) [upper bound]"	"Power am Boden (p) [obere Grenze]"
@@ -3805,7 +3674,6 @@ TEXT	TRANSLATION
 "Precipitation Column"	"Niederschlag Spalte"
 "Precipitation [m / dt]"	""
 "Precipitation [mm]"	"Niederschlag [mm]"
-"Precipition Quantitiy [mm]"	""
 "Precise Datum Conversion"	""
 "Precise Tracing"	"genaue Spurverfolgung"
 "Precisions"	""
@@ -3821,7 +3689,6 @@ TEXT	TRANSLATION
 "Predictors"	"Vorhersager"
 "Preferred Routing"	""
 "Preferred Target Grid Type"	"Bevorzugter Zielrastertyp"
-"Preferred data storage type"	"Bevorzugter Datenspeichertyp"
 "Preliminary scene analysis:"	""
 "Preprocessed DEM"	"vorverarbeitetes DGM"
 "Preprocessed DEM. If this is not set changes will be stored in the original DEM grid."	"Vorverarbeitetes DGM. Falls dieses nicht eingestellt ist werden die �nderungen im originalen DGM-Raster gespeichert."
@@ -3869,7 +3736,6 @@ TEXT	TRANSLATION
 "Processing observer %d ..."	""
 "Product"	"Produkt"
 "Production"	""
-"Production Rates [m/h]"	""
 "Profile"	"Profile"
 "Profile (lines)"	"Profile (Linien)"
 "Profile (points)"	"Profile (Punkte)"
@@ -3935,6 +3801,7 @@ TEXT	TRANSLATION
 "Quadric: a + b * x + c * x^2"	"Quadratisch: a + b * x + c * x^2"
 "Quality"	"Qualit�t"
 "Quality Measure"	"Qualit�tsma�"
+"Quality assessment is not calculated, because the number of classes in the input grids differ."	""
 "Quantile"	""
 "Queen"	"K�nigin"
 "Queen's case"	""
@@ -3982,7 +3849,6 @@ TEXT	TRANSLATION
 "RED_GREEN_BLUE"	"ROT_GR�N_BLAU"
 "RED_GREY_BLUE"	"ROT_GRAU_BLAU"
 "RED_GREY_GREEN"	"ROT_GRAU_GR�N"
-"REMO Level Interpolation"	""
 "RESIDUAL"	""
 "RGB"	""
 "RGB Coded Values"	""
@@ -4026,6 +3892,11 @@ TEXT	TRANSLATION
 "Rank"	"Rankzahl"
 "Rank Filter"	"Rangzahlfilter"
 "Rank [Percent]"	"Rangzahl [%]"
+"Raster Band Deletion"	""
+"Raster Band Identifier"	""
+"Raster Catalogue"	""
+"Raster Catalogue (unknown CRS)"	""
+"Raster Catalogues"	""
 "Raster Dimension"	"Raster Dimension"
 "Raster Resolution (Pixel Size)"	"Raster Aufl�sung (Pixelgr��e)"
 "Raster Resolution (Pixels Size)"	"Raster Aufl�sung (Pixelgr��e)"
@@ -4054,7 +3925,6 @@ TEXT	TRANSLATION
 "Reclassify|Extract Subset|"	"Reklassifizieren|Extrakt Teilmenge|"
 "Recognised Files"	""
 "Reconstruction result"	""
-"Records"	""
 "Rectangles"	""
 "Rectify Grid"	""
 "Red"	"Rot"
@@ -4071,9 +3941,6 @@ TEXT	TRANSLATION
 "Reflectance"	""
 "Refresh"	"aktualisieren"
 "Region of Interest"	""
-"Regolith Smoothing"	""
-"Regolith Thickness"	""
-"Regolith_cover_thickness"	""
 "Regression"	"Regression"
 "Regression Analysis"	"Regressionsanalyse"
 "Regression Analysis (Points and Predictor Grid)"	""
@@ -4096,15 +3963,14 @@ TEXT	TRANSLATION
 "Relative Area"	"Relative Fl�che"
 "Relative Height"	"Relative H�he"
 "Relative Heights and Slope Positions"	"Relative H�hen und Neigungspositionen"
-"Relative Relief Position"	""
 "Relative Richness"	"relativer Reichtum"
 "Relative Slope Position"	""
 "Relative from cell value"	"Relativ vom Zellwert"
 "Relative heights calculation..."	"Relative H�hen Berechnung..."
-"Relative position"	""
 "Relaxation"	"Entspannung"
 "Reload"	""
 "Reload tool chain"	""
+"Remove"	""
 "Remove Border Regions?"	""
 "Remove Duplicate Points"	"Entferne doppelte Punkte"
 "Remove Overlap from Virtual Point Cloud Tiles"	""
@@ -4114,7 +3980,10 @@ TEXT	TRANSLATION
 "Removing ambiguous pixels..."	""
 "Rename"	""
 "Rename Fields"	"Feld umbenennen"
+"Rename Raster Band"	""
 "Rename Table"	""
+"Reopen Database Connections"	""
+"Reopen PostgreSQL database connections. Warning: if set to true account information including unencrypted paswords for automatic connection will be stored."	""
 "Replace Condition"	"Austauschbedingungen"
 "Replace Text"	""
 "Replace first PC with PAN"	""
@@ -4132,7 +4001,6 @@ TEXT	TRANSLATION
 "Rescale to 0 - 1"	"Massstabs�nderung von 0 - 1"
 "Rescale to 0 - 1.0"	"Massstabs�nderung von 0 - 1.0"
 "Resection (Terrestrial)"	""
-"Reset Regolith"	""
 "Residual Analysis (Grid)"	"R�ckstandsanalyse (Raster)"
 "Residual Corrected Regression"	""
 "Residual Correction"	""
@@ -4167,20 +4035,15 @@ TEXT	TRANSLATION
 "Rill/Interrill Erosivity"	"Rinnsal/Erosivit�t"
 "RivFlow"	""
 "RivFlow."	""
-"River Flooding (Mean Value Cellular Automat)"	""
-"River Flow Terraces"	""
-"River Flow Terraces Elevations"	""
 "River Heads"	"Flussquellen"
 "River Mouths"	"Flussm�ndungen"
-"River Pixels"	""
 "Rn, number of rain days in timespan [-]"	""
 "Road Width"	"Strassenbreite"
-"Rock Layers"	""
 "Roll Left [F4]"	""
 "Roll Right[F3]"	""
 "Rook"	"Saatkr�he"
 "Rook's case"	"Rook�s Fall"
-"Rooke"	""
+"Rooke's case"	""
 "Roots"	"Wurzeln"
 "Roots to Humus"	"Wurzeln zu Humus"
 "Rotate"	"Drehen"
@@ -4201,17 +4064,14 @@ TEXT	TRANSLATION
 "Routing Error"	"Routenplanung Fehler"
 "Row Order"	""
 "Rows"	"Reihen"
+"Run Once"	""
 "Run Tool"	"Werkzeug ausf�hren"
-"Run duration"	""
 "Running Average"	"gleitendes Mittel"
 "Running Script"	""
 "Runoff"	"Abfluss"
-"S Model"	""
-"S u m"	""
 "S, slope [rad]"	""
 "SAFETYFACTOR"	""
 "SAGA Colors"	"SAGA Farben"
-"SAGA GUI Tool Menus"	""
 "SAGA Grid Files (*.sgrd)|*.sgrd|All Files|*.*"	""
 "SAGA Help"	"SAGA Hilfe"
 "SAGA Parameter Files"	"SAGA Parameter-Datei"
@@ -4230,7 +4090,6 @@ TEXT	TRANSLATION
 "SAGA Wetness Index"	"SAGA Feuchtigkeits Index"
 "SAGA: Print Map"	"SAGA: Karte drucken"
 "SAGA\nSystem for Automated Geoscientific Analyses\nVersion 2.0"	""
-"SALEM"	""
 "SECTIONS"	"ABSCHNITTE"
 "SHALSTAB"	""
 "SIZE"	""
@@ -4260,8 +4119,6 @@ TEXT	TRANSLATION
 "SVM Classification"	""
 "SVM Type"	""
 "SVR Epsilon"	""
-"S_Model"	""
-"S_Z_Model"	""
 "Saddle"	""
 "Sample Variogram"	"Proben Variogramm"
 "Sample from training population with or without replacement?"	""
@@ -4279,12 +4136,8 @@ TEXT	TRANSLATION
 "Saturation overland flow [m/dt]"	"S�ttigung �berlandstr�mung [m/dt]"
 "Saturation zone (WI > 1)"	""
 "Save"	"Speichern"
-"Save All"	""
 "Save As Image"	"Als Bild speichern"
-"Save As Image to Workspace"	""
-"Save As Image when changed"	""
-"Save As Image..."	"Als Bild speichern..."
-"Save As..."	"Speichern unter..."
+"Save Attributes as..."	""
 "Save Colors"	"Farben speichern"
 "Save Configuration"	""
 "Save Georeference"	"Georeferenzierung speichern"
@@ -4296,12 +4149,13 @@ TEXT	TRANSLATION
 "Save History as Model"	""
 "Save KML file"	""
 "Save Map as Image..."	"Karte als Bild speichern..."
+"Save Map to KMZ"	""
 "Save Modified Data"	""
 "Save Parameters"	"Parameter speichern"
 "Save Point"	""
 "Save Point Cloud"	"Punktwolke speichern"
 "Save Project"	"Projekt speichern"
-"Save Project As..."	"Projekt speichern als..."
+"Save Project as..."	""
 "Save Settings"	"Einstellungen speichern"
 "Save Shapes"	"Vektoren speichern"
 "Save Statistics to File..."	""
@@ -4312,7 +4166,12 @@ TEXT	TRANSLATION
 "Save Tiles to Disk"	""
 "Save To Memory Grid"	""
 "Save all"	"Alles speichern"
+"Save as Image to Workspace"	""
+"Save as Image when changed"	""
+"Save as Image..."	""
+"Save as KMZ..."	""
 "Save as Tool Chain"	""
+"Save as..."	""
 "Save changes?"	"�nderungen speichern?"
 "Save grid"	"Raster speichern"
 "Save point cloud"	"Punktwolke speichern"
@@ -4320,10 +4179,12 @@ TEXT	TRANSLATION
 "Save table"	"Tabelle speichern"
 "Save tiles to disk individually"	""
 "Save to Clipboard"	""
+"Save to Database..."	""
 "Save to File"	""
 "Save to File..."	""
 "Save to Path"	""
 "Save to Script File"	""
+"Save to Workspace"	""
 "Scalable Vector Graphics Files (*.svg)"	"Skalierbare Vector Graphics Dateien (*.svg)"
 "Scale"	"Massstab"
 "Scale (Cells)"	""
@@ -4354,14 +4215,12 @@ TEXT	TRANSLATION
 "Search Mode"	"Suche Betriebsart"
 "Search Options"	"Suchoptionen"
 "Search Radius"	"Suche Radius"
-"Search Radius (Cells)"	""
 "Search Range"	"Suche Bereich"
 "Search Result"	""
 "Search Shape"	"Vektoren suchen"
 "Search chip size set to %d"	""
 "Search distance given as number cells."	""
 "Search for Projects"	""
-"Search for Projects..."	""
 "Search for..."	"Suche nach..."
 "Search radius of kernel in cells."	"Suchradius des Kernels in Zellen"
 "Search text not found"	"Gesuchten Text nicht gefunden"
@@ -4370,26 +4229,20 @@ TEXT	TRANSLATION
 "Secondary Name"	"untergeordneter Name"
 "Section"	"Sektion"
 "Sections"	"Sektionen"
-"Sed_thickness_a"	""
-"Sed_thickness_b"	""
 "Sediment Balance"	""
 "Sediment Balance Clay"	""
 "Sediment Balance Sand"	""
 "Sediment Balance Silt"	""
-"Sediment Influx from Upstream"	""
 "Sediment Limited [%d], Transport Limited (SL = TC) [%d], Transport Limited (SL = G) [%d]"	""
 "Sediment Yield Delivery Ratio"	""
-"Sediment_infux_from_upstream"	""
 "Seed Generation"	"Keimgenerationen"
 "Seed Points"	"Saatpunkte"
 "Seed Type"	""
 "Seed Value"	"Keimwert"
 "Seeded Region Growing"	""
 "Seeds"	"Keime"
-"Seeds (Mask)"	""
 "Seeds Grid"	"Keime Raster"
 "Seeds Only"	"Keime ausschlie�lich"
-"Segment Connection"	""
 "Segment ID"	"Segment ID"
 "Segmentation"	"Segmentierung"
 "Segments"	"Segmente"
@@ -4502,7 +4355,9 @@ TEXT	TRANSLATION
 "Shapes to TIN"	"Vektoren zu TIN"
 "Shapes to project"	"abzubildende Vektoren"
 "Shapes with Text Replacements"	""
+"Shapes|Export"	""
 "Shapes|Grid"	"Vektoren|Raster"
+"Shapes|Import"	""
 "Shapes|Lines"	"Vektoren|Linien"
 "Shapes|Lines|Transects"	"Vektoren|Linien|Transekte"
 "Shapes|Point Clouds"	"Vektoren|Punktwolken"
@@ -4534,6 +4389,7 @@ TEXT	TRANSLATION
 "Show Categories"	"Zeige Kategorien"
 "Show Cell Values"	"Zeige Zellenwerte"
 "Show Centroid"	""
+"Show Data File Sources"	""
 "Show Data Source Window"	""
 "Show Edges"	""
 "Show Filled"	""
@@ -4553,11 +4409,13 @@ TEXT	TRANSLATION
 "Show Results"	""
 "Show Scale"	"Zeige Massstab"
 "Show Scale Bar"	""
+"Show Selection"	""
 "Show Toolbar"	"Zeige Werkzeugleiste"
 "Show Vertical Legend"	""
 "Show Vertices"	""
 "Show a Composite"	""
 "Show at all scales"	"Zeige bei allen Massst�ben"
+"Show data sources tab for file system. Disabling might speed up start-up. Changes take effect after restart."	""
 "Shrink"	""
 "Shrink and Expand"	""
 "Shrinking"	""
@@ -4608,7 +4466,6 @@ TEXT	TRANSLATION
 "Single Value Decomposition (OpenCV)"	""
 "Single value"	"Einzelner Wert"
 "Sink Drainage Route Detection"	"Senke Entw�sserungsroutendetektion"
-"Sink Fill Algorithm"	""
 "Sink Removal"	"Senke Beseitigung"
 "Sink Route"	"Senke Route"
 "Sink Routes"	"Senke Routen"
@@ -4649,8 +4506,6 @@ TEXT	TRANSLATION
 "Slope Tolerance"	""
 "Slope Units"	""
 "Slope Weighting"	""
-"Slope exponent Nb for bedrock channel erosion"	""
-"Slope exponent Nf for fluvial sediment transport"	""
 "Slope gradient to left neighbour [%%]"	"Neigungsgradient zum linken Nachbarn [%%]"
 "Slope gradient to left neighbour [Degree]"	"Neigungsgradient zum linken Nachbarn [Grad]"
 "Slope grid, in radians."	""
@@ -4658,16 +4513,11 @@ TEXT	TRANSLATION
 "Slope threshold, given as degree, above which flow transport is unlimited."	""
 "Slope tolerance that defines a 'flat' surface (degrees)"	""
 "Slope, Aspect, Curvature"	""
-"Slope_failure_locations"	""
 "Slopes"	""
 "Smith"	""
 "Smooth"	"Gl�tten"
-"Smooth River Flow Terraces"	""
 "Smoothed Lines"	""
-"Smoothed River Elevations"	""
-"Smoothing"	""
 "Smoothing (ViGrA)"	""
-"Smoothing Threshold"	""
 "Snap Distance"	""
 "Snap Features"	""
 "Snap Points to Grid"	""
@@ -4679,20 +4529,14 @@ TEXT	TRANSLATION
 "Soil"	""
 "Soil Adjusted Vegetation Index"	""
 "Soil Adjustment Factor"	""
-"Soil Depth"	""
-"Soil Depth Right"	""
-"Soil Friction Coefficient"	""
 "Soil Moisture"	"Bodenfeuchte"
 "Soil Moisture Content"	"Bodenfeuchte Gehalt"
 "Soil Moisture Deficit"	"Bodenfeuchte Defizit"
 "Soil Moisture Power Eq."	"Bodenfeuchte Kraft Eq."
 "Soil Nitrogen"	"Bodenstickstoff"
-"Soil Parameter"	""
 "Soil Texture"	"Bodentextur"
 "Soil Texture Classification"	"Bodentextureinteilung"
 "Soil Texture Classification for Tables"	""
-"Soil Thickness"	""
-"Soil Things"	""
 "Soil Water"	""
 "Soil moisture (at FC)"	""
 "Soil moisture index (l)"	"Bodenfeuchteindex (l)"
@@ -4715,7 +4559,6 @@ TEXT	TRANSLATION
 "Sommergerste"	"Sommergerste"
 "Sort"	"Sortieren"
 "Sort Fields"	""
-"Sort Selection to Top"	""
 "Sort Table"	"Tabelle sortieren"
 "Sort first by"	"Sortiere erst nach.."
 "Sort second by"	"Sortiere zweitens nach.."
@@ -4802,17 +4645,13 @@ TEXT	TRANSLATION
 "Standardised Grid"	"Standardisiertes Raster"
 "Standardize"	""
 "Standardized Height"	"Standarisierte H�he"
-"Start"	""
 "Start Degree"	""
 "Start Latitude"	""
 "Start Longitude"	""
 "Start Size"	""
-"Start Time"	""
 "Start Value"	"Startwert"
 "Start Values"	"Startwerte"
-"Start [a BP]"	""
 "Start [ka]"	""
-"Start [years BP]"	""
 "Starting flood fill..."	"Beginne Flutf�llung"
 "Startup Project"	""
 "State t"	""
@@ -4825,30 +4664,20 @@ TEXT	TRANSLATION
 "Steepened escarpment"	""
 "Steepest gradient (first version)"	"steilster Gradient (erste Version)"
 "Steepest gradient (second version)"	"steilster Gradient (zweite Version)"
-"Steepest_slope"	""
 "Stems"	"Halme"
 "Stems to Litter"	"Halme zu Abfall"
 "Step"	"Schritt"
-"Step 1: Surface Gradient"	""
 "Step 1: low-pass of stripe"	"Schritt 1: Tiefpass von Streifen"
-"Step 2: Concentration"	""
 "Step 2: low-pass between stripe and its surruondings"	"Schritt 2: Tiefpass zwischen Streifen und ihrer Umgebung"
-"Step [a]"	""
 "Step [ka]"	""
-"Step [years]"	""
 "Steps"	""
-"Steps 1+2: Surface, Gradient, Concentration"	""
 "Steps to Next"	""
 "Stepwidth"	"Schrittweite"
 "Stereo Anaglyph"	""
 "Stereo Eye Distance [Degree]"	"Stereo Augendistanz [Grad]"
 "Stereo Match (OpenCV)"	""
 "Stereographic"	"Stereographisch"
-"Stop"	""
-"Stop [a BP]"	""
-"Stop [h]"	""
 "Stop [ka]"	""
-"Stop [years BP]"	""
 "Stop at Edge"	""
 "Stop on Error"	"Halt bei Fehler"
 "Storage"	"Speicherung"
@@ -4859,7 +4688,6 @@ TEXT	TRANSLATION
 "Stratification"	""
 "Stream Order"	""
 "Stream Power Index"	"Str�mungsenergie Index"
-"Stream_channel_length_between_cells"	""
 "Streamflow (obs.) Column"	"Str�mungsenergie (obs.) Spalte"
 "Streamflow Column"	"Str�mungsenergie Spalte"
 "Streams"	""
@@ -4892,6 +4720,7 @@ TEXT	TRANSLATION
 "Summary_"	"Zusammenfassung_"
 "Sun's height above horizon in degree"	""
 "Sunrise"	"Sonnenaufgang"
+"Sunrise and Sunset"	""
 "Suns's Height"	""
 "Sunset"	"Sonnenuntergang"
 "Supervised Classification for Grids"	""
@@ -4900,11 +4729,8 @@ TEXT	TRANSLATION
 "Support Vector Machine"	""
 "Suppress Negative Flow Accumulation Values"	""
 "Surface"	"Oberfl�che"
-"Surface Approximation Threshold"	""
 "Surface Area"	""
-"Surface Elevation"	""
 "Surface Specific Points"	"Oberfl�che spezifische Punkte"
-"Surface Water [m]"	""
 "Surface hydraulic conductivity [m/h]"	"Oberfl�che hydraulische Durchl�ssigkeit [m/h]"
 "Surface roughness"	""
 "Surface used to derive the LDD network, e.g. a DTM."	""
@@ -4912,7 +4738,6 @@ TEXT	TRANSLATION
 "Surfer Blanking Files (*.bln)|*.bln|All Files|*.*"	"Surfer Blanking Dateien (*.bln)|*.bln|Alle Dateien|*.*"
 "Surfer Grid (*.grd)|*.grd|All Files|*.*"	"Surfer Rasterdateien (*.grd)|*.grd|Alle Dateien|*.*"
 "Surfer's No Data Value"	"Surfer NoData-Werte"
-"Surrounding Air Temperature [�C]"	""
 "Swath Profile"	"Schneisenprofile"
 "Swath Width"	"Schneisenbreite"
 "Swath width measured in map units."	"Schneisenbreite gemessen in Karteneinheiten."
@@ -4927,15 +4752,9 @@ TEXT	TRANSLATION
 "Synchronize Map Extents"	""
 "Syntax error at position #%d: \n%s\n"	"Syntaxfehler an Position #%: \n%s\n"
 "Synthesized Grid"	""
-"T"	""
 "T Curvature"	"T Kurvatur"
-"T Height Correction"	""
-"T Offset"	""
 "T Slope"	"T Neigung"
 "T Vertical Distance to Channel Network"	"T Vertikale Entfernung zum Gew�ssernetz"
-"T [ka BP]"	""
-"T max"	""
-"T min"	""
 "T, mean temperature [degree C]"	""
 "TCI Low"	""
 "TCc"	""
@@ -5013,7 +4832,6 @@ TEXT	TRANSLATION
 "Target X coordinate"	""
 "Target Y coordinate"	""
 "Tasseled Cap Transformation"	""
-"Temperatur offset"	""
 "Temperature"	""
 "Temperature (2pm) [DegreeC]"	"Temperatur (14.00 Uhr) [GradCelsius]"
 "Temperature Column"	"Temperatur Spalte"
@@ -5029,12 +4847,8 @@ TEXT	TRANSLATION
 "Temperature Threshold for Rainfall (lower bound)"	"Temperatur Schwellenwert f�r Regenf�lle (untere Grenze)"
 "Temperature Threshold for Rainfall (upper bound)"	"Temperatur Schwellenwert f�r Regenf�lle (obere Grenze)"
 "Temperature at Reference Station [Deg.Celsius]"	"Temperatur an Referenzstation [Grad.Celsius]"
-"Temperature from Pressure Levels to Surface"	""
-"Template"	""
 "Template Menu|Template Sub Menu"	"Vorlagenmenu|Vorlagen Untermen�"
-"Template."	""
 "Templates"	""
-"Template|Template"	""
 "Temporary files"	"tempor�re Dateien"
 "Tension Threshold"	"Spannungsschwellenwert"
 "Tension Threshold [Percentage of Cell Size]"	""
@@ -5086,6 +4900,7 @@ TEXT	TRANSLATION
 "The attribute field with the x-coordinate."	""
 "The attribute field with the y-coordinate."	""
 "The attribute field with the z-coordinate."	""
+"The attribute field(s) to drop."	""
 "The attribute fields to cluster"	""
 "The attribute fields to convert, optional."	""
 "The attribute with the class IDs, used to link the table and the grid."	""
@@ -5100,8 +4915,8 @@ TEXT	TRANSLATION
 "The column holding the Z-coordinate."	"Die Spalte, die die Z-Koordinate enth�lt."
 "The converted shapefile."	""
 "The cutted output point cloud dataset(s)."	""
-"The datatype to use for each field, separated by semicolon, e.g. \"2;2;3;\". The number equals the choice selection, see GUI version."	""
-"The decimal precision to use for each field, separated by semicolon, e.g. \"2;2;2;0\""	""
+"The datatype to use for each field, separated by semicolon, e.g. \"	""
+"The decimal precision to use for each field, separated by semicolon, e.g. \"	""
 "The delay after the start of rainfall, before the discharge starts to rise."	"Die Verz�gerung zwischen dem Beginn des Regenfalls, bevor der Abfluss zu steigen beginnt."
 "The difference of positive and negative openness."	""
 "The field with B values (0-255)"	""
@@ -5134,14 +4949,13 @@ TEXT	TRANSLATION
 "The length of the Gaussian window is too small, please provide a larger sigma."	""
 "The merged point cloud."	""
 "The method used to identify surface specific points."	"Die Methode die zum Identifizieren spezifischer Oberfl�chenpunkte benutzt wird."
-"The name to use for each field, separated by semicolon, e.g. \"intensity;class;range\""	""
+"The name to use for each field, separated by semicolon, e.g. \"	""
 "The number of days to model."	""
 "The number of smoothing iterations [-]."	""
 "The number of supplied grids exceeds the number of variables in formula."	""
 "The number of supplied grids is less than the number of variables in formula."	""
-"The numbers (starting from 1) of the fields to drop, separated by semicolon, e.g. \"5;8;9\""	""
-"The numbers (starting from 1) of the fields to export, separated by semicolon, e.g. \"1;2;3;5\""	""
-"The numbers (starting from 1) of the fields to import, separated by semicolon, e.g. \"5;6;8\""	""
+"The numbers (starting from 1) of the fields to export, separated by semicolon, e.g. \"	""
+"The numbers (starting from 1) of the fields to import, separated by semicolon, e.g. \"	""
 "The output grid(s)"	""
 "The output grids, one grid for each table column."	""
 "The output point cloud"	""
@@ -5160,11 +4974,13 @@ TEXT	TRANSLATION
 "The shapefile to use for clipping."	""
 "The smoothed output line shapefile."	""
 "The smoothing preservation factor [-]."	""
+"The start value to use for the identifier."	""
 "The table with the (numeric) data values for each class. The module creates a grid for each table column (besides the ID)."	""
 "The terrain exaggeration factor allows to increase the shading contrasts in flat areas."	"Der Relief�berh�hungsfaktor erlaubt das Anheben der Schattenkontraste in flachen Fl�chen."
 "The transmittance of the atmosphere, usually between 60 and 80 percent."	"Der Durchl�ssigkeitswert der Atmosph�re, gew�hnlich zwischen 60 und 80 Prozent."
 "The transparency of the shade [%]"	""
 "The unobstructed hemisphere given as percentage."	"Die unversperrte Hemisph�re beschrieben in Prozent."
+"The value for the option '%s' must be specified."	""
 "The value to apply."	""
 "The values in the specified radius is used in the average calculation only if its difference with the central value is lesser or equal to this threshold."	"Die Werte in dem spezifizierten Radius werden f�r die Berechnung des Durchschnitts nur benutzt wenn ihre Differenz zu dem zentralen Wert kleiner oder gleich des Schwellenwertes sind."
 "The values of the resultant grid can be either the seed value (e.g. the local maximum) or the enumerated segment id."	"Die Werte des resultierenden Rasters k�nnen entweder der Ausgangswert (z.B. lokales Maximum) oder die ausgez�hlte Segment ID sein."
@@ -5180,7 +4996,6 @@ TEXT	TRANSLATION
 "These are the probabilities for the winner classes given by the neural network."	""
 "These are the winner class vectors."	""
 "Thiam's Transformed Vegetation Index"	"Thiams umgewandelter Vegetationsindex"
-"Thickness_of_uppermost_rock_layer"	""
 "Thiessen Polygons"	""
 "Thin Plate Spline"	""
 "Thin Plate Spline (TIN)"	"Thin Plate Spline (TIN)"
@@ -5205,11 +5020,9 @@ TEXT	TRANSLATION
 "This section contains all parameters used by the backpropagation algorithm."	""
 "This shapes layer will contain the resulting channel network in vector format (lines)."	"Diese Vektorebene enth�lt das resultierende Gew�ssernetz im Vektorformat (Linien)."
 "This value is ignored if set to zero."	"Dieser Wert wird ignoriert wenn er auf Null gesetzt wird."
-"This value is used as constant if no vapour pressure grid is given."	"Dieser Wert wird als Konstante genutzt wenn kein Raster mit Dampfdruck gegeben ist."
 "This will contain your output data of type grid."	"Dieses wird Deine Ausgabedaten vom Typ Rasterdaten enthalten."
 "This will contain your output data of type shapes."	"Dieses wird Deine Ausgabedaten vom Typ Vektordaten enthalten."
 "Thomas Schorr (c) 2007"	""
-"Thread"	""
 "Threshold"	"Schwellenwert"
 "Threshold (Grid Units)"	"Schwellenwert (Rastereinheiten)"
 "Threshold (Init.)"	"Schwellenwert (Init.)"
@@ -5218,9 +5031,7 @@ TEXT	TRANSLATION
 "Threshold Error"	"Schwellenwertfehler"
 "Threshold Grid"	"Schwellenwert Raster"
 "Threshold Height"	"Schwellenwert H�he"
-"Threshold Infected"	""
 "Threshold Linear Flow"	""
-"Threshold Sickness"	""
 "Threshold Type"	"Schwellenwert Typ"
 "Threshold [Percent]"	"Schwellenwert [Prozent]"
 "Threshold for Elevation Percentile (Lowness)"	"Schwellenwert f�r Erh�hung Perzentile (Niedrigkeit)"
@@ -5230,7 +5041,6 @@ TEXT	TRANSLATION
 "Threshold for different route"	"Schwellenwert f�r unterschiedliche Routen"
 "Threshold for linear flow, if exceeded D8 is used."	""
 "Threshold for plane"	"Schwellenwert f�r Ebene"
-"Threshold for sediment motion"	""
 "Thresholded Linear Flow"	""
 "Thresholds"	"Schwellenwert"
 "Thumbnail Size"	"Miniaturbildgr��e"
@@ -5277,10 +5087,8 @@ TEXT	TRANSLATION
 "Time span used for the calculation of daily radiation sums."	"Zeitspanne die f�r die Berechnung der t�glichen Strahlungssummen benutzt wird."
 "Time stamp of Image"	""
 "Time step exceeds duration"	""
-"Time step size (yrs)"	""
 "Time step size for a day's calculation given in hours."	"Zeitschrittgr��e f�r eine Tagesberechnung gegeben in Stunden."
 "Time step size for a range of days calculation given in days."	"Zeitschrittgr��e f�r eine Berechnung eines Bereichs von Tagen gegeben in Tagen."
-"Times"	""
 "Timespan (days)"	""
 "Tip of the Day..."	"Tip des Tages.."
 "Tissot's Indicatrix"	""
@@ -5304,11 +5112,9 @@ TEXT	TRANSLATION
 "Tools"	"Werkzeuge"
 "Tools for (grid based) digital terrain analysis."	"Werkzeuge f�r (rasterbasierte) digitale Reliefanalysen."
 "Tools for GPS data handling."	""
-"Tools for Soil."	""
 "Tools for Triangulated Irregular Network (TIN) processing."	"Werkzeuge f�r die Berechnung dreieckiger irregul�rer Netzwerke (TIN). "
 "Tools for digital terrain analysis."	"Werkzeuge f�r digitale Reliefanalyse."
 "Tools for lines."	"Werkzeuge f�r Linien"
-"Tools for managing weather and climate data."	""
 "Tools for point clouds."	"Werkzeuge f�r Punktwolken"
 "Tools for polygons."	"Werkzeuge f�r Polygone"
 "Tools for regression analyses."	"Werkzeuge f�r die Regressionsanalyse"
@@ -5351,12 +5157,9 @@ TEXT	TRANSLATION
 "Total area is zero or minimum elevation is equal or lower than maximum elevation!"	""
 "Total flow (in watershed) [m^3/dt]"	""
 "Total flow [m/dt]"	"Gesamtstr�mung [m/dt]"
-"Total insolation, the sum of direct and diffuse incoming solar radiation."	"Gesamt Sonneneinstrahlung, die Summe direkt und diffus ankommender Solarstrahlung."
 "Total memory size"	"Gesamte Speichergr��e"
 "Total number of points: %s"	""
 "Total number of referenced datasets: %d"	""
-"Tracer"	""
-"Tracer Lines"	""
 "Tracing: Convergence"	"�berwachung: �bereinstimmung (Konvergenz)"
 "Tracing: Max. Divergence"	"�berwachung: max. Abweichung (Divergenz)"
 "Tracing: Stop after x cells with divergent flow"	"�berwachung: Anhalten nach x Zellen mit abweichender Flie�richtung"
@@ -5389,15 +5192,12 @@ TEXT	TRANSLATION
 "Transmissivity"	"Transmissivit�t"
 "Transparency [%]"	"Transparenz [%]"
 "Transparent"	""
-"Transport"	""
 "Transport Capacity Clay"	""
 "Transport Capacity Sand"	""
 "Transport Capacity Silt"	""
 "Transport Condition Clay"	""
 "Transport Condition Sand"	""
 "Transport Condition Silt"	""
-"Transport Function"	""
-"Transportation Depth"	""
 "Transpose Grids"	""
 "Transpose Table"	""
 "Transposed Grids"	""
@@ -5427,7 +5227,7 @@ TEXT	TRANSLATION
 "Type of Slope"	""
 "Type of distance calculation"	"Typ der Entfernungsberechnung"
 "Type of smoothing"	"Typ der Gl�ttung"
-"Type=\"%s\""	""
+"Type=\"	""
 "U-shaped Valleys"	""
 "UNRECOGNISED COMMAND ID"	""
 "USGS SRTM Grids (*.hgt)|*.hgt|All Files|*.*"	"USGS SRTM Raster (*.hgt)|*.hgt|Alle Dateien|*.*"
@@ -5455,7 +5255,6 @@ TEXT	TRANSLATION
 "Uniform"	"einheitlich"
 "Union"	"Verbindung"
 "Unique"	"eindeutig"
-"Unique Production Rate [m/h]"	""
 "Unit"	"Einheit"
 "Unit Name"	"Einheitenname"
 "Units"	"Einheiten"
@@ -5476,7 +5275,6 @@ TEXT	TRANSLATION
 "Up/Down"	"Auf/Ab"
 "Update"	"Aktualisiere"
 "Update Data"	""
-"Update Frequency"	""
 "Update Raster SRID"	""
 "Update Shapes SRID"	""
 "Update View"	"Aktualisiere Ansicht"
@@ -5489,19 +5287,13 @@ TEXT	TRANSLATION
 "Upland Drainages"	""
 "Upland Drainages, Headwaters"	""
 "Upper"	""
-"Upper Half"	""
 "Upper Slopes"	""
 "Upper Slopes, Mesas"	""
 "Upper Tolerance"	"Obere Toleranz"
-"Uppermost Rock Type"	""
-"Uppermost Rock Type Thickness"	""
 "Upscaling Method"	""
 "Upslope Area"	"Ansteigende Fl�che"
 "Upslope Basins"	"ansteigende Becken"
-"Upslope Curv UnNormalized"	""
 "Upslope Curvature"	""
-"Upslope Curvature Normalized"	""
-"Upslope Curvatures"	""
 "Upslope Flow Width"	""
 "Upslope Length Factor"	""
 "Upslope Slope"	""
@@ -5597,7 +5389,6 @@ TEXT	TRANSLATION
 "Van der Grinten"	"Van der Grinten"
 "Var.cum."	""
 "Variable"	""
-"Variables to Import"	""
 "Variance"	"Streuung"
 "Variance (version 1)"	"Varianz (Version 1)"
 "Variance (version 2)"	"Varianz (Version 2)"
@@ -5623,8 +5414,6 @@ TEXT	TRANSLATION
 "Vegetation parameters"	"Parameter Vegetation"
 "Velocidad del viento"	""
 "Velocidad del viento (km/h)"	""
-"Velocity"	""
-"Velocity Calculation"	""
 "Verbose"	""
 "Verbose Messages"	""
 "Verbose Output"	""
@@ -5642,13 +5431,11 @@ TEXT	TRANSLATION
 "Vertical Overland Flow Distance"	"Vertikale �berlandflie�entfernung"
 "Vertical Range"	"Vertikaler Bereich"
 "Vertical Scaling"	""
-"Vertical Tracer Density"	""
 "Vertical hatch"	"vertikale Schraffur"
 "Vertical scaling factor"	""
 "Vertically mirrored"	"vertikal gespiegelt"
 "Vertices"	""
 "Vertikale Zufluesse"	""
-"Verwitterungsformeln"	""
 "ViGrA"	""
 "Victor Olaya (c) 2004"	""
 "Victor Olaya (c) 2005"	""
@@ -5692,13 +5479,10 @@ TEXT	TRANSLATION
 "WKT: %s"	""
 "WMS Import"	"WMS Import"
 "WMS Map"	"WMS Karte"
-"WRF Extract Data"	""
-"WRF Extract and Downscale to DEM"	""
 "WUse Einheit"	""
 "W_up"	""
 "Wa-Tor"	""
 "Waehlen ob TestRoutine 1 durchgefuehrt werden soll... 1) nur fuer Teileinzugsgebiet der HG-Rasterzelle oder 2) fuer das Flusseinzugsgebiet bis zum Erreichen der HG-Rasterzelle."	""
-"Wang/Liu"	""
 "Warm Cloud"	""
 "Warning"	""
 "Warning: there are more predictor variables then dependent ones, surplus will be ignored."	""
@@ -5706,21 +5490,14 @@ TEXT	TRANSLATION
 "Water"	"Wasser"
 "Water Content [cm]"	"Wassergehalt [cm]"
 "Water Retention Capacity"	"Wasserretentionskapazit�t"
-"Water Surface Exaggeration"	""
 "Water Vapour Pressure [mbar]"	"Wasserdampfdruck [mbar]"
 "Water content change across the wetting front"	"Wassergehalts�nderung �ber die Befeuchtungsfront"
 "Water content of a vertical slice of atmosphere in cm: 1.5 to 1.7, average=1.68"	"Wassergehalt einer vertikalen Scheibe Atmosph�re in cm: 1,5 bis 1,7, Durchschnitt=1,68"
-"Water_discharge"	""
 "Watershed Basins"	"Wassereinzugsgebiete"
 "Watershed Basins (Extended)"	"Wassereinzugsgebiete (erweitert)"
 "Watershed Segmentation"	"Wassereinzugsgebietteile"
 "Watershed Segmentation (ViGrA)"	""
 "Weather Records"	"Wetterdaten"
-"Weathering"	""
-"Weathering Formulas"	""
-"Weathering Variables"	""
-"Weathering rate decay constant (1/m)"	""
-"Weathering threshold area"	""
 "Web Service Data Access"	""
 "Weight"	"Gewichtung"
 "Weight for grid "	"Gewichtung f�r Raster"
@@ -5751,6 +5528,8 @@ TEXT	TRANSLATION
 "Wind Direction Units"	"Windrichtung Einheiten"
 "Wind Effect"	"Windeffekt"
 "Wind Effect (Windward / Leeward Index)"	"Windeffekt (Windw�rts / Leew�rts Index)"
+"Wind Exposition"	""
+"Wind Exposition Index"	""
 "Wind Speed"	"Windgeschwindigkeit"
 "Wind Speed (m/s)"	"Windgeschwindigkeit (m/s)"
 "Wind direction (degrees clockwise from north)"	"Windrichtung (Grad im Uhrzeigersinn aus Norden)"
@@ -5767,9 +5546,9 @@ TEXT	TRANSLATION
 "Wire Frame Color"	"Drahtrahmenfarbe"
 "Wischmeier & Smith 1978"	""
 "Wombling (Edge Detection)"	""
-"Wombling Direction"	""
-"Wombling Magnitude"	""
+"Wombling for Multiple Features (Edge Detection)"	""
 "Wood Fuel Moisture"	"Holzfeuchte"
+"Workspace"	""
 "World File"	""
 "World File from Flight and Camera Settings"	""
 "Write Field Names"	"Schreibe Feldnamen"
@@ -5833,9 +5612,7 @@ TEXT	TRANSLATION
 "YMax: %.6f"	""
 "YMin: %.6f"	""
 "Year"	"Jahr"
-"Year [ka BP]"	""
 "Year [ka]"	"Jahr [ka]"
-"Years BP"	""
 "Yoshimasa Tsuruoka"	""
 "You can specify the number of layers in the network (including input and output layer)."	""
 "You can specify the number of neurons in each layer of the network."	""
@@ -5847,12 +5624,10 @@ TEXT	TRANSLATION
 "Z"	"Z"
 "Z Attribute"	"Z Attribute"
 "Z Axis"	"Z-Achse"
-"Z Model"	""
 "Z Multiplier"	""
 "Z Value"	"Z Wert"
 "Z Values"	"Z Werte"
 "Z is Column ..."	"Z ist Spalte..."
-"Z+S Model"	""
 "Z-Offset"	""
 "Z-Range"	"Z-Bereich"
 "Z-Rotation"	"Z-Rotation"
@@ -5862,9 +5637,9 @@ TEXT	TRANSLATION
 "ZMin"	""
 "ZMin: %.6f"	""
 "ZONE"	"ZONE"
-"Z_Model"	""
 "Zenith"	""
 "Zero"	"Null"
+"Zero as No-Data"	""
 "Zevenbergen & Thorne"	""
 "Zevenbergen & Thorne (1987) refer to this as plan curvature"	""
 "Zevenbergen & Thorne (1987) refer to this as profile curvature"	""
@@ -5920,32 +5695,6 @@ TEXT	TRANSLATION
 "\n\n ** Error : Could not close PDF engine ** \n\n"	"\n\n **Fehler: Konnte PDF-Modul nicht beenden **\n\n"
 "\n\n ** Error : Could not save PDF file ** \n\n"	"\n\n **Fehler: Konnte PDF-Datei nicht speichern **\n\n"
 "_TL"	""
-"__ACHAN__"	""
-"__C0__"	""
-"__CHANA__"	""
-"__DOWNWT__"	""
-"__DX__"	""
-"__KCI__"	""
-"__KC__"	""
-"__KDP__"	""
-"__KT__"	""
-"__MB__"	""
-"__MCI__"	""
-"__MDP__"	""
-"__MF__"	""
-"__MW__"	""
-"__NB__"	""
-"__NCI__"	""
-"__NF__"	""
-"__OPTDIFF__"	""
-"__OPTTRANS__"	""
-"__PF__"	""
-"__PMA__"	""
-"__PPT__"	""
-"__SCR__"	""
-"__TAUC__"	""
-"__TCI__"	""
-"__WRTINT__"	""
 "a * b"	""
 "a + b * (1 - exp(-(x / c)^2))"	""
 "a + b * (1 - exp(-x / c))"	""
@@ -5958,7 +5707,6 @@ TEXT	TRANSLATION
 "a(s)"	"a(s)"
 "a(s) [lower bound]"	"a(s) [untere Grenze]"
 "a(s) [upper bound]"	"a(s) [obere Grenze]"
-"abort"	""
 "abort export"	"breche Export ab"
 "absolute"	"absolut"
 "absolute catchment area"	""
@@ -5991,14 +5739,14 @@ TEXT	TRANSLATION
 "alternating scale bar"	""
 "alternative"	""
 "always ask what to do"	""
+"analyzing"	""
 "angle calculation is only available when exact two features are compared"	""
 "another grid"	"andere Rasterdaten"
-"append"	""
 "append records, if table structure allows"	"H�nge Datens�tze an, wenn die Tabellenstruktur dieses erlaubt"
 "appending to existing table"	"an bestehende Tabelle anh�ngen"
 "apply coordinate transformation if appropriate"	""
 "apply linear flow routing (D8) to all cells, having a flow accumulation greater than the specified threshold"	""
-"approximating points..."	"Punkte angleichend�"
+"approximating points..."	"Punkte angleichend?"
 "are completely within"	"sind vollkommen innerhalb"
 "are in the specified directory.\n"	"sind in der vorgegebenen Richtung.\n"
 "area"	"Fl�che"
@@ -6019,8 +5767,7 @@ TEXT	TRANSLATION
 "automatically"	""
 "average"	"Durchschnitt"
 "average size of the area covered by each category that occurs within search area"	""
-"averages"	""
-"averages + standard deviations"	""
+"average value"	""
 "avoids precision problems when source and target crs use different geodedtic datums."	""
 "b(q)"	"b(q)"
 "b(q) [lower bound]"	"b(q) [untere Grenze]"
@@ -6033,7 +5780,9 @@ TEXT	TRANSLATION
 "bar (not outlined)"	"Balken (nicht umrandet)"
 "basic SIA model"	""
 "before"	"vor"
+"before tool execution check failed"	""
 "begin transaction command failed"	""
+"between cells"	""
 "bi-linear saddle"	"bilinearer Sattel"
 "bicubic spline"	""
 "bilinear"	""
@@ -6047,20 +5796,22 @@ TEXT	TRANSLATION
 "blending distance given in map units"	""
 "blue channel color"	"Blauer Farbkanal"
 "bm"	""
-"both"	""
 "bottom"	"Unten"
 "bottom / left"	"unten / links"
 "bottom left"	"unten links"
 "bottom right"	"unten rechts"
 "bottom up"	""
+"bottom-left"	""
+"bottom-right"	""
 "bright - dark"	"hell - dunkel"
 "built-in"	"eingebaut"
 "c, Percentage clays [%]"	"c, Prozentanteil Tage [%]"
 "cache memory size in MB"	""
 "calculate averages"	"berechne Durchschnitt"
+"calculate from grid system"	""
 "calculate gradient magnitude"	"berechne Gradient der Magnitude"
 "calculate gradients"	"berechne Gradienten"
-"calculating splines..."	"Splines berechnend�"
+"calculating splines..."	"Splines berechnend?"
 "calculating variance"	""
 "cartesian"	"kartesisch"
 "catchment area and slope..."	""
@@ -6078,6 +5829,7 @@ TEXT	TRANSLATION
 "cellsize and upper left corner coordinates"	""
 "center"	"zentriert"
 "center cell's aspect direction"	"zentrale Zelle Bezugsrichtung"
+"centered"	""
 "central"	"zentral"
 "change"	"Wechsel"
 "check for building parts failed"	""
@@ -6103,7 +5855,6 @@ TEXT	TRANSLATION
 "clip features"	""
 "clipped"	""
 "clockwise"	"im Uhrzeigersinn"
-"closed"	""
 "closing"	"Schlie�en"
 "coef0"	""
 "coef0 in kernel function"	""
@@ -6124,8 +5875,9 @@ TEXT	TRANSLATION
 "concavity"	""
 "confirm"	"Best�tige"
 "confirm with options"	"Best�tige mit Optionen"
-"conrad"	""
 "constant direction into the wind blows, given as degree"	""
+"constant histogram stretch for all time steps"	""
+"constant latitude"	""
 "contain the centeroid of"	"enth�lt den Schwerpunkt von "
 "continue"	"fortsetzen"
 "continuous"	""
@@ -6142,25 +5894,29 @@ TEXT	TRANSLATION
 "corrupted record header"	"besch�digter Datensatzkopf"
 "corrupted shapefile."	"besch�digte Vektordatei."
 "could allocate memory for scaled grid"	""
+"could not access raster table"	""
+"could not access table"	""
 "could not add save point"	""
 "could not allocate memory for temporary grid."	""
 "could not allocate sufficient memory"	""
 "could not commit/rollback transactions."	"Konnte nicht �bergeben/wiederhole Transaktion."
 "could not connect ODBC source"	"kann nicht mit ODBC-Quelle verbinden"
 "could not connect to PostgreSQL source"	""
+"could not connect to database."	""
 "could not create KML file"	"KML-Datei kann nicht erzeugt werden"
 "could not create distance grid"	"Entfernungsraster konnte nicht erstellt werden"
 "could not create geometry field"	"Kann kein Geometriefeld erzeugen"
 "could not create index on observations"	""
 "could not create index: insufficient memory"	"Index konnte nicht erzeugt werden: nicht gen�gend Speicher"
+"could not create new PostgreSQL database"	""
 "could not create table"	""
 "could not create weights grid"	""
 "could not disconnect ODBC source"	""
 "could not disconnect PostgreSQL source"	""
+"could not disconnect and drop PostgreSQL database"	""
+"could not drop PostgreSQL database"	""
 "could not execute module"	"Werkzeug konnte nicht ausgef�hrt werden"
 "could not execute tool"	"Werkzeug konnte nicht ausgef�hrt werden"
-"could not find any band data"	""
-"could not find level data"	""
 "could not find module"	"Werkzeug konnte nicht lokalisiert werden"
 "could not find tool"	"Werkzeug konnte nicht lokalisiert werden"
 "could not import random forest"	""
@@ -6177,6 +5933,7 @@ TEXT	TRANSLATION
 "could not initialize tool"	"Werkzeug konnte nicht initialisiert werden"
 "could not load file"	""
 "could not load model from file"	""
+"could not load raster"	""
 "could not locate line string to polygon conversion tool"	""
 "could not open GetMap stream"	""
 "could not open data source"	"kann Datenquelle nicht �ffnen"
@@ -6200,7 +5957,6 @@ TEXT	TRANSLATION
 "creating batch file example"	"erzeuge Batch-Datei als Beispiel"
 "creating interpolator"	"erzeuge Interpolator"
 "creating tool documentation files"	"Erstelle Dateien zur Werkzeugdokumentation"
-"critical slope"	""
 "cross"	"Kreuz"
 "cubic convolution"	""
 "cubic surface"	"kubische Oberfl�che"
@@ -6219,7 +5975,6 @@ TEXT	TRANSLATION
 "dark object subtraction 4"	""
 "data / no-data"	""
 "data file could not be openend"	"Datendatei konnte nicht ge�ffnet werden"
-"data file does not exist"	""
 "data set has no attributes"	""
 "database table does not exist"	"Datentabelle existiert nicht"
 "date"	"Datum"
@@ -6247,12 +6002,11 @@ TEXT	TRANSLATION
 "delivery index calculation failed"	""
 "descending"	"absteigend"
 "diffuse pollution risk calculation failed"	""
-"diffusive"	""
-"diffusive and fluvial"	""
 "digital elevation model"	"digitales H�henmodell"
 "digital elevation model [m]"	"Digitales H�henmodell [m]"
 "digitzing a polygon"	"Digitalisiere ein Polygon"
 "dilation"	"Streckung"
+"direction"	""
 "direction of scan flag"	"Richtung des Scanflag"
 "direction of sun (degree, clockwise from North)"	"Richtung der Sonne (Grad, im Uhrzeigersinn von Nord)"
 "direction to the center cell"	"Richtung zur Mittelzelle"
@@ -6264,6 +6018,7 @@ TEXT	TRANSLATION
 "do not confirm"	"nicht best�tigen"
 "do not join"	"nicht verbinden"
 "do not show"	"nicht anzeigen"
+"do not sort"	""
 "do not update"	"nicht aktualisieren"
 "down"	"herunter"
 "downscaling"	""
@@ -6276,6 +6031,7 @@ TEXT	TRANSLATION
 "each pair with a single record"	""
 "each shape"	"jeder Vektor"
 "each shape's part"	""
+"edge cells"	""
 "edge collection"	"Eckensammlung"
 "edge detection"	"Eckenerkennung"
 "edge of flight line flag"	"Ecken der Flugroute flag"
@@ -6350,6 +6106,7 @@ TEXT	TRANSLATION
 "first"	"zu Erst"
 "first point"	"Erster Punkt"
 "first value"	"erster Wert"
+"fit histogram stretch for each time step"	""
 "fit to each grid"	"passe an alle Raster an"
 "fit to overall range"	"passe an gesamten Bereich an"
 "fit to overall standard deviation"	""
@@ -6368,7 +6125,6 @@ TEXT	TRANSLATION
 "flow directions..."	"Flie�richtungen..."
 "flow travel time to channel expressed in hours based on Manning's Equation"	""
 "flow width (original)"	"Flie�breite (original)"
-"fluvial"	""
 "forward"	"vorw�rts"
 "found less than two categories, nothing to do"	""
 "four-neighbourhood"	""
@@ -6377,11 +6133,8 @@ TEXT	TRANSLATION
 "full frame"	""
 "function fitting failed !"	"Funktionsanpassung fehlgeschlagen!"
 "function not found"	"Funktion nicht gefunden"
-"function parameters"	""
-"function parameters + trend quality"	""
 "function table full"	"Funktionstabelle voll"
 "gamma in kernel function"	""
-"gaps filled"	""
 "gaussian"	"Gaussche"
 "gaussian kernel"	"Gausscher kernel"
 "gaussian weighting"	"Gaussche Gewichtung"
@@ -6393,6 +6146,7 @@ TEXT	TRANSLATION
 "gps-time"	"GPS-Zeit"
 "gradient (degree)"	"Gradient (Grad)"
 "gradient (tangens)"	"Gradient (tangens)"
+"gradients"	""
 "green > blue"	"gr�n > blau"
 "green > grey > blue"	"gr�n > grau > blau"
 "green > red > blue"	"gr�n > rot > blau"
@@ -6424,7 +6178,6 @@ TEXT	TRANSLATION
 "high"	""
 "highest"	""
 "highest z"	"h�chster z"
-"hillslope length-to-channel"	""
 "histogram match"	""
 "horizontal"	"horizontal"
 "hours"	"Stunden"
@@ -6458,11 +6211,8 @@ TEXT	TRANSLATION
 "initial number of lag distance classes"	""
 "initial number of lag distance classes for variogram estimation"	""
 "initialisation error"	"Initialisierungsfehler"
-"initialising gradient..."	"Initialisiere Gradient..."
-"initialising planetary bending..."	"initialisiere planetare Beugung"
 "initialization"	"Initialisierung"
 "initialization failed"	""
-"initialize grid cells"	""
 "input"	"Eingabe"
 "input file"	"Eingabedatei"
 "instable (thawing)"	"instabil (auftauend)"
@@ -6482,9 +6232,11 @@ TEXT	TRANSLATION
 "invalid control points"	"ung�ltige Kontrollpunkte"
 "invalid data"	"ung�ltige Daten"
 "invalid division size"	""
+"invalid extent"	""
 "invalid features"	""
 "invalid field selection"	"ung�ltige Feldauswahl"
 "invalid file code"	"ung�ltiger Dateicode"
+"invalid file name"	""
 "invalid filter matrix"	"ung�ltige Filtermatrix"
 "invalid geographic coordinate system / datum"	"ung�ltiges geographisches Koordinatensystem / Datum"
 "invalid geogrid file name"	""
@@ -6503,6 +6255,7 @@ TEXT	TRANSLATION
 "invalid point cloud"	""
 "invalid points have been skipped"	"ung�ltige Punkte werden �bersprungen"
 "invalid points layer"	"ung�ltige Punktebene"
+"invalid polygons"	""
 "invalid production date"	""
 "invalid project file."	"ung�ltige Projektdatei."
 "invalid snap features"	""
@@ -6569,7 +6322,6 @@ TEXT	TRANSLATION
 "local"	""
 "local maximum search distance given in map units"	""
 "local slope"	""
-"local time"	"Lokalzeit"
 "local water depth or absolute water level at the user specified cell"	"lokale Wassertiefe oder absolute Wassertiefe in der vom Benutzer spezifizierten Zelle"
 "localhost"	"localhost"
 "logarithmic"	""
@@ -6587,15 +6339,13 @@ TEXT	TRANSLATION
 "m2/h"	""
 "m3/Monat"	""
 "m3/s"	""
-"m_pBoundary"	""
-"m_pRock_Top_Idx"	""
 "magenta - white"	"magenta - wei�"
 "main basins..."	"Hauptbecken..."
 "majority"	""
 "map units"	""
 "mark breaks in first line"	"Markierung bricht in erster Zeile"
 "masking no data"	""
-"masking..."	"maskieren�"
+"masking..."	"maskieren?"
 "match input data"	"�bereinstimmung Eingabedaten"
 "matching histogram"	""
 "mathematical"	"mathematisch"
@@ -6639,7 +6389,6 @@ TEXT	TRANSLATION
 "minimum number of upslope contributing cells to start a channel"	""
 "minimum requirement"	""
 "minimum slope angle preserved from one cell to the next, zero results in flat areas [Degree]"	"minimaler Neigungswinkel der von einer Zelle zur n�chsten erhalten bleibt, null ergibt eine ebene Fl�che [Grad]."
-"minimum sub-time step size in years"	""
 "minimum value"	"Minimalwert"
 "minimum value of all duplicates"	""
 "minimum x value"	"minimaler x-Wert"
@@ -6648,7 +6397,6 @@ TEXT	TRANSLATION
 "missing icon tags"	""
 "missing operand"	"fehlender Operand"
 "missing tool chain tags"	""
-"missing year"	""
 "model application"	""
 "model creation"	""
 "moment"	"Moment"
@@ -6680,6 +6428,7 @@ TEXT	TRANSLATION
 "no attributes in table"	"keine Attribute in der Tabelle"
 "no choice available"	""
 "no class definitions for final state"	"keine Klassendefinitionen f�r Endzustand"
+"no class definitions for grid"	""
 "no class definitions for initial state"	"Keine Klassendefinitionen f�r Ausgangszustand"
 "no conversion (areas already given as specific catchment area)"	"keine Umwandlung (Gebiete sind bereits als spezifische Einzugsgebiete gegeben)"
 "no data entries in project file."	""
@@ -6694,7 +6443,6 @@ TEXT	TRANSLATION
 "no features to buffer."	"keine Eigenschaften zum Puffern."
 "no fields in selection"	"Keine Felder in der Auswahl"
 "no fields to add"	""
-"no files in selection"	""
 "no gaps"	"Keine L�cken."
 "no geometry in selection"	""
 "no grid in list"	"kein Raster in Auflistung"
@@ -6708,7 +6456,7 @@ TEXT	TRANSLATION
 "no layers in data source"	"Keine Ebenen in Datenquelle"
 "no lines for splitting"	""
 "no memory"	"kein Speicher"
-"no output"	""
+"no name has been specified for new raster table"	""
 "no output parameter in selection"	"kein Ausgabeparameter in der Auswahl"
 "no parameter output specified"	""
 "no points in input layer"	""
@@ -6771,7 +6519,6 @@ TEXT	TRANSLATION
 "nothing to do. transformation needs at least two components."	""
 "nothing to do: input format is same as output format"	""
 "nothing to do: no data in selection"	"nichts zu tun: keine Daten ausgew�hlt"
-"nothing to do: no output to memory or file has been specified"	""
 "nothing to do: original and desired field types are identical"	""
 "nu-SVC"	""
 "nu-SVR"	""
@@ -6780,6 +6527,7 @@ TEXT	TRANSLATION
 "number of cells"	""
 "number of cells in S-N direction"	"Anzahl der Zellen in S-N-Richtung"
 "number of cells in W-E direction"	"Anzahl der Zellen in W-E-Richtung"
+"number of different categories (unique values) per area"	""
 "number of different categories (unique values) within search area"	""
 "number of dropped observations"	""
 "number of dropped shapes"	"Nummer der abgeworfenen Vektoren"
@@ -6802,6 +6550,9 @@ TEXT	TRANSLATION
 "offset in minutes relative to 00:00 (midnight)"	""
 "okay"	"okay"
 "old value"	"alter Wert"
+"on cell"	""
+"one catalogue for each coordinate system"	""
+"one catalogue using geographic coordinates"	""
 "one hull for all shapes"	"eine H�lle f�r alle Vektoren"
 "one hull per shape"	"eine H�lle pro Vektor"
 "one hull per shape part"	"eine H�lle pro Vektorteil"
@@ -6818,7 +6569,6 @@ TEXT	TRANSLATION
 "only points with given minimum number of points in search radius will be processed"	"nur Punkte mit einer gegebenen Mindestanzahl von Punkten im Suchradius werden bearbeitet"
 "only show within scale range; values are given as extent measured in map units"	""
 "only z"	"nur z"
-"open"	""
 "open transactions committed"	"offene Transaktionen �bermittelt"
 "open transactions rollbacked"	"offene Transaktionen wiederholt"
 "open transactions rolled back"	""
@@ -6828,6 +6578,7 @@ TEXT	TRANSLATION
 "optional grid providing values to be compared with linear flow threshold instead of flow accumulation"	""
 "optional input"	"optionale Eingabe"
 "optional output"	"optionale Ausgabe"
+"orientation"	""
 "origin adjustment for Z axis (heading)"	""
 "original"	""
 "original calculation (Ringeler)"	"Originalberechnung (Ringeler)"
@@ -6856,7 +6607,7 @@ TEXT	TRANSLATION
 "percent"	"Prozent"
 "percentiles"	""
 "perform region growing"	"ausf�hren des Regionen wachsen"
-"performing distance calculation..."	"f�hre Enfernungsberechnung aus�"
+"performing distance calculation..."	"f�hre Enfernungsberechnung aus?"
 "pie"	"Torte"
 "pie (not outlined)"	"Torte (nicht umrandet)"
 "point (.)"	"Punkt (.)"
@@ -6883,11 +6634,10 @@ TEXT	TRANSLATION
 "polynomial"	""
 "polynomial trend"	""
 "polynomial trend (coefficient interpolation)"	""
-"polyonom fit"	""
 "post-processing..."	""
 "power of distance"	"power of distance"
 "prediction"	""
-"preparing distance calculation..."	"bereite Entfernungsberechnung vor�"
+"preparing distance calculation..."	"bereite Entfernungsberechnung vor?"
 "press any key"	"Dr�cke eine beliebige Taste"
 "processed DEM"	"berechnetes DGM"
 "processing"	""
@@ -6899,7 +6649,6 @@ TEXT	TRANSLATION
 "quadratic surface"	"quadratische Oberfl�che"
 "quantiles"	"Quantile"
 "quartic kernel"	"biquadratischer Systemkern"
-"r2"	""
 "radial basis function"	""
 "radians"	"Radians"
 "radians to degree"	"Radians zu Grad"
@@ -6907,7 +6656,6 @@ TEXT	TRANSLATION
 "radius given in map units used to fill valleys"	""
 "radius in map units"	"Radius in Karteneinheiten"
 "rainbow"	"Regenbogen"
-"random"	""
 "random read"	"zuf�llig lesen"
 "random write"	"zuf�llig schreiben"
 "range"	""
@@ -6940,7 +6688,6 @@ TEXT	TRANSLATION
 "remove maxima (with tolerance)"	"entferne Maxima (mit Tolernz)"
 "remove minima (with tolerance)"	"entferne Minima (mit Toleranz)"
 "removed"	""
-"replace"	""
 "replace existing table"	"ersetze bestehende Tabelle"
 "replacements"	"Austausch"
 "resampling"	"Neuberechnung"
@@ -7010,7 +6757,6 @@ TEXT	TRANSLATION
 "shapes extent"	""
 "shapes have been dropped"	"Vektoren wurden zugewiesen"
 "shapes layer extent"	"Vektorebenen-Umfang"
-"shear stress coefficient Kt:"	""
 "show direct insolation for each time step."	"zeige direkte Sonneneinstrahlung f�r jeden Zeitschritt."
 "show mouse position in statusbar using geographic coordinates if possible"	""
 "shows cell values when zoomed"	""
@@ -7065,7 +6811,6 @@ TEXT	TRANSLATION
 "statistics table does not contain any records"	""
 "statistics table is missing required fields"	""
 "stddev"	""
-"steepest neighbour"	""
 "step"	"Schritt"
 "step size should not exceed number of cells in x or y direction"	""
 "stepwise"	"Schrittweise"
@@ -7091,6 +6836,7 @@ TEXT	TRANSLATION
 "take value from the point to be kept"	""
 "target"	"Ziel"
 "target area is distinct from levels area "	""
+"target's spatial reference system is undefined"	""
 "text"	"Text"
 "the lower this value is the stronger is the suction effect"	""
 "theta"	"theata"
@@ -7099,7 +6845,6 @@ TEXT	TRANSLATION
 "this operation requires locations to be of type polygon"	"diese Operation ben�tigt Standorte vom Typ Polygon"
 "this operation requires selectable shapes to be of type polygon"	"diese Operation ben�tigt ausw�hlbare Vektoren vom Typ Polygon"
 "threshold slope"	"Schwellenwert Neigung"
-"time of sunrise/sunset is only calculated if time span is set to single day"	"Die Zeit des Sonnenauf-/-untergangs kann nur berechnet werden wenn die Zeitspanne auf einzelnen Tag gesetzt ist."
 "tolerance as absolute values"	"Toleranz als absoluter Wert"
 "tolerance of termination criterion"	""
 "too few parameters"	"Zu wenige Parameter"
@@ -7117,6 +6862,8 @@ TEXT	TRANSLATION
 "top hat"	""
 "top left"	"Oben links"
 "top right"	"Oben rechts"
+"top-left"	""
+"top-right"	""
 "top-to-bottom and left-to-right cell sizes differ."	""
 "topographic wetness index..."	""
 "topography"	"Topographie"
@@ -7158,8 +6905,6 @@ TEXT	TRANSLATION
 "unsupported vector type"	""
 "until user closes it"	"bis Mausklick"
 "up"	"auf"
-"update, colour stretch for each time step"	"aktualisieren, Farbkennzeichnung f�r jeden Zeitschritt"
-"update, fixed colour stretch"	"aktualisieren, feste Farbkennzeichnung"
 "upscaling of predictors"	""
 "upsetting model domain"	""
 "use a zero value for hillslopes, any other value for channel cells."	""
@@ -7167,12 +6912,10 @@ TEXT	TRANSLATION
 "use old version for constant wind direction (no acceleration and averaging option)"	""
 "use this for (linear) flow routing, if the value is a valid direction (0-7 = N, NE, E, SE, S, SW, W, NW)"	""
 "use this grid's system for output grids"	""
-"use values in selected cold air height output grid"	""
 "user data"	"Benutzerdaten"
 "user defined"	"nutzerdefiniert"
 "user defined NoData value"	""
 "user defined kernel"	"Benutzerdefinierter Kernel"
-"user defined reference"	"Benutzerdefinierte Referenz"
 "user defined size"	"Benutzer definierte Gr��e"
 "using cellsize"	""
 "valid data cells match original grid extent"	""
@@ -7185,18 +6928,12 @@ TEXT	TRANSLATION
 "variance-covariance matrix"	"Varianz-Kovarianz Matrix"
 "variogram model"	""
 "vertical"	"vertikal"
-"virus 1"	""
-"virus 2"	""
-"von Neumann (4)"	""
 "w"	""
-"wang/liu"	""
 "warning"	""
 "warning, input uses less than 4 bytes per value"	""
 "warning: albedo is ignored"	""
-"warning: local sink detected"	""
 "warning: number of Eigen vectors and components differs."	""
 "warning: number of component grids and components differs."	""
-"weathering only"	""
 "weighting factor for slope in index calculation"	""
 "whether to train a SVC or SVR model for probability estimates"	""
 "whether to use the shrinking heuristics"	""
@@ -7209,6 +6946,7 @@ TEXT	TRANSLATION
 "wire"	"Draht"
 "with B-spline refinement"	"mit B-Spline-Verfeinerung"
 "without B-spline refinement"	"ohne B-Spline-Verfeinerung"
+"world"	""
 "x - Values"	"x - Werte"
 "x Position"	"x Position"
 "x, y"	""
@@ -7224,8 +6962,6 @@ TEXT	TRANSLATION
 "y Position"	"y Position"
 "yMax"	""
 "yMin"	""
-"years"	""
-"years before present"	""
 "yellow - white"	"gelb - wei�"
 "yellow > blue"	"gelb > blau"
 "yellow > green"	"gelb > gr�n"
diff --git a/src/saga_core/saga_gui/res/saga.lng.txt b/src/saga_core/saga_gui/res/saga.lng.txt
index 2aaf06b..3b76706 100644
--- a/src/saga_core/saga_gui/res/saga.lng.txt
+++ b/src/saga_core/saga_gui/res/saga.lng.txt
@@ -46,7 +46,6 @@ TEXT	TRANSLATION
 "  Total Points:\t%ld"	""
 "  Total Pulses:\t%ld"	""
 "  Version:\t\t\t%d.%d"	""
-" Bed_shear_stress"	""
 "%.0f points from %d dataset(s) written to output grid %s."	""
 "%d points from %d dataset(s) written to output point cloud %s."	""
 "%d points from %s written to output %s."	""
@@ -68,7 +67,6 @@ TEXT	TRANSLATION
 "(b)"	""
 "(b) [lower bound]"	""
 "(b) [upper bound]"	""
-"(c) 2007 by O.Conrad, R.Heinrich"	""
 "(c) Parameter [lower bound]"	""
 "(c) Parameter [upper bound]"	""
 "(f) Temperature Modulation Factor [lower bound]"	""
@@ -160,6 +158,7 @@ TEXT	TRANSLATION
 "20 seconds"	""
 "200-400 mm/day"	""
 "256x256"	""
+"2nd Date (End of Range)"	""
 "2nd Order Polynomial"	""
 "2nd Std. Parallel"	""
 "3"	""
@@ -240,7 +239,6 @@ TEXT	TRANSLATION
 "A3 Portrait"	""
 "A4 Landscape"	""
 "A4 Portrait"	""
-"A:Garden"	""
 "A:Garden|Imagery"	""
 "A:Grid|Analysis|Macroecology"	""
 "A:Grid|Distances"	""
@@ -253,18 +251,21 @@ TEXT	TRANSLATION
 "A:Imagery|Fourier Analysis"	""
 "A:Imagery|Segmentation"	""
 "A:Imagery|Tools"	""
-"A:Jan Hohlbein"	""
 "A:Shapes|Construction"	""
 "A:Shapes|Conversion"	""
 "A:Shapes|Selection"	""
 "A:Shapes|Table"	""
 "A:Shapes|Tools"	""
+"A:Simulation|Hillslope Evolution"	""
+"A:Simulation|Hydrology"	""
 "A:Spatial and Geostatistics|Geographically Weighted Regression"	""
 "A:Spatial and Geostatistics|Points"	""
 "A:Table|Construction"	""
 "A:Table|Selection"	""
 "A:Table|Tools"	""
 "A:Terrain Analysis|Climate and Weather"	""
+"A:Terrain Analysis|Hydrology|Flow Accumulation"	""
+"A:Terrain Analysis|Preprocessing"	""
 "A:Terrain Analysis|Terrain Classification"	""
 "ADDR"	""
 "AFAC("	""
@@ -333,7 +334,6 @@ TEXT	TRANSLATION
 "Add Field"	""
 "Add Frame"	""
 "Add Graticule"	""
-"Add Grid Name Field"	""
 "Add Grid Values to Points"	""
 "Add Grid Values to Shapes"	""
 "Add Identifier"	""
@@ -345,7 +345,6 @@ TEXT	TRANSLATION
 "Add Point Attributes to Polygons"	""
 "Add Point Order"	""
 "Add Polygon Attributes to Points"	""
-"Add Position [A]"	""
 "Add Position [Ctrl + A]"	""
 "Add Project"	""
 "Add Record"	""
@@ -357,9 +356,11 @@ TEXT	TRANSLATION
 "Add overlap to AOI"	""
 "Add point order as additional attribute."	""
 "Add to Map"	""
+"Add to Table"	""
 "Add unique identifier attribute field to output, ID resembles processing order."	""
 "Added"	""
 "Addition"	""
+"Additional Output"	""
 "Additional Point Clouds"	""
 "Additional Values"	""
 "Additional point clouds to merge with main point cloud."	""
@@ -380,7 +381,6 @@ TEXT	TRANSLATION
 "Aggregation"	""
 "Aggregation Index"	""
 "Aggregation Size"	""
-"Air Flow"	""
 "Air Humidity (2pm) [%%]"	""
 "Air Pressure, Water and Dust Content"	""
 "Albedo"	""
@@ -388,6 +388,7 @@ TEXT	TRANSLATION
 "Alessandro Perego"	""
 "Algorithm"	""
 "Algorithm for the detection of Surface Specific Points"	""
+"Alignment"	""
 "All"	""
 "All Files"	""
 "All Files|*.*|"	""
@@ -400,8 +401,6 @@ TEXT	TRANSLATION
 "Allgemeine Parameter"	""
 "Allocation"	""
 "Allocation Grid"	""
-"Allochthone Input"	""
-"Allochthoner Eintrag"	""
 "Allow Edge Pixels to be Seeds"	""
 "Allow longitudes outside -180 to 180 Range"	""
 "Allow multiple observer positions."	""
@@ -432,10 +431,9 @@ TEXT	TRANSLATION
 "Angle in degrees, clockwise around z axis"	""
 "Angle in degrees, counting clockwise from north"	""
 "Angular Distance Weighted"	""
+"Angular Step Size (Degree)"	""
 "Annual"	""
-"Annual Climate"	""
 "Annual Course of Daily Insolation"	""
-"Answer"	""
 "Append Fields from another Table"	""
 "Append Rows from ..."	""
 "Applies also to the binary format header file."	""
@@ -462,7 +460,6 @@ TEXT	TRANSLATION
 "Area Conversion"	""
 "Area [km2]"	""
 "Area [km2] Subbasin("	""
-"Area of an active channel within a cell"	""
 "Area of the Watershed in [km2]"	""
 "Area of the Watershed in [km2] used for unit conversion"	""
 "Area to Length Conversion"	""
@@ -490,7 +487,6 @@ TEXT	TRANSLATION
 "Atlas Boundary Files (*.bna)"	""
 "Atmospheric Correction"	""
 "Atmospheric Effects"	""
-"Atmospheric Pressure [mbar]"	""
 "Attribute"	""
 "Attribute (Size)"	""
 "Attribute Field"	""
@@ -510,7 +506,6 @@ TEXT	TRANSLATION
 "Attributes to import besides x,y,z ..."	""
 "August"	""
 "Ausgabedaten"	""
-"Ausgangsgestein Layer"	""
 "Ausgangsrasterzelle Flusseinzugsgebiet [Default: Elbe5000]"	""
 "Auswahl der Art der anteiligen Flaechenwasserwasserentnahme."	""
 "Auswahl der Art der dynamischen Flaechenwasserwassernutzung (WUse). ACHTUNG: Funktioniert ggf. nur bei bereits initiierten Systemen bzw. nach Vorlauf"	""
@@ -578,7 +573,6 @@ TEXT	TRANSLATION
 "Backward Diagonal"	""
 "Backward [Page Down]"	""
 "Backward diagonal hatch"	""
-"Bagnold"	""
 "Band"	""
 "Band 1"	""
 "Band 2"	""
@@ -589,9 +583,11 @@ TEXT	TRANSLATION
 "Band 62"	""
 "Band 7"	""
 "Band 8"	""
+"Band Name Field"	""
 "Bands"	""
 "Bandwidth (Cells)"	""
 "Bare Earth"	""
+"Barometric Pressure [mbar]"	""
 "Bars"	""
 "Base Level"	""
 "Base Name"	""
@@ -600,10 +596,8 @@ TEXT	TRANSLATION
 "Basic measures for spatial point patterns."	""
 "Basin Type (Gravelius)"	""
 "Basins"	""
-"Bed_shear_stress"	""
 "Beep when finished"	""
 "Begin Transaction"	""
-"Begin with Year..."	""
 "Below this threshold precipitation will fall as snow"	""
 "Beruecksichtigung der Hauptgerinnerasterzellen?"	""
 "Beta"	""
@@ -637,10 +631,8 @@ TEXT	TRANSLATION
 "Borders"	""
 "Bottom"	""
 "Bottom to Top"	""
-"Boundary"	""
 "Boundary Effect"	""
 "Boundary Effect Color"	""
-"Boundery"	""
 "Bounding Box"	""
 "Bounding Box [B]"	""
 "Branches"	""
@@ -677,7 +669,6 @@ TEXT	TRANSLATION
 "CENTER"	""
 "CFAC("	""
 "CFit\n(created by SAGA Wizard)."	""
-"CHELSA"	""
 "CLASS"	""
 "CLASS_ID"	""
 "CLASS_NR"	""
@@ -753,12 +744,10 @@ TEXT	TRANSLATION
 "Centroid Y"	""
 "Centroids"	""
 "Centroids for each part"	""
-"Change"	""
 "Change Cell Values"	""
 "Change Color Format"	""
 "Change Data Storage"	""
 "Change Date Format"	""
-"Change Detection"	""
 "Change Field Type"	""
 "Change Grid Values"	""
 "Change Grid Values - Flood Fill"	""
@@ -769,11 +758,9 @@ TEXT	TRANSLATION
 "Change all values within radius."	""
 "Changed"	""
 "Changed Grid"	""
-"Changes"	""
 "Channel"	""
 "Channel Definition Threshold (ha)"	""
 "Channel Density"	""
-"Channel Depth"	""
 "Channel Direction"	""
 "Channel Initiation Threshold"	""
 "Channel Mask"	""
@@ -788,16 +775,9 @@ TEXT	TRANSLATION
 "Channel Network: Pass 5"	""
 "Channel Network: Pass 6"	""
 "Channel Skeleton"	""
-"Channel Type"	""
 "Channel definition threshold"	""
-"Channel depth constant"	""
-"Channel depth exponent (depth = KDP * AREA^MDP)"	""
 "Channel network, all other cells NoData"	""
 "Channel side slope(m/m)"	""
-"Channel width constant ((s/m)^1/2"	""
-"Channel width constant [(s/m)^0.5]"	""
-"Channel_depth"	""
-"Channel_type"	""
 "Channels"	""
 "Channels (Raster)"	""
 "Channels (Vector)"	""
@@ -809,7 +789,6 @@ TEXT	TRANSLATION
 "Check Point Validity"	""
 "Check Vertices"	""
 "Check for Building Parts"	""
-"Check the attributes to drop"	""
 "Check the fields to export"	""
 "Check this in order to include NoData cells in the calculation."	""
 "Check this in order to include NoData points in the calculation."	""
@@ -821,6 +800,7 @@ TEXT	TRANSLATION
 "Chip size of reference chip to be found in search chip"	""
 "Chip size of search chip, used to find correlating reference chip"	""
 "Choice"	""
+"Choose 'slim' to trace grid node's shadow, 'fat' to trace the whole cell's shadow, or ignore shadowing effects. The first is slightly faster but might show some artifacts."	""
 "Choose 'slim' to trace grid node's shadow, 'fat' to trace the whole cell's shadow. The first is slightly faster but might show some artifacts."	""
 "Choose Cut from ..."	""
 "Choose Directory"	""
@@ -851,6 +831,7 @@ TEXT	TRANSLATION
 "Circle Point Distance [Degree]"	""
 "Circles"	""
 "Circular"	""
+"Citation"	""
 "CityGML file import failed"	""
 "CityGML import failed"	""
 "Class"	""
@@ -859,8 +840,11 @@ TEXT	TRANSLATION
 "Class Identifier"	""
 "Class Name"	""
 "Class Selection"	""
+"Class Values"	""
 "Classes"	""
 "Classification"	""
+"Classification 1"	""
+"Classification 2"	""
 "Classification Constant"	""
 "Classification Method"	""
 "Classification Quality"	""
@@ -878,10 +862,7 @@ TEXT	TRANSLATION
 "Clear Selection"	""
 "Climate"	""
 "Climate Data"	""
-"Climate and Weather Data"	""
-"Climate data regionalisation."	""
 "Climate parameters"	""
-"Climate|Climate Data"	""
 "Climatic Precession"	""
 "Clip Features"	""
 "Clip Grid with Polygon"	""
@@ -899,6 +880,7 @@ TEXT	TRANSLATION
 "Close Gaps with Spline"	""
 "Close Gaps with Stepwise Resampling"	""
 "Close One Cell Gaps"	""
+"Close Project"	""
 "Close all data sets"	""
 "Closed Depressions"	""
 "Closed Gaps Grid"	""
@@ -916,9 +898,6 @@ TEXT	TRANSLATION
 "ClusterID"	""
 "Clusters"	""
 "Coefficient of Determination"	""
-"Cold Air Height"	""
-"Cold Air Surface"	""
-"Cold Air Temperature [�C]"	""
 "Cold Cloud"	""
 "Collect values"	""
 "Collpase Options"	""
@@ -945,9 +924,11 @@ TEXT	TRANSLATION
 "Colours"	""
 "Colours Palette"	""
 "Columns"	""
+"Combination"	""
 "Combination A"	""
 "Combination B"	""
 "Combine Grids"	""
+"Combined Classes"	""
 "Combined Minimum Distance / Hillclimbing"	""
 "Combined Shading"	""
 "Comma Separated Values"	""
@@ -970,17 +951,19 @@ TEXT	TRANSLATION
 "CompuServe Graphics Interchange"	""
 "CompuServe Graphics Interchange (*.gif)"	""
 "Computed flow directions, 0=N, 1=NE, 2=E, ... 7=NW"	""
-"Concentration"	""
-"Concentration Approximation Threshold"	""
 "Concentration time (h)"	""
-"Conceptualization of Spatial Relationships"	""
 "Condition"	""
 "Cone (Down)"	""
 "Cone (Up)"	""
 "Cone (down)"	""
 "Cone (up)"	""
 "Confirm file caching"	""
+"Confusion"	""
 "Confusion Index"	""
+"Confusion Matrix"	""
+"Confusion Matrix (Polygons / Grid)"	""
+"Confusion Matrix (Two Grids)"	""
+"Connect to Database"	""
 "Connect to ODBC Source"	""
 "Connect to PostgreSQL"	""
 "Connected"	""
@@ -992,8 +975,8 @@ TEXT	TRANSLATION
 "Connectivity Neighbourhood"	""
 "Connectivity Weighting"	""
 "Connectivity [Percent]"	""
-"Conrad"	""
 "Constant Grid"	""
+"Constant Histogram Stretch"	""
 "Constant Value"	""
 "Constant Variation Range [Degree]"	""
 "Constant Wind Direction"	""
@@ -1059,6 +1042,8 @@ TEXT	TRANSLATION
 "Copy Legend to Clipboard [Ctrl+L]"	""
 "Copy Legend to Clipboard..."	""
 "Copy Map to Clipboard [Ctrl+C]"	""
+"Copy Project to Database"	""
+"Copy Project to..."	""
 "Copy Selection"	""
 "Copy Selection to New Shapes Layer"	""
 "Copy Settings from other Layer"	""
@@ -1102,12 +1087,12 @@ TEXT	TRANSLATION
 "Count Only Above Base Level"	""
 "Count Only Below Base Level"	""
 "Count Points in Polygons"	""
-"Counter for function calls greater 0"	""
 "Covariance"	""
 "Covariance Surface"	""
 "Covered Distance"	""
 "Create 3D Image"	""
 "Create Chart Layer (bars/sectors)"	""
+"Create Database"	""
 "Create Graticule"	""
 "Create Grid System"	""
 "Create KML File"	""
@@ -1120,7 +1105,8 @@ TEXT	TRANSLATION
 "Create PDF Documents"	""
 "Create Point Grid"	""
 "Create Propabilities"	""
-"Create Reference Data"	""
+"Create Raster Catalogue from Files"	""
+"Create Raster Catalogues from Directory"	""
 "Create Reference Points"	""
 "Create Script Command File"	""
 "Create Single Multipart Polygon"	""
@@ -1182,6 +1168,7 @@ TEXT	TRANSLATION
 "D/sqrt(A)"	""
 "D8"	""
 "DATA_CELLS"	""
+"DBMS"	""
 "DBase"	""
 "DBase file could not be opened."	""
 "DBase file does not contain any records."	""
@@ -1199,12 +1186,10 @@ TEXT	TRANSLATION
 "DIFF_MEAN"	""
 "DN"	""
 "DSN"	""
-"DT Time step size (yrs)"	""
 "DTM 1"	""
 "DTM 2"	""
 "DTM Filter (slope-based)"	""
 "DTM, digital terrain model [m]"	""
-"DTMIN Minimum sub-time"	""
 "DXF"	""
 "DXF Files (*.dxf)|*.dxf|All Files|*.*"	""
 "Daily Data"	""
@@ -1214,14 +1199,13 @@ TEXT	TRANSLATION
 "Dark Object Subtraction"	""
 "Darkness Digital Number (DN)"	""
 "Data"	""
-"Data Directory"	""
 "Data History"	""
 "Data Manager"	""
 "Data Object"	""
 "Data Objects"	""
 "Data Offset (Bytes)"	""
-"Data Source"	""
 "Data Source Name"	""
+"Data Sources"	""
 "Data Storage Type"	""
 "Data Table"	""
 "Data Type"	""
@@ -1230,7 +1214,6 @@ TEXT	TRANSLATION
 "Data storage type"	""
 "Data type"	""
 "Database"	""
-"Database Connection Error"	""
 "Database Name"	""
 "Database access through the libmysql.lib interface."	""
 "Database with Coordinate Reference System (CRS) definitions. A restart of SAGA is required to have the changes take effect!"	""
@@ -1248,9 +1231,9 @@ TEXT	TRANSLATION
 "Datums (3 Parameters)"	""
 "Datums (7 Parameters)"	""
 "Day"	""
+"Day Length"	""
 "Day of Month"	""
 "Day of Year"	""
-"Day of Year (End of Range)"	""
 "Day-Degree Factor"	""
 "Day-Degree Factor (lower bound)"	""
 "Day-Degree Factor (upper bound)"	""
@@ -1279,7 +1262,6 @@ TEXT	TRANSLATION
 "Default Reference Height"	""
 "Default Rotation"	""
 "Default Size"	""
-"Default Weathering Formula"	""
 "Defaults"	""
 "Defaults for New Maps"	""
 "Define AOI by ..."	""
@@ -1287,7 +1269,6 @@ TEXT	TRANSLATION
 "Definition"	""
 "Degree"	""
 "Dekang Lin"	""
-"Delay"	""
 "Delete"	""
 "Delete All Positions"	""
 "Delete All Positions [Ctrl + X]"	""
@@ -1295,19 +1276,16 @@ TEXT	TRANSLATION
 "Delete Fields"	""
 "Delete History Entries"	""
 "Delete Last Position [Ctrl + D]"	""
-"Delete Last Position [D]"	""
 "Delete Selected Part"	""
 "Delete Selected Point"	""
-"Delete Selected Record(s)"	""
-"Delete Selected Shape(s)"	""
 "Delete Selection"	""
 "Delete Selection from Shapes Layer"	""
 "Delete selected point(s)."	""
 "Delete selected shape(s)."	""
+"Deleting raster band"	""
 "Deleting table"	""
 "Delineated watershed basins"	""
 "Delivery Index"	""
-"Dem"	""
 "Denoised"	""
 "Denoised Grid"	""
 "Denormalisation"	""
@@ -1324,7 +1302,6 @@ TEXT	TRANSLATION
 "Depression-free digital elevation model"	""
 "Depth"	""
 "Depth to which data history is stored. Set -1 keeps all history entries (default), 0 switches history option off."	""
-"Depth_base_rock"	""
 "Der Gerinne- bzw. Hauptgerinneabfluss kann mit dieser Methode fuer Rasterzelle 1 manipuliert werden. "	""
 "Der Gerinne- bzw. Hauptgerinneabfluss kann mit dieser Methode fuer Rasterzelle 2 manipuliert werden. "	""
 "Derivation of slope lengths from catchment areas. These are rough approximations! Applies not to Desmet & Govers' method."	""
@@ -1344,6 +1321,7 @@ TEXT	TRANSLATION
 "Detector type"	""
 "Determination"	""
 "Determination Coefficients"	""
+"Determines how the graticule is aligned to the extent, if division sizes do not fit."	""
 "Deterministic 8"	""
 "Deterministic 8 (D8)"	""
 "Deterministic Infinity"	""
@@ -1372,11 +1350,7 @@ TEXT	TRANSLATION
 "Diffusive Hillslope Evolution (ADI)"	""
 "Diffusive Hillslope Evolution (FTCS)"	""
 "Diffusivity [m2 / kyr]"	""
-"Diffusivity coefficient Kd (m^2/yr"	""
-"Diffusivity coefficient Kd (m^2/yr)"	""
-"Diffusivity coefficient Kd [m^2/a]"	""
 "Difuse Pollution Risk"	""
-"Digital Elevation Model"	""
 "Digital Elevation Model that has to be processed"	""
 "Digital Terrain Model"	""
 "Digital elevation model"	""
@@ -1393,6 +1367,7 @@ TEXT	TRANSLATION
 "Direct Insolation"	""
 "Direct to Diffuse Ratio"	""
 "Direction"	""
+"Direction Difference"	""
 "Direction [Degree]"	""
 "Direction into which the wind blows, starting with 0 for North and increasing clockwise."	""
 "Direction of Minimum Standard Deviation"	""
@@ -1405,10 +1380,7 @@ TEXT	TRANSLATION
 "Directional Statistics for Points"	""
 "Directional Statistics for Single Grid"	""
 "Directory"	""
-"Directory with NCAR Grib Files"	""
 "Directory, where temporary cache files shall be saved."	""
-"Discharge exponent Mb for bedrock channel erosion"	""
-"Discharge exponent Mf for fluvial sediment transport"	""
 "Disconnect All"	""
 "Disconnect from ODBC Source"	""
 "Disconnect from PostgreSQL"	""
@@ -1419,9 +1391,6 @@ TEXT	TRANSLATION
 "Displacement Vector"	""
 "Displacement vectors between correlated points"	""
 "Display"	""
-"Display Maximun"	""
-"Display Minimum"	""
-"Display Minimun"	""
 "Display Resolution"	""
 "Display Type"	""
 "Dissolve Buffers"	""
@@ -1441,14 +1410,10 @@ TEXT	TRANSLATION
 "Distance Weighting"	""
 "Distance Weighting Exponent"	""
 "Distance between points (grid units)."	""
-"Distance to the Channel"	""
-"Distance to the Crest"	""
 "Distances"	""
 "Distinct"	""
 "Diurnal Anisotropic Heating"	""
 "Divergence"	""
-"Divergent Flow Accumulation / Object Update"	""
-"Divergent Upslope Curvature"	""
 "Diversity"	""
 "Diversity of Categories"	""
 "Dividend"	""
@@ -1458,6 +1423,7 @@ TEXT	TRANSLATION
 "Division by zero is not allowed !!!"	""
 "Divisor"	""
 "Do you really want to delete the table"	""
+"Do you really want to delete this raster band"	""
 "Do you want to delete the selection?"	""
 "Do you want to exit SAGA?"	""
 "Do you wish to estimate Principal Point Offsets?"	""
@@ -1478,11 +1444,8 @@ TEXT	TRANSLATION
 "Downslope Basins"	""
 "Downslope Curvature"	""
 "Downslope Distance Gradient"	""
-"Downstream weighting factor (between zero and ~1/2)"	""
-"Drainage Area"	""
 "Drainage Basins"	""
 "Drainage Network"	""
-"Drainage_area"	""
 "Drape Map"	""
 "Draw Box"	""
 "Draw Faces"	""
@@ -1492,6 +1455,8 @@ TEXT	TRANSLATION
 "Draw a section each n points"	""
 "Driver"	""
 "Driver does not support file creation."	""
+"Drop"	""
+"Drop Database"	""
 "Drop Point Cloud Attributes"	""
 "Drop Table"	""
 "Dummy Grid"	""
@@ -1500,7 +1465,6 @@ TEXT	TRANSLATION
 "Duration of Insolation"	""
 "Dust [ppm]"	""
 "Dust factor: 100 ppm (standard)"	""
-"Dynamics"	""
 "Dynamische Flaechenwassernutzung und Abflussreduktion"	""
 "Dynamische Flaechenwassernutzung..."	""
 "EDGES"	""
@@ -1527,6 +1491,8 @@ TEXT	TRANSLATION
 "Eccentricity (e)"	""
 "Eckert IV/VI"	""
 "Edge"	""
+"Edge Cells"	""
+"Edge Connectivity"	""
 "Edge Contamination"	""
 "Edge Detection (ViGrA)"	""
 "Edge Points"	""
@@ -1537,16 +1503,13 @@ TEXT	TRANSLATION
 "Edit 3D-View Sequencer Positions"	""
 "Edit Point Cloud"	""
 "Edit Positions"	""
-"Edit Selected Shape"	""
+"Edit Selection"	""
 "Edit Shapes"	""
 "Efective friction = stated friction ^f , where f = cos(DifAngle)^k."	""
-"Eff. Precipitation Rate"	""
 "Effective Air Flow Heights"	""
 "Effective Flow Length"	""
 "Effective Rainfall"	""
 "Effective hydrological depth"	""
-"Effective precipitation rate (m/yr, or m/s for MPM)"	""
-"Effective precipitation rate, [m/a] or [m/s] for MPM"	""
 "Eigen Vectors"	""
 "Eigen reduction failed"	""
 "Eigenvalue"	""
@@ -1566,7 +1529,6 @@ TEXT	TRANSLATION
 "Elevation at Reference Station [m]"	""
 "Elevation grid"	""
 "Elevation range (zMax (%.2f) - zMin (%.2f)) is equal or lower than zero!"	""
-"Elevations"	""
 "Ellipsoid Definition"	""
 "Ellipsoid Height [m]"	""
 "Ellipsoids"	""
@@ -1574,8 +1536,6 @@ TEXT	TRANSLATION
 "Encountered invalid path description in *.spcvf_tile_info file!"	""
 "End Latitude"	""
 "End Longitude"	""
-"End Time"	""
-"End with Year..."	""
 "Enforce True Color"	""
 "Enhanced Vegetation Index"	""
 "Entropy"	""
@@ -1611,7 +1571,6 @@ TEXT	TRANSLATION
 "Estimated noise relative to mean standard deviation"	""
 "Et/Eo, ratio of actual to potential evapotranspiration"	""
 "Euclidean"	""
-"Euclidian Distance"	""
 "EvP1 Name"	""
 "EvP2 Name"	""
 "EvP3 Name"	""
@@ -1624,7 +1583,6 @@ TEXT	TRANSLATION
 "Exaggeration"	""
 "Exaggeration Factor"	""
 "Exaggeration Z"	""
-"Excess shear stress exponent"	""
 "Exclude No-Data Area"	""
 "Exclude NoData Cells"	""
 "Execute"	""
@@ -1645,14 +1603,18 @@ TEXT	TRANSLATION
 "Export ESRI Arc/Info Grid"	""
 "Export GPX"	""
 "Export GStat Shapes"	""
+"Export GeoTIFF"	""
 "Export Grid to KML"	""
 "Export Grid to XYZ"	""
 "Export Image (bmp, jpg, pcx, png, tif)"	""
 "Export LAS Files"	""
 "Export Point Cloud to Text File"	""
+"Export Raster"	""
 "Export Raster to PostGIS"	""
 "Export Scalable Vector Graphics (SVG) File"	""
+"Export Shapes"	""
 "Export Shapes to Generate"	""
+"Export Shapes to KML"	""
 "Export Shapes to PostGIS"	""
 "Export Shapes to XYZ"	""
 "Export Simple Features to Well Known Text"	""
@@ -1667,6 +1629,7 @@ TEXT	TRANSLATION
 "Export to File"	""
 "Expression"	""
 "Extended Neighourhood"	""
+"Extensions"	""
 "Extent"	""
 "Extent [Cut]"	""
 "Extent to CellSize"	""
@@ -1750,7 +1713,6 @@ TEXT	TRANSLATION
 "Filepath"	""
 "Files"	""
 "File|ESRI E00"	""
-"File|GDAL/OGR"	""
 "File|GPS Import"	""
 "File|Grid"	""
 "File|Reports"	""
@@ -1761,12 +1723,12 @@ TEXT	TRANSLATION
 "Fill Color"	""
 "Fill Color 1"	""
 "Fill Color 2"	""
-"Fill Gaps (Mean Value Cellular Automat)"	""
 "Fill Gaps in Records"	""
 "Fill Increment"	""
 "Fill NoData"	""
 "Fill Sinks"	""
 "Fill Sinks (Planchon/Darboux, 2001)"	""
+"Fill Sinks (QM of ESP)"	""
 "Fill Sinks (Wang & Liu)"	""
 "Fill Sinks XXL (Wang & Liu)"	""
 "Fill Style"	""
@@ -1836,18 +1798,13 @@ TEXT	TRANSLATION
 "Floating Point (4 byte)"	""
 "Floating Point (8 byte)"	""
 "Floating point"	""
-"Flood Depth"	""
-"Flood Height"	""
-"Flooded"	""
-"Flooded Surface"	""
 "Flooded digital elevation model"	""
-"Flooding Status"	""
-"Flooding_status"	""
 "Flow"	""
 "Flow Accumulation"	""
 "Flow Accumulation (Flow Tracing)"	""
 "Flow Accumulation (Mass-Flux Method)"	""
 "Flow Accumulation (Parallel)"	""
+"Flow Accumulation (QM of ESP)"	""
 "Flow Accumulation (Recursive)"	""
 "Flow Accumulation (Top-Down)"	""
 "Flow Accumulation (Trace)"	""
@@ -1877,8 +1834,6 @@ TEXT	TRANSLATION
 "Flow Width and Specific Catchment Area"	""
 "Flow at Gauges"	""
 "Flow threshold, given as amount of cells, above which flow transport is unlimited. Ignored if range equals zero."	""
-"Fluvial Transport"	""
-"Fluvial sediment transport coefficient Kf"	""
 "Flux"	""
 "Flux out of each cell, i.e. everything accumulated so far."	""
 "Flying Height"	""
@@ -1924,7 +1879,6 @@ TEXT	TRANSLATION
 "Fuel Model"	""
 "Full path to the directory for the output grids of each model step"	""
 "Function"	""
-"Function Calls > 0"	""
 "Function Fit"	""
 "Function Fitting Range"	""
 "Function Parameters"	""
@@ -1939,10 +1893,6 @@ TEXT	TRANSLATION
 "G"	""
 "GC, Ground cover expressed as a portion [between 0-1] of the soil surface protected by vegetation or crop cover on the ground"	""
 "GDAL/OGR"	""
-"GDAL: Export Raster"	""
-"GDAL: Export Raster to GeoTIFF"	""
-"GDAL: Import NetCDF"	""
-"GDAL: Import Raster"	""
 "GE / GR"	""
 "GE / V"	""
 "GE / X"	""
@@ -1954,7 +1904,6 @@ TEXT	TRANSLATION
 "GPX file"	""
 "GPX files (*.gpx)|*.gpx|All Files|*.*"	""
 "GPX to shapefile"	""
-"GRAD * MFD"	""
 "GREEN_BLUE"	""
 "GREEN_GREY_BLUE"	""
 "GREEN_RED_BLUE"	""
@@ -1980,7 +1929,6 @@ TEXT	TRANSLATION
 "Games"	""
 "Gamma"	""
 "Garden"	""
-"Garden|Dynamics"	""
 "Garden|Introducing Module Programming"	""
 "Garden|Recreations|Fractals"	""
 "Garden|Recreations|Games"	""
@@ -1993,7 +1941,6 @@ TEXT	TRANSLATION
 "Gaussian Landscapes"	""
 "Gaussian and Exponential Weighting Bandwidth"	""
 "Gc"	""
-"Geary's C"	""
 "General"	""
 "General Curvature"	""
 "General Settings"	""
@@ -2001,7 +1948,6 @@ TEXT	TRANSLATION
 "Generalized Surface"	""
 "Generate Shapes"	""
 "Generated Shapefile."	""
-"Generic"	""
 "Geo-Reference"	""
 "GeoTIFF (*.tif)"	""
 "GeoTIFF Files"	""
@@ -2021,7 +1967,6 @@ TEXT	TRANSLATION
 "Geoid"	""
 "Geometric Figures"	""
 "Geometry Type"	""
-"Geopotential Height"	""
 "Geoprocessing"	""
 "Georeferencing"	""
 "Get CRS Definition from..."	""
@@ -2037,10 +1982,6 @@ TEXT	TRANSLATION
 "Globe Viewer for Grids"	""
 "Gnomonic"	""
 "Gpx2shp path"	""
-"GraD"	""
-"Grad"	""
-"Grad Norm"	""
-"Grad_Poss"	""
 "Gradient"	""
 "Gradient Calculation"	""
 "Gradient Difference"	""
@@ -2051,7 +1992,7 @@ TEXT	TRANSLATION
 "Gradient Vectors from Directional Components"	""
 "Gradient Vectors from Surface"	""
 "Gradient threshold"	""
-"Gradient_Tangs"	""
+"Gradients"	""
 "Graduated"	""
 "Graduated Colors"	""
 "Graduated Colours"	""
@@ -2062,7 +2003,6 @@ TEXT	TRANSLATION
 "Green (TM 3)"	""
 "Green-Ampt Infiltration"	""
 "Greenness"	""
-"Grib Files (*.grb)"	""
 "Grid"	""
 "Grid 1"	""
 "Grid 2"	""
@@ -2104,7 +2044,6 @@ TEXT	TRANSLATION
 "Grid describing the AOI."	""
 "Grid describing the state of each cell at timestep t + 1."	""
 "Grid describing the state of each cell at timestep t."	""
-"Grid file could not be opened."	""
 "Grid file could not be saved."	""
 "Grid list"	""
 "Grid range"	""
@@ -2116,8 +2055,6 @@ TEXT	TRANSLATION
 "Grid to filter"	""
 "Grid to reclassify"	""
 "Grid value equals low value"	""
-"Grid with Gaps"	""
-"Grid with Gaps Filled"	""
 "Grid with category of nearest source cell [Category]"	""
 "Grid with euclidian distance to nearest source cell [grid units]"	""
 "Grid with features to be buffered [Category/NoData]"	""
@@ -2137,8 +2074,10 @@ TEXT	TRANSLATION
 "Grids with continuous data, statistics are calculated for each grid. Coding: NoData / continuous values."	""
 "Grid|Analysis"	""
 "Grid|Calculus"	""
+"Grid|Export"	""
 "Grid|Filter"	""
 "Grid|Gridding"	""
+"Grid|Import"	""
 "Grid|Tools"	""
 "Ground cover"	""
 "Group A"	""
@@ -2183,7 +2122,6 @@ TEXT	TRANSLATION
 "Hill Radius"	""
 "Hill-Climbing (Rubin 1967)"	""
 "Hillslope Index"	""
-"Hillslope_reservoir"	""
 "Histogram"	""
 "Histogram Stretch"	""
 "Histogram Stretch Dialog"	""
@@ -2194,8 +2132,7 @@ TEXT	TRANSLATION
 "Histogram cloud signature:"	""
 "History"	""
 "History Depth"	""
-"Hodge-Podge"	""
-"Hodge-Podge Machine"	""
+"Hofierka and Suri"	""
 "Hollow"	""
 "Homepage"	""
 "Homogenous"	""
@@ -2205,13 +2142,11 @@ TEXT	TRANSLATION
 "Horizontal Offset"	""
 "Horizontal Overland Flow Distance"	""
 "Horizontal Range"	""
-"Horizontal Tracer Density"	""
 "Horizontal hatch"	""
 "Horizontally mirrored"	""
 "Host"	""
 "Hourly Data"	""
 "How many trees to create?"	""
-"Html Extra Info"	""
 "Hull Construction"	""
 "Humedad del combustible herb�ceo vivo"	""
 "Humedad del combustible le�oso vivo"	""
@@ -2220,10 +2155,6 @@ TEXT	TRANSLATION
 "Humedad del combustible muerto en 100-horas"	""
 "Humification Factor"	""
 "Humus to Charcoal"	""
-"Hydro CA"	""
-"Hydro CA 2"	""
-"Hydro CA 3"	""
-"Hydro CA 4"	""
 "Hydrology"	""
 "Hydrology: IHACRES"	""
 "Hypsometric Curve"	""
@@ -2257,7 +2188,6 @@ TEXT	TRANSLATION
 "Ice"	""
 "Identifier"	""
 "Identity"	""
-"If Table exists..."	""
 "If checked the snow module is active"	""
 "If checked, it means there is no external inflow to the subbasin"	""
 "If checked, snow-melt module is used."	""
@@ -2313,8 +2243,6 @@ TEXT	TRANSLATION
 "Import Filter"	""
 "Import GPX"	""
 "Import GRIB2 record"	""
-"Import GSOD Stations to Data Base"	""
-"Import GSOD to Data Base"	""
 "Import GStat Shapes"	""
 "Import Grid from Table"	""
 "Import Grid from XYZ"	""
@@ -2325,12 +2253,15 @@ TEXT	TRANSLATION
 "Import NetCDF"	""
 "Import Point Cloud from Shape File"	""
 "Import Point Cloud from Text File"	""
+"Import Raster"	""
 "Import Raster from PostGIS"	""
 "Import SRTM30 DEM"	""
 "Import Scalable Vector Graphics (SVG) File"	""
+"Import Shapes"	""
 "Import Shapes from PostGIS"	""
 "Import Shapes from XYZ"	""
 "Import Simple Features from Well Known Text"	""
+"Import Single Raster Band from PostGIS"	""
 "Import Stereo Lithography File (STL)"	""
 "Import Surfer Blanking Files"	""
 "Import Surfer Grid"	""
@@ -2355,7 +2286,6 @@ TEXT	TRANSLATION
 "In this section you can define the topology of the neural network."	""
 "In/Out"	""
 "Include Center Cell"	""
-"Include Planetery Bending"	""
 "Include X Coordinate"	""
 "Include Y Coordinate"	""
 "Include a category for cloud shadows"	""
@@ -2374,7 +2304,6 @@ TEXT	TRANSLATION
 "Index"	""
 "Indicatrix"	""
 "Indices"	""
-"Infection Speed"	""
 "Infiltration excess runoff [m/dt]"	""
 "Infiltration rate [m/dt]"	""
 "Informe"	""
@@ -2386,24 +2315,19 @@ TEXT	TRANSLATION
 "Initial Number of Fishes [%]"	""
 "Initial Number of Sharks [%]"	""
 "Initial State"	""
-"Initial Surface"	""
 "Initial Threshold for Slope"	""
 "Initial root zone storage deficit [m]"	""
-"Initial sediment cover (m)"	""
-"Initial sediment cover thickness (m)"	""
 "Initial subsurface flow per unit area [m/h]"	""
 "Initial update value"	""
 "Initial value delta_0 of update-values delta_ij."	""
 "Initialisation"	""
 "Initialization Value"	""
-"Initialize"	""
 "Initializing ..."	""
 "Initializing Fields"	""
 "Initializing direction matrix..."	""
 "Initiation Grid"	""
 "Initiation Threshold"	""
 "Initiation Type"	""
-"Inlet Concentration"	""
 "Inner Buffer"	""
 "Input"	""
 "Input Binary Grid"	""
@@ -2527,10 +2451,10 @@ TEXT	TRANSLATION
 "K2"	""
 "K3"	""
 "KE"	""
-"KF Fluvial sediment transport coefficien"	""
 "KML files (*.kml)"	""
 "KML/KMZ File"	""
 "KML/KMZ Files"	""
+"KMZ Files"	""
 "Kappa"	""
 "Kappa Offset [degree]"	""
 "Kappa [degree]"	""
@@ -2560,7 +2484,6 @@ TEXT	TRANSLATION
 "LAS Info"	""
 "LAS header exception: %s"	""
 "LAS reader exception: %s"	""
-"LEM 2013-02-21"	""
 "LFAC("	""
 "LP, Saturated lateral permeability of the soil [m/day]"	""
 "LS"	""
@@ -2605,19 +2528,14 @@ TEXT	TRANSLATION
 "Landsat-5 TM"	""
 "Landsat-7 ETM+"	""
 "Landsat-8 OLI/TIRS"	""
-"Landscape Evolution"	""
-"Landscape Evolution Model"	""
-"Landscape Evolution Modelling"	""
 "Language Translations"	""
 "Laplace Filter"	""
 "Laplacian Filter"	""
 "Laplacian Filter Kernel"	""
 "Last Day"	""
-"Last RingeLEM"	""
 "Lat"	""
 "Lat. of True Scale"	""
 "Latitude"	""
-"Latitude (user defined reference)"	""
 "Latitude / Longitude Increment"	""
 "Latitude 1"	""
 "Latitude 2"	""
@@ -2626,8 +2544,6 @@ TEXT	TRANSLATION
 "Latitude Increment [Degree]"	""
 "Latitude Pole"	""
 "Latitude [Degree]"	""
-"Latitude [degree]"	""
-"Latitude relates to grid's..."	""
 "Latitude/Longitude Graticule"	""
 "Latitudinal Statistics"	""
 "Layer A"	""
@@ -2670,7 +2586,6 @@ TEXT	TRANSLATION
 "Level Heights"	""
 "Level of Detail"	""
 "Level of Generalisation"	""
-"Levels"	""
 "Library"	""
 "Life"	""
 "Life Cycle"	""
@@ -2708,6 +2623,7 @@ TEXT	TRANSLATION
 "Lines (extended)"	""
 "Lines and Points"	""
 "Lines with Property Attributes"	""
+"Linke Turbidity Coefficient"	""
 "List"	""
 "List ODBC Servers"	""
 "List PostgreSQL Connections"	""
@@ -2717,8 +2633,6 @@ TEXT	TRANSLATION
 "List of Measured Points as PC"	""
 "List of Shapes Layers"	""
 "Listing"	""
-"Lithology"	""
-"Lithology_of_uppermost_rock_layer"	""
 "Litter to Humus"	""
 "Litterfall Rate [g/m\xb2/a]"	""
 "Little Endian (Intel)"	""
@@ -2737,6 +2651,7 @@ TEXT	TRANSLATION
 "Load Tool Library"	""
 "Load all bands"	""
 "Load from File..."	""
+"Load from Workspace"	""
 "Load grid"	""
 "Load library"	""
 "Load point cloud"	""
@@ -2745,7 +2660,6 @@ TEXT	TRANSLATION
 "Load shapefile after conversion"	""
 "Load shapes"	""
 "Load table"	""
-"Load to Memory"	""
 "Load tool chain"	""
 "Loaded Grid"	""
 "Loaded Shapes"	""
@@ -2753,23 +2667,17 @@ TEXT	TRANSLATION
 "Loam"	""
 "Loamy Sand"	""
 "Local Cartesian"	""
-"Local Correlation"	""
 "Local Curvature"	""
 "Local Downslope Curvature"	""
-"Local Geary's C"	""
 "Local Maxima"	""
 "Local Minima"	""
 "Local Minima and Maxima"	""
-"Local Moran's I"	""
 "Local Ridges"	""
 "Local Ridges, Hills in Valleys"	""
 "Local Rotation Base Level"	""
 "Local Rotation [Degree]"	""
 "Local Sky View Factor"	""
-"Local Spatial Autocorrelation"	""
-"Local Time (user defined reference)"	""
 "Local Upslope Curvature"	""
-"Local time relates to grid's..."	""
 "Locate STRM30 Data File"	""
 "Locate..."	""
 "Location"	""
@@ -2792,7 +2700,6 @@ TEXT	TRANSLATION
 "Longitude 2"	""
 "Longitude 3"	""
 "Longitude Pole"	""
-"Longitude [degree]"	""
 "Longitudinal Curvature"	""
 "Longitudinal Grid Statistics"	""
 "Longitudinal Profile"	""
@@ -2831,7 +2738,6 @@ TEXT	TRANSLATION
 "MDE"	""
 "MEAN"	""
 "MFD"	""
-"MFD * Gradient"	""
 "MIN"	""
 "MINIMUM"	""
 "MLRA Coefficients"	""
@@ -2840,13 +2746,13 @@ TEXT	TRANSLATION
 "MMF-SAGA Soil Erosion Model"	""
 "MOLA Grids (*.img)|*.img|All Files|*.*"	""
 "MORAN_I"	""
-"MPM"	""
 "MRRTF"	""
 "MRVBF"	""
 "MS Windows Bitmap (*.bmp)|*.bmp|All Files|*.*"	""
 "MS, Soil moisture at field capacity [% w/w]"	""
 "MSL Height [m]"	""
 "Maehweide"	""
+"Magnitude"	""
 "Mahalanobis Distance"	""
 "Main"	""
 "Main Basin ID"	""
@@ -2910,7 +2816,6 @@ TEXT	TRANSLATION
 "Maximum"	""
 "Maximum Angle"	""
 "Maximum Cells (C Correction Analysis)"	""
-"Maximum Change"	""
 "Maximum Contour Value"	""
 "Maximum Curvature"	""
 "Maximum Deviation between estimated excess rainfall and observed streamflow volumes"	""
@@ -2937,7 +2842,6 @@ TEXT	TRANSLATION
 "Maximum Selection"	""
 "Maximum Sum of overestimated ExcessRain to total ExcessRain in [%]"	""
 "Maximum Temperature"	""
-"Maximum Thickness"	""
 "Maximum Time Span (Seconds)"	""
 "Maximum Total Order"	""
 "Maximum Value"	""
@@ -2971,7 +2875,6 @@ TEXT	TRANSLATION
 "Mean Temperature"	""
 "Mean Value"	""
 "Mean Value (cell area weighted)"	""
-"Mean annual flow per unit area (m/s for MPM)"	""
 "Mean less Standard Deviation"	""
 "Mean over Catchment"	""
 "Mean plus Standard Deviation"	""
@@ -2979,7 +2882,6 @@ TEXT	TRANSLATION
 "Mean saturation deficit (in watershed) [m]"	""
 "Mean soil loss"	""
 "Mean temperature"	""
-"Mean_elevation"	""
 "Measure Distance"	""
 "Measured Points (PC)"	""
 "Median"	""
@@ -3041,15 +2943,14 @@ TEXT	TRANSLATION
 "Minimum Distance"	""
 "Minimum Distance Analysis"	""
 "Minimum Exaggeration [%]"	""
-"Minimum Gradient"	""
 "Minimum Height"	""
 "Minimum Magnitude"	""
 "Minimum Nash-Sutcliffe Efficiency"	""
 "Minimum Nash-Sutcliffe Efficiency required to print simulation to calibration table"	""
+"Minimum Neighbours"	""
 "Minimum Node Split Size"	""
 "Minimum Number of Dark Object Cells"	""
 "Minimum Number of Points"	""
-"Minimum Pressure Level [mb]"	""
 "Minimum Probability"	""
 "Minimum Redundancy Feature Selection"	""
 "Minimum Resolution (Degree)"	""
@@ -3058,18 +2959,15 @@ TEXT	TRANSLATION
 "Minimum Slope"	""
 "Minimum Slope [Degree]"	""
 "Minimum Standard Deviation"	""
-"Minimum Step Size"	""
 "Minimum Temperature"	""
-"Minimum Thickness"	""
 "Minimum Threshold"	""
-"Minimum Time Step [a]"	""
-"Minimum Time Step [years]"	""
 "Minimum Value"	""
 "Minimum and maximum of attribute range []."	""
 "Minimum and maximum x-coordinate of AOI."	""
 "Minimum and maximum y-coordinate of AOI."	""
 "Minimum magnitude as percentile."	""
 "Minimum number of cells in a group of adjacent cells."	""
+"Minimum number of neighbouring potential edge cells with similar direction."	""
 "Minimum of Darkness DN Cells"	""
 "Minimum pixels to consider digital number as dark object"	""
 "Minimum probability to accept a classification result for a cell."	""
@@ -3077,7 +2975,6 @@ TEXT	TRANSLATION
 "Minimum size"	""
 "Minimum size of basin (cells)"	""
 "Minimum slope gradient to preserve from cell to cell; with a value of zero sinks are filled up to the spill elevation (which results in flat areas). Unit [Degree]"	""
-"Minimum sub-time step size (yrs)"	""
 "Minimum value of the range to be reclassified."	""
 "Minimum/Maximum"	""
 "Minimun"	""
@@ -3102,7 +2999,6 @@ TEXT	TRANSLATION
 "Model parameter [m]"	""
 "Model parameters"	""
 "Model step %d/%d ..."	""
-"Modelled DEM"	""
 "Modelled Elevation"	""
 "Modelling erosion processes."	""
 "Modelling hydrological processes."	""
@@ -3122,8 +3018,6 @@ TEXT	TRANSLATION
 "Monthly Global by Latitude"	""
 "Moore"	""
 "Moore & Nieber 1989"	""
-"Moore (8)"	""
-"Moore Contiguity"	""
 "Moore et al. 1991"	""
 "Moran's I"	""
 "Morphological Filter"	""
@@ -3164,7 +3058,6 @@ TEXT	TRANSLATION
 "Multiple Maximum Downslope Gradient Based Flow Directon"	""
 "Multiple Observer"	""
 "Multiple R-squared"	""
-"Multiple Regression Analysis"	""
 "Multiple Regression Analysis (Grid and Predictor Grids)"	""
 "Multiple Regression Analysis (Points and Predictor Grids)"	""
 "Multiple Triangular Flow Directon"	""
@@ -3180,9 +3073,6 @@ TEXT	TRANSLATION
 "MySQL Data"	""
 "My_Module Module Sub Menu"	""
 "NAME"	""
-"NBR_X"	""
-"NBR_Y"	""
-"NCAR Climate Import"	""
 "NCELLS"	""
 "NCache einlesen"	""
 "NEIGHBORS"	""
@@ -3220,12 +3110,10 @@ TEXT	TRANSLATION
 "Neighborhood"	""
 "Neighborhood Type"	""
 "Neighbourhood"	""
-"Neighbourhood (Radius)"	""
 "Net Primary Production [Gt Carbon / a]"	""
 "NetCDF Files (*.nc)"	""
 "Network topology"	""
 "Neumann"	""
-"Neumann Contiguity"	""
 "Neumann: the four horizontally and vertically neighboured cells; Moore: all eight adjacent cells"	""
 "Neural Networks (OpenCV)"	""
 "New"	""
@@ -3262,16 +3150,17 @@ TEXT	TRANSLATION
 "No Sinks"	""
 "No attribute fields selected!"	""
 "No attribute fields specified!"	""
+"No compatible table has been found."	""
 "No data"	""
 "No data loaded."	""
 "No description available"	""
 "No duplicates found."	""
-"No grid in list"	""
 "No objects"	""
 "No parameters available."	""
 "No path for output files specified!"	""
 "No pen is used"	""
 "No projects in directory"	""
+"No raster files have been found in directory."	""
 "No shapes in selection"	""
 "No sinks have been detected."	""
 "No translation set by user"	""
@@ -3304,14 +3193,12 @@ TEXT	TRANSLATION
 "North|South|"	""
 "Not Named"	""
 "Not Null"	""
-"Not a valid PostGIS database!"	""
 "Nothing to do be done. Raster splitting is not supported."	""
 "Nothing to do! Merging needs more than one input data set."	""
 "Nothing to do. Raster is already within target range."	""
 "Nothing to do: there is no intersection with additonal grid."	""
 "November"	""
 "No|Yes|"	""
-"Number Of Shapes"	""
 "Number in Latitudinal Direction"	""
 "Number in Meridional Direction"	""
 "Number of Attributes"	""
@@ -3336,7 +3223,6 @@ TEXT	TRANSLATION
 "Number of Fields"	""
 "Number of Grid Cells"	""
 "Number of Grids"	""
-"Number of Infection States"	""
 "Number of Intervals"	""
 "Number of Iterations"	""
 "Number of Iterations for Normal Updating"	""
@@ -3352,6 +3238,7 @@ TEXT	TRANSLATION
 "Number of Row Cells"	""
 "Number of Rows"	""
 "Number of Sectors"	""
+"Number of Shapes"	""
 "Number of Simulations"	""
 "Number of Simulations for Calibration"	""
 "Number of Steps"	""
@@ -3381,6 +3268,7 @@ TEXT	TRANSLATION
 "Number of points on each side of the section"	""
 "Number of points per return:"	""
 "Number of raindays is greater than model timespan!"	""
+"Number of raster files found in directory"	""
 "Number of sub-basins"	""
 "Number of the last x Iteration to be plotted."	""
 "Number of vertical tiles"	""
@@ -3392,7 +3280,6 @@ TEXT	TRANSLATION
 "Numerical Precision"	""
 "O. Conrad (c) 2009"	""
 "O. Conrad (c) 2011"	""
-"O.C.'s Tests"	""
 "O.Conrad (c) 2010"	""
 "O.Conrad (c) 2011"	""
 "O.Conrad (c) 2013"	""
@@ -3403,9 +3290,6 @@ TEXT	TRANSLATION
 "ODBC source connected"	""
 "ODBC source disconnected"	""
 "ODBC/OTL"	""
-"OGR: Export Shapes to KML"	""
-"OGR: Export Vector Data"	""
-"OGR: Import Vector Data"	""
 "OID"	""
 "OSM Areas"	""
 "OSM Locations"	""
@@ -3415,7 +3299,6 @@ TEXT	TRANSLATION
 "OUTPUT certainty"	""
 "OUTPUT classes"	""
 "Object Grid"	""
-"Object Update"	""
 "Objective Function"	""
 "Objects removed from input grid"	""
 "Oblique Mercator"	""
@@ -3445,15 +3328,15 @@ TEXT	TRANSLATION
 "Only Header Info"	""
 "Only List Connected Servers"	""
 "Only Process Gaps with Less Cells"	""
-"Only Show Selection"	""
 "Only Z-Direction Position is Updated"	""
 "Opaque"	""
 "Open"	""
 "Open Database Connection"	""
 "Open Project"	""
 "Open Slopes"	""
+"Open as data set"	""
+"Open with external application"	""
 "OpenCV"	""
-"OpenMP: Slope, Aspect"	""
 "Opening"	""
 "Openness"	""
 "Operation"	""
@@ -3461,7 +3344,6 @@ TEXT	TRANSLATION
 "Operator Type"	""
 "Operator scale"	""
 "Opposite Neighbours"	""
-"Optimised"	""
 "Optional Output Filepath"	""
 "Optional Target Grids"	""
 "Optional Tile Info Filename"	""
@@ -3473,7 +3355,6 @@ TEXT	TRANSLATION
 "Order"	""
 "Order by"	""
 "Order by..."	""
-"Order of Polynomial Function"	""
 "Ordered Weighted Averaging (OWA)"	""
 "Ordern in den alle Ausgabedaten gespeichert werden sollen"	""
 "Ordinary Kriging"	""
@@ -3485,18 +3366,13 @@ TEXT	TRANSLATION
 "Origin Latitude"	""
 "Original"	""
 "Original Channels"	""
-"Original DEM"	""
-"Original Grid"	""
 "Original Image"	""
-"Original River Elevations"	""
 "Orographic Coefficient"	""
 "Orthoclinal slope"	""
 "Orthodromes"	""
 "Orthographic"	""
 "Ouput"	""
-"Outflow"	""
 "Outlet"	""
-"Outlet Concentration"	""
 "Outlet Hydrographs"	""
 "Outlet X"	""
 "Outlet Y"	""
@@ -3510,8 +3386,6 @@ TEXT	TRANSLATION
 "Output Filepath"	""
 "Output Format"	""
 "Output Grid"	""
-"Output Grid Down"	""
-"Output Grid Up"	""
 "Output Lod"	""
 "Output Seeds"	""
 "Output Text File"	""
@@ -3524,20 +3398,17 @@ TEXT	TRANSLATION
 "Output file path"	""
 "Output format"	""
 "Output grid"	""
-"Output interval"	""
-"Output interval (time steps)"	""
 "Output of Change Vector"	""
-"Output of Grids"	""
-"Output of Level Data"	""
+"Output of Gradients"	""
 "Output of Model Parameters"	""
 "Output of Regression Parameters"	""
-"Output of Trend Data"	""
 "Output of module calculations."	""
 "Output of..."	""
 "Output parameters"	""
 "Output shapes with field(s) deleted"	""
 "Output table with field(s) deleted"	""
 "Output will inherit shape type and table structure from the first layer in this list."	""
+"Overall Accuracy"	""
 "Overall Bounding Box:"	""
 "Overdip slope"	""
 "Overland"	""
@@ -3551,8 +3422,8 @@ TEXT	TRANSLATION
 "Overlay Image"	""
 "Override"	""
 "Overview"	""
+"Overview Content"	""
 "Overwrite"	""
-"P"	""
 "P/A"	""
 "P/sqrt(A)"	""
 "PATB"	""
@@ -3584,7 +3455,6 @@ TEXT	TRANSLATION
 "Panchromatic Channel Matching"	""
 "Panorama"	""
 "Panorama Break [%]"	""
-"Paolo"	""
 "Paper Format"	""
 "Parallelepiped"	""
 "Parameter"	""
@@ -3664,15 +3534,11 @@ TEXT	TRANSLATION
 "Planar"	""
 "Plane"	""
 "Plane (%.2fDegree)"	""
-"Planetary Bending"	""
-"Planetary Radius"	""
 "Plant Height"	""
 "Platform"	""
-"Play And Save As Images..."	""
+"Play And Save as Images..."	""
 "Play Loop [Ctrl + L]"	""
-"Play Loop [L]"	""
 "Play Once [Ctrl + P]"	""
-"Play Once [P]"	""
 "Play and Save to Image"	""
 "Please choose a method of module operation."	""
 "Please enter a numeric value:"	""
@@ -3712,7 +3578,6 @@ TEXT	TRANSLATION
 "Point Cloud to Shapes"	""
 "Point Cloud to drop attribute from."	""
 "Point Cloud to reclassify/extract"	""
-"Point Cloud with attribute dropped."	""
 "Point Clouds"	""
 "Point Clouds Viewer"	""
 "Point Data Record Format"	""
@@ -3724,6 +3589,8 @@ TEXT	TRANSLATION
 "Point Size: Scaling"	""
 "Point Statistics for Polygons"	""
 "Point View Settings"	""
+"Point cloud to drop attribute(s) from."	""
+"Point cloud with attribute(s) dropped."	""
 "Point clouds viewer."	""
 "Point insertion distance [map units]."	""
 "Point shapefile with source point(s)"	""
@@ -3780,17 +3647,19 @@ TEXT	TRANSLATION
 "Positive values result in a shift in N direction."	""
 "Possible error"	""
 "PostGIS"	""
+"PostGIS extension added"	""
+"PostGIS extension missing or too old"	""
 "PostgreSQL"	""
 "PostgreSQL Connections"	""
 "PostgreSQL Database Connection Error"	""
 "PostgreSQL Sources"	""
+"PostgreSQL database is already connected"	""
 "PostgreSQL source connected"	""
 "PostgreSQL source disconnected"	""
 "PostgreSQL source is already connected"	""
 "Potential Evapotranspiration"	""
 "Potential Incoming Solar Radiation"	""
 "Power"	""
-"Power (Distance Weighting)"	""
 "Power on soil (p)"	""
 "Power on soil (p) [lower bound]"	""
 "Power on soil (p) [upper bound]"	""
@@ -3805,7 +3674,6 @@ TEXT	TRANSLATION
 "Precipitation Column"	""
 "Precipitation [m / dt]"	""
 "Precipitation [mm]"	""
-"Precipition Quantitiy [mm]"	""
 "Precise Datum Conversion"	""
 "Precise Tracing"	""
 "Precisions"	""
@@ -3821,7 +3689,6 @@ TEXT	TRANSLATION
 "Predictors"	""
 "Preferred Routing"	""
 "Preferred Target Grid Type"	""
-"Preferred data storage type"	""
 "Preliminary scene analysis:"	""
 "Preprocessed DEM"	""
 "Preprocessed DEM. If this is not set changes will be stored in the original DEM grid."	""
@@ -3869,7 +3736,6 @@ TEXT	TRANSLATION
 "Processing observer %d ..."	""
 "Product"	""
 "Production"	""
-"Production Rates [m/h]"	""
 "Profile"	""
 "Profile (lines)"	""
 "Profile (points)"	""
@@ -3935,6 +3801,7 @@ TEXT	TRANSLATION
 "Quadric: a + b * x + c * x^2"	""
 "Quality"	""
 "Quality Measure"	""
+"Quality assessment is not calculated, because the number of classes in the input grids differ."	""
 "Quantile"	""
 "Queen"	""
 "Queen's case"	""
@@ -3982,7 +3849,6 @@ TEXT	TRANSLATION
 "RED_GREEN_BLUE"	""
 "RED_GREY_BLUE"	""
 "RED_GREY_GREEN"	""
-"REMO Level Interpolation"	""
 "RESIDUAL"	""
 "RGB"	""
 "RGB Coded Values"	""
@@ -4026,6 +3892,11 @@ TEXT	TRANSLATION
 "Rank"	""
 "Rank Filter"	""
 "Rank [Percent]"	""
+"Raster Band Deletion"	""
+"Raster Band Identifier"	""
+"Raster Catalogue"	""
+"Raster Catalogue (unknown CRS)"	""
+"Raster Catalogues"	""
 "Raster Dimension"	""
 "Raster Resolution (Pixel Size)"	""
 "Raster Resolution (Pixels Size)"	""
@@ -4054,7 +3925,6 @@ TEXT	TRANSLATION
 "Reclassify|Extract Subset|"	""
 "Recognised Files"	""
 "Reconstruction result"	""
-"Records"	""
 "Rectangles"	""
 "Rectify Grid"	""
 "Red"	""
@@ -4071,9 +3941,6 @@ TEXT	TRANSLATION
 "Reflectance"	""
 "Refresh"	""
 "Region of Interest"	""
-"Regolith Smoothing"	""
-"Regolith Thickness"	""
-"Regolith_cover_thickness"	""
 "Regression"	""
 "Regression Analysis"	""
 "Regression Analysis (Points and Predictor Grid)"	""
@@ -4096,15 +3963,14 @@ TEXT	TRANSLATION
 "Relative Area"	""
 "Relative Height"	""
 "Relative Heights and Slope Positions"	""
-"Relative Relief Position"	""
 "Relative Richness"	""
 "Relative Slope Position"	""
 "Relative from cell value"	""
 "Relative heights calculation..."	""
-"Relative position"	""
 "Relaxation"	""
 "Reload"	""
 "Reload tool chain"	""
+"Remove"	""
 "Remove Border Regions?"	""
 "Remove Duplicate Points"	""
 "Remove Overlap from Virtual Point Cloud Tiles"	""
@@ -4114,7 +3980,10 @@ TEXT	TRANSLATION
 "Removing ambiguous pixels..."	""
 "Rename"	""
 "Rename Fields"	""
+"Rename Raster Band"	""
 "Rename Table"	""
+"Reopen Database Connections"	""
+"Reopen PostgreSQL database connections. Warning: if set to true account information including unencrypted paswords for automatic connection will be stored."	""
 "Replace Condition"	""
 "Replace Text"	""
 "Replace first PC with PAN"	""
@@ -4132,7 +4001,6 @@ TEXT	TRANSLATION
 "Rescale to 0 - 1"	""
 "Rescale to 0 - 1.0"	""
 "Resection (Terrestrial)"	""
-"Reset Regolith"	""
 "Residual Analysis (Grid)"	""
 "Residual Corrected Regression"	""
 "Residual Correction"	""
@@ -4167,20 +4035,15 @@ TEXT	TRANSLATION
 "Rill/Interrill Erosivity"	""
 "RivFlow"	""
 "RivFlow."	""
-"River Flooding (Mean Value Cellular Automat)"	""
-"River Flow Terraces"	""
-"River Flow Terraces Elevations"	""
 "River Heads"	""
 "River Mouths"	""
-"River Pixels"	""
 "Rn, number of rain days in timespan [-]"	""
 "Road Width"	""
-"Rock Layers"	""
 "Roll Left [F4]"	""
 "Roll Right[F3]"	""
 "Rook"	""
 "Rook's case"	""
-"Rooke"	""
+"Rooke's case"	""
 "Roots"	""
 "Roots to Humus"	""
 "Rotate"	""
@@ -4201,17 +4064,14 @@ TEXT	TRANSLATION
 "Routing Error"	""
 "Row Order"	""
 "Rows"	""
+"Run Once"	""
 "Run Tool"	""
-"Run duration"	""
 "Running Average"	""
 "Running Script"	""
 "Runoff"	""
-"S Model"	""
-"S u m"	""
 "S, slope [rad]"	""
 "SAFETYFACTOR"	""
 "SAGA Colors"	""
-"SAGA GUI Tool Menus"	""
 "SAGA Grid Files (*.sgrd)|*.sgrd|All Files|*.*"	""
 "SAGA Help"	""
 "SAGA Parameter Files"	""
@@ -4230,7 +4090,6 @@ TEXT	TRANSLATION
 "SAGA Wetness Index"	""
 "SAGA: Print Map"	""
 "SAGA\nSystem for Automated Geoscientific Analyses\nVersion 2.0"	""
-"SALEM"	""
 "SECTIONS"	""
 "SHALSTAB"	""
 "SIZE"	""
@@ -4260,8 +4119,6 @@ TEXT	TRANSLATION
 "SVM Classification"	""
 "SVM Type"	""
 "SVR Epsilon"	""
-"S_Model"	""
-"S_Z_Model"	""
 "Saddle"	""
 "Sample Variogram"	""
 "Sample from training population with or without replacement?"	""
@@ -4279,12 +4136,8 @@ TEXT	TRANSLATION
 "Saturation overland flow [m/dt]"	""
 "Saturation zone (WI > 1)"	""
 "Save"	""
-"Save All"	""
 "Save As Image"	""
-"Save As Image to Workspace"	""
-"Save As Image when changed"	""
-"Save As Image..."	""
-"Save As..."	""
+"Save Attributes as..."	""
 "Save Colors"	""
 "Save Configuration"	""
 "Save Georeference"	""
@@ -4296,12 +4149,13 @@ TEXT	TRANSLATION
 "Save History as Model"	""
 "Save KML file"	""
 "Save Map as Image..."	""
+"Save Map to KMZ"	""
 "Save Modified Data"	""
 "Save Parameters"	""
 "Save Point"	""
 "Save Point Cloud"	""
 "Save Project"	""
-"Save Project As..."	""
+"Save Project as..."	""
 "Save Settings"	""
 "Save Shapes"	""
 "Save Statistics to File..."	""
@@ -4312,7 +4166,12 @@ TEXT	TRANSLATION
 "Save Tiles to Disk"	""
 "Save To Memory Grid"	""
 "Save all"	""
+"Save as Image to Workspace"	""
+"Save as Image when changed"	""
+"Save as Image..."	""
+"Save as KMZ..."	""
 "Save as Tool Chain"	""
+"Save as..."	""
 "Save changes?"	""
 "Save grid"	""
 "Save point cloud"	""
@@ -4320,10 +4179,12 @@ TEXT	TRANSLATION
 "Save table"	""
 "Save tiles to disk individually"	""
 "Save to Clipboard"	""
+"Save to Database..."	""
 "Save to File"	""
 "Save to File..."	""
 "Save to Path"	""
 "Save to Script File"	""
+"Save to Workspace"	""
 "Scalable Vector Graphics Files (*.svg)"	""
 "Scale"	""
 "Scale (Cells)"	""
@@ -4354,14 +4215,12 @@ TEXT	TRANSLATION
 "Search Mode"	""
 "Search Options"	""
 "Search Radius"	""
-"Search Radius (Cells)"	""
 "Search Range"	""
 "Search Result"	""
 "Search Shape"	""
 "Search chip size set to %d"	""
 "Search distance given as number cells."	""
 "Search for Projects"	""
-"Search for Projects..."	""
 "Search for..."	""
 "Search radius of kernel in cells."	""
 "Search text not found"	""
@@ -4370,26 +4229,20 @@ TEXT	TRANSLATION
 "Secondary Name"	""
 "Section"	""
 "Sections"	""
-"Sed_thickness_a"	""
-"Sed_thickness_b"	""
 "Sediment Balance"	""
 "Sediment Balance Clay"	""
 "Sediment Balance Sand"	""
 "Sediment Balance Silt"	""
-"Sediment Influx from Upstream"	""
 "Sediment Limited [%d], Transport Limited (SL = TC) [%d], Transport Limited (SL = G) [%d]"	""
 "Sediment Yield Delivery Ratio"	""
-"Sediment_infux_from_upstream"	""
 "Seed Generation"	""
 "Seed Points"	""
 "Seed Type"	""
 "Seed Value"	""
 "Seeded Region Growing"	""
 "Seeds"	""
-"Seeds (Mask)"	""
 "Seeds Grid"	""
 "Seeds Only"	""
-"Segment Connection"	""
 "Segment ID"	""
 "Segmentation"	""
 "Segments"	""
@@ -4502,7 +4355,9 @@ TEXT	TRANSLATION
 "Shapes to TIN"	""
 "Shapes to project"	""
 "Shapes with Text Replacements"	""
+"Shapes|Export"	""
 "Shapes|Grid"	""
+"Shapes|Import"	""
 "Shapes|Lines"	""
 "Shapes|Lines|Transects"	""
 "Shapes|Point Clouds"	""
@@ -4534,6 +4389,7 @@ TEXT	TRANSLATION
 "Show Categories"	""
 "Show Cell Values"	""
 "Show Centroid"	""
+"Show Data File Sources"	""
 "Show Data Source Window"	""
 "Show Edges"	""
 "Show Filled"	""
@@ -4553,11 +4409,13 @@ TEXT	TRANSLATION
 "Show Results"	""
 "Show Scale"	""
 "Show Scale Bar"	""
+"Show Selection"	""
 "Show Toolbar"	""
 "Show Vertical Legend"	""
 "Show Vertices"	""
 "Show a Composite"	""
 "Show at all scales"	""
+"Show data sources tab for file system. Disabling might speed up start-up. Changes take effect after restart."	""
 "Shrink"	""
 "Shrink and Expand"	""
 "Shrinking"	""
@@ -4608,7 +4466,6 @@ TEXT	TRANSLATION
 "Single Value Decomposition (OpenCV)"	""
 "Single value"	""
 "Sink Drainage Route Detection"	""
-"Sink Fill Algorithm"	""
 "Sink Removal"	""
 "Sink Route"	""
 "Sink Routes"	""
@@ -4649,8 +4506,6 @@ TEXT	TRANSLATION
 "Slope Tolerance"	""
 "Slope Units"	""
 "Slope Weighting"	""
-"Slope exponent Nb for bedrock channel erosion"	""
-"Slope exponent Nf for fluvial sediment transport"	""
 "Slope gradient to left neighbour [%%]"	""
 "Slope gradient to left neighbour [Degree]"	""
 "Slope grid, in radians."	""
@@ -4658,16 +4513,11 @@ TEXT	TRANSLATION
 "Slope threshold, given as degree, above which flow transport is unlimited."	""
 "Slope tolerance that defines a 'flat' surface (degrees)"	""
 "Slope, Aspect, Curvature"	""
-"Slope_failure_locations"	""
 "Slopes"	""
 "Smith"	""
 "Smooth"	""
-"Smooth River Flow Terraces"	""
 "Smoothed Lines"	""
-"Smoothed River Elevations"	""
-"Smoothing"	""
 "Smoothing (ViGrA)"	""
-"Smoothing Threshold"	""
 "Snap Distance"	""
 "Snap Features"	""
 "Snap Points to Grid"	""
@@ -4679,20 +4529,14 @@ TEXT	TRANSLATION
 "Soil"	""
 "Soil Adjusted Vegetation Index"	""
 "Soil Adjustment Factor"	""
-"Soil Depth"	""
-"Soil Depth Right"	""
-"Soil Friction Coefficient"	""
 "Soil Moisture"	""
 "Soil Moisture Content"	""
 "Soil Moisture Deficit"	""
 "Soil Moisture Power Eq."	""
 "Soil Nitrogen"	""
-"Soil Parameter"	""
 "Soil Texture"	""
 "Soil Texture Classification"	""
 "Soil Texture Classification for Tables"	""
-"Soil Thickness"	""
-"Soil Things"	""
 "Soil Water"	""
 "Soil moisture (at FC)"	""
 "Soil moisture index (l)"	""
@@ -4715,7 +4559,6 @@ TEXT	TRANSLATION
 "Sommergerste"	""
 "Sort"	""
 "Sort Fields"	""
-"Sort Selection to Top"	""
 "Sort Table"	""
 "Sort first by"	""
 "Sort second by"	""
@@ -4802,17 +4645,13 @@ TEXT	TRANSLATION
 "Standardised Grid"	""
 "Standardize"	""
 "Standardized Height"	""
-"Start"	""
 "Start Degree"	""
 "Start Latitude"	""
 "Start Longitude"	""
 "Start Size"	""
-"Start Time"	""
 "Start Value"	""
 "Start Values"	""
-"Start [a BP]"	""
 "Start [ka]"	""
-"Start [years BP]"	""
 "Starting flood fill..."	""
 "Startup Project"	""
 "State t"	""
@@ -4825,30 +4664,20 @@ TEXT	TRANSLATION
 "Steepened escarpment"	""
 "Steepest gradient (first version)"	""
 "Steepest gradient (second version)"	""
-"Steepest_slope"	""
 "Stems"	""
 "Stems to Litter"	""
 "Step"	""
-"Step 1: Surface Gradient"	""
 "Step 1: low-pass of stripe"	""
-"Step 2: Concentration"	""
 "Step 2: low-pass between stripe and its surruondings"	""
-"Step [a]"	""
 "Step [ka]"	""
-"Step [years]"	""
 "Steps"	""
-"Steps 1+2: Surface, Gradient, Concentration"	""
 "Steps to Next"	""
 "Stepwidth"	""
 "Stereo Anaglyph"	""
 "Stereo Eye Distance [Degree]"	""
 "Stereo Match (OpenCV)"	""
 "Stereographic"	""
-"Stop"	""
-"Stop [a BP]"	""
-"Stop [h]"	""
 "Stop [ka]"	""
-"Stop [years BP]"	""
 "Stop at Edge"	""
 "Stop on Error"	""
 "Storage"	""
@@ -4859,7 +4688,6 @@ TEXT	TRANSLATION
 "Stratification"	""
 "Stream Order"	""
 "Stream Power Index"	""
-"Stream_channel_length_between_cells"	""
 "Streamflow (obs.) Column"	""
 "Streamflow Column"	""
 "Streams"	""
@@ -4892,6 +4720,7 @@ TEXT	TRANSLATION
 "Summary_"	""
 "Sun's height above horizon in degree"	""
 "Sunrise"	""
+"Sunrise and Sunset"	""
 "Suns's Height"	""
 "Sunset"	""
 "Supervised Classification for Grids"	""
@@ -4900,11 +4729,8 @@ TEXT	TRANSLATION
 "Support Vector Machine"	""
 "Suppress Negative Flow Accumulation Values"	""
 "Surface"	""
-"Surface Approximation Threshold"	""
 "Surface Area"	""
-"Surface Elevation"	""
 "Surface Specific Points"	""
-"Surface Water [m]"	""
 "Surface hydraulic conductivity [m/h]"	""
 "Surface roughness"	""
 "Surface used to derive the LDD network, e.g. a DTM."	""
@@ -4912,7 +4738,6 @@ TEXT	TRANSLATION
 "Surfer Blanking Files (*.bln)|*.bln|All Files|*.*"	""
 "Surfer Grid (*.grd)|*.grd|All Files|*.*"	""
 "Surfer's No Data Value"	""
-"Surrounding Air Temperature [�C]"	""
 "Swath Profile"	""
 "Swath Width"	""
 "Swath width measured in map units."	""
@@ -4927,15 +4752,9 @@ TEXT	TRANSLATION
 "Synchronize Map Extents"	""
 "Syntax error at position #%d: \n%s\n"	""
 "Synthesized Grid"	""
-"T"	""
 "T Curvature"	""
-"T Height Correction"	""
-"T Offset"	""
 "T Slope"	""
 "T Vertical Distance to Channel Network"	""
-"T [ka BP]"	""
-"T max"	""
-"T min"	""
 "T, mean temperature [degree C]"	""
 "TCI Low"	""
 "TCc"	""
@@ -5013,7 +4832,6 @@ TEXT	TRANSLATION
 "Target X coordinate"	""
 "Target Y coordinate"	""
 "Tasseled Cap Transformation"	""
-"Temperatur offset"	""
 "Temperature"	""
 "Temperature (2pm) [DegreeC]"	""
 "Temperature Column"	""
@@ -5029,12 +4847,8 @@ TEXT	TRANSLATION
 "Temperature Threshold for Rainfall (lower bound)"	""
 "Temperature Threshold for Rainfall (upper bound)"	""
 "Temperature at Reference Station [Deg.Celsius]"	""
-"Temperature from Pressure Levels to Surface"	""
-"Template"	""
 "Template Menu|Template Sub Menu"	""
-"Template."	""
 "Templates"	""
-"Template|Template"	""
 "Temporary files"	""
 "Tension Threshold"	""
 "Tension Threshold [Percentage of Cell Size]"	""
@@ -5086,6 +4900,7 @@ TEXT	TRANSLATION
 "The attribute field with the x-coordinate."	""
 "The attribute field with the y-coordinate."	""
 "The attribute field with the z-coordinate."	""
+"The attribute field(s) to drop."	""
 "The attribute fields to cluster"	""
 "The attribute fields to convert, optional."	""
 "The attribute with the class IDs, used to link the table and the grid."	""
@@ -5139,7 +4954,6 @@ TEXT	TRANSLATION
 "The number of smoothing iterations [-]."	""
 "The number of supplied grids exceeds the number of variables in formula."	""
 "The number of supplied grids is less than the number of variables in formula."	""
-"The numbers (starting from 1) of the fields to drop, separated by semicolon, e.g. \"5;8;9\""	""
 "The numbers (starting from 1) of the fields to export, separated by semicolon, e.g. \"1;2;3;5\""	""
 "The numbers (starting from 1) of the fields to import, separated by semicolon, e.g. \"5;6;8\""	""
 "The output grid(s)"	""
@@ -5160,11 +4974,13 @@ TEXT	TRANSLATION
 "The shapefile to use for clipping."	""
 "The smoothed output line shapefile."	""
 "The smoothing preservation factor [-]."	""
+"The start value to use for the identifier."	""
 "The table with the (numeric) data values for each class. The module creates a grid for each table column (besides the ID)."	""
 "The terrain exaggeration factor allows to increase the shading contrasts in flat areas."	""
 "The transmittance of the atmosphere, usually between 60 and 80 percent."	""
 "The transparency of the shade [%]"	""
 "The unobstructed hemisphere given as percentage."	""
+"The value for the option '%s' must be specified."	""
 "The value to apply."	""
 "The values in the specified radius is used in the average calculation only if its difference with the central value is lesser or equal to this threshold."	""
 "The values of the resultant grid can be either the seed value (e.g. the local maximum) or the enumerated segment id."	""
@@ -5180,7 +4996,6 @@ TEXT	TRANSLATION
 "These are the probabilities for the winner classes given by the neural network."	""
 "These are the winner class vectors."	""
 "Thiam's Transformed Vegetation Index"	""
-"Thickness_of_uppermost_rock_layer"	""
 "Thiessen Polygons"	""
 "Thin Plate Spline"	""
 "Thin Plate Spline (TIN)"	""
@@ -5205,11 +5020,9 @@ TEXT	TRANSLATION
 "This section contains all parameters used by the backpropagation algorithm."	""
 "This shapes layer will contain the resulting channel network in vector format (lines)."	""
 "This value is ignored if set to zero."	""
-"This value is used as constant if no vapour pressure grid is given."	""
 "This will contain your output data of type grid."	""
 "This will contain your output data of type shapes."	""
 "Thomas Schorr (c) 2007"	""
-"Thread"	""
 "Threshold"	""
 "Threshold (Grid Units)"	""
 "Threshold (Init.)"	""
@@ -5218,9 +5031,7 @@ TEXT	TRANSLATION
 "Threshold Error"	""
 "Threshold Grid"	""
 "Threshold Height"	""
-"Threshold Infected"	""
 "Threshold Linear Flow"	""
-"Threshold Sickness"	""
 "Threshold Type"	""
 "Threshold [Percent]"	""
 "Threshold for Elevation Percentile (Lowness)"	""
@@ -5230,7 +5041,6 @@ TEXT	TRANSLATION
 "Threshold for different route"	""
 "Threshold for linear flow, if exceeded D8 is used."	""
 "Threshold for plane"	""
-"Threshold for sediment motion"	""
 "Thresholded Linear Flow"	""
 "Thresholds"	""
 "Thumbnail Size"	""
@@ -5277,10 +5087,8 @@ TEXT	TRANSLATION
 "Time span used for the calculation of daily radiation sums."	""
 "Time stamp of Image"	""
 "Time step exceeds duration"	""
-"Time step size (yrs)"	""
 "Time step size for a day's calculation given in hours."	""
 "Time step size for a range of days calculation given in days."	""
-"Times"	""
 "Timespan (days)"	""
 "Tip of the Day..."	""
 "Tissot's Indicatrix"	""
@@ -5304,11 +5112,9 @@ TEXT	TRANSLATION
 "Tools"	""
 "Tools for (grid based) digital terrain analysis."	""
 "Tools for GPS data handling."	""
-"Tools for Soil."	""
 "Tools for Triangulated Irregular Network (TIN) processing."	""
 "Tools for digital terrain analysis."	""
 "Tools for lines."	""
-"Tools for managing weather and climate data."	""
 "Tools for point clouds."	""
 "Tools for polygons."	""
 "Tools for regression analyses."	""
@@ -5351,12 +5157,9 @@ TEXT	TRANSLATION
 "Total area is zero or minimum elevation is equal or lower than maximum elevation!"	""
 "Total flow (in watershed) [m^3/dt]"	""
 "Total flow [m/dt]"	""
-"Total insolation, the sum of direct and diffuse incoming solar radiation."	""
 "Total memory size"	""
 "Total number of points: %s"	""
 "Total number of referenced datasets: %d"	""
-"Tracer"	""
-"Tracer Lines"	""
 "Tracing: Convergence"	""
 "Tracing: Max. Divergence"	""
 "Tracing: Stop after x cells with divergent flow"	""
@@ -5389,15 +5192,12 @@ TEXT	TRANSLATION
 "Transmissivity"	""
 "Transparency [%]"	""
 "Transparent"	""
-"Transport"	""
 "Transport Capacity Clay"	""
 "Transport Capacity Sand"	""
 "Transport Capacity Silt"	""
 "Transport Condition Clay"	""
 "Transport Condition Sand"	""
 "Transport Condition Silt"	""
-"Transport Function"	""
-"Transportation Depth"	""
 "Transpose Grids"	""
 "Transpose Table"	""
 "Transposed Grids"	""
@@ -5455,7 +5255,6 @@ TEXT	TRANSLATION
 "Uniform"	""
 "Union"	""
 "Unique"	""
-"Unique Production Rate [m/h]"	""
 "Unit"	""
 "Unit Name"	""
 "Units"	""
@@ -5476,7 +5275,6 @@ TEXT	TRANSLATION
 "Up/Down"	""
 "Update"	""
 "Update Data"	""
-"Update Frequency"	""
 "Update Raster SRID"	""
 "Update Shapes SRID"	""
 "Update View"	""
@@ -5489,19 +5287,13 @@ TEXT	TRANSLATION
 "Upland Drainages"	""
 "Upland Drainages, Headwaters"	""
 "Upper"	""
-"Upper Half"	""
 "Upper Slopes"	""
 "Upper Slopes, Mesas"	""
 "Upper Tolerance"	""
-"Uppermost Rock Type"	""
-"Uppermost Rock Type Thickness"	""
 "Upscaling Method"	""
 "Upslope Area"	""
 "Upslope Basins"	""
-"Upslope Curv UnNormalized"	""
 "Upslope Curvature"	""
-"Upslope Curvature Normalized"	""
-"Upslope Curvatures"	""
 "Upslope Flow Width"	""
 "Upslope Length Factor"	""
 "Upslope Slope"	""
@@ -5597,7 +5389,6 @@ TEXT	TRANSLATION
 "Van der Grinten"	""
 "Var.cum."	""
 "Variable"	""
-"Variables to Import"	""
 "Variance"	""
 "Variance (version 1)"	""
 "Variance (version 2)"	""
@@ -5623,8 +5414,6 @@ TEXT	TRANSLATION
 "Vegetation parameters"	""
 "Velocidad del viento"	""
 "Velocidad del viento (km/h)"	""
-"Velocity"	""
-"Velocity Calculation"	""
 "Verbose"	""
 "Verbose Messages"	""
 "Verbose Output"	""
@@ -5642,13 +5431,11 @@ TEXT	TRANSLATION
 "Vertical Overland Flow Distance"	""
 "Vertical Range"	""
 "Vertical Scaling"	""
-"Vertical Tracer Density"	""
 "Vertical hatch"	""
 "Vertical scaling factor"	""
 "Vertically mirrored"	""
 "Vertices"	""
 "Vertikale Zufluesse"	""
-"Verwitterungsformeln"	""
 "ViGrA"	""
 "Victor Olaya (c) 2004"	""
 "Victor Olaya (c) 2005"	""
@@ -5692,13 +5479,10 @@ TEXT	TRANSLATION
 "WKT: %s"	""
 "WMS Import"	""
 "WMS Map"	""
-"WRF Extract Data"	""
-"WRF Extract and Downscale to DEM"	""
 "WUse Einheit"	""
 "W_up"	""
 "Wa-Tor"	""
 "Waehlen ob TestRoutine 1 durchgefuehrt werden soll... 1) nur fuer Teileinzugsgebiet der HG-Rasterzelle oder 2) fuer das Flusseinzugsgebiet bis zum Erreichen der HG-Rasterzelle."	""
-"Wang/Liu"	""
 "Warm Cloud"	""
 "Warning"	""
 "Warning: there are more predictor variables then dependent ones, surplus will be ignored."	""
@@ -5706,21 +5490,14 @@ TEXT	TRANSLATION
 "Water"	""
 "Water Content [cm]"	""
 "Water Retention Capacity"	""
-"Water Surface Exaggeration"	""
 "Water Vapour Pressure [mbar]"	""
 "Water content change across the wetting front"	""
 "Water content of a vertical slice of atmosphere in cm: 1.5 to 1.7, average=1.68"	""
-"Water_discharge"	""
 "Watershed Basins"	""
 "Watershed Basins (Extended)"	""
 "Watershed Segmentation"	""
 "Watershed Segmentation (ViGrA)"	""
 "Weather Records"	""
-"Weathering"	""
-"Weathering Formulas"	""
-"Weathering Variables"	""
-"Weathering rate decay constant (1/m)"	""
-"Weathering threshold area"	""
 "Web Service Data Access"	""
 "Weight"	""
 "Weight for grid "	""
@@ -5751,6 +5528,8 @@ TEXT	TRANSLATION
 "Wind Direction Units"	""
 "Wind Effect"	""
 "Wind Effect (Windward / Leeward Index)"	""
+"Wind Exposition"	""
+"Wind Exposition Index"	""
 "Wind Speed"	""
 "Wind Speed (m/s)"	""
 "Wind direction (degrees clockwise from north)"	""
@@ -5767,9 +5546,9 @@ TEXT	TRANSLATION
 "Wire Frame Color"	""
 "Wischmeier & Smith 1978"	""
 "Wombling (Edge Detection)"	""
-"Wombling Direction"	""
-"Wombling Magnitude"	""
+"Wombling for Multiple Features (Edge Detection)"	""
 "Wood Fuel Moisture"	""
+"Workspace"	""
 "World File"	""
 "World File from Flight and Camera Settings"	""
 "Write Field Names"	""
@@ -5833,9 +5612,7 @@ TEXT	TRANSLATION
 "YMax: %.6f"	""
 "YMin: %.6f"	""
 "Year"	""
-"Year [ka BP]"	""
 "Year [ka]"	""
-"Years BP"	""
 "Yoshimasa Tsuruoka"	""
 "You can specify the number of layers in the network (including input and output layer)."	""
 "You can specify the number of neurons in each layer of the network."	""
@@ -5847,12 +5624,10 @@ TEXT	TRANSLATION
 "Z"	""
 "Z Attribute"	""
 "Z Axis"	""
-"Z Model"	""
 "Z Multiplier"	""
 "Z Value"	""
 "Z Values"	""
 "Z is Column ..."	""
-"Z+S Model"	""
 "Z-Offset"	""
 "Z-Range"	""
 "Z-Rotation"	""
@@ -5862,9 +5637,9 @@ TEXT	TRANSLATION
 "ZMin"	""
 "ZMin: %.6f"	""
 "ZONE"	""
-"Z_Model"	""
 "Zenith"	""
 "Zero"	""
+"Zero as No-Data"	""
 "Zevenbergen & Thorne"	""
 "Zevenbergen & Thorne (1987) refer to this as plan curvature"	""
 "Zevenbergen & Thorne (1987) refer to this as profile curvature"	""
@@ -5920,32 +5695,6 @@ TEXT	TRANSLATION
 "\n\n ** Error : Could not close PDF engine ** \n\n"	""
 "\n\n ** Error : Could not save PDF file ** \n\n"	""
 "_TL"	""
-"__ACHAN__"	""
-"__C0__"	""
-"__CHANA__"	""
-"__DOWNWT__"	""
-"__DX__"	""
-"__KCI__"	""
-"__KC__"	""
-"__KDP__"	""
-"__KT__"	""
-"__MB__"	""
-"__MCI__"	""
-"__MDP__"	""
-"__MF__"	""
-"__MW__"	""
-"__NB__"	""
-"__NCI__"	""
-"__NF__"	""
-"__OPTDIFF__"	""
-"__OPTTRANS__"	""
-"__PF__"	""
-"__PMA__"	""
-"__PPT__"	""
-"__SCR__"	""
-"__TAUC__"	""
-"__TCI__"	""
-"__WRTINT__"	""
 "a * b"	""
 "a + b * (1 - exp(-(x / c)^2))"	""
 "a + b * (1 - exp(-x / c))"	""
@@ -5958,7 +5707,6 @@ TEXT	TRANSLATION
 "a(s)"	""
 "a(s) [lower bound]"	""
 "a(s) [upper bound]"	""
-"abort"	""
 "abort export"	""
 "absolute"	""
 "absolute catchment area"	""
@@ -5991,9 +5739,9 @@ TEXT	TRANSLATION
 "alternating scale bar"	""
 "alternative"	""
 "always ask what to do"	""
+"analyzing"	""
 "angle calculation is only available when exact two features are compared"	""
 "another grid"	""
-"append"	""
 "append records, if table structure allows"	""
 "appending to existing table"	""
 "apply coordinate transformation if appropriate"	""
@@ -6019,8 +5767,7 @@ TEXT	TRANSLATION
 "automatically"	""
 "average"	""
 "average size of the area covered by each category that occurs within search area"	""
-"averages"	""
-"averages + standard deviations"	""
+"average value"	""
 "avoids precision problems when source and target crs use different geodedtic datums."	""
 "b(q)"	""
 "b(q) [lower bound]"	""
@@ -6033,7 +5780,9 @@ TEXT	TRANSLATION
 "bar (not outlined)"	""
 "basic SIA model"	""
 "before"	""
+"before tool execution check failed"	""
 "begin transaction command failed"	""
+"between cells"	""
 "bi-linear saddle"	""
 "bicubic spline"	""
 "bilinear"	""
@@ -6047,17 +5796,19 @@ TEXT	TRANSLATION
 "blending distance given in map units"	""
 "blue channel color"	""
 "bm"	""
-"both"	""
 "bottom"	""
 "bottom / left"	""
 "bottom left"	""
 "bottom right"	""
 "bottom up"	""
+"bottom-left"	""
+"bottom-right"	""
 "bright - dark"	""
 "built-in"	""
 "c, Percentage clays [%]"	""
 "cache memory size in MB"	""
 "calculate averages"	""
+"calculate from grid system"	""
 "calculate gradient magnitude"	""
 "calculate gradients"	""
 "calculating splines..."	""
@@ -6078,6 +5829,7 @@ TEXT	TRANSLATION
 "cellsize and upper left corner coordinates"	""
 "center"	""
 "center cell's aspect direction"	""
+"centered"	""
 "central"	""
 "change"	""
 "check for building parts failed"	""
@@ -6103,7 +5855,6 @@ TEXT	TRANSLATION
 "clip features"	""
 "clipped"	""
 "clockwise"	""
-"closed"	""
 "closing"	""
 "coef0"	""
 "coef0 in kernel function"	""
@@ -6124,8 +5875,9 @@ TEXT	TRANSLATION
 "concavity"	""
 "confirm"	""
 "confirm with options"	""
-"conrad"	""
 "constant direction into the wind blows, given as degree"	""
+"constant histogram stretch for all time steps"	""
+"constant latitude"	""
 "contain the centeroid of"	""
 "continue"	""
 "continuous"	""
@@ -6142,25 +5894,29 @@ TEXT	TRANSLATION
 "corrupted record header"	""
 "corrupted shapefile."	""
 "could allocate memory for scaled grid"	""
+"could not access raster table"	""
+"could not access table"	""
 "could not add save point"	""
 "could not allocate memory for temporary grid."	""
 "could not allocate sufficient memory"	""
 "could not commit/rollback transactions."	""
 "could not connect ODBC source"	""
 "could not connect to PostgreSQL source"	""
+"could not connect to database."	""
 "could not create KML file"	""
 "could not create distance grid"	""
 "could not create geometry field"	""
 "could not create index on observations"	""
 "could not create index: insufficient memory"	""
+"could not create new PostgreSQL database"	""
 "could not create table"	""
 "could not create weights grid"	""
 "could not disconnect ODBC source"	""
 "could not disconnect PostgreSQL source"	""
+"could not disconnect and drop PostgreSQL database"	""
+"could not drop PostgreSQL database"	""
 "could not execute module"	""
 "could not execute tool"	""
-"could not find any band data"	""
-"could not find level data"	""
 "could not find module"	""
 "could not find tool"	""
 "could not import random forest"	""
@@ -6177,6 +5933,7 @@ TEXT	TRANSLATION
 "could not initialize tool"	""
 "could not load file"	""
 "could not load model from file"	""
+"could not load raster"	""
 "could not locate line string to polygon conversion tool"	""
 "could not open GetMap stream"	""
 "could not open data source"	""
@@ -6200,7 +5957,6 @@ TEXT	TRANSLATION
 "creating batch file example"	""
 "creating interpolator"	""
 "creating tool documentation files"	""
-"critical slope"	""
 "cross"	""
 "cubic convolution"	""
 "cubic surface"	""
@@ -6219,7 +5975,6 @@ TEXT	TRANSLATION
 "dark object subtraction 4"	""
 "data / no-data"	""
 "data file could not be openend"	""
-"data file does not exist"	""
 "data set has no attributes"	""
 "database table does not exist"	""
 "date"	""
@@ -6247,12 +6002,11 @@ TEXT	TRANSLATION
 "delivery index calculation failed"	""
 "descending"	""
 "diffuse pollution risk calculation failed"	""
-"diffusive"	""
-"diffusive and fluvial"	""
 "digital elevation model"	""
 "digital elevation model [m]"	""
 "digitzing a polygon"	""
 "dilation"	""
+"direction"	""
 "direction of scan flag"	""
 "direction of sun (degree, clockwise from North)"	""
 "direction to the center cell"	""
@@ -6264,6 +6018,7 @@ TEXT	TRANSLATION
 "do not confirm"	""
 "do not join"	""
 "do not show"	""
+"do not sort"	""
 "do not update"	""
 "down"	""
 "downscaling"	""
@@ -6276,6 +6031,7 @@ TEXT	TRANSLATION
 "each pair with a single record"	""
 "each shape"	""
 "each shape's part"	""
+"edge cells"	""
 "edge collection"	""
 "edge detection"	""
 "edge of flight line flag"	""
@@ -6350,6 +6106,7 @@ TEXT	TRANSLATION
 "first"	""
 "first point"	""
 "first value"	""
+"fit histogram stretch for each time step"	""
 "fit to each grid"	""
 "fit to overall range"	""
 "fit to overall standard deviation"	""
@@ -6368,7 +6125,6 @@ TEXT	TRANSLATION
 "flow directions..."	""
 "flow travel time to channel expressed in hours based on Manning's Equation"	""
 "flow width (original)"	""
-"fluvial"	""
 "forward"	""
 "found less than two categories, nothing to do"	""
 "four-neighbourhood"	""
@@ -6377,11 +6133,8 @@ TEXT	TRANSLATION
 "full frame"	""
 "function fitting failed !"	""
 "function not found"	""
-"function parameters"	""
-"function parameters + trend quality"	""
 "function table full"	""
 "gamma in kernel function"	""
-"gaps filled"	""
 "gaussian"	""
 "gaussian kernel"	""
 "gaussian weighting"	""
@@ -6393,6 +6146,7 @@ TEXT	TRANSLATION
 "gps-time"	""
 "gradient (degree)"	""
 "gradient (tangens)"	""
+"gradients"	""
 "green > blue"	""
 "green > grey > blue"	""
 "green > red > blue"	""
@@ -6424,7 +6178,6 @@ TEXT	TRANSLATION
 "high"	""
 "highest"	""
 "highest z"	""
-"hillslope length-to-channel"	""
 "histogram match"	""
 "horizontal"	""
 "hours"	""
@@ -6458,11 +6211,8 @@ TEXT	TRANSLATION
 "initial number of lag distance classes"	""
 "initial number of lag distance classes for variogram estimation"	""
 "initialisation error"	""
-"initialising gradient..."	""
-"initialising planetary bending..."	""
 "initialization"	""
 "initialization failed"	""
-"initialize grid cells"	""
 "input"	""
 "input file"	""
 "instable (thawing)"	""
@@ -6482,9 +6232,11 @@ TEXT	TRANSLATION
 "invalid control points"	""
 "invalid data"	""
 "invalid division size"	""
+"invalid extent"	""
 "invalid features"	""
 "invalid field selection"	""
 "invalid file code"	""
+"invalid file name"	""
 "invalid filter matrix"	""
 "invalid geographic coordinate system / datum"	""
 "invalid geogrid file name"	""
@@ -6503,6 +6255,7 @@ TEXT	TRANSLATION
 "invalid point cloud"	""
 "invalid points have been skipped"	""
 "invalid points layer"	""
+"invalid polygons"	""
 "invalid production date"	""
 "invalid project file."	""
 "invalid snap features"	""
@@ -6569,7 +6322,6 @@ TEXT	TRANSLATION
 "local"	""
 "local maximum search distance given in map units"	""
 "local slope"	""
-"local time"	""
 "local water depth or absolute water level at the user specified cell"	""
 "localhost"	""
 "logarithmic"	""
@@ -6587,8 +6339,6 @@ TEXT	TRANSLATION
 "m2/h"	""
 "m3/Monat"	""
 "m3/s"	""
-"m_pBoundary"	""
-"m_pRock_Top_Idx"	""
 "magenta - white"	""
 "main basins..."	""
 "majority"	""
@@ -6639,7 +6389,6 @@ TEXT	TRANSLATION
 "minimum number of upslope contributing cells to start a channel"	""
 "minimum requirement"	""
 "minimum slope angle preserved from one cell to the next, zero results in flat areas [Degree]"	""
-"minimum sub-time step size in years"	""
 "minimum value"	""
 "minimum value of all duplicates"	""
 "minimum x value"	""
@@ -6648,7 +6397,6 @@ TEXT	TRANSLATION
 "missing icon tags"	""
 "missing operand"	""
 "missing tool chain tags"	""
-"missing year"	""
 "model application"	""
 "model creation"	""
 "moment"	""
@@ -6680,6 +6428,7 @@ TEXT	TRANSLATION
 "no attributes in table"	""
 "no choice available"	""
 "no class definitions for final state"	""
+"no class definitions for grid"	""
 "no class definitions for initial state"	""
 "no conversion (areas already given as specific catchment area)"	""
 "no data entries in project file."	""
@@ -6694,7 +6443,6 @@ TEXT	TRANSLATION
 "no features to buffer."	""
 "no fields in selection"	""
 "no fields to add"	""
-"no files in selection"	""
 "no gaps"	""
 "no geometry in selection"	""
 "no grid in list"	""
@@ -6708,7 +6456,7 @@ TEXT	TRANSLATION
 "no layers in data source"	""
 "no lines for splitting"	""
 "no memory"	""
-"no output"	""
+"no name has been specified for new raster table"	""
 "no output parameter in selection"	""
 "no parameter output specified"	""
 "no points in input layer"	""
@@ -6771,7 +6519,6 @@ TEXT	TRANSLATION
 "nothing to do. transformation needs at least two components."	""
 "nothing to do: input format is same as output format"	""
 "nothing to do: no data in selection"	""
-"nothing to do: no output to memory or file has been specified"	""
 "nothing to do: original and desired field types are identical"	""
 "nu-SVC"	""
 "nu-SVR"	""
@@ -6780,6 +6527,7 @@ TEXT	TRANSLATION
 "number of cells"	""
 "number of cells in S-N direction"	""
 "number of cells in W-E direction"	""
+"number of different categories (unique values) per area"	""
 "number of different categories (unique values) within search area"	""
 "number of dropped observations"	""
 "number of dropped shapes"	""
@@ -6802,6 +6550,9 @@ TEXT	TRANSLATION
 "offset in minutes relative to 00:00 (midnight)"	""
 "okay"	""
 "old value"	""
+"on cell"	""
+"one catalogue for each coordinate system"	""
+"one catalogue using geographic coordinates"	""
 "one hull for all shapes"	""
 "one hull per shape"	""
 "one hull per shape part"	""
@@ -6818,7 +6569,6 @@ TEXT	TRANSLATION
 "only points with given minimum number of points in search radius will be processed"	""
 "only show within scale range; values are given as extent measured in map units"	""
 "only z"	""
-"open"	""
 "open transactions committed"	""
 "open transactions rollbacked"	""
 "open transactions rolled back"	""
@@ -6828,6 +6578,7 @@ TEXT	TRANSLATION
 "optional grid providing values to be compared with linear flow threshold instead of flow accumulation"	""
 "optional input"	""
 "optional output"	""
+"orientation"	""
 "origin adjustment for Z axis (heading)"	""
 "original"	""
 "original calculation (Ringeler)"	""
@@ -6883,7 +6634,6 @@ TEXT	TRANSLATION
 "polynomial"	""
 "polynomial trend"	""
 "polynomial trend (coefficient interpolation)"	""
-"polyonom fit"	""
 "post-processing..."	""
 "power of distance"	""
 "prediction"	""
@@ -6899,7 +6649,6 @@ TEXT	TRANSLATION
 "quadratic surface"	""
 "quantiles"	""
 "quartic kernel"	""
-"r2"	""
 "radial basis function"	""
 "radians"	""
 "radians to degree"	""
@@ -6907,7 +6656,6 @@ TEXT	TRANSLATION
 "radius given in map units used to fill valleys"	""
 "radius in map units"	""
 "rainbow"	""
-"random"	""
 "random read"	""
 "random write"	""
 "range"	""
@@ -6940,7 +6688,6 @@ TEXT	TRANSLATION
 "remove maxima (with tolerance)"	""
 "remove minima (with tolerance)"	""
 "removed"	""
-"replace"	""
 "replace existing table"	""
 "replacements"	""
 "resampling"	""
@@ -7010,7 +6757,6 @@ TEXT	TRANSLATION
 "shapes extent"	""
 "shapes have been dropped"	""
 "shapes layer extent"	""
-"shear stress coefficient Kt:"	""
 "show direct insolation for each time step."	""
 "show mouse position in statusbar using geographic coordinates if possible"	""
 "shows cell values when zoomed"	""
@@ -7065,7 +6811,6 @@ TEXT	TRANSLATION
 "statistics table does not contain any records"	""
 "statistics table is missing required fields"	""
 "stddev"	""
-"steepest neighbour"	""
 "step"	""
 "step size should not exceed number of cells in x or y direction"	""
 "stepwise"	""
@@ -7091,6 +6836,7 @@ TEXT	TRANSLATION
 "take value from the point to be kept"	""
 "target"	""
 "target area is distinct from levels area "	""
+"target's spatial reference system is undefined"	""
 "text"	""
 "the lower this value is the stronger is the suction effect"	""
 "theta"	""
@@ -7099,7 +6845,6 @@ TEXT	TRANSLATION
 "this operation requires locations to be of type polygon"	""
 "this operation requires selectable shapes to be of type polygon"	""
 "threshold slope"	""
-"time of sunrise/sunset is only calculated if time span is set to single day"	""
 "tolerance as absolute values"	""
 "tolerance of termination criterion"	""
 "too few parameters"	""
@@ -7117,6 +6862,8 @@ TEXT	TRANSLATION
 "top hat"	""
 "top left"	""
 "top right"	""
+"top-left"	""
+"top-right"	""
 "top-to-bottom and left-to-right cell sizes differ."	""
 "topographic wetness index..."	""
 "topography"	""
@@ -7158,8 +6905,6 @@ TEXT	TRANSLATION
 "unsupported vector type"	""
 "until user closes it"	""
 "up"	""
-"update, colour stretch for each time step"	""
-"update, fixed colour stretch"	""
 "upscaling of predictors"	""
 "upsetting model domain"	""
 "use a zero value for hillslopes, any other value for channel cells."	""
@@ -7167,12 +6912,10 @@ TEXT	TRANSLATION
 "use old version for constant wind direction (no acceleration and averaging option)"	""
 "use this for (linear) flow routing, if the value is a valid direction (0-7 = N, NE, E, SE, S, SW, W, NW)"	""
 "use this grid's system for output grids"	""
-"use values in selected cold air height output grid"	""
 "user data"	""
 "user defined"	""
 "user defined NoData value"	""
 "user defined kernel"	""
-"user defined reference"	""
 "user defined size"	""
 "using cellsize"	""
 "valid data cells match original grid extent"	""
@@ -7185,18 +6928,12 @@ TEXT	TRANSLATION
 "variance-covariance matrix"	""
 "variogram model"	""
 "vertical"	""
-"virus 1"	""
-"virus 2"	""
-"von Neumann (4)"	""
 "w"	""
-"wang/liu"	""
 "warning"	""
 "warning, input uses less than 4 bytes per value"	""
 "warning: albedo is ignored"	""
-"warning: local sink detected"	""
 "warning: number of Eigen vectors and components differs."	""
 "warning: number of component grids and components differs."	""
-"weathering only"	""
 "weighting factor for slope in index calculation"	""
 "whether to train a SVC or SVR model for probability estimates"	""
 "whether to use the shrinking heuristics"	""
@@ -7209,6 +6946,7 @@ TEXT	TRANSLATION
 "wire"	""
 "with B-spline refinement"	""
 "without B-spline refinement"	""
+"world"	""
 "x - Values"	""
 "x Position"	""
 "x, y"	""
@@ -7224,8 +6962,6 @@ TEXT	TRANSLATION
 "y Position"	""
 "yMax"	""
 "yMin"	""
-"years"	""
-"years before present"	""
 "yellow - white"	""
 "yellow > blue"	""
 "yellow > green"	""
diff --git a/src/saga_core/saga_gui/res/saga_icon_128.png b/src/saga_core/saga_gui/res/saga_icon_128.png
new file mode 100644
index 0000000..d1c4e38
Binary files /dev/null and b/src/saga_core/saga_gui/res/saga_icon_128.png differ
diff --git a/src/saga_core/saga_gui/res/saga_icon_64.png b/src/saga_core/saga_gui/res/saga_icon_64.png
new file mode 100644
index 0000000..a0e22b2
Binary files /dev/null and b/src/saga_core/saga_gui/res/saga_icon_64.png differ
diff --git a/src/saga_core/saga_gui/res_commands.cpp b/src/saga_core/saga_gui/res_commands.cpp
index 833997d..ca01cf9 100644
--- a/src/saga_core/saga_gui/res_commands.cpp
+++ b/src/saga_core/saga_gui/res_commands.cpp
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: res_commands.cpp 2650 2015-10-15 17:01:38Z oconrad $
+ * Version $Id: res_commands.cpp 2698 2015-11-24 13:45:01Z oconrad $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -113,9 +113,6 @@ wxString CMD_Get_Name(int Cmd_ID)
 	case ID_CMD_WKSP_ITEM_SETTINGS_COPY:return( _TL("Copy Settings from other Layer") );
 	case ID_CMD_WKSP_ITEM_SEARCH:		return( _TL("Search for...") );
 
-	case ID_CMD_WKSP_OPEN:				return( _TL("Open") );
-	case ID_CMD_WKSP_SAVE:				return( _TL("Save All") );
-
 	case ID_CMD_INFO_CLEAR:				return( _TL("Clear") );
 	case ID_CMD_INFO_COPY:				return( _TL("Copy") );
 	case ID_CMD_INFO_SELECTALL:			return( _TL("Select All") );
@@ -143,19 +140,28 @@ wxString CMD_Get_Name(int Cmd_ID)
 	case ID_CMD_MODULES_CHAIN_RELOAD:	return( _TL("Reload") );
 	case ID_CMD_MODULES_CHAIN_EDIT:		return( _TL("Edit") );
 
-	case ID_CMD_DATA_PROJECT_NEW:		return( _TL("Close All") );
 	case ID_CMD_DATA_PROJECT_OPEN:		return( _TL("Load Project") );
 	case ID_CMD_DATA_PROJECT_OPEN_ADD:	return( _TL("Add Project") );
+	case ID_CMD_DATA_PROJECT_BROWSE:	return( _TL("Search for Projects") );		
+	case ID_CMD_DATA_PROJECT_CLOSE:		return( _TL("Close Project") );
 	case ID_CMD_DATA_PROJECT_SAVE:		return( _TL("Save Project") );
-	case ID_CMD_DATA_PROJECT_SAVE_AS:	return( _TL("Save Project As...") );
-	case ID_CMD_DATA_PROJECT_BROWSE:	return( _TL("Search for Projects...") );		
+	case ID_CMD_DATA_PROJECT_SAVE_AS:	return( _TL("Save Project as...") );
+	case ID_CMD_DATA_PROJECT_COPY:		return( _TL("Copy Project to...") );
+	case ID_CMD_DATA_PROJECT_COPY_DB:	return( _TL("Copy Project to Database") );
+
 	case ID_CMD_DATA_LEGEND_COPY:		return( _TL("Copy Legend to Clipboard...") );
 	case ID_CMD_DATA_LEGEND_SIZE_INC:	return( _TL("Increase Legend Size") );
 	case ID_CMD_DATA_LEGEND_SIZE_DEC:	return( _TL("Decrease Legend Size") );
+
 	case ID_CMD_DATA_HISTORY_CLEAR:		return( _TL("Clear History") );
 	case ID_CMD_DATA_HISTORY_TO_MODEL:	return( _TL("Save as Tool Chain") );
 	case ID_CMD_DATA_HISTORY_OPTIONS_COLLAPSE:	return( _TL("Collpase Options") );
 	case ID_CMD_DATA_HISTORY_OPTIONS_EXPAND:	return( _TL("Expand Options") );
+
+	case ID_CMD_DATA_OPEN:				return( _TL("Open") );
+	case ID_CMD_DATA_SAVE:				return( _TL("Save") );
+	case ID_CMD_DATA_SAVEAS:			return( _TL("Save as...") );
+	case ID_CMD_DATA_SAVETODB:			return( _TL("Save to Database...") );
 	case ID_CMD_DATA_PROJECTION:		return( _TL("Spatial Reference") );
 
 	case ID_CMD_GRIDS_OPEN:
@@ -163,9 +169,6 @@ wxString CMD_Get_Name(int Cmd_ID)
 	case ID_CMD_TABLES_OPEN:
 	case ID_CMD_TIN_OPEN:
 	case ID_CMD_POINTCLOUD_OPEN:		return( _TL("Load") );
-	case ID_CMD_DATA_SAVE:				return( _TL("Save") );
-	case ID_CMD_DATA_SAVEAS:			return( _TL("Save as...") );
-	case ID_CMD_DATA_SAVETODB:			return( _TL("Save to Database...") );
 
 	case ID_CMD_GRIDS_SHOW:
 	case ID_CMD_SHAPES_SHOW:
@@ -185,7 +188,7 @@ wxString CMD_Get_Name(int Cmd_ID)
 
 	case ID_CMD_TABLES_DIAGRAM:			return( _TL("Diagram") );
 
-	case ID_CMD_GRIDS_SAVEAS_IMAGE:		return( _TL("Save As Image...") );
+	case ID_CMD_GRIDS_SAVEAS_IMAGE:		return( _TL("Save as Image...") );
 	case ID_CMD_GRIDS_EQUALINTERVALS:	return( _TL("Create Normalised Classification") );
 	case ID_CMD_GRIDS_FIT_MINMAX:		return( _TL("Histogram Stretch to Minimum/Maximum") );
 	case ID_CMD_GRIDS_FIT_STDDEV:		return( _TL("Histogram Stretch to Standard Deviation") );
@@ -194,12 +197,13 @@ wxString CMD_Get_Name(int Cmd_ID)
 	case ID_CMD_GRIDS_SEL_CLEAR:		return( _TL("Clear Selection") );
 	case ID_CMD_GRIDS_SEL_DELETE:		return( _TL("Delete Selection") );
 
-	case ID_CMD_SHAPES_EDIT_SHAPE:		return( _TL("Edit Selected Shape") );
+	case ID_CMD_SHAPES_SAVE_ATTRIBUTES:	return( _TL("Save Attributes as...") );
+	case ID_CMD_SHAPES_EDIT_SHAPE:		return( _TL("Edit Selection") );
 	case ID_CMD_SHAPES_EDIT_SEL_CLEAR:	return( _TL("Clear Selection") );
 	case ID_CMD_SHAPES_EDIT_SEL_INVERT:	return( _TL("Invert Selection") );
 	case ID_CMD_SHAPES_EDIT_ADD_SHAPE:	return( _TL("Add Shape") );
 	case ID_CMD_SHAPES_EDIT_ADD_PART:	return( _TL("Add Part") );
-	case ID_CMD_SHAPES_EDIT_DEL_SHAPE:	return( _TL("Delete Selected Shape(s)") );
+	case ID_CMD_SHAPES_EDIT_DEL_SHAPE:	return( _TL("Delete Selection") );
 	case ID_CMD_SHAPES_EDIT_DEL_PART:	return( _TL("Delete Selected Part") );
 	case ID_CMD_SHAPES_EDIT_DEL_POINT:	return( _TL("Delete Selected Point") );
 	case ID_CMD_SHAPES_EDIT_SPLIT:		return( _TL("Split with Line") );
@@ -213,9 +217,10 @@ wxString CMD_Get_Name(int Cmd_ID)
 	case ID_CMD_MAPS_SHOW:						return( _TL("Show Map") );
 	case ID_CMD_MAPS_3D_SHOW:					return( _TL("Show 3D-View") );
 	case ID_CMD_MAPS_LAYOUT_SHOW:				return( _TL("Show Print Layout") );
-	case ID_CMD_MAPS_SAVE_IMAGE:				return( _TL("Save As Image...") );
-	case ID_CMD_MAPS_SAVE_IMAGE_ON_CHANGE:		return( _TL("Save As Image when changed") );
-	case ID_CMD_MAPS_SAVE_IMAGE_TO_MEMORY:		return( _TL("Save As Image to Workspace") );
+	case ID_CMD_MAPS_SAVE_IMAGE:				return( _TL("Save as Image...") );
+	case ID_CMD_MAPS_SAVE_IMAGE_ON_CHANGE:		return( _TL("Save as Image when changed") );
+	case ID_CMD_MAPS_SAVE_IMAGE_TO_KMZ:			return( _TL("Save as KMZ...") );
+	case ID_CMD_MAPS_SAVE_IMAGE_TO_MEMORY:		return( _TL("Save as Image to Workspace") );
 	case ID_CMD_MAPS_SAVE_TO_CLIPBOARD:			return( _TL("Copy Map to Clipboard [Ctrl+C]") );
 	case ID_CMD_MAPS_SAVE_TO_CLIPBOARD_LEGEND:	return( _TL("Copy Legend to Clipboard [Ctrl+L]") );
 	case ID_CMD_MAPS_SYNCHRONIZE:				return( _TL("Synchronise Map Extents") );
@@ -277,14 +282,14 @@ wxString CMD_Get_Name(int Cmd_ID)
 	case ID_CMD_MAP3D_STEREO_MORE:		return( _TL("Increase Eye Distance") );
 	case ID_CMD_MAP3D_STEREO:			return( _TL("Anaglyph [S]") );
 	case ID_CMD_MAP3D_INTERPOLATED:		return( _TL("Interpolated Colors") );
-	case ID_CMD_MAP3D_SAVE:				return( _TL("Save As Image...") );
-	case ID_CMD_MAP3D_SEQ_POS_ADD:		return( _TL("Add Position [A]") );
-	case ID_CMD_MAP3D_SEQ_POS_DEL:		return( _TL("Delete Last Position [D]") );
+	case ID_CMD_MAP3D_SAVE:				return( _TL("Save as Image...") );
+	case ID_CMD_MAP3D_SEQ_POS_ADD:		return( _TL("Add Position [Ctrl + A]") );
+	case ID_CMD_MAP3D_SEQ_POS_DEL:		return( _TL("Delete Last Position [Ctrl + D]") );
 	case ID_CMD_MAP3D_SEQ_POS_DEL_ALL:	return( _TL("Delete All Positions") );
 	case ID_CMD_MAP3D_SEQ_POS_EDIT:		return( _TL("Edit Positions") );
-	case ID_CMD_MAP3D_SEQ_PLAY:			return( _TL("Play Once [P]") );
-	case ID_CMD_MAP3D_SEQ_PLAY_LOOP:	return( _TL("Play Loop [L]") );
-	case ID_CMD_MAP3D_SEQ_SAVE:			return( _TL("Play And Save As Images...") );
+	case ID_CMD_MAP3D_SEQ_PLAY:			return( _TL("Play Once [Ctrl + P]") );
+	case ID_CMD_MAP3D_SEQ_PLAY_LOOP:	return( _TL("Play Loop [Ctrl + L]") );
+	case ID_CMD_MAP3D_SEQ_SAVE:			return( _TL("Play And Save as Images...") );
 
 	case ID_CMD_LAYOUT_PRINT_SETUP:		return( _TL("Print Setup") );
 	case ID_CMD_LAYOUT_PAGE_SETUP:		return( _TL("Page Setup") );
@@ -297,12 +302,14 @@ wxString CMD_Get_Name(int Cmd_ID)
 	case ID_CMD_TABLE_FIELD_SORT:		return( _TL("Sort Fields") );
 	case ID_CMD_TABLE_FIELD_RENAME:		return( _TL("Rename Fields") );
 	case ID_CMD_TABLE_FIELD_TYPE:		return( _TL("Change Field Type") );
+	case ID_CMD_TABLE_FIELD_OPEN_APP:	return( _TL("Open with external application") );
+	case ID_CMD_TABLE_FIELD_OPEN_DATA:	return( _TL("Open as data set") );
 	case ID_CMD_TABLE_RECORD_ADD:		return( _TL("Add Record") );
 	case ID_CMD_TABLE_RECORD_INS:		return( _TL("Insert Record") );
-	case ID_CMD_TABLE_RECORD_DEL:		return( _TL("Delete Selected Record(s)") );
+	case ID_CMD_TABLE_RECORD_DEL:		return( _TL("Delete Selection") );
 	case ID_CMD_TABLE_RECORD_DEL_ALL:	return( _TL("Delete All Records") );
-	case ID_CMD_TABLE_SELECTION_TO_TOP:	return( _TL("Sort Selection to Top") );
-	case ID_CMD_TABLE_SELECTION_ONLY:	return( _TL("Only Show Selection") );
+	case ID_CMD_TABLE_SELECTION_CLEAR:	return( _TL("Clear Selection") );
+	case ID_CMD_TABLE_SELECTION_ONLY:	return( _TL("Show Selection") );
 	case ID_CMD_TABLE_AUTOSIZE_COLS:	return( _TL("Fit Column Sizes") );
 	case ID_CMD_TABLE_AUTOSIZE_ROWS:	return( _TL("Fit Row Sizes") );
 
@@ -348,8 +355,8 @@ int CMD_Get_ImageID(int Cmd_ID)
 	case ID_CMD_FRAME_ACTIVE_SHOW:		return( ID_IMG_TB_ACTIVE );
 	case ID_CMD_FRAME_INFO_SHOW:		return( ID_IMG_TB_INFO );
 	case ID_CMD_FRAME_HELP:				return( ID_IMG_TB_HELP );
-	case ID_CMD_WKSP_OPEN:				return( ID_IMG_TB_OPEN );
-	case ID_CMD_WKSP_SAVE:				return( ID_IMG_TB_SAVE );
+	case ID_CMD_DATA_OPEN:				return( ID_IMG_TB_OPEN );
+	case ID_CMD_DATA_PROJECT_SAVE:		return( ID_IMG_TB_SAVE );
 	case ID_CMD_MODULES_OPEN:			return( ID_IMG_TB_OPEN_MODULE );
 	case ID_CMD_MODULES_SEARCH:			return( ID_IMG_NB_WKSP_MODULES );
 	case ID_CMD_TABLES_OPEN:			return( ID_IMG_TB_OPEN_TABLE );
diff --git a/src/saga_core/saga_gui/res_commands.h b/src/saga_core/saga_gui/res_commands.h
index 4d5591e..d6d75e8 100644
--- a/src/saga_core/saga_gui/res_commands.h
+++ b/src/saga_core/saga_gui/res_commands.h
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: res_commands.h 2650 2015-10-15 17:01:38Z oconrad $
+ * Version $Id: res_commands.h 2698 2015-11-24 13:45:01Z oconrad $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -113,8 +113,6 @@ enum ID_COMMANDS
 
 	//-----------------------------------------------------
 	ID_CMD_WKSP_FIRST,
-	ID_CMD_WKSP_OPEN,
-	ID_CMD_WKSP_SAVE,
 	ID_CMD_WKSP_ITEM_RETURN,
 	ID_CMD_WKSP_ITEM_CLOSE,
 	ID_CMD_WKSP_ITEM_SETTINGS_LOAD,
@@ -156,23 +154,29 @@ enum ID_COMMANDS
 	ID_CMD_DATA_FIRST,
 	ID_CMD_DATA_PROJECT_RECENT_FIRST,
 	ID_CMD_DATA_PROJECT_RECENT_LAST	= RECENT_COUNT + ID_CMD_DATA_PROJECT_RECENT_FIRST,
-	ID_CMD_DATA_PROJECT_NEW,
 	ID_CMD_DATA_PROJECT_OPEN,
 	ID_CMD_DATA_PROJECT_OPEN_ADD,
+	ID_CMD_DATA_PROJECT_BROWSE,
+	ID_CMD_DATA_PROJECT_CLOSE,
 	ID_CMD_DATA_PROJECT_SAVE,
 	ID_CMD_DATA_PROJECT_SAVE_AS,
-	ID_CMD_DATA_PROJECT_BROWSE,
+	ID_CMD_DATA_PROJECT_COPY,
+	ID_CMD_DATA_PROJECT_COPY_DB,
+
 	ID_CMD_DATA_LEGEND_COPY,
 	ID_CMD_DATA_LEGEND_SIZE_INC,
 	ID_CMD_DATA_LEGEND_SIZE_DEC,
+
 	ID_CMD_DATA_HISTORY_CLEAR,
 	ID_CMD_DATA_HISTORY_TO_MODEL,
 	ID_CMD_DATA_HISTORY_OPTIONS_COLLAPSE,
 	ID_CMD_DATA_HISTORY_OPTIONS_EXPAND,
-	ID_CMD_DATA_PROJECTION,
+
+	ID_CMD_DATA_OPEN,
 	ID_CMD_DATA_SAVE,
 	ID_CMD_DATA_SAVEAS,
 	ID_CMD_DATA_SAVETODB,
+	ID_CMD_DATA_PROJECTION,
 	ID_CMD_DATA_LAST,
 
 	ID_CMD_GRIDS_FIRST,
@@ -249,6 +253,7 @@ enum ID_COMMANDS
 	ID_CMD_MAPS_LAYOUT_SHOW,
 	ID_CMD_MAPS_SAVE_IMAGE,
 	ID_CMD_MAPS_SAVE_IMAGE_ON_CHANGE,
+	ID_CMD_MAPS_SAVE_IMAGE_TO_KMZ,
 	ID_CMD_MAPS_SAVE_IMAGE_TO_MEMORY,
 	ID_CMD_MAPS_SAVE_TO_CLIPBOARD,
 	ID_CMD_MAPS_SAVE_TO_CLIPBOARD_LEGEND,
@@ -335,11 +340,13 @@ enum ID_COMMANDS
 	ID_CMD_TABLE_FIELD_SORT,
 	ID_CMD_TABLE_FIELD_RENAME,
 	ID_CMD_TABLE_FIELD_TYPE,
+	ID_CMD_TABLE_FIELD_OPEN_APP,
+	ID_CMD_TABLE_FIELD_OPEN_DATA,
 	ID_CMD_TABLE_RECORD_ADD,
 	ID_CMD_TABLE_RECORD_INS,
 	ID_CMD_TABLE_RECORD_DEL,
 	ID_CMD_TABLE_RECORD_DEL_ALL,
-	ID_CMD_TABLE_SELECTION_TO_TOP,
+	ID_CMD_TABLE_SELECTION_CLEAR,
 	ID_CMD_TABLE_SELECTION_ONLY,
 	ID_CMD_TABLE_AUTOSIZE_COLS,
 	ID_CMD_TABLE_AUTOSIZE_ROWS,
diff --git a/src/saga_core/saga_gui/res_controls.cpp b/src/saga_core/saga_gui/res_controls.cpp
index b508776..e0b4943 100644
--- a/src/saga_core/saga_gui/res_controls.cpp
+++ b/src/saga_core/saga_gui/res_controls.cpp
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: res_controls.cpp 1921 2014-01-09 10:24:11Z oconrad $
+ * Version $Id: res_controls.cpp 2682 2015-11-06 12:44:37Z oconrad $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -77,36 +77,39 @@ const wxString CTRL_Get_Name(int ID_CTRL)
 {
 	switch( ID_CTRL )
 	{
-	case wxID_OK:
-	case ID_BTN_OK:						return( _TL("Okay") );
-	case wxID_CANCEL:
-	case ID_BTN_CANCEL:					return( _TL("Cancel") );
+	case wxID_OK               :
+	case ID_BTN_OK             :	return( _TL("Okay") );
+	case wxID_CANCEL           :
+	case ID_BTN_CANCEL         :	return( _TL("Cancel") );
 
-	case ID_BTN_APPLY:					return( _TL("Apply") );
-	case ID_BTN_RESTORE:				return( _TL("Restore") );
+	case ID_BTN_APPLY          :	return( _TL("Apply") );
+	case ID_BTN_RESTORE        :	return( _TL("Restore") );
 
-	case ID_BTN_EXECUTE:				return( _TL("Execute") );
+	case ID_BTN_EXECUTE        :	return( _TL("Execute") );
 
-	case ID_BTN_LOAD:					return( _TL("Load") );
-	case ID_BTN_SAVE:					return( _TL("Save") );
+	case ID_BTN_LOAD           :	return( _TL("Load") );
+	case ID_BTN_SAVE           :	return( _TL("Save") );
 
-	case ID_BTN_DEFAULTS:				return( _TL("Defaults") );
+	case ID_BTN_DEFAULTS       :	return( _TL("Defaults") );
 
-	case ID_BTN_ADD:					return( _TL("Add") );
-	case ID_BTN_ADD_ALL:				return( _TL("Add All") );
-	case ID_BTN_INSERT:					return( _TL("Insert") );
-	case ID_BTN_DELETE:					return( _TL("Delete") );
-	case ID_BTN_DELETE_ALL:				return( _TL("Clear") );
+	case ID_BTN_ADD            :	return( _TL("Add") );
+	case ID_BTN_ADD_ALL        :	return( _TL("Add All") );
+	case ID_BTN_INSERT         :	return( _TL("Insert") );
+	case ID_BTN_DELETE         :	return( _TL("Delete") );
+	case ID_BTN_DELETE_ALL     :	return( _TL("Clear") );
 
-	case ID_BTN_UP:						return( _TL("Up") );
-	case ID_BTN_DOWN:					return( _TL("Down") );
+	case ID_BTN_UP             :	return( _TL("Up") );
+	case ID_BTN_DOWN           :	return( _TL("Down") );
 
-	case ID_BTN_COLORS:					return( _TL("Colors") );
-	case ID_BTN_COLORS_MIRROR:			return( _TL("Mirror") );
-	case ID_BTN_COLORS_INVERT:			return( _TL("Invert") );
-	case ID_BTN_COLORS_RANDOM:			return( _TL("Random") );
-	case ID_BTN_COLORS_PRESET:			return( _TL("Presets") );
-	case ID_BTN_COLORS_COUNT:			return( _TL("Count") );
+	case ID_BTN_TABLE_TO_WKSP  :	return( _TL("Workspace") );
+	case ID_BTN_TABLE_FROM_WKSP:	return( _TL("Workspace") );
+
+	case ID_BTN_COLORS         :	return( _TL("Colors") );
+	case ID_BTN_COLORS_MIRROR  :	return( _TL("Mirror") );
+	case ID_BTN_COLORS_INVERT  :	return( _TL("Invert") );
+	case ID_BTN_COLORS_RANDOM  :	return( _TL("Random") );
+	case ID_BTN_COLORS_PRESET  :	return( _TL("Presets") );
+	case ID_BTN_COLORS_COUNT   :	return( _TL("Count") );
 	}
 
 	return( _TL("Button") );
diff --git a/src/saga_core/saga_gui/res_controls.h b/src/saga_core/saga_gui/res_controls.h
index bc21d13..02da1fd 100644
--- a/src/saga_core/saga_gui/res_controls.h
+++ b/src/saga_core/saga_gui/res_controls.h
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: res_controls.h 1939 2014-01-14 16:48:06Z oconrad $
+ * Version $Id: res_controls.h 2682 2015-11-06 12:44:37Z oconrad $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -168,6 +168,9 @@ enum ID_CONTROLS
 
 	ID_BTN_DEFAULTS,
 
+	ID_BTN_TABLE_TO_WKSP,
+	ID_BTN_TABLE_FROM_WKSP,
+
 	ID_BTN_COLORS,
 	ID_BTN_COLORS_MIRROR,
 	ID_BTN_COLORS_INVERT,
diff --git a/src/saga_core/saga_gui/saga.cpp b/src/saga_core/saga_gui/saga.cpp
index 078cb3c..23234d0 100644
--- a/src/saga_core/saga_gui/saga.cpp
+++ b/src/saga_core/saga_gui/saga.cpp
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: saga.cpp 2582 2015-09-16 18:53:55Z oconrad $
+ * Version $Id: saga.cpp 2694 2015-11-20 16:43:15Z oconrad $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -382,17 +382,21 @@ bool CSAGA::Process_Wait(bool bEnforce)
 	static bool			bYield	= false;
 	static wxDateTime	tYield	= wxDateTime::UNow();
 
-	if( !bYield && (bEnforce || m_Process_Frequency <= 0 || (wxDateTime::UNow() - tYield).GetMilliseconds() > m_Process_Frequency) )
+	if( !bYield && (bEnforce || m_Process_Frequency <= 0 || m_Process_Frequency <= (wxDateTime::UNow() - tYield).GetMilliseconds()) )
 	{
 		bYield	= true;
 
-		//	Yield();
-		//	wxSafeYield(g_pSAGA_Frame);
+	//	Yield();
+	//	wxSafeYield(g_pSAGA_Frame);
 
 		while( Pending() && Dispatch() );
 
+		if( m_Process_Frequency > 0 )
+		{
+			tYield	= wxDateTime::UNow();
+		}
+
 		bYield	= false;
-		tYield	= wxDateTime::UNow();
 	}
 
 	return( true );
diff --git a/src/saga_core/saga_gui/saga_frame.cpp b/src/saga_core/saga_gui/saga_frame.cpp
index dcd7573..c810032 100644
--- a/src/saga_core/saga_gui/saga_frame.cpp
+++ b/src/saga_core/saga_gui/saga_frame.cpp
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: saga_frame.cpp 2640 2015-10-07 17:29:38Z oconrad $
+ * Version $Id: saga_frame.cpp 2724 2015-12-11 10:24:35Z oconrad $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -71,6 +71,7 @@
 #include <wx/toolbar.h>
 #include <wx/tipdlg.h>
 #include <wx/aui/aui.h>
+#include <wx/display.h>
 
 #include <saga_api/saga_api.h>
 
@@ -138,10 +139,10 @@ public:
 	CSAGA_Frame_StatusBar(wxWindow *parent, wxWindowID id, long style = wxST_SIZEGRIP, const wxString& name = wxT("statusBar"))
 		: wxStatusBar(parent, id, style, name)
 	{
-		m_pProgressBar	= new wxGauge(this, ID_WND_PROGRESSBAR, 100);
+		m_pProgressBar	= new wxGauge(this, ID_WND_PROGRESSBAR, 100, wxDefaultPosition, wxDefaultSize, wxGA_HORIZONTAL|wxGA_SMOOTH);
 	}
 
-	void		On_Size		(wxSizeEvent     &event)
+	void		On_Size		(wxSizeEvent &event)
 	{
 		wxRect	r;
 
@@ -149,8 +150,6 @@ public:
 		{
 			m_pProgressBar->SetSize(r);
 		}
-
-		event.Skip();
 	}
 
 	wxGauge		*m_pProgressBar;
@@ -315,38 +314,43 @@ CSAGA_Frame::CSAGA_Frame(void)
 
 	wxString	s;
 
-	if( CONFIG_Read(wxT("/FL"), wxT("MANAGER"), s) )
+	if( CONFIG_Read("/FL", "MANAGER", s) )
 	{
 		m_pLayout->LoadPerspective(s);
 	}
 
 	_Bar_Show(m_pTB_Main, true);
 
-	//-----------------------------------------------------
 	m_pLayout->Update();
 
-#if !defined(_SAGA_LINUX)
-	Show(true);
-#endif
-
-	int		x, y, dx, dy;
+	//-----------------------------------------------------
 	long	l;
+	wxRect	r, rDefault	= wxGetClientDisplayRect();
 
-	x	= CONFIG_Read(wxT("/FL"), wxT("X" ), l) ? l : -1;
-	y	= CONFIG_Read(wxT("/FL"), wxT("Y" ), l) ? l : -1;
-	dx	= CONFIG_Read(wxT("/FL"), wxT("DX"), l) ? l : 800;
-	dy	= CONFIG_Read(wxT("/FL"), wxT("DY"), l) ? l : 600;
+	rDefault.Deflate((int)(0.1 * rDefault.GetWidth()), (int)(0.1 * rDefault.GetHeight()));
 
-	SetSize(x, y, dx, dy);
+	r.SetLeft  (CONFIG_Read("/FL", "X" , l) ? l : rDefault.GetLeft  ());
+	r.SetTop   (CONFIG_Read("/FL", "Y" , l) ? l : rDefault.GetTop   ());
+	r.SetWidth (CONFIG_Read("/FL", "DX", l) ? l : rDefault.GetWidth ());
+	r.SetHeight(CONFIG_Read("/FL", "DY", l) ? l : rDefault.GetHeight());
 
-	if( !(CONFIG_Read(wxT("/FL"), wxT("STATE"), l) && l == 0) )
+	if( wxDisplay::GetFromPoint(r.GetTopLeft    ()) == wxNOT_FOUND
+	&&  wxDisplay::GetFromPoint(r.GetTopRight   ()) == wxNOT_FOUND
+	&&  wxDisplay::GetFromPoint(r.GetBottomLeft ()) == wxNOT_FOUND
+	&&  wxDisplay::GetFromPoint(r.GetBottomRight()) == wxNOT_FOUND	)
+	{
+		r	= rDefault;
+	}
+
+	SetSize(r);
+
+	if( !(CONFIG_Read("/FL", "STATE", l) && l == 0) )
 	{
 		Maximize();
 	}
 
-#if defined(_SAGA_LINUX)
+	//-----------------------------------------------------
 	Show(true);
-#endif
 
 	Update();
 
@@ -365,19 +369,20 @@ CSAGA_Frame::~CSAGA_Frame(void)
 
 	if( IsMaximized() )
 	{
-		CONFIG_Write(wxT("/FL"), wxT("STATE"), (long)1);
+		CONFIG_Write("/FL", "STATE", (long)1);
 	}
 	else
 	{
-		CONFIG_Write(wxT("/FL"), wxT("STATE"), (long)0);
-		CONFIG_Write(wxT("/FL"), wxT("X"    ), (long)GetPosition().x);
-		CONFIG_Write(wxT("/FL"), wxT("Y"    ), (long)GetPosition().y);
-		CONFIG_Write(wxT("/FL"), wxT("DX"   ), (long)GetSize().x);
-		CONFIG_Write(wxT("/FL"), wxT("DY"   ), (long)GetSize().y);
+		CONFIG_Write("/FL", "STATE", (long)0);
+
+		CONFIG_Write("/FL", "X"    , (long)GetPosition().x);
+		CONFIG_Write("/FL", "Y"    , (long)GetPosition().y);
+		CONFIG_Write("/FL", "DX"   , (long)GetSize    ().x);
+		CONFIG_Write("/FL", "DY"   , (long)GetSize    ().y);
 	}
 
 	//-----------------------------------------------------
-	CONFIG_Write(wxT("/FL"), wxT("MANAGER"), m_pLayout->SavePerspective());
+	CONFIG_Write("/FL", "MANAGER", m_pLayout->SavePerspective());
 
 	m_pLayout->UnInit();
 
@@ -444,6 +449,13 @@ void CSAGA_Frame::On_Close(wxCloseEvent &event)
 //---------------------------------------------------------
 void CSAGA_Frame::On_Size(wxSizeEvent &event)
 {
+	if( wxDisplay::GetFromWindow(this) == wxNOT_FOUND )
+	{
+		wxRect	r	= wxGetClientDisplayRect();	r.Deflate((int)(0.1 * r.GetWidth()), (int)(0.1 * r.GetHeight()));
+
+		SetSize(r);
+	}
+
 	event.Skip();
 }
 
@@ -746,7 +758,7 @@ bool CSAGA_Frame::Process_Set_Okay(bool bOkay)
 {
 	StatusBar_Set_Text(_TL("ready"));
 
-	ProgressBar_Set_Position(-1);
+	m_pProgressBar->SetValue(0);
 
 	g_pSAGA->Process_Set_Okay(bOkay);
 
@@ -758,28 +770,26 @@ bool CSAGA_Frame::ProgressBar_Set_Position(int Position)
 {
 	if( Position < 0 )
 	{
-		m_pProgressBar->SetValue(0);
+		Position	= 0;
 	}
-	else
+	else if( Position > 100 )
 	{
-		if( Position > 100 )
-		{
-			Position	= 100;
-		}
+		Position	= 100;
+	}
 
-		if( m_pProgressBar->GetValue() != Position )
-		{
-			m_pProgressBar->SetValue(Position);
-		}
+	if( m_pProgressBar->GetValue() != Position )
+	{
+		m_pProgressBar->SetValue(Position);
+	//	m_pProgressBar->SetLabel(wxString::Format("%d%%", Position));
 	}
 
-	return( Process_Get_Okay(false) );
+	return( g_pSAGA->Process_Get_Okay() );
 }
 
 //---------------------------------------------------------
 bool CSAGA_Frame::ProgressBar_Set_Position(double Position, double Range)
 {
-	return( ProgressBar_Set_Position(Range != 0.0 ? (int)(100.0 * Position / Range) : 0) );
+	return( ProgressBar_Set_Position(Range < 0.0 ? 0 : (int)(0.5 + 100.0 * Position / Range)) );
 }
 
 //---------------------------------------------------------
@@ -1107,8 +1117,8 @@ wxToolBarBase * CSAGA_Frame::_Create_ToolBar(void)
 {
 	wxToolBarBase	*pToolBar	= TB_Create(ID_TB_MAIN);
 
-	CMD_ToolBar_Add_Item(pToolBar, false, ID_CMD_WKSP_OPEN);
-	CMD_ToolBar_Add_Item(pToolBar, false, ID_CMD_WKSP_SAVE);
+	CMD_ToolBar_Add_Item(pToolBar, false, ID_CMD_DATA_OPEN);
+	CMD_ToolBar_Add_Item(pToolBar, false, ID_CMD_DATA_PROJECT_SAVE);
 	CMD_ToolBar_Add_Separator(pToolBar);
 	CMD_ToolBar_Add_Item(pToolBar, true , ID_CMD_FRAME_WKSP_SHOW);
 	CMD_ToolBar_Add_Item(pToolBar, true , ID_CMD_FRAME_ACTIVE_SHOW);
diff --git a/src/saga_core/saga_gui/view_map.cpp b/src/saga_core/saga_gui/view_map.cpp
index 737564a..ee5995f 100644
--- a/src/saga_core/saga_gui/view_map.cpp
+++ b/src/saga_core/saga_gui/view_map.cpp
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: view_map.cpp 2066 2014-03-24 08:55:13Z oconrad $
+ * Version $Id: view_map.cpp 2681 2015-11-06 12:31:05Z oconrad $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -101,6 +101,7 @@ BEGIN_EVENT_TABLE(CVIEW_Map, CVIEW_Base)
 	EVT_MENU			(ID_CMD_MAP_GRATICULE_ADD				, CVIEW_Map::On_Map_Graticule)
 	EVT_MENU			(ID_CMD_MAP_SAVE_IMAGE					, CVIEW_Map::On_Map_Save_Image)
 	EVT_MENU			(ID_CMD_MAP_SAVE_IMAGE_ON_CHANGE		, CVIEW_Map::On_Map_Save_Image_On_Change)
+	EVT_MENU			(ID_CMD_MAPS_SAVE_IMAGE_TO_KMZ			, CVIEW_Map::On_Map_Save_Image_To_KMZ)
 	EVT_MENU			(ID_CMD_MAPS_SAVE_IMAGE_TO_MEMORY		, CVIEW_Map::On_Map_Save_Image_To_Memory)
 	EVT_MENU			(ID_CMD_MAPS_SAVE_TO_CLIPBOARD			, CVIEW_Map::On_Map_Save_Image_Clipboard)
 	EVT_MENU			(ID_CMD_MAPS_SAVE_TO_CLIPBOARD_LEGEND	, CVIEW_Map::On_Map_Save_Image_ClipboardL)
@@ -171,6 +172,8 @@ wxMenu * CVIEW_Map::_Create_Menu(void)
 	CMD_Menu_Add_Item(pMenu, false, ID_CMD_MAP_SAVE_IMAGE);
 //	CMD_Menu_Add_Item(pMenu, true , ID_CMD_MAP_SAVE_IMAGE_ON_CHANGE);
 	CMD_Menu_Add_Item(pMenu, false, ID_CMD_MAPS_SAVE_IMAGE_TO_MEMORY);
+	CMD_Menu_Add_Item(pMenu, false, ID_CMD_MAPS_SAVE_IMAGE_TO_KMZ);
+	pMenu->AppendSeparator();
 	CMD_Menu_Add_Item(pMenu, false, ID_CMD_MAPS_SAVE_TO_CLIPBOARD);
 	CMD_Menu_Add_Item(pMenu, false, ID_CMD_MAPS_SAVE_TO_CLIPBOARD_LEGEND);
 	pMenu->AppendSeparator();
@@ -484,6 +487,12 @@ void CVIEW_Map::On_Map_Save_Image_On_Change(wxCommandEvent &event)
 }
 
 //---------------------------------------------------------
+void CVIEW_Map::On_Map_Save_Image_To_KMZ(wxCommandEvent &event)
+{
+	m_pMap->SaveAs_Image_To_KMZ(m_pControl->GetClientSize().x, m_pControl->GetClientSize().y);
+}
+
+//---------------------------------------------------------
 void CVIEW_Map::On_Map_Save_Image_To_Memory(wxCommandEvent &event)
 {
 	m_pMap->SaveAs_Image_To_Memory(m_pControl->GetClientSize().x, m_pControl->GetClientSize().y);
diff --git a/src/saga_core/saga_gui/view_map.h b/src/saga_core/saga_gui/view_map.h
index c387651..f95576e 100644
--- a/src/saga_core/saga_gui/view_map.h
+++ b/src/saga_core/saga_gui/view_map.h
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: view_map.h 2061 2014-03-20 11:48:01Z oconrad $
+ * Version $Id: view_map.h 2681 2015-11-06 12:31:05Z oconrad $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -122,6 +122,7 @@ private:
 	void							On_Map_Layout_Show			(wxCommandEvent  &event);
 	void							On_Map_Save_Image			(wxCommandEvent  &event);
 	void							On_Map_Save_Image_On_Change	(wxCommandEvent  &event);
+	void							On_Map_Save_Image_To_KMZ	(wxCommandEvent  &event);
 	void							On_Map_Save_Image_To_Memory	(wxCommandEvent  &event);
 	void							On_Map_Save_Image_Clipboard	(wxCommandEvent  &event);
 	void							On_Map_Save_Image_ClipboardL(wxCommandEvent  &event);
diff --git a/src/saga_core/saga_gui/view_map_3d.cpp b/src/saga_core/saga_gui/view_map_3d.cpp
index 5a1088f..bd539b7 100644
--- a/src/saga_core/saga_gui/view_map_3d.cpp
+++ b/src/saga_core/saga_gui/view_map_3d.cpp
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: view_map_3d.cpp 2473 2015-04-21 16:03:37Z oconrad $
+ * Version $Id: view_map_3d.cpp 2684 2015-11-06 14:38:52Z oconrad $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -366,7 +366,18 @@ void CVIEW_Map_3D::On_Command(wxCommandEvent &event)
 	case ID_CMD_MAP3D_SEQ_POS_DEL_ALL:	m_pPanel->Play_Pos_Clr();	return;
 	case ID_CMD_MAP3D_SEQ_PLAY       :	m_pPanel->Play_Once   ();	return;
 	case ID_CMD_MAP3D_SEQ_PLAY_LOOP  :	m_pPanel->Play_Loop   ();	return;
-	case ID_CMD_MAP3D_SEQ_SAVE       :	m_pPanel->Play_Save   ();	return;
+	case ID_CMD_MAP3D_SEQ_SAVE       :
+		{
+			int			Type;
+			wxString	File;
+
+			if( DLG_Image_Save(File, Type) )
+			{
+				m_pPanel->m_Parameters("PLAY_FILE")->Set_Value(File.wc_str());
+				m_pPanel->Play_Save();
+			}
+		}
+		return;
 
 	//-----------------------------------------------------
 	case ID_CMD_MAP3D_ROTATE_X_LESS  :	m_pPanel->Get_Projector().Set_xRotation(m_pPanel->Get_Projector().Get_xRotation() + 4.0 * M_DEG_TO_RAD);	break;
diff --git a/src/saga_core/saga_gui/view_map_3d_panel.cpp b/src/saga_core/saga_gui/view_map_3d_panel.cpp
index c67af1f..056d9eb 100644
--- a/src/saga_core/saga_gui/view_map_3d_panel.cpp
+++ b/src/saga_core/saga_gui/view_map_3d_panel.cpp
@@ -120,16 +120,17 @@ void CView_Map_3DPanel::Update_Statistics(void)
 		Cellsize = m_pDEM->Get_Cellsize();
 
 	m_DEM.Create(CSG_Grid_System(Cellsize, r), SG_DATATYPE_Float);
+	m_DEM.Set_NoData_Value(m_pDEM->Get_NoData_Value());
 
 	for(int y=0; y<m_DEM.Get_NY(); y++)
 	{
-		int	wy	= m_DEM.Get_YMin() + m_DEM.Get_Cellsize() * y;
+		double	wy	= m_DEM.Get_YMin() + y * m_DEM.Get_Cellsize();
 
 		for(int x=0; x<m_DEM.Get_NX(); x++)
 		{
-			double	z;
+			double	z, wx	= m_DEM.Get_XMin() + x * m_DEM.Get_Cellsize();
 
-			if( m_pDEM->Get_Value(m_DEM.Get_XMin() + m_DEM.Get_Cellsize() * x, wy, z) )
+			if( m_pDEM->Get_Value(wx, wy, z, GRID_INTERPOLATION_BSpline, false, true) )
 			{
 				m_DEM.Set_Value(x, y, z);
 			}
diff --git a/src/saga_core/saga_gui/view_map_control.cpp b/src/saga_core/saga_gui/view_map_control.cpp
index 3337fad..8532ad1 100644
--- a/src/saga_core/saga_gui/view_map_control.cpp
+++ b/src/saga_core/saga_gui/view_map_control.cpp
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: view_map_control.cpp 2548 2015-08-13 13:07:55Z oconrad $
+ * Version $Id: view_map_control.cpp 2735 2015-12-16 17:47:02Z oconrad $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -661,10 +661,29 @@ void CVIEW_Map_Control::On_Key_Down(wxKeyEvent &event)
 //---------------------------------------------------------
 void CVIEW_Map_Control::On_Mouse_LDown(wxMouseEvent &event)
 {
-	bool	bCaptureMouse	= true;
-
 	m_Mouse_Down	= m_Mouse_Move	= event.GetPosition();
 
+	//-----------------------------------------------------
+	if( m_Mode != MAP_MODE_SELECT )	// clipboard copy ?
+	{
+		if( event.ControlDown() )
+		{
+			m_pMap->SaveAs_Image_Clipboard(false);
+
+			return;
+		}
+
+		if( event.AltDown() )
+		{
+			m_pMap->SaveAs_Image_Clipboard(GetClientSize().x, GetClientSize().y, -1);
+
+			return;
+		}
+	}
+
+	//-----------------------------------------------------
+	bool	bCaptureMouse	= true;
+
 	switch( m_Mode )
 	{
 	//-----------------------------------------------------
@@ -683,6 +702,7 @@ void CVIEW_Map_Control::On_Mouse_LDown(wxMouseEvent &event)
 				break;
 
 			case WKSP_ITEM_Grid:
+			case WKSP_ITEM_PointCloud:
 				m_Drag_Mode		= MODULE_INTERACTIVE_DRAG_BOX;
 				break;
 
@@ -736,6 +756,13 @@ void CVIEW_Map_Control::On_Mouse_LUp(wxMouseEvent &event)
 		ReleaseMouse();
 	}
 
+	//-----------------------------------------------------
+	if( m_Mode != MAP_MODE_SELECT && (event.ControlDown() || event.AltDown()) )	// clipboard copy ?
+	{
+		return;
+	}
+
+	//-----------------------------------------------------
 	_Draw_Inverse(m_Mouse_Down, event.GetPosition());
 	m_Drag_Mode	= MODULE_INTERACTIVE_DRAG_NONE;
 
@@ -789,19 +816,7 @@ void CVIEW_Map_Control::On_Mouse_LDClick(wxMouseEvent &event)
 		break;
 
 	//-----------------------------------------------------
-	case MAP_MODE_DISTANCE:
-		break;
-
-	//-----------------------------------------------------
-	case MAP_MODE_ZOOM:
-		break;
-
-	//-----------------------------------------------------
-	case MAP_MODE_PAN:
-		break;
-
-	//-----------------------------------------------------
-	case MAP_MODE_PAN_DOWN:
+	default:
 		break;
 	}
 }
@@ -816,6 +831,8 @@ void CVIEW_Map_Control::On_Mouse_LDClick(wxMouseEvent &event)
 //---------------------------------------------------------
 void CVIEW_Map_Control::On_Mouse_RDown(wxMouseEvent &event)
 {
+	m_pParent->Activate();
+
 	m_Mouse_Down	= m_Mouse_Move	= event.GetPosition();
 
 	_Draw_Inverse(m_Mouse_Down, event.GetPosition());
@@ -836,20 +853,7 @@ void CVIEW_Map_Control::On_Mouse_RDown(wxMouseEvent &event)
 		break;
 
 	//-----------------------------------------------------
-	case MAP_MODE_DISTANCE:
-		_Distance_Reset();
-		break;
-
-	//-----------------------------------------------------
-	case MAP_MODE_ZOOM:
-		break;
-
-	//-----------------------------------------------------
-	case MAP_MODE_PAN:
-		break;
-
-	//-----------------------------------------------------
-	case MAP_MODE_PAN_DOWN:
+	default:
 		break;
 	}
 }
@@ -869,34 +873,51 @@ void CVIEW_Map_Control::On_Mouse_RUp(wxMouseEvent &event)
 		{
 			g_pModule->Execute(_Get_World(event.GetPosition()), MODULE_INTERACTIVE_RUP, GET_KEYS(event));
 		}
-		else if( m_pMap->Find_Layer(Get_Active_Layer()) )
+		else if( m_pMap->Find_Layer(Get_Active_Layer()) && !Get_Active_Layer()->Edit_On_Mouse_Up(_Get_World(event.GetPosition()), _Get_World(1.0), GET_KEYS(event)|MODULE_INTERACTIVE_KEY_RIGHT) )
 		{
-			if(	!Get_Active_Layer()->Edit_On_Mouse_Up(_Get_World(event.GetPosition()), _Get_World(1.0), GET_KEYS(event)|MODULE_INTERACTIVE_KEY_RIGHT)
-			&&	(pMenu = Get_Active_Layer()->Edit_Get_Menu()) != NULL )
-			{
-				PopupMenu(pMenu, event.GetPosition());
-
-				delete(pMenu);
-			}
+			pMenu	= Get_Active_Layer()->Edit_Get_Menu();
+		}
+		else
+		{
+			pMenu	= m_pParent->_Create_Menu();
 		}
 		break;
 
 	//-----------------------------------------------------
 	case MAP_MODE_DISTANCE:
+		if( event.ControlDown() )	// context menu
+		{
+			pMenu	= m_pParent->_Create_Menu();
+		}
+		else	// reset
+		{
+			_Distance_Reset();
+		}
 		break;
 
-	//-----------------------------------------------------
 	case MAP_MODE_ZOOM:
-		_Zoom(_Get_World(event.GetPosition()), false);
+		if( event.ControlDown() )	// context menu
+		{
+			pMenu	= m_pParent->_Create_Menu();
+		}
+		else	// zoom out
+		{
+			_Zoom(_Get_World(event.GetPosition()), false);
+		}
 		break;
 
 	//-----------------------------------------------------
-	case MAP_MODE_PAN:
+	default:
+		pMenu	= m_pParent->_Create_Menu();
 		break;
+	}
 
 	//-----------------------------------------------------
-	case MAP_MODE_PAN_DOWN:
-		break;
+	if( pMenu != NULL )
+	{
+		PopupMenu(pMenu, event.GetPosition());
+
+		delete(pMenu);
 	}
 }
 
diff --git a/src/saga_core/saga_gui/view_table.cpp b/src/saga_core/saga_gui/view_table.cpp
index 165d6a1..4e5ae44 100644
--- a/src/saga_core/saga_gui/view_table.cpp
+++ b/src/saga_core/saga_gui/view_table.cpp
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: view_table.cpp 2067 2014-03-24 10:53:19Z oconrad $
+ * Version $Id: view_table.cpp 2698 2015-11-24 13:45:01Z oconrad $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -86,27 +86,8 @@ IMPLEMENT_CLASS(CVIEW_Table, CVIEW_Base);
 
 //---------------------------------------------------------
 BEGIN_EVENT_TABLE(CVIEW_Table, CVIEW_Base)
-	EVT_MENU					(ID_CMD_TABLE_FIELD_ADD			, CVIEW_Table::On_Field_Add)
-	EVT_UPDATE_UI				(ID_CMD_TABLE_FIELD_ADD			, CVIEW_Table::On_Field_Add_UI)
-	EVT_MENU					(ID_CMD_TABLE_FIELD_DEL			, CVIEW_Table::On_Field_Del)
-	EVT_UPDATE_UI				(ID_CMD_TABLE_FIELD_DEL			, CVIEW_Table::On_Field_Del_UI)
-	EVT_MENU					(ID_CMD_TABLE_FIELD_SORT		, CVIEW_Table::On_Field_Sort)
-	EVT_UPDATE_UI				(ID_CMD_TABLE_FIELD_SORT		, CVIEW_Table::On_Field_Sort_UI)
-	EVT_MENU					(ID_CMD_TABLE_FIELD_RENAME		, CVIEW_Table::On_Field_Rename)
-	EVT_UPDATE_UI				(ID_CMD_TABLE_FIELD_RENAME		, CVIEW_Table::On_Field_Rename_UI)
-	EVT_MENU					(ID_CMD_TABLE_FIELD_TYPE		, CVIEW_Table::On_Field_Type)
-	EVT_UPDATE_UI				(ID_CMD_TABLE_FIELD_TYPE		, CVIEW_Table::On_Field_Type_UI)
-
-	EVT_MENU					(ID_CMD_TABLE_RECORD_ADD		, CVIEW_Table::On_Record_Add)
-	EVT_UPDATE_UI				(ID_CMD_TABLE_RECORD_ADD		, CVIEW_Table::On_Record_Add_UI)
-	EVT_MENU					(ID_CMD_TABLE_RECORD_INS		, CVIEW_Table::On_Record_Ins)
-	EVT_UPDATE_UI				(ID_CMD_TABLE_RECORD_INS		, CVIEW_Table::On_Record_Ins_UI)
-	EVT_MENU					(ID_CMD_TABLE_RECORD_DEL		, CVIEW_Table::On_Record_Del)
-	EVT_UPDATE_UI				(ID_CMD_TABLE_RECORD_DEL		, CVIEW_Table::On_Record_Del_UI)
-	EVT_MENU					(ID_CMD_TABLE_RECORD_DEL_ALL	, CVIEW_Table::On_Record_Clr)
-	EVT_UPDATE_UI				(ID_CMD_TABLE_RECORD_DEL_ALL	, CVIEW_Table::On_Record_Clr_UI)
-	EVT_MENU					(ID_CMD_TABLE_SELECTION_TO_TOP	, CVIEW_Table::On_Sel_To_Top)
-	EVT_UPDATE_UI				(ID_CMD_TABLE_SELECTION_TO_TOP	, CVIEW_Table::On_Sel_To_Top_UI)
+	EVT_MENU_RANGE		(ID_CMD_TABLE_FIRST, ID_CMD_TABLE_LAST, CVIEW_Table::On_Command)
+	EVT_UPDATE_UI_RANGE	(ID_CMD_TABLE_FIRST, ID_CMD_TABLE_LAST, CVIEW_Table::On_Command_UI)
 END_EVENT_TABLE()
 
 
@@ -193,113 +174,33 @@ void CVIEW_Table::Update_Selection(void)
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
-void CVIEW_Table::On_Field_Add(wxCommandEvent &event)
+void CVIEW_Table::On_Command(wxCommandEvent &event)
 {
-	m_pControl->On_Field_Add(event);
-}
-
-void CVIEW_Table::On_Field_Add_UI(wxUpdateUIEvent &event)
-{
-	m_pControl->On_Field_Add_UI(event);
-}
-
-//---------------------------------------------------------
-void CVIEW_Table::On_Field_Del(wxCommandEvent &event)
-{
-	m_pControl->On_Field_Del(event);
-}
-
-void CVIEW_Table::On_Field_Del_UI(wxUpdateUIEvent &event)
-{
-	m_pControl->On_Field_Del_UI(event);
-}
-
-//---------------------------------------------------------
-void CVIEW_Table::On_Field_Sort(wxCommandEvent &event)
-{
-	m_pControl->On_Field_Sort(event);
-}
-
-void CVIEW_Table::On_Field_Sort_UI(wxUpdateUIEvent &event)
-{
-	m_pControl->On_Field_Sort_UI(event);
-}
-
-//---------------------------------------------------------
-void CVIEW_Table::On_Field_Rename(wxCommandEvent &event)
-{
-	m_pControl->On_Field_Rename(event);
-}
-
-void CVIEW_Table::On_Field_Rename_UI(wxUpdateUIEvent &event)
-{
-	m_pControl->On_Field_Rename_UI(event);
-}
-
-//---------------------------------------------------------
-void CVIEW_Table::On_Field_Type(wxCommandEvent &event)
-{
-	m_pControl->On_Field_Type(event);
-}
-
-void CVIEW_Table::On_Field_Type_UI(wxUpdateUIEvent &event)
-{
-	m_pControl->On_Field_Type_UI(event);
+	switch( event.GetId() )
+	{
+	case ID_CMD_TABLE_FIELD_ADD     :
+	case ID_CMD_TABLE_FIELD_DEL     :
+	case ID_CMD_TABLE_RECORD_ADD    :
+	case ID_CMD_TABLE_RECORD_INS    :
+	case ID_CMD_TABLE_RECORD_DEL    :
+	case ID_CMD_TABLE_RECORD_DEL_ALL:
+		m_pControl->ProcessWindowEvent(event);
+	}
 }
 
 //---------------------------------------------------------
-void CVIEW_Table::On_Record_Add(wxCommandEvent &event)
-{
-	m_pControl->On_Record_Add(event);
-}
-
-void CVIEW_Table::On_Record_Add_UI(wxUpdateUIEvent &event)
-{
-	m_pControl->On_Record_Add_UI(event);
-}
-
-//---------------------------------------------------------
-void CVIEW_Table::On_Record_Ins(wxCommandEvent &event)
-{
-	m_pControl->On_Record_Ins(event);
-}
-
-void CVIEW_Table::On_Record_Ins_UI(wxUpdateUIEvent &event)
-{
-	m_pControl->On_Record_Ins_UI(event);
-}
-
-//---------------------------------------------------------
-void CVIEW_Table::On_Record_Del(wxCommandEvent &event)
-{
-	m_pControl->On_Record_Del(event);
-}
-
-void CVIEW_Table::On_Record_Del_UI(wxUpdateUIEvent &event)
-{
-	m_pControl->On_Record_Del_UI(event);
-}
-
-//---------------------------------------------------------
-void CVIEW_Table::On_Record_Clr(wxCommandEvent &event)
-{
-	m_pControl->On_Record_Clr(event);
-}
-
-void CVIEW_Table::On_Record_Clr_UI(wxUpdateUIEvent &event)
-{
-	m_pControl->On_Record_Clr_UI(event);
-}
-
-//---------------------------------------------------------
-void CVIEW_Table::On_Sel_To_Top(wxCommandEvent &event)
-{
-	m_pControl->On_Sel_To_Top(event);
-}
-
-void CVIEW_Table::On_Sel_To_Top_UI(wxUpdateUIEvent &event)
+void CVIEW_Table::On_Command_UI(wxUpdateUIEvent &event)
 {
-	m_pControl->On_Sel_To_Top_UI(event);
+	switch( event.GetId() )
+	{
+	case ID_CMD_TABLE_FIELD_ADD     :
+	case ID_CMD_TABLE_FIELD_DEL     :
+	case ID_CMD_TABLE_RECORD_ADD    :
+	case ID_CMD_TABLE_RECORD_INS    :
+	case ID_CMD_TABLE_RECORD_DEL    :
+	case ID_CMD_TABLE_RECORD_DEL_ALL:
+		m_pControl->ProcessWindowEvent(event);
+	}
 }
 
 
diff --git a/src/saga_core/saga_gui/view_table.h b/src/saga_core/saga_gui/view_table.h
index 34292eb..cd2e270 100644
--- a/src/saga_core/saga_gui/view_table.h
+++ b/src/saga_core/saga_gui/view_table.h
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: view_table.h 2061 2014-03-20 11:48:01Z oconrad $
+ * Version $Id: view_table.h 2698 2015-11-24 13:45:01Z oconrad $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -97,32 +97,11 @@ public:
 
 private:
 
-	class CWKSP_Table				*m_pTable;
-
 	class CVIEW_Table_Control		*m_pControl;
 
 
-	void							On_Field_Add		(wxCommandEvent  &event);
-	void							On_Field_Add_UI		(wxUpdateUIEvent &event);
-	void							On_Field_Del		(wxCommandEvent  &event);
-	void							On_Field_Del_UI		(wxUpdateUIEvent &event);
-	void							On_Field_Sort		(wxCommandEvent  &event);
-	void							On_Field_Sort_UI	(wxUpdateUIEvent &event);
-	void							On_Field_Rename		(wxCommandEvent  &event);
-	void							On_Field_Rename_UI	(wxUpdateUIEvent &event);
-	void							On_Field_Type		(wxCommandEvent  &event);
-	void							On_Field_Type_UI	(wxUpdateUIEvent &event);
-
-	void							On_Record_Add		(wxCommandEvent  &event);
-	void							On_Record_Add_UI	(wxUpdateUIEvent &event);
-	void							On_Record_Ins		(wxCommandEvent  &event);
-	void							On_Record_Ins_UI	(wxUpdateUIEvent &event);
-	void							On_Record_Del		(wxCommandEvent  &event);
-	void							On_Record_Del_UI	(wxUpdateUIEvent &event);
-	void							On_Record_Clr		(wxCommandEvent  &event);
-	void							On_Record_Clr_UI	(wxUpdateUIEvent &event);
-	void							On_Sel_To_Top		(wxCommandEvent  &event);
-	void							On_Sel_To_Top_UI	(wxUpdateUIEvent &event);
+	void							On_Command			(wxCommandEvent  &event);
+	void							On_Command_UI		(wxUpdateUIEvent &event);
 
 
 	//-----------------------------------------------------
diff --git a/src/saga_core/saga_gui/view_table_control.cpp b/src/saga_core/saga_gui/view_table_control.cpp
index 530b4b9..0698fb7 100644
--- a/src/saga_core/saga_gui/view_table_control.cpp
+++ b/src/saga_core/saga_gui/view_table_control.cpp
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: view_table_control.cpp 2355 2014-12-19 09:55:41Z reklov_w $
+ * Version $Id: view_table_control.cpp 2730 2015-12-16 11:55:46Z oconrad $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -62,15 +62,13 @@
 
 //---------------------------------------------------------
 #include <wx/window.h>
+#include <wx/filename.h>
 
 #include <saga_api/saga_api.h>
 
 #include "res_commands.h"
 #include "res_dialogs.h"
 
-#include "active.h"
-#include "active_attributes.h"
-
 #include "helper.h"
 
 #include "wksp_data_manager.h"
@@ -85,34 +83,37 @@
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
-#define FIXED_COLS		((m_Constraint & TABLE_CTRL_FIXED_COLS)   != 0)
-#define FIXED_ROWS		((m_Constraint & TABLE_CTRL_FIXED_ROWS)   != 0)
-#define LABEL_COL		((m_Constraint & TABLE_CTRL_COL1ISLABEL)  != 0)
-
-
-///////////////////////////////////////////////////////////
-//														 //
-//														 //
-//														 //
-///////////////////////////////////////////////////////////
-
-//---------------------------------------------------------
 IMPLEMENT_CLASS(CVIEW_Table_Control, wxGrid)
 
 //---------------------------------------------------------
 BEGIN_EVENT_TABLE(CVIEW_Table_Control, wxGrid)
-	EVT_SIZE					(CVIEW_Table_Control::On_Size)
 	EVT_KEY_DOWN				(CVIEW_Table_Control::On_Key)
+	EVT_SCROLLWIN				(CVIEW_Table_Control::On_Scroll)
+	EVT_SIZE					(CVIEW_Table_Control::On_Size)
 
 	EVT_GRID_EDITOR_SHOWN		(CVIEW_Table_Control::On_Edit_Start)
 	EVT_GRID_EDITOR_HIDDEN		(CVIEW_Table_Control::On_Edit_Stop)
 	EVT_GRID_CELL_CHANGED		(CVIEW_Table_Control::On_Changed)
+
 	EVT_GRID_CELL_LEFT_CLICK	(CVIEW_Table_Control::On_LClick)
+	EVT_GRID_CELL_RIGHT_CLICK	(CVIEW_Table_Control::On_RClick)
 	EVT_GRID_LABEL_LEFT_CLICK	(CVIEW_Table_Control::On_LClick_Label)
 	EVT_GRID_LABEL_LEFT_DCLICK	(CVIEW_Table_Control::On_LDClick_Label)
 	EVT_GRID_LABEL_RIGHT_CLICK	(CVIEW_Table_Control::On_RClick_Label)
+
 	EVT_GRID_RANGE_SELECT		(CVIEW_Table_Control::On_Select)
 
+	EVT_MENU					(ID_CMD_TABLE_SELECTION_ONLY	, CVIEW_Table_Control::On_Sel_Only)
+	EVT_UPDATE_UI				(ID_CMD_TABLE_SELECTION_ONLY	, CVIEW_Table_Control::On_Sel_Only_UI)
+	EVT_MENU					(ID_CMD_TABLE_SELECTION_CLEAR	, CVIEW_Table_Control::On_Sel_Clear)
+	EVT_UPDATE_UI				(ID_CMD_TABLE_SELECTION_CLEAR	, CVIEW_Table_Control::On_Sel_Clear_UI)
+
+	EVT_MENU					(ID_CMD_TABLE_AUTOSIZE_COLS		, CVIEW_Table_Control::On_Autosize_Cols)
+	EVT_MENU					(ID_CMD_TABLE_AUTOSIZE_ROWS		, CVIEW_Table_Control::On_Autosize_Rows)
+
+	EVT_MENU					(ID_CMD_TABLE_FIELD_OPEN_APP	, CVIEW_Table_Control::On_Cell_Open)
+	EVT_MENU					(ID_CMD_TABLE_FIELD_OPEN_DATA	, CVIEW_Table_Control::On_Cell_Open)
+
 	EVT_MENU					(ID_CMD_TABLE_FIELD_ADD			, CVIEW_Table_Control::On_Field_Add)
 	EVT_UPDATE_UI				(ID_CMD_TABLE_FIELD_ADD			, CVIEW_Table_Control::On_Field_Add_UI)
 	EVT_MENU					(ID_CMD_TABLE_FIELD_DEL			, CVIEW_Table_Control::On_Field_Del)
@@ -132,15 +133,6 @@ BEGIN_EVENT_TABLE(CVIEW_Table_Control, wxGrid)
 	EVT_UPDATE_UI				(ID_CMD_TABLE_RECORD_DEL		, CVIEW_Table_Control::On_Record_Del_UI)
 	EVT_MENU					(ID_CMD_TABLE_RECORD_DEL_ALL	, CVIEW_Table_Control::On_Record_Clr)
 	EVT_UPDATE_UI				(ID_CMD_TABLE_RECORD_DEL_ALL	, CVIEW_Table_Control::On_Record_Clr_UI)
-
-	EVT_MENU					(ID_CMD_TABLE_SELECTION_ONLY	, CVIEW_Table_Control::On_Sel_Only)
-	EVT_UPDATE_UI				(ID_CMD_TABLE_SELECTION_ONLY	, CVIEW_Table_Control::On_Sel_Only_UI)
-
-	EVT_MENU					(ID_CMD_TABLE_SELECTION_TO_TOP	, CVIEW_Table_Control::On_Sel_To_Top)
-	EVT_UPDATE_UI				(ID_CMD_TABLE_SELECTION_TO_TOP	, CVIEW_Table_Control::On_Sel_To_Top_UI)
-
-	EVT_MENU					(ID_CMD_TABLE_AUTOSIZE_COLS		, CVIEW_Table_Control::On_Autosize_Cols)
-	EVT_MENU					(ID_CMD_TABLE_AUTOSIZE_ROWS		, CVIEW_Table_Control::On_Autosize_Rows)
 END_EVENT_TABLE()
 
 
@@ -155,85 +147,61 @@ CVIEW_Table_Control::CVIEW_Table_Control(wxWindow *pParent, CSG_Table *pTable, i
 	: wxGrid(pParent, -1, wxDefaultPosition, wxDefaultSize, wxWANTS_CHARS|wxSUNKEN_BORDER)
 {
 	m_pTable		= pTable;
-	m_pRecords		= NULL;
-	m_Constraint	= Constraint;
+
 	m_bSelOnly		= false;
 	m_bEditing		= false;
 
-	Set_Labeling(false);
+	m_Cursor		= -1;
+
+	m_Scroll_Start	= 0;
+	m_Scroll_Range	= 0;
+
+	SetRowLabelAlignment(wxALIGN_RIGHT, wxALIGN_CENTRE);
 
-	CreateGrid(m_pTable->Get_Record_Count(), m_pTable->Get_Field_Count(), wxGrid::wxGridSelectRows);
+	DisableDragRowSize();
+
+	CreateGrid(0, 0, wxGrid::wxGridSelectRows);
 
 	Update_Table();
 }
 
 //---------------------------------------------------------
 CVIEW_Table_Control::~CVIEW_Table_Control(void)
-{
-	if( m_pRecords )
-	{
-		SG_Free(m_pRecords);
-	}
-}
+{}
 
 
 ///////////////////////////////////////////////////////////
 //														 //
-//														 //
-//														 //
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
-void CVIEW_Table_Control::Set_Labeling(bool bOn)
+bool CVIEW_Table_Control::Load(const wxString &File_Name)
 {
-	if( bOn && m_Field_Offset == 0 )
-	{
-		m_Field_Offset	= 1;
-
-		SetRowLabelAlignment(wxALIGN_RIGHT, wxALIGN_CENTRE);
-	}
-	else if( !bOn && m_Field_Offset != 0 )
-	{
-		m_Field_Offset	= 0;
-
-		SetRowLabelAlignment(wxALIGN_CENTRE, wxALIGN_CENTRE);
+	CSG_Table	Table(&File_Name);
 
-		Freeze();
+	bool	bResult	= Table.Get_Count() > 0
+		&& Table.Get_Field_Count() == m_pTable->Get_Field_Count()
+		&& m_pTable->Assign_Values(&Table)
+		&& Update_Table();
 
-		for(int i=0; i<GetRows(); i++)
-		{
-			SetRowLabelValue(i, wxString::Format("%d", 1 + i));
-		}
+	PROCESS_Set_Okay();
 
-		Thaw();
-	}
+	return( bResult );
 }
 
-
-///////////////////////////////////////////////////////////
-//														 //
-//														 //
-//														 //
-///////////////////////////////////////////////////////////
-
 //---------------------------------------------------------
-void CVIEW_Table_Control::_Update_Views(void)
+bool CVIEW_Table_Control::Save(const wxString &File_Name, int Format)
 {
-	if( GetBatchCount() == 0 )
-	{
-		BeginBatch();
+	bool	bResult	= m_pTable->Save(&File_Name);
 
-		g_pData->Update_Views(m_pTable);
+	PROCESS_Set_Okay();
 
-		EndBatch();
-	}
+	return( bResult );
 }
 
 
 ///////////////////////////////////////////////////////////
 //														 //
-//														 //
-//														 //
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
@@ -247,21 +215,21 @@ bool CVIEW_Table_Control::Update_Table(void)
 	BeginBatch();
 
 	//-----------------------------------------------------
-	int	Difference	= (m_pTable->Get_Field_Count() - m_Field_Offset) - GetNumberCols();
+	int	Difference;
 
-	if( Difference > 0 )
+	if( (Difference = (m_pTable->Get_Field_Count()) - GetNumberCols()) > 0 )
 	{
 		AppendCols(Difference);
 	}
-	else if( (Difference = -Difference < GetNumberCols() ? -Difference : GetNumberCols()) > 0 )
+	else if( Difference < 0 && (Difference = -Difference < GetNumberCols() ? -Difference : GetNumberCols()) > 0 )
 	{	// here is (or was!?) a memory leak - solution: use own wxGridTableBase derived grid table class
 		DeleteCols(0, Difference);
 	}
 
 	//-----------------------------------------------------
-	for(int iCol=0, iField=m_Field_Offset; iField<m_pTable->Get_Field_Count(); iCol++, iField++)
+	for(int iField=0; iField<m_pTable->Get_Field_Count(); iField++)
 	{
-		SetColLabelValue(iCol, m_pTable->Get_Field_Name(iField));
+		SetColLabelValue(iField, m_pTable->Get_Field_Name(iField));
 
 		switch( m_pTable->Get_Field_Type(iField) )
 		{
@@ -271,7 +239,7 @@ bool CVIEW_Table_Control::Update_Table(void)
 		case SG_DATATYPE_String:
 		case SG_DATATYPE_Date:
 		case SG_DATATYPE_Binary:
-			SetColFormatCustom(iCol, wxGRID_VALUE_STRING);
+			SetColFormatCustom(iField, wxGRID_VALUE_STRING);
 			break;
 
 		case SG_DATATYPE_Bit:
@@ -282,36 +250,51 @@ bool CVIEW_Table_Control::Update_Table(void)
 		case SG_DATATYPE_ULong:
 		case SG_DATATYPE_Long:
 		case SG_DATATYPE_Color:
-			SetColFormatNumber(iCol);
+			SetColFormatNumber(iField);
 			break;
 
 		case SG_DATATYPE_Float:
 		case SG_DATATYPE_Double:
-			SetColFormatFloat(iCol);
+			SetColFormatFloat(iField);
 			break;
 		}
 	}
 
 	//-----------------------------------------------------
+	if( _Update_Records() )
+	{
+		EndBatch();
+
+		return( true );
+	}
+
 	EndBatch();
 
-	return( _Set_Records() );
+	return( false );
 }
 
+
+///////////////////////////////////////////////////////////
+//														 //
+///////////////////////////////////////////////////////////
+
 //---------------------------------------------------------
-bool CVIEW_Table_Control::_Set_Records(bool bSelection_To_Top)
+bool CVIEW_Table_Control::_Update_Records(void)
 {
 	BeginBatch();
 
 	//-----------------------------------------------------
-	if( m_bSelOnly && m_pTable->Get_Selection_Count() <= 0 )
+	int	nRows	= _Get_Record_Count();
+
+	if( nRows > m_Scroll_Range )
 	{
-		m_bSelOnly	= false;
+		nRows	= m_Scroll_Range;
 	}
 
-	int	Difference, nRecords	= m_bSelOnly ? m_pTable->Get_Selection_Count() : m_pTable->Get_Count();
+	//-----------------------------------------------------
+	int	Difference;
 
-	if( (Difference = nRecords - GetNumberRows()) > 0 )
+	if( (Difference = nRows - GetNumberRows()) > 0 )
 	{
 		AppendRows(Difference);
 	}
@@ -320,82 +303,114 @@ bool CVIEW_Table_Control::_Set_Records(bool bSelection_To_Top)
 		DeleteRows(0, Difference);
 	}
 
-	m_pRecords	= (CSG_Table_Record **)SG_Realloc(m_pRecords, nRecords * sizeof(CSG_Table_Record *));
+	//-----------------------------------------------------
+	m_Scroll_Start	= _Get_Scroll_Start(m_Scroll_Start);
 
 	ClearSelection();
 
-	//-----------------------------------------------------
-	if( m_bSelOnly )
-	{
-	//	#pragma omp parallel for
-		for(int iRecord=0; iRecord<nRecords; iRecord++)
-		{
-			_Set_Record(iRecord, m_pTable->Get_Selection(iRecord));
-		}
-	}
-	else if( !bSelection_To_Top )
+	for(int iRow=0; iRow<nRows; iRow++)
 	{
-	//	#pragma omp parallel for
-		for(int iRecord=0; iRecord<nRecords; iRecord++)
-		{
-			_Set_Record(iRecord, m_pTable->Get_Record_byIndex(iRecord));
-		}
+		_Set_Record(iRow);
 	}
-	else // if( bSelection_To_Top && m_pTable->Get_Selection_Count() > 0 )
+
+	//-----------------------------------------------------
+	_Update_Views();
+
+	EndBatch();
+
+	return( true );
+}
+
+//---------------------------------------------------------
+inline int CVIEW_Table_Control::_Get_Record_Count(void)
+{
+	return( m_bSelOnly ? m_pTable->Get_Selection_Count() : m_pTable->Get_Count() );
+}
+
+//---------------------------------------------------------
+inline CSG_Table_Record * CVIEW_Table_Control::_Get_Record(int iRow)
+{
+	return( m_bSelOnly ? m_pTable->Get_Selection(m_Scroll_Start + iRow) : m_pTable->Get_Record_byIndex(m_Scroll_Start + iRow) );
+}
+
+//---------------------------------------------------------
+bool CVIEW_Table_Control::_Set_Record(int iRow)
+{
+	CSG_Table_Record	*pRecord	= _Get_Record(iRow);
+
+	if( pRecord )
 	{
-		for(int iRecord=0, iSel=0, iNoSel=m_pTable->Get_Selection_Count(); iRecord<nRecords && PROGRESSBAR_Set_Position(iRecord, nRecords); iRecord++)
-		{
-			CSG_Table_Record	*pRecord	= m_pTable->Get_Record_byIndex(iRecord);
+		SetRowLabelValue(iRow, wxString::Format("%d", 1 + m_Scroll_Start + iRow));
 
-			if( pRecord->is_Selected() )
-			{
-				_Set_Record(iSel  ++, pRecord);
-			}
-			else
+		for(int iField=0; iField<m_pTable->Get_Field_Count(); iField++)
+		{
+			switch( m_pTable->Get_Field_Type(iField) )
 			{
-				_Set_Record(iNoSel++, pRecord);
+			default:
+				SetCellValue(iRow, iField, pRecord->is_NoData(iField) ? SG_T("") : pRecord->asString(iField));
+				break;
+
+			case SG_DATATYPE_Color:
+				SetCellBackgroundColour(iRow, iField, Get_Color_asWX(pRecord->asInt(iField)));
+				break;
 			}
 		}
 
-		PROCESS_Set_Okay();
+		if( m_bSelOnly || pRecord->is_Selected() )
+		{
+			SelectRow(iRow, true);
+		}
+
+		return( true );
 	}
 
-	//-----------------------------------------------------
-	EndBatch();
+	return( false );
+}
 
-	_Update_Views();
 
-	return( true );
-}
+///////////////////////////////////////////////////////////
+//														 //
+///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
-bool CVIEW_Table_Control::_Set_Record(int iRecord, CSG_Table_Record *pRecord)
+bool CVIEW_Table_Control::Update_Selection(void)
 {
-	m_pRecords[iRecord]	= pRecord;
-
-	if( m_Field_Offset )
+	if( GetBatchCount() > 0 )
 	{
-		SetRowLabelValue(iRecord, pRecord->asString(0));
+		return( false );
 	}
 
-	for(int iCol=0, iField=m_Field_Offset; iField<m_pTable->Get_Field_Count(); iCol++, iField++)
+	BeginBatch();
+
+	//-----------------------------------------------------
+	if( m_bSelOnly )
 	{
-		switch( m_pTable->Get_Field_Type(iField) )
+		_Update_Records();
+	}
+	else if( m_pTable->Get_Selection_Count() >= m_pTable->Get_Count() )
+	{
+		SelectAll();
+	}
+	else
+	{
+		ClearSelection();
+
+		if( m_pTable->Get_Selection_Count() > 0 )
 		{
-		default:
-			SetCellValue(iRecord, iCol, pRecord->is_NoData(iField) ? SG_T("") : pRecord->asString(iField));
-			break;
+			for(int iRow=0; iRow<GetNumberRows(); iRow++)
+			{
+				CSG_Table_Record	*pRecord	= _Get_Record(iRow);
 
-		case SG_DATATYPE_Color:
-			SetCellBackgroundColour(iRecord, iCol, Get_Color_asWX(pRecord->asInt(iField)));
-			break;
+				if( pRecord && pRecord->is_Selected() )
+				{
+					SelectRow(iRow, true);
+				}
+			}
 		}
 	}
 
-	if( pRecord->is_Selected() )
-	{
-		SelectRow(iRecord, true);
-	}
+	//-----------------------------------------------------
+	EndBatch();
 
 	return( true );
 }
@@ -403,24 +418,41 @@ bool CVIEW_Table_Control::_Set_Record(int iRecord, CSG_Table_Record *pRecord)
 
 ///////////////////////////////////////////////////////////
 //														 //
-//														 //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+void CVIEW_Table_Control::_Update_Views(void)
+{
+	if( GetBatchCount() == 0 )
+	{
+		BeginBatch();
+
+		g_pData->Update_Views(m_pTable);
+
+		EndBatch();
+	}
+}
+
+
+///////////////////////////////////////////////////////////
 //														 //
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
-bool CVIEW_Table_Control::Update_Sorting(int iField, int Direction)
+bool CVIEW_Table_Control::_Update_Sorting(int iField, int Direction)
 {
 	if( iField >= 0 && iField < m_pTable->Get_Field_Count() )
 	{
 		switch( Direction )
 		{
 		default:	m_pTable->Toggle_Index(iField);	break;
-		case 0:		m_pTable->Set_Index(iField, TABLE_INDEX_None      );	break;
-		case 1:		m_pTable->Set_Index(iField, TABLE_INDEX_Ascending );	break;
-		case 2:		m_pTable->Set_Index(iField, TABLE_INDEX_Descending);	break;
+
+		case  0:	m_pTable->Set_Index(iField, TABLE_INDEX_None      );	break;
+		case  1:	m_pTable->Set_Index(iField, TABLE_INDEX_Ascending );	break;
+		case  2:	m_pTable->Set_Index(iField, TABLE_INDEX_Descending);	break;
 		}
 
-		return( _Set_Records() );
+		return( _Update_Records() );
 	}
 
 	return( false );
@@ -429,162 +461,444 @@ bool CVIEW_Table_Control::Update_Sorting(int iField, int Direction)
 
 ///////////////////////////////////////////////////////////
 //														 //
-//														 //
-//														 //
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
-bool CVIEW_Table_Control::Add_Record(void)
+int CVIEW_Table_Control::_Get_Scroll_Start(int Position)
 {
-	if( !FIXED_ROWS && m_pTable->Get_ObjectType() == DATAOBJECT_TYPE_Table )
+	if( Position   >= _Get_Record_Count() - m_Scroll_Range )
 	{
-		AppendRows();
+		Position	= _Get_Record_Count() - m_Scroll_Range;
+	}
 
-		m_pRecords	= (CSG_Table_Record **)SG_Realloc(m_pRecords, GetNumberRows() * sizeof(CSG_Table_Record *));
+	if( Position < 0 )
+	{
+		Position	= 0;
+	}
 
-		_Set_Record(GetNumberRows() - 1, m_pTable->Add_Record());
+	return( Position );
+}
 
-		return( true );
+//---------------------------------------------------------
+bool CVIEW_Table_Control::_Set_Scroll_Start(int Position, bool bEnforceUpdate)
+{
+	Position	= _Get_Scroll_Start(Position);
+
+	if( m_Scroll_Start != Position || bEnforceUpdate )
+	{
+		m_Scroll_Start	= Position;
+
+		return( _Update_Records() );
 	}
 
-	return( false );
+	return( true );
 }
 
 //---------------------------------------------------------
-bool CVIEW_Table_Control::Ins_Record(void)
+void CVIEW_Table_Control::AdjustScrollbars(void)
 {
-	if( !FIXED_ROWS && m_pTable->Get_ObjectType() == DATAOBJECT_TYPE_Table )
+	Freeze();
+	
+	wxGrid::AdjustScrollbars();
+
+	m_Scroll_Range	= (GetClientSize().y - GetColLabelSize()) / GetDefaultRowSize();
+
+	SetScrollbar(wxVERTICAL, m_Scroll_Start, m_Scroll_Range, _Get_Record_Count());
+
+	Thaw();
+}
+
+//---------------------------------------------------------
+void CVIEW_Table_Control::On_Scroll(wxScrollWinEvent &event)
+{
+	if( event.GetOrientation() == wxHORIZONTAL )
+	{
+		event.Skip();
+	}
+	else
 	{
-		int		iRecord	= GetGridCursorRow();
+		if     ( event.GetEventType() == wxEVT_SCROLLWIN_LINEUP       )	_Set_Scroll_Start(m_Scroll_Start - 1             , false);
+		else if( event.GetEventType() == wxEVT_SCROLLWIN_LINEDOWN     )	_Set_Scroll_Start(m_Scroll_Start + 1             , false);
+		else if( event.GetEventType() == wxEVT_SCROLLWIN_PAGEUP       )	_Set_Scroll_Start(m_Scroll_Start - m_Scroll_Range, false);
+		else if( event.GetEventType() == wxEVT_SCROLLWIN_PAGEDOWN     )	_Set_Scroll_Start(m_Scroll_Start + m_Scroll_Range, false);
+		else if( event.GetEventType() == wxEVT_SCROLLWIN_TOP          )	_Set_Scroll_Start(0                              , false);
+		else if( event.GetEventType() == wxEVT_SCROLLWIN_BOTTOM       )	_Set_Scroll_Start(m_pTable->Get_Count()          , false);
+		else if( event.GetEventType() == wxEVT_SCROLLWIN_THUMBTRACK   )	_Set_Scroll_Start(event.GetPosition()            , false);
+		else if( event.GetEventType() == wxEVT_SCROLLWIN_THUMBRELEASE )	_Set_Scroll_Start(event.GetPosition()            , false);
+	}
+}
 
-		if( iRecord >= 0 && iRecord < GetNumberRows() )
+//---------------------------------------------------------
+void CVIEW_Table_Control::On_Key(wxKeyEvent &event)
+{
+	if     ( event.GetKeyCode() == WXK_UP       )
+	{
+		if( GetCursorRow() > 0 )
+		{
+			SetGridCursor(GetCursorRow() - 1, GetCursorColumn());
+		}
+		else
 		{
-			InsertRows(iRecord);
+			_Set_Scroll_Start(m_Scroll_Start - 1             , false);
+		}
+	}
+	else if( event.GetKeyCode() == WXK_DOWN     )
+	{
+		if( GetCursorRow() < m_Scroll_Range - 1 )
+		{
+			SetGridCursor(GetCursorRow() + 1, GetCursorColumn());
+		}
+		else
+		{
+			_Set_Scroll_Start(m_Scroll_Start + 1             , false);
+		}
+	}
+	else if( event.GetKeyCode() == WXK_PAGEUP   )	_Set_Scroll_Start(m_Scroll_Start - m_Scroll_Range, false);
+	else if( event.GetKeyCode() == WXK_PAGEDOWN )	_Set_Scroll_Start(m_Scroll_Start + m_Scroll_Range, false);
+	else if( event.GetKeyCode() == WXK_HOME     )	_Set_Scroll_Start(0                              , false);
+	else if( event.GetKeyCode() == WXK_END      )	_Set_Scroll_Start(m_pTable->Get_Count()          , false);
+	else
+	{
+		event.Skip(true);
+	}
+}
 
-			m_pRecords	= (CSG_Table_Record **)SG_Realloc(m_pRecords, GetNumberRows() * sizeof(CSG_Table_Record *));
+//---------------------------------------------------------
+void CVIEW_Table_Control::On_Size(wxSizeEvent &event)//&WXUNUSED(event))
+{
+	event.Skip();
 
-			for(int i=GetNumberRows()-1; i>iRecord; i--)
-			{
-				m_pRecords[i]	= m_pRecords[i - 1];
-			}
+	if( GetNumberCols() > 0 )
+	{
+		int	Scroll_Range	= m_Scroll_Range;
 
-			_Set_Record(iRecord, m_pTable->Ins_Record(iRecord));
+		AdjustScrollbars();
 
-			return( true );
+		if( Scroll_Range != m_Scroll_Range )
+		{
+			Freeze();
+			_Update_Records();
+			Thaw();
 		}
 	}
+}
 
-	return( false );
+
+///////////////////////////////////////////////////////////
+//														 //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+void CVIEW_Table_Control::On_Edit_Start(wxGridEvent &event)
+{
+	m_bEditing	= true;
+
+	event.Skip();
 }
 
 //---------------------------------------------------------
-bool CVIEW_Table_Control::Del_Record(void)
+void CVIEW_Table_Control::On_Edit_Stop(wxGridEvent &event)
 {
-	return( !FIXED_ROWS && m_pTable->Del_Selection() && Update_Table() );
+	m_bEditing	= false;
+
+	event.Skip();
 }
 
 //---------------------------------------------------------
-bool CVIEW_Table_Control::Del_Records(void)
+void CVIEW_Table_Control::On_Changed(wxGridEvent &event)
 {
-	return( !FIXED_ROWS && m_pTable->Del_Records() && Update_Table() );
+	CSG_Table_Record	*pRecord	= _Get_Record(event.GetRow());
+
+	if( pRecord )
+	{
+		pRecord->Set_Value(event.GetCol(), GetCellValue(event.GetRow(), event.GetCol()).wx_str());
+
+		SetCellValue(event.GetRow(), event.GetCol(), pRecord->asString(event.GetCol()));
+	}
+}
+
+//---------------------------------------------------------
+void CVIEW_Table_Control::On_Select(wxGridRangeSelectEvent &event)
+{
+	Update_Selection();
 }
 
 
 ///////////////////////////////////////////////////////////
 //														 //
-//														 //
-//														 //
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
-bool CVIEW_Table_Control::Load(const wxString &File_Name)
+void CVIEW_Table_Control::On_LClick(wxGridEvent &event)
 {
-	CSG_Table	Table(&File_Name);
+	SetGridCursor(event.GetRow(), event.GetCol());
 
-	bool	bResult	= Table.Get_Count() > 0
-		&& Table.Get_Field_Count() == m_pTable->Get_Field_Count()
-		&& m_pTable->Assign_Values(&Table)
-		&& Update_Table();
+	//-----------------------------------------------------
+	if( event.AltDown() )
+	{
+		if( m_pTable->Get_Field_Type(event.GetCol()) == SG_DATATYPE_String )
+		{
+			Open_Application(GetCellValue(event.GetRow(), event.GetCol()));
+		}
+	}
 
-	PROCESS_Set_Okay();
+	//-----------------------------------------------------
+	else if( event.ControlDown() )
+	{
+		if( m_pTable->Get_Field_Type(event.GetCol()) == SG_DATATYPE_String )
+		{
+			g_pData->Open   (GetCellValue(event.GetRow(), event.GetCol()));
+		}
+	}
 
-	return( bResult );
+	//-----------------------------------------------------
+	else if( m_pTable->Get_Field_Type(event.GetCol()) == SG_DATATYPE_Color )
+	{
+		CSG_Table_Record	*pRecord	= _Get_Record(event.GetRow());
+
+		long	lValue;
+
+		if( pRecord && DLG_Color(lValue = pRecord->asInt(event.GetCol())) )
+		{
+			pRecord->Set_Value(event.GetCol(), lValue);
+
+			SetCellBackgroundColour(event.GetRow(), event.GetCol(), Get_Color_asWX(pRecord->asInt(event.GetCol())));
+
+			ForceRefresh();
+		}
+	}
 }
 
 //---------------------------------------------------------
-bool CVIEW_Table_Control::Save(const wxString &File_Name, int Format)
+void CVIEW_Table_Control::On_LClick_Label(wxGridEvent &event)
 {
-	bool	bResult	= m_pTable->Save(&File_Name);
+	if( m_bSelOnly )
+	{
+		// nop
+	}
+	else if( event.GetRow() < 0 )
+	{
+		if( event.GetCol() < 0 && m_pTable->Get_Selection_Count() > 0 )	// deselect everything
+		{
+			m_pTable->Select();
 
-	PROCESS_Set_Okay();
+			Update_Selection();	_Update_Views();
+		}
+	}
+	else // if( event.GetRow() >= 0 )	// select records
+	{
+		if( !event.ControlDown() )
+		{
+			m_pTable->Select();
 
-	return( bResult );
+			if( !event.ShiftDown() || m_Cursor < 0 || m_Cursor >= m_pTable->Get_Count() )
+			{
+				m_pTable->Select(_Get_Record(event.GetRow()), false);
+			}
+			else // if( event.ShiftDown() )
+			{
+				int	iFirst	= m_Scroll_Start + event.GetRow() <= m_Cursor ? m_Scroll_Start + event.GetRow() : m_Cursor;
+				int	iLast	= m_Scroll_Start + event.GetRow() >  m_Cursor ? m_Scroll_Start + event.GetRow() : m_Cursor;
+
+				for(int iRecord=iFirst; iRecord<=iLast; iRecord++)
+				{
+					m_pTable->Select(iRecord, true);
+				}
+			}
+		}
+		else // if( event.ControlDown() )
+		{
+			m_pTable->Select(_Get_Record(event.GetRow()), true);
+		}
+
+		Update_Selection();	_Update_Views();
+	}
+
+	m_Cursor	= m_Scroll_Start + event.GetRow();
+
+	SetGridCursor(event.GetRow(), GetGridCursorCol());
+}
+
+//---------------------------------------------------------
+void CVIEW_Table_Control::On_LDClick_Label(wxGridEvent &event)
+{
+	_Update_Sorting(event.GetCol(), -1);
 }
 
 
 ///////////////////////////////////////////////////////////
 //														 //
-//														 //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+bool CVIEW_Table_Control::_Get_DataSource(wxString &Source)
+{
+	if( Source.Find("PGSQL:") == 0 || wxFileExists(Source) )
+	{
+		return( true );
+	}
+
+	if( m_pTable->Get_File_Name(false) )
+	{
+		wxFileName	fn(Source), dir(m_pTable->Get_File_Name(false));
+
+		if( fn.MakeAbsolute(dir.GetPath()) && fn.Exists() )
+		{
+			Source	= fn.GetFullPath();
+
+			return( true );
+		}
+	}
+
+	return( false );
+}
+
+//---------------------------------------------------------
+void CVIEW_Table_Control::On_RClick(wxGridEvent &event)
+{
+	SetGridCursor(event.GetRow(), event.GetCol());
+
+	//-----------------------------------------------------
+	if( m_pTable->Get_Field_Type(event.GetCol()) == SG_DATATYPE_String )
+	{
+		wxMenu	Menu;
+
+		CMD_Menu_Add_Item(&Menu, false, ID_CMD_TABLE_FIELD_OPEN_APP);
+
+		wxString	Value	= GetCellValue(event.GetRow(), event.GetCol());
+
+		if( _Get_DataSource(Value) )
+		{
+			CMD_Menu_Add_Item(&Menu, false, ID_CMD_TABLE_FIELD_OPEN_DATA);
+		}
+
+		PopupMenu(&Menu, event.GetPosition());
+	}
+}
+
+//---------------------------------------------------------
+void CVIEW_Table_Control::On_RClick_Label(wxGridEvent &event)
+{
+	//-----------------------------------------------------
+	if( event.GetCol() != -1 )
+	{
+		wxMenu	Menu(_TL("Columns"));
+
+		CMD_Menu_Add_Item(&Menu, false, ID_CMD_TABLE_FIELD_ADD);
+		CMD_Menu_Add_Item(&Menu, false, ID_CMD_TABLE_FIELD_DEL);
+
+		Menu.AppendSeparator();
+		CMD_Menu_Add_Item(&Menu, false, ID_CMD_TABLE_AUTOSIZE_COLS);
+		CMD_Menu_Add_Item(&Menu, false, ID_CMD_TABLE_FIELD_SORT);
+		CMD_Menu_Add_Item(&Menu, false, ID_CMD_TABLE_FIELD_RENAME);
+		CMD_Menu_Add_Item(&Menu, false, ID_CMD_TABLE_FIELD_TYPE);
+
+		PopupMenu(&Menu, event.GetPosition().x, event.GetPosition().y - GetColLabelSize());
+	}
+
+	//-----------------------------------------------------
+	else if( event.GetRow() != -1 )
+	{
+		wxMenu	Menu(_TL("Rows"));
+
+		if( m_bSelOnly )
+		{
+			CMD_Menu_Add_Item(&Menu,  true, ID_CMD_TABLE_SELECTION_ONLY);
+		}
+		else
+		{
+			CMD_Menu_Add_Item(&Menu, false, ID_CMD_TABLE_RECORD_ADD);
+			CMD_Menu_Add_Item(&Menu, false, ID_CMD_TABLE_RECORD_INS);
+			CMD_Menu_Add_Item(&Menu, false, ID_CMD_TABLE_RECORD_DEL);
+			CMD_Menu_Add_Item(&Menu, false, ID_CMD_TABLE_RECORD_DEL_ALL);
+
+		//	Menu.AppendSeparator();
+		//	CMD_Menu_Add_Item(&Menu, false, ID_CMD_TABLE_AUTOSIZE_ROWS);
+
+			Menu.AppendSeparator();
+			CMD_Menu_Add_Item(&Menu,  true, ID_CMD_TABLE_SELECTION_ONLY);
+			CMD_Menu_Add_Item(&Menu, false, ID_CMD_TABLE_SELECTION_CLEAR);
+		}
+
+		PopupMenu(&Menu, event.GetPosition().x - GetRowLabelSize(), event.GetPosition().y);
+	}
+}
+
+
+///////////////////////////////////////////////////////////
 //														 //
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
-void CVIEW_Table_Control::On_Size(wxSizeEvent &event)//&WXUNUSED(event))
+void CVIEW_Table_Control::On_Sel_Only(wxCommandEvent  &event)
+{
+	if( m_bSelOnly == true )
+	{
+		m_bSelOnly	= false;
+
+		_Update_Records();
+	}
+	else if( m_pTable->Get_Selection_Count() > 0 )
+	{
+		m_bSelOnly	= true;
+
+		_Update_Records();
+	}
+}
+
+void CVIEW_Table_Control::On_Sel_Only_UI(wxUpdateUIEvent &event)
 {
-	if( m_Field_Offset && GetNumberCols() && GetClientSize().x > GetRowLabelSize() )
-	{
-		SetColSize(0, GetClientSize().x - GetRowLabelSize());
-	}
+	event.Enable(m_pTable->Get_Selection_Count() > 0);
 
-	event.Skip();
+	event.Check (m_bSelOnly);
 }
 
 //---------------------------------------------------------
-void CVIEW_Table_Control::On_Key(wxKeyEvent &event)
+void CVIEW_Table_Control::On_Sel_Clear(wxCommandEvent  &event)
 {
-	event.Skip(true);
-
-	if( event.GetKeyCode() == WXK_RETURN )
+	if( m_pTable->Get_Selection_Count() > 0 )
 	{
-		if( !m_bEditing && GetParent() == g_pACTIVE->Get_Attributes() )
-		{
-			event.Skip(false);
+		m_pTable->Select();
 
-			g_pACTIVE->Get_Attributes()->Save_Changes(false);
-		}
+		Update_Selection();	_Update_Views();
 	}
 }
 
-//---------------------------------------------------------
-void CVIEW_Table_Control::On_Edit_Start(wxGridEvent &event)
+void CVIEW_Table_Control::On_Sel_Clear_UI(wxUpdateUIEvent &event)
 {
-	m_bEditing	= true;
-
-	event.Skip();
+	event.Enable(!m_bSelOnly && m_pTable->Get_Selection_Count() > 0);
 }
 
 //---------------------------------------------------------
-void CVIEW_Table_Control::On_Edit_Stop(wxGridEvent &event)
+void CVIEW_Table_Control::On_Autosize_Cols(wxCommandEvent &event)
 {
-	m_bEditing	= false;
+	AutoSizeColumns(false);
+}
 
-	event.Skip();
+//---------------------------------------------------------
+void CVIEW_Table_Control::On_Autosize_Rows(wxCommandEvent &event)
+{
+	AutoSizeRows(false);
 }
 
 //---------------------------------------------------------
-void CVIEW_Table_Control::On_Changed(wxGridEvent &event)
+void CVIEW_Table_Control::On_Cell_Open(wxCommandEvent &event)
 {
-	CSG_Table_Record	*pRecord	= m_pRecords[event.GetRow()];
+	wxString	Value	= GetCellValue(GetGridCursorRow(), GetGridCursorCol());
 
-	if( pRecord )
+	if( event.GetId() == ID_CMD_TABLE_FIELD_OPEN_APP )
 	{
-		int	iField	= m_Field_Offset + event.GetCol();
-
-		if( iField >= m_Field_Offset && iField < m_pTable->Get_Field_Count() )
+		if( !Open_Application(Value) )
 		{
-			pRecord->Set_Value(iField, GetCellValue(event.GetRow(), event.GetCol()).wx_str());
+			DLG_Message_Show_Error(_TL("failed"), CMD_Get_Name(ID_CMD_TABLE_FIELD_OPEN_APP));
+		}
+	}
 
-			SetCellValue(event.GetRow(), event.GetCol(), pRecord->asString(iField));
+	if( event.GetId() == ID_CMD_TABLE_FIELD_OPEN_DATA )
+	{
+		if( !_Get_DataSource(Value) || !g_pData->Open(Value) )
+		{
+			DLG_Message_Show_Error(_TL("failed"), CMD_Get_Name(ID_CMD_TABLE_FIELD_OPEN_DATA));
 		}
 	}
 }
@@ -592,8 +906,6 @@ void CVIEW_Table_Control::On_Changed(wxGridEvent &event)
 
 ///////////////////////////////////////////////////////////
 //														 //
-//														 //
-//														 //
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
@@ -621,7 +933,7 @@ void CVIEW_Table_Control::On_Field_Add(wxCommandEvent &event)
 	P.Add_Choice(
 		NULL	, "TYPE"	, _TL("Field Type"),
 		_TL(""),
-		CSG_String::Format(SG_T("%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|"),
+		CSG_String::Format("%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|",
 			SG_Data_Type_Get_Name(SG_DATATYPE_String).c_str(),
 			SG_Data_Type_Get_Name(SG_DATATYPE_Date  ).c_str(),
 			SG_Data_Type_Get_Name(SG_DATATYPE_Color ).c_str(),
@@ -664,17 +976,17 @@ void CVIEW_Table_Control::On_Field_Add(wxCommandEvent &event)
 		{
 		default:
 		case  0:	Type	= SG_DATATYPE_String;	break;
-		case  1:	Type	= SG_DATATYPE_Date;		break;
-		case  2:	Type	= SG_DATATYPE_Color;	break;
-		case  3:	Type	= SG_DATATYPE_Byte;		break;
-		case  4:	Type	= SG_DATATYPE_Char;		break;
-		case  5:	Type	= SG_DATATYPE_Word;		break;
-		case  6:	Type	= SG_DATATYPE_Short;	break;
-		case  7:	Type	= SG_DATATYPE_DWord;	break;
-		case  8:	Type	= SG_DATATYPE_Int;		break;
-		case  9:	Type	= SG_DATATYPE_ULong;	break;
-		case 10:	Type	= SG_DATATYPE_Long;		break;
-		case 11:	Type	= SG_DATATYPE_Float;	break;
+		case  1:	Type	= SG_DATATYPE_Date  ;	break;
+		case  2:	Type	= SG_DATATYPE_Color ;	break;
+		case  3:	Type	= SG_DATATYPE_Byte  ;	break;
+		case  4:	Type	= SG_DATATYPE_Char  ;	break;
+		case  5:	Type	= SG_DATATYPE_Word  ;	break;
+		case  6:	Type	= SG_DATATYPE_Short ;	break;
+		case  7:	Type	= SG_DATATYPE_DWord ;	break;
+		case  8:	Type	= SG_DATATYPE_Int   ;	break;
+		case  9:	Type	= SG_DATATYPE_ULong ;	break;
+		case 10:	Type	= SG_DATATYPE_Long  ;	break;
+		case 11:	Type	= SG_DATATYPE_Float ;	break;
 		case 12:	Type	= SG_DATATYPE_Double;	break;
 		case 13:	Type	= SG_DATATYPE_Binary;	break;
 		}
@@ -689,7 +1001,7 @@ void CVIEW_Table_Control::On_Field_Add(wxCommandEvent &event)
 
 void CVIEW_Table_Control::On_Field_Add_UI(wxUpdateUIEvent &event)
 {
-	event.Enable(FIXED_COLS == false);
+	event.Enable(true);
 }
 
 //---------------------------------------------------------
@@ -725,7 +1037,7 @@ void CVIEW_Table_Control::On_Field_Del(wxCommandEvent &event)
 
 void CVIEW_Table_Control::On_Field_Del_UI(wxUpdateUIEvent &event)
 {
-	event.Enable(FIXED_COLS == false);
+	event.Enable(m_pTable->Get_Field_Count() > 0);
 }
 
 //---------------------------------------------------------
@@ -741,8 +1053,8 @@ void CVIEW_Table_Control::On_Field_Sort(wxCommandEvent &event)
 		sFields.Append(m_pTable->Get_Field_Name(i));	sFields.Append('|');
 	}
 
-	sOrder.Printf(SG_T("%s|%s|%s|"),
-		_TL("unsorted"),
+	sOrder.Printf("%s|%s|%s|",
+		_TL("do not sort"),
 		_TL("ascending"),
 		_TL("descending")
 	);
@@ -768,7 +1080,7 @@ void CVIEW_Table_Control::On_Field_Sort(wxCommandEvent &event)
 			P("FIELD_3")->asInt(), P("ORDER_3")->asInt() == 1 ? TABLE_INDEX_Ascending : P("ORDER_3")->asInt() == 2 ? TABLE_INDEX_Descending : TABLE_INDEX_None
 		);
 
-		_Set_Records();
+		_Update_Records();
 	}
 }
 
@@ -828,23 +1140,23 @@ void CVIEW_Table_Control::On_Field_Type(wxCommandEvent &event)
 		{
 		default:
 		case SG_DATATYPE_String:	Types[i]	=  0;	break;
-		case SG_DATATYPE_Date:		Types[i]	=  1;	break;
-		case SG_DATATYPE_Color:		Types[i]	=  2;	break;
-		case SG_DATATYPE_Byte:		Types[i]	=  3;	break;
-		case SG_DATATYPE_Char:		Types[i]	=  4;	break;
-		case SG_DATATYPE_Word:		Types[i]	=  5;	break;
-		case SG_DATATYPE_Short:		Types[i]	=  6;	break;
-		case SG_DATATYPE_DWord:		Types[i]	=  7;	break;
-		case SG_DATATYPE_Int:		Types[i]	=  8;	break;
-		case SG_DATATYPE_ULong:		Types[i]	=  9;	break;
-		case SG_DATATYPE_Long:		Types[i]	= 10;	break;
-		case SG_DATATYPE_Float:		Types[i]	= 11;	break;
+		case SG_DATATYPE_Date  :	Types[i]	=  1;	break;
+		case SG_DATATYPE_Color :	Types[i]	=  2;	break;
+		case SG_DATATYPE_Byte  :	Types[i]	=  3;	break;
+		case SG_DATATYPE_Char  :	Types[i]	=  4;	break;
+		case SG_DATATYPE_Word  :	Types[i]	=  5;	break;
+		case SG_DATATYPE_Short :	Types[i]	=  6;	break;
+		case SG_DATATYPE_DWord :	Types[i]	=  7;	break;
+		case SG_DATATYPE_Int   :	Types[i]	=  8;	break;
+		case SG_DATATYPE_ULong :	Types[i]	=  9;	break;
+		case SG_DATATYPE_Long  :	Types[i]	= 10;	break;
+		case SG_DATATYPE_Float :	Types[i]	= 11;	break;
 		case SG_DATATYPE_Double:	Types[i]	= 12;	break;
 		case SG_DATATYPE_Binary:	Types[i]	= 13;	break;
 		}
 
         P.Add_Choice(NULL, "", m_pTable->Get_Field_Name(i), _TL(""),
-            CSG_String::Format(SG_T("%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|"),
+            CSG_String::Format("%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|",
 			SG_Data_Type_Get_Name(SG_DATATYPE_String).c_str(),
 			SG_Data_Type_Get_Name(SG_DATATYPE_Date  ).c_str(),
 			SG_Data_Type_Get_Name(SG_DATATYPE_Color ).c_str(),
@@ -876,17 +1188,17 @@ void CVIEW_Table_Control::On_Field_Type(wxCommandEvent &event)
 			{
 			default:
 			case  0:	Type	= SG_DATATYPE_String;	break;
-			case  1:	Type	= SG_DATATYPE_Date;		break;
-			case  2:	Type	= SG_DATATYPE_Color;	break;
-			case  3:	Type	= SG_DATATYPE_Byte;		break;
-			case  4:	Type	= SG_DATATYPE_Char;		break;
-			case  5:	Type	= SG_DATATYPE_Word;		break;
-			case  6:	Type	= SG_DATATYPE_Short;	break;
-			case  7:	Type	= SG_DATATYPE_DWord;	break;
-			case  8:	Type	= SG_DATATYPE_Int;		break;
-			case  9:	Type	= SG_DATATYPE_ULong;	break;
-			case 10:	Type	= SG_DATATYPE_Long;		break;
-			case 11:	Type	= SG_DATATYPE_Float;	break;
+			case  1:	Type	= SG_DATATYPE_Date  ;	break;
+			case  2:	Type	= SG_DATATYPE_Color ;	break;
+			case  3:	Type	= SG_DATATYPE_Byte  ;	break;
+			case  4:	Type	= SG_DATATYPE_Char  ;	break;
+			case  5:	Type	= SG_DATATYPE_Word  ;	break;
+			case  6:	Type	= SG_DATATYPE_Short ;	break;
+			case  7:	Type	= SG_DATATYPE_DWord ;	break;
+			case  8:	Type	= SG_DATATYPE_Int   ;	break;
+			case  9:	Type	= SG_DATATYPE_ULong ;	break;
+			case 10:	Type	= SG_DATATYPE_Long  ;	break;
+			case 11:	Type	= SG_DATATYPE_Float ;	break;
 			case 12:	Type	= SG_DATATYPE_Double;	break;
 			case 13:	Type	= SG_DATATYPE_Binary;	break;
 			}
@@ -902,6 +1214,7 @@ void CVIEW_Table_Control::On_Field_Type(wxCommandEvent &event)
 		if( bChanged )
 		{
 			Update_Table();
+
 			g_pData->Update(m_pTable, NULL);
 		}
 	}
@@ -915,321 +1228,62 @@ void CVIEW_Table_Control::On_Field_Type_UI(wxUpdateUIEvent &event)
 
 ///////////////////////////////////////////////////////////
 //														 //
-//														 //
-//														 //
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
 void CVIEW_Table_Control::On_Record_Add(wxCommandEvent &event)
 {
-	Add_Record();
+	if( m_pTable->Get_ObjectType() == DATAOBJECT_TYPE_Table && m_pTable->Add_Record() )
+	{
+		_Set_Scroll_Start(m_pTable->Get_Count() - 1);
+	}
 }
 
 void CVIEW_Table_Control::On_Record_Add_UI(wxUpdateUIEvent &event)
 {
-	event.Enable(!FIXED_ROWS && m_pTable->Get_ObjectType() == DATAOBJECT_TYPE_Table);
+	event.Enable(m_pTable->Get_ObjectType() == DATAOBJECT_TYPE_Table && !m_pTable->is_Indexed());
 }
 
 //---------------------------------------------------------
 void CVIEW_Table_Control::On_Record_Ins(wxCommandEvent &event)
 {
-	Ins_Record();
+	if( m_pTable->Get_ObjectType() == DATAOBJECT_TYPE_Table && m_pTable->Ins_Record(m_Scroll_Start + GetGridCursorRow()) )
+	{
+		_Update_Records();
+	}
 }
 
 void CVIEW_Table_Control::On_Record_Ins_UI(wxUpdateUIEvent &event)
 {
-	event.Enable(!FIXED_ROWS && m_pTable->Get_ObjectType() == DATAOBJECT_TYPE_Table);
+	event.Enable(m_pTable->Get_ObjectType() == DATAOBJECT_TYPE_Table && !m_pTable->is_Indexed());
 }
 
 //---------------------------------------------------------
 void CVIEW_Table_Control::On_Record_Del(wxCommandEvent &event)
 {
-	Del_Record();
-}
-
-void CVIEW_Table_Control::On_Record_Del_UI(wxUpdateUIEvent &event)
-{
-	event.Enable(!FIXED_ROWS && m_pTable->Get_Selection_Count() > 0);
-}
-
-//---------------------------------------------------------
-void CVIEW_Table_Control::On_Record_Clr(wxCommandEvent &event)
-{
-	Del_Records();
-}
-
-void CVIEW_Table_Control::On_Record_Clr_UI(wxUpdateUIEvent &event)
-{
-	event.Enable(!FIXED_ROWS);
-}
-
-
-///////////////////////////////////////////////////////////
-//														 //
-//														 //
-//														 //
-///////////////////////////////////////////////////////////
-
-//---------------------------------------------------------
-void CVIEW_Table_Control::On_Sel_To_Top(wxCommandEvent  &event)
-{
-	if( m_pTable->Get_Selection_Count() > 0 )
+	if( m_pTable->Del_Selection() )
 	{
-		_Set_Records(true);
+		_Update_Records();
 	}
 }
 
-void CVIEW_Table_Control::On_Sel_To_Top_UI(wxUpdateUIEvent &event)
+void CVIEW_Table_Control::On_Record_Del_UI(wxUpdateUIEvent &event)
 {
 	event.Enable(m_pTable->Get_Selection_Count() > 0);
 }
 
 //---------------------------------------------------------
-void CVIEW_Table_Control::On_Sel_Only(wxCommandEvent  &event)
-{
-	if( m_pTable->Get_Selection_Count() > 0 && m_pTable->Get_Selection_Count() < GetNumberRows() )
-	{
-		m_bSelOnly	= true;
-
-		_Set_Records();
-	}
-	else if( m_bSelOnly )
-	{
-		m_bSelOnly	= false;
-
-		_Set_Records();
-	}
-}
-
-void CVIEW_Table_Control::On_Sel_Only_UI(wxUpdateUIEvent &event)
-{
-	event.Check(m_bSelOnly);
-}
-
-
-///////////////////////////////////////////////////////////
-//														 //
-//														 //
-//														 //
-///////////////////////////////////////////////////////////
-
-//---------------------------------------------------------
-void CVIEW_Table_Control::On_Autosize_Cols(wxCommandEvent &event)
-{
-	AutoSizeColumns(false);
-}
-
-//---------------------------------------------------------
-void CVIEW_Table_Control::On_Autosize_Rows(wxCommandEvent &event)
-{
-	AutoSizeRows(false);
-}
-
-
-///////////////////////////////////////////////////////////
-//														 //
-//														 //
-//														 //
-///////////////////////////////////////////////////////////
-
-//---------------------------------------------------------
-void CVIEW_Table_Control::On_LClick(wxGridEvent &event)
-{
-	int					iField		= m_Field_Offset + event.GetCol();
-	CSG_Table_Record	*pRecord	= m_pRecords[event.GetRow()];
-
-	//-----------------------------------------------------
-	if( event.ControlDown() )
-	{
-		m_pTable->Select(pRecord, true);
-
-		Update_Selection();
-	}
-
-	else if( event.ShiftDown() )
-	{
-		SelectBlock(event.GetRow(), 0, GetGridCursorRow(), GetNumberCols(), false);
-	}
-
-	else if( event.AltDown() )
-	{
-		if( m_pTable->Get_Field_Type(iField) == SG_DATATYPE_String )
-		{
-			Open_Application(pRecord->asString(iField));
-		}
-	}
-
-	else
-	{
-		SelectRow(event.GetRow(), false);
-
-		if( pRecord && iField >= m_Field_Offset && iField < m_pTable->Get_Field_Count() && m_pTable->Get_Field_Type(iField) == SG_DATATYPE_Color )
-		{
-			long	lValue;
-
-			if( DLG_Color(lValue = pRecord->asInt(iField)) )
-			{
-				pRecord->Set_Value(iField, lValue);
-
-				SetCellBackgroundColour(event.GetRow(), event.GetCol(), Get_Color_asWX(pRecord->asInt(iField)));
-
-				ForceRefresh();
-			}
-		}
-	}
-
-	//-----------------------------------------------------
-	SetGridCursor(event.GetRow(), event.GetCol());
-}
-
-
-///////////////////////////////////////////////////////////
-//														 //
-//														 //
-//														 //
-///////////////////////////////////////////////////////////
-
-//---------------------------------------------------------
-void CVIEW_Table_Control::On_LClick_Label(wxGridEvent &event)
-{
-	if( event.GetCol() >= 0 )
-	{
-		SetGridCursor	(GetGridCursorRow(), event.GetCol());
-	}
-	else if( event.GetRow() >= 0 )
-	{
-		SetGridCursor	(event.GetRow(), GetGridCursorCol());
-	}
-	else
-	{
-	//	SelectAll();
-	}
-}
-
-//---------------------------------------------------------
-void CVIEW_Table_Control::On_RClick_Label(wxGridEvent &event)
-{
-	wxMenu	Menu;
-
-	//-----------------------------------------------------
-	if( event.GetCol() != -1 )
-	{
-		Menu.SetTitle(wxString::Format(wxT("%s"), _TL("Columns")));
-
-		CMD_Menu_Add_Item(&Menu, false, ID_CMD_TABLE_FIELD_ADD);
-		CMD_Menu_Add_Item(&Menu, false, ID_CMD_TABLE_FIELD_DEL);
-
-		Menu.AppendSeparator();
-		CMD_Menu_Add_Item(&Menu, false, ID_CMD_TABLE_AUTOSIZE_COLS);
-		CMD_Menu_Add_Item(&Menu, false, ID_CMD_TABLE_FIELD_SORT);
-		CMD_Menu_Add_Item(&Menu, false, ID_CMD_TABLE_FIELD_RENAME);
-		CMD_Menu_Add_Item(&Menu, false, ID_CMD_TABLE_FIELD_TYPE);
-
-		PopupMenu(&Menu, event.GetPosition().x, event.GetPosition().y - GetColLabelSize());
-	}
-
-	//-----------------------------------------------------
-	else if( event.GetRow() != -1 )
-	{
-		Menu.SetTitle(wxString::Format(wxT("%s"), _TL("Rows")));
-
-		CMD_Menu_Add_Item(&Menu, false, ID_CMD_TABLE_RECORD_ADD);
-		CMD_Menu_Add_Item(&Menu, false, ID_CMD_TABLE_RECORD_INS);
-		CMD_Menu_Add_Item(&Menu, false, ID_CMD_TABLE_RECORD_DEL);
-		CMD_Menu_Add_Item(&Menu, false, ID_CMD_TABLE_RECORD_DEL_ALL);
-
-		Menu.AppendSeparator();
-		CMD_Menu_Add_Item(&Menu, false, ID_CMD_TABLE_AUTOSIZE_ROWS);
-
-		if( !FIXED_ROWS )
-		{
-			Menu.AppendSeparator();
-			CMD_Menu_Add_Item(&Menu, false, ID_CMD_TABLE_SELECTION_TO_TOP);
-			CMD_Menu_Add_Item(&Menu,  true, ID_CMD_TABLE_SELECTION_ONLY);
-		}
-
-		PopupMenu(&Menu, event.GetPosition().x - GetRowLabelSize(), event.GetPosition().y);
-	}
-
-	//-----------------------------------------------------
-	else
-	{
-		ClearSelection();
-	}
-}
-
-//---------------------------------------------------------
-void CVIEW_Table_Control::On_LDClick_Label(wxGridEvent &event)
-{
-	Update_Sorting(event.GetCol(), -1);
-}
-
-
-///////////////////////////////////////////////////////////
-//														 //
-//														 //
-//														 //
-///////////////////////////////////////////////////////////
-
-//---------------------------------------------------------
-bool CVIEW_Table_Control::Update_Selection(void)
+void CVIEW_Table_Control::On_Record_Clr(wxCommandEvent &event)
 {
-	if( GetBatchCount() == 0 )
+	if( DLG_Message_Confirm(CMD_Get_Name(ID_CMD_TABLE_RECORD_DEL_ALL), _TL("Table")) && m_pTable->Del_Records() )
 	{
-		BeginBatch();
-
-		if( m_pTable->Get_Selection_Count() >= m_pTable->Get_Count() )
-		{
-			SelectAll();
-		}
-		else
-		{
-			ClearSelection();
-
-			if( m_pTable->Get_Selection_Count() > 0 )
-			{
-				#pragma omp parallel for
-				for(int iRecord=0; iRecord<GetNumberRows(); iRecord++)
-				{
-					if( m_pRecords[iRecord]->is_Selected() )
-					{
-						SelectRow(iRecord, true);
-					}
-				}
-			}
-		}
-
-		EndBatch();
-
-		_Update_Views();
-
-		return( true );
+		_Update_Records();
 	}
-
-	return( false );
 }
 
-//---------------------------------------------------------
-void CVIEW_Table_Control::On_Select(wxGridRangeSelectEvent &event)
+void CVIEW_Table_Control::On_Record_Clr_UI(wxUpdateUIEvent &event)
 {
-	if( GetBatchCount() == 0 )
-	{
-		BeginBatch();
-
-		for(int iRow=event.GetTopRow(); iRow<=event.GetBottomRow(); iRow++)
-		{
-			if( m_pRecords[iRow]->is_Selected() != event.Selecting() )
-			{
-				m_pTable->Select(m_pRecords[iRow], true);
-			}
-		}
-
-		EndBatch();
-
-		_Update_Views();
-	}
-
-	event.Skip();
+	event.Enable(m_pTable->Get_Count() > 0);
 }
 
 
diff --git a/src/saga_core/saga_gui/view_table_control.h b/src/saga_core/saga_gui/view_table_control.h
index 32b51bf..51565f0 100644
--- a/src/saga_core/saga_gui/view_table_control.h
+++ b/src/saga_core/saga_gui/view_table_control.h
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: view_table_control.h 2074 2014-03-31 10:32:12Z oconrad $
+ * Version $Id: view_table_control.h 2730 2015-12-16 11:55:46Z oconrad $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -82,19 +82,6 @@
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
-#define TABLE_CTRL_FIXED_COLS	0x01
-#define TABLE_CTRL_FIXED_ROWS	0x02
-#define TABLE_CTRL_FIXED_TABLE	(TABLE_CTRL_FIXED_ROWS|TABLE_CTRL_FIXED_COLS)
-#define TABLE_CTRL_COL1ISLABEL	0x04
-
-
-///////////////////////////////////////////////////////////
-//														 //
-//														 //
-//														 //
-///////////////////////////////////////////////////////////
-
-//---------------------------------------------------------
 class CVIEW_Table_Control : public wxGrid
 {
 	DECLARE_CLASS(CVIEW_Table_Control)
@@ -103,77 +90,88 @@ public:
 	CVIEW_Table_Control(wxWindow *pParent, class CSG_Table *pTable, int Constraint);
 	virtual ~CVIEW_Table_Control(void);
 
-	void						On_Field_Add		(wxCommandEvent  &event);
-	void						On_Field_Add_UI		(wxUpdateUIEvent &event);
-	void						On_Field_Del		(wxCommandEvent  &event);
-	void						On_Field_Del_UI		(wxUpdateUIEvent &event);
-	void						On_Field_Sort		(wxCommandEvent  &event);
-	void						On_Field_Sort_UI	(wxUpdateUIEvent &event);
-	void						On_Field_Rename		(wxCommandEvent  &event);
-	void						On_Field_Rename_UI	(wxUpdateUIEvent &event);
-	void						On_Field_Type		(wxCommandEvent  &event);
-	void						On_Field_Type_UI	(wxUpdateUIEvent &event);
-
-	void						On_Record_Add		(wxCommandEvent  &event);
-	void						On_Record_Add_UI	(wxUpdateUIEvent &event);
-	void						On_Record_Ins		(wxCommandEvent  &event);
-	void						On_Record_Ins_UI	(wxUpdateUIEvent &event);
-	void						On_Record_Del		(wxCommandEvent  &event);
-	void						On_Record_Del_UI	(wxUpdateUIEvent &event);
-	void						On_Record_Clr		(wxCommandEvent  &event);
-	void						On_Record_Clr_UI	(wxUpdateUIEvent &event);
-
-	void						On_Sel_To_Top		(wxCommandEvent  &event);
-	void						On_Sel_To_Top_UI	(wxUpdateUIEvent &event);
-
-	void						On_Sel_Only			(wxCommandEvent  &event);
-	void						On_Sel_Only_UI		(wxUpdateUIEvent &event);
-
-	void						On_Autosize_Cols	(wxCommandEvent  &event);
-	void						On_Autosize_Rows	(wxCommandEvent  &event);
-
-	void						On_Size				(wxSizeEvent     &event);
-	void						On_Key				(wxKeyEvent      &event);
-
-	void						On_Edit_Start		(wxGridEvent     &event);
-	void						On_Edit_Stop		(wxGridEvent     &event);
-	void						On_Changed			(wxGridEvent     &event);
-	void						On_LClick			(wxGridEvent     &event);
-	void						On_LClick_Label		(wxGridEvent     &event);
-	void						On_RClick_Label		(wxGridEvent     &event);
-	void						On_LDClick_Label	(wxGridEvent     &event);
-	void						On_Select			(wxGridRangeSelectEvent &event);
-
-	void						Set_Labeling		(bool bOn);
+	bool						Load				(const wxString &File_Name);
+	bool						Save				(const wxString &File_Name, int Format = 0);
 
 	bool						Update_Table		(void);
 	bool						Update_Selection	(void);
-	bool						Update_Sorting		(int iField, int Direction);
 
-	bool						Add_Record			(void);
-	bool						Ins_Record			(void);
-	bool						Del_Record			(void);
-	bool						Del_Records			(void);
 
-	bool						Load				(const wxString &File_Name);
-	bool						Save				(const wxString &File_Name, int Format = 0);
+protected:
+
+	virtual void				AdjustScrollbars	(void);
+
+	void						On_Scroll			(wxScrollWinEvent &event);
+	void						On_Key				(wxKeyEvent       &event);
+	void						On_Size				(wxSizeEvent      &event);
+
+	void						On_Edit_Start		(wxGridEvent      &event);
+	void						On_Edit_Stop		(wxGridEvent      &event);
+	void						On_Changed			(wxGridEvent      &event);
+
+	void						On_LClick			(wxGridEvent      &event);
+	void						On_LClick_Label		(wxGridEvent      &event);
+	void						On_LDClick_Label	(wxGridEvent      &event);
+
+	void						On_RClick			(wxGridEvent      &event);
+	void						On_RClick_Label		(wxGridEvent      &event);
+
+	void						On_Select			(wxGridRangeSelectEvent &event);
+
+	void						On_Sel_Only			(wxCommandEvent   &event);
+	void						On_Sel_Only_UI		(wxUpdateUIEvent  &event);
+	void						On_Sel_Clear		(wxCommandEvent   &event);
+	void						On_Sel_Clear_UI		(wxUpdateUIEvent  &event);
+
+	void						On_Autosize_Cols	(wxCommandEvent   &event);
+	void						On_Autosize_Rows	(wxCommandEvent   &event);
+
+	void						On_Cell_Open		(wxCommandEvent   &event);
+
+	void						On_Field_Add		(wxCommandEvent   &event);
+	void						On_Field_Add_UI		(wxUpdateUIEvent  &event);
+	void						On_Field_Del		(wxCommandEvent   &event);
+	void						On_Field_Del_UI		(wxUpdateUIEvent  &event);
+	void						On_Field_Sort		(wxCommandEvent   &event);
+	void						On_Field_Sort_UI	(wxUpdateUIEvent  &event);
+	void						On_Field_Rename		(wxCommandEvent   &event);
+	void						On_Field_Rename_UI	(wxUpdateUIEvent  &event);
+	void						On_Field_Type		(wxCommandEvent   &event);
+	void						On_Field_Type_UI	(wxUpdateUIEvent  &event);
+
+	void						On_Record_Add		(wxCommandEvent   &event);
+	void						On_Record_Add_UI	(wxUpdateUIEvent  &event);
+	void						On_Record_Ins		(wxCommandEvent   &event);
+	void						On_Record_Ins_UI	(wxUpdateUIEvent  &event);
+	void						On_Record_Del		(wxCommandEvent   &event);
+	void						On_Record_Del_UI	(wxUpdateUIEvent  &event);
+	void						On_Record_Clr		(wxCommandEvent   &event);
+	void						On_Record_Clr_UI	(wxUpdateUIEvent  &event);
 
 
 private:
 
 	bool						m_bSelOnly, m_bEditing;
 
-	int							m_Constraint, m_Field_Offset;
-
-	class CSG_Table_Record		**m_pRecords;
+	int							m_Scroll_Start, m_Scroll_Range, m_Cursor;
 
 	class CSG_Table				*m_pTable;
 
 
 	void						_Update_Views		(void);
 
-	bool						_Set_Records		(bool bSelection_To_Top = false);
-	bool						_Set_Record			(int iRecord, class CSG_Table_Record *pRecord);
+	bool						_Update_Sorting		(int iField, int Direction);
+
+	bool						_Update_Records		(void);
+
+	int							_Get_Record_Count	(void);
+	CSG_Table_Record *			_Get_Record			(int iRow);
+	bool						_Set_Record			(int iRow);
+
+	int							_Get_Scroll_Start	(int Position);
+	bool						_Set_Scroll_Start	(int Position, bool bEnforceUpdate = true);
+
+	bool						_Get_DataSource		(wxString &Source);
 
 
 //---------------------------------------------------------
diff --git a/src/saga_core/saga_gui/wksp.cpp b/src/saga_core/saga_gui/wksp.cpp
index 561e3f8..d4a128a 100644
--- a/src/saga_core/saga_gui/wksp.cpp
+++ b/src/saga_core/saga_gui/wksp.cpp
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: wksp.cpp 2501 2015-06-12 10:02:42Z oconrad $
+ * Version $Id: wksp.cpp 2674 2015-11-03 17:03:58Z oconrad $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -321,11 +321,13 @@ void CWKSP::On_Command(wxCommandEvent &event)
 		m_pModules->On_Command(event);
 		break;
 
-	case ID_CMD_DATA_PROJECT_NEW:
 	case ID_CMD_DATA_PROJECT_OPEN:
 	case ID_CMD_DATA_PROJECT_OPEN_ADD:
+	case ID_CMD_DATA_PROJECT_CLOSE:
 	case ID_CMD_DATA_PROJECT_SAVE:
 	case ID_CMD_DATA_PROJECT_SAVE_AS:
+	case ID_CMD_DATA_PROJECT_COPY:
+	case ID_CMD_DATA_PROJECT_COPY_DB:
 	case ID_CMD_DATA_PROJECT_BROWSE:
 	case ID_CMD_TABLES_OPEN:
 	case ID_CMD_SHAPES_OPEN:
@@ -335,13 +337,9 @@ void CWKSP::On_Command(wxCommandEvent &event)
 		m_pData->On_Command(event);
 		break;
 
-	case ID_CMD_WKSP_OPEN:
+	case ID_CMD_DATA_OPEN:
 		Open();
 		break;
-
-	case ID_CMD_WKSP_SAVE:
-		g_pData->On_Command(ID_CMD_DATA_PROJECT_SAVE);
-		break;
 	}
 }
 
@@ -370,14 +368,17 @@ void CWKSP::On_Command_UI(wxUpdateUIEvent &event)
 		}
 		break;
 
-	case ID_CMD_WKSP_OPEN:
+	case ID_CMD_DATA_OPEN:
 		break;
 
 	case ID_CMD_MODULES_SEARCH:
 		m_pModules->On_Command_UI(event);
 		break;
 
-	case ID_CMD_WKSP_SAVE:
+	case ID_CMD_DATA_PROJECT_SAVE:
+	case ID_CMD_DATA_PROJECT_SAVE_AS:
+	case ID_CMD_DATA_PROJECT_COPY:
+	case ID_CMD_DATA_PROJECT_COPY_DB:
 		event.Enable(g_pData->Get_Count() > 0);
 		break;
 	}
diff --git a/src/saga_core/saga_gui/wksp_base_item.h b/src/saga_core/saga_gui/wksp_base_item.h
index 74ce44b..c83ca95 100644
--- a/src/saga_core/saga_gui/wksp_base_item.h
+++ b/src/saga_core/saga_gui/wksp_base_item.h
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: wksp_base_item.h 2548 2015-08-13 13:07:55Z oconrad $
+ * Version $Id: wksp_base_item.h 2700 2015-11-24 17:18:29Z oconrad $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -87,6 +87,7 @@
 //---------------------------------------------------------
 #define LAYER_DRAW_FLAG_NOEDITS		0x01
 #define LAYER_DRAW_FLAG_NOLABELS	0x02
+#define LAYER_DRAW_FLAG_THUMBNAIL	0x04
 
 
 ///////////////////////////////////////////////////////////
diff --git a/src/saga_core/saga_gui/wksp_data_item.cpp b/src/saga_core/saga_gui/wksp_data_item.cpp
index 4aa9044..ba314ca 100644
--- a/src/saga_core/saga_gui/wksp_data_item.cpp
+++ b/src/saga_core/saga_gui/wksp_data_item.cpp
@@ -338,13 +338,11 @@ bool CWKSP_Data_Item::DataObject_Changed(void)
 }
 
 //---------------------------------------------------------
-#include "wksp_grid.h"
-
 bool CWKSP_Data_Item::DataObject_Changed(CSG_Parameters *pParameters)
 {
-	if( !pParameters && Get_Type() == WKSP_ITEM_Grid )
+	if( !pParameters )
 	{
-		return( ((CWKSP_Grid *)this)->Fit_Color_Range() );
+		Fit_Colors();
 	}
 
 	m_Parameters.Assign_Values(pParameters);
diff --git a/src/saga_core/saga_gui/wksp_data_item.h b/src/saga_core/saga_gui/wksp_data_item.h
index 0acf9c6..88d5f15 100644
--- a/src/saga_core/saga_gui/wksp_data_item.h
+++ b/src/saga_core/saga_gui/wksp_data_item.h
@@ -125,6 +125,8 @@ protected:
 	virtual void					On_DataObject_Changed	(void);
 	virtual void					On_Update_Views			(bool bAll)	{}
 
+	virtual bool					Fit_Colors				(void)	{	return( true );	}
+
 	bool							Add_ScatterPlot			(void);
 
 
diff --git a/src/saga_core/saga_gui/wksp_data_manager.cpp b/src/saga_core/saga_gui/wksp_data_manager.cpp
index 94878a6..b55385b 100644
--- a/src/saga_core/saga_gui/wksp_data_manager.cpp
+++ b/src/saga_core/saga_gui/wksp_data_manager.cpp
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: wksp_data_manager.cpp 2633 2015-10-02 16:24:33Z oconrad $
+ * Version $Id: wksp_data_manager.cpp 2723 2015-12-11 10:18:03Z oconrad $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -168,6 +168,12 @@ CWKSP_Data_Manager::CWKSP_Data_Manager(void)
 	);
 
 	m_Parameters.Add_Value(
+		pNode	, "SHOW_FILE_SOURCES"		, _TL("Show Data File Sources"),
+		_TL("Show data sources tab for file system. Disabling might speed up start-up. Changes take effect after restart."),
+		PARAMETER_TYPE_Bool, true
+	);
+
+	m_Parameters.Add_Value(
 		pNode	, "NUMBERING"				, _TL("Numbering of Data Sets"),
 		_TL("Leading zeros for data set numbering. Set to -1 for not using numbers at all."),
 		PARAMETER_TYPE_Int, m_Numbering = 2, -1, true
@@ -466,18 +472,16 @@ wxMenu * CWKSP_Data_Manager::Get_Menu(void)
 
 	pMenu	= new wxMenu(_TL("Data"));
 
-//	CMD_Menu_Add_Item(pMenu, false, ID_CMD_WKSP_ITEM_CLOSE);
-
-//	pMenu->AppendSeparator();
-
-	CMD_Menu_Add_Item(pMenu, false, ID_CMD_DATA_PROJECT_NEW);
 	CMD_Menu_Add_Item(pMenu, false, ID_CMD_DATA_PROJECT_OPEN);
 //	CMD_Menu_Add_Item(pMenu, false, ID_CMD_DATA_PROJECT_OPEN_ADD);
+	CMD_Menu_Add_Item(pMenu, false, ID_CMD_DATA_PROJECT_CLOSE);
 
 	if( Get_Count() > 0 )
 	{
 		CMD_Menu_Add_Item(pMenu, false, ID_CMD_DATA_PROJECT_SAVE);
 		CMD_Menu_Add_Item(pMenu, false, ID_CMD_DATA_PROJECT_SAVE_AS);
+		CMD_Menu_Add_Item(pMenu, false, ID_CMD_DATA_PROJECT_COPY);
+	//	CMD_Menu_Add_Item(pMenu, false, ID_CMD_DATA_PROJECT_COPY_DB);
 		pMenu->AppendSeparator();
 		CMD_Menu_Add_Item(pMenu, false, ID_CMD_WKSP_ITEM_SEARCH);
 	}
@@ -533,12 +537,14 @@ bool CWKSP_Data_Manager::On_Command(int Cmd_ID)
 		return( CWKSP_Base_Manager::On_Command(Cmd_ID) );
 
 	//-----------------------------------------------------
-	case ID_CMD_DATA_PROJECT_NEW:		Close(false);						break;
 	case ID_CMD_DATA_PROJECT_OPEN:		m_pProject->Load(false);			break;
 	case ID_CMD_DATA_PROJECT_OPEN_ADD:	m_pProject->Load(true);				break;
+	case ID_CMD_DATA_PROJECT_BROWSE:	Open_Browser();						break;
+	case ID_CMD_DATA_PROJECT_CLOSE:		Close(false);						break;
 	case ID_CMD_DATA_PROJECT_SAVE:		m_pProject->Save(true);				break;
 	case ID_CMD_DATA_PROJECT_SAVE_AS:	m_pProject->Save();					break;
-	case ID_CMD_DATA_PROJECT_BROWSE:	Open_Browser();						break;
+	case ID_CMD_DATA_PROJECT_COPY:		m_pProject->Copy();					break;
+	case ID_CMD_DATA_PROJECT_COPY_DB:	m_pProject->CopyToDB();				break;
 
 	//-----------------------------------------------------
 	case ID_CMD_TABLES_OPEN:			Open(DATAOBJECT_TYPE_Table);		break;
@@ -568,7 +574,7 @@ bool CWKSP_Data_Manager::On_Command_UI(wxUpdateUIEvent &event)
 	default:
 		return( CWKSP_Base_Manager::On_Command_UI(event) );
 
-	case ID_CMD_DATA_PROJECT_NEW:
+	case ID_CMD_DATA_PROJECT_CLOSE:
 		event.Enable(Get_Count() > 0 && g_pModule == NULL);
 		break;
 
diff --git a/src/saga_core/saga_gui/wksp_data_menu_file.cpp b/src/saga_core/saga_gui/wksp_data_menu_file.cpp
index d9d2052..8bf4c41 100644
--- a/src/saga_core/saga_gui/wksp_data_menu_file.cpp
+++ b/src/saga_core/saga_gui/wksp_data_menu_file.cpp
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: wksp_data_menu_file.cpp 2583 2015-09-16 18:55:03Z oconrad $
+ * Version $Id: wksp_data_menu_file.cpp 2674 2015-11-03 17:03:58Z oconrad $
  *********************************************************/
 	
 ///////////////////////////////////////////////////////////
@@ -225,12 +225,14 @@ void CWKSP_Data_Menu_File::Update(wxMenu *pMenu)
 			return;
 
 		case DATAOBJECT_TYPE_Undefined:
-//			CMD_Menu_Add_Item(pMenu, false, ID_CMD_DATA_PROJECT_NEW);
 			CMD_Menu_Add_Item(pMenu, false, ID_CMD_DATA_PROJECT_OPEN);
-//			CMD_Menu_Add_Item(pMenu, false, ID_CMD_DATA_PROJECT_OPEN_ADD);
-//			CMD_Menu_Add_Item(pMenu, false, ID_CMD_DATA_PROJECT_SAVE);
-			CMD_Menu_Add_Item(pMenu, false, ID_CMD_DATA_PROJECT_SAVE_AS);
+		//	CMD_Menu_Add_Item(pMenu, false, ID_CMD_DATA_PROJECT_OPEN_ADD);
 			CMD_Menu_Add_Item(pMenu, false, ID_CMD_DATA_PROJECT_BROWSE);
+			CMD_Menu_Add_Item(pMenu, false, ID_CMD_DATA_PROJECT_CLOSE);
+			CMD_Menu_Add_Item(pMenu, false, ID_CMD_DATA_PROJECT_SAVE);
+			CMD_Menu_Add_Item(pMenu, false, ID_CMD_DATA_PROJECT_SAVE_AS);
+			CMD_Menu_Add_Item(pMenu, false, ID_CMD_DATA_PROJECT_COPY);
+		//	CMD_Menu_Add_Item(pMenu, false, ID_CMD_DATA_PROJECT_COPY_DB);
 			break;
 
 		case DATAOBJECT_TYPE_Table:
diff --git a/src/saga_core/saga_gui/wksp_data_menu_files.cpp b/src/saga_core/saga_gui/wksp_data_menu_files.cpp
index e9fe7f2..2527da4 100644
--- a/src/saga_core/saga_gui/wksp_data_menu_files.cpp
+++ b/src/saga_core/saga_gui/wksp_data_menu_files.cpp
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: wksp_data_menu_files.cpp 2551 2015-08-14 15:24:25Z oconrad $
+ * Version $Id: wksp_data_menu_files.cpp 2674 2015-11-03 17:03:58Z oconrad $
  *********************************************************/
 	
 ///////////////////////////////////////////////////////////
@@ -85,9 +85,7 @@ CWKSP_Data_Menu_Files::CWKSP_Data_Menu_Files(void)
 	m_bUpdate	= true;
 	m_pMenu		= new wxMenu;
 
-	CMD_Menu_Add_Item(m_pMenu, false, ID_CMD_WKSP_OPEN);
-	CMD_Menu_Add_Item(m_pMenu, false, ID_CMD_WKSP_SAVE);
-	CMD_Menu_Add_Item(m_pMenu, false, ID_CMD_DATA_PROJECT_NEW);
+	CMD_Menu_Add_Item(m_pMenu, false, ID_CMD_DATA_OPEN);
 
 	m_pMenu->AppendSeparator();
 	m_pMenu->Append(ID_CMD_DATA_FIRST      , _TL("Project")    , m_Projects   .Create(DATAOBJECT_TYPE_Undefined));
diff --git a/src/saga_core/saga_gui/wksp_grid.cpp b/src/saga_core/saga_gui/wksp_grid.cpp
index 6cfc340..30e89c6 100644
--- a/src/saga_core/saga_gui/wksp_grid.cpp
+++ b/src/saga_core/saga_gui/wksp_grid.cpp
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: wksp_grid.cpp 2650 2015-10-15 17:01:38Z oconrad $
+ * Version $Id: wksp_grid.cpp 2716 2015-12-04 11:55:42Z oconrad $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -101,7 +101,7 @@ CWKSP_Grid::CWKSP_Grid(CSG_Grid *pGrid)
 
 	DataObject_Changed();
 
-	Fit_Color_Range();
+	Fit_Colors();
 }
 
 
@@ -623,6 +623,27 @@ bool CWKSP_Grid::Update(CWKSP_Layer *pChanged)
 //---------------------------------------------------------
 int CWKSP_Grid::On_Parameter_Changed(CSG_Parameters *pParameters, CSG_Parameter *pParameter, int Flags)
 {
+	//-----------------------------------------------------
+	if( Flags & PARAMETER_CHECK_VALUES )
+	{
+		if(	!SG_STR_CMP(pParameter->Get_Identifier(), "GENERAL_Z_FACTOR")
+		||	!SG_STR_CMP(pParameter->Get_Identifier(), "GENERAL_Z_OFFSET") )
+		{
+			double	newFactor	= pParameters->Get_Parameter("GENERAL_Z_FACTOR")->asDouble(), oldFactor	= m_Parameters("GENERAL_Z_FACTOR")->asDouble();
+			double	newOffset	= pParameters->Get_Parameter("GENERAL_Z_OFFSET")->asDouble(), oldOffset	= m_Parameters("GENERAL_Z_OFFSET")->asDouble();
+
+			if( newFactor != 0.0 && oldFactor != 0.0 )
+			{
+				CSG_Parameter_Range	*newRange	= pParameters->Get_Parameter("METRIC_ZRANGE")->asRange();
+				CSG_Parameter_Range	*oldRange	= m_Parameters.Get_Parameter("METRIC_ZRANGE")->asRange();
+
+				newRange->Set_LoVal(((oldRange->Get_LoVal() - oldOffset) / oldFactor) * newFactor + newOffset);
+				newRange->Set_HiVal(((oldRange->Get_HiVal() - oldOffset) / oldFactor) * newFactor + newOffset);
+			}
+		}
+	}
+
+	//-----------------------------------------------------
 	if( Flags & PARAMETER_CHECK_ENABLE )
 	{
 		if(	!SG_STR_CMP(pParameter->Get_Identifier(), "COLORS_TYPE") )
@@ -981,7 +1002,7 @@ bool CWKSP_Grid::Edit_On_Mouse_Up(CSG_Point Point, double ClientToWorld, int Key
 
 			for(x=0; x<nx; x++)
 			{
-				m_Edit_Attributes.Add_Field(CSG_String::Format(SG_T("%d"), x + 1), SG_DATATYPE_Double);
+				m_Edit_Attributes.Add_Field(CSG_String::Format(SG_T("%d"), x + 1), Get_Grid()->Get_Type());
 			}
 
 			for(y=0; y<ny; y++)
@@ -1099,7 +1120,7 @@ bool CWKSP_Grid::_Edit_Del_Selection(void)
 ///////////////////////////////////////////////////////////
 
 //---------------------------------------------------------
-bool CWKSP_Grid::Fit_Color_Range(void)
+bool CWKSP_Grid::Fit_Colors(void)
 {
 	switch( g_pData->Get_Parameter("GRID_COLORS_FIT")->asInt() )
 	{
diff --git a/src/saga_core/saga_gui/wksp_grid.h b/src/saga_core/saga_gui/wksp_grid.h
index 2986428..55b9f1d 100644
--- a/src/saga_core/saga_gui/wksp_grid.h
+++ b/src/saga_core/saga_gui/wksp_grid.h
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: wksp_grid.h 2548 2015-08-13 13:07:55Z oconrad $
+ * Version $Id: wksp_grid.h 2716 2015-12-04 11:55:42Z oconrad $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -101,7 +101,6 @@ public:
 	virtual wxString			Get_Value				(CSG_Point ptWorld, double Epsilon);
 	virtual double				Get_Value_Range			(void);
 
-	bool						Fit_Color_Range			(void);
 	bool						Fit_Color_Range			(CSG_Rect rWorld);
 
 	virtual bool				asImage					(CSG_Grid *pImage);
@@ -125,6 +124,8 @@ protected:
 	virtual void				On_Parameters_Changed	(void);
 	virtual int					On_Parameter_Changed	(CSG_Parameters *pParameters, CSG_Parameter *pParameter, int Flags);
 
+	virtual bool				Fit_Colors				(void);
+
 	virtual void				On_Draw					(CWKSP_Map_DC &dc_Map, int Flags);
 
 
diff --git a/src/saga_core/saga_gui/wksp_layer.cpp b/src/saga_core/saga_gui/wksp_layer.cpp
index 8e0210c..cb8785b 100644
--- a/src/saga_core/saga_gui/wksp_layer.cpp
+++ b/src/saga_core/saga_gui/wksp_layer.cpp
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: wksp_layer.cpp 2548 2015-08-13 13:07:55Z oconrad $
+ * Version $Id: wksp_layer.cpp 2700 2015-11-24 17:18:29Z oconrad $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -460,7 +460,7 @@ bool CWKSP_Layer::_Set_Thumbnail(bool bRefresh)
 		wxRect			r(0, 0, m_Thumbnail.GetWidth(), m_Thumbnail.GetHeight());
 		CWKSP_Map_DC	dc_Map(Get_Extent(), r, 1.0, SG_GET_RGB(255, 255, 255));
 
-		Draw(dc_Map, LAYER_DRAW_FLAG_NOEDITS|LAYER_DRAW_FLAG_NOLABELS);
+		Draw(dc_Map, LAYER_DRAW_FLAG_NOEDITS|LAYER_DRAW_FLAG_NOLABELS|LAYER_DRAW_FLAG_THUMBNAIL);
 
 		dc.SelectObject(m_Thumbnail);
 		dc.SetBackground(*wxWHITE_BRUSH);
diff --git a/src/saga_core/saga_gui/wksp_map.cpp b/src/saga_core/saga_gui/wksp_map.cpp
index 5e4ef9e..fa70cbf 100644
--- a/src/saga_core/saga_gui/wksp_map.cpp
+++ b/src/saga_core/saga_gui/wksp_map.cpp
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: wksp_map.cpp 2552 2015-08-14 15:25:36Z oconrad $
+ * Version $Id: wksp_map.cpp 2681 2015-11-06 12:31:05Z oconrad $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -1384,6 +1384,81 @@ void CWKSP_Map::SaveAs_Image_Clipboard(int nx, int ny, int frame)
 }
 
 //---------------------------------------------------------
+void CWKSP_Map::SaveAs_Image_To_KMZ(int nx, int ny)
+{
+	if( nx < 1 || ny < 1 )
+	{
+		return;
+	}
+
+	//-----------------------------------------------------
+	CSG_Rect		Extent(Get_Extent());
+
+	CSG_Parameters	P(NULL, _TL("Save Map to KMZ"), _TL(""));
+
+	P.Add_FilePath(NULL, "FILE"    , _TL("File"    ), _TL(""), CSG_String::Format("%s|*.kmz|%s|*.*", _TL("KMZ Files"), _TL("All Files")), NULL, true);
+	P.Add_Value   (NULL, "CELLSIZE", _TL("Cellsize"), _TL(""), PARAMETER_TYPE_Double, SG_Get_Rounded_To_SignificantFigures(Extent.Get_XRange() / (double)nx, 2), 0.0, true);
+	P.Add_Value   (NULL, "LOAD"    , _TL("Load"    ), _TL(""), PARAMETER_TYPE_Bool  , true);
+
+	if( !DLG_Parameters(&P) || P("CELLSIZE")->asDouble() <= 0.0 )
+	{
+		return;
+	}
+
+	wxFileName	FileName(P("FILE")->asString());
+
+	if( !FileName.IsOk() )
+	{
+		DLG_Message_Show_Error(_TL("invalid file name"), _TL("Save Map to KMZ"));
+
+		return;
+	}
+
+	//-----------------------------------------------------
+	nx	= Extent.Get_XRange() / P("CELLSIZE")->asDouble();
+	ny	= Extent.Get_YRange() / P("CELLSIZE")->asDouble();
+
+	wxImage		Image(nx, ny);
+
+	if( !Get_Image(Image, Extent) )
+	{
+		return;
+	}
+
+	//-----------------------------------------------------
+	CSG_Grid	Map(SG_DATATYPE_Int, Image.GetWidth(), Image.GetHeight(), Extent.Get_XRange() / (double)Image.GetWidth(), Extent.Get_XMin(), Extent.Get_YMin());
+
+	Map.Set_Name(Get_Name().wx_str());
+	Map.Set_NoData_Value(16711935);
+	Map.Get_Projection().Create(m_Projection);
+
+	for(int y=0, yy=Map.Get_NY()-1; y<Map.Get_NY(); y++, yy--)
+	{
+		for(int x=0; x<Map.Get_NX(); x++)
+		{
+			Map.Set_Value(x, y, SG_GET_RGB(Image.GetRed(x, yy), Image.GetGreen(x, yy), Image.GetBlue(x, yy)));
+		}
+	}
+
+	//-----------------------------------------------------
+	bool	bResult;
+
+	SG_RUN_MODULE(bResult, "io_grid_image", 2,
+			SG_MODULE_PARAMETER_SET("GRID"     , &Map)
+		&&	SG_MODULE_PARAMETER_SET("FILE"     , FileName.GetFullPath().wc_str())
+		&&	SG_MODULE_PARAMETER_SET("COLOURING", 4)	// rgb coded values
+		&&	SG_MODULE_PARAMETER_SET("OUTPUT"   , 2)	// kmz file
+	);
+
+	if( bResult && P("LOAD")->asBool() )
+	{
+		FileName.SetExt("kmz");
+
+		Open_Application(FileName.GetFullPath());
+	}
+}
+
+//---------------------------------------------------------
 void CWKSP_Map::SaveAs_Image_To_Memory(int nx, int ny)
 {
 	if( nx < 1 || ny < 1 )
diff --git a/src/saga_core/saga_gui/wksp_map.h b/src/saga_core/saga_gui/wksp_map.h
index 709e40b..9082770 100644
--- a/src/saga_core/saga_gui/wksp_map.h
+++ b/src/saga_core/saga_gui/wksp_map.h
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: wksp_map.h 2548 2015-08-13 13:07:55Z oconrad $
+ * Version $Id: wksp_map.h 2681 2015-11-06 12:31:05Z oconrad $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -180,6 +180,7 @@ public:
 	void						SaveAs_Image			(void);
 	void						SaveAs_Image_Clipboard	(int nx, int ny, int frame);
 	void						SaveAs_Image_Clipboard	(bool bLegend = false);
+	void						SaveAs_Image_To_KMZ		(int nx, int ny);
 	void						SaveAs_Image_To_Memory	(int nx, int ny);
 	void						SaveAs_Image_On_Change	(void);
 	void						SaveAs_Image_To_Grid	(CSG_Grid &Grid, int Size);
diff --git a/src/saga_core/saga_gui/wksp_module.cpp b/src/saga_core/saga_gui/wksp_module.cpp
index b432a29..5cf0615 100644
--- a/src/saga_core/saga_gui/wksp_module.cpp
+++ b/src/saga_core/saga_gui/wksp_module.cpp
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: wksp_module.cpp 2530 2015-07-01 07:08:40Z oconrad $
+ * Version $Id: wksp_module.cpp 2686 2015-11-12 16:36:59Z oconrad $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -828,7 +828,7 @@ void CWKSP_Module::_Get_CMD(CSG_String &Command, CSG_Parameters *pParameters)
 			break;
 
 		case PARAMETER_TYPE_Table_Fields:
-			if( p->asString() != '\0' )
+			if( p->asString() && *p->asString() )
 				Command	+= CSG_String::Format(SG_T(" -%s=%s"), GET_ID1(p), p->asString());
 			break;
 
diff --git a/src/saga_core/saga_gui/wksp_module_manager.cpp b/src/saga_core/saga_gui/wksp_module_manager.cpp
index 5c0e289..6a5d902 100644
--- a/src/saga_core/saga_gui/wksp_module_manager.cpp
+++ b/src/saga_core/saga_gui/wksp_module_manager.cpp
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: wksp_module_manager.cpp 2496 2015-05-21 14:16:21Z oconrad $
+ * Version $Id: wksp_module_manager.cpp 2723 2015-12-11 10:18:03Z oconrad $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -145,7 +145,7 @@ CWKSP_Module_Manager::CWKSP_Module_Manager(void)
 	m_Parameters.Add_Value(
 		pNode	, "BEEP"			, _TL("Beep when finished"),
 		_TL(""),
-		PARAMETER_TYPE_Bool	, true
+		PARAMETER_TYPE_Bool	, false
 	);
 
 	m_Parameters.Add_Choice(
diff --git a/src/saga_core/saga_gui/wksp_module_menu.cpp b/src/saga_core/saga_gui/wksp_module_menu.cpp
index aa10ae6..3ab1a38 100644
--- a/src/saga_core/saga_gui/wksp_module_menu.cpp
+++ b/src/saga_core/saga_gui/wksp_module_menu.cpp
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: wksp_module_menu.cpp 2349 2014-12-11 13:42:58Z oconrad $
+ * Version $Id: wksp_module_menu.cpp 2678 2015-11-05 18:29:16Z oconrad $
  *********************************************************/
 	
 ///////////////////////////////////////////////////////////
@@ -111,19 +111,19 @@ void CWKSP_Menu_Modules::Update(void)
 	}
 
 	//-----------------------------------------------------
-	int		ID_Menu;
+	wxMenuBar	*pMenuBar	= m_pMenu->GetMenuBar();
 
-	while( (ID_Menu = m_pMenu->GetMenuItemCount()) > 0 )
+	if( pMenuBar )
 	{
-		m_pMenu->Destroy(m_pMenu->GetMenuItems().Item(ID_Menu - 1)->GetData());
+		pMenuBar->Replace(1, new wxMenu, _TL("Geoprocessing"));
 	}
 
+	delete(m_pMenu);	m_pMenu	= new wxMenu;
+
 	//-----------------------------------------------------
 	if( g_pModules->Get_Count() > 0 )
 	{
-		ID_Menu	= ID_CMD_MODULE_START;
-
-		for(int iGroup=0; iGroup<g_pModules->Get_Count(); iGroup++)
+		for(int iGroup=0, ID_Menu=ID_CMD_MODULE_START; iGroup<g_pModules->Get_Count(); iGroup++)
 		{
 			for(int iLibrary=0; iLibrary<g_pModules->Get_Group(iGroup)->Get_Count(); iLibrary++)
 			{
@@ -157,8 +157,9 @@ void CWKSP_Menu_Modules::Update(void)
 		}
 
 		m_pMenu->InsertSeparator(0);
-		CMD_Menu_Ins_Item(m_pMenu, false, ID_CMD_MODULES_OPEN	, 0);
-		CMD_Menu_Ins_Item(m_pMenu, false, ID_CMD_MODULES_SEARCH	, 1);
+
+		CMD_Menu_Ins_Item(m_pMenu, false, ID_CMD_MODULES_OPEN  , 0);
+		CMD_Menu_Ins_Item(m_pMenu, false, ID_CMD_MODULES_SEARCH, 1);
 
 		_Set_Recent(m_pMenu);
 	}
@@ -166,6 +167,11 @@ void CWKSP_Menu_Modules::Update(void)
 	{
 		CMD_Menu_Add_Item(m_pMenu, false, ID_CMD_MODULES_OPEN);
 	}
+
+	if( pMenuBar )
+	{
+		delete(pMenuBar->Replace(1, m_pMenu, _TL("Geoprocessing")));
+	}
 }
 
 //---------------------------------------------------------
diff --git a/src/saga_core/saga_gui/wksp_pointcloud.cpp b/src/saga_core/saga_gui/wksp_pointcloud.cpp
index cf6e547..fd5a46e 100644
--- a/src/saga_core/saga_gui/wksp_pointcloud.cpp
+++ b/src/saga_core/saga_gui/wksp_pointcloud.cpp
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: wksp_pointcloud.cpp 2650 2015-10-15 17:01:38Z oconrad $
+ * Version $Id: wksp_pointcloud.cpp 2716 2015-12-04 11:55:42Z oconrad $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -73,7 +73,7 @@
 
 #include "wksp_pointcloud.h"
 #include "wksp_table.h"
-
+#include "view_table.h"
 #include "view_scatterplot.h"
 
 
@@ -87,10 +87,10 @@
 CWKSP_PointCloud::CWKSP_PointCloud(CSG_PointCloud *pPointCloud)
 	: CWKSP_Layer(pPointCloud)
 {
-	m_pTable		= new CWKSP_Table(pPointCloud);
+	m_pTable	= new CWKSP_Table(pPointCloud);
 
 	m_Edit_Attributes.Destroy();
-	m_Edit_Attributes.Add_Field(_TL("Name") , SG_DATATYPE_String);
+	m_Edit_Attributes.Add_Field(_TL("Name" ), SG_DATATYPE_String);
 	m_Edit_Attributes.Add_Field(_TL("Value"), SG_DATATYPE_String);
 
 	//-----------------------------------------------------
@@ -98,7 +98,7 @@ CWKSP_PointCloud::CWKSP_PointCloud(CSG_PointCloud *pPointCloud)
 
 	DataObject_Changed();
 
-	m_Parameters("COLORS_TYPE"  )->Set_Value(CLASSIFY_METRIC);
+	m_Parameters("COLORS_TYPE"  )->Set_Value(CLASSIFY_GRADUATED);
 	m_Parameters("METRIC_ATTRIB")->Set_Value(2);
 
 	On_Parameter_Changed(&m_Parameters, m_Parameters("METRIC_ATTRIB"), PARAMETER_CHECK_ALL);
@@ -129,17 +129,17 @@ wxString CWKSP_PointCloud::Get_Description(void)
 
 	s	+= wxT("<table border=\"0\">");
 
-	DESC_ADD_STR(_TL("Name")			, m_pObject->Get_Name());
-	DESC_ADD_STR(_TL("Description")		, m_pObject->Get_Description());
-	DESC_ADD_STR(_TL("File")			, SG_File_Exists(m_pObject->Get_File_Name()) ? m_pObject->Get_File_Name() : _TL("memory"));
-	DESC_ADD_STR(_TL("Modified")		, m_pObject->is_Modified() ? _TL("yes") : _TL("no"));
-	DESC_ADD_STR(_TL("Projection")		, m_pObject->Get_Projection().Get_Description().c_str());
-	DESC_ADD_FLT(_TL("West")			, Get_PointCloud()->Get_Extent().Get_XMin());
-	DESC_ADD_FLT(_TL("East")			, Get_PointCloud()->Get_Extent().Get_XMax());
-	DESC_ADD_FLT(_TL("West-East")		, Get_PointCloud()->Get_Extent().Get_XRange());
-	DESC_ADD_FLT(_TL("South")			, Get_PointCloud()->Get_Extent().Get_YMin());
-	DESC_ADD_FLT(_TL("North")			, Get_PointCloud()->Get_Extent().Get_YMax());
-	DESC_ADD_FLT(_TL("South-North")		, Get_PointCloud()->Get_Extent().Get_YRange());
+	DESC_ADD_STR(_TL("Name"            ), m_pObject->Get_Name());
+	DESC_ADD_STR(_TL("Description"     ), m_pObject->Get_Description());
+	DESC_ADD_STR(_TL("File"            ), SG_File_Exists(m_pObject->Get_File_Name()) ? m_pObject->Get_File_Name() : _TL("memory"));
+	DESC_ADD_STR(_TL("Modified"        ), m_pObject->is_Modified() ? _TL("yes") : _TL("no"));
+	DESC_ADD_STR(_TL("Projection"      ), m_pObject->Get_Projection().Get_Description().c_str());
+	DESC_ADD_FLT(_TL("West"            ), Get_PointCloud()->Get_Extent().Get_XMin());
+	DESC_ADD_FLT(_TL("East"            ), Get_PointCloud()->Get_Extent().Get_XMax());
+	DESC_ADD_FLT(_TL("West-East"       ), Get_PointCloud()->Get_Extent().Get_XRange());
+	DESC_ADD_FLT(_TL("South"           ), Get_PointCloud()->Get_Extent().Get_YMin());
+	DESC_ADD_FLT(_TL("North"           ), Get_PointCloud()->Get_Extent().Get_YMax());
+	DESC_ADD_FLT(_TL("South-North"     ), Get_PointCloud()->Get_Extent().Get_YRange());
 	DESC_ADD_INT(_TL("Number of Points"), Get_PointCloud()->Get_Count());
 
 	s	+= wxT("</table>");
@@ -252,6 +252,7 @@ bool CWKSP_PointCloud::On_Command(int Cmd_ID)
 		if( Get_PointCloud()->Get_Selection_Count() > 0 && DLG_Message_Confirm(_TL("Delete selected point(s)."), _TL("Edit Point Cloud")) )
 		{
 			Get_PointCloud()->Del_Selection();
+
 			Update_Views();
 		}
 		break;
@@ -427,10 +428,8 @@ int CWKSP_PointCloud::On_Parameter_Changed(CSG_Parameters *pParameters, CSG_Para
 	//-----------------------------------------------------
 	if( Flags & PARAMETER_CHECK_VALUES )
 	{
-		if(	!SG_STR_CMP(pParameter->Get_Identifier(), wxT("METRIC_ATTRIB")) )
+		if(	!SG_STR_CMP(pParameter->Get_Identifier(), "METRIC_ATTRIB") )
 		{
-			CSG_Parameters	Parameters;
-	
 			int		zField	= pParameter->asInt();
 
 			double	m	= Get_PointCloud()->Get_Mean  (zField);
@@ -445,14 +444,14 @@ int CWKSP_PointCloud::On_Parameter_Changed(CSG_Parameters *pParameters, CSG_Para
 	//-----------------------------------------------------
 	if( Flags & PARAMETER_CHECK_ENABLE )
 	{
-		if(	!SG_STR_CMP(pParameter->Get_Identifier(), SG_T("COLORS_TYPE")) )
+		if(	!SG_STR_CMP(pParameter->Get_Identifier(), "COLORS_TYPE") )
 		{
 			int	Value	= pParameter->asInt();
 
-			pParameters->Get_Parameter("NODE_UNISYMBOL")->Set_Enabled(Value == CLASSIFY_UNIQUE);
-			pParameters->Get_Parameter("NODE_LUT"      )->Set_Enabled(Value == CLASSIFY_LUT);
-			pParameters->Get_Parameter("NODE_METRIC"   )->Set_Enabled(Value == CLASSIFY_METRIC || Value == CLASSIFY_GRADUATED);
-			pParameters->Get_Parameter("NODE_RGB"	   )->Set_Enabled(Value == 4);
+			pParameters->Set_Enabled("NODE_UNISYMBOL", Value == CLASSIFY_UNIQUE);
+			pParameters->Set_Enabled("NODE_LUT"      , Value == CLASSIFY_LUT);
+			pParameters->Set_Enabled("NODE_METRIC"   , Value == CLASSIFY_METRIC || Value == CLASSIFY_GRADUATED);
+			pParameters->Set_Enabled("NODE_RGB"	     , Value == 4);
 
 			return( 1 );
 		}
@@ -468,6 +467,22 @@ void CWKSP_PointCloud::On_Update_Views(void)
 	m_pTable->Update_Views();
 }
 
+//---------------------------------------------------------
+bool CWKSP_PointCloud::Fit_Colors(void)
+{
+	if( m_Color_Field >= Get_PointCloud()->Get_Field_Count() )
+	{
+		m_Color_Field	= Get_PointCloud()->Get_Field_Count() - 1;
+	}
+
+	double	m	= Get_PointCloud()->Get_Mean  (m_Color_Field);
+	double	s	= Get_PointCloud()->Get_StdDev(m_Color_Field) * 2.0;
+
+	m_Parameters("METRIC_ZRANGE")->asRange()->Set_Range(m - s, m + s);
+
+	return( true );
+}
+
 
 ///////////////////////////////////////////////////////////
 //														 //
@@ -836,6 +851,7 @@ bool CWKSP_PointCloud::Edit_On_Mouse_Up(CSG_Point Point, double ClientToWorld, i
 
 		//-----------------------------------------------------
 		m_Edit_Attributes.Del_Records();
+		m_Edit_Index	= 0;
 
 		CSG_Table_Record	*pRecord	= Get_PointCloud()->Get_Selection();
 
@@ -852,6 +868,11 @@ bool CWKSP_PointCloud::Edit_On_Mouse_Up(CSG_Point Point, double ClientToWorld, i
 		//-----------------------------------------------------
 		g_pACTIVE->Get_Attributes()->Set_Attributes();
 
+		if( m_pTable->Get_View() )
+		{
+			m_pTable->Get_View()->Update_Selection();
+		}
+
 		Update_Views(false);
 	}
 
@@ -859,6 +880,38 @@ bool CWKSP_PointCloud::Edit_On_Mouse_Up(CSG_Point Point, double ClientToWorld, i
 }
 
 //---------------------------------------------------------
+bool CWKSP_PointCloud::Edit_Set_Index(int Index)
+{
+	m_Edit_Attributes.Del_Records();
+
+	if( Index > (int)Get_PointCloud()->Get_Selection_Count() )
+	{
+		Index	= Get_PointCloud()->Get_Selection_Count();
+	}
+
+	CSG_Table_Record	*pSelection	= Get_PointCloud()->Get_Selection(Index);
+
+	if( pSelection )
+	{
+		m_Edit_Index	= Index;
+
+		for(int i=0; i<Get_PointCloud()->Get_Field_Count(); i++)
+		{
+			CSG_Table_Record	*pRecord	= m_Edit_Attributes.Add_Record();
+
+			pRecord->Set_Value(0, pSelection->Get_Table()->Get_Field_Name(i));
+			pRecord->Set_Value(1, pSelection->asString(i));
+		}
+	}
+	else
+	{
+		m_Edit_Index	= 0;
+	}
+
+	return( true );
+}
+
+//---------------------------------------------------------
 bool CWKSP_PointCloud::Edit_Set_Attributes(void)
 {
 	CSG_Table_Record	*pSelection	= Get_PointCloud()->Get_Selection(m_Edit_Index);
@@ -890,7 +943,14 @@ void CWKSP_PointCloud::On_Draw(CWKSP_Map_DC &dc_Map, int Flags)
 {
 	if( Get_Extent().Intersects(dc_Map.m_rWorld) != INTERSECTION_None && dc_Map.IMG_Draw_Begin(m_Parameters("DISPLAY_TRANSPARENCY")->asDouble() / 100.0) )
 	{
-		_Draw_Points	(dc_Map);
+		if( (Flags & LAYER_DRAW_FLAG_THUMBNAIL) == 0 )
+		{
+			_Draw_Points   (dc_Map);
+		}
+		else
+		{
+			_Draw_Thumbnail(dc_Map);
+		}
 
 		dc_Map.IMG_Draw_End();
 	}
@@ -974,27 +1034,35 @@ void CWKSP_PointCloud::_Draw_Points(CWKSP_Map_DC &dc_Map)
 	}
 
 	//-----------------------------------------------------
-	for(int i=0; i<Get_PointCloud()->Get_Count(); i++)
+	CSG_PointCloud	*pPoints	= Get_PointCloud();
+
+	int	Selection	= pPoints->Get_Selection_Count() > 0 ? (int)pPoints->Get_Selection_Index(m_Edit_Index) : -1;
+
+	for(int i=0; i<pPoints->Get_Count(); i++)
 	{
-		if( !Get_PointCloud()->is_NoData(i, m_Color_Field) )
+		pPoints->Set_Cursor(i);
+
+		if( !pPoints->is_NoData(m_Color_Field) )
 		{
-			TSG_Point_Z	Point	= Get_PointCloud()->Get_Point(i);
+			TSG_Point_Z	Point	= pPoints->Get_Point();
 
 			if( dc_Map.m_rWorld.Contains(Point.x, Point.y) )
 			{
 				int		x	= (int)dc_Map.xWorld2DC(Point.x);
 				int		y	= (int)dc_Map.yWorld2DC(Point.y);
 
-				if( Get_PointCloud()->is_Selected(i) )
+				if( Selection >= 0 && pPoints->is_Selected(i) )
 				{
-					_Draw_Point(dc_Map, x, y, Point.z, SG_COLOR_RED   , m_PointSize + 2);
-					_Draw_Point(dc_Map, x, y, Point.z, SG_COLOR_YELLOW, m_PointSize);
+					int	Size	= Selection == i ? 2 + m_PointSize : m_PointSize;
+
+					_Draw_Point(dc_Map, x, y, Point.z, SG_COLOR_YELLOW, Size    );
+					_Draw_Point(dc_Map, x, y, Point.z, SG_COLOR_RED   , Size + 2);
 				}
 				else
 				{
 					int		Color;
 
-					m_pClassify->Get_Class_Color_byValue(Get_PointCloud()->Get_Value(i, m_Color_Field), Color);
+					m_pClassify->Get_Class_Color_byValue(pPoints->Get_Value(m_Color_Field), Color);
 
 					_Draw_Point(dc_Map, x, y, Point.z, Color, m_PointSize);
 				}
@@ -1003,6 +1071,33 @@ void CWKSP_PointCloud::_Draw_Points(CWKSP_Map_DC &dc_Map)
 	}
 }
 
+//---------------------------------------------------------
+void CWKSP_PointCloud::_Draw_Thumbnail(CWKSP_Map_DC &dc_Map)
+{
+	CSG_PointCloud	*pPoints	= Get_PointCloud();
+
+	int	n	= 1 + (int)(pPoints->Get_Count() / (2 * dc_Map.m_rDC.GetWidth() * dc_Map.m_rDC.GetHeight()));
+
+	for(int i=0; i<pPoints->Get_Count(); i+=n)
+	{
+		pPoints->Set_Cursor(i);
+
+		if( !pPoints->is_NoData(m_Color_Field) )
+		{
+			TSG_Point_Z	Point	= pPoints->Get_Point();
+
+			int	x	= (int)dc_Map.xWorld2DC(Point.x);
+			int	y	= (int)dc_Map.yWorld2DC(Point.y);
+
+			int	Color;
+
+			m_pClassify->Get_Class_Color_byValue(pPoints->Get_Value(m_Color_Field), Color);
+
+			dc_Map.IMG_Set_Pixel(x, y, Color);
+		}
+	}
+}
+
 
 ///////////////////////////////////////////////////////////
 //														 //
diff --git a/src/saga_core/saga_gui/wksp_pointcloud.h b/src/saga_core/saga_gui/wksp_pointcloud.h
index 304c214..9654b48 100644
--- a/src/saga_core/saga_gui/wksp_pointcloud.h
+++ b/src/saga_core/saga_gui/wksp_pointcloud.h
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: wksp_pointcloud.h 2548 2015-08-13 13:07:55Z oconrad $
+ * Version $Id: wksp_pointcloud.h 2716 2015-12-04 11:55:42Z oconrad $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -110,11 +110,25 @@ public:
 	virtual wxMenu *			Edit_Get_Menu			(void);
 	virtual TSG_Rect			Edit_Get_Extent			(void);
 	virtual bool				Edit_On_Mouse_Up		(CSG_Point Point, double ClientToWorld, int Key);
+	virtual bool				Edit_Set_Index			(int Index);
 	virtual bool				Edit_Set_Attributes		(void);
 
 
 protected:
 
+	virtual void				On_Create_Parameters	(void);
+	virtual void				On_DataObject_Changed	(void);
+	virtual void				On_Parameters_Changed	(void);
+	virtual int					On_Parameter_Changed	(CSG_Parameters *pParameters, CSG_Parameter *pParameter, int Flags);
+	virtual void				On_Update_Views			(void);
+
+	virtual bool				Fit_Colors				(void);
+
+	virtual void				On_Draw					(CWKSP_Map_DC &dc_Map, int Flags);
+
+
+private:
+
 	int							m_Color_Field, m_PointSize, m_Aggregation;
 
 	wxColour					m_Color_Pen;
@@ -124,19 +138,12 @@ protected:
 	class CWKSP_Table			*m_pTable;
 
 
-	virtual void				On_Create_Parameters	(void);
-	virtual void				On_DataObject_Changed	(void);
-	virtual void				On_Parameters_Changed	(void);
-	virtual int					On_Parameter_Changed	(CSG_Parameters *pParameters, CSG_Parameter *pParameter, int Flags);
-	virtual void				On_Update_Views			(void);
-
 	void						_LUT_Create				(void);
 
-	virtual void				On_Draw					(CWKSP_Map_DC &dc_Map, int Flags);
-
 	void						_Draw_Point				(CWKSP_Map_DC &dc_Map, int x, int y, double z, int Color);
 	void						_Draw_Point				(CWKSP_Map_DC &dc_Map, int x, int y, double z, int Color, int Radius);
 	void						_Draw_Points			(CWKSP_Map_DC &dc_Map);
+	void						_Draw_Thumbnail			(CWKSP_Map_DC &dc_Map);
 
 	CSG_Parameter *				_AttributeList_Add		(CSG_Parameter *pNode, const CSG_String &Identifier, const CSG_String &Name, const CSG_String &Description);
 	void						_AttributeList_Set		(CSG_Parameter *pFields, bool bAddNoField);
diff --git a/src/saga_core/saga_gui/wksp_shapes.cpp b/src/saga_core/saga_gui/wksp_shapes.cpp
index 9d973be..8f97ad1 100644
--- a/src/saga_core/saga_gui/wksp_shapes.cpp
+++ b/src/saga_core/saga_gui/wksp_shapes.cpp
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: wksp_shapes.cpp 2650 2015-10-15 17:01:38Z oconrad $
+ * Version $Id: wksp_shapes.cpp 2668 2015-10-30 11:03:12Z oconrad $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -190,7 +190,7 @@ wxMenu * CWKSP_Shapes::Get_Menu(void)
 
 	pMenu->AppendSeparator();
 
-	wxMenu	*pTable	= new wxMenu(_TL("Table"));
+	wxMenu	*pTable	= new wxMenu(_TL("Attributes"));
 	CMD_Menu_Add_Item(pTable,  true, ID_CMD_TABLES_SHOW);
 	CMD_Menu_Add_Item(pTable,  true, ID_CMD_TABLES_DIAGRAM);
 	CMD_Menu_Add_Item(pTable, false, ID_CMD_TABLES_SCATTERPLOT);
@@ -463,21 +463,6 @@ void CWKSP_Shapes::On_Create_Parameters(void)
 		PARAMETER_TYPE_Int, 10, 0, true
 	);
 
-#ifdef USE_HTMLINFO
-	//-----------------------------------------------------
-	// HTML Extra info
-
-	m_Parameters.Add_Node(
-		NULL							, "NODE_EXTRAINFO"			, _TL("Html Extra Info"),
-		_TL("")
-	);
-
-	AttributeList_Add(
-		m_Parameters("NODE_EXTRAINFO")	, "EXTRAINFO_ATTRIB"		, _TL("Attribute"),
-		_TL("")
-	);
-#endif
-
 	m_Parameters("LUT")->asTable()->Set_Field_Type(LUT_MIN, SG_DATATYPE_String);
 	m_Parameters("LUT")->asTable()->Set_Field_Type(LUT_MAX, SG_DATATYPE_String);
 }
@@ -494,18 +479,14 @@ void CWKSP_Shapes::On_DataObject_Changed(void)
 {
 	CWKSP_Layer::On_DataObject_Changed();
 
-	AttributeList_Set(m_Parameters("LUT_ATTRIB")			, false);
-	AttributeList_Set(m_Parameters("METRIC_ATTRIB")		, false);
-	AttributeList_Set(m_Parameters("LABEL_ATTRIB")			, true);
-	AttributeList_Set(m_Parameters("LABEL_ATTRIB_SIZE_BY")	, true);
+	AttributeList_Set(m_Parameters("LUT_ATTRIB"          ), false);
+	AttributeList_Set(m_Parameters("METRIC_ATTRIB"       ), false);
+	AttributeList_Set(m_Parameters("LABEL_ATTRIB"        ), true );
+	AttributeList_Set(m_Parameters("LABEL_ATTRIB_SIZE_BY"), true );
 
 	_Chart_Set_Options();
 
 	m_pTable->DataObject_Changed();
-
-#ifdef USE_HTMLINFO
-	AttributeList_Set(m_Parameters("EXTRAINFO_ATTRIB") , true);
-#endif
 }
 
 //---------------------------------------------------------
@@ -1145,14 +1126,7 @@ void CWKSP_Shapes::_Draw_Label(CWKSP_Map_DC &dc_Map, CSG_Shape *pShape, int Poin
 //---------------------------------------------------------
 CSG_Parameter * CWKSP_Shapes::AttributeList_Add(CSG_Parameter *pNode, const CSG_String &Identifier, const CSG_String &Name, const CSG_String &Description)
 {
-	CSG_Parameter *pParameter;
-
-	pParameter	= m_Parameters.Add_Choice(
-		pNode, Identifier, Name, Description,
-		CSG_String::Format(SG_T("%s|"), _TL("<default>")), 0
-	);
-
-	return( pParameter );
+	return( m_Parameters.Add_Choice(pNode, Identifier, Name, Description, CSG_String(_TL("<default>")) + "|") );
 }
 
 //---------------------------------------------------------
@@ -1160,21 +1134,24 @@ void CWKSP_Shapes::AttributeList_Set(CSG_Parameter *pFields, bool bAddNoField)
 {
 	if( pFields && pFields->Get_Type() == PARAMETER_TYPE_Choice )
 	{
-		wxString	s;
+		CSG_String	Items;
 
 		for(int i=0; i<Get_Shapes()->Get_Field_Count(); i++)
 		{
-			s.Append(wxString::Format(wxT("%s|"), Get_Shapes()->Get_Field_Name(i)));
+			Items	+= CSG_String(Get_Shapes()->Get_Field_Name(i)) + "|";
 		}
 
 		if( bAddNoField )
 		{
-			s.Append(wxString::Format(wxT("%s|"), _TL("<none>")));
+			Items	+= CSG_String(_TL("<none>")) + "|";
 		}
 
-		pFields->asChoice()->Set_Items(s);
+		int			iChoice	= pFields->asInt   ();
+		CSG_String	sChoice	= pFields->asString();
 
-		if( bAddNoField )
+		pFields->asChoice()->Set_Items(Items);
+
+		if( bAddNoField && (iChoice < 0 || iChoice >= pFields->asChoice()->Get_Count() || sChoice.Cmp(pFields->asChoice()->Get_Item(iChoice))) )
 		{
 			pFields->Set_Value(Get_Shapes()->Get_Field_Count());
 		}
@@ -1191,23 +1168,18 @@ void CWKSP_Shapes::AttributeList_Set(CSG_Parameter *pFields, bool bAddNoField)
 //---------------------------------------------------------
 CSG_Parameter * CWKSP_Shapes::BrushList_Add(CSG_Parameter *pNode, const CSG_String &Identifier, const CSG_String &Name, const CSG_String &Description)
 {
-	CSG_Parameter *pParameter;
-
-	pParameter	= m_Parameters.Add_Choice(
-		pNode, Identifier, Name, Description,
-		CSG_String::Format(SG_T("%s|%s|%s|%s|%s|%s|%s|%s|"),
-			_TL("Opaque"),
-			_TL("Transparent"),
+	return( m_Parameters.Add_Choice(pNode, Identifier, Name, Description,
+		CSG_String::Format("%s|%s|%s|%s|%s|%s|%s|%s|",
+			_TL("Opaque"           ),
+			_TL("Transparent"      ),
 			_TL("Backward Diagonal"),
-			_TL("Cross Diagonal"),
-			_TL("Forward Diagonal"),
-			_TL("Cross"),
-			_TL("Horizontal"),
-			_TL("Vertical")
-		), 0
+			_TL("Cross Diagonal"   ),
+			_TL("Forward Diagonal" ),
+			_TL("Cross"            ),
+			_TL("Horizontal"       ),
+			_TL("Vertical"         )
+		), 0)
 	);
-
-	return( pParameter );
 }
 
 //---------------------------------------------------------
@@ -1215,35 +1187,29 @@ int CWKSP_Shapes::BrushList_Get_Style(int Index)
 {
 	switch( Index )
 	{
-	default:
-	case 0:	return( wxSOLID				);
-	case 1:	return( wxTRANSPARENT		);
-	case 2:	return( wxBDIAGONAL_HATCH	);
-	case 3:	return( wxCROSSDIAG_HATCH	);
-	case 4:	return( wxFDIAGONAL_HATCH	);
-	case 5:	return( wxCROSS_HATCH		);
-	case 6:	return( wxHORIZONTAL_HATCH	);
-	case 7:	return( wxVERTICAL_HATCH	);
+	default:	return( wxSOLID				);
+	case  1:	return( wxTRANSPARENT		);
+	case  2:	return( wxBDIAGONAL_HATCH	);
+	case  3:	return( wxCROSSDIAG_HATCH	);
+	case  4:	return( wxFDIAGONAL_HATCH	);
+	case  5:	return( wxCROSS_HATCH		);
+	case  6:	return( wxHORIZONTAL_HATCH	);
+	case  7:	return( wxVERTICAL_HATCH	);
 	}
 }
 
 //---------------------------------------------------------
 CSG_Parameter * CWKSP_Shapes::PenList_Add(CSG_Parameter *pNode, const CSG_String &Identifier, const CSG_String &Name, const CSG_String &Description)
 {
-	CSG_Parameter *pParameter;
-
-	pParameter	= m_Parameters.Add_Choice(
-		pNode, Identifier, Name, Description,
-		CSG_String::Format(SG_T("%s|%s|%s|%s|%s|"),
-			_TL("Solid"),
-			_TL("Dotted"),
-			_TL("Long Dashed"),
+	return( m_Parameters.Add_Choice(pNode, Identifier, Name, Description,
+		CSG_String::Format("%s|%s|%s|%s|%s|",
+			_TL("Solid"       ),
+			_TL("Dotted"      ),
+			_TL("Long Dashed" ),
 			_TL("Short Dashed"),
 			_TL("Dot And Dash")
-		), 0
+		), 0)
 	);
-
-	return( pParameter );
 }
 
 //---------------------------------------------------------
@@ -1251,12 +1217,11 @@ int CWKSP_Shapes::PenList_Get_Style(int Index)
 {
 	switch( Index )
 	{
-	default:
-	case 0:	return( wxSOLID );
-	case 1:	return( wxDOT );
-	case 2:	return( wxLONG_DASH );
-	case 3:	return( wxSHORT_DASH );
-	case 4:	return( wxDOT_DASH );
+	default:	return( wxSOLID      );
+	case  1:	return( wxDOT        );
+	case  2:	return( wxLONG_DASH  );
+	case  3:	return( wxSHORT_DASH );
+	case  4:	return( wxDOT_DASH   );
 	}
 }
 
diff --git a/src/saga_core/saga_gui/wksp_shapes_point.cpp b/src/saga_core/saga_gui/wksp_shapes_point.cpp
index 2c21eea..a544932 100644
--- a/src/saga_core/saga_gui/wksp_shapes_point.cpp
+++ b/src/saga_core/saga_gui/wksp_shapes_point.cpp
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: wksp_shapes_point.cpp 2329 2014-11-05 19:32:43Z oconrad $
+ * Version $Id: wksp_shapes_point.cpp 2719 2015-12-07 16:27:37Z oconrad $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -422,8 +422,8 @@ bool CWKSP_Shapes_Point::Get_Style_Size(int &min_Size, int &max_Size, double &mi
 //---------------------------------------------------------
 inline void CWKSP_Shapes_Point::Draw_Initialize(CWKSP_Map_DC &dc_Map)
 {
-	dc_Map.dc.SetBrush	(m_Brush);
-	dc_Map.dc.SetPen	(m_Pen);
+	dc_Map.dc.SetBrush(m_Brush);
+	dc_Map.dc.SetPen  (m_Pen  );
 
 	m_Sel_Color_Fill	= Get_Color_asWX(m_Parameters("SEL_COLOR_FILL")->asInt());
 }
@@ -432,87 +432,87 @@ inline void CWKSP_Shapes_Point::Draw_Initialize(CWKSP_Map_DC &dc_Map)
 inline bool CWKSP_Shapes_Point::Draw_Initialize(CWKSP_Map_DC &dc_Map, int &Size, CSG_Shape *pShape, int Selection)
 {
 	//-----------------------------------------------------
+	if( m_Brush.IsTransparent() && !m_bOutline && !Selection )
+	{
+		return( false );	// nothing to draw !
+	}
+
+	//-----------------------------------------------------
 	double	dSize;
 
 	if( m_iSize < 0 )	// default size
 	{
 		dSize	= m_Size;
 	}
-	else				// size by attribute
+	else				// size by attribute value
 	{
-		if( m_Size_Scale == 0 )	// take value as is
-		{
-			dSize	= pShape->asDouble(m_iSize);
-		}
-		else					// scale to size range
+		dSize	= pShape->asDouble(m_iSize);
+
+		if( m_Size_Scale != 0 )	// scale to size range
 		{
-			dSize	= (pShape->asDouble(m_iSize) - m_Size_Min) * m_dSize + m_Size;
+			dSize	= (dSize - m_Size_Min) * m_dSize + m_Size;
 		}
 	}
 
 	switch( m_Size_Type )
 	{
-	default:
-	case 0:	dSize	*= dc_Map.m_Scale;		break;
-	case 1:	dSize	*= dc_Map.m_World2DC;	break;
+	default:	dSize	*= dc_Map.m_Scale;		break;
+	case  1:	dSize	*= dc_Map.m_World2DC;	break;
 	}
 
 	Size	= (int)(0.5 + dSize);
 
+	if( Size <= 0 )
+	{
+		return( false );
+	}
+
 	//-----------------------------------------------------
-	if( Size > 0 )
+	int	Color;
+
+	if( Selection )
 	{
-		if( Selection )
+		dc_Map.dc.SetBrush(wxBrush(m_Sel_Color_Fill, wxSOLID));
+		dc_Map.dc.SetPen  (wxPen(m_Sel_Color, Selection == 1 ? 2 : 0, wxSOLID));
+	}
+	else if( Get_Class_Color(pShape, Color) )
+	{
+		if( !m_Brush.IsTransparent() )
 		{
-			dc_Map.dc.SetBrush(wxBrush(m_Sel_Color_Fill	, wxSOLID));
-			dc_Map.dc.SetPen  (wxPen(m_Sel_Color, Selection == 1 ? 2 : 0, wxSOLID));
+			wxBrush	Brush(m_Brush);	Brush.SetColour(SG_GET_R(Color), SG_GET_G(Color), SG_GET_B(Color));
+
+			dc_Map.dc.SetBrush(Brush);
 		}
-		else
+
+		if( !m_bOutline )
 		{
-			int		Color;
+			wxPen	Pen  (m_Pen  );	Pen  .SetColour(SG_GET_R(Color), SG_GET_G(Color), SG_GET_B(Color));
 
-			if( Get_Class_Color(pShape, Color) )
-			{
-				wxBrush	Brush(m_Brush);
-				Brush.SetColour(SG_GET_R(Color), SG_GET_G(Color), SG_GET_B(Color));
-				dc_Map.dc.SetBrush(Brush);
-
-				if( !m_bOutline )
-				{
-					wxPen	Pen(m_Pen);
-					Pen.SetColour(SG_GET_R(Color), SG_GET_G(Color), SG_GET_B(Color));
-					dc_Map.dc.SetPen(Pen);
-				}
-			}
+			dc_Map.dc.SetPen(Pen);
 		}
-
-		return( true );
 	}
 
-	return( false );
+	return( true );
 }
 
 //---------------------------------------------------------
 void CWKSP_Shapes_Point::Draw_Shape(CWKSP_Map_DC &dc_Map, CSG_Shape *pShape, int Selection)
 {
-	if( m_iSize >= 0 && pShape->is_NoData(m_iSize) )
+	if( m_iSize < 0 || !pShape->is_NoData(m_iSize) )
 	{
-		return;
-	}
+		int		Size;
 
-	//-----------------------------------------------------
-	int		Size;
-
-	if( Draw_Initialize(dc_Map, Size, pShape, Selection) )
-	{
-		TSG_Point_Int	p(dc_Map.World2DC(pShape->Get_Point(0)));
+		if( Draw_Initialize(dc_Map, Size, pShape, Selection) )
+		{
+			TSG_Point_Int	p(dc_Map.World2DC(pShape->Get_Point(0)));
 
-		Draw_Symbol(dc_Map.dc, p.x, p.y, Size);
+			Draw_Symbol(dc_Map.dc, p.x, p.y, Size);
 
-		//-------------------------------------------------
-		if( Selection )
-		{
-			Draw_Initialize(dc_Map);
+			if( Selection )
+			{
+				dc_Map.dc.SetBrush(m_Brush);
+				dc_Map.dc.SetPen  (m_Pen  );
+			}
 		}
 	}
 }
diff --git a/src/saga_core/saga_gui/wksp_shapes_polygon.cpp b/src/saga_core/saga_gui/wksp_shapes_polygon.cpp
index fb9596b..275ced6 100644
--- a/src/saga_core/saga_gui/wksp_shapes_polygon.cpp
+++ b/src/saga_core/saga_gui/wksp_shapes_polygon.cpp
@@ -1,5 +1,5 @@
 /**********************************************************
- * Version $Id: wksp_shapes_polygon.cpp 2329 2014-11-05 19:32:43Z oconrad $
+ * Version $Id: wksp_shapes_polygon.cpp 2719 2015-12-07 16:27:37Z oconrad $
  *********************************************************/
 
 ///////////////////////////////////////////////////////////
@@ -211,20 +211,30 @@ void CWKSP_Shapes_Polygon::Draw_Shape(CWKSP_Map_DC &dc_Map, CSG_Shape *pShape, i
 	if( Selection )
 	{
 		dc_Map.dc.SetBrush(wxBrush(Selection == 1 ? m_Sel_Color_Fill[0] : m_Sel_Color_Fill[1], wxSOLID));
-		dc_Map.dc.SetPen(wxPen(m_Sel_Color, 0, wxSOLID));
+		dc_Map.dc.SetPen  (wxPen(m_Sel_Color, 0, wxSOLID));
 
 		dc_Map.Draw_Polygon((CSG_Shape_Polygon *)pShape);
 
 		dc_Map.dc.SetBrush(m_Brush);
-		dc_Map.dc.SetPen(m_Pen);
+		dc_Map.dc.SetPen  (m_Pen  );
+
+		return;
+	}
+
+	//-----------------------------------------------------
+	if( m_Brush.IsTransparent() && !m_bOutline )
+	{
+		return;	// nothing to draw !
 	}
-	else if( m_pClassify->Get_Mode() == CLASSIFY_UNIQUE )
+
+	//-----------------------------------------------------
+	if( m_pClassify->Get_Mode() == CLASSIFY_UNIQUE )
 	{
 		dc_Map.Draw_Polygon((CSG_Shape_Polygon *)pShape);
 	}
 	else if( m_iColor >= 0 && (m_pClassify->Get_Mode() != CLASSIFY_METRIC || !pShape->is_NoData(m_iColor)) )
 	{
-		int		Color;
+		int	Color;
 
 		if( Get_Class_Color(pShape, Color) )
 		{
@@ -241,6 +251,7 @@ void CWKSP_Shapes_Polygon::Draw_Shape(CWKSP_Map_DC &dc_Map, CSG_Shape *pShape, i
 		}
 	}
 
+	//-----------------------------------------------------
 	if( m_bCentroid )
 	{
 		TSG_Point	Point	= ((CSG_Shape_Polygon *)pShape)->Get_Centroid();
diff --git a/src/scripting/helper/make_arcsaga_toolboxes.bat b/src/scripting/helper/make_arcsaga_toolboxes.bat
new file mode 100644
index 0000000..d1eff60
--- /dev/null
+++ b/src/scripting/helper/make_arcsaga_toolboxes.bat
@@ -0,0 +1,43 @@
+ at ECHO OFF
+
+REM ___________________________________
+SET SAGA_ROOT=D:\saga\saga-code\trunk\saga-gis
+
+REM ___________________________________
+SET OUTDIR=ArcSAGA Toolboxes
+
+IF EXIST "%OUTDIR%" RMDIR "%OUTDIR%" /S/Q
+MKDIR "%OUTDIR%"
+
+COPY "%SAGA_ROOT%\src\dev_tools\ArcSAGA.py" "%OUTDIR%"
+COPY "%SAGA_ROOT%\src\dev_tools\ArcSAGA_Grid.lyr" "%OUTDIR%\grid.lyr"
+
+"%SAGA_ROOT%\bin\saga_vc_win32\saga_cmd.exe" dev_tools 5 -BOX_NAMING=1 -ARC_VERSION=1 -DIRECTORY="%OUTDIR%"
+
+RMDIR /S/Q "%SAGA_ROOT%\bin\saga_vc_win32\%OUTDIR%\"
+XCOPY /C/Q/Y "%OUTDIR%" "%SAGA_ROOT%\bin\saga_vc_win32\%OUTDIR%\"
+RMDIR /S/Q "%SAGA_ROOT%\bin\saga_vc_x64\%OUTDIR%\"
+XCOPY /C/Q/Y "%OUTDIR%" "%SAGA_ROOT%\bin\saga_vc_x64\%OUTDIR%\"
+
+RMDIR "%OUTDIR%" /S/Q
+
+REM ___________________________________
+SET OUTDIR=ArcSAGA Toolboxes 10.1
+
+IF EXIST "%OUTDIR%" RMDIR "%OUTDIR%" /S/Q
+MKDIR "%OUTDIR%"
+
+COPY "%SAGA_ROOT%\src\dev_tools\ArcSAGA.py" "%OUTDIR%"
+COPY "%SAGA_ROOT%\src\dev_tools\ArcSAGA_Grid.lyr" "%OUTDIR%\grid.lyr"
+
+"%SAGA_ROOT%\bin\saga_vc_win32\saga_cmd.exe" dev_tools 5 -BOX_NAMING=1 -ARC_VERSION=0 -DIRECTORY="%OUTDIR%"
+
+RMDIR /S/Q "%SAGA_ROOT%\bin\saga_vc_win32\%OUTDIR%\"
+XCOPY /C/Q/Y "%OUTDIR%" "%SAGA_ROOT%\bin\saga_vc_win32\%OUTDIR%\"
+RMDIR /S/Q "%SAGA_ROOT%\bin\saga_vc_x64\%OUTDIR%\"
+XCOPY /C/Q/Y "%OUTDIR%" "%SAGA_ROOT%\bin\saga_vc_x64\%OUTDIR%\"
+
+RMDIR "%OUTDIR%" /S/Q
+
+REM ___________________________________
+REM PAUSE
\ No newline at end of file
diff --git a/src/scripting/helper/make_saga_release.bat b/src/scripting/helper/make_saga_release.bat
new file mode 100644
index 0000000..41b49e5
--- /dev/null
+++ b/src/scripting/helper/make_saga_release.bat
@@ -0,0 +1,171 @@
+ at ECHO OFF
+
+REM ___________________________________
+SET SAGA_VER_MAJOR=2
+SET SAGA_VER_MINOR=2
+SET SAGA_VER_RELEASE=3
+
+SET SAGA_VERSION=saga_%SAGA_VER_MAJOR%.%SAGA_VER_MINOR%.%SAGA_VER_RELEASE%
+SET SVN__VERSION=%SAGA_VER_MAJOR%-%SAGA_VER_MINOR%-%SAGA_VER_RELEASE%
+
+SET SAGA_ROOT=D:\saga\saga-code\trunk
+
+SET ZIPEXE="C:\Program Files\7-Zip\7z.exe" a -r -y -mx5
+SET ISETUP="C:\Program Files (x86)\Inno Setup 5\ISCC.exe"
+SET SVNEXE=svn
+SET DOXEXE=doxygen.exe
+SET SWIGEXE="D:\libs\swigwin-3.0.7\swig.exe"
+SET PYTHONDIR=D:\libs\Python-2.7
+SET PYTHONVER=27
+
+
+REM ___________________________________
+REM ###################################
+REM PRE-RELEASE STEPS
+REM ###################################
+
+ECHO __________________________________
+ECHO ##################################
+ECHO #
+ECHO # MAKE SAGA RELEASE: %SVN__VERSION%
+ECHO #
+ECHO ##################################
+ECHO.
+ECHO Things you should have updated before:
+ECHO - ArcSAGA Tools
+ECHO - Translation Files
+ECHO - Python Tools Interface Update
+ECHO.
+ECHO Enter 'y' to continue!
+SET /P CONTINUE=
+IF NOT '%CONTINUE%' == 'y' EXIT
+
+REM ___________________________________
+REM Create a branch
+REM %SVNEXE% copy svn://svn.code.sf.net/p/saga-gis/code-0/trunk svn://svn.code.sf.net/p/saga-gis/code-0/branches/release-%SVN__VERSION% -m "branch release-%SVN__VERSION% created from trunk"
+
+
+REM ___________________________________
+REM ###################################
+REM MAKE RELEASE
+REM ###################################
+
+REM ___________________________________
+MKDIR "%SAGA_VERSION%"
+PUSHD "%SAGA_VERSION%"
+
+REM ___________________________________
+REM win32 Binaries
+SET SAGA_CONFIG=win32
+MKDIR "%SAGA_VERSION%_%SAGA_CONFIG%"
+PUSHD "%SAGA_VERSION%_%SAGA_CONFIG%"
+XCOPY /C/S/Q/Y "%SAGA_ROOT%\saga-gis\bin\saga_vc_%SAGA_CONFIG%"
+DEL /F saga_gui.cfg saga_gui.ini *.exp modules\*.exp modules\*.lib modules\dev_tools.*
+RMDIR /S/Q _private
+POPD
+%ZIPEXE% "%SAGA_VERSION%_%SAGA_CONFIG%.zip" "%SAGA_VERSION%_%SAGA_CONFIG%"
+
+COPY "%SAGA_ROOT%\saga_setup_readme.rtf" "%SAGA_VERSION%_%SAGA_CONFIG%"
+COPY "%SAGA_ROOT%\saga_setup_%SAGA_CONFIG%.iss" "%SAGA_VERSION%_%SAGA_CONFIG%"
+%ISETUP% "%SAGA_VERSION%_%SAGA_CONFIG%\saga_setup_%SAGA_CONFIG%.iss"
+MOVE "%SAGA_VERSION%_%SAGA_CONFIG%\%SAGA_VERSION%_%SAGA_CONFIG%_setup.exe"
+
+RMDIR /S/Q "%SAGA_VERSION%_%SAGA_CONFIG%"
+
+REM ___________________________________
+REM x64 Binaries
+SET SAGA_CONFIG=x64
+MKDIR "%SAGA_VERSION%_%SAGA_CONFIG%"
+PUSHD "%SAGA_VERSION%_%SAGA_CONFIG%"
+XCOPY /C/S/Q/Y "%SAGA_ROOT%\saga-gis\bin\saga_vc_%SAGA_CONFIG%"
+DEL /F saga_gui.cfg saga_gui.ini *.exp modules\*.exp modules\*.lib modules\dev_tools.*
+RMDIR /S/Q _private
+POPD
+%ZIPEXE% "%SAGA_VERSION%_%SAGA_CONFIG%.zip" "%SAGA_VERSION%_%SAGA_CONFIG%"
+
+COPY "%SAGA_ROOT%\saga_setup_readme.rtf" "%SAGA_VERSION%_%SAGA_CONFIG%"
+COPY "%SAGA_ROOT%\saga_setup_%SAGA_CONFIG%.iss" "%SAGA_VERSION%_%SAGA_CONFIG%"
+%ISETUP% "%SAGA_VERSION%_%SAGA_CONFIG%\saga_setup_%SAGA_CONFIG%.iss"
+MOVE "%SAGA_VERSION%_%SAGA_CONFIG%\%SAGA_VERSION%_%SAGA_CONFIG%_setup.exe"
+
+RMDIR /S/Q "%SAGA_VERSION%_%SAGA_CONFIG%"
+
+REM ___________________________________
+REM SVN Source Code Repository
+%SVNEXE% checkout svn://svn.code.sf.net/p/saga-gis/code-0/trunk %SAGA_VERSION%_src -q --non-interactive
+PUSHD %SAGA_VERSION%_src
+RMDIR /S/Q .svn
+POPD
+%ZIPEXE% %SAGA_VERSION%_src.zip %SAGA_VERSION%_src
+
+REM ___________________________________
+REM Doxygen API Documentation
+PUSHD %SAGA_VERSION%_src
+%DOXEXE% saga_api_Doxyfile
+POPD
+%ZIPEXE% "%SAGA_VERSION%_api_doc.zip" "%SAGA_VERSION%_api_doc"
+RMDIR /S/Q "%SAGA_VERSION%_api_doc"
+
+REM ___________________________________
+REM SWIG/Python (win32)
+SET WXWINLIB="%WXWIN%\lib\vc_dll"
+SET SAGA="%SAGA_ROOT%\saga-gis\bin\saga_vc_Win32"
+PUSHD "%SAGA_ROOT%\saga-gis\src\saga_core\saga_api"
+%SWIGEXE% -c++ -python -includeall -I. -D_SAGA_PYTHON -D_SAGA_UNICODE saga_api.h
+"%PYTHONDIR%\python.exe" saga_api_to_python_win.py install
+MOVE saga_api.py "%PYTHONDIR%\Lib\site-packages\saga_api.py"
+DEL /F saga_api_wrap.cxx
+RMDIR /S/Q build
+POPD
+SET PYTHONOUT=Python%PYTHONVER%
+XCOPY /C/Q/Y "%PYTHONDIR%\Lib\site-packages\*saga*.*" "%PYTHONOUT%\Lib\site-packages\"
+COPY "%SAGA_ROOT%\saga-gis\src\scripting\python\saga_python_api.txt" "%PYTHONOUT%\Lib\site-packages\"
+XCOPY /C/Q/Y "%SAGA_ROOT%\saga-gis\src\scripting\python\examples" "%PYTHONOUT%\Lib\site-packages\saga_api_examples\"
+%ZIPEXE% %SAGA_VERSION%_win32_python%PYTHONVER%.zip "%PYTHONOUT%"
+RMDIR /S/Q "%PYTHONOUT%"
+
+REM ___________________________________
+REM The End
+RMDIR /S/Q %SAGA_VERSION%_src
+POPD
+
+
+REM ___________________________________
+REM ###################################
+REM POST-RELEASE STEPS
+REM ###################################
+
+ECHO __________________________________
+ECHO ##################################
+ECHO #
+ECHO # What is left to do ?!
+ECHO #
+ECHO ##################################
+ECHO.
+ECHO - Don't forget to make the Linux tarball!
+ECHO.    make dist
+ECHO.
+ECHO - Upload all release files
+ECHO.    including an up-to-date 'readme.txt'
+ECHO.
+ECHO - Upload API Documentation to saga-gis.org
+ECHO.
+ECHO - Update version numbers in:
+ECHO.    ./saga_setup_win32.iss
+ECHO.    ./saga_setup_x64.iss
+ECHO.    ./saga_api_Doxyfile
+ECHO.    ./saga-gis/configure.ac
+ECHO.    ./saga-gis/README
+ECHO.    ./saga-gis/src/saga_core/saga_api/saga_api.h
+ECHO.    ./saga-gis/src/scripting/helper/make_saga_release.bat (this file!)
+ECHO.
+ECHO - Create SAGA Module Reference Documentation
+ECHO.    sagadoc-code: ./parse_modules.py
+ECHO.    upload created version folder to saga-gis.org and update link
+ECHO.
+ECHO - Add new bug tracker milestone for next version
+ECHO.    https://sourceforge.net/p/saga-gis/bugs/milestones
+ECHO.
+ECHO - Commit a comment like: SAGA version updated to %SVN__VERSION%
+
+PAUSE
diff --git a/src/scripting/helper/make_saga_snapshot.bat b/src/scripting/helper/make_saga_snapshot.bat
new file mode 100644
index 0000000..e96ef0c
--- /dev/null
+++ b/src/scripting/helper/make_saga_snapshot.bat
@@ -0,0 +1,42 @@
+ at ECHO OFF
+
+REM ___________________________________
+ECHO Enter version number:
+SET /P VERSION=
+ECHO.
+ECHO Enter date of snapshot:
+SET /P DATUM=
+
+SET SAGA_VERSION=saga_%VERSION%_%DATUM%
+SET SAGA_ROOT=D:\saga\saga-code\trunk
+
+SET ZIPEXE="C:\Program Files\7-Zip\7z.exe" a -r -y -mx5
+
+REM ___________________________________
+REM win32 Binaries
+SET SAGA_CONFIG=win32
+MKDIR "%SAGA_VERSION%_%SAGA_CONFIG%"
+PUSHD "%SAGA_VERSION%_%SAGA_CONFIG%"
+XCOPY /C/S/Q/Y "%SAGA_ROOT%\saga-gis\bin\saga_vc_%SAGA_CONFIG%"
+DEL /F saga_gui.cfg saga_gui.ini *.exp modules\*.exp modules\*.lib modules\dev_tools.*
+RMDIR /S/Q _private
+POPD
+
+%ZIPEXE% "%SAGA_VERSION%_%SAGA_CONFIG%.zip" "%SAGA_VERSION%_%SAGA_CONFIG%"
+RMDIR /S/Q "%SAGA_VERSION%_%SAGA_CONFIG%"
+
+REM ___________________________________
+REM x64 Binaries
+SET SAGA_CONFIG=x64
+MKDIR "%SAGA_VERSION%_%SAGA_CONFIG%"
+PUSHD "%SAGA_VERSION%_%SAGA_CONFIG%"
+XCOPY /C/S/Q/Y "%SAGA_ROOT%\saga-gis\bin\saga_vc_%SAGA_CONFIG%"
+DEL /F saga_gui.cfg saga_gui.ini *.exp modules\*.exp modules\*.lib modules\dev_tools.*
+RMDIR /S/Q _private
+POPD
+
+%ZIPEXE% "%SAGA_VERSION%_%SAGA_CONFIG%.zip" "%SAGA_VERSION%_%SAGA_CONFIG%"
+RMDIR /S/Q "%SAGA_VERSION%_%SAGA_CONFIG%"
+
+REM ___________________________________
+REM PAUSE
diff --git a/src/scripting/helper/make_tools_interface.bat b/src/scripting/helper/make_tools_interface.bat
new file mode 100644
index 0000000..699ccf7
--- /dev/null
+++ b/src/scripting/helper/make_tools_interface.bat
@@ -0,0 +1,12 @@
+ at ECHO OFF
+
+REM ___________________________________
+SET SAGA_ROOT=D:\saga\saga-code\trunk
+SET SAGA_CMD="%SAGA_ROOT%\saga-gis\bin\saga_vc_Win32\saga_cmd.exe"
+SET SAGA_TOOLS_PY=%SAGA_ROOT%\saga-gis\src\scripting\python\helpers\saga_cmd_param_interface\tools.py
+
+REM ___________________________________
+%SAGA_CMD% dev_tools 6 -INPUT="%SAGA_TOOLS_PY%" -OUTPUT="%SAGA_TOOLS_PY%"
+
+REM ___________________________________
+PAUSE
diff --git a/src/scripting/helper/make_translation_files.bat b/src/scripting/helper/make_translation_files.bat
new file mode 100644
index 0000000..409c02f
--- /dev/null
+++ b/src/scripting/helper/make_translation_files.bat
@@ -0,0 +1,29 @@
+ at ECHO OFF
+
+REM ___________________________________
+SET SVNEXE=svn
+
+SET SAGA_ROOT=D:\saga\saga-code\trunk\saga-gis
+SET SAGA_CMD="%SAGA_ROOT%\bin\saga_vc_win32\saga_cmd.exe" -f=s
+SET SAGA_SRC=saga_src
+
+SET RESPATH=%SAGA_ROOT%\src\saga_core\saga_gui\res
+
+REM ___________________________________
+REM SVN Source Code Repository
+%SVNEXE% checkout svn://svn.code.sf.net/p/saga-gis/code-0/trunk %SAGA_SRC% -q --non-interactive
+PUSHD %SAGA_SRC%
+RMDIR /S/Q .svn
+POPD
+
+REM ___________________________________
+%SAGA_CMD% dev_tools 0 -TARGET="%RESPATH%\saga.lng.txt" -DIRECTORY="%SAGA_SRC%"
+
+%SAGA_CMD% dev_tools 1 -MASTER="%RESPATH%\saga.lng.txt" -IMPORT="%RESPATH%\saga.ger.txt" -UNION="%RESPATH%\saga.ger.txt" -METHOD=1
+
+DEL "%RESPATH%\*.mtab"
+
+RMDIR /S/Q %SAGA_SRC%
+
+REM ___________________________________
+PAUSE
\ No newline at end of file
diff --git a/src/scripting/python/examples/02_grid_morphometry.py b/src/scripting/python/examples/02_grid_morphometry.py
index 7b6de48..e708103 100644
--- a/src/scripting/python/examples/02_grid_morphometry.py
+++ b/src/scripting/python/examples/02_grid_morphometry.py
@@ -79,12 +79,12 @@ if __name__ == '__main__':
         if os.path.split(fDEM)[0] == '':
             fDEM    = './' + fDEM
 
-    saga_api.SG_UI_Msg_Lock(1)
+    saga_api.SG_UI_Msg_Lock(True)
     if os.name == 'nt':    # Windows
         os.environ['PATH'] = os.environ['PATH'] + ';' + os.environ['SAGA_32'] + '/dll'
-        saga_api.SG_Get_Module_Library_Manager().Add_Directory(os.environ['SAGA_32' ] + '/modules', 0)
+        saga_api.SG_Get_Module_Library_Manager().Add_Directory(os.environ['SAGA_32' ] + '/modules', False)
     else:                  # Linux
-        saga_api.SG_Get_Module_Library_Manager().Add_Directory(os.environ['SAGA_MLB'], 0)
-    saga_api.SG_UI_Msg_Lock(0)
+        saga_api.SG_Get_Module_Library_Manager().Add_Directory(os.environ['SAGA_MLB'], False)
+    saga_api.SG_UI_Msg_Lock(False)
 
     morphometry(fDEM)
diff --git a/src/scripting/python/examples/04_grid_contour.py b/src/scripting/python/examples/04_grid_contour.py
index 2974de4..588b37e 100644
--- a/src/scripting/python/examples/04_grid_contour.py
+++ b/src/scripting/python/examples/04_grid_contour.py
@@ -9,8 +9,6 @@ def grid_contour(fGrid, fLines):
         print 'ERROR: loading grid [' + fGrid + ']'
         return 0
     
-    Lines   = saga_api.SG_Get_Data_Manager().Add_Shapes()
-
     # ------------------------------------
     if os.name == 'nt':    # Windows
         saga_api.SG_Get_Module_Library_Manager().Add_Library(os.environ['SAGA_32' ] + '/modules/shapes_grid.dll')
@@ -19,9 +17,7 @@ def grid_contour(fGrid, fLines):
 
     m      = saga_api.SG_Get_Module_Library_Manager().Get_Module(saga_api.CSG_String('shapes_grid'), 5) # 'Contour Lines from Grid'
     p      = m.Get_Parameters()
-    p.Get_Grid_System().Assign(Grid.Get_System()) # module needs to use conformant grid system!
     p(saga_api.CSG_String('GRID'   )).Set_Value(Grid)
-    p(saga_api.CSG_String('CONTOUR')).Set_Value(Lines)
     p(saga_api.CSG_String('ZSTEP'  )).Set_Value(25.0)
 
     if m.Execute() == 0:
@@ -29,6 +25,7 @@ def grid_contour(fGrid, fLines):
         return 0
 
     # ------------------------------------
+    Lines = p(saga_api.CSG_String('CONTOUR')).asShapes()
     Lines.Save(saga_api.CSG_String(fLines))
     
     print 'success'
@@ -44,7 +41,7 @@ if __name__ == '__main__':
         print 'Usage: grid_contour.py <in: grid> <out: contour>'
         print '... trying to run with test_data'
         fGrid   = './test.sgrd'
-        fLines  = './test_contours'
+        fLines  = './test_contours.shp'
     else:
         fGrid   = sys.argv[1]
         if os.path.split(fGrid)[0] == '':
diff --git a/src/scripting/python/helpers/saga_cmd_param_interface/tools.py b/src/scripting/python/helpers/saga_cmd_param_interface/tools.py
index 579c17a..9857e9a 100644
--- a/src/scripting/python/helpers/saga_cmd_param_interface/tools.py
+++ b/src/scripting/python/helpers/saga_cmd_param_interface/tools.py
@@ -247,13 +247,13 @@ tools = [
 ['imagery_vigra', 9, 'Random Forest Classification (ViGrA)'],
 ['imagery_vigra', 10, 'Random Forest Presence Prediction (ViGrA)'],
 ['io_esri_e00', 0, 'Import ESRI E00 File'],
-['io_gdal', 0, 'GDAL: Import Raster'],
-['io_gdal', 1, 'GDAL: Export Raster'],
-['io_gdal', 2, 'GDAL: Export Raster to GeoTIFF'],
-['io_gdal', 3, 'OGR: Import Vector Data'],
-['io_gdal', 4, 'OGR: Export Vector Data'],
-['io_gdal', 5, 'OGR: Export Shapes to KML'],
-['io_gdal', 6, 'GDAL: Import NetCDF'],
+['io_gdal', 0, 'Import Raster'],
+['io_gdal', 1, 'Export Raster'],
+['io_gdal', 2, 'Export GeoTIFF'],
+['io_gdal', 3, 'Import Shapes'],
+['io_gdal', 4, 'Export Shapes'],
+['io_gdal', 5, 'Export Shapes to KML'],
+['io_gdal', 6, 'Import NetCDF'],
 ['io_gps', 0, 'GPX to shapefile'],
 ['io_gps', 1, 'GPSBabel'],
 ['io_grid', 0, 'Export ESRI Arc/Info Grid'],
@@ -446,7 +446,7 @@ tools = [
 ['sim_ecosystems_hugget', 0, '01: A Simple Litter System'],
 ['sim_ecosystems_hugget', 1, '02: Carbon Cycle Simulation for Terrestrial Biomass'],
 ['sim_ecosystems_hugget', 2, '03: Spatially Distributed Simulation of Soil Nitrogen Dynamics'],
-['sim_erosion', 0, 'MMF-SAGA Soil Erosion Mode'],
+['sim_erosion', 0, 'MMF-SAGA Soil Erosion Model'],
 ['sim_fire_spreading', 0, 'Fire Risk Analysis'],
 ['sim_fire_spreading', 1, 'Simulation'],
 ['sim_hydrology', 0, 'Soil Moisture Content'],
@@ -555,7 +555,7 @@ tools = [
 ['ta_morphometry', 19, 'TPI Based Landform Classification'],
 ['ta_morphometry', 20, 'Terrain Surface Texture'],
 ['ta_morphometry', 21, 'Terrain Surface Convexity'],
-['ta_morphometry', 22, 'Terrain Surface Classification'],
+['ta_morphometry', 22, 'Terrain Surface Classification (Iwahashi and Pike)'],
 ['ta_morphometry', 23, 'Morphometric Features'],
 ['ta_morphometry', 24, 'Valley and Ridge Detection (Top Hat Approach)'],
 ['ta_morphometry', 25, 'Fuzzy Landform Element Classification'],
@@ -632,7 +632,14 @@ tools = [
 ['grid_filter', 17, 'Wombling for Multiple Features (Edge Detection)'],
 ['db_pgsql', 33, 'Import Single Raster Band from PostGIS'],
 ['ta_morphometry', 27, 'Wind Exposition Index'],
-['imagery_classification', 7, 'Confusion Matrix (Polygons / Grid)'],
+['imagery_classification', 6, 'Confusion Matrix (Polygons / Grid)'],
 ['db_pgsql', 35, 'Create Database'],
-['db_pgsql', 36, 'Drop Database']
+['db_pgsql', 36, 'Drop Database'],
+['io_gdal', 7, 'Create Raster Catalogue from Files'],
+['io_gdal', 8, 'Create Raster Catalogues from Directory'],
+['sim_qm_of_esp', 0, 'Diffusive Hillslope Evolution (FTCS)'],
+['sim_qm_of_esp', 1, 'Fill Sinks (QM of ESP)'],
+['sim_qm_of_esp', 2, 'Flow Accumulation (QM of ESP)'],
+['sim_qm_of_esp', 3, 'Successive Flow Routing'],
+['sim_qm_of_esp', 4, 'Diffusive Hillslope Evolution (ADI)']
 ]
diff --git a/src/scripting/python/saga_python_api.txt b/src/scripting/python/saga_python_api.txt
new file mode 100644
index 0000000..1ee1a2b
--- /dev/null
+++ b/src/scripting/python/saga_python_api.txt
@@ -0,0 +1,8 @@
+SAGA API - Python Interface
+* MS-Windows Installation *
+
+In order to use the Python interface for the SAGA API you have to extract the files of this archive to the 'site-packages' folder of your Python installation. You also have to make sure that the dynamic link library 'saga_api.dll' can be located by your Python interpreter, either by adding the directory of your SAGA installation to the PATH environment variable or by copying the library to a standard DLL search path (e.g. 'C:\Windows\system32').
+
+
+Important Note:
+For some reason the Python interpreter seems to work only with dynamic link libraries, if these have been compiled with the same compiler version that has been used for the Python interpreter compilation itself. The Python library interfacing the SAGA API, which you find in this archive, has been compiled using Python v2.7 for Win32, which should be compatible with ArcGIS 10. If you want to use a different Python version or a different compiler for the SAGA compilation, you have to ensur [...]
\ No newline at end of file

-- 
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/pkg-grass/saga.git



More information about the Pkg-grass-devel mailing list