Refactors some stuff at @benizi's suggestion