code quality improvements, fix bugs introduced by PR, fix tests