Updated the code to run inside an EM loop