/* sorting functions */

/*

Copyright (C) 1995 Andrew Tefft. I liked Henry Spencer's terms so:

        Permission is granted to anyone to use this software for any
        purpose on any computer system, and to redistribute it freely,
        subject to the following restrictions:

        1. The author is not responsible for the consequences of use of
                this software, no matter how awful, even if they arise
                from defects in it.

        2. The origin of this software must not be misrepresented, either
                by explicit claim or by omission.

        3. Altered versions must be plainly marked as such, and must not
                be misrepresented as being the original software.

*/


#include "mr.h"
#include "externs.h"

void swap();
int compare();

void sort(keys) 
int keys;
{
  int i,j;

    for (i=0; i<number; i++)
      for (j=i; j<number; j++)
	if (compare(i,j,keys) > 0) 
	  swap(i,j);
}


/* compare returns 1 if first item is less than the second
 based on what the things are (i.e. dates oldest -> newest,
 hits most -> least, etc. */

int compare(x,y,what)
  int x,y,what;
    {
      char *c1,*c2;
      int re1, re2;

      if (what == HITS) return
	messages[x]->hits < messages[y]->hits;
      else if (what == SEQUENCE) return
	messages[x]->sequence > messages[y]->sequence;
      else if (what == DATE) return
	messages[x]->date > messages[y]->date;
      else if (what == HEADER) return
	strncmp(messages[x]->hdr, messages[y]->hdr, HDR_ADDR);
      else if (what == SUBJECT) {
	c1=(messages[x]->hdr)+HDR_SUBSTART;
	c2=(messages[y]->hdr)+HDR_SUBSTART;

	/* check for re:'s */

	re1=0; re2=0;
	if (!strncasecmp(c1,"re: ",4)) re1=1; 
	if (!strncasecmp(c2,"re: ",4)) re2=1;
		
	/* if both have them, compare on part after re: */
	
	if (re1 && re2) {
	  c1 = strchr(c1,' ');
	  c2 = strchr(c2,' ');
	  c1 = skip_whitespace(c1);
	  c2 = skip_whitespace(c2);
	  return (strcasecmp(c1,c2));
	}

/* if neither has them, just compare */

	else if (!re1 && !re2) 
	  return strcasecmp(c1,c2);


/* if one has one, we need to strip it off and then compare.
   if they end up being the same, the re: comes second. */

	else {
	  if (re1) {
	    c1 = strchr(c1,' ');
	    c1 = skip_whitespace(c1);
	  }
	  if (re2) {
	    c2 = strchr(c2,' ');
	    c2 = skip_whitespace(c2);
	  }
	  if (re2=strncasecmp(c1,c2,HDR_SUBJ-5))  return re2;
	  else return re1;  /* save us a variable */
	  
	  
	}			
      }
    }
   
void swap(x,y)
	int x,y;
{
	struct message *temp;

	temp = messages[x];
	messages[x]=messages[y];
	messages[y]=temp;

      }
