Removed repeated code and simplified loops.

Signed-off-by: Lucas Arnström <lucasarnstrom@gmail.com>