%==========================================================================
% Purpose: filter out suspecious data points for lab 1f Boiling curve
% Input: file name; format: (time, data)
% Methods: 1) skip every specific points
%          2) filter out points that have positive derivative
%
% Last updated: Yuwei Li, Feb, 13, 2014
%==========================================================================

%--echo information
disp('            *** Post-processing for lab 1f ***                 ');
disp('Purpose: filter data points');
disp('Input  : <file_name> of the data to be processed, e.g. test.txt');
disp('          Format : time  data (It works fine for the file to have header or not)');
disp('Output : new_<file_name>');
disp('Method 1: skip every specific points');
disp('Method 2: filter out points that have positive derivative');
disp(' ');

%--file
prompt = 'Please enter file name: ';
fname  = input(prompt,'s');

[file_all D H]= importdata(fname);

if(H == 0)
    data_all = file_all;
else
    data_all = file_all.data;
end

[row column]=size(data_all);
time     = zeros(row,1);
data     = zeros(row,1);
new_time = zeros(row,1);
new_data = zeros(row,1);

time = data_all(:,1);
data = data_all(:,2);

%--method
prompt = 'Choose your method, enter 1 for Method 1, 2 for Method 2: ';
method = input(prompt,'s');

if(strcmp(method, '1'))
    prompt    = 'Enter number of points to skip, e.g. 0 = no skip, 1 = skip every 1 point: ';
    iskip_tmp = input(prompt,'s');
    iskip     = str2num(iskip_tmp) + 1;       % +1 here is necessary as the increment
    
    npts = 0;
    idx  = 1;
    for i=1:iskip:row
       new_time(idx) = time(i);
       new_data(idx) = data(i);
    
       idx  = idx  + 1;      
       npts = npts + 1;
    end
    
elseif(strcmp(method, '2'))
    new_time(1) = time(1);
    new_data(1) = data(1);
    npts = 1;
    idx  = 2;
    for i=2:row
        
        if( data(i)-data(i-1)<0 )
            new_time(idx) = time(i);
            new_data(idx) = data(i);
            
            idx  = idx  + 1;
            npts = npts + 1;
        end
        
    end    
else
    disp('Method not found!');    
end
    
%Export data
fid = fopen(['new_',fname], 'wt');
for i=1:npts
   
    fprintf(fid, '%12.8f\t%12.8f\n', new_time(i),new_data(i)');
    
end
fclose(fid)