refactor, im most have introduced a bug here but it seems to still work