Finally a working version. Pretty ugly though.