clear all; clc;

testvar = readtable('D:\ACC Data\ACC\747/XYtotalspike1.csv');

 xposn=testvar.Var2;xposn=xposn-min(xposn);
 yposn=testvar.Var3;yposn=yposn-min(yposn);
 
 %smooth first
linearizedposn=NaN(length(xposn),1);

for num_pos=1:length(xposn);

 if yposn(num_pos)<20;
    linearizedposn(num_pos)=xposn(num_pos);

 elseif yposn(num_pos)>=20 & xposn(num_pos)<23;
         linearizedposn(num_pos)=9 - yposn(num_pos);

 elseif yposn(num_pos)>384 & xposn(num_pos)>23;
             linearizedposn(num_pos)=9-405-xposn(num_pos);

 elseif xposn(num_pos)>402 & yposn(num_pos)<394;
                 linearizedposn(num_pos)=9-405-411-(412-xposn(num_pos));
 else linearizedposn(num_pos)=NaN;
 end;
end;

% Interpolate to remove NaN values
fixedlinearizedposn = 0.5 * (fillmissing(linearizedposn, 'previous' ) + fillmissing(linearizedposn, 'next' ));

smoothed_linearized_posn=fixedlinearizedposn;

for pos_num=2:length(smoothed_linearized_posn);
    if abs((smoothed_linearized_posn(pos_num-1))-(smoothed_linearized_posn(pos_num)))>100;
        smoothed_linearized_posn(pos_num)=smoothed_linearized_posn(pos_num-1);
    end;
end;

smoothed_linearized_posn=smoothdata(smoothed_linearized_posn, 'movmedian', 20);


number_bins=50;
[binned_linear_posn,E] = discretize(smoothed_linearized_posn,number_bins);

labels = binned_linear_posn;

testvar=table2array(testvar);
testvar=testvar(:,6:end);


t = templateSVM('Standardize',true,'KernelFunction','gaussian');

fraction_train = 0.5;
[trainInd,valInd,testInd] = dividerand(size(testvar,1),fraction_train,0,(1-fraction_train));
[Model] = fitcecoc(testvar(trainInd,:),labels(trainInd,:),'Learners','knn');%,'OptimizeHyperparameters','auto');

newly_labelled_data=predict(Model,testvar(testInd,:));
%tf = strcmp(newly_labelled_data,labels(testInd)); 
%tf=find(newly_labelled_data==labels(testInd));
%decodingaccuracy=length(tf)/length(newly_labelled_data)*100;

temp1=newly_labelled_data;
temp2=labels(testInd);

nonmoving=[];

for num=2:length(temp2);
if temp2(num-1)==temp2(num)
    nonmoving=[nonmoving;num];
end;
end;

temp2(nonmoving)=[];
temp1(nonmoving)=[];
perecent_error=(nanmean(abs(temp1-temp2)))/50*100;
