#!/bin/sh
# This is a Tcl/Tk script to be interpreted by wish (Tk8.3 or better): \
exec wish8.4 "$0" -- "$@"

#
#  gpsman --- GPS Manager: a manager for GPS receiver data
#
# Copyright (c) 1998-2004 Miguel Filgueiras mig@ncc.up.pt Universidade do Porto
#
#    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.
#
## Incorporates contributions by
#  - Brian Baulch (baulchb@onthenet.com.au)
#      Copyright (c) 2002 by Brian Baulch
#      that allow for the support of Lowrance receivers
#  - Alessandro Palmas (alpalmas@tin.it)
#      Copyright (c) 2003 by Alessandro Palmas
#      that implement 2D and 3D elevation graphs for tracks and routes,
#      and support for exportation of waypoints and tracks to OziExplorer
#      files
#  - Matt Martin (matt.martin@ieee.org)
#      Copyright (c) 2003 by Matt Martin
#      implementing the support of Magellan receivers
#  - Stefan Heinen (stefan.heinen@djh-freeweb.de)
#      Copyright (c) 2002 by Stefan Heinen
#      allowing for better usage under non-Unix-like systems
#  - Valere Robin (valere.robin@wanadoo.fr)
#      Copyright (c) 2004 by Valere Robin
#      implementing importation of EasyGPS and GPX data files
#  - Martin Buck (m@rtin-buck.de)
#      Copyright (c) 2003 by Martin Buck
#      for resizing of 2D graphs, change in track edit window
#  - Jean H. Theoret (ve2za@rac.ca)
#      Copyright (c) 2004 by Jean H. Theoret
#      for changing the symbol of each waypoint in a group
#  - Paul Scorer (p.scorer@leedsmet.ac.uk)
#      Copyright (c) 2004 by Paul Scorer, Leeds Metropolitan University
#      implementing inportation of BGA turnpoint (DOS) files
##
#
## German language support:
#      before version 6.0: by Andreas Lange (Andreas.C.Lange@GMX.de)
#       Copyright (c) 2002 by Andreas Lange
#      since version 6.0: by Sabine Broda (sbb@ncc.up.pt) Copyright (c) 2004
#       by Sabine Broda
##
#
## Italian language support by Alessandro Palmas (alpalmas@tin.it)
#      Copyright (c) 2004 by Alessandro Palmas
##
#
## French language support by Valere Robin
#      (valere.robin@wanadoo.fr) Copyright (c) 2004 by Valere Robin
##
#
## Dutch language support by Rob Buitenhuis (rob@buitenhs.demon.nl)
#      Copyright (c) 2004 by Rob Buitenhuis
##
#
## Indonesian language support by Tri Agus Prayitno; (acuss@bk.or.id)
#      Copyright (c) 2004 by Tri Agus Prayitno
##
#
## Spanish language support by Alberto Morales; (amd77@gulic.org)
#      Copyright (c) 2004 by Alberto Morales
##
#
## Includes:
#      - a translation of a Perl script by Niki Hammler
#      (http://www.nobaq.net) that converts exported FUGAWI data to DDD
#      GPSman data
#
#      - an adaptation of the script "mg2gpsman.tcl" by Heiko Thede
#      (Heiko.Thede@gmx.de) that converts exported Map&Guide data to
#      GPSman data
##
#
## Some algorithms, formulae and geodetic information taken or adopted from
#  gpstrans - a program to communicate with garmin gps
#      containing parts taken from John F. Waers (jfwaers@csn.net)
#      program MacGPS.
#        Copyright (c) 1995 by Carsten Tschach (tschach@zedat.fu-berlin.de)
#      Uniform Finish grid support:
#        Copyright (c) 1996 Janne Sinkkonen (janne@iki.fi) 
#      Swedish grid support:
#        Copyright (c) 1999 by Anders Lennartsson
#        (anders.lennartsson@sto.foa.se)
#  INVERSE, FORWARD, INVERS3D, FORWRD3D - programs to compute distances and
#      azimuths between two points.
#      Available from ftp://www.ngs.noaa.gov/pub/pcsoft/for_inv.3d/
#  libproj and PROJ4.0 - cartographic projection software
#      by Gerald I. Evenden (gerald.evenden@verizon.net)
#      Available from http://members.bellatlantic.net/~vze2hc4d/proj4
#      (March 2004)
#  International Institute for Aerospace Survey and Earth Sciences (ITC),
#      Enschede, http://kartoweb.itc.nl/geometrics
#  Guidance Note Number 7, European Petroleum Survey Group
#      Revised November 1999
#  Kenneth Foote pages, Department of Geography, The University of
#      Colorado at Boulder
#      http://www.colorado.edu/geography/gcraft/notes/datum/edlist.html
#  geotrans - an open source coordinate transformation tool from the
#      USA National Imagery and Mapping Agency (NIMA)
#      http://www.remotesensing.org
#  Computation of area of spherical polygon adapted from sph_poly.c in
#      "Graphics Gems IV", edited by Paul Heckbert, Academic Press, 1994.
#  Formula for ellipsoid radius from
#      "Ellipsoidal Area Computations of Large Terrestrial Objects"
#      by Hrvoje Lukatela
#      http://www.geodyssey.com/papers/ggelare.html
#  "Formulas and constants for the calculation of the Swiss conformal
#      cylindrical projection and for the transformation between coordinate
#      systems", September 2001
#      http://www.swisstopo.ch/pub/data/geo/refsyse.pdf
#  "Het stelsel van de Rijksdriehoeksmeting en het European Terrestrial
#      Reference System 1989", September 2000 (containing formulas and
#      constants for the Schreiber projection and the RD grid, used in
#      The Netherlands; partial English translation kindly provided by
#      Rob Buitenhuis, rob@buitenhs.demon.nl)
#      http://www.rdnap.nl
#  "Le carte topografiche CTR ed il loro uso GPS"
#      (http://www.gpscomefare.com/guide/tutorialgps/mapdatum.htm)
#      May 2003 (information kindly sent by Alessandro Palmas)
#  IGN site (http://www.ign.fr)
#
# look for these notices in the corresponding files
##
#
## This program uses the following Tcl libraries if they are installed:
#    - Img, written by Jan Nijtmans
#      http://www.xs4all.nl/~nijtmans/img.html
#      and available as a Debian package under the name libtk-img
#    - gpsmanshp, written by Miguel Filgueiras
#      http://www.ncc.up.pt/gpsmanshp
#
##
#
## Some formulae and geodetic information kindly provided by
#      Luisa Bastos, Universidade do Porto
#      Gil Goncalves, Universidade de Coimbra
#      Jose Alberto Goncalves, Universidade do Porto
#      Sergio Cunha, Universidade do Porto
#      Peter H. Dana, University of Texas
##
#
## Correction of bugs in the conversion of UTM/UPS coordinates provided by
#      Peter H. Dana, University of Texas
##
#
#  File: gpsman.tcl
#  Last change:  12 July 2004
#

