Flattened the code, more functions and modular.