#!/usr/local/bin/wish8.4

#(c) Michel Van den Bergh 2000
#This program falls under the GPL. See the file COPYING for details


#begin ttraffic.tcl

set ttversion 0.8

#source config.tcl


#begin config.tcl

# munch  : file with packed levels
# configfile : contains configuration data

# solvedlevels : sorted list with OFFSETS in ttraffic.levels containing SOLVED
# levels
# slicedsolvedlevels : some slice of solvedlevels


# Generates random number [0:n-1].

expr srand([expr [clock clicks]])

proc rand {n} {
    return [expr int (  $n* rand())]
}


set munchlocations {
    ./ttraffic.levels
    /usr/share/ttraffic/ttraffic.levels
    /usr/local/share/ttraffic/ttraffic.levels
    ~/ttraffic.levels
}


proc setmunch {} {
    global munchlocations munch
    foreach l $munchlocations {
	if { [file exists $l] } {
	    set munch $l
	    return 1
	    break
	}
    }
    return 0
}


set configfile  ~/.ttraffic



proc writeconfigfile {} {
    global configfile solvedlevels
    global history board originalboard currentoffset
    global historyindex maxhistory youvewon nrofmovestaken bestyoucando
    global ttversion type




    set fp [open $configfile w]
    puts $fp "array set history {[array get history]}"
    puts $fp "set solvedlevels {$solvedlevels}"
    puts $fp "set board {$board}"
    puts $fp "set originalboard {$originalboard}"
    puts $fp "set currentoffset $currentoffset"
    puts $fp "set historyindex $historyindex"
    puts $fp "set maxhistory $maxhistory"
    puts $fp "set youvewon $youvewon"
    puts $fp "set nrofmovestaken $nrofmovestaken"
    puts $fp "set bestyoucando $bestyoucando"
    puts $fp "set type $type"
    puts $fp "set ttversion $ttversion"
    close $fp
   
}

proc readconfigfile {} {
    global configfile solvedlevels
    global history board originalboard currentoffset
    global historyindex maxhistory youvewon nrofmovestaken bestyoucando
    global ttversion type


    if { ![file exist $configfile] } {
	return 0
    }
    source $configfile
    return 1
}



proc insertinsolvedlevels { offset } {
    global solvedlevels
    lappend solvedlevels $offset
    set solvedlevels [lsort -integer $solvedlevels]
}









#sets slicedsolvedlevels to levels >= b and < e

proc slicesolvedlevels { b e } {
    global slicedsolvedlevels solvedlevels
    set slicedsolvedlevels {}
    foreach i $solvedlevels {
	if { $b <= $i && $i<$e } {
	    lappend slicedsolvedlevels  $i
	}
    }
}

# finds a random nonsolved level between offsets >=b and <e
# returns -1 if nothing left

proc randomoffset { b e } {
    global slicedsolvedlevels
    slicesolvedlevels  $b $e 
    set length [llength $slicedsolvedlevels]
#this is really 8 times the available slots!
    set availableslots [expr $e-$b-8*$length]
    if { $availableslots == 0 } {
	return -1
    }
    set preoffset [expr $b+8*[rand [expr $availableslots/8]]]
    foreach i $slicedsolvedlevels {
	if { $preoffset >= $i } {
	    incr preoffset 8
	}
    }
    return $preoffset
}


#eliminates all b<= . <e from solvedlevels

proc resetsolvedlevels { b e } {
    global solvedlevels
    set newsolvedlevels {}
    foreach i $solvedlevels {
	if { ( $i < $b) || ( $i >= $e) } {
	    lappend newsolvedlevels $i
	}
    }
    set solvedlevels $newsolvedlevels
}

#returns true if reset is allowed
proc askforreset {} {
    set result [tk_messageBox -icon question -message "No more levels of this type! Do you want to reset these levels?" -type yesno]
    if { [string compare $result yes] == 0 } {
	return 1
    } else {
	return 0
    }
}









#end config.tcl

#source menu.tcl


