Cleaned up the code and made the patch smaller