#include <dom/dom.h>
 #include <dom/bindings/xml/xmlparser.h>
 
+#include <libcss/libcss.h>
+
 #include "svgtiny.h"
 #include "svgtiny_internal.h"
 
                       int viewport_height)
 {
        float x, y, width, height;
+       css_error css_code;
 
+       /* initialize the state struct with zeros */
        memset(state, 0, sizeof(*state));
 
        state->diagram = diagram;
        state->fill = 0x000000;
        state->stroke = svgtiny_TRANSPARENT;
        state->stroke_width = 1;
+
+       /* Initialize the CSS context */
+       css_code = css_select_ctx_create(&state->select_ctx);
+       if (css_code != CSS_OK) {
+               dom_node_unref(svg);
+               dom_node_unref(document);
+               return svgtiny_LIBCSS_ERROR;
+       }
+
        return svgtiny_OK;
 }
 
 
 static svgtiny_code finalise_parse_state(struct svgtiny_parse_state *state)
 {
+       css_error css_code;
        svgtiny_cleanup_state_local(state);
 
 #define SVGTINY_STRING_ACTION2(s,n)                            \
                dom_string_unref(state->interned_##s);
 #include "svgtiny_strings.h"
 #undef SVGTINY_STRING_ACTION2
+
+       css_code = css_select_ctx_destroy(state->select_ctx);
+       if (css_code != CSS_OK) {
+               return svgtiny_LIBCSS_ERROR;
+       }
+
        return svgtiny_OK;
 }