major refactor and bug fixes