summaryrefslogtreecommitdiff
path: root/src/map.c
blob: 052e54459c412f45fe7bc14c8324e19672a94ca6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
/*
 * Copyright 2010-2018 Adrian Thurston <thurston@colm.net>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#include <colm/map.h>

#include <assert.h>
#include <stdbool.h>

#include <colm/pdarun.h>
#include <colm/pool.h>
#include <colm/bytecode.h>

struct colm_struct *colm_map_el_get( struct colm_program *prg,
		map_el_t *map_el, word_t gen_id, word_t field )
{
	struct generic_info *gi = &prg->rtd->generic_info[gen_id];
	map_el_t *result = 0;
	switch ( field ) {
		case 0: 
			result = map_el->prev;
			break;
		case 1: 
			result = map_el->next;
			break;
		default:
			assert( 0 );
			break;
	}

	struct colm_struct *s = result != 0 ?
			colm_struct_container( result, gi->el_offset ) : 0;
	return s;
}

struct colm_struct *colm_map_get( struct colm_program *prg,
		map_t *map, word_t gen_id, word_t field )
{
	struct generic_info *gi = &prg->rtd->generic_info[gen_id];
	map_el_t *result = 0;
	switch ( field ) {
		case 0: 
			result = map->head;
			break;
		case 1: 
			result = map->tail;
			break;
		default:
			assert( 0 );
			break;
	}

	struct colm_struct *s = result != 0 ?
			colm_struct_container( result, gi->el_offset ) : 0;
	return s;
}

void map_list_abandon( map_t *map )
{
	map->head = map->tail = 0;
}

void map_list_add_before( map_t *map, map_el_t *next_el, map_el_t *new_el )
{
	/* Set the next pointer of the new element to next_el. We do
	 * this regardless of the state of the list. */
	new_el->next = next_el; 

	/* Set reverse pointers. */
	if ( next_el == 0 ) {
		/* There is no next elememnt. We are inserting at the tail. */
		new_el->prev = map->tail;
		map->tail = new_el;
	} 
	else {
		/* There is a next element and we can access next's previous. */
		new_el->prev = next_el->prev;
		next_el->prev = new_el;
	} 

	/* Set forward pointers. */
	if ( new_el->prev == 0 ) {
		/* There is no previous element. Set the head pointer.*/
		map->head = new_el;
	}
	else {
		/* There is a previous element, set it's next pointer to new_el. */
		new_el->prev->next = new_el;
	}
}

void map_list_add_after( map_t *map, map_el_t *prev_el, map_el_t *new_el )
{
	/* Set the previous pointer of new_el to prev_el. We do
	 * this regardless of the state of the list. */
	new_el->prev = prev_el; 

	/* Set forward pointers. */
	if (prev_el == 0) {
		/* There was no prev_el, we are inserting at the head. */
		new_el->next = map->head;
		map->head = new_el;
	} 
	else {
		/* There was a prev_el, we can access previous next. */
		new_el->next = prev_el->next;
		prev_el->next = new_el;
	} 

	/* Set reverse pointers. */
	if (new_el->next == 0) {
		/* There is no next element. Set the tail pointer. */
		map->tail = new_el;
	}
	else {
		/* There is a next element. Set it's prev pointer. */
		new_el->next->prev = new_el;
	}
}


map_el_t *map_list_detach( map_t *map, map_el_t *el )
{
	/* Set forward pointers to skip over el. */
	if ( el->prev == 0 ) 
		map->head = el->next; 
	else
		el->prev->next = el->next; 

	/* Set reverse pointers to skip over el. */
	if ( el->next == 0 ) 
		map->tail = el->prev; 
	else
		el->next->prev = el->prev; 

	/* Update List length and return element we detached. */
	return el;
}


/* Once an insertion position is found, attach a element to the tree. */
void map_attach_rebal( map_t *map, map_el_t *element, map_el_t *parent_el, map_el_t *last_less )
{
	/* Increment the number of element in the tree. */
	map->tree_size += 1;

	/* Set element's parent. */
	element->parent = parent_el;

	/* New element always starts as a leaf with height 1. */
	element->left = 0;
	element->right = 0;
	element->height = 1;

	/* Are we inserting in the tree somewhere? */
	if ( parent_el != 0 ) {
		/* We have a parent so we are somewhere in the tree. If the parent
		 * equals lastLess, then the last traversal in the insertion went
		 * left, otherwise it went right. */
		if ( last_less == parent_el ) {
			parent_el->left = element;

			map_list_add_before( map, parent_el, element );
		}
		else {
			parent_el->right = element;

			map_list_add_after( map, parent_el, element );
		}
	}
	else {
		/* No parent element so we are inserting the root. */
		map->root = element;

		map_list_add_after( map, map->tail, element );
	}

	/* Recalculate the heights. */
	map_recalc_heights( map, parent_el );

	/* Find the first unbalance. */
	map_el_t *ub = mapFindFirstUnbalGP( map, element );

	/* rebalance. */
	if ( ub != 0 )
	{
		/* We assert that after this single rotation the 
		 * tree is now properly balanced. */
		map_rebalance( map, ub );
	}
}

