/*
    rand.c - A program that sends random system commands.
    Copyright (C) 1995 Fergus Duniho

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; version 2 of the License.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <fpd/fpdio.h>
#include <fpd/fpdstrm.h>

void setseed ();

int main (int argc, char **argv) {
    unsigned int i, j, which, maximum;
    char lines[256], line[256], fname[256];
    FILE *fptr;

    if (argc < 2)
        fprintf (stderr,
        "Usage: rand <file> <format_string> [<file> <format> ...]\n"
        "$VER: rand v1.00 (7 Jan 1995)\n"
        "Copyright 1995 Fergus Duniho\n");

    setseed();
    for (i = 1; i < argc; i+=2) {
        if ((fptr = fopen(argv[i], "r")) == NULL) {
            fprintf (stderr, "Couldn't find %s.\n", argv[i]);
            continue;
        }
        maximum = fgetp(fptr);
        which = rand() % maximum;
        for (j = 0; j < which; j++)
            next (fptr, '\n');
        getline (fptr, fname, 256);
        fclose (fptr);
        repstr (lines, argv[i+1], "[]", fname, -1);
        while ((j = strcspn(lines, ";")) != 0) {
            restring (line, lines, lines, "", 0, j, 1);
            system (line);
        }
    }
}

void setseed () {
    FILE *fptr;
    int seed;

    if ((fptr = fopen("SYS:Prefs/randseed", "r")) != NULL) {
        seed = fgetp(fptr);
        fclose (fptr);
    }
    else
        seed = 1;
    srand (seed);
    if ((fptr = fopen("SYS:Prefs/randseed", "w")) != NULL) {
        fprintf (fptr, "%d", rand());
        fclose (fptr);
    }
}
