Moved code around a bit to simplify.