%% This is an example on how to analyse new ABR data
% for now it only works for users of the IAN that have access to our test
% raw data stored on the UKON

% start by cleaning up your workspace
clearvars -except ukonmap; close all;



%% Get info for the animal
ExpID='GEK030';
 % path parts from the UKONMAP to the raw data
rawDatadir=  ["archiv","systems","AllDataTypesForAnalysisTests","GEK030"];
experimenterID='test';


%% create new Anex (since usually analysis starts with ABR)
enablecache off % make sure you load raw data
D(1).dir =rawDatadir;
D(1).type ="ABR";
ee = anex(ExpID, experimenterID, D);
ee = setAnimalSpecies(ee,'dinosaur'); % just making sure the correct anex gets loaded =)
initProcessedExp(ee) % creates save folder
initKiwi(ee) % notes file for the anex, but whatever you notice during the analysis in here
saveAnex(ee);% updates the ee

%% Optional add Metadata manually
%  MetaData=ee.ExpMetaData;
% MetaData(1).DateOfBirth=datetime('26.11.2024');
% MetaData.TickAtLabID=212309;
% MetaData.DateOfExperiment=datetime('23.04.2025');
% MetaData.AgeDays=days(MetaData(1).DateOfExperiment-MetaData(1).DateOfBirth);
% MetaData.DateOfInjection=datetime('05.03.2025');
% MetaData.Construct='ADULT_INJ_PHP.S-hSyn_fChrimson-EYFP_WPREmut6_bGHA';
% MetaData.Titer='unknown';
% MetaData.VirusBatch='#178';
% ee=ee.setExpMetaData(MetaData);
% saveAnex(ee)

%% load existing Anex
enablecache on
ee = anex(ExpID, 'test'); 
ee=loadAnex(ee);

%% do ABR analysis for existing Anex
enablecache off % make sure you load raw data
allBerabr(ee) % handles preprocessing for all expeirments in this folder (G0XX)
waitfor(exploreBerabr(ee) )% opens GUI to click on waves
waitfor(userberabrOD(ee))% add density filters manually in a GUI

setCalibrationBeraFromLaserControl(ee)
% setCalibrationFromTxt(ee, ee.RawDataDir(find([ee.RawDataDir.type]=='ABR')).dir)
enablecache off % make sure you load raw data
[ExpIntThrAcoustic] = intensityThreshold(ee, 'Acoustic');
[ExpIntThrOptical] = intensityThreshold(ee, 'Optical');
[MaxABRValues] = ABRMaxWaveValues(ee, 'Optical');
% [MaxABRValues] = ABRMaxWaveValues(ee, 'Acoustic') % does not yet work

saveAnex(ee); % updates the ee





%% options to work with analysed data
enablecache('on') % load already processed data
Bs=listBerabr(ee); % get a list of all berabr object

% load a single ABR recording and plot every second trace
B=loadBerabr(berabr(ee,string(Bs.ABR_SeriesID(1))));
figure
hold on
for ii =1:2:B.nTraces 
    plot(B.F(ii).t*1e3, B.F(ii).ABR*1e6);
end
xlabel('Time (ms)')
ylabel('Amplitude (\muV)','interpreter','Tex')
title('aABR traces')

% quick function for plotting
B.plotBerabr

% get some parameters from this ABR recording
B.Stim.intensity % presented intensities in %
B.C.Ical %presented intensities in mW (is empty for aABRs)
B.ExpInfo.ProtokollSetting
B.Stim.modality % gives acoustiv vs optical