############ configuration parameters
#
# the first 4 variables below MUST be correctly set for GPSMan to work!
#  DEFSPORT (or SERIALPORT in non-Unix systems), SRCDIR, USERDIR, USEROPTIONS

 # NOTE for non-Unix users: use "/" (not "\") in pathnames

 # path to serial port; make sure all users have read/write permission

switch $tcl_platform(platform) {
    unix {
	set UNIX 1
	# on Unix systems the path may be passed as an argument
	if { [llength $argv] < 2 } {
	    set SERIALPORT [lindex $argv 0]
	    set CMDLINE 0
	} else {
	    set SERIALPORT ""
	    set CMDLINE 1
	}
	# otherwise the default is
	set DEFSPORT /dev/cuaa0
	# path to directory containing user data
	set USERDIR ~/.gpsman-dir
	# name of user preferences file
	set USEROPTIONS gpsman-options
	# default print command
	set PRINTCMD "/usr/bin/lpr"
    }
    default {
	set UNIX 0 ; set CMDLINE 0
	# on Apple Macintoshes the serial port cannot be used under Tcl/Tk
	# on MS-Windows it could be as follows
	set SERIALPORT com2:
	# path to directory containing user data
	set USERDIR gpmandir
	# name of user preferences file
	set USEROPTIONS gpmanopt
	# default print command
	set PRINTCMD ""
    }
}

 # path to directory containing program files
