Removed naive algorithm and cleaned up the code a bit.