Final Code, includes MIToolbox by Adam Pocock