(define make-rhythm
(lambda (beats tactus syncopation rhythm-list)
(define beats-divisible-by-rlst
(lambda (dur)
(member 0 (map (lambda (r) (modulo dur r)) rhythm-list))))
(set! rhythm-list (cl:sort rhythm-list >))
(if (not (= 0 (modulo beats tactus)))
(begin (log-error "Tactus must be a subdivision of beats") '())
(if #f ;(not (beats-divisible-by-rlst beats))
(begin (println "Impossible rhythm-list selection") '())
(let loop ((rl '())
(cnt 0))
(if (null? rl) (list (random rhythm-list)))
(let ((sum (apply + rl)))
(cond ((> cnt 500)
(log-error "Could not make valid rhythm")
'())
((> sum beats)
(loop (cdr rl) (+ cnt 1)))
((not (beats-divisible-by-rlst (- beats sum)))
(loop (cdr rl) (+ cnt 1)))
((>= (car rhythm-list) (- beats sum))
(cond ((= sum beats)
(reverse rl))
((member (- beats sum) rhythm-list)
(reverse (cons (car (member (- beats sum) rhythm-list)) rl)))
(else (loop (cons (random rhythm-list) rl) (+ cnt 1)))))
(else (if (= 0 (modulo sum tactus))
(loop (cons (random rhythm-list) rl) (+ cnt 1))
(if (> (random) (+ .05 syncopation))
(loop (cons (car rl) rl) (+ cnt 1))
(loop (cons (random rhythm-list) rl) (+ cnt 1))))))))))))