Update #7: I'm not happy with this anymore :(

Just a few changes I had to make that make the code a bit redundant and slightly more readable.