clear
%clc
%select the files

[file,path] = uigetfile('*.hpf','MultiSelect','On');
%options from selection
if isequal(file,0)
   error('Error occured: no file selected');
else
   %disp(['selected file:', fullfile(path,file)]);
   InputFile=fullfile(path,file);
   %count number of files
   if ischar(file)
       file={file};
   end
   numofinputs=length(file);
end
disp(['Number of files selected: ',num2str(numofinputs)])
%get the number of decimals after zero
prompt={'Enter number of decimals'};
dlgtitle = 'Number of decimals';
dims=[1 200];
answer = inputdlg(prompt,dlgtitle,[1 50]);
numof_dec=str2double(answer);  %number of decimals
%field width if fixed field width required:
%fieldwidth=10;
%data calculations
tic;
for n=1:numofinputs
    %---------------------------------------------------------------------%
    %1 file selected
    if numofinputs==1           
        clear filepath
        clear name
        [filepath, name, ~]=fileparts(InputFile);
        clear hpfdata
        clear data
        %get the number of channels
        pos=0;
        in.file = fopen(InputFile);                               % pens the file locate in dat.in, for binary read access, and returns an integer file identifier equal to or greater than 3
            while ~feof(in.file)                                  % wait till the End of the file
            in.chunkID = fread(in.file, 1, 'int64');              % Read the  values into a 1-by-0 array. Specify that the source data is class uint64
            off = fread(in.file, 1, 'int64');                     % number of Data available  
                if feof(in.file) || off == 0                      % look if the end of the file is reached or the data are finish
                break; 
                end    
                switch in.chunkID         
                    case 8192
                        in.XMLdata = fread(in.file, off-(ftell(in.file)-pos), 'char');
                        %transform the file
                        in.XMLdata = in.XMLdata'; 
                        start = strfind(in.XMLdata, '<Name>');
                        % display the total number of channels
                        numofch=length(start);
                end
            Position = off - (ftell(in.file) - pos) ;%
            fseek(in.file, Position, 0); % jump over offset to go to the next chunk
            pos = ftell(in.file);
            end
        fclose(in.file);
        %get hpf data from ReadHPFdata
        t0_1=toc;
            for i=1:numofch
                hpfdata=ReadHPFdata(i,InputFile);
                data(:,i+1)=hpfdata.ReturnData;
                meas_type(:,i)={'Time Waveform'};
                ch_name(:,i)={hpfdata.Name};
                ch_unit_x(:,i)={'Sec'};
                ch_unit_y(:,i)={hpfdata.Unit};
                ch_vartype(:,i)={'Real'};
            end
        %first column = time    
        data(:,1)=hpfdata.TimeAxis;
        t0_2=toc;
        %define textfile via extension 
        ext='.txt';
        %disp(['--Busy estimating format ',num2str(n),' of ',num2str(numofinputs)]);
        %format for textfile
        t1=toc;
        %variable format for textfile
        format=[repmat((['%.',num2str(numof_dec),'f\t ']), 1, size(data,2)-1), (['%.',num2str(numof_dec),'f\t\n'])];
        %fixed field width = fixed number of significant digits
        % format=[repmat((['%',num2str(fieldwidth),'.',num2str(numof_dec),'f\t ']), 1, size(data,2)-1), (['%',num2str(fieldwidth),'.',num2str(numof_dec),'f\t\n'])]
        %old fix format:
        %format=[repmat('%.5f\t ', 1, size(data,2)-1), '%.5f\t\n'];
        %disp('---Done');
        t2=toc;
        disp(['--Busy writing textfile ',num2str(n),' of ',num2str(numofinputs)]);
        t3=toc;
        %write to .txt file
        %open textfile / save it under the same name as the raw data
        fid=fopen(fullfile(filepath, strcat(name,ext)),'w');
        %write header
        fprintf(fid,['QuickDAQ Data','\n']);
        fprintf(fid,[hpfdata.RecordingDate,'\n']);
        fprintf(fid,['Notes:','\n']);
        fprintf(fid,['SampleRate: ','\t', num2str(1/str2double(hpfdata.TimeIncrement)),'\t', 'Hz','\n']);
        fprintf(fid,['Measurement Type:','\t',(strjoin(meas_type)),'\n']);
        fprintf(fid,['Channel Name:','\t',strjoin(ch_name),'\n']);
        fprintf(fid,['X Axis Units:','\t',strjoin(ch_unit_x),'\n']);
        fprintf(fid,['Y Axis Units:','\t',strjoin(ch_unit_y),'\n']);
        fprintf(fid,['Seconds','\t',strjoin(ch_vartype),'\n']);
        %write data
        fprintf(fid,format,data.');
        %close file
        fclose(fid);
        t4=toc;
        disp('---Done');
        %display the used files
        disp(['<strong>','Import file: ',fullfile(path,file{n}),'</strong>']);
        disp(['<strong>','Export file: ',fullfile(filepath, strcat(name,ext)),'</strong>']);
        %get filesize
        s=dir((fullfile(filepath, strcat(name,ext)))); 
        filesize=s.bytes/10^9;  %in GB
    %---------------------------------------------------------------------%
    %more than 1 file selected
    elseif numofinputs>=1
        clear filepath
        clear name
        [filepath, name, ~]=fileparts(InputFile{n});
        clear hpfdata
        clear data
        %get the number of channels
        pos=0;
        in.file = fopen(InputFile{n});                  % pens the file locate in dat.in, for binary read access, and returns an integer file identifier equal to or greater than 3
            while ~feof(in.file)                        % wait till the End of the file
            in.chunkID = fread(in.file, 1, 'int64');    % Read the  values into a 1-by-0 array. Specify that the source data is class uint64
            off = fread(in.file, 1, 'int64');           % number of Data available  
                if feof(in.file) || off == 0            % look if the end of the file is reached or the data are finish
                break; 
                end    
            switch in.chunkID         
                case 8192
                    in.XMLdata = fread(in.file, off-(ftell(in.file)-pos), 'char');
                    %transform the file
                    in.XMLdata = in.XMLdata'; 
                    start = strfind(in.XMLdata, '<Name>');
                    % display the total number of channels
                    numofch=length(start);
            end
            Position = off - (ftell(in.file) - pos) ;%
            fseek(in.file, Position, 0); % jump over offset to go to the next chunk
            pos = ftell(in.file);
            end
        fclose(in.file);
        %get hpf data from ReadHPFdata
        t0_1(n)=toc;
            for i=1:numofch
                hpfdata=ReadHPFdata(i,InputFile{n});                
                data(:,i+1)=hpfdata.ReturnData;
                meas_type(:,i)={'Time Waveform'};
                ch_name(:,i)={hpfdata.Name};
                ch_unit_x(:,i)={'Sec'};
                ch_unit_y(:,i)={hpfdata.Unit};
                ch_vartype(:,i)={'Real'};
            end
        %first column = time
        data(:,1)=hpfdata.TimeAxis;
        t0_2(n)=toc;
        %define textfile via extension        
        ext='.txt';
        %show import time
        disp(['--Import time this file: ',num2str(t0_2(n)-t0_1(n)),'s']);
        %show filesize and time from last loop
        if n>=2
            disp(['--Writing time last file: ',num2str((t4(n-1)-t3(n-1))/60),'min or ', num2str(t4(n-1)-t3(n-1)),'s.']);
            disp(['--Writing speed last file: ',num2str(1000*filesize(n-1,:)/(t4(n-1)-t3(n-1))),'MB/s']);
        else
        end
        %disp(['--Busy estimating format ',num2str(n),' of ',num2str(numofinputs)]);
        t1(n)=toc;
        %variable format for textfile
        format=[repmat((['%.',num2str(numof_dec),'f\t ']), 1, size(data,2)-1), (['%.',num2str(numof_dec),'f\t\n'])];
        %fixed field width = fixed number of significant digits
        % format=[repmat((['%',num2str(fieldwidth),'.',num2str(numof_dec),'f\t ']), 1, size(data,2)-1), (['%',num2str(fieldwidth),'.',num2str(numof_dec),'f\t\n'])]
        %disp('---Done');
        t2(n)=toc;
        disp(['--Busy writing textfile ',num2str(n),' of ',num2str(numofinputs)]);
        t3(n)=toc;
        %write to .txt file
        %open textfile / save it under the same name as the raw data
        fid=fopen(fullfile(filepath, strcat(name,ext)),'w');
        %write header
        fprintf(fid,['QuickDAQ Data','\n']);
        fprintf(fid,[hpfdata.RecordingDate,'\n']);
        fprintf(fid,['Notes:','\n']);
        fprintf(fid,['SampleRate: ','\t', num2str(1/str2double(hpfdata.TimeIncrement)),'\t', 'Hz','\n']);
        fprintf(fid,['Measurement Type:','\t',(strjoin(meas_type)),'\n']);
        fprintf(fid,['Channel Name:','\t',strjoin(ch_name),'\n']);
        fprintf(fid,['X Axis Units:','\t',strjoin(ch_unit_x),'\n']);
        fprintf(fid,['Y Axis Units:','\t',strjoin(ch_unit_y),'\n']);
        fprintf(fid,['Seconds','\t',strjoin(ch_vartype),'\n']);
        %write data
        fprintf(fid,format,data.');
        %close file
        fclose(fid);
        t4(n)=toc;
        disp('---Done');
        %display the used files
        disp(['<strong>','Import file: ',fullfile(path,file{n}),'</strong>']);
        disp(['<strong>','Export file: ',fullfile(filepath, strcat(name,ext)),'</strong>']);
        %get filesize 
        s=dir((fullfile(filepath, strcat(name,ext))));
        filesize(n,1)=s.bytes/10^9; %in GB
    %---------------------------------------------------------------------%    
    %error in file selection
    else
        disp(['<strong>','error occured: number of input files not defined','</strong>']);
    end
    
end
%running times
t5=toc;
t_import=mean(t0_2-t0_1);
%t_format=mean(t2-t1);
t_fprintf=mean(t4-t3);
t_fprintftotal=sum(t4)-sum(t3);
%show filesize and writing speed
filesize=sum(filesize);
if filesize>=1 %GB
    disp(['Total amount of ','<strong>',num2str(filesize),' GB','</strong>',' with an average speed of ', num2str(filesize*1000/t_fprintftotal),'MB/s written to the directory.']);    
elseif filesize<=1 %GB
    disp(['Total amount of ','<strong>',num2str(round(filesize*1000)),' MB','</strong>',' with an average speed of ', num2str(filesize*1000/t_fprintftotal),'MB/s written to the directory.']);
else
    disp('Unvalid filesize');
end
%Command Window Output
%import time
disp(['Average time importing data: ',num2str(t_import),'s']);
%time formatting matrix
% disp(['Average time calculating format: ',num2str(t_format),'s']);
%time for fprintf
disp(['Average time required for fprintf: ',num2str(t_fprintf/60),'min or ',num2str(t_fprintf),'s']);
%other stats
ttime_s=toc;
disp(['Average time required per data file: ',num2str(ttime_s/numofinputs/60),'min or ',num2str(ttime_s/numofinputs),'s (~',num2str(filesize*1000/ttime_s),'MB/s or ',num2str(ttime_s/60/filesize),'min/GB)'])
disp(['Number of decimals used: ',num2str(numof_dec)]);
%disp total time
%runtime longer 1 hour
if ttime_s>3600
    ttime_h=ttime_s/3600;
    j=1;
    h=ttime_h;
    while h>=1
        h=ttime_h/j;
        if h<=1
            break
        else
            j=j+1;
        end
    end
    j=j-1;
else
    j=0;
end
%estimate missing time after 1 hour
seconds=round(ttime_s-j*3600);
minutes=round(seconds/60);
%part seconds or minutes
if seconds<60
        if seconds==1
            part_smin=(' second.');
        else
            part_smin=(' seconds.');
        end
        part_smin=([num2str(seconds),part_smin]);
    else
        if minutes==1
            part_smin=(' minute.');
        else
            part_smin=(' minutes.');
        end
        part_smin=([num2str(minutes),part_smin]);
end
%part_h
if j==1 %1 hour and x minutes/seconds
    part_h=(' hour and ~');
    disp(['Elapsed time is ',num2str(j),part_h,part_smin]);
elseif j>1 %longer 1 hour
    part_h=(' hours and ~');
    disp(['Elapsed time is ',num2str(j),part_h,part_smin]);
else 
    %runtime shorter 1 hour
    disp(['Elapsed time is ~',part_smin]);
end
disp('---Finish');