Added error checking and split into two phases