clear all;
close all;
clc;
format long;
tic
%----------- Data input from DataBase-------------------
% The PRD including Damage(Cv), I-V excess (P=Ci-Cv), calculated by IM3D

Files = dir(strcat('DataBase\\','*-depth_dist_functions.dat'));              % Windows environment
%Files = dir(strcat('DataBase/','*-depth_dist_functions.dat'));            % Linux environment

LengthFiles = length(Files);

%-----------------Nomenclature---------------------
%PDF-probability density function
%CDF-cumulative density function
%-------------------------------------------------------

%  PDF and CDF of I-V Excesses from IM3D
fid_Epdf= fopen('Outputs/ExcPDF-RawData.txt','w');
fid_Ecdf= fopen('Outputs/ExcCDF-RawData.txt','w');

% PDF and CDF of Damage from IM3D
fid_Dpdf= fopen('Outputs/DamPDF-RawData.txt','w');
fid_Dcdf= fopen('Outputs/DamCDF-RawData.txt','w');

for i =1:1:LengthFiles;
    depth=[];
    Ci=[];
    Cv=[];
    Exc=[];
str=[strcat('DataBase\',Files(i).name)];                                 % Windows environment
%str=[strcat('DataBase/',Files(i).name)];                              % Linux environment
str0=num2str(str(10:11));
A = importdata(str);

%Read PDF of damage and excesses in depth window of  0.045-2.085 ¦Ìm
depth   = (A(2:70,1) *30+15)/1000;
Ci = A(2:70,6)/30/1000000;
Cv = A(2:70,8)/30/1000000;

dep=depth';
dz = dep(2)-dep(1);
Exc=(Ci-Cv)';
%----------------------------------------------------------------------
%Output PDF of I-V Excess to a file
for j=1:length(dep)
  fprintf(fid_Epdf,'%s\t',str0);
  fprintf(fid_Epdf,'%20.15f\t',dep(j),Exc(j));
  fprintf(fid_Epdf,'\n');
end

% Excess PDF output checking
%subplot(2,1,1);plot(dep,Exc,'+'); hold on;

%Output CDF of I-V Excess to a file
Exc_cdf=dep*0;
Exc_temp=0;
for j=1:length(dep)
Exc_temp=Exc_temp+Exc(j)*dz;
Exc_cdf(j)=Exc_temp ;
end

for j=1:length(dep)
  fprintf(fid_Ecdf,'%s\t',str0);
  fprintf(fid_Ecdf,'%20.15f\t',dep(j),Exc_cdf(j));
  fprintf(fid_Ecdf,'\n');
end

% Excess CDF output checking
%subplot(2,1,2);plot(dep,Exc_cdf,'o'); hold on;
%--------------------------------------------------------------
%--------------------------------------------------------------
%Output Damage PDF data to a file.
for j=1:length(dep)
fprintf(fid_Dpdf,'%s\t',str0);
fprintf(fid_Dpdf,'%20.15f\t',dep(j),Cv(j));
fprintf(fid_Dpdf,'\n');
end

%%%%%%%%%%%%%%%%
%Damage PDF output checking
%subplot(2, 1, 1); plot(dep,Cv,'+'); hold on;

%%Output CDF data to a file.
Dam_cdf=dep*0;
Cv_temp=0;
for j=1:length(dep)
Cv_temp=Cv_temp+Cv(j)*dz;
Dam_cdf(j)=Cv_temp ;
end

for j=1:length(dep)
fprintf(fid_Dcdf,'%s\t',str0);
fprintf(fid_Dcdf,'%20.15f\t',dep(j),Dam_cdf(j));
fprintf(fid_Dcdf,'\n');
end
% Damage CDF output checking
%subplot(2, 1, 2); plot(dep,Dam_cdf,'o'); hold on;
end
toc
fprintf('%s','Data acquisition is done')