Improved code based on feedback from Felix