function out=legTrackerClassifyRawData(data,trainingbundle)
%legTrackerClassifyRawData calls all scripts needed to take the raw output
%of the Leg Tracker and produce a KNN-annotated behavioral sequence, using
%the JK training set.
%Usage:
%out=legTrackerClassifyRawData(data,trainingbundle)
%data = raw data from instrument, imported into N x 29 array.
%trainingbundle = variable trnBundle in "legTracker Training Bundle.mat"


% unpack training bundle
trnFeatures=trainingbundle.trnFeatures;
trnGroups=trainingbundle.trnGroups;
trnFPS=30;
tstFPS=100;
cutoff=750;

% KNN and low-pass filter parameters
stdWindow=5;
lpWindow=5;
kOptim=24;
metric='correlation';

dat=data;

%interpolate data into even 10ms intervals, discard trigonometric output
%from instrument, retain cartesian form of data
disp('interpolating raw data...')
dat=legTrackerCleanData(dat(cutoff:end,:));
dat=dat(:,[2:13 26:28]);

% filter data for erroneous frames
disp('error filtering raw data...')
dat=legTrackerErrorCheck(dat);

% calculate standard deviation of each vector in sliding window fashion
disp('calculating local stds...')
dat_E=legTrackerPrepLocalSTDs(dat,round((tstFPS/trnFPS)*stdWindow));

% calculate derivative of each vector 
disp('calculating derivatives...')
dat_C=legTrackerPrepDerivatives(dat);

% concatenate raw data and higher order features
disp('concatenating AEC data...');
dat_AEC=[dat dat_E dat_C];

% z-score normalize all vectors
disp('normalizing AEC data...');
trnMu=nanmean(dat_AEC);
trnSt=nanstd(dat_AEC);
numData=size(dat_AEC,1);
temp=repmat(trnSt,numData,1);
dat_AEC=(dat_AEC-repmat(trnMu,numData,1))./repmat(trnSt,numData,1);

% classify data using training bundle data
disp('knn classifying...');
predictions=knnclassify(dat_AEC,trnFeatures,trnGroups,kOptim,metric);

% apply low pass filter
disp('low-pass filtering...');
predictions=legTrackerPredFilt(predictions,round((tstFPS/trnFPS)*lpWindow));

% save data, prediction results, and transition Markov matrices into output
out.pred=predictions;
out.data=dat_AEC;
out.perc=legTrackerMarkovMat(predictions,'pie');
out.trans0=legTrackerMarkovMat(predictions);
out.trans1=legTrackerMarkovMat(predictions,1,0);
out.trans2=legTrackerMarkovMat(predictions,1,1);