+ uchar *node = ReadBlock (node_num);
+ BTreeNodeHeader node_header;
+ ReadNodoHeader (node, &node_header);
+
+ if (node_header.free_space > data->Size ()) {
+ BTreeData *datait;
+ node_keys = ReadKeys (node, node_header);
+ std::list<BTreeData *>::iterator it = node_keys.begin ();
+
+ while (it != node_keys.end ()) {
+ datait = (*it);
+ if ((*data) < (*datait))
+ /* Me pase, lo agrego aca! */
+ break;
+ it++;
+ }
+ node_keys.insert (it, data);
+ WriteKeys (node, node_header, node_keys);
+ WriteNodoHeader (node, &node_header);
+ WriteBlock (node, node_num);
+ DeleteKeys (node_keys);
+ delete [] node;
+
+ PrintNode (node_num);
+ } else {
+ /* Split : Creo e inicializo el nuevo nodo */
+ std::list<BTreeData *> new_node_keys;
+ std::list<BTreeData *> old_node_keys;
+ BTreeNodeHeader new_node_header;
+ uint new_node_num;
+ uchar *new_node = NewBlock (new_node_num);
+ ReadNodoHeader (new_node, &new_node_header);
+ new_node_header.level = node_header.level;
+
+ node_keys = ReadKeys (node, node_header);
+ new_node_keys = ReadKeys (new_node, new_node_header);
+
+ /* Agrego la clave en la lista que ya tengo de manera ordenada */
+ std::list<BTreeData *>::iterator it = node_keys.begin ();
+ std::list<BTreeData *>::iterator previt = node_keys.begin ();
+
+ while (it != node_keys.end ()) {
+ BTreeData *datait;
+ datait = (*it);
+ if ((*data) < (*datait))
+ /* Me pase, lo agrego aca! */
+ break;
+ previt = it;
+ it++;
+ }
+ if (it != node_keys.end ())
+ node_keys.insert (it, data);
+ else
+ node_keys.push_back (data);
+
+ /* Tengo que guardar claves hasta ocupar nodo size/2 en cada nodo
+ * y subir la clave del medio */
+ node_header.item_count = 0;
+ node_header.free_space = header.block_size - sizeof (BTreeNodeHeader);
+
+ uint total_size = 0;
+ it = node_keys.begin ();
+ while (it != node_keys.end ()) {
+ BTreeData *datait;
+ datait = (*it);
+ total_size += datait->Size ();
+ it++;
+ /* Hack : Si me quedo con todas las claves, en el caso de ser
+ * del mismo tama#o se desbalancea. Hay que ver que efecto
+ * puede tener en el caso de claves de long. variable
+ */
+ if (it == node_keys.end ())
+ total_size -= datait->Size ();
+ }
+
+ it = node_keys.begin ();
+ uint used = 0;
+ while (used < total_size/2) {
+ BTreeData *d = (*it);
+ old_node_keys.push_back (d);
+ used += d->Size ();
+ it++;
+ }
+ kout = (*it++)->getClave (); // Esta se retorna al "padre" para que se la agregue
+
+ while (it != node_keys.end ()) {
+ BTreeData *d = (*it);
+ new_node_keys.push_back (d);
+ it++;
+ }
+
+ /* Guardo */
+ WriteKeys (node, node_header, old_node_keys);
+ WriteNodoHeader (node, &node_header);
+ WriteBlock (node, node_num);
+ WriteKeys (new_node, new_node_header, new_node_keys);
+ WriteNodoHeader (new_node, &new_node_header);
+ WriteBlock (new_node, new_node_num);
+ DeleteKeys (old_node_keys);
+ DeleteKeys (new_node_keys);
+
+ PrintNode (node_num);
+ PrintNode (new_node_num);
+
+ /* Paso los hijos */
+ left_child = node_num;
+ right_child = new_node_num;
+ delete [] new_node;
+ delete [] node;
+ }
+
+ return kout;
+}
+
+Clave* BTree::AddKeyOtherR (const Clave *k, uint node_num, uint &left_child, uint &right_child)
+{
+ Clave *kout = NULL;
+ std::list<BTreeData *> node_keys;
+
+ BTreeData *data = new BTreeLeafData (k->Clone ());
+
+ /* Leo el nodo raiz para empezar a agregar */
+ uchar *node = ReadBlock (node_num);
+ BTreeNodeHeader node_header;
+ ReadNodoHeader (node, &node_header);
+
+ node_keys = ReadKeys (node, node_header);
+
+ std::list<BTreeData *>::iterator it = node_keys.begin ();
+ std::list<BTreeData *>::iterator posterior;
+ std::list<BTreeData *>::iterator ultima;
+
+ /* Se supone que la primera es un hijo :) */
+ BTreeData *lchild = (*it++);
+ posterior = it;
+
+ while (it != node_keys.end ()) {
+ if ((*data) < (*(*it)))
+ break;
+ ultima = it;
+ it++;
+ }
+
+ if (it == posterior) {
+ k = AddKeyR (k, lchild->getChild (), left_child, right_child);
+ } else {
+ k = AddKeyR (k, (*ultima)->getChild (), left_child, right_child);
+ }
+ DeleteKeys (node_keys);
+
+ /* Nada que hacer */
+ if (data) delete data;
+ if (!k) {
+ delete [] node;
+ return NULL;
+ }
+
+ data = new BTreeData (k->Clone (), right_child);
+
+ if (node_header.free_space > data->Size ()) {
+ BTreeData *datait;
+ node_keys = ReadKeys (node, node_header);
+ std::list<BTreeData *>::iterator it = node_keys.begin ();
+
+ while (it != node_keys.end ()) {
+ datait = (*it);
+ if ((*data) < (*datait))
+ /* Me pase, lo agrego aca! */
+ break;
+ it++;
+ }
+ node_keys.insert (it, data);
+ WriteKeys (node, node_header, node_keys);
+ WriteNodoHeader (node, &node_header);
+ WriteBlock (node, node_num);
+ DeleteKeys (node_keys);
+ delete [] node;
+
+ PrintNode (node_num);
+ } else {
+ /* Split : Creo e inicializo el nuevo nodo */
+ std::list<BTreeData *> new_node_keys;
+ std::list<BTreeData *> old_node_keys;
+ BTreeNodeHeader new_node_header;
+ uint new_node_num;
+ uchar *new_node = NewBlock (new_node_num);
+ ReadNodoHeader (new_node, &new_node_header);
+ new_node_header.level = node_header.level;
+
+ node_keys = ReadKeys (node, node_header);
+ new_node_keys = ReadKeys (new_node, new_node_header);
+
+ /* Agrego la clave en la lista que ya tengo de manera ordenada */
+ std::list<BTreeData *>::iterator it = node_keys.begin ();
+ std::list<BTreeData *>::iterator previt = node_keys.begin ();
+
+ previt = ++it;
+
+ while (it != node_keys.end ()) {
+ BTreeData *datait;
+ datait = (*it);
+ if ((*data) < (*datait))
+ /* Me pase, lo agrego aca! */
+ break;
+ previt = it;
+ it++;
+ }
+ if (it != node_keys.end ())
+ node_keys.insert (it, data);
+ else
+ node_keys.push_back (data);
+
+ /* Tengo que guardar claves hasta ocupar nodo size/2 en cada nodo
+ * y subir la clave del medio */
+ node_header.item_count = 0;
+ node_header.free_space = header.block_size - sizeof (BTreeNodeHeader);
+
+ uint total_size = 0;
+ it = node_keys.begin ();
+ while (it != node_keys.end ()) {
+ BTreeData *datait;
+ datait = (*it);
+ total_size += datait->Size ();
+ it++;
+ /* Hack : Si me quedo con todas las claves, en el caso de ser
+ * del mismo tama#o se desbalancea. Hay que ver que efecto
+ * puede tener en el caso de claves de long. variable
+ */
+ if (it == node_keys.end ())
+ total_size -= datait->Size ();
+ }
+
+ it = node_keys.begin ();
+ uint used = 0;
+ while (used < total_size/2) {
+ BTreeData *d = (*it);
+ old_node_keys.push_back (d);
+ used += d->Size ();
+ it++;
+ }
+ kout = (*it)->getClave (); // Esta se retorna al "padre" para que se la agregue
+
+ new_node_keys.push_back ( new BTreeChildData ((*it)->getChild ()));
+ it++;
+ while (it != node_keys.end ()) {
+ BTreeData *d = (*it);
+ new_node_keys.push_back (d);
+ it++;
+ }
+
+ /* Guardo */
+ WriteKeys (node, node_header, old_node_keys);
+ WriteNodoHeader (node, &node_header);
+ WriteBlock (node, node_num);
+ WriteKeys (new_node, new_node_header, new_node_keys);
+ WriteNodoHeader (new_node, &new_node_header);
+ WriteBlock (new_node, new_node_num);
+ DeleteKeys (old_node_keys);
+ DeleteKeys (new_node_keys);
+
+ PrintNode (node_num);
+ PrintNode (new_node_num);
+
+ /* Paso los hijos */
+ left_child = node_num;
+ right_child = new_node_num;
+ delete [] new_node;
+ delete [] node;
+ }
+
+ return kout;
+}
+
+void BTree::DelKey (const Clave &k)
+{
+ std::string s = k;
+ std::cout << "========= Borrando " << s << " =================\n";
+ DelKeyR (new BTreeLeafData (k.Clone ()), 0, 0);
+}
+
+void BTree::DelKeyR (BTreeData *k, uint node_num, uint padre)
+{
+ std::list<BTreeData *> node_keys;
+ BTreeNodeHeader node_header;
+ uchar *node;
+
+ node = ReadBlock (node_num);
+ ReadNodoHeader (node, &node_header);
+ node_keys = ReadKeys (node, node_header);
+
+ std::list<BTreeData *>::iterator it = node_keys.begin ();
+ std::list<BTreeData *>::iterator ultima;
+ std::list<BTreeData *>::iterator posterior;
+
+ BTreeData *lchild;
+ if (node_header.level != 0) {
+ lchild = (*it++);
+ }
+ posterior = it;
+
+ while (it != node_keys.end ()) {
+ if ((*k) == (*(*it))) {
+ /* La encontre!, retorno */
+ if (node_header.level == 0) {
+ DelKeyFromLeaf (k->getClave (), node_num, padre);
+ } else {
+ uint left, right;
+ if (it == posterior) {
+ left = lchild->getChild ();
+ right = (*it)->getChild ();
+ } else {
+ left = (*ultima)->getChild ();
+ right = (*it)->getChild ();
+ }
+ std::cout << "Eliminar de Nodo con hijos : " << left << " y " << right << std::endl;
+ DelKeyFromNode (k->getClave (), node_num, padre, left, right);
+ }
+ return;
+ }
+
+ if ((*k) < (*(*it)))
+ break;
+ ultima = it;
+ it++;
+ }
+
+ /* Si llego aca y estoy en nivel 0 (una hoja) quiere
+ * decir que no lo encontre
+ */
+ if (node_header.level == 0) {
+ std::cout << "*** Clave no encontrada ***\n";
+ return;
+ }
+
+ /* TODO: Aca faltaria liberar memoria */
+ if (it == posterior) {
+ DelKeyR (k, lchild->getChild (), node_num);
+ } else {
+ DelKeyR (k, (*ultima)->getChild (), node_num);
+ }
+}
+
+void BTree::DelKeyFromLeaf (Clave *k, uint node_num, uint padre)
+{
+ BTreeData *data;
+ uchar *node;
+ BTreeNodeHeader node_header;
+ std::list<BTreeData *> node_keys;
+
+ node = ReadBlock (node_num);
+ ReadNodoHeader (node, &node_header);
+ node_keys = ReadKeys (node, node_header);
+
+ data = new BTreeLeafData (k);
+
+ std::list<BTreeData *>::iterator it;
+ it = node_keys.begin ();
+ while (it != node_keys.end ()) {
+ if ((*data) == (*(*it))) {
+ node_keys.erase (it);
+ break;
+ }
+ it++;
+ }
+
+ delete data;
+
+ /* TODO : que pasa cuando el nodo se queda vacio o con
+ * muy pocas claveS??
+ */
+ WriteKeys (node, node_header, node_keys);
+ WriteNodoHeader (node, &node_header);
+ WriteBlock (node, node_num);
+
+ /* Veo si se cumple la condición de minimalidad */
+ uint min_free = (header.block_size-sizeof(BTreeNodeHeader))/2;
+ if ((node_header.free_space > min_free) && (node_num != 0)) {
+ /* Oops! Debo pedir prestada clave */
+ uint hi, hd;
+ Clave *pedida;
+
+ FindBrothers (node_num, padre, hi, hd);
+
+ if ((pedida = GetKey (hi, 1)) != NULL) {
+ std::string s = *pedida;
+ std::cout << "Clave Pedida : " << s << std::endl;
+
+ pedida = ReplaceKeyInFather (node_num, padre, pedida);
+
+ node_keys.insert (node_keys.begin (), new BTreeLeafData (pedida));
+ } else if ((pedida = GetKey (hd, 0)) != NULL) {
+ std::string s = *pedida;
+ std::cout << "Clave Pedida : " << s << std::endl;
+
+ pedida = ReplaceKeyInFather (node_num, padre, pedida);
+
+ node_keys.push_back (new BTreeLeafData (pedida));
+ } else {
+ std::cout << "NADIE ME PUEDE PRESTAR, FUNDIR NODOS\n";
+ uint join1, join2;
+ int tipoh;
+ if (hi != 0) {
+ std::cout << "Join con Hermano Izquierdo\n";
+ join1 = hi;
+ join2 = node_num;
+ tipoh = 0;
+ } else {
+ std::cout << "Join con Hermano Derecho\n";
+ join1 = node_num;
+ join2 = hd;
+ tipoh = 1;
+ }
+
+ JoinNodes (join1, join2, padre, tipoh);
+ return;
+ }
+
+ WriteKeys (node, node_header, node_keys);
+ WriteNodoHeader (node, &node_header);
+ WriteBlock (node, node_num);
+ }
+
+ DeleteKeys (node_keys);
+ delete [] node;
+ std::cout << "Borrado de una hoja listo\n";
+}
+
+void BTree::JoinNodes (uint node1, uint node2, uint padre, int tipohermano)
+{
+ uchar *n1, *n2, *npadre;
+ BTreeNodeHeader nh1, nh2, nhp;
+ std::list<BTreeData *> nk1, nk2, nkpadre;
+
+ if (node1 == node2) {
+ std::cout << "PANIC : No puedo juntar el mismo nodo con si mismo!!\n";
+ exit (1);
+ }
+ if (node1 == padre) {
+ std::cout << "PANIC : No puedo juntar el mismo nodo con si mismo!!\n";
+ exit (1);
+ }
+ if (node2 == padre) {
+ std::cout << "PANIC : No puedo juntar el mismo nodo con si mismo!!\n";
+ exit (1);
+ }
+
+ PrintNode (padre);
+ PrintNode (node1);
+ PrintNode (node2);
+
+ /* Leo los nodos */
+ n1 = ReadBlock (node1);
+ n2 = ReadBlock (node2);
+ npadre = ReadBlock (padre);
+
+ ReadNodoHeader (n1, &nh1);
+ ReadNodoHeader (n2, &nh2);
+ ReadNodoHeader (npadre, &nhp);
+
+ /* Apunto de Unir */
+ uint tmp = header.block_size - sizeof (BTreeNodeHeader);
+ uint l = tmp - nh1.free_space;
+ l += tmp - nh1.free_space;
+ l += 4;
+
+ std::cout << "Espacio ocupado despues de unir : " << l << " de " << tmp << std::endl;
+
+ nk1 = ReadKeys (n1, nh1);
+ nk2 = ReadKeys (n2, nh2);
+ nkpadre = ReadKeys (npadre, nhp);
+
+ /* Busco la clave del padre a juntar con los nodos */
+ std::list<BTreeData *>::iterator it = nkpadre.begin ();
+ std::list<BTreeData *>::iterator borrar_padre;
+ std::list<BTreeData *>::iterator sig;
+ std::list<BTreeData *>::iterator anterior = it;
+
+ Clave *cpadre;
+ BTreeData *lchild = (*it++);
+
+ if (lchild->getChild () == node1) {
+ cpadre = (*it)->getClave ();
+ borrar_padre = it;
+ } else {
+ while (it != nkpadre.end ()) {
+ if (tipohermano == 0) {
+ if ((*it)->getChild () == node2)
+ break;
+ } else {
+ if ((*it)->getChild () == node1)
+ break;
+ }
+ anterior = it;
+ it++;
+ }
+ cpadre = (*it)->getClave ();
+ borrar_padre = it;
+ }
+ if (it == nkpadre.end ()) {
+ std::cout << "PANIC : Me pase sin encontrar la clave!!\n";
+ exit(1);
+ }
+ it++;
+ sig = it;
+
+ std::list<BTreeData *> newkeys;
+ std::list<BTreeData *>::iterator i;
+
+ i = nk1.begin ();
+ while (i != nk1.end ()) {
+ newkeys.push_back ( new BTreeLeafData ((*i)->getClave ()->Clone ()));
+ i++;
+ }
+ //if (tipohermano == 0)
+ newkeys.push_back ( new BTreeLeafData (cpadre->Clone ()));
+ i = nk2.begin ();
+ while (i != nk2.end ()) {
+ newkeys.push_back ( new BTreeLeafData ((*i)->getClave ()->Clone ()));
+ i++;
+ }
+
+ std::cout << "Espacio ocupado por las nuevas claves : " << (newkeys.size()*4) << std::endl;
+ if ((newkeys.size()*4) > tmp) {
+ std::cout << "PANIC : El nodo fundido no entra !!!\n";
+ exit (1);
+ }
+
+ /* Para el padre, tener 2 items significa tener solo 1 clave, ya que
+ * el otro item es el LeftChild!
+ */
+ if ((padre == 0) && (nhp.item_count == 2)) {
+ /* Si junte 2 nodos, cuyo padre era la raiz, y esta tenia
+ * solo una clave, quiere decir que lo que me queda
+ * es de nuevo solo una raiz con todas las claves
+ */
+ nhp.level = 0;
+ WriteKeys (npadre, nhp, newkeys);
+ WriteNodoHeader (npadre, &nhp);
+ WriteBlock (npadre, padre);
+
+ /* TODO: Recuperar nodo1 y nodo2 */
+ } else {
+ WriteKeys (n1, nh1, newkeys);
+ WriteNodoHeader (n1, &nh1);
+ WriteBlock (n1, node1);
+
+ /* TODO : Recuperar node2 */
+ /* Actualizo punero al padre */
+ (*anterior)->setChild (node1);
+
+ nkpadre.erase (borrar_padre);
+ WriteKeys (npadre, nhp, nkpadre);
+ WriteNodoHeader (npadre, &nhp);
+ WriteBlock (npadre, padre);
+ }