% global variables
global xTIE;
global yTIE;
global xX_WING;
global yX_WING;
global v2;
global vLaser;
global d; 
global w; 
global mu;
global t1;

% reading values from file
fid = fopen("input_outlab_task_A2.txt", "r");
[xTIE, yTIE, xX_WING, yX_WING, v2, vLaser, d, w, mu, t1, count, errmsg] = fscanf(fid, "%lf %lf %lf %lf %lf %lf %lf %lf %lf %lf", "C");
fclose(fid);


%(x1, y1) - position of x-Xwing relative to xTIE
global x1 = xX_WING - xTIE;
global y1 = yX_WING - yTIE;


% function which gives value of expression at x(1) - incident angle on smoke screen x(2) - refracted angle on smoke screen
% x(3) - y coordinate of x-Xwing relative to xTIE at the time of impact whose(expression's) value has to be made zero
function y = f(x)
	global x1;
	global y1;
	global v2;
	global vLaser;
	global d;
	global w;
	global mu;
	global t1;
	y= zeros(3,1);
	y(1) = (x(3) - w) * tand(x(1)) + w * tand(x(2)) - x1;
	y(2) = (v2/vLaser)*((x(3) - w)/(cosd(x(1))) + w * mu/(cosd(x(2)))) - x(3) + y1 + v2 * t1;
	y(3) = sind(x(1)) - mu * sind(x(2));
endfunction

% solving the equations using fsolve

%initial values for fsolve
yInitial = y1 + v2*t1;
i = atand(yInitial/x1);
r = asind(sind(i)/mu);

[x, fval, info] = fsolve("f", [i, r, yInitial]);

% writing (angle at which laser has to shot and the nearest position at which x-Xwing will get hit to the file )
output_ptr = fopen("output_outab_task_A2.txt", "w");
fprintf(output_ptr, "%.1f %.1f %.1f", x(1), x1, x(3));

fclose(output_ptr);
