% edited on 20150302
% using Track_each_session_v11
% using TrackCenter_v3
% using TrackStartingZone_v2
% using TrackRewardLocations_v2

% need to track the reward locations before the recording!
% make the center of starting zone to be ang_ontrack=0


%% settings
vt_acq_entvt_acq_ent='VT1';
rot='Clockwise';
% rot='Counterclockwise';

sample_time=0.1;
time_stay_correct_alarm=0.1; % 1s
time_stay_error_alarm=0.2; % 1s
vfs=29.97;  % ======= the sample frequency of video ========
scale_x=0.264; % convert to cm
scale_y=0.294;

subdir='C:\DATA\Chenguang\Rat68';

% sound
load('beep.mat')
sound_beep_start=beep;
sound_beep_end=beep_long;
sound_beep_fs=Fs;

%% Connection with Cheetah
Cheetah_Matlab_Connection

%% Track the circular track center
% put the headstage at the inner edge of the circular track. When hear the
% beep, move the headstage around the inner edge of the track, and then
% stop also at inner edge. When hear another beep, remove the headstage.
TrackCenter_v3

% important: put the wooden block on the inner edge of the track, but not inside
% the inner edge.
diam_inner=diam_inner-4;  % wooden block width
diam_outer=diam_inner+22; % radius is 11cm
R_inner=diam_inner/2;
R_outer=diam_outer/2;
R_inner0=78/2;

figure;
plot(x_circle-x_center,y_circle-y_center,'k.')
xlim([-50,50]);
ylim([-50,50]);
axis square

%% track the starting zone
% When hear the beep, put the headstage at the first border of starting
% zone. When hear the second beep, put the headstge at the second border of
% starting zone. When hear the 3th beep, done.
TrackStartingZone_v2
% consider the Ang_StartZone_center to be 0, and calculated all angles
% compared to it
fprintf('Ang_StartZone_center: %s \r', num2str(Ang_StartZone_center));
Ang_StartZone_center_ontrack=0;
Ang_StartZone_depart_ontrack=mod(Ang_StartZone_center_ontrack+ang_startzone_width,2*pi);
Ang_StartZone_arrive_ontrack=mod(Ang_StartZone_center_ontrack-ang_startzone_width,2*pi);

% Ang_StartZone_arrive=mod(Ang_StartZone_arrive0-Ang_StartZone_depart0,2*pi);

%% track the reward locations
Ind_loc=4:9;
N_loc=length(Ind_loc);
TrackRewardLocations_v2
Ang_RewardLoc_ontrack=mod(Ang_RewardLoc-Ang_StartZone_center,2*pi);
if strcmp(rot,'Counterclockwise');
    Ang_RewardLoc_ontrack=2*pi-Ang_RewardLoc_ontrack;
end
fprintf('Reward Locations : %s \r', num2str(Ang_RewardLoc_ontrack));

%% plot the circular track
figure;
plot(x_circle-x_center,y_circle-y_center,'k.')
hold on
plot(x1_StartZone,y1_StartZone,'r.')
plot(x2_StartZone,y2_StartZone,'g.')
for ind=Ind_loc
    plot(X_RewardLoc(ind),Y_RewardLoc(ind),'b.')
end
xlim([-60,60]);
ylim([-60,60]);
axis square
hold off

%% find averaged R_inner for 12 segments of the track
x0 = x_circle-x_center;
y0 = y_circle-y_center;
ind=find(x0==0);
x0(ind)=0.01;

ind=find(x0>0);
ang0(ind)=mod(atan(-y0(ind)./x0(ind)),2*pi);
ind=find(x0<0);
ang0(ind)=mod(atan(-y0(ind)./x0(ind))+pi,2*pi);
if strcmp(rot,'Counterclockwise');
    ang0=2*pi-ang0;
end
ang_ontrack=mod(ang0-Ang_StartZone_center,2*pi);
distance_center=sqrt(x0.*x0+y0.*y0);
ind_segment=ceil(ang_ontrack/(2*pi/12));
R_inner_segment=zeros(12,1);
for ns=1:12
    ind=find(ind_segment==ns);
    R_inner_segment(ns)=mean(distance_center(ind));
end

% NOTE: set 1cm tolorance for the R_inner_segment
R_inner_segment=R_inner_segment-1.5;

%% Disconnection with Cheetah
Cheetah_Matlab_Disconnection

%% begin sessions

% setting in the trials
n_sample=6; % 6 learning laps in sample trial
n_test=1; % only one testing lap in test trial
time_stay_sample=0.2; % in sample trials, if the rat stay at a location for 'time_stay_sample'
                    % we will mark here as a reward location
time_stay_test=0.2; % in sample trials, if the rat stay at a location for 'time_stay_sample'
                    % we will mark here as a reward location
