#!/bin/bash
# Published under GNU Public License (GPL) May 2014 ML
# syntax: rc-gopal7 'filename' 
# filename should be of the form foobar.xml, the converted file
# will appear as foobar-gp7.xml in th local directory,
# the original file will be untouched
# error checking is only rudimentary, feel free to improve it
#
# run default path \
exec tclsh "$0" ${1+"$@"}

# as stated below, the tdom package is required see: http://tdom.github.com
package require tdom

# as with most (all ?) tcl progs, the 'main' proc is at the end of the file

# the 'City' attribute is searched for a country name
# comparison is done on  City string converted to lower case
# add country/code pairs as needed

proc chkForCCode { destName } {
   set compareList [list \
   "deutschland" 49 "frankreich" 31 "polen" 48 "spanien" 34 ]

   set loname [string tolower $destName]
   set iret [expr -1]
   foreach { name icode } $compareList {
      if { [string first $name $loname] > -1 } {
         set iret $icode
	 break
      }
   }
   return $iret
}
# this code will only search for the first 'City' and 'Country'
# entry in a 'Destination'. it is unknown what a read Medion would do,
# if given a secnd tag ...
# 
proc chkDestNode { dom dest_nd } {
   set dNameList [$dest_nd selectNodes {City[@name]} ]
   if { [llength $dNameList] < 1 } {
      puts stderr "waypoint: w/o name"
   } else {
      set destName [[lindex $dNameList 0] getAttribute name]
      set ncode [chkForCCode $destName]
      puts "wayp name: $destName > $ncode"
   }
   set dCodeNode [$dest_nd selectNode Country]
   if { $dCodeNode == "" } {
     set dCodeNode [$dom createElement "Country"]
     $dest_nd insertBefore $dCodeNode [$dest_nd firstChild]
   }
   $dCodeNode setAttribute "code" $ncode
   return $ncode
}
#  append -gp7 to regular filename

proc getGP7name { fname } {
   set rawname [file tail $fname]
   set fext [file extension $rawname]

   set outgp7 [file rootname $rawname]

   append outgp7 "-gp7" $fext
   puts "names: $fname $outgp7"
   return $outgp7
}

puts "Program name: $argv0 narg: $argc"

if { $argc  < 1 } {
   puts stderr "$argv0: need an argument"
} else {
   set fname [ lindex $argv 0 ]
   if [ catch {open $fname r} fdi ] {
      puts stderr "$argv0: failed read file: $fname"
      exit 1
   } else {
      puts "Processing $fname"
      set doc [dom parse -channel $fdi]
      close $fdi

      set root [$doc documentElement]

      set start_node [$root selectNodes /Tour/Start]
      if {$start_node == ""} {
         puts stderr "No start tag found"
      } else {
         chkDestNode $doc $start_node
      }
      set dest_l [$root selectNodes //Destination]
      puts "$fname: [llength $dest_l] waypoints"
      foreach dest $dest_l {
         chkDestNode $doc $dest
      }
   }
   set outf [getGP7name $fname]
   if [ catch { open $outf w} fdo ] {
      puts stderr "write to $outf failed"
   } else {
      puts $fdo [$root asXML]
      close $fdo
   }
}
