Cleaned up code and improved modularization