abstracted functions used with fapply. lots of minor changes