Refactoring fs.c, moving common parts to a shared generic function