modified to have shorter inner loop and use scipy instead of numpy