# Read/write tcl preference files.
# Rick Smereka, Copyright (C) 2004-2005.

# 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; if not, get a copy via the Internet at
# http://gnu.org/copyleft/gpl.html or write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307 USA

# You can contact the author via email at rsmereka@future-lab.com

# Initial tcl version. Jul/2004, Rick Smereka

proc prefsave { filename arrayname } {
   # Save all elements of an array to a file
   # as tcl code. Returns 1 upon success,
   # 0 otherwise.
   upvar #0 $arrayname alink

   # open file, truncate if exist
   set ret [catch {
      set fileid [open $filename "w"]
      set names [array names alink]
      puts $fileid "# program prefs, modify at your own risk"
      puts $fileid "global $arrayname"

      foreach name $names {
         set var [format "set %s(%s)" $arrayname $name]
         puts $fileid "$var \"$alink($name)\""
      }

      close $fileid
   }]

   if {$ret} {
      return 0
   } else {
      return 1
   }
}

proc prefload { filename } {
   # Load prefs file as a tcl 'source' file. Returns 1 upon
   # success, 0 otherwise.
   if {[file readable $filename]} {
      source $filename
      set ret 1
   } else {
      set ret 0
   }

   return $ret
}
