Added most important logic (not tested yet)