%% v6: 
% totoally differnet from previous versions of 'Track_each_session.m'
% the experiment is setting as:
%
% 10 sessions in a day; a sample trial and a test trial in each session
%
% In sample trial, a piece of tape at reward location. The rat has to run 6 
% laps, and stop at the tape in each lap to get the reward. A correct/incorrect tone
% goes off when he stop at correct/incorrect spot.
% At the beginning of the sample trial, the rat was sitting in starting-zone for
% 30s, to let me sit down and close the curtain. At the end of this trial,
% he needs to be back to starting-zone, and then sitting for another 30s
% right before the test trial.
%
% In the test trial, no tape was on the track. If he stops at correct
% spot, i.e. ~10 degress close to the spot, the correct tone will go off. 
% Otherwise, if he stops outside ~10 degree but inside 90 degree around
% the spot, or run out of the spot without stopping, 
% the incorrect tone will go off. 
% At the end of test trial, the rat needs to be back to starting-zone. When
% he leave the track, this session ends. 
% 
% ******* Importantly, to detect the rat's stop, we measure the distance from rat's
% head to circular track center. If the distance < inner diameter (or even
% shorter), that means the rat stops to get reward.

% ******* Importantly, we get the reward location from his behavior.
% That is, to record the location where he stops to get food

% set the missing date [0,0] as the same as the last visited data

%%
ind_left_error=0;
ind_correct=0;
ind_right_error=0;

run_correct=[]; % 1 is correct; 0 is incorrect
run_areas=[];
run_ts=[];
run_ang=[];
run_num=0;

% detect if the rat arrived at Starting-zone, if so, this session starts
locationArray_end=[];
while 1
    %Pause to let some new data load up in NetCom's buffers.
    pause(sample_time);
    %Request all new VT data that has been acquired since the last pass.
    [~, timeStampArray, locationArray, ~, VTRecsReturned, ~] = NlxGetNewVTData(vt_acq_ent);
    %Get the X and Y location value for this VT frame. The
    %locationArray is in the form [x1, y1, x2, y2, ... xN, yN].
    x_loc = locationArray(end - 1);
    y_loc = locationArray(end);
    if ~x_loc && ~y_loc %% if x_loc=0, y_loc=0, means it's a missing data from the video
        if isempty(locationArray_end)
            continue
        end
        x_loc=locationArray_end(1);
        y_loc=locationArray_end(2);
    end
    x0 = double(x_loc).*scale_x-x_center;
    y0 = double((-1)*y_loc).*scale_y-y_center;
    if x0>=0
        if x0==0
            x0=0.1;
        end
        ang0=mod(atan(y0/x0),2*pi);
    else
        ang0=mod(atan(y0/x0)+pi,2*pi);
    end
    if strcmp(rot,'Clockwise');
        ang0=2*pi-ang0;
    end
    ang_ontrack=mod(ang0-Ang_StartZone_depart0,2*pi);
    locationArray_end=[x_loc,y_loc];
    
    if ang_ontrack > Ang_StartZone_depart && ang_ontrack < Ang_StartZone_arrive
        break
    end
end
sound(beep0,fs_sin);


%% sample trial

[~, timeStampArray, locationArray, ~, VTRecsReturned, ~] = NlxGetNewVTData(vt_acq_ent);
ts_sample_start1=timeStampArray(end);
pause(time_fix);
% give me 30s to sit into the track, close the curtain and prepare the
% treat
[~, timeStampArray, locationArray, ~, VTRecsReturned, ~] = NlxGetNewVTData(vt_acq_ent);
ts_sample_start2=timeStampArray(end);
sound(sound_beep_start,sound_beep_fs);

n_sample;
n_reward_lap=0;
n_running_lap=0;
locationArray_end=[];
ang_ontrack_end=0;
sign_enter=0;  % sign_enter=1 means the rat is ready to enter a reward spot;
% otherwise, sign_enter=0 means the rat is just leaving a reward spot
sign_leave=0;  % sign_leave=1 means the rat is just leaving a reward spot;
% otherwise, sign_enter=0 means the rat is just leaving a reward spot
% Note: when the rat is back to starting zone, both sign_enter and
% sign_leave are set to 0
sign_reward=0;  % sign_reward=1 means the rat has found the reward location,
% and ready to eat the reward. (the rat headed out toward the center)
% otherwise, sign_reward=0 means the rat is not at reward location yet

