Final copy of code. It works :D