Reorganise code and be slightly less hacky