finalized version of the code