Code improvements and fix for #1721