initial code from the internal repo. all code credit to Jan Møller