Some cleanup + reusable function. Still needs finetuning