Refactored and minor tweaks.