moved code from adapy