final sampling code, w/ bug fix