Most of the logic done