Almost complete rewrite for better performance