time_stay_reward=0;
Ang_sample_reward_actual=zeros(n_sample,1);
Ang_sample_reward_ontrack=zeros(n_sample,1);
Time_sample_reward=zeros(n_sample,1);
while n_reward_lap<n_sample
    pause(sample_time);
    [~, timeStampArray, locationArray, ~, VTRecsReturned, ~] = NlxGetNewVTData(vt_acq_ent);
    time0=timeStampArray(end);
    time_win=length(VTRecsReturned)./(2*vfs);
    x_loc = locationArray(end - 1);
    y_loc = locationArray(end);
    if ~x_loc && ~y_loc %% if x_loc=0, y_loc=0 means it's a missing data from the video
        if isempty(locationArray_end)
            continue
        end
        x_loc=locationArray_end(1);
        y_loc=locationArray_end(2);
    end
    x0 = double(x_loc).*scale_x-x_center;
    y0 = double((-1)*y_loc).*scale_y-y_center;
    
    if x0>=0
        if x0==0
            x0=0.1;
        end
        ang0=mod(atan(y0/x0),2*pi);
    else
        ang0=mod(atan(y0/x0)+pi,2*pi);
    end
    if strcmp(rot,'Clockwise');
        ang0=2*pi-ang0;
    end
    ang_ontrack=mod(ang0-Ang_StartZone_depart0,2*pi);
    distance_center=sqrt(x0^2+y0^2);
    
    if sign_enter==0 && sign_leave==0 && ang_ontrack > Ang_StartZone_depart + ang_startzone_border && ang_ontrack < Ang_StartZone_arrive - ang_startzone_border
        % as soon as the rat is starting from the starting zone
        sign_enter=1;
        sign_leave=0;
    elseif sign_enter==1 && sign_leave==0 && ang_ontrack > Ang_StartZone_depart + ang_startzone_border && ang_ontrack < Ang_StartZone_arrive - ang_startzone_border
        % if the rat is coming to a reward location
        if sign_reward==1
            % if the rat headed out towards the center
            if time_stay_reward >= time_stay_sample
                % if the rat has stopped at reward location for "time_stay_sample"
                % mark here as a reward location
                n_reward_lap=n_reward_lap+1;
                Ang_sample_reward_actual(n_reward_lap)=ang0;
                Ang_sample_reward_ontrack(n_reward_lap)=ang_ontrack;
                fprintf('Loc: %s \r',num2str(ang_ontrack));
                Time_sample_reward(n_reward_lap)=time0;
                sign_enter=0;
                sign_leave=1;
                sign_reward=0;
            else % time_stay_reward < time_stay_sample
                if abs(ang_ontrack-ang_ontrack_end) <= ang_nomving && abs(ang_ontrack-ang_ontrack_stop0) <= ang_stop_tolerance
                    % if the rat is still close to the location where he headed out to, and he is staying here
                    time_stay_reward=time_stay_reward+time_win;
                elseif abs(ang_ontrack-ang_ontrack_stop0) > ang_stop_tolerance
                    % The rat found a wrong reward location
                    sign_reward=0;
                    time_stay_reward=0; % reset it to 0
                else
                    time_stay_reward=0; % reset it to 0
                end
            end
        else % sign_reward==0
            % the rat is hasn't found the reward loction, which means
            % the rat hasn't headed out toward the center
            if distance_center < diam_inner/2
                sign_reward=1;
                ang_ontrack_stop0=ang_ontrack;
                % record the location where the rat headed out towards center
            end
        end
    elseif ang_ontrack > Ang_StartZone_arrive - ang_startzone_border || ang_ontrack < Ang_StartZone_depart + ang_startzone_border
        % the rat is back into starting-zone
        if sign_enter || sign_leave || sign_reward
            % if the rat just run back to the starting zone after a lap
            % count the number of running laps
            n_running_lap=n_running_lap+1;
        end
        if n_reward_lap < n_running_lap
            %in this lap, the rat runs without stop
            n_reward_lap=n_reward_lap+1;
            Ang_sample_reward_actual(n_reward_lap)=NaN;
            Ang_sample_reward_ontrack(n_reward_lap)=NaN;
            fprintf('Loc: NaN\r');
            Time_sample_reward(n_reward_lap)=NaN;
        end
        sign_enter=0;
        sign_leave=0;
        time_stay_reward=0; % reset it to 0
    end
    
    locationArray_end=[x_loc,y_loc];
    ang_ontrack_end=ang_ontrack;
