/* by Paul Kienitz, 5/18/89.  Public domain. */

#include <Paul.h>

main()
{
    char where[256], oldspec[256];
    FILE *m;
    bool FindCON();
    void DOIT();

    puts("\nThis program will surgically replace the CON: window spec in a");
    puts("copy of the MORE program that came with your Amiga.  See the file");
    puts("\"Fenestrate.readme\" for hints on what sort of changes to make.");
    puts("\nFirst I need the pathname of the copy of More to work on,");
    puts("like maybe SYS:Utilities/More or C:More.");
    for (;;) {
	put("\nWhere is it?  [return to quit]  ");
	if (!gets(where) || !strlen(where)) {
	    puts("\nOkay, forget it.");
	    Delay(30L);
	    exit(5);
	}
	if (m = fopen(where, "r+")) {
	    if (FindCON(m, oldspec))
		DOIT(oldspec, m);
	    else
		puts("\nCouldn't find a window spec in that file.");
	    fclose(m);
	} else
	    puts("\nCouldn't find anything there.");
    }
}



bool FindCON(m, oldspec) FILE *m; str oldspec;
{
    int c;
    long p;

    for (;;) {
	do c = getc(m); while (c != EOF && toupper(c) != 'C');
	if (feof(m)) return (false);
	if (ferror(m)) {
	    puts("\nGaah!  Read error in trying to search the file!");
	    return (false);
	}
	if (toupper(getc(m)) == 'O' && toupper(getc(m)) == 'N' &&
			getc(m) == ':' && getc(m) > ' ') {
	    fseek(m, -5L, 1);  /* back up to beginning of CON:... */
	    p = ftell(m);
	    c = fread(oldspec, 1, 255, m);
	    oldspec[255] = 0;
	    if (!c) {
		puts("\nGaah!  Read error in trying to search the file!");
		return (false);
	    }
	    if (strlen(oldspec) > 250) {
		puts("\n**** Something's wrong; the window spec string is");
		puts("**** too long!  Proceed at your own risk!");
	    }
	    fseek(m, p, 0);   /* position for rewriting */
	    return (true);
	}
    }
}



void DOIT(oldspec, m) str oldspec; FILE *m;
{
    char spec[256];
    int l, ll, g;

    for (;;) {
	puts("The old window spec is as follows:");
	put("   ");
	puts(oldspec);
	put("Your new specification?  [return to quit]  ");
	if (gets(spec) && (l = strlen(spec)) > 3) {
	    if (l <= strlen(oldspec)) {
		put("CONFIRM:  Your new spec is \"");
		put(spec);
		put("\".\nType Y to go ahead and put it in: ");
		if ((g = toupper(getchar())) == 'Y') {
		    ll = fwrite(spec, 1, l + 1, m);
		    if (ll != l + 1) {
			puts("\nGAAAH!  The write failed!");
			if (ll) 
			    puts("AND THE FILE IS PROBABLY CORRUPT NOW!");
			else
			    puts("I think the file is unchanged.");
		    } else puts("\nAll done.");
		    exit(0);
		} else
		    puts("\nOkay, I'll let you retype it.");
		while (g && g != '\n') g = getchar();
	    } else
		puts("\nSorry, the new spec CANNOT be longer than the old one.");
	} else {
	    puts("\nOkay, forget it.");
	    Delay(30L);
	    exit(5);
	}
    }
}