#begin menu.tcl

proc updateglobalmovebounds {} {
    global globalminmoves globalmaxmoves type
    if { [string compare $type Intermediate]==0 } {
	set globalminmoves 21 
	set globalmaxmoves 31
    } elseif { [string compare $type Advanced]==0 } {
	set globalminmoves 31 
	set globalmaxmoves 41
    } elseif { [string compare $type Expert]==0 } {
	set globalminmoves 41 
	set globalmaxmoves 52
    }
}



proc makemenus {} {
    menu .menubar -type menubar 
    .menubar add cascade -label File -menu .file
    .menubar add cascade -label Type -menu .type
    .menubar add cascade -label Help -menu .help

    menu .file -type normal -tearoff 0
    menu .type -type normal -tearoff 0
    menu .help -type normal -tearoff 0

    .file add command -label Quit -command { writeconfigfile ; exit } 
    .type add radiobutton -label Intermediate -variable type -value\
	    Intermediate   -command updateglobalmovebounds
    .type add radiobutton -label Advanced -variable type -value Advanced\
	    -command updateglobalmovebounds
    .type add radiobutton -label Expert -variable type -value Expert\
	    -command updateglobalmovebounds
    .help add command -label About -command {
	tk_messageBox -message "TTraffic 0.8: A Tcl/Tk version of the game\
Rush Hour created\
by Binary Arts Corporation.\n
(c) Michel Van den Bergh <vdbergh@luc.ac.be> 2000"
}

. configure -menu .menubar

}
#end menu.tcl

#Basic data structures

#car: list with the following components
#  row col horizontal  length

#originalboard,  board: list of cars   (global)
 
#physicalboard: array[row][col] with boolean values (occupied or not) (global)

#move: list with the following components

#  carnr origrowcol newrowcolnr

#history: list of moves plus historyindex, maxhistory (integer)

#colors: list of color names

#currentoffset : offset in munchfile

#youvewon : (boolean)


#initializing the user interface

proc initwindows {} {
    wm resizable . false false
    wm title .  TTraffic
    wm protocol . WM_DELETE_WINDOW {
	writeconfigfile
	exit
    }
    wm protocol . WM_SAVE_YOURSELF {
	writeconfigfile
	exit
    }
}

proc  setsomeconstants {} {
    global cellheight cellwidth borderwidth gridwidth extraroomonright
    global bordercolor

    set cellheight 50
    set cellwidth 50
    set borderwidth 10
    set gridwidth 2
    set extraroomonright $cellwidth

    set bordercolor black
}




proc initjam {} {
    global cellheight cellwidth backgroundcolor bordercolor 
    global borderwidth gridwidth extraroomonright
    global jamheight jamwidth jamoriginx jamoriginy boardheight boardwidth
#draw border
    set boardheight [expr 6 * $cellheight]
    set boardwidth [expr 6 * $cellwidth]
    set jamheight [expr $boardheight + 2 * $borderwidth]
    set jamwidth  [expr  $boardwidth + 2 * $borderwidth]
    set totaljamwidth [expr $jamwidth + $extraroomonright]
    set jamoriginx $borderwidth
    set jamoriginy $borderwidth
    canvas .jam -width $totaljamwidth -height $jamheight -relief flat 
	    pack .jam -side left
    .jam create rectangle 0 0  $borderwidth $jamheight -fill $bordercolor
    .jam create rectangle 0 0  $jamwidth $borderwidth -fill $bordercolor

    .jam create rectangle [expr $boardwidth + $borderwidth] 0\
	    $jamwidth [expr $borderwidth+2*$cellheight] -fill $bordercolor
    .jam create rectangle [expr $boardwidth + $borderwidth] \
	    [expr 3*$cellheight + $borderwidth]\
	    $jamwidth $jamheight -fill $bordercolor
  

    .jam create rectangle 0 [expr $boardheight + $borderwidth] \
	    $jamwidth $jamheight -fill $bordercolor
#drawgrid
    for {set i 0} { $i<=6 } {set i [expr $i +1]} {
	set topleftx [expr $jamoriginx+$i*$cellwidth-$gridwidth/2]
	set toplefty 0
	set bottomrightx [expr $jamoriginx+$i*$cellwidth+$gridwidth/2]
	set bottomrighty $jamheight
	.jam create rectangle $topleftx $toplefty $bottomrightx $bottomrighty\
		-fill $bordercolor
    }
    for {set i 0} { $i<=6 } {set i [expr $i +1]} {
	set toplefty [expr $jamoriginy+$i*$cellheight-$gridwidth/2]
	set topleftx 0
	set bottomrighty [expr $jamoriginy+$i*$cellheight+$gridwidth/2]
	set bottomrightx $jamwidth
	.jam create rectangle $topleftx $toplefty $bottomrightx $bottomrighty\
		-fill $bordercolor
    }
}

