Code

Second patch from issue2550688 -- with some changes: