treesort.c 20.8 KB
Newer Older
Andreas Tille's avatar
Andreas Tille committed
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
/*
 * treesort.c
 *
 *
 * Part of TREE-PUZZLE 5.2 (July 2004)
 *
 * (c) 2003-2004 by Heiko A. Schmidt, Korbinian Strimmer, and Arndt von Haeseler
 * (c) 1999-2003 by Heiko A. Schmidt, Korbinian Strimmer,
 *                  M. Vingron, and Arndt von Haeseler
 * (c) 1995-1999 by Korbinian Strimmer and Arndt von Haeseler
 *
 * All parts of the source except where indicated are distributed under
 * the GNU public licence.  See http://www.opensource.org for details.
 *
 * ($Id$)
 *
 */


#define EXTERN extern
#include "treesort.h"

int YYY=0;
/* fprintf(stderr, "YYY: %d (%s:%d)\n", YYY++, __FILE__, __LINE__); */


/*******************************************/
/* tree sorting                            */
/*******************************************/

/* compute address of the 4 int (sort key) in the 4 int node */
int ct_sortkeyaddr(int addr)
{
  int a, res;
  a = addr % 4;
  res = addr - a + 3;
  return res;
} /* ct_sortkeyaddr */


/**********/

/* compute address of the next edge pointer in a 4 int node (0->1->2->0) */
int ct_nextedgeaddr(int addr)
{
  int a, res;
  a = addr % 4;
  if ( a == 2 ) { res = addr - 2; }
  else          { res = addr + 1; }
  return res;
} /* ct_nextedgeaddr */


/**********/

/* compute address of 1st edge of a 4 int node from node number */
int ct_1stedge(int node)
{
  int res;
  res = 4 * node;
  return res;
} /* ct_1stedge */


/**********/

/* compute address of 2nd edge of a 4 int node from node number */
int ct_2ndedge(int node)
{
  int res;
  res = 4 * node +1;
  return res;
} /* ct_2ndedge */


/**********/

/* compute address of 3rd edge of a 4 int node from node number */
int ct_3rdedge(int node)
{
  int res;
  res = 4 * node +2;
  return res;
} /* ct_3rdedge */


/**********/

/* check whether node 'node' is a leaf (2nd/3rd edge pointer = -1) */
int ct_isleaf(int node, int *ctree)
{
  return (ctree[ct_3rdedge(node)] < 0);
} /* ct_isleaf */


/**********/

/* compute node number of 4 int node from an edge addr. */
int ct_addr2node(int addr)
{
  int a, res;
  a = addr % 4;
  res = (int) ((addr - a) / 4);
  return res;
} /* ct_addr2node */


/**********/

/* print graph pointers for checking */
void printctree(int *ctree)
{
	int n;
	for (n=0; n < 2*Maxspc; n++) {
		printf("n[%3d] = (%3d.%2d, %3d.%2d, %3d.%2d | %3d)\n", n,
		(int) ctree[ct_1stedge(n)]/4,
		(int) ctree[ct_1stedge(n)]%4,
		(int) ctree[ct_2ndedge(n)]/4,
		(int) ctree[ct_2ndedge(n)]%4,
		(int) ctree[ct_3rdedge(n)]/4,
		(int) ctree[ct_3rdedge(n)]%4,
		ctree[ct_3rdedge(n)+1]);
	}
        printf("\n");
} /* printctree */


/**********/

/* allocate memory for ctree 3 ints pointer plus 1 check byte */
int *initctree(void)
{
  int *snodes;
  int n;

  snodes = (int *) calloc((size_t) (4 * 2 * Maxspc), sizeof(int));
  if (snodes == NULL) maerror("snodes in copytree");

  for (n=0; n<(4 * 2 * Maxspc); n++) {
      snodes[n]=-1;
  }
  return snodes;
} /* initctree */


/**********/

/* free memory of a tree for sorting */
void freectree(int **snodes)
{
	free(*snodes);
	*snodes = NULL;
} /* freectree */


#if 0
/**********/

/* trueID (HAS) */
/* copy subtree recursively */
void copyOTU_trueID(int   *ctree,      /* in/out: tree array struct         */
             int          *ct_nextnode,/* in/out: next free node            */
             int           ct_curredge,/* in: currend edge to add subtree   */
             int          *ct_nextleaf,/* in/out: next free leaf (0-maxspc) */
             int           ed,         /* in: current edge in puzzling tree */
             ONEEDGE      *edge,       /* in: tree topology                 */
             int          *edgeofleaf, /* in: external edge list            */
             int           numleaves,  /* in: number of leaves              */
             int          *trueID)     /* in: permutation vector            */
{
        int i, nextcurredge;

        /* test whether we are on a leaf */
        if (edge[ed].downright == NULL && edge[ed].downleft == NULL) {
                for (i = 1; i < numleaves; i++) {
                        if (edgeofleaf[i] == ed) { /* i is the leaf of ed */
				nextcurredge          = ct_1stedge(*ct_nextleaf);
				ctree[ct_curredge]    = nextcurredge;
				ctree[nextcurredge]   = ct_curredge;
				/* trueID (HAS) */
                                ctree[ct_sortkeyaddr(nextcurredge)] = trueID[i];
				(*ct_nextleaf)++;
                                return;
                        }
                }
        }

        /* we are NOT on a leaf */
	nextcurredge        = ct_1stedge(*ct_nextnode);
        ctree[ct_curredge]     = nextcurredge;
	ctree[nextcurredge] = ct_curredge;
        (*ct_nextnode)++;
	nextcurredge = ct_nextedgeaddr(nextcurredge);
        copyOTU_trueID(ctree, ct_nextnode, nextcurredge, 
                ct_nextleaf, edge[ed].downleft->numedge,
                edge, edgeofleaf, numleaves, trueID);

	nextcurredge = ct_nextedgeaddr(nextcurredge);
        copyOTU_trueID(ctree, ct_nextnode, nextcurredge, 
                ct_nextleaf, edge[ed].downright->numedge, 
                edge, edgeofleaf, numleaves, trueID);
} /* copyOTU_trueID */

/********/


/* trueID (HAS) */
/* copy treestructure to sorting structure */
void copytree_trueID(int   *ctree,      /* out: copy for effective sorting */
              int          *trueID,     /* in:  permutation vector         */
              ONEEDGE      *edgeset,    /* in: intermediate tree topology  */
              int          *edgeofleaf, /*     dito.                       */
              int           numleaves)  /* in: number of leaves            */
{
        int ct_curredge;
        int ct_nextleaf;
        int ct_nextnode;

        ct_nextnode = Maxspc;
        ct_curredge = ct_1stedge(ct_nextnode);
        ct_nextleaf = 1;

        ctree[ct_1stedge(0)] = ct_curredge;
        ctree[ct_curredge]   = ct_1stedge(0);
	/* trueID (HAS) */
        ctree[ct_sortkeyaddr(0)] = trueID[0];

        ct_nextnode++;
        
        ct_curredge = ct_nextedgeaddr(ct_curredge);

        copyOTU_trueID(ctree, &ct_nextnode, ct_curredge, 
                &ct_nextleaf, edgeset[edgeofleaf[0]].downleft->numedge,
                edgeset, edgeofleaf, numleaves, trueID);

        ct_curredge = ct_nextedgeaddr(ct_curredge);
        copyOTU_trueID(ctree, &ct_nextnode, ct_curredge, 
                &ct_nextleaf, edgeset[edgeofleaf[0]].downright->numedge,
                edgeset, edgeofleaf, numleaves, trueID);
} /* copytree_trueID */
#endif


/**********/

/* copy subtree recursively */
void copyOTU(int          *ctree,      /* in/out: tree array struct         */
             int          *ct_nextnode,/* in/out: next free node            */
             int           ct_curredge,/* in: currend edge to add subtree   */
             int          *ct_nextleaf,/* in/out: next free leaf (0-maxspc) */
             int           ed,         /* in: current edge in puzzling tree */
             ONEEDGE      *edge,       /* in: tree topology                 */
             int          *edgeofleaf, /* in: external edge list            */
             int           numleaves)  /* in: number of leaves              */
{
        int nextcurredge;

        /* test whether we are on a leaf */
        if (edge[ed].downright == NULL && edge[ed].downleft == NULL) {
		nextcurredge          = ct_1stedge(*ct_nextleaf);
		ctree[ct_curredge]    = nextcurredge;
		ctree[nextcurredge]   = ct_curredge;
		ctree[ct_sortkeyaddr(nextcurredge)] = edge[ed].taxon;
		(*ct_nextleaf)++;
		return;
        }

        /* we are NOT on a leaf */
	nextcurredge        = ct_1stedge(*ct_nextnode);
        ctree[ct_curredge]     = nextcurredge;
	ctree[nextcurredge] = ct_curredge;
        (*ct_nextnode)++;
	nextcurredge = ct_nextedgeaddr(nextcurredge);
        copyOTU(ctree, ct_nextnode, nextcurredge, 
                ct_nextleaf, edge[ed].downleft->numedge,
                edge, edgeofleaf, numleaves);

	nextcurredge = ct_nextedgeaddr(nextcurredge);
        copyOTU(ctree, ct_nextnode, nextcurredge, 
                ct_nextleaf, edge[ed].downright->numedge, 
                edge, edgeofleaf, numleaves);
} /* copyOTU */


/**********/

/* copy treestructure to sorting structure */
void copytree(int          *ctree,      /* out: copy for effective sorting */
              ONEEDGE      *edgeset,    /* in: intermediate tree topology  */
              int          *edgeofleaf, /*     dito.                       */
              int           rootleaf,
              int           numleaves)  /* in: number of leaves            */
{
        int ct_curredge;
        int ct_nextleaf;
        int ct_nextnode;

        ct_nextnode = Maxspc;
        ct_curredge = ct_1stedge(ct_nextnode);
        ct_nextleaf = 1;

        ctree[ct_1stedge(0)]     = ct_curredge;
        ctree[ct_curredge]       = ct_1stedge(0);
        ctree[ct_sortkeyaddr(0)] = rootleaf;

        ct_nextnode++;
        
        ct_curredge = ct_nextedgeaddr(ct_curredge);

        copyOTU(ctree, &ct_nextnode, ct_curredge, 
                &ct_nextleaf, edgeset[edgeofleaf[rootleaf]].downleft->numedge,
                edgeset, edgeofleaf, numleaves);

        ct_curredge = ct_nextedgeaddr(ct_curredge);
        copyOTU(ctree, &ct_nextnode, ct_curredge, 
                &ct_nextleaf, edgeset[edgeofleaf[rootleaf]].downright->numedge,
                edgeset, edgeofleaf, numleaves);
} /* copytree */


/**********/

/* sort subtree from edge recursively by indices */
int sortOTU(int edge, int *ctree)
{
	int key1, key2;
	int edge1, edge2;
	int tempedge;

	/* if leaf, return taxonID */
	if (ctree[ct_2ndedge((int) (edge / 4))] < 0)
		return ctree[ct_sortkeyaddr(edge)];

	edge1 = ctree[ct_nextedgeaddr(edge)];
	edge2 = ctree[ct_nextedgeaddr(ct_nextedgeaddr(edge))];

        /* printf ("visiting [%5d] -> [%5d], [%5d]\n", edge, edge1, edge2); */
        /* printf ("visiting [%2d.%2d] -> [%2d.%2d], [%2d.%2d]\n", 
           (int)(edge/4), edge%4, (int)(edge1/4), edge1%4, 
           (int)(edge2/4), edge2%4); */

	key1  = sortOTU(edge1, ctree); 
	key2  = sortOTU(edge2, ctree); 
	
	if (key2 < key1) {
		tempedge            = ctree[ctree[edge1]];
		ctree[ctree[edge1]] = ctree[ctree[edge2]];
		ctree[ctree[edge2]] = tempedge;
		tempedge            = ctree[edge1];
		ctree[edge1]        = ctree[edge2];
		ctree[edge2]        = tempedge;
	  	ctree[ct_sortkeyaddr(edge)] = key2;
		
	} else {
	  ctree[ct_sortkeyaddr(edge)] = key1;
	}
	return ctree[ct_sortkeyaddr(edge)];
} /* sortOTU */


/**********/

/* sort ctree recursively by indices */
int sortctree(int *ctree)
{
	int n, startnode=-1;

	/* find virtual root node (ID=0) */
	for(n=0; n<Maxspc; n++) {
		if (ctree[ct_sortkeyaddr(n*4)] == 0)
			startnode = n;
	}

	/* sort it starting at virtual root node */
	sortOTU(ctree[startnode * 4], ctree);
	return startnode;
} /* sortctree */


/**********/

/* print recursively subtree of edge of sorted tree ctree */
void fprintfsortOTU(FILE *ofp, int edge, int *ctree)
{
        int edge1, edge2;

        if (ctree[ct_2ndedge((int) (edge / 4))] < 0) {
                fprintf(ofp, "%d", ctree[ct_sortkeyaddr(edge)]);
                return;
        }

        edge1 = ctree[ct_nextedgeaddr(edge)];
        edge2 = ctree[ct_nextedgeaddr(ct_nextedgeaddr(edge))];

        fprintf(ofp, "(");
        fprintfsortOTU(ofp, edge1, ctree); 
        fprintf(ofp, ",");
        fprintfsortOTU(ofp, edge2, ctree); 
        fprintf(ofp, ")");

} /* fprintfsortOTU */


/**********/

/* print recursively sorted tree ctree */
int fprintfsortctree(FILE *ofp, int *ctree)
{
        int n, startnode=-1;
        for(n=0; n<Maxspc; n++) {
                if (ctree[ct_sortkeyaddr(n*4)] == 0)
                        startnode = n;
        }
        fprintf (ofp, "(%d,", ctree[ct_sortkeyaddr(startnode*4)]);
        fprintfsortOTU(ofp, ctree[startnode * 4], ctree);
        fprintf (ofp, ");\n");
        return startnode;
} /* fprintfsortctree */


/**********/

/* print recursively subtree of edge of sorted tree ctree to string */
void sprintfOTU(char *str, int *len, int edge, int *ctree)
{
        int edge1, edge2;

        if (ctree[ct_2ndedge((int) (edge / 4))] < 0) {
                *len+=sprintf(&(str[*len]), "%d", ctree[ct_sortkeyaddr(edge)]);
		return;
	}

        edge1 = ctree[ct_nextedgeaddr(edge)];
        edge2 = ctree[ct_nextedgeaddr(ct_nextedgeaddr(edge))];

	sprintf(&(str[*len]), "(");
	(*len)++;
        sprintfOTU(str, len, edge1, ctree); 
	sprintf(&(str[*len]), ",");
	(*len)++;
        sprintfOTU(str, len, edge2, ctree); 
	sprintf(&(str[*len]), ")");
	(*len)++;
} /* sprintfOTU */

/**********/


/* print recursively sorted tree ctree to string */
char *sprintfctree(int *ctree, int strglen)
{
	char *treestr,
	     *tmpptr;
        int n,
	    len=0,
	    startnode=-1;
	treestr = (char *) calloc((size_t) strglen, sizeof(char));
	tmpptr  = treestr;
        for(n=0; n<Maxspc; n++) {
                if (ctree[ct_sortkeyaddr(n*4)] == 0)
                        startnode = n;
        }
	len+=sprintf (&(tmpptr[len]), "(%d,", ctree[ct_sortkeyaddr(startnode*4)]);
        sprintfOTU(tmpptr, &len, ctree[startnode * 4], ctree);
	len+=sprintf (&(tmpptr[len]), ");");
        return treestr;
} /* sprintfctree */


/**********/


/***********************************************/
/* establish and handle a list of sorted trees */
/***********************************************/

int itemcount;

/* initialize structure */
treelistitemtype *inittreelist(int *treenum)
{
	*treenum = 0;
	return    NULL;
} /* itemcount */


/**********/

/* malloc new tree list item */
treelistitemtype *gettreelistitem()
{
	treelistitemtype *tmpptr;
	tmpptr = (treelistitemtype *)calloc((size_t) 1, sizeof(treelistitemtype));
	if (tmpptr == NULL) maerror("item of intermediate tree stuctures");
	(*tmpptr).pred = NULL;
	(*tmpptr).succ = NULL;
	(*tmpptr).tree = NULL;
	(*tmpptr).count = 0;
	(*tmpptr).idx = itemcount++;
	return tmpptr;
} /* gettreelistitem */

/**********/