proc initbuttonsandlabels {} {
    frame .f 
    button .f.forward -text "Forward" -width 10 -command forwardinhistory
    button .f.backward -text "Back" -width 10   -command backinhistory
    button .f.newlevel -text "New Level" -width 10 -command "newlevel"
    button .f.restart -text "Restart"  -width 10 -command startofhistory
    label .f.bestyoucando 
    label .f.nrofmovestaken 
    label .f.youvewon 
    grid .f.backward -column 0 -row 0 
    grid .f.forward -column 1 -row 0
    grid .f.restart -column 0 -row 1
    grid .f.newlevel -column 1 -row 1
    grid rowconfigure .f 2 -minsize 30
    grid .f.bestyoucando -column 0 -row 4 -columnspan 2  
    grid .f.nrofmovestaken -column 0 -row 3 -columnspan 2 
    grid rowconfigure .f 5 -minsize 30
    grid .f.youvewon -column 0 -row 6 -columnspan 2
    pack .f -side left
    .f.forward configure -state disabled
    .f.backward configure -state disabled
}

proc initvars {} {
    global maxhistory historyindex nrofmovestaken youvewon bestyoucando
    set maxhistory 0
    set historyindex 0
    set nrofmovestaken 0
    set youvewon 0
}

proc updatenrofmovestaken {} {
    global nrofmovestaken
    .f.nrofmovestaken configure -text "You have taken $nrofmovestaken moves"
}

proc updateyouvewon {} {
    global youvewon currentoffset
    
    if { $youvewon} {
	.f.youvewon configure -text "YOU HAVE WON!" 
    } else {
	.f.youvewon configure -text "" 
    }
}

proc updatebestyoucando {} {
    global bestyoucando
    .f.bestyoucando configure -text "The best you can do is\
 [expr $bestyoucando-1]"
}

proc newlevel  {} {
    global firsttime originalboard currentoffset board globalminmoves globalmaxmoves
    set offset [randomlevel $globalminmoves $globalmaxmoves]
    if { $offset >= 0 } {
	initvars
	updatenrofmovestaken
	updateyouvewon
	updatebestyoucando
	set board $originalboard
	destroycars
	.f.backward configure -state disabled
	.f.forward configure -state disabled
	setupboard
	set currentoffset $offset
	writeconfigfile
    } 
	
}

#setup up colors

set colors {
green
yellow
darksalmon
mediumturquoise
darkblue
orange
seagreen
magenta
purple
brown
steelblue
chocolate
burlywood
darkgreen
darkmagenta
deeppink
tan4
grey30
}



#setup a testboard

proc testboard {} {
    global originalboard
    set originalboard {{0 0 0 2} {0 2 1 2} {0  4 1 2} {1 1 1 3}\
	    {1 5 0 2} {2 0 1 2} {2 2 0 2} {2 3 0 2} \
	    {3 4 1 2} {4 1 1 3} {4 4 0 2} {4 5 0 2} \
	    {5 1 1 3}}
}

# returns the nearest gridpoint  for a given point x,y in canvas coordinates
# the returned point maybe outside board

