Add support for automatic sorting. Fix visibility bugs.