#include <stdio.h>
#include <ctype.h>

void change_case(FILE *, FILE *, char);
int count_words(char c);
int count_sentence(char c);
int min_max(char c);
void find_num(FILE *, FILE *);


int main(int argc, char *argv[])
{
	char c;
	int w_count = 0;
	int i, s;
	int s_count = 0;
	char str[10];


	FILE *in = fopen(argv[1], "r");
	if(in == NULL)
	{
		fprintf(stderr, "File %s could not be read", argv[1]);
		return 2;
	}

	FILE *out = fopen(argv[2], "w");
	if(out == NULL)
	{
		fprintf(stderr, "File %s can not be written to", argv[2]);
		return 2;
	}

	fprintf(out,"********************************************************************************\n");
	fprintf(out,"Below is the text that, for each character, the case has been changed. There are\n");
	fprintf(out,"also integers included in this text.  The integer value has not been altered.\n");
	fprintf(out,"********************************************************************************\n");

		       
	while((c = getc(in)) != EOF)
	{

		change_case(in, out, c);
		i = count_words(c);
		w_count += i;
		s = count_sentence(c);
		s_count += s;
		

	}

	fprintf(out,"*****************\n");
	fprintf(out,"W_count is:%5i\n", (w_count + 1));
	fprintf(out,"S_count is:%5i\n", s_count);
	fprintf(out,"*****************\n");

	rewind(in);
	find_num(in, out);

}

int count_words(char c)
{
	if(c == ' ')
	{
		return 1;
	}

	return 0;
}


void change_case(FILE *in, FILE *out, char c)
{
	
	//upper to lower 
	if(c >= 65 && c <= 90)
	{
		c += 32;
		putc(c, out);
	}
	else if (c >= 97 && c <= 122)
	{
		c -= 32;
		putc(c, out);
	}
	else
	{
		putc(c,out);
	}
}

int count_sentence(char c)
{
	if((c == '!') || (c == '?') || (c == '.'))
	{
		return 1;
	} 
	else
	{
		return 0;
	}
}

void find_num(FILE *in, FILE *out)
{	
	char c;
	int num[20];
	int index = 0;
	int i;
	int sum = 0;
	int ave = 0;

	fprintf(out,"***************************\n");
	fprintf(out,"Below is a list of the     \n");
	fprintf(out,"integers scattered in this\n");
	fprintf(out,"file\n");
	fprintf(out,"***************************\n");
	while((c = getc(in)) != EOF)
	{
		if(isdigit(c) == 1)
		{
			ungetc(c,in);
			fscanf(in, "%d", &num[index]);
			fprintf(out, "%d\n", num[index]);
			index++;
			
		}
	}
	for(i = 0; i < index; i++)
	{
		sum += num[i];
	}
	ave = sum/index;

	fprintf(out,"*****************\n");
	fprintf(out,"Sum is:    %5d\n", sum); 
	fprintf(out,"Ave is:    %5d\n", ave);
	fprintf(out,"*****************\n");
}

