#!/usr/bin/tclsh
###
### removetoken.tcl
###

# (C) Pascal Georges 2007, Uwe Klimmek 2020
#
# Will remove entries containing a token from the argumentlist.
# Removes the token(s) from all language files in a single run.
#
# Usage (run from the tcl/lang directory):
#   tclsh removetoken.tcl TokenName
#   tclsh removetoken.tcl Token1 Token2 Token3

array set encodings {
  czech utf-8
  deutsch utf-8
  francais utf-8
  hungary utf-8
  italian utf-8
  nederlan utf-8
  norsk utf-8
  polish utf-8
  portbr utf-8
  russian utf-8
  serbian iso8859-2
  spanish utf-8
  swedish utf-8
  catalan utf-8
  suomi utf-8
  greek utf-8
  turkish utf-8
  SerbCyr utf-8
  japanese utf-8
  romanian utf-8
}

set languages {czech deutsch francais hungary italian nederlan norsk polish
  portbr spanish swedish serbian russian catalan suomi greek turkish SerbCyr japanese romanian
}

################################################################################
proc remove {langfile enc tokens} {
  # Read the language file

  set f [open $langfile.tcl r]
  fconfigure $f -encoding $enc
  set data [read $f]
  close $f
  set langData [split $data "\n"]
  set tokenList [split $tokens " "]
  #split generates an additional "\n", delete this
  set langData [lreplace $langData end end]

  set fnew [open $langfile.tcl w]
  fconfigure $fnew -encoding $enc
  set removenext 0
  set removebrace 0
  foreach line $langData {
    set fields [split $line]
    set command [lindex $fields 0]
    set lang [lindex $fields 1]
    set name [lindex $fields 2]
    if { $removebrace } {
        set removebrace 0
        if { [string first "\}" $line] < 0 } {
          set removebrace 1
        }
    } elseif { $removenext } {
        set removenext 0
        if { [string index $line end] == "\\" } {
          set removenext 1
        }
    } elseif { [regexp {^#.*TODO.*translate} $line] } {
        set to_be_translated $line
        continue
    } elseif { $command == "translate" || $command == "menuText" } {
        foreach token $tokenList {
            set found 0
            if { $name == $token } {
                set found 1
                break
            }
        }
        if { ! $found } {
            if {[info exists to_be_translated]} { puts $fnew $to_be_translated }
            puts $fnew $line
        } else {
            if { [string index $line end] == "\\" } {
                set removenext 1
            } elseif { [string first "\{" $line] >= 0 &&  [string first "\}" $line] < 0} {
                set removebrace 1
            }
        }
    } else {
        if {[info exists to_be_translated]} { puts $fnew $to_be_translated }
        puts $fnew $line
    }
    unset -nocomplain to_be_translated
  }
  close $fnew
}
################################################################################

set token $argv

foreach language $languages {
  remove $language $encodings($language) $token
}

# end of file
