/*
** ライフゲーム  life.c  1995.02.23  By JOUJI
**
** Usage:life [-{fm|98}] life.dat
**
** d[y][x]:回りの生の数
** s[y]:今の状態を表す文字列
*/

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <jstring.h>

static char csroff[8]="\0";
static char csron[8]="\0";
static char t[20];
static char s[24][80];
static char d[26][41];

main(int argc,char *argv[])
{
	char *p,*q,*px,*qx,*fn,sw;
	int i,j,l,x,y,xm,ym,g,gm;
	FILE *fp;

	if (argc<2) {
		puts("Parameter error !\a\n");
		exit(1);
	}
	i = 1;
	for(i=1; i<argc; i++ ) {				/* オプションスイッチのチェック */
		if(argv[i][0] == '-') {
			sw = tolower(argv[i][1]);
			if(sw == 'f') {
				strcpy(csroff,"\x1b[1v");
				strcpy(csron,"\x1b[0v");
			} else if(sw == '9') {
				strcpy(csroff,"\x1b[>5h");
				strcpy(csron,"\x1b[>5l");
			}
		} else j = i;
	}
	fn = argv[j];
	if((fp=fopen(argv[j],"r")) == NULL) {	/* ファイルがない */
		puts("File not exist !\a");
		exit(1);
	}
	fprintf(stderr,"\x1b[2J%s",csroff);
	printf("%12s    世代 000\n", fn);
	for(i=0,xm=0; fgets(s[i],80,fp) != NULL; i++) {
		printf("%s", s[i]);
		l=jstrlen(s[i]);
		if(l>xm) xm = l;
	}
	fclose(fp);
	ym = i;
	for(g=gm=1;; g++) {
		fprintf(stderr,"世代増分('Q'で終了) >\x1b[0K");
		if(g<gm) {
			printf("\n");
		} else {
			fprintf(stderr,"%s",csron);
			gets(t);
			if(t[0]=='Q' || t[0]=='q') exit(0);
			fprintf(stderr,"%s",csroff);
			gm = g + atoi(t);
		}
		for(y=1,p=s[0]+1,q=d[0]; y<=ym; y++,p+=80,q+=41) {
			for( x=1,px=p; x<xm; x++,px+=2) {
				if(*px == '\x9c')
					for(j=0,qx=q+x-1; j<3; j++,qx+=38)
						for(i=0; i<3; i++,qx++)
							(*qx)++;
			}
		}
		for(y=1,p=s[0]+1,q=d[1]+1; y<=ym; y++,p+=80,q+=41) {
			for(x=1,qx=q; x<xm; x++,qx++) {
				if(*qx=='\0') continue;
				px = p+x+x-2;
				if(*qx=='\03') {
					*px = '\x9c';
				} else if(*qx!='\04') {
					*px = '\x40';
				}
				*qx = '\0';
			}
		}
		fprintf(stderr,"\x1b[%dA", ym+2);
		printf("%12s    世代 %03d\n", fn, g);
		for(y=0; y<ym; y++) {
			printf("%s", s[y]);
		}
	}
}
