;;; -*- Lisp -*-

(defvar fm-insect-degree 0.0)
(defvar fm-insect-distance 1.0)
(defvar fm-insect-reverb-amount 0.005)


;;; FM-INSECT ---------------------------------------------------

(defInstrument FM-insect (start-time duration frequency amplitude amp-env 
			  mod-freq mod-skew mod-freq-env mod-index mod-index-env 
			  fm-index fm-ratio
			  &key (degree fm-insect-degree)
		     	       (distance fm-insect-distance)
		               (reverb-amount fm-insect-reverb-amount))
  (let* ((beg (floor (* start-time sampling-rate)))
	 (end (+ beg (floor (* duration sampling-rate))))
	 (loc (make-locsig :degree degree :distance distance :revscale reverb-amount))
	 (carrier (make-oscil :frequency frequency))
	 (fm1-osc (make-oscil :frequency mod-freq))
	 (fm2-osc (make-oscil :frequency (* fm-ratio frequency)))
	 (ampf (make-func :envelope amp-env 
			  :scaler amplitude :start-time start-time :duration duration))
	 (indf (make-func :envelope mod-index-env
			  :scaler (in-Hz mod-index)
			  :start-time start-time :duration duration))
	 (modfrqf (make-func :envelope mod-freq-env
			     :scaler (in-Hz mod-skew)
			     :start-time start-time :duration duration))
	 (fm2-amp (in-Hz (* fm-index fm-ratio frequency)))
	 (garble-in 0.0)
	 (garble-out 0.0))
    (Run
     (loop for i from beg to end do
       (setf garble-in (* (env indf)
			  (oscil fm1-osc (env modfrqf))))
       (setf garble-out (* fm2-amp (oscil fm2-osc garble-in)))
       (locsig loc i (* (env ampf) 
			(oscil carrier (+ garble-out garble-in))))))))

#|
(defvar locust '(0 0 40 1 95 1 100 .5));
(defvar Bug_hi '(0 1 25 .7 75 .78 100 1));
(defvar amp    '(0 0 25 1 75 .7 100 0))
	
(FM-Insect 0      1.699  4142.627  .015 amp 60 -16.707 locust 500.866 bug_hi  .346  .500)
(FM-Insect 0.195   .233  4126.284  .030 amp 60 -12.142 locust 649.490 bug_hi  .407  .500)
(FM-Insect 0.217  2.057  3930.258  .045 amp 60 -3.011  locust 562.087 bug_hi  .591  .500)
(FM-Insect 2.100  1.500   900.627  .06  amp 40 -16.707 locust 300.866 bug_hi  .346  .500)
(FM-Insect 3.000  1.500   900.627  .06  amp 40 -16.707 locust 300.866 bug_hi  .046  .500)
(FM-Insect 3.450  1.500   900.627  .09  amp 40 -16.707 locust 300.866 bug_hi  .006  .500)
(FM-Insect 3.950  1.500   900.627  .12  amp 40 -10.707 locust 300.866 bug_hi  .346  .500)
(FM-Insect 4.300  1.500   900.627  .09  amp 40 -20.707 locust 300.866 bug_hi  .246  .500)
|#
