backported some changes to fix #4 from whummer repo.
merged changes from whummer repo
merged changes from whummer repo