re-integrated with some changes from paulmillr