#if 0
/* Recursively delete all the children of a element. */
void map_delete_children_of( map_t *map, map_el_t *element )
{
	/* Recurse left. */
	if ( element->left ) {
		map_delete_children_of( map, element->left );

		/* Delete left element. */
		delete element->left;
		element->left = 0;
	}

	/* Recurse right. */
	if ( element->right ) {
		map_delete_children_of( map, element->right );

		/* Delete right element. */
		delete element->right;
		element->left = 0;
	}
}

void map_empty( map_t *map )
{
	if ( map->root ) {
		/* Recursively delete from the tree structure. */
		map_delete_children_of( map, map->root );
		delete map->root;
		map->root = 0;
		map->tree_size = 0;

		map_list_abandon( map );
	}
}
#endif

/* rebalance from a element whose gradparent is unbalanced. Only
 * call on a element that has a grandparent. */
map_el_t *map_rebalance( map_t *map, map_el_t *n )
{
	long lheight, rheight;
	map_el_t *a, *b, *c;
	map_el_t *t1, *t2, *t3, *t4;

	map_el_t *p = n->parent; /* parent (Non-NUL). L*/
	map_el_t *gp = p->parent; /* Grand-parent (Non-NULL). */
	map_el_t *ggp = gp->parent; /* Great grand-parent (may be NULL). */

	if (gp->right == p)
	{
		/*  gp
		 *   		 *    p
		 p
		 */
		if (p->right == n)
		{
			/*  gp
			 *   			 *    p
			 p
			 *     			 *      n
			 n
			 */
			a = gp;
			b = p;
			c = n;
			t1 = gp->left;
			t2 = p->left;
			t3 = n->left;
			t4 = n->right;
		}
		else
		{
			/*  gp
			 *     			 *       p
			 p
			 *      /
			 *     n
			 */
			a = gp;
			b = n;
			c = p;
			t1 = gp->left;
			t2 = n->left;
			t3 = n->right;
			t4 = p->right;
		}
	}
	else
	{
		/*    gp
		 *   /
		 *  p
		 */
		if (p->right == n)
		{
			/*      gp
			 *    /
			 *  p
			 *   			 *    n
			 n
			 */
			a = p;
			b = n;
			c = gp;
			t1 = p->left;
			t2 = n->left;
			t3 = n->right;
			t4 = gp->right;
		}
		else
		{
			/*      gp
			 *     /
			 *    p
			 *   /
			 *  n
			 */
			a = n;
			b = p;
			c = gp;
			t1 = n->left;
			t2 = n->right;
			t3 = p->right;
			t4 = gp->right;
		}
	}

	/* Perform rotation.
	*/

	/* Tie b to the great grandparent. */
	if ( ggp == 0 )
		map->root = b;
	else if ( ggp->left == gp )
		ggp->left = b;
	else
		ggp->right = b;
	b->parent = ggp;

	/* Tie a as a leftchild of b. */
	b->left = a;
	a->parent = b;

	/* Tie c as a rightchild of b. */
	b->right = c;
	c->parent = b;

	/* Tie t1 as a leftchild of a. */
	a->left = t1;
	if ( t1 != 0 ) t1->parent = a;

	/* Tie t2 as a rightchild of a. */
	a->right = t2;
	if ( t2 != 0 ) t2->parent = a;

	/* Tie t3 as a leftchild of c. */
	c->left = t3;
	if ( t3 != 0 ) t3->parent = c;

	/* Tie t4 as a rightchild of c. */
	c->right = t4;
	if ( t4 != 0 ) t4->parent = c;

	/* The heights are all recalculated manualy and the great
	 * grand-parent is passed to recalcHeights() to ensure
	 * the heights are correct up the tree.
	 *
	 * Note that recalcHeights() cuts out when it comes across
	 * a height that hasn't changed.
	 */

	/* Fix height of a. */
	lheight = a->left ? a->left->height : 0;
	rheight = a->right ? a->right->height : 0;
	a->height = (lheight > rheight ? lheight : rheight) + 1;

	/* Fix height of c. */
	lheight = c->left ? c->left->height : 0;
	rheight = c->right ? c->right->height : 0;
	c->height = (lheight > rheight ? lheight : rheight) + 1;

	/* Fix height of b. */
	lheight = a->height;
	rheight = c->height;
	b->height = (lheight > rheight ? lheight : rheight) + 1;

	/* Fix height of b's parents. */
	map_recalc_heights( map, ggp );
	return ggp;
}

