condensed slightly, about to rewrite