Fix select bug, add tests, refactor

[#sixth]