Added sphinx documentation, because why not. Moved a lot of the main loop into functions to make it less ugly. Added some doc strings