%PREFIX zz
%NOHEADERS
%GLOBAL rec_name

%x IN_RECORD

%%

\[.+\]               { set rec_name [string range $zztext 1 end-1]
                       BEGIN IN_RECORD zz}
<IN_RECORD>name.*    add_name $rec_name $zztext
<IN_RECORD>loc.*     add_loc $rec_name $zztext
<IN_RECORD>regions.* ;# ignore these
<IN_RECORD>states.*  ;# and these
<IN_RECORD>\n\n      BEGIN INITIAL zz
<*>\n                ;# ignore newlines
.                    ECHO

%%

proc add_loc {rec_name loc} {
    global loc_table locations
    if {[regexp {^.+=(((\\\\ )|[^ ])+)\s+(.{4})} $loc foo city bar woz code] \
            == 0} {
        ;# should never get here, but just in case...
        puts stderr "Death on $loc (in $rec_name)."
        exit -1
    }
    regsub -all {\\\\} $city "" city
    regsub -all {\/} $city "-" city
    set locations([file join $loc_table($rec_name) $city]) $code
}

proc add_name {rec_name name} {
    global loc_table locations
    ;# check if this is a subregion
    if {[string length $rec_name] > 4} {
        regexp {^(..)} $rec_name foo parent
        set parent $loc_table($parent)
    } else {
        set parent "/"
    }
    regexp {^name=(.*)} $name foo real_name
    set loc_table($rec_name) [file join $parent $real_name]
    set locations([file join $parent $real_name]) ""
}

global zzin loc_table locations rec_name

puts "Building the locations.cache file..."

if {[catch {open "Locations" r} loc]} {
    puts stderr "Could not open the 'Locations' file."
    exit -1
}
if {[catch {open "locations.cache" w} cache]} {
    puts stderr "Could not open the 'location.cache' file."
    exit -1
}
set zzin $loc
zzlex
close $loc

foreach key [lsort -dictionary [array names locations]] {
    set value $locations($key)
    if {[string equal $value ""]} {
        puts $cache "     $key"
    } else {
        puts $cache "$value $key"
    }
}

close $cache
