# File: "AddressbookFromTab.tcl"
#                        Created: 2003-12-11 13:09:31
#              Last modification: 2004-01-23 09:07:17
# Author: Bernard Desgraupes
# e-mail: <bdesgraupes@easyconnect.fr>
# www: <http://webperso.easyconnect.fr/bdesgraupes/>
# Description: this simple script is an example file. You will 
# have to adapt it to your own needs. It reads a file of tab
# separated database records and writes them in the Address Book: all the 
# records are created in a subgroup called "Imported".
# 
# This script has been placed in the public domain.


package require addressbook

# Set the fname variable to the pathname of the db file you want to import
set fname "/Users/MyName/tabdb.txt"



set fid [open $fname r]
set lines [read $fid]
close $fid

# Suppose each line of the file is a database record with seven tab separated 
# fields corresponding respectively to the first name, the last name, a first 
# line of address, a second line of address, a Zip code, a city and a 
# phone number.
set keylist [list first last adr1 adr2 zip city tel]

# Search if there is already a subgroup called "Imported". If not, create it.
set groupId [addressbook search -groups -ids GroupName == Imported]
if {$groupId == ""} {
    set groupId [addressbook create group Imported]
} 

set lines [split $lines "\r\n"]
set keysnum [llength $keylist]

foreach line $lines {
    unset -nocomplain Rec
    # Store a line
    set line [split $line "\t"]
    set len [llength $line]
    if {$len == $keysnum} {
        for {set i 0} {$i < $len} {incr i} {
            array set Rec [list [lindex $keylist $i] [lindex $line $i]]
        }
	# Create a new record in AB inside the subgroup
	if {$groupId != ""} {
	    set theid [addressbook create person $Rec(last) -ingroup $groupId]
	} 
	# Add the data to the record
	catch {addressbook set $theid First $Rec(first)}
	catch {addressbook set $theid Phone [list [list Home [lindex $Rec(tel) 0]]]}
	set thestreet $Rec(adr1)
	if {$Rec(adr2) != ""} {
	    append thestreet "\r$Rec(adr2)"
	} 
	set theaddr [list [list Home [list [list City $Rec(city)] [list ZIP $Rec(zip)] [list Street $thestreet]]]]
	catch {addressbook set $theid Address $theaddr}
	addressbook save
	unset -nocomplain Rec
    } 
} 

