Update code to fix errors and make more effecient