All of Sam's code added with more adjustments