public static String escapeArgument(String argument) {
        logger.trace("Escaping argument: " + argument);
        String result = argument;

        if (result.contains("\"")) {
            Matcher matcher = escapePattern.matcher(result);
            int longestFound = 0;
            while (matcher.find())
                if (matcher.group(1) != null)
                    longestFound = max(longestFound, matcher.group(1).length());

            for (int i = longestFound; i >= 0; i--) {
                int replacementSize = (i + 1) * 2 - 1;
                String original = repeat("\\", i) + "\"";
                String replacement = repeat("\\", replacementSize) + quoteReplacement;
                result = result.replace(original, replacement);
            }
            result = result.replace(quoteReplacement, "\"");
        }

        logger.detailedTrace("Escaped argument: " + argument);
        return result;
    }