Mostly done with the port, untested of course

Man there's lots of magic math in there