/* (C) litchie.net, 2010 */

#include <stdio.h>

#define MAXLINES 9996
#define BUFSZ    999
char * lines[MAXLINES];
int nlines = 0;

int main(int c, char *v[]) {
    FILE *fp = stdin;
    int i, j;
    char buf[BUFSZ];
    
    srand(time(NULL));

    for (i = 1; i < c; i++) {
        if (strcmp(v[i], "-h")==0
            || strcmp(v[i],"--help") == 0) {
            fprintf(stderr,
                    "I am the black brother of sort, and I shuffles text lines, ha!\n"
                    "Usage: shuffle  [filename]\n"
                    "  If no file specified, read from stdin.\n"
                    "Bug report: \154ich\141oji AT \147mail DOT com\n");
            return -1;
        } else if (fp == stdin) {
            fp = fopen(v[i], "r");
            if (!fp) {
                fprintf(stderr, "Error: can not open `%s\' for read\n", v[i]);
                return -1;
            }
        } else {
            fprintf(stderr, "Warning: one time one file, `%s\' is skipped\n", v[i]);
        }
    }

    while (fgets(buf, BUFSZ, fp)) {
        if (nlines == MAXLINES) {
            i = rand()%(MAXLINES+1);
            if (i != MAXLINES) {
                printf("%s", lines[i]);
                free(lines[i]);
                lines[i] = (char*)malloc(strlen(buf)+1);
                strcpy(lines[i], buf);
            } else {
                printf("%s", buf);
            }
        } else {
            i = nlines++;
            lines[i] = (char*)malloc(strlen(buf)+1);
            strcpy(lines[i], buf);
        }
    }

    for (i = 0; i < nlines; i++) {
        char *t;
        j = i+rand()%(nlines-i);
        t = lines[j];
        lines[j] = lines[i];
        printf("%s", t);
    }
}
