Fully working code with edgecases addressed