completed function, adapted from k.cole.R