Fixing issue #189 from Simon Sokolov
Aligned with pull request #390, for better performances