re-adding changes made to fix bug#6400, includes fixes for bug#8222 and bug#8223 that were introduced with the initial commit of this code.
original pull request was #3868
re-adding changes made to fix bug#6400, includes fixes for bug#8222 and bug#8223 that were introduced with the initial commit of this code.
original pull request was #3868