Refactoring, fixes and real tests