proc nearestgridpoint {x y} {
    global jamoriginx jamoriginy cellheight cellwidth
    set roundy [expr (round (($y-$jamoriginy+0.0)/$cellheight))\
	    *$cellheight+$jamoriginy]
    set roundx [expr (round (($x-$jamoriginx+0.0)/$cellwidth))\
	    *$cellwidth+$jamoriginx]
    return "$roundx $roundy"
}

#converts x,y coordinates on grid to row col pairs
#rounding is not strictly necessary

proc torowcol {x y} {
    global jamoriginx jamoriginy cellheight cellwidth
    set row  [expr round(($y-$jamoriginy+0.0)/$cellheight)]
    set column  [expr round(($x-$jamoriginx+0.0)/$cellwidth)]
    return "$row $column"
}

proc togridpoint {row col } {
    global jamoriginx jamoriginy cellheight cellwidth
    set x [expr $col*$cellwidth +$jamoriginx]
    set y [expr $row*$cellwidth +$jamoriginx]
    return "$x $y"
}

#send board to canvas

proc setupboard {} {
    global board colors
    set i 0
    foreach car $board {
	if { ([lindex $car 0] == 2) && [lindex $car 2] } {     # red car
	    drawcar $car car$i red 
	} else {
	    drawcar $car car$i [lindex $colors $i] 
	}
	.jam bind car$i <Button-1> "startdrag %x %y car$i"
	.jam bind car$i <Button1-Motion> "drag  %x %y car$i"
	.jam bind car$i <ButtonRelease-1> "enddrag %x %y car$i $i"
	    set i [expr "$i+1"]

    }
    tophysicalboard
}

proc destroycars {} {
    .jam delete cars
}



#make a board to indicate filled cases
proc tophysicalboard {} {
    global physicalboard board
    for { set row 0 } { $row <=5 } { set row [expr $row+1] } {
	for { set column 0 } { $column <=5 } { set column [expr $column+1] } {
	    set physicalboard($row,$column) 0
	}
	
    }
    foreach car $board {
	set row [lindex $car 0]
	set col [lindex $car 1]
	set horizontal [lindex $car 2]
	set length [lindex $car 3]
	for { set i 0 } { $i<= ($length-1) } { set i [expr $i+1] } {
	    if { $horizontal } {
		set physicalboard($row,[expr $col+$i]) 1
	    } else {
		set physicalboard([expr $row+$i],$col) 1
	    }
	}
    }   
}



proc printphysicalboard {} {
    global physicalboard
    puts ""
    for { set row 0 } { $row <= 5 } { set row [expr $row +1] } {
	for { set column 0 } { $column <= 5 } { set column [expr $column +1] } {
	    puts -nonewline $physicalboard($row,$column)
	}
	puts ""
    }

}


#draw a car. This could be done better!

proc drawcar {car tag color}  {
    global cellwidth cellheight gridwidth
    global jamoriginx jamoriginy
    set row [lindex $car 0]
    set col [lindex $car 1]
    set horizontal [lindex $car 2]
    set length [lindex $car 3]
    set upperleftx [expr $jamoriginx+ $col*$cellwidth+$gridwidth/2]
    set upperlefty [expr $jamoriginy+ $row*$cellheight+$gridwidth/2]
    if { $horizontal } {
	set lowerrightx [expr $jamoriginx+($col+$length)*$cellwidth\
	-$gridwidth/2]
	set lowerrighty [expr $jamoriginy+($row+1)*$cellheight\
		-$gridwidth/2]
    } else {
	set lowerrightx [expr $jamoriginx+($col+1)*$cellwidth\
		-$gridwidth/2]
	set lowerrighty [expr $jamoriginy+($row+$length)*$cellheight\
		-$gridwidth/2]
    }
    .jam create rectangle $upperleftx $upperlefty\
	    $lowerrightx $lowerrighty  -fill $color -tags "$tag  cars"
}

proc reversemove {move} {
    return "[lindex $move 0] [lindex $move 2] [lindex $move 1]"
}


