Rewrite to have make the code more modular