function [OutMat]=WriteCtfSess(InDataset, varargin)

if nargin<1; error('no dataset defined'); end

fh = read_CTF_fileheaderM(InDataset);

Nchannels = fh.Nchannels;
Ntrials = fh.Ntrials;

if Ntrials == 1
	Message=char('Sorry,');
	Message=char(Message,'unable to load datset:');
	Message=char(Message,'');
	Message=char(Message,[SetFilePath]);
	Message=char(Message,'');
	Message=char(Message,[SetFilePath]);
	Message=char(Message,'dataset is not in trial mode');
	hmsgbox=msgbox(Message,'Info','help'); 
	return;
end

ch = read_CTF_channelheaderM(InDataset);

NChanTmp=0;
NmegChan=0;
NeegChan=0;
for ChanInd=1:Nchannels,
	if ch(ChanInd).SensorType==5
    	NChanTmp=NChanTmp+1;
        ChanIndVec(NChanTmp)=ChanInd;
		NmegChan=NmegChan+1;
	elseif ch(ChanInd).SensorType==9
    	NChanTmp=NChanTmp+1;
        ChanIndVec(NChanTmp)=ChanInd;
		NeegChan=NeegChan+1;
    end
end
mess = sprintf('found %d MEG and %d EEG channels', NmegChan, NeegChan);
disp(mess);

% determine .ses.ctf output file name
Nat=findstr(InDataset,'.ds');
if Nat(1)<length(InDataset)-2
	OutFile=[InDataset(1:Nat(1)-1),InDataset(Nat+2:length(InDataset)),'.ses.ctf'];
else
	OutFile=[InDataset(1:Nat(1)-1),'.ses.ctf'];
end
disp(OutFile);
fd = fopen(OutFile,'a');

% write data to .ctf file
for t=1:Ntrials,
	inData = read_CTF_data_selectiveM(InDataset, 'channels', ChanIndVec, 'includeTrials', int2str(t));
	disp(int2str(t));

	fwrite(fd, inData.Data', 'float');
end

fclose(fd);


% determine .ses.set output file name
Nat=findstr(InDataset,'.ds');
if Nat(1)<length(InDataset)-2
	OutFile=[InDataset(1:Nat(1)-1),InDataset(Nat+2:length(InDataset)),'.ses.set'];
else
	OutFile=[InDataset(1:Nat(1)-1),'.ses.set'];
end
disp(OutFile);

%fd = fopen(OutFile,'w');
%fprintf(fd, 'Nchannels\t%d', fh.Nchannels);
%fprintf(fd, 'Nsamples\t%d', fh.Nsamples);
%fprintf(fd, 'Ntrials\t%d', fh.Ntrials);
%fprintf(fd, 'NMegChan\t%d', NmegChan);
%fprintf(fd, 'NEegChan\t%d', NeegChan);
%fprintf(fd, 'SampRate\t%f', fh.Srate);
%fprintf(fd, 'SampPeriod\t%f', 1.0/fh.Srate);
%fprintf(fd, 'BaseMs\t%f', fh.PreTrgTime*0.001);
%fprintf(fd, 'Duration\t%f', fh.Nsamples / fh.Srate);
%Nbit = 4; % for float32
%fprintf(fd, 'Nbit\t%d', Nbit);
%fprintf(fd, 'NexternChan\t%d', 0);
%fclose(fd);

save(OutFile, 'fh', 'ch', '-MAT');

return;
