Fixed issue with finding the end. Also added code for trials.