#define _CRT_SECURE_NO_WARNINGS
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include "header.h"

int main() {
	FILE* fp;
	FILE* fg;
	FILE* fw;
	double a;
	double b;
	int n;
	char funcc[2][3] = { "fs","fg" };
	char path_grid[100];
	char path_weights[100];
	char path_poly[100];
	double* xh;
	double* yh;
	double** h;
	double* p;
	double* coefs;
	int start_n, end_n;
	start_n = 100;
	end_n = 100;

	int start_pow, end_pow;
	start_pow = 4;
	end_pow = 4;

	int change = 0;
	int change_amount = 3;
	for (int c = 0;c <= 3*change;c++) {
		for (int f_i = 0; f_i < 2; f_i++) {
			if (f_i == 0) {
				a = -2;
				b = 4;
			}
			if (f_i == 1) {
				a = 0;
				b = 5;
			}
			for (int pow = start_pow;pow <= end_pow;pow++) {
				for (n = start_n;n <= end_n;n += 10) {
					if (change) {
						snprintf(path_poly, 100, "lab9_interpol/a_poly_%s_%d_%d.txt", funcc[f_i], pow, c);
						snprintf(path_grid, 100, "lab9_interpol/a_grid_%s_%d_%d.txt", funcc[f_i], pow, c);
						snprintf(path_weights, 100, "lab9_interpol/a_weights_%s_%d.txt", funcc[f_i],c);
						p = change_p(n, 4,c,change_amount);
						fw = fopen(path_weights, "w+");
						if (fw == NULL) {
							exit(10);
						}
						for (int i = 0;i < n;i++) {
							fprintf(fw, "%lf", p[i]);
							if (i != n - 1) {
								fprintf(fw, "\n");
							}
						}
					}
					else {
						snprintf(path_poly, 100, "lab9_interpol/poly_%s_%d_%d.txt", funcc[f_i], pow, n);
						snprintf(path_grid, 100, "lab9_interpol/grid_%s_%d_%d.txt", funcc[f_i], pow, n);
						p = malloc(sizeof(double) * n);
						for (int i = 0;i < n;i++) {
							p[i] = 1;
						}
					}
					
					
					
					if (f_i == 0) {
						h = generate_ugrid(f1, n, a, b);
					}
					else {
						h = generate_ugrid(f2, n, a, b);
					}
					xh = malloc(sizeof(double) * n);
					yh = malloc(sizeof(double) * n);
					for (int i = 0; i < n;i++) {
						xh[i] = h[i][0];
						yh[i] = h[i][1];
					}
					printf("%s\n", path_poly);
					fg = fopen(path_grid, "w+");
					if (fg == NULL) {
						exit(10);
					}
					fp = fopen(path_poly, "w+");
					if (fp == NULL) {
						exit(10);
					}

					
					for (int i = 0;i < n;i++) {
						fprintf(fg, "%.25lf %.25lf", h[i][0], h[i][1]);
						if (i != n - 1) {
							fprintf(fg, "\n");
						}
					}
					fclose(fg);
					coefs = MLS_coef(xh, yh, p, pow, n);
					
					for (double x = a;x < b - (double)(b - a) / 10000;x += (double)(b - a) / 10000) {
						
						fprintf(fp, "%lf %lf", x, MLS(x,coefs,pow));

						if (x <= b - (double)(b - a) / 5000) {
							fprintf(fp, "\n");
						}
					}
					
					fclose(fp);
					free(xh);
					free(yh);
					for (int i = 0;i < n;i++) {
						free(h[i]);
					}
					free(h);
					free(p);
					
				}
			}

		}
	}

	return 0;
}