time_fix=30; % the rat needs to sit in starting zone for time_fix before running
distance_nomving=1; % 1cm
                    % if the rat's current location is less than 1cm close
                    % to last position, then we consider he's not moving
distance_tostop=2; % 2cm
                    % if the rat's current location is less than 2cm close
                    % to fist stop location, then we consider he's still
                    % waiting here
ang_nomving=distance_nomving/R_inner0;

distance_startzone_border=10; % 10cm
% reward location starts from Ang_StartZone_depart + ang_startzone_border,
% and ends at Ang_StartZone_arrive - ang_startzone_border
ang_startzone_border=distance_startzone_border/R_inner0;

dist_crct_zone_sample=6; % 5 cm at each side of the reward location
ang_crct_zone_sample=dist_crct_zone_sample/R_inner0;
dist_incrct_zone_sample=15;
ang_incrct_zone_sample=dist_incrct_zone_sample/R_inner0;

dist_crct_zone_test=6; % 5 cm at each side of the reward location
ang_crct_zone_test=dist_crct_zone_test/R_inner0;
dist_incrct_zone_test=30;
ang_incrct_zone_test=dist_incrct_zone_test/R_inner0;


% setting of the tones
fs_tone1 = 2000;
fs_sample_tone1=fs_tone1*10;
T = 0.25; % 1 seconds duration
t = 0:(1/fs_sample_tone1):T;
tone1 = sin(2*pi*fs_tone1*t);
sound(tone1, fs_sample_tone1);
pause(5)
fs_tone2 = 6000;
fs_sample_tone2=fs_tone2*10;
T = 0.25; % 1 seconds duration
t = 0:(1/fs_sample_tone2):T;
tone2 = sin(2*pi*fs_tone2*t);
sound(tone2, fs_sample_tone2);

% For rat 68, use tone1 as correct tone, and tone2 as incorrect tone
tone_correct=tone1;
fs_tone_correct=fs_sample_tone1;
tone_incorrect=tone2;
fs_tone_incorrect=fs_sample_tone2;

save(strcat(subdir,'\',date,'_CT_tracking.mat'));
%% Connection with Cheetah
Cheetah_Matlab_Connection

%% session start

for nsession=1:12
    sound(beep0,fs_sin);
    prompt = strcat('Where is reward location for session',num2str(nsession),' ? ');
    ind_rewardloc = input(prompt);
    
    % begin session starts
    Track_each_session_v11
    
    Ind_rewardloc(1,nsession)=ind_rewardloc;
    Ang_sample_reward_actual(:,nsession)=ang_sample_reward_actual;
    Ang_sample_reward_ontrack(:,nsession)=ang_sample_reward_ontrack;
    Time_sample_reward(:,nsession)=time_sample_reward;
    Ang_sample_reward_ontrack_mean(1,nsession)=ang_sample_reward_ontrack_mean;
    Ang_test_reward_actual(1,nsession)=ang_test_reward_actual;
    Ang_test_reward_ontrack(1,nsession)=ang_test_reward_ontrack;
    Time_test_reward(1,nsession)=time_test_reward;
    Sign_correct_sample(:,nsession)=sign_correct_sample;
    Sign_correct_test(1,nsession)=sign_correct_test;
    Ts_sample_start1(1,nsession)=ts_sample_start1;
    Ts_sample_start2(1,nsession)=ts_sample_start2;
    Ts_sample_stop(1,nsession)=ts_sample_stop;
    Ts_test_start1(1,nsession)=ts_test_start1;
    Ts_test_start2(1,nsession)=ts_test_start2;
    Ts_test_stop(1,nsession)=ts_test_stop;
    
    % sleep session starts
    while 1
        pause(sample_time);
        [~, timeStampArray, locationArray, ~, VTRecsReturned, ~] = NlxGetNewVTData(vt_acq_ent);
        x_loc = locationArray(end - 1);
        y_loc = locationArray(end);
        locationArray_end=[x_loc,y_loc];
        if max(locationArray_end)==0
            break
        end
    end
    Ts_sleep_start(1,nsession)=timeStampArray(end);
    
    h=waitbar(0, 'sleep session');
    for min0=1:5
        pause(60);
        waitbar(min0/5);
    end
    close(h)
    % sleep session ends
end


csclist_CA1=[1,2,3,4,5,6,7,10,11,12];
save(strcat(subdir,'\',date,'_CT_tracking.mat'));

%% Disconnection with Cheetah
Cheetah_Matlab_Disconnection



%% test
[~, timeStampArray, locationArray, ~, VTRecsReturned, ~] = NlxGetNewVTData(vt_acq_ent);
tic
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)
    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_center,2*pi);
vel_ontrack=(ang_ontrack-ang_ontrack_end)/sample_time;
distance_center=sqrt(x0^2+y0^2);
ind_segment=ceil(ang_ontrack/(2*pi/12));
toc