copy of cs-wd.js implementation by zac everett and Rick