Implemented all Nipun's ideas suggested in comments to commit 74df4ac