fixed and renamed and divided into functions -MM