function rewritten to run faster