Improved code following Chris' comments