+(define (time<= time1 time2)
+ "Check if TIME1 is less than or equal to TIME2"
+ (or (time< time1 time2)
+ (time= time1 time2)))
+
+
+(define-record-type <time-delta>
+ (make-time-delta-intern sec usec)
+ time-delta?
+ (sec time-delta-sec)
+ (usec time-delta-usec))
+
+(define* (make-time-delta sec #:optional (usec 0))
+ "Make a <time-delta> of SEC seconds and USEC microseconds.
+
+This is used primarily so the agenda can recognize RUN-REQUEST objects
+which are meant "
+ (make-time-delta-intern sec usec))
+
+(define tdelta make-time-delta)
+
+(define (time-carry-correct time)
+ "Corrects/handles time microsecond carry.
+Will produce (0 . 0) instead of a negative number, if needed."
+ (cond ((>= (cdr time) 1000000)
+ (cons
+ (+ (car time) 1)
+ (- (cdr time) 1000000)))
+ ((< (cdr time) 0)
+ (if (= (car time) 0)
+ '(0 0)
+ (cons
+ (- (car time) 1)
+ (+ (cdr time) 1000000))))
+ (else time)))
+
+(define (time-delta+ time time-delta)
+ "Increment a TIME by the value of TIME-DELTA"
+ (time-carry-correct
+ (cons (+ (car time) (time-delta-sec time-delta))
+ (+ (cdr time) (time-delta-usec time-delta)))))
+
+(define (time-minus time1 time2)
+ "Subtract TIME2 from TIME1"
+ (time-carry-correct
+ (cons (- (car time1) (car time2))
+ (- (cdr time2) (cdr time2)))))
+
+(define (time-plus time1 time2)
+ "Add TIME1 and TIME2"
+ (time-carry-correct
+ (cons (+ (car time1) (car time2))
+ (+ (cdr time2) (cdr time2)))))
+
+
+(define-record-type <schedule>
+ (make-schedule-intern segments)
+ schedule?
+ (segments schedule-segments set-schedule-segments!))
+
+(define* (make-schedule #:optional segments)
+ "Make a schedule, optionally pre-composed of SEGMENTS"
+ (make-schedule-intern (or segments '())))
+
+(define (schedule-soonest-time schedule)
+ "Return a cons of (sec . usec) for next time segement, or #f if none"
+ (let ((segments (schedule-segments schedule)))
+ (if (eq? segments '())
+ #f
+ (time-segment-time (car segments)))))
+
+;; TODO: This code is reasonably easy to read but it
+;; mutates AND is worst case of O(n) in both space and time :(
+;; but at least it'll be reasonably easy to refactor to
+;; a more functional setup?
+(define (schedule-add! schedule time proc)
+ "Mutate SCHEDULE, adding PROC at an appropriate time segment for TIME"