function [MER, pos]=fake_MER(L,N,noise)
% Details:
% Function fake_MER produces an artifical MER signal adding real spikes at 
% random intervals, without superposition. Files N*_spk*.txt contain 
% isolated spikes from single unit recordings from healthy rats obtained 
% with actual MER (neurons 1 to 7). Sampling frequency for neurons is 
% 50kHz. The basal noise level (between spikes) is of the order of current 
% basal line variability. Units are in mV. 
% 
% input parameters:
% L is the length of the final signal (number of points) 
% L needs to be at least = length of spikes*number of spikes
% N is a vector with 7 values, each determining how many spikes from 
% neurons 1 to 7 are to be used
% noise is the level of noise (between 0 and 1) to be added to the signal 
% (also over spikes)

% pos = positions and corresponding neuron number for testing purposes

S='spk';
S2='.txt';
S3=1;

window=zeros(7,1);
d=0;
r=0;

for i=1:length(N)
        S4=sprintf('N%0.f_%s%0.f%s',i,S,S3,S2);
        spk=load(S4,'-ascii');
        window(i)=length(spk);
        rnew=std(spk(1:10))-min(spk(1:10));
        if (rnew>r) r=rnew; end
        d=d+N(i)*window(i);
end

S3=0;
  
if (L<d)
    'ERROR0: L too small'
end

MER=rand(L,1)*r-0.5*r; %r = basal noise level
positions=zeros(1,sum(N));
  
% choose spikes' positions
v=(1:L-max(window(:)));
positions=zeros(sum(N),1);
for i=1:1:sum(N)
l=length(v);
p=floor(l*rand()+1);
positions(i)=v(p);
if(positions(i)==0)
    while(v(p)==0&&p<l)
        p=p+1;
        positions(i)=v(p);
    end
end    
if(positions(i)==0)
    while(v(p)==0&&p>2)
        p=p-1;
        positions(i)=v(p);
    end
end
if (positions(i)==0)
    'ERROR1: position==0'  
end
for k=0:1:window+1
    u=positions(i)+k;
    uu=positions(i)-k;
    v(v==u)=0;
    v(v==uu)=0; 
end
end

pos= zeros (length(positions),2);
pos(:,1)=positions;

v(v==0)=[];

% checking that spikes' separation > a single spike's length
for i=1:length(positions)-1
    g(i)=abs(positions(i+1)-positions(i));
    if (g(i)<max(window(:)))
        'ERROR2: positions too close to another'
    end
end

position=1;

%load spikes into signal at randomly chosen positions
a=1;
for n=1:7
 for i=1:sum(N(n))
        S3=S3+1;
        S4=sprintf('N%0.f_%s%0.f%s',n,S,S3,S2);
        spk=load(S4,'-ascii');
        inicio=positions(a);
        fin=positions(a)+window(n)-1;
        a=a+1;
        MER(inicio:fin)=spk(1:window(n));
        pos(position,2)=n;
        position=position+1;
 end
 S3=0;
end

% add noise
R=rand(L,1)*noise-0.5*noise;
%rangoR=max(R)-min(R);

MER=MER+R;

figure;
plot(MER);

pos=sortrows(pos,1);
end