Refactored code; fixed some errors