Move this part to another function? apply is getting large