Fix bug and added unit tests