#!/usr/bin/wish -f

font create clock_font -size 24  -family "Helvetica"

label .clock -textvariable elapsed -font clock_font

frame .buttons
button .buttons.start -text Start -command start -default disabled
button .buttons.stop -text Stop -command stop
button .buttons.reset -text Reset -command reset
button .buttons.quit -text Quit -command exit
pack .buttons.start .buttons.stop .buttons.reset .buttons.quit -side left

pack .clock .buttons

proc start { } {
    global start_time running
    set start_time [clock seconds]
    # start process
    set running true
    updateClock
}

proc stop { } {
    global running
    set running false
}

proc updateClock { } {
    global elapsed_time running
    if $running {
        incr elapsed_time
        setElapsed $elapsed_time
        after 1000 updateClock
    }
}

proc zeroBefore {n} {
    if {$n < 10} {
        return 0$n
    } else {
        return $n
    }
}

proc setElapsed {n} {
    global elapsed
    set minutes [zeroBefore [expr $n / 60]]
    set seconds [zeroBefore [expr $n % 60]]
    set elapsed $minutes:$seconds
}

proc reset { } {
    global elapsed_time
    set elapsed_time 0
    setElapsed 0
}

reset