Redid the logic according to comments