Added some error checking and optimization