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

# This is the main file of:
#
#  gpsman --- GPS Manager: a manager for GPS receiver data
#
# Copyright (c) 1998-2013 Miguel Filgueiras migfilg@t-online.de
#
#    This program is free software; you can redistribute it and/or modify
#      it under the terms of the GNU General Public License as published by
#      the Free Software Foundation; either version 3 of the License, or
#      (at your option) any later version.
#
#      This program is distributed in the hope that it will be useful,
#      but WITHOUT ANY WARRANTY; without even the implied warranty of
#      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#      GNU General Public License for more details.
#
#      You should have received a copy of the GNU General Public License
#      along with this program.
#
## Incorporates contributions by
#  - Brian Baulch (baulchb_AT_onthenet.com.au)
#      Copyright (c) 2002 by Brian Baulch
#      that allow for the support of Lowrance receivers
#  - Alessandro Palmas (alpalmas_AT_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_AT_ieee.org)
#      Copyright (c) 2003 by Matt Martin
#      implementing the support of Magellan receivers
#  - Stefan Heinen (stefan.heinen_AT_djh-freeweb.de)
#      Copyright (c) 2002 by Stefan Heinen
#      allowing for better usage under non-Unix-like systems
#  - Valere Robin (valere.robin_AT_wanadoo.fr)
#      Copyright (c) 2004-2008 by Valere Robin
#      implementing support for EasyGPS, GPX and KML data files
#  - Martin Buck (m_AT_rtin-buck.de)
#      Copyright (c) 2003 by Martin Buck
#      for resizing of 2D graphs, change in track edit window
#  - Jean H. Theoret (ve2za_AT_rac.ca)
#      Copyright (c) 2004 by Jean H. Theoret
#      for changing the symbol of each waypoint in a group
#  - Paul Scorer (p.scorer_AT_leedsmet.ac.uk)
#      Copyright (c) 2004 by Paul Scorer, Leeds Metropolitan University
#      implementing inportation of BGA turnpoint (DOS) files
#  - David Gardner (djgardner_AT_users.sourceforge.net)
#      Copyright (c) 2004 by David Gardner
#      for creating a group from (un)displayed items, and for re-numbering
#      routes when sending to the receiver
#  - Benoit Steiner (benetsteph_AT_free.fr)
#      Copyright (c) 2008 by Benoit Steiner
#      computation of cummulative height of climbing for tracks, and
#      displaying point information on 2D elevation plots
#  - Sandor Laky (laky.sandor_AT_freemail.hu)
#      Copyright (c) 2008 by Sandor Laky
#      implementation of the EOV projection
#  - Rudolf Martin (rudolf.martin_AT_gmx.de)
#      Copyright (c) 2010 by Rudolf Martin
#      plug-ins for creating plots of tracks using gnuplot and for
#      other computations related with tracks
#
##
#
## German language support:
#      before version 6.0: by Andreas Lange (Andreas.C.Lange_AT_GMX.de)
#       Copyright (c) 2002 by Andreas Lange
#      since version 6.0: by Sabine Broda (sbb_AT_dcc.fc.up.pt)
#       Copyright (c) 2009 by Sabine Broda
##
#
## Italian language support by Alessandro Palmas (alpalmas_AT_tin.it)
#      Copyright (c) 2011 by Alessandro Palmas
##
#
## French language support by Valere Robin (valere.robin_AT_wanadoo.fr)
#       Copyright (c) 2011 by Valere Robin
##
#
## Dutch language support by Rob Buitenhuis (geo_AT_btnhs.nl)
#      Copyright (c) 2011 by Rob Buitenhuis
##
#
## Indonesian language support by Tri Agus Prayitno; (acuss_AT_bk.or.id)
#      Copyright (c) 2008 by Tri Agus Prayitno
##
#
## Spanish language support by Alberto Morales; (amd77_AT_gulic.org)
#      Copyright (c) 2011 by Alberto Morales
##
#
## Russian language support:
#      until version 6.4:  by Nikolai Kosyakoff (priroda.net_AT_gmail.com)
#       Copyright (c) 2007 by Nikolai Kosyakoff
#      since October 2009: by Alexander B. Preobrazhenskiy, (modul_AT_ihome.ru)
#       Copyright (c) 2011 by Alexander B. Preobrazhenskiy
##
#
## 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_AT_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_AT_csn.net)
#      program MacGPS.
#        Copyright (c) 1995 by Carsten Tschach (tschach_AT_zedat.fu-berlin.de)
#      Uniform Finish grid support:
#        Copyright (c) 1996 Janne Sinkkonen (janne_AT_iki.fi) 
#      Swedish grid support:
#        Copyright (c) 1999 by Anders Lennartsson
#        (anders.lennartsson_AT_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_AT_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_AT_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)
#  Parameters for the Hungarian Datum 72
#      http://ftp/gps/honlap-jan2002.pdf, September 2008
#
# look for these notices in the corresponding files
##
#
## This program uses the following Tcl libraries if they are installed:
#    - Img, written by Jan Nijtmans
#      now part of the standard Tcl distribution
#    - gpsmanshp, written by Miguel Filgueiras
#      http://sourceforge.net/projects/gpsmanshp
#      and available as a Debian package under the name gpsmanshp
#    - TclCurl, available as a Debian package under the name tclcurl
#
##
#
## 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:  6 October 2013
#

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

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

 # path to I/O port; make sure all users have read/write permission
 #  (the globals SERIALPORT and DEFSPORT have outdated names)