set SRCDIR /usr/local/share/gpsman/gmsrc

## the following values can be set from the options dialog of the interface

 # language: see lang*.tcl files, ALLMONTH array below, main.tcl KNOWNLANGS
    # currently available: engl for English, port for Portuguese, deutsch for
    #   German, it for Italian, fr for French, nl for Dutch, id for Indonesian,
    #   es for Spanish

set LANG engl

 # ISO latin1 character composition (accents, cedilla, ...)
set ISOLATIN1 1

 # Delete-key to delete last character
set DELETE 1

 # Configuration of main window in {map, lists} ("single" no longer supported)
set MWINDOWSCONF map

 # GPS receiver trade mark and model (if applicable): give trade mark
 #   (one of: Garmin, Lowrance, Magellan) followed by model name.
 #   See file recmodels.tcl for list of known models

set GPSREC "Garmin"

 # default baud rate for serial port
switch $GPSREC {
    Garmin {
	set SERIALBAUD 9600
    }
    Magellan {
	set SERIALBAUD 115200
    }
}

 # default receiver protocol (only used if $GPSREC=="Garmin"): see possible
 #  values in list RECPROTOCOLS defined for each trade mark in file
 #  recmodels.tcl
set DEFTRECPROTOCOL garmin

 # GPS receiver dependent values (set to Garmin GPS II)

       # accept all characters in names/comments; this may be risky!
set ACCEPTALLCHARS 0

set NAMELENGTH 6
set COMMENTLENGTH 16
set MAXWPOINTS 250
set MAXROUTES 20
set MAXWPINROUTE 30
set MAXTPOINTS 768
set CREATIONDATE 0
set NOLOWERCASE 1

    # sampling interval for Lowrance receivers in seconds
set INTERVAL 3

   # default symbol name (GPSMan convention; see symbols.tcl)
set DEFAULTSYMBOL WP_dot
    #  and symbol display options (GPSMan convention; see symbols.tcl)
set DEFAULTDISPOPT s_name

  # default line widths for routes, tracks and lines
set DEFTRTWIDTH 2
set DEFTTRWIDTH 2
set DEFTLNWIDTH 1

  # count to show number of track point on map; 0 means no numbers shown
set TRNUMBERINTVL 10

  # whether polylines on map react to mouse events (they should not if
  #  they are seen as part of the background)
set LNSREACT 0

 # data items with same name will be overwritten (ovwrt) or created under
 #  new name (rename):
set EQNAMEDATA ovwrt

 # keep hidden data (not available for editing) when changing item;
 #  one of: never, ask (at every change), always
set KEEPHIDDEN never

 # default values

         # possible distance units: KM NAUTMILE STATMILE
set DISTUNIT KM
         # altitude units: M FT
set ALTUNIT M

         # possible position formats: DMS (hdeg, min, sec), DMM (hdeg, min),
         #                            DDD (hdeg), UTM/UPS (ze, zn, e, n),
         #                            MH (Maidenhead locator, 6 characters)
         #                            BNG (British grid: zone, e, n),
         #                            CMP (Portuguese military grid: e, n),
         #                            GKK (German grid: zone, e, n),
         #                            ITM (Irish grid: zone, e, n)
         #                            SEG (Swedish grid: e, n)
         #  and maybe other grids (see projections.tcl)
set PositionFormat DMS
set Datum "WGS 84"
         # difference in hours to UTC (must be an integer)
