class HeaderHelper {

    public static NewCookie parseNewCookie(String newCookieString) {
        int p = 0;
        int n = findCookieParameterSeparator(newCookieString, p);
        int separator = -1;
        if (n > 0 && n < newCookieString.length()) {
            separator = newCookieString.charAt(n);
        }
        NewCookieBuilder newCookieBuilder = null;

        while (p < newCookieString.length()) {

            String pair = newCookieString.substring(p, n);

            String name;
            String value = "";

            int eq = scan(pair, '=');
            if (charAtIs(pair, eq, '=')) {
                name = pair.substring(0, eq).trim();
                value = pair.substring(eq + 1).trim();
                if (value.length() > 1 && value.startsWith("\"") && value.endsWith("\"")) {
                    value = value.substring(1, value.length() - 1);
                }
            } else {
                name = pair.trim();
            }

            if (newCookieBuilder == null) {
                newCookieBuilder = aNewCookie().withName(name).withValue(value).withVersion(Cookie.DEFAULT_VERSION);
            } else {
                if (name.equalsIgnoreCase("version")) {
                    newCookieBuilder.withVersion(Integer.parseInt(value));
                } else if (name.equalsIgnoreCase("domain")) {
                    newCookieBuilder.withDomain(value);
                } else if (name.equalsIgnoreCase("path")) {
                    newCookieBuilder.withPath(value);
                } else if (name.equalsIgnoreCase("secure")) {
                    newCookieBuilder.withSecure(true);
                } else if (name.equalsIgnoreCase("HttpOnly")) {
                    newCookieBuilder.withHttpOnly(true);
                } else if (name.equalsIgnoreCase("Max-Age")) {
                    newCookieBuilder.withMaxAge(Integer.parseInt(value));
                } else if (name.equalsIgnoreCase("expires")) {
                    try {
                        newCookieBuilder.withExpiry(parseDateHeader(value));
                    } catch (IllegalArgumentException ignored) {
                        ignored.printStackTrace();
                    }
                } else if (name.equalsIgnoreCase("comment")) {
                    newCookieBuilder.withComment(value);
                }
            }
            if (separator == -1) {
                break;
            }
            p = n + 1;
            n = scan(newCookieString, p, (char)separator);
        }

        if (newCookieBuilder == null) {
            return null;
        }
        return newCookieBuilder.build();
    }

    private  HeaderHelper();

}