  */
 byte getFreeChannel(byte midiChannel) {  
 	byte opl2Channel = 255;
-
-	// Look for a free OPL2 channel.
+	byte oldestIndex = 0;
+
+	// Look for a free OPL2 channel starting with the oldest.
 	for (byte i = 0; i < OPL2_NUM_CHANNELS; i ++) {
-		if (!opl2.getKeyOn(i)) {
-			opl2Channel = i;
+		if (!opl2.getKeyOn(oldestChannel[i])) {
+			opl2Channel = oldestChannel[i];
+			oldestIndex = i;
 			break;
 		}
 	}

		for (byte i = 0; i < OPL2_NUM_CHANNELS; i ++) {
			if (channelMap[oldestChannel[i]].midiChannel == MIDI_DRUM_CHANNEL) {
				opl2Channel = oldestChannel[i];
			}
		}
	}

	// Update the list of last used channels by moving the current channel to the bottom so the last updated channel
	// will move to the front of the list. If no more OPL2 channels are free then the last updated one will be recycled.
	byte i;
	for (i = 0; i < OPL2_NUM_CHANNELS && oldestChannel[i] != opl2Channel; i ++) {}

	while (i < OPL2_NUM_CHANNELS - 1) {
		byte temp = oldestChannel[i + 1];
		oldestChannel[i + 1] = oldestChannel[i];
		oldestChannel[i] = temp;
		i ++;
	}

	return opl2Channel;
}


#include <SPI.h>
#include <OPL2.h>
#include <midi_instruments.h>
#include <midi_drums.h>

