algorithm fixed; code cleanup