%reading MEG dat files to a matrix, and every row will be one channel. 
%Assumption: you need to first export MEG sqd files into bin files choosing all MEG channels(157)
%If channelfilename are not given,all the 157 MEG channels will be chosen.
%reading_size is used to limit the reading number when memory problem occurs, and it is really useful when you want to read the data of all
%trials rather than just avg file. reading_size can only be n*157*trial_length.
%When reading_size is not given, the function will try to read all (default). 

%Example
%[data_new,channelnum,datapoints] = readingMEGfile(filename,channelfilename,reading_size)
%[data_new,channelnum,datapoints] =
%readingMEGfile(filename,[],reading_size); %reading all channels with
%limited number
%[data_new,channelnum,datapoints] = readingMEGfile(filename,[]); %reading
%all channels and all the data.


function [data_new,channelnum,datapoints] = readingMEGfile(filename,channelfilename,reading_size)

if nargin==3,   %having reading_size input, limiting input number.
    [fid,message]=fopen(filename,'r','l');
    [rawdata,count]=fread(fid,reading_size,'float');
    fclose(fid);
    datacols=157;
    datarows=count/datacols;  
    data=reshape(rawdata,datacols,datarows);
else             %reading the total bin file 
   [fid,message]=fopen(filename,'r','l');
   [rawdata,count]=fread(fid,inf,'float');               
   fclose(fid);
   datacols=157;%channels numbers////157
   datarows=count/datacols;%datapoint per channel.
   data=reshape(rawdata,datacols,datarows); %every row will be one channel
end;

if isempty(channelfilename),
   data_new=data;
    channelnum=157;
    datapoints=datarows;
else
    [fid1,message1]=fopen(channelfilename);
 [L_channel,count1]=fscanf(fid1,'%i',inf);    
 fclose(fid1);
 data_new=data(L_channel+1,:);     
 channelnum=count1;
 datapoints=datarows;

end;
 




