Pretty large refactoring, cleaning up the source helps. Fixes a few issues too