# when called as a command, if there are 2 or more arguments the
#  command-line mode is entered instead of the graphical mode; a single
#  argument is taken as the serial/USB port and the prefix "usb=" means
#  that the Garmin USB protocol is to be used

if { [llength $argv] < 2 } {
    set SERIALPORT [lindex $argv 0]
    set CMDLINE 0
} else {
    set SERIALPORT ""
    set CMDLINE 1
}

switch $tcl_platform(platform) {
    unix {
	set UNIX 1
	# default serial/USB port is
	set DEFSPORT /dev/ttyS0	
	# path to directory containing user data
	set USERDIR $env(HOME)/.gpsman-dir
	# name of user preferences file
	set USEROPTIONS gpsman-options
	# path to directory for temporary files (cleaned when GPSMan starts)
	set USERTMPDIR $USERDIR/.tmp
	# default HTTP address of the HTML version of the user manual
	#  set to "" if unavailable
	set DEFTMANHTTPADDR "file:///usr/share/doc/gpsman/html"
    }
    default {
	set UNIX 0 ; set CMDLINE 0
	# on MS-Windows the serial port could be as follows
	set SERIALPORT com1:
	# path to directory containing user data
	#  on MS-Windows it can be set as follows (see the manual)
	#    set USERDIR $::env(APPDATA)\\gpmandir
	set USERDIR gpmandir
	# name of user preferences file
	set USEROPTIONS gpmanopt
	# path to directory for temporary files (cleaned when GPSMan starts)
	set USERTMPDIR [file join $USERDIR .tmp]
	# default HTTP address of the HTML version of the user manual
	#  set to "" if unavailable
	set DEFTMANHTTPADDR ""
    }
}

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

# all other default configuration is now done in file $SRCDIR/config.tcl

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

# abstract data used in the program is now in file $SRCDIR/metadata.tcl

foreach f {config metadata} {
    source [file join $SRCDIR $f.tcl]
}

# prepare to deal with files not in ascii

set SYSENC [encoding system]

proc SourceEnc {path} {
    # source $path that may be not in ascii
    global SYSENC ENCODED

    set fn [file tail $path]
    if { [catch {set enc $ENCODED($fn)}] || $enc == $SYSENC } {
	uplevel source $path
    } else {
	encoding system $enc
	uplevel source $path
	encoding system $SYSENC
    }
    return
}

##### user options: files assumed to be in system encoding

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
    }
} elseif { ! [file writable $USERDIR] } {
    set UDUnwritable 1
} else { set UDUnwritable 0 }

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
	if { $SYSENC != "iso8859-1" && \
		 $SYSENC != "iso8859-9" } {
	    set ISOLATIN1 0
	}
    }
}

##### source files

# source files read before initialization of preferences file
set SRCFILESBEGIN {i18n-utf8 lang$LANG symbols gendials util check
    datumell geod plugins compute posncomp projections projs_main
    recmodels recdefs rgb options}

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

# 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 {setup wrtdials search lists files files_foreign
        gpsinfo	maptransf map mapanim realtime know trtort gdata
	cluster elevation navigate}
# conditional source files
set SRCFILESCOND {{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 } {
    SourceEnc [file join $SRCDIR command_parse.tcl]
    if { [BadCommandLine] } { exit 1 }
    if { $COMMAND(prefsfile) != "" } { source $COMMAND(prefsfile) }
}

SourceEnc [file join $SRCDIR main.tcl]

##### execution

GMStart

if { $CMDLINE } {
    if { $COMMAND(command) } { 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
}


