Complete rewrite to be more functional