Some bugs fixed and huge refactoring