Fixing bug in sanitizing filenames

Adapting code from a stackoverflow answer to sanitize filenames.