function export_LFA_GoAmazon(labels,units,Instrument,Model,serial_num,Site,Val_level,Proc_vers,orig_size,time_X,X,size_part,distr_part)

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Written by Joel Brito - 22-Jan-2015
%
% Function designed to export instrument data according to the format used
% by the group of atmospheric physics from the university of Sao Paulo
%
% Update: Improved for level-2 and level-3 statistics
%
% orig_size->number of points of raw data prior level1 cut
% time_X->vector of time in matlab number (e.g. datenum(2014,11,16))
% X-> the variable to be exported. If more than one should be written then X
% can be a matrix (e.g. from TEOM X=[Fine;Coarse])
%
% If Val_level=2: the user shall use level1_5min as input to this code, after the
% required level2 corrections. Time should be converted from unix to matlab
% time. This code will then print the level2_5min file, and take 30min
% averages to print the level2_30min file.
%
% If exporting SMPS data:
%
% size_part: bins diamenters in nm
% distr_part: matrix with dimension n,p with n being size(size_part) and p being size(time_X)
%
% If not exporting SMPS data, simply ignore last two parameters.
%
% Example TEOM:
%
% Instrument='TEOM';
% Model='1405A';
% serial_num='518591108';
% site='T2';
% Val_level='1';
% Proc_vers='1.0';
% labels{1}='Fine';
% labels{2}='Coarse';
% units{1}='(ug m-3)';
% units{2}='(ug m-3)';
% export_LFA_GoAmazon(labels,units,Instrument,Model,serial_num,Site,Val_level,Proc_vers,orig_size,time_TEOM,[Fine;Coarse])
%
%
% Example SMPS:
%
% Instrument='SMPS TSI';
% Model='3082';
% serial_num='3082001415003';
% Site='T2';
% Val_level='1';
% Proc_vers='1.0';
% labels{1}='Total concentration';
% labels{2}='Mean diameter';
% labels{3}='Mean diameter';
% units{1}='(cm-3)';
% units{2}='(cm3)';
% units{3}='(nm)';
% export_LFA_GoAmazon(labels,units,Instrument,Model,serial_num,Site,Val_level,Proc_vers,orig_size,time_SMPS_TSI,[SMPS_TSI_CPC;SMPS_TSI_vol;mean_DPg],size_part,distr_part)
%
%
% Example Level 2:
% Instrument='CAPS';
% Model='Aerodyne';
% serial_num='114001';
% Site='T2';
% Val_level='2';
% Proc_vers='1.0';
% labels{1}='NO2';
% units{1}='(ppb)';
% % orig_size= sum(~isnan(level1_5min(:,2)));
% export_LFA_GoAmazon_jan2015(labels,units,Instrument,Model,serial_num,Site,Val_level,Proc_vers,orig_size,level1_5min(:,1),level1_5min(:,2))
%
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

fdir=['0_Ascii-files/Level',Val_level,'/'];
mkdir(fdir)
tol=-0.05/60/24; % tolerancia de -3 segundos no final de cada periodo
[anoi,~,~,~,~,~]=datevec(time_X(1,1));
[anof,~,~,~,~,~]=datevec(time_X(length(time_X),1));
startdate=datenum(2023,09,11); %datenum(anoi,1,1);
finaldate=datenum(2024,02,01); %datenum(anof+1,1,1);

%If X is a matrix, it places time as rows
[dummy,idx]=max(size(X));
if dummy>0
if idx==2
X=X';
end
end;

fname=[Site,'_',Instrument,'_',Model,'_Level',Val_level];

if strcmp(Val_level,'1')
header_1=['File generated on ',datestr(now),'; Level:',Val_level,'; Processing Version: ',Proc_vers,'; Amount of raw data removed: ',num2str((100.*(1- max(size(time_X))./orig_size)),2),'%%; Site: ',Site,'; Instrument: ',Instrument,'; Model:',Model,'; S/N: ',serial_num,'; Data processing details can be found in ftp://ftp.lfa.if.usp.br/LFA_Processed_Data/DataProcessing_GoAmazon_LFA.pdf'];
else
header_1=['File generated on ',datestr(now),'; Level:',Val_level,'; Processing Version: ',Proc_vers,'; Amount of data removed from level 1: ',num2str((100.*(1- sum(~isnan(X(:,1)))./orig_size)),2),'%%; Site: ',Site,'; Instrument: ',Instrument,'; Model:',Model,'; S/N: ',serial_num,'; Data processing details can be found in ftp://ftp.lfa.if.usp.br/LFA_Processed_Data/DataProcessing_GoAmazon_LFA.pdf'];
end
header='Time(UTC); UnixTime(UTC); ';

