Improved code somewhat