Fix segfault on friend id copy, refactor some code