end

% as soon as the rat is back into starting-zone, this sample trial ends
while ang_ontrack > Ang_StartZone_depart && ang_ontrack < Ang_StartZone_arrive
    pause(sample_time);
    [~, timeStampArray, locationArray, ~, VTRecsReturned, ~] = NlxGetNewVTData(vt_acq_ent);
    time0=timeStampArray(end);
    x_loc = locationArray(end - 1);
    y_loc = locationArray(end);
    if ~x_loc && ~y_loc %% if x_loc=0, y_loc=1, means it's a missing data from the video
        if isempty(locationArray_end)
            continue
        end
        x_loc=locationArray_end(1);
        y_loc=locationArray_end(2);
    end
    x0 = double(x_loc).*scale_x-x_center;
    y0 = double((-1)*y_loc).*scale_y-y_center;
    
    if x0>=0
        if x0==0
            x0=0.1;
        end
        ang0=mod(atan(y0/x0),2*pi);
    else
        ang0=mod(atan(y0/x0)+pi,2*pi);
    end
    if strcmp(rot,'Clockwise');
        ang0=2*pi-ang0;
    end
    ang_ontrack=mod(ang0-Ang_StartZone_depart0,2*pi);
end
ts_sample_stop=time0;
sound(sound_beep_start,sound_beep_fs);


%% test trial

ts_test_start1=ts_sample_stop;
pause(time_fix);
% give me 30s to swipe the track and prepare the treat
[~, timeStampArray, locationArray, ~, VTRecsReturned, ~] = NlxGetNewVTData(vt_acq_ent);
ts_test_start2=timeStampArray(end);
sound(sound_beep_start,sound_beep_fs);

% get the correct reward location from the sample trial
Ang_sample_reward_ontrack_mean=nanmean(Ang_sample_reward_ontrack);
Ang_test_reward_correct_left=max(Ang_sample_reward_ontrack_mean-ang_correct_tolerance,Ang_StartZone_depart);
Ang_test_reward_correct_right=min(Ang_sample_reward_ontrack_mean+ang_correct_tolerance,Ang_StartZone_arrive);
Ang_test_reward_incorrect_left=max(Ang_sample_reward_ontrack_mean-ang_incorrect_tolerance,Ang_StartZone_depart);
Ang_test_reward_incorrect_right=min(Ang_sample_reward_ontrack_mean+ang_incorrect_tolerance,Ang_StartZone_arrive);

