[fitresult, gof] = createFit(X, Y);
vv = ppval(fitresult.p, X);
d1 = ppval(fnder(fitresult.p, 1), X);
nn = 1 ./ (d1 + epsilon);
largh = zeros(size(clu_sli, 1), 1);
scatter(clu_sli(:,1), clu_sli(:,2), 'r');
scatter(clu_sli(:,1), clu_sli(:,2), 'r');
plot(X, vv, 'b', 'LineWidth', 2);
quiver(X, vv, normal_x, normal_y, 0.5, 'k', 'LineWidth', 1);
intensity_profiles = cell(size(clu_sli, 1), 1);
vet_in = zeros(size(clu_sli, 1), 2);
vet_fin = zeros(size(clu_sli, 1), 2);
for kk = 1:size(clu_sli, 1)
x_profile = round(c + (-span:span) * normal_x(kk));
y_profile = round(r + (-span:span) * normal_y(kk));
valid_idx = x_profile > 0 & x_profile <= size(I, 2) & y_profile > 0 & y_profile <= size(I, 1);
x_profile = x_profile(valid_idx);
y_profile = y_profile(valid_idx);
profilo = I(sub2ind(size(I), y_profile, x_profile));
intensity_profiles{kk} = profilo;
largh(kk) = conv_crepa(profilo);
half_width = largh(kk) / 2;
segment_x = [c - half_width * normal_x(kk), c + half_width * normal_x(kk)];
segment_y = [r - half_width * normal_y(kk), r + half_width * normal_y(kk)];
vet_in(kk,1) = c - half_width * normal_x(kk);
vet_fin(kk,1) = c + half_width * normal_x(kk);
vet_in(kk,2) = r - half_width * normal_y(kk);
vet_fin(kk,2) = r + half_width * normal_y(kk);
plot(segment_x, segment_y, 'g', 'LineWidth', 2);
mean_width = mean(largh, 'omitnan');
std_width = std(largh, 'omitnan');
min_width = min(largh, [], 'omitnan');
max_width = max(largh, [], 'omitnan');
mean_widths = [mean_widths; mean_width];
std_widths = [std_widths; std_width];
min_widths = [min_widths; min_width];
max_widths = [max_widths; max_width];
all_x = [vet_in(:,1); flip(vet_fin(:,1))];
all_y = [vet_in(:,2); flip(vet_fin(:,2))];
valid_idx = ~isnan(all_x) & ~isnan(all_y);
all_x = all_x(valid_idx);
all_y = all_y(valid_idx);
if length(all_x) > 1 && (all_x(1) ~= all_x(end) || all_y(1) ~= all_y(end))
area = trapz(all_x, all_y);
title('Area Between Curves per Slice');
areas_mm = areas.* voxel_size^2
std_mm=std_widths.*voxel_size
mean_mm=mean_widths.*voxel_size
min_mm=min_widths.*voxel_size
max_mm=max_widths.*voxel_size