refactored code into functions. Workng a little better than non-factored form, but still a lot of bugs