function [kin_data, startingPoint]=upsample_kin(kin,bci_signal,bci_sf,bci_total_samples,channelNames)
% function for kin data upsampling to EMG data frequency (2500Hz)
%     inputs:
%     kin: kin data
%     bci_signal: signal recorded in bci (emg+eeg+eog+synchro)
%     bci_sf: sampling Frequency of bci signal
%     bci_total_samples: length of emg signal (2500Hz)
%     channelNames: names of channels recorded in bci (1:32 --> eeg, 33:42--> emg, 43: EOG, 44: synchro, 45: null)
%     
% 
%     outputs:
%     kin_data: kin data matrix (bci_total_samplesx13 kin variables) of same length as emg data, upsampled
%     startingPoint: starting point is the position point in the EMG data (2500 Hz) where
%     %kin data starts being recorded (synchronization step). the
%     %staringPoint position in EMG data corresponds to the first data point
%     %of kinematic data

    %upsampling --> get it equal to bci2000 data frequency
    kin_total_samples=length(kin_filt); % kin number of data points

    %1. find the starting point in the bci2000 data within the first 4 seconds (step in synchronization trigger)

    %look for a step in the beginning of kinematic signal
    [~,startingPoint]=max(abs(diff(bci_signal(1:4*bci_sf,(find(ismember(channelNames,'Synchro')))))));

    %2. create a new vector for kinematic data as long as the vector for EMG
    %data

    kin_data=NaN(bci_total_samples,13);%creates a new matrix of same lenght as EMG data
    
    
    %for kin variables 2-13 (not time), from 1 to startingPoint, we asign a
    %constant value, the same value that each variable has in the first
    %data point
    for j=2:13
        kin_data(1:startingPoint,j)=kin(1,j); % from 1 to startingPoint, the kinematic data 
    end
    
    %we take the time array 
    time=kin(:,1);%in ms

    for i=1:length(time) %length in kinematic data
      
       %assign the value of kin data in each time position in 17 Hz to the time
       %position that would have in 2500Hz (the rest of the positions stay with a NaN value)
        kin_data((startingPoint+floor(time(i)*bci_sf/1000)),2:13)=kin_filt(i,2:13);
     
    end

    %interpolate NaN values
    
    X=[1:bci_total_samples]';
    for i=2:13
        Y=(kin_data(1:bci_total_samples,i));
        ix=~isnan(Y);
        kin_data(1:bci_total_samples,i)=interp1(X(ix),Y(ix),X,'CUBIC');
    end

end
