#
# This file is part of:
#
#  gpsman --- GPS Manager: a manager for GPS receiver data
#
# Copyright (c) 1998-2011 Miguel Filgueiras migf@portugalmail.pt
#
#    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.
#
#  File: main.tcl
#  Last change:  21 September 2011
#

# code here or called from here is not affected by patch files

set VERSIONDATE(day) 21
set VERSIONDATE(month) 9
set VERSIONDATE(year) 2011

set VERSION 6.4.2

      # these tests here prevent errors in the lang*.tcl files
if { [lsearch -exact {KM NAUTMILE STATMILE} $DISTUNIT] == -1 } {
    puts stderr \
	"Bad value in variable DISTUNIT: $DISTUNIT (see file config.tcl)"
    exit 1
}

if { [lsearch -exact {M FT} $ALTUNIT] == -1 } {
    puts stderr "Bad value in variable ALTUNIT: $ALTUNIT (see file gpsman.tcl)"
    exit 1
}

      # conversion factors to km
array set DSCALEFOR {
    KM             1
    sub,KM         0.001
    NAUTMILE       0.5399568
    sub,NAUTMILE   0.00016457916
    STATMILE       0.6213882
    sub,STATMILE   0.00018939432
}

      # conversion factors from km2 to km2, and from nml2 to nml2 or stml2
array set ASCALEFOR {
    KM             1
    NAUTMILE       1
    STATMILE       2.5899881
}

      # conversion factors to metre
array set ALSCALEFOR {
    M   1
    FT  0.3048
}

      # MAPDISTS must have a single value of 1 (for the main distance unit)
      #  all values before taken to be in sub-unit
set MAPDISTSFOR(KM) [list "50 m" "100 m" "200 m" "500 m" "1 km" "2 km" \
	"4 km" "8 km" "16 km" "32 km" "64 km" "128 km" "512 km"]
set MAPDISTSFOR(NAUTMILE) [list "150 ft" "300 ft" "600 ft" "1200 ft" \
	"2400 ft" "1 n ml" "2 n ml" "4 n ml" "8 n ml" "16 n ml" "32 n ml" \
	"64 n ml" "128 n ml" "512 n ml"]
set MAPDISTSFOR(STATMILE) [list "150 ft" "300 ft" "600 ft" "1200 ft" \
	"2400 ft" "1 st ml" "2 st ml" "4 st ml" "8 st ml" "16 st ml" \
	"32 st ml" "64 st ml" "128 st ml" "512 st ml"]

      # default denotations for units; can be overriden by lang*.tcl
set MAPDISTUNITS(KM) [list km m]
set MAPDISTUNITS(NAUTMILE) [list "n ml" ft]
set MAPDISTUNITS(STATMILE) [list "st ml" ft]

set DSCALE $DSCALEFOR($DISTUNIT)
set SUBDSCALE $DSCALEFOR(sub,$DISTUNIT)
set ASCALE $ASCALEFOR($DISTUNIT)
set ALSCALE $ALSCALEFOR($ALTUNIT)

set MAPDISTS $MAPDISTSFOR($DISTUNIT)
set MAPFTSIZES "Tcl/Tk 9 10 11 12 14 18 24 36"

# needed for error dialogs

set WindowStack ""

# knonw languages

set KNOWNLANGS {deutsch engl es fr id it nl port ru}

# known date formats are the indices of this array (for their widths in chars)
array set DATEW {
    YYYYMMDD   19
    ISO8601    22
    YYYY-MM-DD 21
    MMDDYYYY   19
    DDMMMYYYY  20
    YYYY/MM/DD 19
}

# other source files

  # source the English messages; other language files can omit translations
SourceEnc [file join $SRCDIR langengl.tcl]

foreach f $SRCFILESBEGIN {
       SourceEnc [file join $SRCDIR $f.tcl]
}

# other tests

if { int($TimeOffset) != $TimeOffset && int(2*$TimeOffset) != 2*$TimeOffset } {
    GMMessage $MESS(timeoffnotint) wait
    exit 1
}

# fonts are needed in proc AboutInfo

 # save Tk default as it may be needed later
set TkDefaultFont [font actual default]

if { $DEFAULTFONT != "default" } {
    set DefaultFont $DEFAULTFONT
    option add *Font $DEFAULTFONT
} else { set DefaultFont $TkDefaultFont }

if { $FIXEDFONT != "default" } {
    set FixedFont $FIXEDFONT
} else { set FixedFont fixed }	    

##

