#include <stdio.h>
#include <math.h>

main()
{
	printf("\n\tf(t) = 5t + [sin(9t-5)]/t Numerical Integration Program\n");

	float start_pt, end_pt, steps, switched, split_pt, steps_left, steps_right, h, t, height;
	int i;
	char user_selection = '\0';

	FILE *output;
	output = fopen("output.txt", "w");
	fprintf(output, "    t\t\tx(t)\n  -----\t\t-----\t\t\n", "w");
	
	do
	{	
		while (1)
		{
			printf("\nEnter Start Point: ");
			scanf("%f", &start_pt);
			printf("\nEnter End Point: ");
			scanf("%f", &end_pt);

			if (start_pt == 0 || end_pt == 0)
			{
				printf("\nSorry t = 0 is not defined\n");
			}
			else
			{
				printf("\nEnter Number of steps: ");
				scanf("%f", &steps);
				break;
			}
		}

		if (start_pt > end_pt)
		{
			switched = start_pt;
			start_pt = end_pt;
			end_pt = switched;
		}

		if (start_pt < 0 && end_pt > 0)
		{
			split_pt = end_pt;
			end_pt = -0.001;
			steps_left = ((end_pt - start_pt) / (split_pt - start_pt) * steps);

			h = (end_pt - start_pt) / steps_left;

			for (i = 0; i < steps_left; i++)
			{
				t = start_pt + (i*h);
				fprintf(output, "%f\t", t);
				height = (5*(t + (h/2)) + ((sin(9*(t + (h/2)) - 5))/(t + (h/2))));
				fprintf(output, "%f\n", height);
			}

			start_pt = 0.001;
			end_pt = split_pt;
			steps_right = steps - steps_left;

			h = (end_pt - start_pt) / steps_right;

			for (i = 0; i < steps_right; i++)
			{
				t = start_pt + (i*h);
				fprintf(output, "%f\t", t);
				height = (5*(t + (h/2)) + ((sin(9*(t + (h/2)) - 5))/(t + (h/2))));
				fprintf(output, "%f\n", height);
			}
			
		}
		else
		{
			h = (end_pt - start_pt) / steps;

			for (i = 0; i < steps; i++)
			{
				t = start_pt + (i*h);
				fprintf(output, "%f\t", t);
				height = (5*(t + (h/2)) + ((sin(9*(t + (h/2)) - 5))/(t + (h/2))));
				fprintf(output, "%f\n", height);
			}
		}
				
		printf("\nDo you want to quit (y/n)?: ");
		scanf("%s", &user_selection);

	}
	while (user_selection != 'y');

	fclose(output);
}
