moved calculations out of innermost loop