Applied Manik's pull request (with some changes)