Code cleanup

Reorganised code and made a few minor changes