DatasetReference StaticGeometryHandler::load_dataset(const Filename &src) {

    // TODO: Check for duplicates
    // for (DatasetList::const_iterator iter = _datasets.cbegin(); iter != _datasets.cend(); ++iter) {
    // }

    ifstream infile(src.get_fullpath(), ios::in | ios::binary | ios::ate);

    if (!infile.is_open()) {
        cout << "ERROR: Could not open " << src.get_fullpath() << "!" << endl;
        return -1;
    }

    // Extract filesize and reset filepointer afterwards
    size_t fsize = infile.tellg();
    infile.seekg(0, ios::beg);

    // Read file content
    char *data = new char[fsize];
    infile.read(data, fsize);

    // Construct datagram and an iterator from file content
    Datagram dg(data, fsize);
    DatagramIterator dgi(dg);

    // For now we assume the file is structured correctly, and the header is
    // correct aswell
    string header = dgi.get_fixed_string(4);
    size_t tri_group_size = dgi.get_uint32();

    if (tri_group_size != SG_TRI_GROUP_SIZE) {
        cout << "ERROR: The rpsg file uses a tri-group size of " << tri_group_size << ", but expected"
            << " a size of "<< SG_TRI_GROUP_SIZE << endl;
        cout << "Please regenerate the file!" << endl;
        delete [] data;
        return -1;    
    } 

    size_t num_strips = dgi.get_uint32();

    if (num_strips >= SG_MAX_DATASET_STRIPS) {
        cout << "ERROR! Dataset exceeds maximum amount of " << SG_MAX_DATASET_STRIPS << " strips (has " << num_strips << ")!" << endl;
        delete [] data;
        return -1;
    }

    SGDataset *dataset = new SGDataset();
    dataset->read_bounds(dgi);

    // Read in all strips and store them
    PTA_uchar dataset_handle = _dataset_tex->modify_ram_image();
    for (size_t i = 0; i < num_strips; ++i) {
        SGTriangleStrip* strip = new  SGTriangleStrip();
        strip->load_from_datagram(dgi);
        strip->write_to(dataset_handle, _dataset_index++);
        dataset->attach_strip(strip);
    }

    PTA_uchar mapping_handle = _mapping_tex->modify_ram_image();

    dataset->write_mappings(mapping_handle, _datasets.size());

    if (dgi.get_remaining_size() != 0) {
        cout << "Corrupt RPSG file! " << dgi.get_remaining_size() << " bytes left!" << endl;
    }

    // Write out debug textures?
    // _dataset_tex->write("dataset.png");
    // _mapping_tex->write("mappings.png");

    // Attach dataset, clean up the variables, and finally return a handle to the dataset
    _datasets.push_back(dataset);
    delete [] data;

    return _datasets.size() - 1;
}