ported ivan's code to a function, for sane integration