# File : "ABtoTclArrays.tcl"
#                        Created: 2004-01-05 05:21:11
#              Last modification: 2004-01-05 05:21:11
# Author: Alexander Schöpe
# e-mail: <schoepe@users.sourceforge.net>
# Description: export the records from the Address Book to Tcl arrays. This 
# script creates a Tcl script file which can be sourced to create three 
# arrays called respectively persons, parents and groups. The keys of these 
# arrays are the IDs of the records. Note that, depending on the system 
# you work with, you might have to fconfigure the file encoding to an 
# appropriate value (see in the script below).
# 
# This software is free software and distributed under the same licensing terms 
# as the Tcl language itself. See license.terms in the Tcl distribution.
# 
# © Copyright Alexander Schöpe 2004



package require addressbook

foreach id [addressbook persons -ids] {
    foreach item [addressbook record $id] {
	array set person $item
    }
    set uid $person(UID)
    array unset person UID
    set persons($uid) [array get person]
    set list [addressbook parents $id]
    if {[llength $list] > 0} {
	set parents($uid) $list
	foreach item $list {
	    if {![info exists parents($item)] || [lsearch -exact $parents($item) $uid] == -1} {
		lappend parents($item) $uid
	    }
	}
    }
    unset person
}

foreach id [addressbook groups -ids] {
    foreach item [addressbook record $id] {
	array set group $item
    }
    set uid $group(UID)
    array unset group UID
    set groups($uid) [array get group]
    unset group
}

set fd [open addressbook.txt w]

# -------------------------------------------------------------
# Here, configure the file stream to the appropriate encoding
# (iso8859-1, macRoman...)
fconfigure $fd -encoding macRoman
# -------------------------------------------------------------

puts $fd "array set persons {"
foreach {n v} [array get persons] {
    puts $fd "  [list $n $v]"
}
puts $fd "}"
puts $fd "array set parents {"
foreach {n v} [array get parents] {
    puts $fd "  [list $n $v]"
}
puts $fd "}"
puts $fd "array set groups {"
foreach {n v} [array get groups] {
    puts $fd "  [list $n $v]"
}
puts $fd "}"

close $fd
