Reorganized the code a bit