Almost straight translation from ruby