Major rewrite inspired by Riley