Minimize stat calls. Also a few refactorings.