Cleaned up code and made stability improvements