set TimeOffset 1

         # possible date and time formats:
         #                        YYYYMMDD  (1998.03.20 09:35:23),
         #                        YYYY-MM-DD  (1998-03-20 09:35:23),
         #                        ISO8601   (2004-03-25T09:35:23Z),
         #                        MMDDYYYY  (03/20/1998 09:35:23),
         #                        DDMMMYYYY (20-Mar-1998 09:35:23),
         #                        YYYY/MM/DD (1998/03/20-09:35:23)
set DateFormat DDMMMYYYY

  # default map projection and cursor position format when starting
  #  (see projections.tcl)
set DEFMAPPROJ UTM
set DEFMAPPFRMT UTM/UPS

  # formulae: either more accurate or faster
set ACCFORMULAE 0

  # ask for confirmation of projection parameters
set ASKPROJPARAMS 1

  # use window to control slow operations
set USESLOWOPWINDOW 1

  # provide balloons with help
set BalloonHelp 1

  # default version for MapGuide (text) export files
set MapGuideVersion 2002

 # geometry

  # map dimensions in pixels
set MAPWIDTH 800 ; set MAPHEIGHT 550
         # length of scale arrow (pixels)
set MAPSCLENGTH 300
         # initial map scale: 1, 2, 4, 8, ... 512*$DISTUNIT/$MAPSCLENGTH pixel
         #  or, if $DISTUNIT==km: 50, 100, 200, 500 m/$MAPSCLENGTH pixel
         #      else: 150, 300, 600, 2400 ft/$MAPSCLENGTH pixel
         # actual distance and unit (from the values above) for the scale arrow
set MAPSCALE "4 km"
  # map font size in points or "Tcl/Tk" for the default of Tcl/Tk
set MAPFONTSIZE Tcl/Tk
  # travel/navigation font size in points or "Tcl/Tk" for the default of Tcl/Tk
set TRAVELFONTSIZE 12

  # menus
set MAXMENUITEMS 20

  # dimensions of lists
set LISTWIDTH 15
set LISTHEIGHT 22

  # initial positions
     # lists window
set LPOSX 40 ; set LPOSY 25
     # map window
set MPOSX 5 ; set MPOSY 0
     # receiver window
set RPOSX 10 ; set RPOSY 250
     # errors, messages, warnings
set EPOSX 340 ; set EPOSY 50
     # dialogs
set DPOSX 290 ; set DPOSY 50
     # offset for dialog for making route on map
set DPOSRTMAP -200

  # colours
       # general fore/background
set COLOUR(fg) "#090980"
set COLOUR(bg) "#f7f7e0"
       # error background
set COLOUR(messbg) "#ff8d90"
       # confirmation background
set COLOUR(confbg) "#F0E9C0"
       # selection background
set COLOUR(selbg) "#F0E9C0"
       # input dialog background
set COLOUR(dialbg) gray
       # receiver offline
set COLOUR(offline) "#d83232"
       # receiver online
set COLOUR(online) green
       # selected checkbutton
set COLOUR(check) red
       # balloon help
set COLOUR(ballbg) #fef6e1
set COLOUR(ballfg) #8d7f56

  # colours on map
       # selected map item
set MAPCOLOUR(mapsel) red
       # wayponts on map
set MAPCOLOUR(WP) "#ff6400"
       # routes on map
set MAPCOLOUR(RT) "#48C1BC"
       # route being defined on map
set MAPCOLOUR(mkRT) "#469e36"
       # tracks on map
set MAPCOLOUR(TR) "#EF9A00"
       # track points on map
set MAPCOLOUR(TP) "#CD69C9"
       # line colour on map
set MAPCOLOUR(LN) "#0000AA"
       # map legends
set MAPCOLOUR(mapleg) "#8B0000"
       # lines in map animation
set MAPCOLOUR(anim) darkblue
       # slots in map image grid
set MAPCOLOUR(emptygrid) white
set MAPCOLOUR(selemptygrid) "#ffe080"
set MAPCOLOUR(fullgrid) "#00d8d8"
set MAPCOLOUR(selfullgrid) "#ffd8d8"
       # travel/navigation
       # TRK arrow
