Fixing a bug with grep and refactoring some functions