;;; -*- Lisp -*-
;;;

(definstrument add-sound (file beg &optional (dur -1.0) 
		                             (orig-beg 0.0) 
					     (amp 1.0) 
					     (amp-env '(0 1 100 1))
					     (rev-amount .1))
  (let ((f (open-input file)))
    (unwind-protect
	(let* ((st (floor (* beg sampling-rate)))
	       (new-dur (if (plusp dur) dur (- (clm-get-duration f) orig-beg)))
	       (amp-val 0.0)
	       (outa-val 0.0)
	       (outb-val 0.0)
	       (rdA (make-readin :file f :start-time orig-beg))
	       (rdB (if (and (stereo f) (stereo *current-output-file*))
			(make-readin :file f :start-time orig-beg :channel :B)))
	       (ampf (make-func :envelope amp-env :scaler amp :start-time beg :duration new-dur))
	       (nd (+ st (floor (* sampling-rate new-dur)))))
	  (Run
	   (loop for i from st to nd do
	     (setf amp-val (env ampf))
	     (setf outa-val (* amp-val (readin rdA)))
	     (if rdB (setf outb-val (* amp-val (readin rdB))))
	     (outa i outa-val)
	     (if *reverb* (outa i (* rev-amount outa-val) *reverb*))
	     (if rdB (outb i outb-val)))))
      (close-input f))))
