 
 : next-alarm ( alarms -- timestamp/f )
     dup heap-empty?
-    [ drop f ] [ heap-peek drop time>> ] if ;
+    [ drop f ] [ heap-peek drop alarm-time ] if ;
 
 : alarm-thread-loop ( -- )
     alarms get-global

: notify-alarm-thread ( -- )
    alarm-thread get-global interrupt ;

ERROR: bad-alarm-frequency frequency ;
: check-alarm ( frequency/f -- frequency/f )
    dup [ duration? ] [ not ] bi or [ bad-alarm-frequency ] unless ;

: <alarm> ( quot time frequency -- alarm )
    check-alarm <box> alarm boa ;

: register-alarm ( alarm -- )
    dup dup time>> alarms get-global heap-push*
    swap entry>> >box
    notify-alarm-thread ;

: alarm-expired? ( alarm now -- ? )
    [ time>> ] dip before=? ;

: reschedule-alarm ( alarm -- )
    dup [ swap interval>> time+ ] change-time register-alarm ;

: call-alarm ( alarm -- )
    [ entry>> box> drop ]
    [ quot>> "Alarm execution" spawn drop ]
    [ dup interval>> [ reschedule-alarm ] [ drop ] if ] tri ;

: (trigger-alarms) ( alarms now -- )
    over heap-empty? [

    [ hence ] keep add-alarm ;

: cancel-alarm ( alarm -- )
    alarm-entry [ alarms get-global heap-delete ] if-box? ;
