Bug fixes and improvements
Big refactoring and bug fixes