proc movecar {move} {
    global board cellwidth cellheight
    set carnr [lindex $move 0]
    set origrowcol [lindex $move 1]
    set newrowcol [lindex $move 2]
    set car [lindex $board $carnr]
    set length [lindex $car 3]
    set horizontal [lindex $car 2]
    if { $horizontal } {
	.jam move car$carnr [expr ($newrowcol-$origrowcol)*$cellwidth] 0 
	set row [lindex $car 0]
	set board [lreplace $board $carnr $carnr "$row $newrowcol $horizontal\
		$length"]
	
    } else {
	.jam move car$carnr 0 [expr ($newrowcol-$origrowcol)*$cellheight]  
	set column [lindex $car 1]
	set board [lreplace $board $carnr $carnr "$newrowcol $column\
		$horizontal $length"]
    }
    tophysicalboard
    
}

proc updatebackandforwardbuttons {} {
    global historyindex maxhistory
    set forwardenabled 1
    set backwardenabled 1
    if { $historyindex == 0 } {
	set backwardenabled 0
    } 
    if { $historyindex == $maxhistory } {
	set forwardenabled 0
    }
    if { $backwardenabled } {
	.f.backward configure -state active
    } else {
	.f.backward configure -state disabled
    }
    if { $forwardenabled } {
	.f.forward configure -state active
    } else {
	.f.forward configure -state disabled
    }
}

proc addtohistory {index origrowcol newrowcol} {
    global history historyindex maxhistory
    set history($historyindex) "$index $origrowcol $newrowcol"
    set historyindex [expr $historyindex +1]
    set maxhistory $historyindex
    updatebackandforwardbuttons
}

proc backinhistory {} {
    global history historyindex nrofmovestaken
    set historyindex [expr $historyindex-1]

    movecar [reversemove $history($historyindex)]
    set nrofmovestaken [expr $nrofmovestaken -1]
    updatenrofmovestaken
    updatebackandforwardbuttons
}

proc forwardinhistory {} {
    global history historyindex nrofmovestaken maxhistory

    movecar $history($historyindex)
    set historyindex [expr $historyindex+1]

    set nrofmovestaken [expr $nrofmovestaken +1]
    updatenrofmovestaken
    updatebackandforwardbuttons

}

proc startofhistory {} {
    global historyindex maxhistory nrofmovestaken board originalboard
    set historyindex 0
    destroycars
    updatebackandforwardbuttons
    set board $originalboard
    setupboard
    set nrofmovestaken 0
    updatenrofmovestaken
}


proc startdrag {x y tag} {
    global xorg yorg xorgorg yorgorg
    set xorg $x
    set yorg $y
    set xorgorg $x
    set yorgorg $y
    .jam raise $tag
}

proc drag {x y tag} {
    global xorg yorg
    .jam move $tag [expr $x-$xorg] [expr $y-$yorg] 
    set xorg $x
    set yorg $y
}

