This and following four lines are really complicated and not easy to understand at all. Are you sure it cannot be done simpler?