/* Recalculates the heights of all the ancestors of element. */
void map_recalc_heights( map_t *map, map_el_t *element )
{
	while ( element != 0 )
	{
		long lheight = element->left ? element->left->height : 0;
		long rheight = element->right ? element->right->height : 0;

		long new_height = (lheight > rheight ? lheight : rheight) + 1;

		/* If there is no chage in the height, then there will be no
		 * change in any of the ancestor's height. We can stop going up.
		 * If there was a change, continue upward. */
		if (new_height == element->height)
			return;
		else
			element->height = new_height;

		element = element->parent;
	}
}

/* Finds the first element whose grandparent is unbalanced. */
map_el_t *mapFindFirstUnbalGP( map_t *map, map_el_t *element )
{
	long lheight, rheight, balance_prop;
	map_el_t *gp;

	if ( element == 0 || element->parent == 0 ||
			element->parent->parent == 0 )
		return 0;

	/* Don't do anything if we we have no grandparent. */
	gp = element->parent->parent;
	while ( gp != 0 )
	{
		lheight = gp->left ? gp->left->height : 0;
		rheight = gp->right ? gp->right->height : 0;
		balance_prop = lheight - rheight;

		if ( balance_prop < -1 || balance_prop > 1 )
			return element;

		element = element->parent;
		gp = gp->parent;
	}
	return 0;
}



/* Finds the first element that is unbalanced. */
map_el_t *map_find_first_unbal_el( map_t *map, map_el_t *element )
{
	if ( element == 0 )
		return 0;

	while ( element != 0 )
	{
		long lheight = element->left ?
			element->left->height : 0;
		long rheight = element->right ?
			element->right->height : 0;
		long balance_prop = lheight - rheight;

		if ( balance_prop < -1 || balance_prop > 1 )
			return element;

		element = element->parent;
	}
	return 0;
}

/* Replace a element in the tree with another element not in the tree. */
void map_replace_el( map_t *map, map_el_t *element, map_el_t *replacement )
{
	map_el_t *parent = element->parent,
			*left = element->left,
			*right = element->right;

	replacement->left = left;
	if (left)
		left->parent = replacement;
	replacement->right = right;
	if (right)
		right->parent = replacement;

	replacement->parent = parent;
	if (parent)
	{
		if (parent->left == element)
			parent->left = replacement;
		else
			parent->right = replacement;
	}
	else {
		map->root = replacement;
	}

	replacement->height = element->height;
}


/* Removes a element from a tree and puts filler in it's place.
 * Filler should be null or a child of element. */
void map_remove_el( map_t *map, map_el_t *element, map_el_t *filler )
{
	map_el_t *parent = element->parent;

	if ( parent )
	{
		if ( parent->left == element )
			parent->left = filler;
		else
			parent->right = filler;
	}
	else {
		map->root = filler;
	}

	if ( filler )
		filler->parent = parent;

	return;
}

#if 0
/* Recursive worker for tree copying. */
map_el_t *map_copy_branch( program_t *prg, map_t *map, map_el_t *el, kid_t *old_next_down, kid_t **new_next_down )
{
	/* Duplicate element. Either the base element's copy constructor or defaul
	 * constructor will get called. Both will suffice for initting the
	 * pointers to null when they need to be. */
	map_el_t *new_el = map_el_allocate( prg );

	if ( (kid_t*)el == old_next_down )
		*new_next_down = (kid_t*)new_el;

	/* If the left tree is there, copy it. */
	if ( new_el->left ) {
		new_el->left = map_copy_branch( prg, map, new_el->left, old_next_down, new_next_down );
		new_el->left->parent = new_el;
	}

	map_list_add_after( map, map->tail, new_el );

	/* If the right tree is there, copy it. */
	if ( new_el->right ) {
		new_el->right = map_copy_branch( prg, map, new_el->right, old_next_down, new_next_down );
		new_el->right->parent = new_el;
	}

	return new_el;
}
#endif