proc enddrag {x y tag  index} {
    global gridwidth
    global xorgorg yorgorg
    global physicalboard
    global board
    global nrofmovestaken
    global youvewon
    global currentoffset

#do a last drag 
    drag $x $y $tag

#compute to left corner
    set coords [.jam coords $tag]
    set upperleftx [lindex $coords 0]
    set upperlefty [lindex $coords 1]
    set  gridpoint [nearestgridpoint $upperleftx $upperlefty ]

#test legality
    set legal 1
    set rowcol [torowcol [lindex $gridpoint 0] [lindex $gridpoint 1]]
    set row [lindex $rowcol 0]
    set column [lindex $rowcol 1]
    set car [lindex $board $index]
    set carrow [lindex $car 0]
    set carcolumn [lindex $car 1]
    set horizontal [lindex $car 2]
    set length [lindex $car 3]
    set perhapsredcarout 0
# perhaps redcar out
    if { $column >= 4 && $carrow==2 && $row==2 && $horizontal} { 
# normalize
	set column 4  
	set gridpoint [togridpoint $row $column]
	set perhapsredcarout 1
    } 

    if { ($row>=6)|| ($row<0) || ($column<0) || ($column>=6) } {
	set legal 0
    } elseif { $horizontal && (($column +$length) > 6) } {
	set legal 0
    } elseif { !$horizontal && (($row +$length) > 6) } {
	set legal 0
    } elseif { $horizontal && ($carrow!=$row) } {
	set legal 0
    } elseif {!$horizontal && ($carcolumn!=$column) } {
	set legal 0
    } elseif { $horizontal && ($column >= $carcolumn) } {
	for {set i $carcolumn } {$i < $column } { set i [expr $i+1]} {
	    if { $physicalboard($row,[expr $i+$length])==1 } {
		set legal 0
	    }
	}
    } elseif { $horizontal && ($column <= $carcolumn) } {
	for {set i $column } {$i < $carcolumn } { set i [expr $i+1]} {
	    if { $physicalboard($row,$i)==1 } {
		set legal 0
	    }
	}
    } elseif { !$horizontal && ($row >= $carrow) } {
	for {set i $carrow } {$i < $row } { set i [expr $i+1]} {
	    if { $physicalboard([expr $i+$length],$column)==1 } {
		set legal 0
	    }
	} 
    } elseif { !$horizontal && ($row <= $carrow) } {
	for {set i $row } {$i < $carrow } { set i [expr $i+1]} {
	    if { $physicalboard($i,$column)==1 } {
		set legal 0
	    }
	}
    }


    if { !$legal } {   #undo move
	.jam move $tag [expr $xorgorg-$x] [expr $yorgorg-$y]
    } else {
	.jam move $tag [expr -$upperleftx+ [lindex $gridpoint 0]+$gridwidth/2]\
	  [expr -$upperlefty+ [lindex $gridpoint 1]+$gridwidth/2]  
	set board [lreplace $board $index $index\
		"$row $column $horizontal $length"]
	tophysicalboard
	if { $row!=$carrow || $column!=$carcolumn } {
	    set nrofmovestaken [expr $nrofmovestaken +1 ]
	    updatenrofmovestaken
	    if { $horizontal } {
		addtohistory $index  $carcolumn $column
	    } else {
		addtohistory $index $carrow $row
	    }
	    if { $perhapsredcarout } {
		if { !$youvewon } {
		    set youvewon 1
		    updateyouvewon
		    insertinsolvedlevels $currentoffset 
		}
	    }
	}
    }

}



#source files.tcl


#begin files.tcl

#file manipulations

#data structure 

#packedboard { rows columns }
#unpackedboard : array (0:11)
#board : see ttraffic.tcl
#directory  array of integers
#directory(0) : minmovestosolution
#directory(1)  : mostcomplexsolution
#directory(2:entriesindirectory+1) : offests in munch file
#directory(entriesindirectory+1) : points right behind end of file

set  gtrafficstrips {
  { {0 0} {0 0} } 
  { {0 2} {0 0} } 
  { {1 2} {0 0} } 
  { {2 2} {0 0} } 
  { {3 2} {0 0} } 
  { {4 2} {0 0} } 
  { {0 3} {0 0} } 
  { {1 3} {0 0} } 
  { {2 3} {0 0} } 
  { {3 3} {0 0} } 
  { {0 2} {2 2} } 
  { {0 2} {3 2} } 
  { {0 2} {4 2} } 
  { {1 2} {3 2} } 
  { {1 2} {4 2} } 
  { {2 2} {4 2} } 
}

proc unpackboard { packedboard } {
    global unpackedboard
    set r [lindex $packedboard 0]
    set c [lindex $packedboard 1]
    for { set i 0 } { $i<=5 } { set i [expr $i+1]} {
	set unpackedboard($i) [expr $r & 0xF]
	set r [expr $r >> 4]
    }
    for {set i 6 } { $i<=11 } {set i [expr $i+1]} {
	set unpackedboard($i) [expr $c & 0xF];
	set c [expr $c >> 4]
    }
}

