Ported most of the code from Ruby