Modified part 1 to make it more modular by breaking things into separate functions
Not done fixing it up yet, not yet tested.