n_test;
n_reward_lap=0;
locationArray_end=[];
ang_ontrack_end=0;
sign_enter=0;
sign_leave=0;
sign_reward=0;
Ang_test_reward_ontrack=0;
Time_test_reward=0;
while n_reward_lap<n_test
    pause(sample_time);
    [~, timeStampArray, locationArray, ~, VTRecsReturned, ~] = NlxGetNewVTData(vt_acq_ent);
    time0=timeStampArray(end);
    time_win=length(VTRecsReturned)./(2*vfs);
    x_loc = locationArray(end - 1);
    y_loc = locationArray(end);
    if ~x_loc && ~y_loc %% if x_loc=0, y_loc=0 means it's a missing data from the video
        if isempty(locationArray_end)
            continue
        end
        x_loc=locationArray_end(1);
        y_loc=locationArray_end(2);
    end
    x0 = double(x_loc).*scale_x-x_center;
    y0 = double((-1)*y_loc).*scale_y-y_center;
    
    if x0>=0
        if x0==0
            x0=0.1;
        end
        ang0=mod(atan(y0/x0),2*pi);
    else
        ang0=mod(atan(y0/x0)+pi,2*pi);
    end
    if strcmp(rot,'Clockwise');
        ang0=2*pi-ang0;
    end
    ang_ontrack=mod(ang0-Ang_StartZone_depart0,2*pi);
    distance_center=sqrt(x0^2+y0^2);
    
    if sign_enter==0 && sign_leave==0 && ang_ontrack > Ang_StartZone_depart + ang_startzone_border && ang_ontrack < Ang_StartZone_arrive - ang_startzone_border
        % as soon as the rat is starting from the starting zone
        sign_enter=1;
        sign_leave=0;
    elseif sign_enter==1 && distance_center < diam_inner/2
        % if the rat is leaving the starting-zone, and stops to get reward
        if ang_ontrack > Ang_test_reward_incorrect_left && ang_ontrack < Ang_test_reward_incorrect_right
            % the rat is entering the 'incorrect area'
            if ang_ontrack < Ang_test_reward_correct_left
                % the rat make an error in front of the reward location
                sound(tone_incorrect,fs_tone_incorrect);
                sign_correct=0;
            elseif ang_ontrack > Ang_test_reward_correct_left && ang_ontrack < Ang_test_reward_correct_right
                % the rat stops at reward location
                sound(tone_correct,fs_tone_correct);
                sign_correct=1;
            elseif ang_ontrack > Ang_test_reward_correct_right
                % the rat make an error behind the reward location
                sound(tone_incorrect,fs_tone_incorrect);
                sign_correct=0;
            end
            n_reward_lap=n_reward_lap+1;
            Ang_test_reward_actual=ang0;
            Ang_test_reward_ontrack=ang_ontrack;
            Time_test_reward=time0;
            sign_enter=0;
            sign_leave=1;
        end
    elseif sign_enter==1 && sign_leave==0 && (ang_ontrack > Ang_StartZone_arrive - ang_startzone_border || ang_ontrack < Ang_StartZone_depart + ang_startzone_border)
        % the rat is back into starting-zone and he doesn't stop at all around the reward location
        n_reward_lap=n_reward_lap+1;
        Ang_test_reward_actual=NaN;
        Ang_test_reward_ontrack=NaN;
        Time_test_reward=NaN;
        sign_correct=0;
        sign_enter=0;
        sign_leave=0;
    end
    
    locationArray_end=[x_loc,y_loc];
    ang_ontrack_end=ang_ontrack;
end
fprintf('TestLoc: %s \r',num2str(Ang_test_reward_ontrack));

% as soon as the rat is back into starting-zone, this test trial ends
while ang_ontrack > Ang_StartZone_depart && ang_ontrack < Ang_StartZone_arrive
    pause(sample_time);
    [~, timeStampArray, locationArray, ~, VTRecsReturned, ~] = NlxGetNewVTData(vt_acq_ent);
    time0=timeStampArray(end);
    x_loc = locationArray(end - 1);
    y_loc = locationArray(end);
    if ~x_loc && ~y_loc %% if x_loc=0, y_loc=1, means it's a missing data from the video
        if isempty(locationArray_end)
            continue
        end
        x_loc=locationArray_end(1);
        y_loc=locationArray_end(2);
    end
    x0 = double(x_loc).*scale_x-x_center;
    y0 = double((-1)*y_loc).*scale_y-y_center;
    
    if x0>=0
        if x0==0
            x0=0.1;
        end
        ang0=mod(atan(y0/x0),2*pi);
    else
        ang0=mod(atan(y0/x0)+pi,2*pi);
    end
    if strcmp(rot,'Clockwise');
        ang0=2*pi-ang0;
    end
    ang_ontrack=mod(ang0-Ang_StartZone_depart0,2*pi);
end

ts_test_stop=time0;
sound(sound_beep_start,sound_beep_fs);
