%coulterWrapper.m
%this function takes a filename of an lvm file and finds the decay envelope
%of the inputted data. If no filename is specified the function will ask
%for one

function [dataOut] = coulterWrapper(fname)

%check for filename if not specified
if nargin < 1
    fname = 'Z:\ChemSensors\CoulterCounter\2mmBead2mmTube2013July08.lvm';
%     fname = input('Input filename: ','s');
end

%open file and read data
fid = fopen(fname);

flag1 = 0;
while flag1 == 0 
    %read data
    cline = strtrim(fgetl(fid));
    flag1 = strcmp(cline,'***End_of_Header***');
    if feof(fid)
        break;
    end
end

cline = fgetl(fid);
cline = fgetl(fid);
csplit = regexp(cline, '\t','split');
clinechanNum = str2double(csplit(2));

cline = fgetl(fid);
csplit = regexp(cline, '\t','split');
sampleNum = str2double(csplit(2));
rawData = zeros(sampleNum,2);

flag1 = 0;
while flag1 == 0 
    %read data
    cline = strtrim(fgetl(fid));
    flag1 = strcmp(cline,'***End_of_Header***');
    if feof(fid)
        break;
    end
end

fgetl(fid);
cline = fgetl(fid);
csplit = regexp(cline, '\t', 'split');
rawData(1,:) = [str2double(csplit(1)) str2double(csplit(2))];
comment = strcat(csplit(3:end));

for si = 2:sampleNum
    cline = fgetl(fid);
    csplit = regexp(cline, '\t', 'split');
    rawData(si,:) = [str2double(csplit(1)) str2double(csplit(2))];
end
fclose(fid);


%apply envelope
disp(comment);
sampleRate = 10000;
cutoff = 10;
envdata = decayEnvelope(rawData(:,2),2,cutoff/sampleRate);

%plot results
figure('color','w')
subplot(2,1,1)
plot(rawData(:,1),rawData(:,2))
subplot(2,1,2)
plot(rawData(:,1),envdata)

dataOut = [rawData(:,1)';rawData(:,2)';envdata'];
end