refactor code - M and J updates, starts main algo