updated based on a bit different algorithm