major refactoring on all functions and control flow