full rewrite to better performance