%% Step 1: Add FieldTrip
addpath('C:\Stah\Downloaded\fieldtrip-master')
ft_defaults
savepath

%% Step 2: Load full dataset (keep this for memory reasons)
cfg = [];
cfg.dataset = 'D:\data\vhdr-allchannels\P01_ses2.vhdr';
data = ft_preprocessing(cfg);  % load full dataset

%% Step 3: Select channels for scoring
cfg = [];
cfg.channel = {'F4', 'F3', 'C4', 'C3', 'Oz', 'O2', 'EOG'};
data_r = ft_selectdata(cfg, data);

%% Step 4: Downsample to 256 Hz
cfg = [];
cfg.resamplefs = 256;
cfg.detrend    = 'no';
data_s = ft_resampledata(cfg, data_r);  % corrected from data_small

%% Step 5: Read events
vmrk_file = 'D:\data\vhdr-allchannels\P01_ses2.vmrk';
event = ft_read_event(vmrk_file);
 

startEvents  = event(strcmp({event.value}, 's1001'));
endEvents    = event(strcmp({event.value}, 's1002'));

if isempty(startEvents) || isempty(endEvents)            
    fprintf('Markers for sleep start or end are missing for sub %s, ses %d.\n', subID, ises);
    error('Markers for sleep start or end are missing.');
end

sleep_start = startEvents(end).sample;
sleep_end   = endEvents(1).sample;

%% Step 6: Preprocess only the sleep segment
% Define the trial for sleep segment based on sample numbers
trl = [sleep_start sleep_end 0];  % [begin end offset]

cfg_redef = [];
cfg_redef.trl = trl;

sleep_data = ft_redefinetrial(cfg_redef, data_s);  % uses already loaded data

%% Step 7: Inspect data in FieldTrip databrowser
cfg = [];
cfg.blocksize        = 30;
cfg.preproc.lpfilter = 'yes';
cfg.preproc.lpfreq   = 30;
cfg.preproc.hpfilter = 'yes';
cfg.preproc.hpfreq   = 0.5;
ft_databrowser(cfg, data_r);  % inspect selected channels

%% save
% Ensure data is of a standard numeric type and real
fprintf('Forcing data to be real and of class double before saving...\n');
for i = 1:length(sleep_data.trial)
    sleep_data.trial{i} = double(real(sleep_data.trial{i}));
end

% Create a new, clean data structure with only essential fields
data_to_save = [];
data_to_save.trial = sleep_data.trial;
data_to_save.time = sleep_data.time;
data_to_save.label = sleep_data.label;
data_to_save.fsample = sleep_data.fsample;

% Define the full filename
tarDir = 'C:\Stah\ProcessedData';
subID = 'P01';
sesID = 'ses2';
filename = fullfile(tarDir, [subID '_' sesID '.edf']);

% Now, write the newly created, clean data structure
ft_write_data(filename, data_to_save);