Fix stability issues and clean up code.