/* free whole tree list */
void freetreelist(treelistitemtype **list,
                  int               *numitems,
                  int               *numsum)
{
	treelistitemtype *current; 
	treelistitemtype *next;
	current = *list;
	while (current != NULL) {
		next = (*current).succ;
		if ((*current).tree != NULL) {
			free ((*current).tree);
			(*current).tree = NULL;
		}
		free(current);
		current = next;
	}
	*list = NULL;
	*numitems = 0;
	*numsum = 0;
} /* freetreelist */


/**********/

/* add tree to the tree list */
treelistitemtype *addtree2list(char             **tree,         /* sorted tree string */
                               int                numtrees,     /* how many occurred, e.g. in parallel */
                               treelistitemtype **list,         /* addr. of tree list */
                               int               *numitems,     
                               int               *numsum)
{
	treelistitemtype *tmpptr = NULL;
	treelistitemtype *newptr = NULL;
	int               result;
	int               done = 0;

	if ((*list == NULL) || (numitems == 0)) {
		newptr = gettreelistitem();
		(*newptr).tree = *tree; 
		*tree = NULL;
		(*newptr).id    = *numitems;
		(*newptr).count = numtrees;
		*numitems = 1;
		*numsum   = numtrees;
		*list = newptr;
	} else {
		tmpptr = *list;
		while(done == 0) {
			result = strcmp( (*tmpptr).tree, *tree);
			if (result==0) {
				free(*tree); *tree = NULL;
				(*tmpptr).count += numtrees;
				*numsum += numtrees;
				done = 1;
				newptr = tmpptr;
			} else { if (result < 0) {
					if ((*tmpptr).succ != NULL)
						tmpptr = (*tmpptr).succ;
					else {
						newptr = gettreelistitem();
						(*newptr).tree = *tree; 
						*tree = NULL;
						(*newptr).id    = *numitems;
						(*newptr).count = numtrees;
						(*newptr).pred  = tmpptr;
						(*tmpptr).succ  = newptr;
						(*numitems)++;
						*numsum += numtrees;
						done = 1;
					}
			} else { /* result < 0 */
				newptr = gettreelistitem();
				(*newptr).tree = *tree; 
				*tree = NULL;
				(*newptr).id    = *numitems;
				(*newptr).count = numtrees;
				(*newptr).succ  = tmpptr;
				(*newptr).pred  = (*tmpptr).pred;
				(*tmpptr).pred  = newptr;
				*numsum += numtrees;

				if ((*newptr).pred != NULL) {
				   (*(*newptr).pred).succ = newptr;
				} else {
				   *list = newptr;
				}
				(*numitems)++;
				done = 1;
			} /* end if result < 0 */
			} /* end if result != 0 */
		} /* while  searching in list */
	} /* if list empty, else */
	return (newptr);
} /* addtree2list */


/**********/

/* resort list of trees by number of occurences for output */
void sortbynum(treelistitemtype *list, treelistitemtype **sortlist)
{
	treelistitemtype *tmpptr = NULL;
	treelistitemtype *curr = NULL;
	treelistitemtype *next = NULL;
	int xchange = 1;

	if (list == NULL) fprintf(stderr, "Grrrrrrrrr>>>>\n");
	tmpptr = list;
	*sortlist = list;
	while (tmpptr != NULL) {
		(*tmpptr).sortnext = (*tmpptr).succ;
		(*tmpptr).sortlast = (*tmpptr).pred;
		tmpptr = (*tmpptr).succ;
	}

	while (xchange > 0) {
		curr = *sortlist;
		xchange = 0;
		if (curr == NULL) fprintf(stderr, "Grrrrrrrrr>>>>\n");
		while((*curr).sortnext != NULL) {
			next = (*curr).sortnext;
			if ((*curr).count >= (*next).count)
				curr = (*curr).sortnext;
			else {
				if ((*curr).sortlast != NULL)
					(*((*curr).sortlast)).sortnext = next;
				if (*sortlist == curr)
					*sortlist = next;
				(*next).sortlast = (*curr).sortlast;

				if ((*next).sortnext != NULL)
					(*((*next).sortnext)).sortlast = curr;
				(*curr).sortnext = (*next).sortnext;

				(*curr).sortlast = next;
				(*next).sortnext = curr;

				xchange++;
			}
		}
	}
}  /* sortbynum */


/**********/

