% edited on 20170219
% using Track_each_session_v16
% using TrackCenter_v4
% using TrackStartingZone_v3
% using TrackRewardLocations_v3

% use a new paradigm: 1 session with 10 trials at a time. Only use 1
% location.

% ======== Important ========
% If connect Matlab to the old version of Cheetah, set path and add folder of "Stream Channel".
% If connect Matlab to the Cheetah v5.7, set path  and add folder and subfolders of "NetComClientDevelopmentPackage_v3".

% need to track the reward locations before the recording!
% make the center of starting zone to be ang_ontrack=0

beep off  % don't make error sound

%% write down the codes used here
code_Track_each_session={'Track_each_session_v16';...
    'Track_each_session_v16_prerunning';...
    'Track_each_session_v16_posttest'};
code_TrackCenter='TrackCenter_v4';
code_TrackStartingZone='TrackStartingZone_v3';
code_TrackRewardLocations='TrackRewardLocations_v3';

%% settings
vt_acq_ent='VT1'; 
recodingroom = 'new'; % old recording room is NHB 2.150E, and new recording room is 2.150F
rot='Clockwise';
% rot='Counterclockwise';

sample_time=0.1;
time_stay_correct_alarm=0.1;
time_stay_error_alarm=0.2;
vfs=29.97;  % ======= the sample frequency of video ========
scale_x=0.25; % convert to cm
scale_y=0.27;
if strcmp(recodingroom,'old')
    x_sign = 1;
    y_sign = -1;
elseif strcmp(recodingroom,'new')
    x_sign = -1;
    y_sign = 1;
end
subdir='C:\DATA\Chenguang\Rat139';

% sound
load('beep.mat')
sound_beep_start=beep;
sound_beep_end=beep_long;
sound_beep_fs=Fs;
clear beep

%% Connection with Cheetah
Cheetah_v5_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_v4

diam_inner=diam_inner;
diam_outer=diam_inner+22; % radius is 11cm
R_inner=diam_inner/2;
R_outer=diam_outer/2;
R_inner0=78/2;  % need to change to real track

figure;
plot(x_circle-x_center,y_circle-y_center,'k.')
xlim([-50,50]);
ylim([-50,50]);
axis square

%% track the animal resting box (improved from starting zone in previous versions)
% 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_v3
% 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=1:19;
N_loc=length(Ind_loc);
TrackRewardLocations_v3
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));

% get left and right bound of each location
para_narrow=1/2;
para_wide=1/2;
Ang_RewardLoc_ontrack_zone_narrow=nan(N_loc,2);
Ang_RewardLoc_ontrack_zone_wide=nan(N_loc,2);
for i=2:N_loc
    Ang_RewardLoc_ontrack_zone_narrow(i,1)=Ang_RewardLoc_ontrack(i)-(Ang_RewardLoc_ontrack(i)-Ang_RewardLoc_ontrack(i-1))*para_narrow;
    Ang_RewardLoc_ontrack_zone_wide(i,1)=Ang_RewardLoc_ontrack(i)-(Ang_RewardLoc_ontrack(i)-Ang_RewardLoc_ontrack(i-1))*para_wide;
end
Ang_RewardLoc_ontrack_zone_narrow(1,1)=Ang_RewardLoc_ontrack(1);
Ang_RewardLoc_ontrack_zone_wide(1,1)=Ang_RewardLoc_ontrack(1);
for i=1:N_loc-1
    Ang_RewardLoc_ontrack_zone_narrow(i,2)=Ang_RewardLoc_ontrack(i)+(Ang_RewardLoc_ontrack(i+1)-Ang_RewardLoc_ontrack(i))*para_narrow;
    Ang_RewardLoc_ontrack_zone_wide(i,2)=Ang_RewardLoc_ontrack(i)+(Ang_RewardLoc_ontrack(i+1)-Ang_RewardLoc_ontrack(i))*para_wide;
end
Ang_RewardLoc_ontrack_zone_narrow(N_loc,2)=Ang_RewardLoc_ontrack(N_loc);
Ang_RewardLoc_ontrack_zone_wide(N_loc,2)=Ang_RewardLoc_ontrack(N_loc);

% get R_inner for all reward locations, by which we'll know if the rat
% stops for reward or for rest
% NOTE: set some tolorance (e.g. 1cm) for the R_inner_RewardLoc
R_inner_RewardLoc=Dist_RewardLoc-3;  % -4 for 3D McNaughton Drive LED

%% 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

%% begin sessions

% setting in the trials
n_prerunning=4; % lap1-lap2-lap3-lap4
n_sample_test=8; % sample1-test1-sample2-test2-sample3-test3
n_posttest=4; % test1-test2-test3-test4
time_prerunning = 50;  % 50s post-tests
time_sample_test = 30;  % 30s between a sample-test pair
time_test_sample = 50;  % 50s between a test and the next sample
time_posttest = 50;  % 50s post-tests
time_inbox = 60*5;  % 3 mins staying in the animal box in between sessions

time_stay_sample=0.1; % in sample trials, if the rat stay at a location for 'time_stay_sample'
                    % we will mark here as a potential reward location
time_stay_test=0.1; % in test trials, if the rat stay at a location for 'time_stay_sample'
                    % we will mark here as a potential reward location

