Fix bugs, add docs and tests