% Blind Calibration of JR CAD data
% code by laura balzano 11/9/2006
% Please use the following citation if you use this code:
% L. Balzano and R. Nowak, "Blind Calibration of Sensor Networks",
% in the Proceedings of Information Processing in Sensor Networks, April 2007.


clear all;
close all;
clc

data = csvread('CAD_06Nov2_smmat.csv');
cdata = csvread('CAD_06Nov2_calibrate_2.csv');

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% get true calibration coeffs
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% A translation from "box" number in calib data to an id 1:10
boxtrans = [111 114 115 116 117 118 120 122 125 126];

n = length(boxtrans);
calibed(:,1)=data(:,1); %copy times from one matrix to the other
k = length(data(:,1));
for i = 1:length(boxtrans) 
    ind = cdata(:,2)==boxtrans(i);
    calib = cdata(ind,:);
    x = [calib(:,3) ones(length(calib),1)];
    y = calib(:,4);
    params(:,i)= x\y;
    calibed(:,i+1) = (data(:,i+1) - params(2,i))/params(1,i);
end

a = params(1,:)';
b = params(2,:)';

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Put data into X and Y.
% The relationship is
% X = (Y-b)/a
% Y = aX + b
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Y = data(:,2:n+1)';
X = calibed(:,2:n+1)';

