Major refactoring of logic to be easier to maintain and more memory efficient
Refactoring and enhancements for memory usage