Modified for my own readability and attempts to understand how the program works