major refactor for modularity and proper scoping