rewritten to improve performance