Separated some functions from the EM file so they can be used more freely.