working and beautified version