improved the logic