Rewrite stuff from Vipul in order to improve maintainability