% 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 139, 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;
% set the reward location indices:
% Note: change it for each day's recording
locnum_start=6;
Ind_rewardloc = [3];
Ind_rewardloc = Ind_rewardloc+locnum_start-1;
savefile = strcat(subdir,'\',date,'_CT_tracking.mat');
save(savefile);

%% Disconnection with Cheetah
Cheetah_v5_Matlab_Disconnection

%% initialize variables for this session
Ts_sleep_pre = nan(1,2);
Ts_sleep_prerunning = nan(1,2);
Ts_sleep_sampletest = nan(length(Ind_rewardloc),2);
Ts_sleep_posttest = nan(length(Ind_rewardloc),2);

Ind_rewardloc_sample={};
Ang_sample_reward_ontrack={};
Ts_sample={};
Sign_correct_sample={};

Ind_rewardloc_test={};
Ang_test_reward_ontrack={};
Ts_test={};
Sign_correct_test={};

Ind_rewardloc_posttest={};
Ang_posttest_reward_ontrack={};
Ts_posttest={};
Sign_correct_posttest={};
%% Connection with Cheetah
Cheetah_v5_Matlab_Connection
beep off  % don't make error sound

%% session start

% Sleep session
time_inbox_min = round(time_inbox/60);
get_current_time_v1  % get the current time point
ts_sleep_start0=time0;  % the very beginning of this session
h=waitbar(0, strcat('Sleep session:',num2str(time_inbox_min),'minutes'));
for min0=1:time_inbox_min
    pause(60);  % rat sitting in the animal box in time_inbox_min minutes totally
    waitbar(min0/time_inbox_min);
end
close(h)
get_current_time_v1  % get the current time point
ts_sleep_end0=time0;
Ts_sleep_pre = [ts_sleep_start0,ts_sleep_end0];
save(savefile);

% Pre-running session:
Track_each_session_v16_prerunning
Ts_prerunning{nsession,1}=[ts_prerunning_start,ts_prerunning_end];
save(savefile);

% Sleep session
get_current_time_v1  % get the current time point
ts_sleep_start0=time0;
h=waitbar(0, strcat('Sleep session:',num2str(time_inbox_min),'minutes'));
for min0=1:time_inbox_min
    pause(60);  % rat sitting in the animal box in time_inbox_min minutes totally
    waitbar(min0/time_inbox_min);
end
close(h)
get_current_time_v1  % get the current time point
ts_sleep_end0=time0; 
Ts_sleep_prerunning = [ts_sleep_start0,ts_sleep_end0];
save(savefile);

% Sample-test session
for nsession=1:length(Ind_rewardloc)
    % if want to continue?
    prompt = strcat('Do you want to start Session',num2str(nsession),' ? ');
    Ans = input(prompt);
    if isempty(Ans)
        % if only press the "Enter", continue this session
    else
        break
    end
    ind_rewardloc = Ind_rewardloc(nsession);
    fprintf('Session : %s , use reward location:  %s \r', num2str(nsession),num2str(ind_rewardloc));
    
    % Running session (sample-test trials)
    Track_each_session_v16
    
    Ind_rewardloc_sample{nsession,1}=ind_rewardloc_sample;
    Ang_sample_reward_ontrack{nsession,1}=ang_sample_reward_ontrack;
    Ts_sample{nsession,1}=[ts_sample_start,ts_sample_reward,ts_sample_end];
    Sign_correct_sample{nsession,1}=sign_correct_sample;
    
    Ind_rewardloc_test{nsession,1}=ind_rewardloc_test;
    Ang_test_reward_ontrack{nsession,1}=ang_test_reward_ontrack;
    Ts_test{nsession,1}=[ts_test_start,ts_test_reward,ts_test_end];
    Sign_correct_test{nsession,1}=sign_correct_test;
    save(savefile);
    
    % Sleep session
    get_current_time_v1
    ts_sleep_start0=time0;  % the very beginning of this session
    h=waitbar(0, strcat('Sleep session:',num2str(time_inbox_min),'minutes'));
    for min0=1:time_inbox_min
        pause(60);  % rat sitting in the animal box in time_inbox_min minutes totally
        waitbar(min0/time_inbox_min);
    end
    close(h)
    get_current_time_v1
    ts_sleep_end0=time0;  % the very beginning of this session
    
    Ts_sleep_sampletest(nsession,:) = [ts_sleep_start0,ts_sleep_end0];
    save(savefile);
    
    % Running session (post-test trials)
    Track_each_session_v16_posttest
    
    Ind_rewardloc_posttest{nsession,1}=ind_rewardloc_posttest;
    Ang_posttest_reward_ontrack{nsession,1}=ang_posttest_reward_ontrack;
    Ts_posttest{nsession,1}=[ts_posttest_start,ts_posttest_reward,ts_posttest_end];
    Sign_correct_posttest{nsession,1}=sign_correct_posttest;
    save(savefile);
    
    % Sleep session
    get_current_time_v1
    ts_sleep_start0=time0;  % the very beginning of this session
    h=waitbar(0, strcat('Sleep session:',num2str(time_inbox_min),'minutes'));
    for min0=1:time_inbox_min
        pause(60);  % rat sitting in the animal box in time_inbox_min minutes totally
        waitbar(min0/time_inbox_min);
    end
    close(h)
    get_current_time_v1
    ts_sleep_end0=time0;  % the very beginning of this session
    
    Ts_sleep_posttest(nsession,:) = [ts_sleep_start0,ts_sleep_end0];
    save(savefile);
end

csclist_CA1=[7 8 9 10 11 12 14 16 17];
save(savefile);

sound(beep0,fs_sin);
%% Disconnection with Cheetah
Cheetah_v5_Matlab_Disconnection

