Wrap most of the logic in a closure

Signed-off-by: Cody Massin <keyosk@gmail.com>