/* The atsUNIX fortune(1) program
 * compilable in NorthC
 * Originally freeware by Adam Sampson
 * (c) 1995-2001 Adam Sampson
 * 
 * Fixed up and ported to real Unix 2001/02/09, Adam Sampson.
 * Released under the terms of the GNU General Public License
 * version 2 or, at the user's option, any later. version.
 */

/* This is not, of course, a very *good* fortune program, since it's biased
 * towards long fortunes... */

#define SEP "%\n"
#define MAXLINE 1000

#include <stdio.h>

int main(int argc, char **argv) {
    unsigned int length;
    char s[MAXLINE];
    FILE *f;
    if (argc < 1) {
        printf("usage: minifortune file\n");
	return 20;
    }
    f = fopen(argv[1], "r");
    if (f==NULL) {
        printf("fortune: can't open fortune file\n");
	return 20;
    }
     
    fseek(f, 0, SEEK_END);
    length = ftell(f);
    srand(time(NULL));
    fseek(f, rand() % length, SEEK_SET);
    do {
	if (!fgets(s, MAXLINE, f)) {
	    fseek(f, 0, SEEK_SET);
	    break;
	}
    } while (strcmp(s, SEP));
    while (fgets(s, MAXLINE, f) && strcmp(s, SEP)) {
	printf("%s", s);
    }
    fclose(f);
    
    return 0;
}

