Split the algorithm out into a function that takes an input and output image

This separates the algorithm from reading and writing of files by the
standalone program.
Removed trailing whitespace