stat_name{1}=' Mean ';
stat_name{2}=' std ';
stat_name{3}=' Median ';
stat_name{4}=' p25 ';
stat_name{5}=' p75 ';
stat_name{6}=' Min ';
stat_name{7}=' Max ';
stat_name{8}=' # of samples ';

if strcmp(Val_level,'1')||strcmp(Val_level,'0');

for i=1:max(size(labels))
for j=1:7
header=[header, labels{i}, stat_name{j}, units{i},'; '];
end;

end

if nargin==13
[dummy,idx]=max(size(distr_part));
if dummy>0
if idx==1
distr_part=distr_part';
end
end;
for i=1:max(size(size_part))
header=[header, num2str(size_part(i)), '; '];
end;
end
header=[header stat_name{8}];

% Creates the file for 5min and writes first and second header
fid = fopen([fdir,fname,'_5min.csv'],'wt');
fprintf(fid,[header_1, '\n']);
fprintf(fid,[header, '\n']);

%Writes 5 minute datafile
for i=startdate:5/(24*60):finaldate
dummy_X=X(time_X>=i&time_X<(i+5./(24*60))+tol,:);
%!!! Na linha acima, troquei <= por <
%!!! E tambim tirei 3 segundos do final do permodo
if max(size(dummy_X,1))==0
for j=1:max(size(dummy_X,2))
dummy_X(1,j)=NaN;
end
if nargin==13
dummy_distr=ones(size(size_part));
dummy_distr(dummy_distr==1)=NaN;
end;
else
if nargin==13
dummy_distr=nanmean(distr_part(:,time_X>=i&time_X<(i+5./(24*60))+tol),2);
%!!! Na linha acima, troquei <= por <
%!!! E tambim tirei 3 segundos do final do permodo
end;
end
fprintf(fid,'%s; %2.0f',datestr(i,'dd-mmm-yyyy HH:MM'),24*60*60*(i-datenum(1970,01,01)));
for j=1:max(size(dummy_X,2))
fprintf(fid,'; %2.2f; %2.2f; %2.2f; %2.2f; %2.2f; %2.2f; %2.2f',nanmean(dummy_X(:,j)),nanstd(dummy_X(:,j)),nanmedian(dummy_X(:,j)),prctile(dummy_X(:,j),25),prctile(dummy_X(:,j),75),nanmin(dummy_X(:,j)),nanmax(dummy_X(:,j)));
end;
if nargin==13
fprintf(fid,['; ', repmat('%2.1f; ', 1, size(size_part, 2)),' %2.0f\n'],dummy_distr,size(dummy_X(isnan(dummy_X(:,1))==0),1));
else
fprintf(fid,'; %2.0f\n',size(dummy_X(isnan(dummy_X(:,1))==0),1));
end;

end
fclose(fid);

%Creates the 30 min file for level1 data
% Creates the file for 30min and writes first and second header
fid = fopen([fdir,fname,'_30min.csv'],'wt');
fprintf(fid,[header_1, '\n']);
fprintf(fid,[header, '\n']);

%Writes 30 minute datafile
for i=startdate:30/(24*60):finaldate
dummy_X=X(time_X>=i&time_X<(i+30./(24*60))+tol,:);
%!!! Na linha acima, troquei <= por <
%!!! E tambim tirei 3 segundos do final do permodo
if max(size(dummy_X,1))==0
for j=1:max(size(dummy_X,2))
dummy_X(1,j)=NaN;
end
if nargin==13
dummy_distr=ones(size(size_part));
dummy_distr(dummy_distr==1)=NaN;
end;
else
if nargin==13
dummy_distr=nanmean(distr_part(:,time_X>=i&time_X<(i+30./(24*60))+tol),2);
%!!! Na linha acima, troquei <= por <
%!!! E tambim tirei 3 segundos do final do permodo
end;
end
fprintf(fid,'%s; %2.0f',datestr(i,'dd-mmm-yyyy HH:MM'),24*60*60*(i-datenum(1970,01,01)));
for j=1:max(size(dummy_X,2))
fprintf(fid,'; %2.2f; %2.2f; %2.2f; %2.2f; %2.2f; %2.2f; %2.2f',nanmean(dummy_X(:,j)),nanstd(dummy_X(:,j)),nanmedian(dummy_X(:,j)),prctile(dummy_X(:,j),25),prctile(dummy_X(:,j),75),nanmin(dummy_X(:,j)),nanmax(dummy_X(:,j)));
end;
if nargin==13
fprintf(fid,['; ', repmat('%2.1f; ', 1, size(size_part, 2)),' %2.0f\n'],dummy_distr,size(dummy_X(isnan(dummy_X(:,1))==0),1));
else
fprintf(fid,'; %2.0f\n',size(dummy_X(isnan(dummy_X(:,1))==0),1));
end;

