// Script to use pad Leds to show tempo on a Arturia Keylab mkII 
// Arguments:  
//		$arg1 : 1 to always run, none or 0 to stop with song
//
// Author: LoopToGo
//
// Description  : 	Will flash one led at each tick and 2 of them at an exact bar. (LED1 and LED5 are always flash together)
//					Two other Leds at the other ticks	
//					IMPORTANT: The keyboard must be in USER mode
//					To be used with ScriptMarker

loadScript ..\..\aliases.txt

// Note value of Leds

variable LED1	36 
variable LED2	38 
variable LED3	42 
variable LED4	46 
variable LED5	41 
variable LED6	43 
variable LED7	45 
variable LED8	47 
variable LED9	48 
variable LED10	49 
variable LED11	51 
variable LED12	57 
variable LED13	37 
variable LED14	39 
variable LED15	40 
variable LED16	44 


while $arg1 + $isPlaying + $isRecording

	variable bar $songBar 
	variable barQ $bar 1	// Quantization to the bar

	variable remaining	$bar - $barQ
		
	for n 1 $topNumber		
									
		if $remaining > $n/$topNumber - 1/$topNumber
							
			if $remaining < $n/$topNumber 
				
					variable ledState&$n ON
					
			else

					variable ledState&$n OFF

			endIf
			
		else
					variable ledState&$n OFF

		endIf
			

	endFor	
	
	for n 1 $topNumber
	
		variable state	ledState&$n
		variable lastState	lastLedState&$n
	
		ifNot $$state = $$lastState
						
			variable led LED&$n
			variable end $n + $topNumber
			
			if $$state = ON
				sendMidiNoteOn Pads $$led 20
				if $n = 1
					sendMidiNoteOn Pads $LED5 20  // We turn on 2 leds on first tick
				endIf
			else
				sendMidiNoteOff Pads $$led
				if $n = 1
					sendMidiNoteOff Pads $LED5  // We turn on 2 leds on first tick
				endIf
			endIf
					
			variable $lastState $$state
		endIf
	endFor
	
	
	waitDelta .01
				
					
	waitDelta .001 // Very important to have at least 1 wait in the while so the script is non blocking!
endWhile

// Turn off the leds 
for n 1 $topNumber + 1						
	sendMidiNoteOff Pads $note - 1 + $n
endFor
		
