this function has become very large, and is difficult to follow: any easy way of separating the ensemble part or something similar?