/*******************************************************************************
*  Copyright 2012, Jeffos                                                      *
*  This program is free software: you can redistribute it and/or modify        *
*  it under the terms of the GNU General Public License as published by        *
*  the Free Software Foundation, either version 3 of the License, or           *
*  (at your option) any later version.                                         *
*******************************************************************************/

desc: S&M - MIDI Bus Router

slider1:0<0,16,1{All,B1,B2,B3,B4,B5,B6,B7,B8,B9,B10,B11,B12,B13,B14,B15,B16}>Input Bus
slider2:0<0,16,1{All,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}>Input Channel
slider3:0<0,16,1{Source,B1,B2,B3,B4,B5,B6,B7,B8,B9,B10,B11,B12,B13,B14,B15,B16}>Output Bus
slider4:0<0,16,1{Source,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}>Output Channel
slider5:1<0,15,1{Filter,Pass-through}>Routed source events

@init
ext_midi_bus = 1;

@slider
inBus = slider1;
inChannel = slider2;
outBus = slider3;
outChannel = slider4;
passThru = slider5;

@block
while (
  midirecv(offset, msg1, msg23) ? (
    mapped = 0;
    status = msg1 & $xF0;
    channel = msg1 & $x0F;
    (!inBus || midi_bus == (inBus-1)) ? (
      (!inChannel || channel == (inChannel-1)) ? (
        mapped = (inChannel!=0 || inBus!=0);
        (mapped && passThru) ? midisend(offset, msg1, msg23); // send original
        midi_bus = (outBus ? outbus-1 : midi_bus);
        msg1 = status + (outChannel ? outChannel-1 : channel);
      );
    );
    midisend(offset, msg1, msg23);
    1;
  );
);