fixed some logic bugs and added new unit tests
Merge remote-tracking branch 'origin/master'