Refactoring, removal of duplicate code and added comments.
(The three patches from issue 1589)

Thanks Alberth.