merged functons copied from cs-wd.js implementatiob by zac everett and Rick C