proc AboutInfo {w} {
    # create widgets for displaying information about GPSMan in window $w
    # all widgets will be inside frame $w.fr and are packed
    global Logo VERSION VERSIONDATE DateFormat COLOUR EPOSX EPOSY TXT \
	FixedFont

    frame $w.fr -relief flat -borderwidth 5 -bg $COLOUR(messbg)
    if { $Logo != "" } {
	label $w.fr.im -image $Logo -relief groove
	pack $w.fr.im
    }
    set d [FormatDay $DateFormat $VERSIONDATE(year) $VERSIONDATE(month) \
	             $VERSIONDATE(day)]
    label $w.fr.title -text "$TXT(GMtit) $VERSION / $d" -relief groove
    set frc $w.fr.frc
    frame $frc -relief flat -borderwidth 0
    text $frc.txt -width 80 -height 12 -font $FixedFont -wrap word \
	    -yscrollcommand "$frc.tscrl set"
    bind $frc.txt <space> "$frc.txt yview scroll 1 pages ; break"
    bind $frc.txt <Key-Delete> "$frc.txt yview scroll -1 pages ; break"
    bind $frc.txt <Any-Key> break
    scrollbar $frc.tscrl -command "$frc.txt yview"
    $frc.txt insert 1.0 "Copyright (c) $VERSIONDATE(year) \
Miguel Filgueiras / DCC-FC & LIACC / Universidade do Porto\n\
*   $TXT(errorsto) migf_AT_portugalmail.pt\n\
$TXT(contrib):\n\
*   Brian Baulch (baulchb_AT_onthenet.com.au)\n\
*   Andreas Lange (Andreas.C.Lange_AT_GMX.de)\n\
*   Alessandro Palmas (alpalmas_AT_tin.it)\n\
*   Valere Robin (valere.robin_AT_wanadoo.fr)\n\
*   Rob Buitenhuis (rob_AT_buitenhs.demon.nl)\n\
*   Tri Agus Prayitno (acuss_AT_bk.or.id)\n\
*   Matt Martin (matt.martin_AT_ieee.org)\n\
*   Stefan Heine (stefan.heinen_AT_djh-freeweb.de)\n\
*   Sabine Broda (sbb_AT_dcc.fc.up.pt)\n\
*   Alberto Morales (amd77_AT_gulic.org)\n\
*   Martin Buck (m_AT_rtin-buck.de)\n\
*   David Kaplan (dmkaplan_AT_ucdavis.edu)\n\
*   Jean H Theoret (ve2za_AT_rac.ca)\n\
*   Paul Scorer (p.scorer_AT_leedsmet.ac.uk)\n\
*   Nigel Orr (gps_AT_river-view.freeserve.co.uk)\n\
*   David Gardner (djgardner_AT_users.sourceforge.net)\n\
*   Nikolai Kosyakoff (priroda.net_AT_gmail.com)\n\
*   Benoit Steiner (benetsteph_AT_free.fr)\n\
*   Sandor Laky (laky.sandor_AT_freemail.hu)\n\
*   Alexander B. Preobrazhenskiy (modul_AT_ihome.ru)\n
*   Rudolf Martin (rudolf.martin_AT_gmx.de)"

    grid $frc.txt -column 0 -row 1 -sticky nesw
    grid $frc.tscrl -column 1 -row 1 -sticky nesw
    pack $w.fr -side top
    pack $w.fr.title $frc -side top -pady 5
    return
}

### images needed when starting up

# user-defined symbol menu (high-level description); see symbols.tcl
set SYUSRMENU ""
if { [file readable [set UFile(symenu) [file join $USERDIR symenu]]] } {
    LoadSymbolCustomMenu
}
InitImages

### on Unix systems GPSMan cannot be executed as root for security reasons
###  this can be disabled by replacing the condition in the if by  0  (zero)
if { $UNIX && $env(USER) == "root" } {
    GMMessage $MESS(cantexecasroot) wait
    exit 1
}

### if no user GPSMan-data directory force one being created
if { $InitDir } {
    if { ! [GMConfirm [format $MESS(oktomkdir) $USERDIR]] || \
	    [catch {file mkdir $USERDIR}] } {
	GMMessage [format $MESS(createdir) $USERDIR] wait
	exit 1
    }
} elseif { $UDUnwritable } {
    GMMessage [format $MESS(cantwrtdir) $USERDIR] wait
    exit 1
}
## similar for temporary file directory, no question, clean all files
if { ! [file exists $USERTMPDIR] } {
    if { [catch {file mkdir $USERTMPDIR}] } {
	GMMessage [format $MESS(createdir) $USERTMPDIR] wait
	exit 1
    }
}

if { ! [file writable $USERTMPDIR] } {
    GMMessage [format $MESS(cantwrtdir) $USERTMPDIR] wait
    exit 1
}

foreach f [glob -nocomplain $USERTMPDIR/*] { catch [file delete -force -- $f] }

if { [glob -nocomplain $USERTMPDIR/*] != {} } {
    GMMessage [format $MESS(cantcleandir) $USERTMPDIR]
}

###
UserDefinitions

### if no preferences file force one being written
if { $InitOpts || [OutDatedOptions] } {
    if { [SetOptions] } {
	GMMessage $MESS(goingdown) wait
	exit 0
    }
    exit 1
}

### read source files

  # files that depend on receiver trade mark
foreach f $SRCFILESFOR($MYGPS) {
    SourceEnc [file join $SRCDIR $f.tcl]
}

  # files that may depend on the preferences file
foreach f $SRCFILESEND {
    SourceEnc [file join $SRCDIR $f.tcl]
}

  # conditional files
foreach p $SRCFILESCOND {
    if { [set [lindex $p 0]] } {
	SourceEnc [file join $SRCDIR [lindex $p 1].tcl]
    }
}

  # user code assumed to be in system encoding
set ucode [file join $USERDIR patch.tcl]
if { [file exists $ucode] } {
    source $ucode
    set VERSION "$VERSION-patched"
}
