Outputs correct result, need refactoring for readability and currently doesn't write the result out to a file in correct format