(defpackage tepid)
(in-package tepid)

(defparameter *length* 4096)
(defparameter *sf* 44100)

(defvar *freq* nil)
(defvar *wav-in* nil)
(defvar *wav-out* nil)

(let ((args (cdr (ext:command-args))))
(handler-case
 (let ((alist (loop for flag in '("-i" "-o" "-f")
               collecting
               (cons flag (nth (1+
                                (search `(,flag) args
                                 :test 'equalp))
                           args)))))
  (setf *freq* (with-input-from-string (in (cdr (assoc "-f" alist
                                                 :test 'string=)))
                (read in))
       *wav-in* (cdr (assoc "-i" alist :test 'string=))
       *wav-out* (cdr (assoc "-o" alist :test 'string=)))
  )
 (t (e) (format t "
Too lazy to write real argument handling.
/tepid -i foo.wav -o bar.wav -f 440 > stride-maximums.txt
expects ~~/ecl/warm/* and ~~/ecl/cold/* to be there and built,
whatever those are.
Writes an fftw based convolution of -f hertz sine of a pcm_f64le
fs 44100 with foo.wav to bar.wav, writing stride maximums to
standard out which could be graphed.
")
  (ext:quit))))

;;; The two ecl ffis: cold->fftw-convolve warm->transform (wav)
;;(with-output-to-string (*standard-output*)
;;(mapc 'load '(#p"~/ecl/cold/cold.fas" #p"~/ecl/warm/warm.fas")))

;;; (1) set kernel
(loop for x below *length*
for f = (* 1.0d0 (sin (* x 2 pi *freq* (/ *sf*))))
do (cold::set-kernth x f))

(cold::fft-kernel)


;;; (2) function that calls fftw-convolve on list
(defun stride (list)
(unless (= (length list) *length*)
 (return-from stride (values (nreverse list))))
(loop initially (setf list (nreverse list))
 for x below *length*
 do (cold::set-anth x (pop list)))
(cold:fftw-convolve)
(loop for x below *length* collecting (/ (cold::anth x) (* 300.0d0 *length*))))

(defun stride-and-record (list)
(let ((list (stride list)))
  (format t "~f~%" (reduce 'max list))
 (values list)))

;;(print (list *freq* *wav-in* *wav-out*))
;;; (3) That function used on one channel of a wav.
(warm:transform  *wav-in* *wav-out*
(lambda (list) (nreverse list))
(lambda (list) (stride-and-record list)))

(ext:quit)