Fixed all potential bugs as pointed out by Brinkman's comments