Refactoring, optimization, fixes and improvements