public static function getSafeFileName($fileName, $directory = null) {
        $lastDot = strrpos($fileName, '.');
        $file = $lastDot ? substr($fileName, 0, $lastDot) : $fileName;
        $ending = $lastDot ? substr($fileName, $lastDot+1) : '';
        $safeName = self::removeSpecChars($file);
        $safeEnding = empty($ending)
            ? ''
            : '.'.self::removeSpecChars($ending);
        
        if ($directory != null && file_exists($directory.$safeName.$safeEnding)) {
            $count = 1;
            while (file_exists($directory.$safeName.'_'.$count.$safeEnding)) {
                $count++;
            }
            $safeName = $safeName.'_'.$count;
        } 
        
        return $safeName.$safeEnding;
    }