static long map_cmp( program_t *prg, map_t *map, const tree_t *tree1, const tree_t *tree2 )
{
	if ( map->generic_info->key_type == TYPE_TREE ) {
		return colm_cmp_tree( prg, tree1, tree2 );
	}
	else {
		if ( (long)tree1 < (long)tree2 )
			return -1;
		else if ( (long)tree1 > (long)tree2)
			return 1;
		return 0;
	}
}

map_el_t *map_insert_el( program_t *prg, map_t *map, map_el_t *element, map_el_t **last_found )
{
	long key_relation;
	map_el_t *cur_el = map->root, *parent_el = 0;
	map_el_t *last_less = 0;

	while ( true ) {
		if ( cur_el == 0 ) {
			/* We are at an external element and did not find the key we were
			 * looking for. Attach underneath the leaf and rebalance. */
			map_attach_rebal( map, element, parent_el, last_less );

			if ( last_found != 0 )
				*last_found = element;
			return element;
		}

		key_relation = map_cmp( prg, map,
			element->key, cur_el->key );

		/* Do we go left? */
		if ( key_relation < 0 ) {
			parent_el = last_less = cur_el;
			cur_el = cur_el->left;
		}
		/* Do we go right? */
		else if ( key_relation > 0 ) {
			parent_el = cur_el;
			cur_el = cur_el->right;
		}
		/* We have hit the target. */
		else {
			if ( last_found != 0 )
				*last_found = cur_el;
			return 0;
		}
	}
}

#if 0
map_el_t *map_insert_key( program_t *prg, map_t *map, tree_t *key, map_el_t **last_found )
{
	long key_relation;
	map_el_t *cur_el = map->root, *parent_el = 0;
	map_el_t *last_less = 0;

	while ( true ) {
		if ( cur_el == 0 ) {
			/* We are at an external element and did not find the key we were
			 * looking for. Create the new element, attach it underneath the leaf
			 * and rebalance. */
			map_el_t *element = map_el_allocate( prg );
			element->key = key;
			map_attach_rebal( map, element, parent_el, last_less );

			if ( last_found != 0 )
				*last_found = element;
			return element;
		}

		key_relation = map_cmp( prg, map, key, cur_el->key );

		/* Do we go left? */
		if ( key_relation < 0 ) {
			parent_el = last_less = cur_el;
			cur_el = cur_el->left;
		}
		/* Do we go right? */
		else if ( key_relation > 0 ) {
			parent_el = cur_el;
			cur_el = cur_el->right;
		}
		/* We have hit the target. */
		else {
			if ( last_found != 0 )
				*last_found = cur_el;
			return 0;
		}
	}
}
#endif

map_el_t *colm_map_insert( program_t *prg, map_t *map, map_el_t *map_el )
{
	return map_insert_el( prg, map, map_el, 0 );
}

map_el_t *colm_vmap_insert( program_t *prg, map_t *map, struct_t *key, struct_t *value )
{
	struct colm_struct *s = colm_struct_new( prg, map->generic_info->el_struct_id );

	colm_struct_set_field( s, struct_t*, map->generic_info->el_offset, key );
	colm_struct_set_field( s, struct_t*, 0, value );

	map_el_t *map_el = colm_struct_get_addr( s, map_el_t*, map->generic_info->el_offset );

	return colm_map_insert( prg, map, map_el );
}

map_el_t *colm_vmap_remove( program_t *prg, map_t *map, tree_t *key )
{
	map_el_t *map_el = colm_map_find( prg, map, key );
	if ( map_el != 0 )
		colm_map_detach( prg, map, map_el );
	return 0;
}

tree_t *colm_vmap_find( program_t *prg, map_t *map, tree_t *key )
{
	map_el_t *map_el = colm_map_find( prg, map, key );
	if ( map_el != 0 ) {
		struct_t *s = colm_generic_el_container( prg, map_el,
				map->generic_info - prg->rtd->generic_info );
		tree_t *val = colm_struct_get_field( s, tree_t*, 0 );

		if ( map->generic_info->value_type == TYPE_TREE )
			colm_tree_upref( prg, val );

		return val;
	}
	return 0;
}

void colm_map_detach( program_t *prg, map_t *map, map_el_t *map_el )
{
	map_detach( prg, map, map_el );
}

map_el_t *colm_map_find( program_t *prg, map_t *map, tree_t *key )
{
	return map_impl_find( prg, map, key );
}

