Make more functional

Use reduce instead of loops