// ARPEGGIATOR

unsigned char arpb[16];//Arp buffer
unsigned char arp_step=0;//Arp position
unsigned char arp_n=0;//Arp notes number
unsigned char arp_tik=0;//Seq position (ppqn)
unsigned char last_arp=0;//Arp notes number
unsigned char arp_dir=0;//Arp direction (0->up ; 1->dwn)



void ARP(void){//(6 calls per notes, or 24 per step)

	MIOS_LCD_CursorSet(0xc0); // upper right
	MIOS_LCD_PrintCString("ARP");

	if(arp_n==0){//dont play when buffer is empty
		arp_step=0;
		MIOS_LCD_PrintCString(" STOP");
		if(last_arp>0){// DO SILENCE
			MIOS_MIDI_TxBufferPut(144 + midi_channel);//Note on
			MIOS_MIDI_TxBufferPut(last_arp);
			MIOS_MIDI_TxBufferPut(0x00);//velocity
			last_arp=0;
		}		
		return;
	}

	arp_tik++;
	if(arp_tik>=3){// play speeds : 1/3/6/12)
		arp_tik=0;
		//MIOS_LCD_PrintBCD3(arpb[arp_step]);//note num
		if(last_arp>0){
			// DO SILENCE
			MIOS_MIDI_TxBufferPut(144 + midi_channel);//Note on
			MIOS_MIDI_TxBufferPut(last_arp);
			MIOS_MIDI_TxBufferPut(0x00);//velocity
			last_arp=0;
		}

		if(arpb[arp_step]>0){
			// PLAY NOTE
			MIOS_LCD_PrintBCD3(arpb[arp_step]);//note num
			MIOS_MIDI_TxBufferPut(144 + midi_channel);//Note on
			MIOS_MIDI_TxBufferPut(arpb[arp_step]);
			MIOS_MIDI_TxBufferPut(0x7f);//velocity
			last_arp=arpb[arp_step];//mem last played
		}
		
		if(arp_step>=arp_n-1){//Change direction (up/dwn)
			arp_dir=1;//dwn
			//arp_step=0;
		}

		if(arp_step<1){//Change direction (up/dwn)
			arp_dir=0;//up
		}
		
		if(arp_dir==0){arp_step++;}else{arp_step--;}


		//LedDisp();//Display pos with leds
		//MIOS_DOUT_SRSet(1,led_pos[step][0]);
		//MIOS_DOUT_SRSet(2,led_pos[step][1]);

/*
		if(arp_step>=arp_n){//Change direction (up/dwn)
			//arp_dir=1;//dwn
			arp_step=0;
		}
*/	
	}
	return;
}






// ADD NOTE TO ARPEGGIO //
void add_arp(void){//Add note to arpegge
	
	//on ajoute la note note_map[last_mx_pin][0]+transpose
	unsigned char tmp;
	unsigned char num=note_map[last_mx_pin][0]+transpose;
	unsigned char test;
	if(note_map[last_mx_pin][0]==0x80){//NULL NOTE
		return;//Do not send stupid datas !
	}

	arpb[arp_n]=num;//add
	test=arp_n;
	arp_n++;
	if(arp_n<=1)return;

	while(test>=1){
		if(arpb[test]<arpb[test-1]){//swap
			tmp=arpb[test-1];
			arpb[test-1]=arpb[test];
			arpb[test]=tmp;
		}
		test--;
	}
	return;
}



//REM NOTE FROM ARPEGGIO
void rem_arp(void){//Rem note to arpegge
	unsigned char i;
	if(note_map[last_mx_pin][0]==0x80){//NULL NOTE
		return;//Do not send stupid datas !
	}

	//for(i=0;i<15;i++){
	for(i=0;i<arp_n;i++){
		//do nothing
		if(arpb[i]>=note_map[last_mx_pin][0]+transpose){
			arpb[i]=arpb[i+1];
		}

	}
	arp_n--;
	return;
}