set MAPCOLOUR(trvtrk) "#ffcc00"
       # vertical speed arrows
set MAPCOLOUR(trvvel_z) "#ffcc00"
       # TRN arrows
set MAPCOLOUR(trvtrn)  red
       # CTS arrow
set MAPCOLOUR(trvcts)  red
       # 2nd CTS arrow
set MAPCOLOUR(trvcts2) "#c5fbd5"
       # warnings
set MAPCOLOUR(trvwrnimportant) red
set MAPCOLOUR(trvwrnnormal) blue
set MAPCOLOUR(trvwrninfo) darkgreen

 # save state on exit, one of: never, ask (when quitting), always
set SAVESTATE ask
 # delete state files after restoring, one of: never, ask, always
set DELSTATE ask

 # permissions of created files
set PERMS 0640

 # default paper size (one of those whose dimensions are given below)

set PAPERSIZE a4

### the following values can be configured if needs be

  # paper size without margins

set PAGEWIDTH(a4) 184m ; set PAGEHEIGHT(a4) 271m
set PAGEWIDTH(a3) 258m ; set PAGEHEIGHT(a3) 379m
set PAGEWIDTH(a5) 134m ; set PAGEHEIGHT(a5) 195m
set PAGEWIDTH(b4) 250m ; set PAGEHEIGHT(b4) 353m
set PAGEWIDTH(b5) 176m ; set PAGEHEIGHT(b5) 250m
set PAGEWIDTH(letter) 211m ; set PAGEHEIGHT(letter) 279m

  # possible abbreviations for months in all known languages
  # English abbreviations must not be deleted
set ALLMONTH(1) "Jan Gen jan Ene"
set ALLMONTH(2) "Feb Fev feb"
set ALLMONTH(3) "Mar Mär mrt"
set ALLMONTH(4) "Apr Abr Avr apr"
set ALLMONTH(5) "May Mai Mag mei Mei"
set ALLMONTH(6) "Jun Giu jun"
set ALLMONTH(7) "Jul Lug jul"
set ALLMONTH(8) "Aug Ago Aou aug Agt"
set ALLMONTH(9) "Sep Set sep"
set ALLMONTH(10) "Oct Okt Out Ott okt"
set ALLMONTH(11) "Nov nov Nop"
set ALLMONTH(12) "Dec Dez Dic dec Des"

###### NO CONFIGURABLE VALUES AFTER THIS LINE ##############################

##### properties of known file formats
#   indices as NAME,PROPERTY  where PROPERTY is
#
#    mode         I/O mode in {in, out, {in out}}
#    depends      optional dependencies as evaluable code (globals must be
#                  declared), returning 0 on failure
#    filetype     in {unique, single, data} meaning: only one possible type,
#                 several types but each file has only one, other situations
#    types        admissible types as a subset of $TYPES-{GR}; the order must
#                 be that imposed by the format on the data in the file, if
#                 there is such an order
#    GREls        defined if there is support for dealing with GR elements
#    MODE,params  list of parameter names
#    MODE,pdefts  list of default values (or "ERROR" if value must be supplied)
#                  aligned with	list of parameter names; missing default
#                  values treated as ""; to get the value of a global
#                  variable use global:VARNAME
#    param,PNAME  list with global variable to set, conversion code from
#                  (external) $val to (internal) $val, constraint on possible
#                  values using $val as local variable and global variables
#                  of previous parameters (in the order given in the list of
#                  names), and, except for Shapefile, widget description as
#                  used by proc GMSetupParams (gendials.tcl); parameters are
#                  first converted in the order of occurrence in the list;
#                  each constraint and global variable are then checked/set
#                  in the same order

# includes VR contribution

