Cleaned up code and added a function