/* print puzzling step tree stuctures for checking */
void printfpstrees(treelistitemtype *list)
{
	char ch;
	treelistitemtype *tmpptr = NULL;
	tmpptr = list;
        ch = '-';
	while (tmpptr != NULL) {
		printf ("%c[%2d]  %5d     %s\n", ch, (*tmpptr).idx, (*tmpptr).count, (*tmpptr).tree);
		tmpptr = (*tmpptr).succ;
		ch = ' ';
	}
} /* printfpstrees */

/**********/

/* print sorted puzzling step tree stucture with names */
void fprintffullpstree(FILE *outf, char *treestr)
{
	int count = 0;
	int idnum = 0;
	int n;
	for(n=0; treestr[n] != '\0'; n++){
		while(isdigit((int)treestr[n])){
			idnum = (10 * idnum) + ((int)treestr[n]-48);
			n++;
			count++;
		}
		if (count > 0){
#			ifdef USEQUOTES
				fprintf(outf, "'");
#			endif
			(void)fputid(outf, idnum);
#			ifdef USEQUOTES
				fprintf(outf, "'");
#			endif
			count = 0;
			idnum = 0;
		}
		fprintf(outf, "%c", treestr[n]);
	}
} /* fprintffullpstree */


/**********/

/* print sorted puzzling step tree stuctures with names */
void fprintfsortedpstrees(FILE *output, 
                          treelistitemtype *list,  /* tree list */
                          int itemnum,             /* order number */
                          int itemsum,             /* number of trees */
                          int comment,             /* with statistics, or puzzle report ? */
                          float cutoff)            /* cutoff percentage */
{
	treelistitemtype *tmpptr = NULL;
	treelistitemtype *slist = NULL;
	int num = 1;
        float percent;

	if (list == NULL) fprintf(stderr, "Grrrrrrrrr>>>>\n");
	sortbynum(list, &slist); 

	tmpptr = slist;
	while (tmpptr != NULL) {
		percent = (float)(100.0 * (*tmpptr).count / itemsum);
		if ((cutoff == 0.0) || (cutoff <= percent)) {
			if (comment)
				fprintf (output, "[ %d. %d %.2f %d %d %d ]", num++, (*tmpptr).count, percent, (*tmpptr).id, itemnum, itemsum);
			else {
				if (num == 1){
					fprintf (output, "\n");
					fprintf (output, "The following tree(s) occured in more than %.2f%% of the %d puzzling steps.\n", cutoff, itemsum);
					fprintf (output, "The trees are orderd descending by the number of occurences.\n");
					fprintf (output, "\n");
					fprintf (output, "\n       occurences    ID  Phylip tree\n");
				}
				fprintf (output, "%2d. %5d %6.2f%% %5d  ", num++, (*tmpptr).count, percent, (*tmpptr).id);
			}
			fprintffullpstree(output, (*tmpptr).tree);
			fprintf (output, "\n");
		}
		tmpptr = (*tmpptr).sortnext;
	}

	if (!comment) {
		fprintf (output, "\n");
		switch(num) {
			case 1: fprintf (output, "There were no tree topologies (out of %d) occuring with a percentage \n>= %.2f%% of the %d puzzling steps.\n", itemnum, cutoff, itemsum); break;
			case 2: fprintf (output, "There was one tree topology (out of %d) occuring with a percentage \n>= %.2f%%.\n", itemnum, cutoff); break;
			default: fprintf (output, "There were %d tree topologies (out of %d) occuring with a percentage \n>= %.2f%%.\n", num-1, itemnum, cutoff); break;
		}
		fprintf (output, "\n");
		fprintf (output, "\n");
	}
	
}  /* fprintfsortedpstrees */

/**********/


/* print sorted tree topologies for checking */
void printfsortedpstrees(treelistitemtype *list)
{
	treelistitemtype *tmpptr = NULL;
	treelistitemtype *slist = NULL;

	sortbynum(list, &slist); 

	tmpptr = slist;
	while (tmpptr != NULL) {
		printf ("[%2d]  %5d     %s\n", (*tmpptr).idx, (*tmpptr).count, (*tmpptr).tree);
		tmpptr = (*tmpptr).sortnext;
	}
}  /* printfsortedpstrees */


/*******************************************/
/* end of tree sorting                     */
/*******************************************/