array set FILEFORMAT {
    GPSMan,mode           {in out}
    GPSMan,filetype       data
    GPSMan,types          {WP RT TR LN}
    GPStrans,mode         {in out}
    GPStrans,filetype     single
    GPStrans,types        {WP RT TR}
    GPStrans,GREls        1
    Shapefile,mode     {in out}
    Shapefile,depends  { global GSHPVersion ; string compare $GSHPVersion "" }
    Shapefile,filetype single
    Shapefile,types    {WP RT TR LN}
    Shapefile,GREls    1
    Shapefile,in,params   {dim pformat zone datum dunit aunit}
    Shapefile,in,pdefts   {3 DDD "" {WGS 84} m m}
    Shapefile,out,params  {dim pformat datum dunit aunit}
    Shapefile,out,pdefts  {3 DDD {WGS 84} m m}
    Shapefile,param,dim   {SHPDim Ignore { expr $val == 3 || $val == 2 }}
    Shapefile,param,pformat {SHPPFormt
	{ global INVTXT ; set val $INVTXT($val) }
	{ global NNUMPFORMATS
          expr [lsearch -exact $NNUMPFORMATS $val] == -1
	}
    }
    Shapefile,param,zone   {SHPZone Ignore
	{ global SHPPFormt ZGRID
	  expr ! $ZGRID($SHPPFormt) || \
	      [CheckZone GMMessage $val $SHPPFormt]
	}
    }
    Shapefile,param,datum  {SHPDatum Ignore { expr [DatumRefId $val]+1 }}
    Shapefile,param,dunit  {SHPDUnit
	{ global INVTXT
	    if { [regexp {[a-z]} $val] } { set val $INVTXT($val) }
	}
	{ expr {$SHPPFormt == "DDD"} || [lsearch -exact {M FT} $val]+1 }
    }
    Shapefile,param,aunit  {SHPAUnit
	{ global INVTXT
	    if { [regexp {[a-z]} $val] } { set val $INVTXT($val) }
	}
	{ expr $SHPDim == 2 || [lsearch -exact {M FT} $val]+1 }
    }

    BGA,mode              in
    BGA,filetype          unique
    BGA,types             WP
    BGA,in,params         {feature findability air_activity}
    BGA,in,pdefts         {}
    BGA,param,feature     {BGAfeature Ignore { expr 1 } =$TXT(BGAfeature)}
    BGA,param,findability {BGAfindblty Ignore
	{ expr [regexp -nocase {^[A-DG]?$} $val] }
	=$TXT(BGAfindblty)
    }
    BGA,param,air_activity {BGAairact Ignore
	{ expr [string length $val] < 3 }
	=$TXT(BGAairact)
    }
    EasyGPS,mode          in
    EasyGPS,filetype      unique
    EasyGPS,types         WP
    EasyGPS,GREls         1
    Fugawi,mode           in
    Fugawi,filetype       unique
    Fugawi,types          WP
    Fugawi,GREls          1
    GD2,mode              in
    GD2,filetype          single
    GD2,types             {WP RT TR}
    GD2,GREls             1
    GPX,mode              {in out}
    GPX,filetype          data
    GPX,types             {WP RT TR}
    GPX,GREls             1
    GTrackMaker,mode      in
    GTrackMaker,filetype  data
    GTrackMaker,types     {WP RT TR}
    IGC,mode              in
    IGC,filetype          unique
    IGC,types             TR
    IGC,in,params         {alt}
    IGC,in,pdefts         {gps}
    IGC,param,alt         {GFOption Ignore
	{ expr [lsearch -exact "gps baro" $val]+1 }
	{/$TXT(alt)|gps baro}
    }
    MapGuide,mode         in
    MapGuide,filetype     unique
    MapGuide,types        RT
    MapGuide,in,params    {version idno commt rem}
    MapGuide,in,pdefts    {global:MapGuideVersion "" "" ""}
    MapGuide,param,version {GFVersion Ignore
	{ expr [lsearch -exact "2002 03/04" $val]+1 }
	{/$TXT(version)|2002 03/04}
    }
    MapGuide,param,idno   {GFItemId Ignore { expr 1 } =$TXT(numberid)}
    MapGuide,param,commt  {GFItemCommt Ignore
	{ CheckComment GMMessage $val }
	=$TXT(cmmt)
    }
    MapGuide,param,rem    {GFItemNB Ignore { expr 1 } =$TXT(rmrk)}
    MapSend,mode          {in out}
    MapSend,filetype      single
    MapSend,types         {WP RT TR}
    Meridian,mode         {in out}
    Meridian,depends      { global GPSREC
                            expr ! [string compare $GPSREC "Magellan"] }
    Meridian,filetype     single
    Meridian,types        {WP RT TR}
    NMEA,mode             in
    NMEA,depends          { global GPSREC
                            expr ! [string compare $GPSREC "Garmin"] }
    NMEA,filetype         unique
    NMEA,types            TR
    Ozi,mode              out
    Ozi,filetype          single
    Ozi,types             {WP TR}
    Ozi,GREls             1
}

