Minimize stat calls

Minimize stat calls. Also a few refactorings.