Refractored code and fixed a few minor errors