#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, char * argv[]){
	
	if (argc != 3){
		fflush(stdout);
		printf("Error: not enough command line arguments entered. First should be the name of the input file, second should be the name of the output file.\n");
		return 1;
	}	

	FILE * fp;
	fp = fopen(argv[1],"r");

	if (fp == NULL){
		printf("Error: cannot open %s.\n",argv[1]);
		return 2;
	}
//	printf("Read file %s.\n",argv[1]);
	fflush(stdout);
	char * story = malloc(sizeof(char)* 10000);
	char newstory [10000];
	int i = 0;
	for (i = 0; i < 10000; i++){
		newstory[i] = '\0';
	}
	fread(story,sizeof(char),9999,fp);

	while (strchr(story,'(') != NULL){
//		printf("top of while");
		fflush(stdout);

		char * beginparen = strchr(story,'(');
		char * endparen = strchr(story, ')');
//		printf("after finds");
		fflush(stdout);
		strncat(newstory,story,beginparen - story);
		
//		printf("afterstrncat");
		fflush(stdout);

		char * field = malloc(sizeof(char) * 50);
		memset(field,'\0',50 * sizeof(char));
//		printf("field width is %d\n",(endparen - beginparen - 1));
		strncpy(field,beginparen + 1,endparen - beginparen - 1);
		printf("Please type a %s: ",field);	
		fflush(stdout);
		char fieldvalue[50];
		scanf("%s",fieldvalue);

		strcat(newstory,fieldvalue);

//		printf("story so far is: %s\n",newstory);

		story = endparen + 1;
//		printf("bottom of loop");
		fflush(stdout);
		free(field);
	}
	strcat(newstory,story);

	fclose(fp);	

	FILE * outfile;
	outfile = fopen(argv[2],"w");
	if (outfile == NULL){
		printf("Error: cannot open %s.\n",argv[2]);
		return 2;
	}
	fprintf(outfile,"Story is:\n%s",newstory);
	fclose(outfile);	


	return 0;
}
