Refactored more and fixed some minor bugs with reference errors