/* Sort alphabetically   */

#include  "libc.h"

#define LINES 200  /* max  of lines to be sorted*/
#define MAXLEN 130  /* max line length */
 
main(argc,argv)    /*  open input and output files*/
int argc;
char *argv[];

{	int c, f1,f2;

	FILE *f1, *f2, *fopen();

	    if((f1 = fopen(argv[1],"r"))    == NULL) {
	    	printf("Can't find %s\n",argv[1]);
		goto error;
		}
	    else{if((f2 = fopen(argv[2],"w")) == NULL){
		    printf("Can't open %s\n",argv[2]);
		    goto error;
		    }
		else{    /*files ok ... sort  */

	char *lineptr[LINES]; /*points to text lines*/
	int nlines;	  /*number of input lines*/

	if ((nlines = readlines(lineptr,LINES,f1)) >=0){
	    sort(lineptr, nlines);
	    writelines(lineptr, nlines,f2);
	}
	else
	    printf("input too big to sort\n");

	error:
	fclose(f1);
	fclose(f2);
	exit(0);
	}
    }
}

readlines(lineptr, maxlines,fp)	/* read input lines */
char *lineptr[];		/* for sorting  */
int maxlines;
FILE *fp;
 {
    int len, nlines;
    char *p, *alloc(), line[MAXLEN];

    printf("input lines to be sorted \n");
    nlines = 0;
    while ((len = getline(line,MAXLEN,fp)) > 0)
	if (nlines >= maxlines)
	    return(-1);
	else if ((p = alloc(len)) == NULL)
	    return(-1);
	else {
	    line[len-1] = '\0';  /* zap newline */
	    strcpy(p, line);
	    lineptr[nlines++] = p;
	}
    return(nlines);
}

writelines(lineptr, nlines,fp)	/* write output lines */
char *lineptr[];
int nlines;
FILE *fp;
{
    int i;

    for (i = 0; i < nlines; i++) {
	fputs(lineptr[i],fp);
	aputc('\n',fp);
	}
}

sort(v,n)	/*sort strings v[0]...v[n-1] */
char *v[];	/* into increasing order */
int n;
{
    int gap, i, j;
    char *temp;

    printf("sort 'em\n");
    for(gap = n/2; gap > 0; gap /= 2)
	for (i = gap; i < n; i++)
	    for (j = i-gap; j >= 0; j -= gap) {
		if (strcmp(v[j], v[j+gap]) <=0)
		    break;
		temp = v[j];
		v[j] = v[j+gap];
		v[j+gap] = temp;
	    }
} 

getline(s,lim,fp)	/* get line in s,return length */
char s[];
int lim;
FILE *fp;
{
    int c, i;

    i = 0;
    while (--lim > 0 && (c=agetc(fp))!=EOF && c != '\n')
	s[i++] = c;
    if (c == '\n')
	s[i++] = c;
    s[i] = '\0';
    return(i);
}
