fixed up a lot of algorithms and bugs for easier refactoring if needed later