proc tottrafficboard {} {
  
    global unpackedboard originalboard gtrafficstrips



    set originalboard {}
    for { set i 0 } { $i<=11 } {incr i} { 
    set stripnr  $unpackedboard($i)
	for {set j 0} { $j<=1 } {incr j} {
#           g=gtrafficstrips[stripnr][j];
	    set g [lindex [lindex $gtrafficstrips $stripnr] $j]
	    set carpos [lindex $g 0]
	    set carlength [lindex $g 1]
	    if { $carlength!=0 } {
		if { $i<=5 } {    #horizontal cars
		    lappend originalboard "$i $carpos  1 $carlength"
		} else {

		    lappend originalboard "$carpos [expr $i-6]  0 $carlength"
		}
	    }
	}
    }

}



proc readint { fileid } {
    set l [read $fileid 4]

  
    binary scan $l i r
    return $r
}


proc readdirectory {} {
    global directory minmovestosolution mostcomplexsolution entriesindirectory
    global munch
    set fp [open $munch r]
    fconfigure $fp -translation  {binary binary}


    set minmovestosolution [readint $fp]
    set mostcomplexsolution [readint $fp]
    set directory(0) $minmovestosolution
    set directory(1) $mostcomplexsolution
    set entriesindirectory [expr $mostcomplexsolution-$minmovestosolution+2]
    for { set i 1 } {$i<=$entriesindirectory} {set i [expr $i+1]} {
	set directory([expr $i+1]) [readint $fp]
    }
    close $fp
}

# returns a level >=minmoves <maxmoves
# return offset in file, if no move level left ask user to reset, if
# user refuser, return -1
# sets bestyoucando if actual level is returned


proc randomlevel { minmoves maxmoves } {
    global directory entriesindirectory minmovestosolution bestyoucando
    global munch
    readdirectory
    set placeofminmoves  [expr $minmoves - $minmovestosolution +2]
    set placeofmaxmoves  [expr $maxmoves - $minmovestosolution +2]
    set beginoffset $directory($placeofminmoves)
    set endoffset $directory($placeofmaxmoves)
    set offset  [randomoffset $beginoffset $endoffset]
    set makenewlevel 0
    if { $offset >= 0 } {
	set makenewlevel 1
    } elseif { [askforreset] } {
	resetsolvedlevels  $beginoffset $endoffset 
	set offset  [randomoffset $beginoffset $endoffset]
	set makenewlevel 1
    }
    if { $makenewlevel } {
	set fp [open $munch r]
	fconfigure $fp -translation  {binary binary}

	seek $fp $offset start
	set rows [readint $fp]
	set columns [readint $fp]
	unpackboard "$rows $columns"
	tottrafficboard
	close $fp
	for { set p $minmoves } { $p< $maxmoves } { incr p } {
	    set directoryentry $directory([expr "$p - $minmovestosolution + 2 + 1"])
	    if {  $directoryentry > $offset } {
		set bestyoucando $p 
		break
	    }
	}
    } 
    return $offset
}

proc showoffset { offset } {
    global unpackedboard munch 
    set fp [open $munch r]
    fconfigure $fp -translation  {binary binary}

    seek $fp $offset start
    set rows [readint $fp]
    set columns [readint $fp]
    puts "rows=$rows columns=$columns"
    unpackboard "$rows $columns"
    for { set i 0 } {$i<=11 } {incr i} {
	puts "$i=$unpackedboard($i)"
    }
    tottrafficboard
   setupboard 
    tophysicalboard
    printphysicalboard
 }



#end files.tcl




setmunch
initwindows
setsomeconstants
initjam
initbuttonsandlabels
makemenus

if { [readconfigfile ]  } {
    setupboard
    updatebackandforwardbuttons
    updatenrofmovestaken
    updateyouvewon
    updatebestyoucando
    updateglobalmovebounds
} else {
    set solvedlevels {}
    set type Intermediate
    updateglobalmovebounds
    newlevel
}




#end ttraffic.tcl



















