Updated with optimizations.