Moved common code to new file

And did some clean up.