class HeaderHelper {

    public static List<Cookie> parseCookies(String cookiesString) {
        final List<Cookie> cookies = new ArrayList<>();

        int p = 0;
        int n;
        CookieBuilder cookieBuilder = null;
        int version = Cookie.DEFAULT_VERSION;

        while (p < cookiesString.length()) {
            n = findCookieParameterSeparator(cookiesString, p);

            String pair = cookiesString.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();
            }

            // Name of parameter not start from '$', then it is cookie name and value.
            // In header string name/value pair (name without '$') SHOULD be before
            // '$Path' and '$Domain' parameters, but '$Version' goes before name/value pair.
            if (doesNotContain(name, '$')) {
                if (cookieBuilder != null) {
                    cookies.add(cookieBuilder.build());
                }
                cookieBuilder = aCookie().withName(name).withValue(value);
                // version was kept before http://www.ietf.org/rfc/rfc2109.txt section 4.4
                cookieBuilder.withVersion(version);
            } else if ("$Version".equalsIgnoreCase(name)) {
                version = Integer.valueOf(value);
            } else if (cookieBuilder != null && "$Path".equalsIgnoreCase(name)) {
                cookieBuilder.withPath(value);
            } else if (cookieBuilder != null && "$Domain".equalsIgnoreCase(name)) {
                cookieBuilder.withDomain(value);
            }

            p = n + 1;
        }

        if (cookieBuilder != null) {
            cookies.add(cookieBuilder.build());
        }

        return cookies;
    }

    private  HeaderHelper();

}