Most of the logic is here