static int
rasqal_graph_rowsource_init(rasqal_rowsource* rowsource, void *user_data)
{
  rasqal_graph_rowsource_context *con;
  raptor_sequence* seq;

  con = (rasqal_graph_rowsource_context*)user_data;
  
  seq = rasqal_query_get_data_graph_sequence(rowsource->query);
  if(!seq)
    return 1;

  con->dg_size = raptor_sequence_size(seq);
  
  con->finished = 0;
  con->dg_offset = -1;
  con->offset = 0;

  /* Do not care if finished at this stage (it is not an
   * error). rasqal_graph_rowsource_read_row() will deal with
   * returning NULL for an empty result.
   */
  rasqal_graph_next_dg(con);

  return 0;
}
static rasqal_row*
rasqal_graph_rowsource_read_row(rasqal_rowsource* rowsource, void *user_data)
{
  rasqal_graph_rowsource_context *con;
  rasqal_row* row = NULL;

  con = (rasqal_graph_rowsource_context*)user_data;

  if(con->finished)
    return NULL;
  
  while(1) {
    row = rasqal_rowsource_read_row(con->rowsource);
    if(row)
      break;
    
    if(rasqal_graph_next_dg(con)) {
      con->finished = 1;
      break;
    }
    if(rasqal_rowsource_reset(con->rowsource)) {
      con->finished = 1;
      break;
    }
  }

  /* If a row is returned, put the GRAPH variable value as first literal */
  if(row) {
    rasqal_row* nrow;
    int i;
    
    nrow = rasqal_new_row_for_size(rowsource->world, 1 + row->size);
    if(!nrow) {
      rasqal_free_row(row);
      row = NULL;
    } else {
      nrow->rowsource = rowsource;
      nrow->offset = row->offset;
      
      /* Put GRAPH variable value (or NULL) first in result row */
      nrow->values[0] = rasqal_new_literal_from_literal(con->var->value);

      /* Copy (size-1) remaining variables from input row */
      for(i = 0; i < row->size; i++)
        nrow->values[i + 1] = rasqal_new_literal_from_literal(row->values[i]);
      rasqal_free_row(row);
      row = nrow;
    }
  }
  
  return row;
}
static int
rasqal_graph_rowsource_reset(rasqal_rowsource* rowsource, void *user_data)
{
  rasqal_graph_rowsource_context *con;
  con = (rasqal_graph_rowsource_context*)user_data;

  con->finished = 0;
  con->dg_offset = -1;
  con->offset = 0;

  rasqal_graph_next_dg(con);
  
  return rasqal_rowsource_reset(con->rowsource);
}