changed algorithm based on latest github version.
i should probably embedding the GitHub code as this is becoming tedious.