Finalized code with bugs fixed