% rd_strip          - Read StripTool data dump

function data = rd_strip(file, skip)

data.type = 'strip';

[fid, msg] = fopen(file, 'r');
if (fid == -1)
  error(['File ', file, ' cannot be opened: ', msg]);
end
data.header = fgetl(fid);

% Parse the header
u = strfind(data.header, 9); % Look for tabs
for k=1:length(u)-1
  data.chan{k} = data.header(u(k)+1:u(k+1)-1);
end
fclose(fid);

if (nargin == 1)
  skip = 0;
end

% Cut data section out
tmpf = tempname;
system(sprintf('tail -n +%d %s > %s', skip+2, file, tmpf));

% Now separate into timestamps and signals
tmp_ts  = tempname;
tmp_sig = tempname;
system(sprintf('cut -f1 %s > %s', tmpf, tmp_ts));
system(sprintf('cut -f2- %s > %s', tmpf, tmp_sig));

data.val = load(tmp_sig);
fid = fopen(tmp_ts, 'r');
ts  = fread(fid, inf, 'uchar');
fclose(fid);
x = char(ts);
u = find(ts==10, 1);
xx = reshape(x, u, length(x)/u)';
xx = xx(:,1:end-1);
data.ts = xx;

if (0)
  %xx = xx(:,12:end);
  xx(:,end+1) = ' ';
  xx = xx'; xx = xx(:)';
  v = sscanf(xx, '%d/%d/%d %d:%d:%f');
  data.t_raw = v(2:6:end)*24+v(4:6:end) + (v(5:6:end) + v(6:6:end)/60)/60;
  % Time in hours
  data.t = (data.t_raw-data.t_raw(end));
else
  data.t_raw = datenum(xx, 'mm/dd/yyyy HH:MM:SS.FFF');
  data.t = (data.t_raw-data.t_raw(end))*3600*24;
end

% Remove temporary files
system(sprintf('rm %s %s %s', tmpf, tmp_ts, tmp_sig));

% Compute sampling rate
data.Ts = mean(diff(data.t));
