Cleaned up the code considerably