Fixed MDL-40225
and added some tests which covers new functionalit.