Fixed bugs, and made code more efficient