Refactor to avoid for loops. Documentation added