port of a lot of code