Improved and extended the code.