Fixed issues #5730 #6076 and probably more

Fixes the issues #5730 #6076 and probably more issues related with this.