fix bug and add unit tests