Updated to make it more a general solution