Final tested and working version of the code.