Add tests and  final bug fixes