Major code refactoring

cleaning up the internals