%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%        Victor V. Matveev, Richard Bertram and Arthur Sherman (2011)
% Ca2+ Cooperativity of Exocytosis as a Measure of Ca2+ Channel Domain Overlap.
%                      Brain Research 1398: 126-138.  
%
% Generate all distinct open-channel configurations for M equidistant channels  
%                  Victor Matveev, January 8, 2011
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 

for M = 2 : 12
    
L = 2^M - 1;      
confList = [0];
revList  = [0];
multList = [1];
openList = [0];

for conf = 1 : L
    bits     = bitand( conf, 2.^(0:M-1) ) > 0;
    rbits    = bits(M:-1:1);
    reversed = sum(bits .* (2.^(M-1:-1:0)) );
    
    shifted = conf;
    flag = 0;
    for shft = 1:M
        I = find(confList == shifted);
        if length(I)==0
            I = find(revList == shifted);
        end
        if length(I) > 0
            multList(I)= multList(I) + 1;
            %fprintf('%s same as %s \n', dec2bin(conf), dec2bin(shifted) );
            flag = 1;
            break;
        end
        shifted = bitshift(shifted, 1, M) + ( bitand(shifted, 2^(M-1)) > 0 );
    end
    
    if flag == 0
        confList = [confList, conf];
        revList  = [revList, reversed];
        multList = [multList, 1];
        openList = [openList, sum(bits) ];
    end;
    
end

N = length(confList);
[openList, I] = sort(openList);
confList = confList(I);
multList = multList(I);

ff = fopen(['M', num2str(M), 'equidistConfig.par'],'w');
SS = 0;

for i = 1: N
    bits = bitand(  confList(i), 2.^(0:M-1) ) > 0;
    fprintf(ff, 'if conf == %d then\n', i);
    j = j + 1;
    fprintf(ff, '  ff = %s\n', num2str(bits) );
    fprintf(ff, '  mult = %d\n', multList(i) );
    fprintf(ff, '  sumf = %d\n', openList(i) );
    fprintf(ff, '  ind  = %d\n', confList(i)  );
    SS = SS + multList(i);
    fprintf(ff, 'endif \n\n');
end

fprintf(ff, 'if conf > %d then\n', N);
fprintf(ff, '   continue \n\n');
fprintf(ff, 'endif \n\n');

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

for i = 1:M 
    fprintf(ff,'a%d = %d*2*pi/M; \n', i, i-1);
end
for i = 1:M 
    fprintf(ff,'x%d = MID + Dist * cos(a%d);  y%d  = MID + Dist * sin(a%d);  \n', i, i, i, i);
end
for i = 1:M 
    fprintf(ff,'Ca.source x%d  y%d  0 ww ww ww;  \n', i, i);
end
for i = 1:M 
    fprintf(ff,'I%d = I ff{%d};  \n', i, i);
end

fprintf(ff, ' currents '); 
for i = 1:M 
    fprintf(ff,' 0');
end
fprintf(ff, '\n currents'); 
for i = 1:M 
    fprintf(ff,' I%d', i);
end
fprintf(ff, '\n currents'); 
for i = 1:M 
    fprintf(ff,' 0');
end
fprintf(ff,'\n');

fclose(ff);

end




        
    
    
    
   