Many fixes and refactor