simplified the logic here, removed some comments