New version of patch with a little more refactoring and comments.
------With best regards,Alexander Korotkov.