;nyquist plug-in
;version 4
;type tool
;name "Export Clips"
;author "Steve Daulton"
;release 3.7.2
;copyright "GNU General Public License v2.0 or later"


;control FILENAME "Export clips to" file "Select folder" "*export*/clip[n].wav" "WAV file|*.wav;*.WAV|MP3 files|*.mp3;*.MP3|OGG files|*.ogg;*.OGG|All files|*.*;*" "save,overwrite"
;control USE_CLIP_NAME "Use clip names" choice "Yes, No" 1

;; Get path and extension from FILENAME.
(dotimes (i (length FILENAME))
  (if (char= (char FILENAME i) *file-separator*)
      (setf idx i)))

(setf folder (subseq FILENAME 0 (1+ idx)))
(setf prefix "clip")
(setf suffix (subseq FILENAME (- (length FILENAME) 4)))
(setf clipnum 1)


(setf clipnames (list))

(defun new-file-name ()
  ;;; Constuct a unique file name.
  (if (= USE_CLIP_NAME 0)
	  (setf name (format nil "~a~a-~a~a" folder clipnum (nth (1- clipnum) clipnames) suffix))
	  (setf name (format nil "~a~a-~a~a" folder prefix clipnum suffix))
	  )
  (incf clipnum)
  name)


(defun clipcount (clipdata tracknum)
  ;;; Return number of clips in specified track
  (setf trackcount 0)
  (sort clipdata (lambda (a b) (< (second (assoc 'start a)) (second (assoc 'start b)))))
  (dolist (clip clipdata trackcount)
    (when (= (second (assoc 'track clip)) tracknum)
	  (setf clipnames (append clipnames (list (second (assoc 'name clip)))))
	  (incf trackcount))))


(defun export-clips (target clipcount channels)
  ; Navigate down to target track.
  (aud-do (format nil "SelectTracks: Track=~a TrackCount=1 Mode=Set"
                  target))
  ; Move cursor to track start
  (aud-do "CursTrackStart:")

  (dotimes (i clipcount)
    (aud-do "SelNextClip")
    (aud-do (format nil "Export2: Filename=~s NumChannels=~a"
                    (new-file-name) channels))))


; Go to first track
(aud-do "SelectTracks: Track=0 TrackCount=1 Mode=Set")

(let ((tracks (aud-get-info "Tracks"))
      (clipdata (aud-get-info "Clips"))
      (idx 0))
  ;; Loop through tracks and call export-clips
  (dolist (track tracks)
    (when (string= (second (assoc 'kind track)) "wave")
      (setf clipcount (clipcount clipdata idx))
      (setf channels (second (assoc 'channels track)))
      (export-clips idx clipcount channels))
    (incf idx))
    "")
