a much faster version (albeit a little rough around the edges)