Major refactoring and error fixing