Copied code from old repo 1.5 branch, tweaked