Fix a bug and add some tests