Big rewrite of midi code