// Script:         audioTrigger.ltgs 
// Description:    Script used to trigger a recording from an audio signal threshold
// Arguments: 
//		1: track
//		2: threshold (absolute value)
//		3: ltgType: (optional) shortcut, shortcutById or LoadScript
//		4: ltgAction (optional but mandatory if arg 3 is provided): shortcutName, shortcutId or scriptFileName depending of arg3
//		5: ltgParameters (optional) : parameters to script if loadScript is provided as arg3
// Author : LoopToGo 
 
if $nbArgs < 2
	endScriptDynamic
endIf

if $nbArgs > 2	
	variable ltgType $arg3
	variable ltgAction $arg4
	variable ltgParameters $arg5	
endIf

// Kill last script instance if any
killScript $g_lastScriptAudioTriggerInstanceID
globalVariable g_lastScriptAudioTriggerInstanceID $scriptID

globalVariable isArmedForRecording 0

variable track $arg1
variable trackName trackName & $arg1
variable threshold $arg2

shortcutByID 23 // Reset all meters

variable volumeMax 

if $isPlaying + $isRecording
	globalVariable g_armScriptMessage "Failed!"
	endScriptDynamic
endIf


globalVariable g_armScriptMessage  "Track " & $track & " is armed"

armRecord	 // Will set the $isArmedForRecording system variable to 1 and will make sure to record midi event occuring before the preRecord Time 

variable waitForAudioTrigger 1

while $waitForAudioTrigger

	variable trackPeakLevel trackPeakLevel & $track
		
	if $$trackPeakLevel > $threshold
		variable waitForAudioTrigger 0
	else	
		waitDeltaTime 1
	endIf	

endWhile

if $ltgType = "loadScript"
	// Important: we use @ltgParameters instead of $ltgParameters to split spaces-separated arguments!
	loadScriptDynamic $ltgAction @ltgParameters
else
	if $ltgType = "shortcut"
		shortcut $ltgAction
	else
		if $ltgType = "shortcutByID"
			shortcutByID $ltgAction
		else
			shortcutByID 39 // Record
		endIf
	endIf
endIf

globalVariable g_armScriptMessage  "Recording"

waitForSongStop // Logically, this should apply to all actions!!!!

globalVariable g_armScriptMessage  "Audio Trigger"

	



