Big function, move this to cpp