Here is the first full working version of the code for your study