end
fclose(fid);

else % level 2 or 3
for i=1:max(size(labels))
header=[header, labels{i}, stat_name{1}, units{i},'; '];
end

if nargin==13
[dummy,idx]=max(size(distr_part));
if dummy>0
if idx==1
distr_part=distr_part';
end
end;
for i=1:max(size(size_part))
header=[header, num2str(size_part(i)), '; '];
end;
end

% Creates the file for 5min and writes first and second header
fid = fopen([fdir,fname,'_5min.csv'],'wt');
fprintf(fid,[header_1, '\n']);
fprintf(fid,[header, '\n']);

count=0;
%Writes 5 minute datafile (level 2)
for i=startdate:5/(24*60):finaldate
count=count+1;
dummy_X=X(time_X>=i&time_X<(i+5./(24*60))+tol,:);
time_mean_X(count)=i;
%!!! Na linha acima, troquei <= por <
%!!! E tambim tirei 3 segundos do final do permodo
if max(size(dummy_X,1))==0
for j=1:max(size(dummy_X,2))
dummy_X(1,j)=NaN;
end
if nargin==13
dummy_distr=ones(size(size_part));
dummy_distr(dummy_distr==1)=NaN;
end;
else
if nargin==13
dummy_distr=nanmean(distr_part(:,time_X>=i&time_X<(i+5./(24*60))+tol),2);
%!!! Na linha acima, troquei <= por <
%!!! E tambim tirei 3 segundos do final do permodo
end;
end
fprintf(fid,'%s; %2.0f',datestr(i,'dd-mmm-yyyy HH:MM'),24*60*60*(i-datenum(1970,01,01)));
for j=1:max(size(dummy_X,2))
fprintf(fid,'; %2.2f',nanmean(dummy_X(:,j)));
mean_X(count,j)=nanmean(dummy_X(:,j));
end;
if nargin==13
fprintf(fid,[repmat('; %2.1f ', 1, size(size_part, 2)),'\n'],dummy_distr);
else
fprintf(fid,'\n');
end;
end
fclose(fid);

%Creates the 30 min file for level2 data
% Creates the file for 30min and writes first and second header
fid = fopen([fdir,fname,'_30min.csv'],'wt');
fprintf(fid,[header_1, '\n']);
fprintf(fid,[header, '\n']);

%Writes 30 minute datafile
for i=startdate:30/(24*60):finaldate
dummy_X=mean_X(time_mean_X>=i&time_mean_X<(i+30./(24*60))+tol,:);
%!!! Na linha acima, troquei <= por <
%!!! E tambim tirei 3 segundos do final do permodo
if max(size(dummy_X,1))==0
for j=1:max(size(dummy_X,2))
dummy_X(1,j)=NaN;
end
if nargin==13
dummy_distr=ones(size(size_part));
dummy_distr(dummy_distr==1)=NaN;
end;
else
if nargin==13
dummy_distr=nanmean(distr_part(:,time_X>=i&time_X<(i+30./(24*60))+tol),2);
%!!! Na linha acima, troquei <= por <
%!!! E tambim tirei 3 segundos do final do permodo
end;
end
fprintf(fid,'%s; %2.0f',datestr(i,'dd-mmm-yyyy HH:MM'),24*60*60*(i-datenum(1970,01,01)));
for j=1:max(size(dummy_X,2))
fprintf(fid,'; %2.2f',nanmean(dummy_X(:,j)));
mean_X(count,j)=nanmean(dummy_X(:,j));
end;
if nargin==13
fprintf(fid,[repmat('; %2.1f ', 1, size(size_part, 2)),'\n'],dummy_distr);
else
fprintf(fid,'\n');
end;

end
fclose(fid);

end;

end