Trying to fix broken algorithm