refactor inner loops into smaller functions ***slower due to numpy array passed to function as arg, need to optimize***