added some safety measures and reduced some code