Fixed bugs handling several corner cases