Major refactoring into functions