while the code works, it is hard to read at first sight. compressing all of it into smaller functions should do the trick.