function [] = meg4write(dsfolder,Trials,TimeIndices,CHANNELS,F,VERBOSE)
%MEG4WRITE - WRITE CTF MEG4 file format
% function [] = meg4write(dsfolder,Trials,TimeIndices,CHANNELS,F,VERBOSE)
% writes directly the data array F into the meg4 file of a CTF ds folder once the res4 was read using ds2brainstorm
% Copy of the original meg4file is written in same dsfolder with .orig extension.
% 
% dsfolder : character string containing the name of the original ds folder
% Trials : integer specifying the trial to write into the meg4 data file
% TimeIndices : a vector specifying the indices of the time samples to write in (default is extract entire trial length)
% CHANNELS : indices of channels to (re)write
% F : data array to be translated int meg4 CTF format
% VERBOSE : turn on/off verbose mode (default is off : 0 )
%

%<autobegin> ---------------------- 26-May-2004 11:30:57 -----------------------
% --------- Automatically Generated Comments Block Using AUTO_COMMENTS ---------
%
% CATEGORY: Data Processing
%
% Alphabetical list of external functions (non-Matlab):
%   toolbox\bst_message_window.m
%   toolbox\ds2brainstorm.m
%
% At Check-in: $Author: Mosher $  $Revision: 11 $  $Date: 5/26/04 9:59a $
%
% This software is part of BrainStorm Toolbox Version 2.0 (Alpha) 24-May-2004
% 
% Principal Investigators and Developers:
% ** Richard M. Leahy, PhD, Signal & Image Processing Institute,
%    University of Southern California, Los Angeles, CA
% ** John C. Mosher, PhD, Biophysics Group,
%    Los Alamos National Laboratory, Los Alamos, NM
% ** Sylvain Baillet, PhD, Cognitive Neuroscience & Brain Imaging Laboratory,
%    CNRS, Hopital de la Salpetriere, Paris, France
% 
% See BrainStorm website at http://neuroimage.usc.edu for further information.
% 
% Copyright (c) 2004 BrainStorm by the University of Southern California
% This software distributed  under the terms of the GNU General Public License
% as published by the Free Software Foundation. Further details on the GPL
% license can be found at http://www.gnu.org/copyleft/gpl.html .
% 
% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED "AS IS," AND THE
% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY
% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF
% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY
% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.
%<autoend> ------------------------ 26-May-2004 11:30:57 -----------------------


% Load Res4 information
[PATHSTR,NAME,EXT,VERSN] = fileparts(dsfolder) ;

if ~isempty(PATHSTR)
    cd(PATHSTR)
end

try 
    [path,rootname] = fileparts(dsfolder);
    if isdir('BrainStorm') % Was a BrainStorm directory created in .ds folder ? Yes if ds2brainstorm called from importdata
        res4_mat = fullfile('BrainStorm',[rootname,'_res4.mat']);
    else
        res4_mat = [rootname,'_res4.mat'];
    end
    
    try 
        load(res4_mat)
    catch
        [f,Channel,imegsens,ieegsens,iothersens,irefsens,grad_order_no,no_trials,filter,Time,RunTitle] = ds2brainstorm(dsfolder,VERBOSE,3,[],[],[],1);
        res4_mat = fullfile(dsfolder,'BrainStorm',[rootname,'_res4.mat']);
        load(res4_mat)
    end
      
    nref=length(irefsens);
catch
    errordlg(...
        {sprintf('Please make sure that resource file %s is available',[NAME,'_res4.mat']),...
            sprintf('in %s.', dsfolder)},...
        'res4 file missing'...
        )
    return
end


nref=length(irefsens);

if nargin == 3
    VERBOSE = 0;
    CHANNELS = [1:length(Channel)];
elseif nargin == 4
    CHANNELS = [1:length(Channel)];
end

meg4file = ([NAME,'reg.meg4']);

[meg,message] = fopen(meg4file,'ab+','s'); % Big-endian byte ordering
if meg < 0
    errordlg(message,mfilename)
    return
end
origmeg4file = [meg4file,'.orig'];
if ~exist(origmeg4file,'file') % Create a backup copy of original meg4file
    switch(upper(computer))
    case('PCWIN')
        dos(sprintf('copy %s %s', [NAME,'.meg4'], [NAME,'reg.meg4.orig']));
    case ('UNIX')
        unix(sprintf('cp %s %s', [NAME,'.meg4'], [NAME,'reg.meg4.orig']));
    end
end

% Extraction time range (sample indices)
if nargin == 2 % Not defined: take entire trial length
    TimeIndices = 1:length(Time);
else
    if length(TimeIndices) > length(Time)
        errordlg(...
            sprintf('Only %d time samples are available in each trial. Please adjust time extraction window',length(Time)));
        return
    end
end

status = fseek(meg,8,-1); % Skip header
if status < 0
    fwrite(meg,[77    69    71    52    49    67    80     0],'char'); % MEG41
end

%implicit.sample_rate = 1/(Time(2) - Time(1)); % i.e. the one used in the data file given the time begin_time end period.

no_samples = length(TimeIndices);
%no_trials = 1:gSetUp.no_trials;
no_channels = length(Channel);

diff_trials = diff(no_trials)-1; % Number of trials between each selected trials (useful when skipping a few trials)

ByteSizeOfTrial= length(Channel)*length(Time)*4; % Byte size of a single trial of data (Int32 coding) 

samples_skip = length(Time)-no_samples; %Number of time samples to skip per channel

LastChannelSkip = (length(Channel) - max(CHANNELS))*length(Time)*4; % Skip data from last channels

channels = [min(CHANNELS):max(CHANNELS)]; % Block of channels to extract.

FirstChannelSkip = (min(CHANNELS)-1)*length(Time)*4; % Skip data from first channels
no_channels = length(channels);    

for k = 1:length(Trials)
    itrial = Trials(k); %0
    %itrial = itrial+1;
    if VERBOSE
        bst_message_window({...
                sprintf('ds2brainstorm -> Writing out trial %d / %d',itrial,length(no_trials))...
            })
    end
    
    %F = zeros(no_channels,no_samples);
    
    if itrial == no_trials(1) % Read first trial
        fseek(meg,(itrial-1)*ByteSizeOfTrial + FirstChannelSkip + (TimeIndices(1)-1)*4 ,-1);
    else % just shift from the size of a trial
        fseek(meg,LastChannelSkip + (itrial-1)*ByteSizeOfTrial + FirstChannelSkip + (TimeIndices(1)-1)*4 ,-1); % was diff_trials(itrial-1)*ByteSizeOfTrial
    end
    
    % remove gains
    tmp = diag(gain_chan(CHANNELS))*F(:,(itrial-1)*no_samples + TimeIndices);
    
    %fwrite(meg,tmp,[num2str(no_samples),'*int32=>int32'], samples_skip*4)';
    fwrite(meg,tmp',['int32'], samples_skip*4)';
    %F = F(CHANNELS-min(CHANNELS)+1,:);
    
    if VERBOSE
        bst_message_window({...
                sprintf('ds2brainstorm -> Done')...
            })
    end
    
end

%fclose(meg);

