Reorganized code to be more modular, some tweaks