Code improvements

See merge comments for details.