Reorganized the code and added a main flow