Cleanup, small optimizations, and implementation of corner-case details