#!/bin/sh
 # the next line restarts using wish \
exec /opt/usr8.6b.2/bin/tclsh8.6  "$0" ${1+"$@"}

proc getDictKeys { d  args } {
    # use -terminalsonly to get keys that are leafs
    # use default sep to get list o keys 
    set allowopts [list -terminalsonly -sep ]
    array set opts { -terminalsonly 0 -sep " " } 
    array set opts $args 
    set badopt ""
    foreach option [array names opts  ] { 
	if { $option ni $allowopts } {lappend badopt $option }
    } 
    if { [llength $badopt ] } {
	error "Unknown option(s) [join $badopt ,]! Only options [join $allowopts ,] allowed"
    }
    set retval "" 
    set keys {} 
    try {
    	set keys [dict keys $d ]
    } on error { a b } {
    	return $retval;
    }
    foreach key $keys {
	set found 0 
	foreach subkey [getDictKeys [dict get $d $key ] -terminalsonly $opts(-terminalsonly) -sep $opts(-sep)] {
	    set found 1 
	    lappend retval "${key}$opts(-sep)$subkey"
	}
	if { !$found && $opts(-terminalsonly) } {
	    lappend retval "$key"
	} 
    }
    return $retval
}

proc printDict {dict {margin "" } } {
    upvar $dict d
    foreach keyset [getDictKeys $d -terminalsonly 1 ]  { 
	puts "[join $keyset "->"] : [dict get $d {*}$keyset]" 
    }
}

if { [ catch {package require http } err ] != 0 } {
    puts stderr "Unable to find package http ... adjust your auto_path!";
}

#if { [ catch {package require json } err ] != 0 } {
#    puts stderr "Unable to find package json ... \n$err\nadjust your auto_path!";
#}
source /tmp/json.tcl
set isbn  9780596004965
set getkeys {feed  entry 0 content \$t }
set baseurl {http://www.google.com/base/feeds/snippets}
set querystring  [::http::formatQuery bq "\[isbn:\"$isbn\"\]" alt json max-results 1 ] 
set token [::http::geturl $baseurl?$querystring ]
set reply [::json::json2dict [http::data $token ] true true ];#  -indexlists true
# output received json object 
puts "[http::data $token]"
# output raw dict 
puts "$reply"
# get all keys that are terminals only 
puts "\nkeys\n[join [getDictKeys $reply -terminalsonly 1 -sep " " ] \n]"
#pull out all terminal data elements.
puts "\n[string repeat  = 80]\n[printDict reply ]\n[string repeat  = 80  ]"
# pull out one data element
puts "[join $getkeys "->" ] = [dict get $reply {*}$getkeys]"