optimizing algorithm
almost finished