Cleaned up and made code reusable