### receiver protocols with external and internal representations

array set RECPROTS {
    Garmin        garmin
    Garmin,Garmin garmin
    Garmin,NMEA   nmea
    Garmin,SText  stext
    Garmin,simul  simul
}

### known map transformations

   # number of points needed to define each transformation
array set MAPTRANSFNPTS {
    Affine     3
    AffineConf 2
    NoRot      3
}

set MAPKNOWNTRANSFS {Affine AffineConf NoRot}


##### user options and source files

set InitDir 0 ; set InitOpts 0

if { ! [file exists $USERDIR] } {
    set InitDir 1
    if { [file readable ~/.gpsman] } {
	# pre-5.4 default options file
	source ~/.gpsman
    }
}

if { [file readable $USEROPTIONS] } {
    source $USEROPTIONS
    set USEROPTIONS [file join [pwd] $USEROPTIONS]
} else {
    set USEROPTIONS [file join $USERDIR $USEROPTIONS]
    if { [file readable $USEROPTIONS] } {
	source $USEROPTIONS
    } else {
	set InitOpts 1
	set ISOLATIN1 0
    }
}

# source files read before initialization of preferences file
set SRCFILESBEGIN "lang$LANG symbols gendials util check \
           datumell geod compute posncomp projections recmodels rgb options"

# this file may cause problems in non-western Linux installations
if { $ISOLATIN1 } { lappend SRCFILESBEGIN isolatin1 }

# source files setting receiver parameters
set SRCFILESREC "recdefs"

# source files depending on receiver brand
set SRCFILESFOR(Garmin) "serial garmin_protocols garmin_symbols \
	garmin_nmea garmin"
set SRCFILESFOR(Lowrance) "lowrance_symbols lowrance_nmea lowrance \
	lowrance_patches"
# MGM contribution
set SRCFILESFOR(Magellan) "serial magellan"

# other generic source files
set SRCFILESEND "wrtdials search lists files files_foreign gpsinfo \
	maptransf map mapanim realtime know trtort gdata cluster \
	elevation navigate"
# conditional source files
set SRCFILESCOND [list "ACCFORMULAE acccomp" "CMDLINE command"]

if { $tcl_version == 8.4 } {
    # Tk8.4 is incompatible with Img < 1.3
    set NoImgLib [catch {package require Img 1.3}]
} else { set NoImgLib  [catch {package require Img}] }

if { [catch {set GSHPVersion [package require gpsmanshp]}] } {
    set GSHPVersion ""
}

#####

if { $CMDLINE } {
    source [file join $SRCDIR command_parse.tcl]
    if { [BadCommandLine] } { exit 1 }
    if { $COMMAND(prefsfile) != "" } { source $COMMAND(prefsfile) }
}

source [file join $SRCDIR main.tcl]

##### execution

GMStart

if { $CMDLINE } {
    if { $COMMAND(name) != "starttravel" } { ShowGPSMan }
    set  CmdClock [clock seconds]
    if { [set r [ExecCommand]] != "wait" } {
	if { ! [string compare $r "0"] && \
		 [set d [expr 100*(6-[clock seconds]+$CmdClock)]] > 0 } {
	    after $d
	}
	exit $r
    }
} else {
    # normal use: initialize and launch graphical interface
    GMInit
}


