Fixed several bugs

This is instead of previous incorrect pull request

Here is working reduction. 

Actually, we should also append commit f11b688521740bf41c3bd7f4a4d80bde68d2d022 to this branch, but I commited it into another branch, and now it is merged everywhere