/**
 * \brief Find a element in the tree with the given key.
 *
 * \returns The element if key exists, null if the key does not exist.
 */
map_el_t *map_impl_find( program_t *prg, map_t *map, tree_t *key )
{
	map_el_t *cur_el = map->root;
	long key_relation;

	while ( cur_el != 0 ) {
		key_relation = map_cmp( prg, map, key, cur_el->key );

		/* Do we go left? */
		if ( key_relation < 0 )
			cur_el = cur_el->left;
		/* Do we go right? */
		else if ( key_relation > 0 )
			cur_el = cur_el->right;
		/* We have hit the target. */
		else {
			return cur_el;
		}
	}
	return 0;
}


/**
 * \brief Find a element, then detach it from the tree. 
 * 
 * The element is not deleted.
 *
 * \returns The element detached if the key is found, othewise returns null.
 */
map_el_t *map_detach_by_key( program_t *prg, map_t *map, tree_t *key )
{
	map_el_t *element = map_impl_find( prg, map, key );
	if ( element )
		map_detach( prg, map, element );

	return element;
}

/**
 * \brief Detach a element from the tree. 
 *
 * If the element is not in the tree then undefined behaviour results.
 * 
 * \returns The element given.
 */
map_el_t *map_detach( program_t *prg, map_t *map, map_el_t *element )
{
	map_el_t *replacement, *fixfrom;
	long lheight, rheight;

	/* Remove the element from the ordered list. */
	map_list_detach( map, element );

	/* Update treeSize. */
	map->tree_size--;

	/* Find a replacement element. */
	if (element->right)
	{
		/* Find the leftmost element of the right subtree. */
		replacement = element->right;
		while (replacement->left)
			replacement = replacement->left;

		/* If replacing the element the with its child then we need to start
		 * fixing at the replacement, otherwise we start fixing at the
		 * parent of the replacement. */
		if (replacement->parent == element)
			fixfrom = replacement;
		else
			fixfrom = replacement->parent;

		map_remove_el( map, replacement, replacement->right );
		map_replace_el( map, element, replacement );
	}
	else if (element->left)
	{
		/* Find the rightmost element of the left subtree. */
		replacement = element->left;
		while (replacement->right)
			replacement = replacement->right;

		/* If replacing the element the with its child then we need to start
		 * fixing at the replacement, otherwise we start fixing at the
		 * parent of the replacement. */
		if (replacement->parent == element)
			fixfrom = replacement;
		else
			fixfrom = replacement->parent;

		map_remove_el( map, replacement, replacement->left );
		map_replace_el( map, element, replacement );
	}
	else
	{
		/* We need to start fixing at the parent of the element. */
		fixfrom = element->parent;

		/* The element we are deleting is a leaf element. */
		map_remove_el( map, element, 0 );
	}

	/* If fixfrom is null it means we just deleted
	 * the root of the tree. */
	if ( fixfrom == 0 )
		return element;

	/* Fix the heights after the deletion. */
	map_recalc_heights( map, fixfrom );

	/* Fix every unbalanced element going up in the tree. */
	map_el_t *ub = map_find_first_unbal_el( map, fixfrom );
	while ( ub )
	{
		/* Find the element to rebalance by moving down from the first unbalanced
		 * element 2 levels in the direction of the greatest heights. On the
		 * second move down, the heights may be equal ( but not on the first ).
		 * In which case go in the direction of the first move. */
		lheight = ub->left ? ub->left->height : 0;
		rheight = ub->right ? ub->right->height : 0;
		assert( lheight != rheight );
		if (rheight > lheight)
		{
			ub = ub->right;
			lheight = ub->left ?
				ub->left->height : 0;
			rheight = ub->right ?
				ub->right->height : 0;
			if (rheight > lheight)
				ub = ub->right;
			else if (rheight < lheight)
				ub = ub->left;
			else
				ub = ub->right;
		}
		else
		{
			ub = ub->left;
			lheight = ub->left ?
				ub->left->height : 0;
			rheight = ub->right ?
				ub->right->height : 0;
			if (rheight > lheight)
				ub = ub->right;
			else if (rheight < lheight)
				ub = ub->left;
			else
				ub = ub->left;
		}


		/* rebalance returns the grandparant of the subtree formed
		 * by the element that were rebalanced.
		 * We must continue upward from there rebalancing. */
		fixfrom = map_rebalance( map, ub );

		/* Find the next unbalaced element. */
		ub = map_find_first_unbal_el( map, fixfrom );
	}

	return element;
}