load pmMatrix_bgnorm 
load ProbeIndices
%
%3) SUMMARY --> RMASUMMARY

PMsum_glob=rmasummary(ProbeIndices,pmMatrix_bgnorm,'Output','natural');
clear pmMatrix_bgnorm
save PMsum_glob PMsum_glob

load nomiChipNo24
narray=length(nomiChipNo24);

%adjust for clustering correction.
for i=1:narray
    aaaa=nomiChipNo24{i};
    switch aaaa
        case 'B4b_Y'
            aaaa='B4b_Z';
        case 'B4a_Z'
            aaaa='B4a_X';
        case 'B5b_Z'
            aaaa='B5b_Y';
    end
    giorniChipNo24(i)=aaaa(end);
end
giorniChipNo24=giorniChipNo24-86;
save giorniChipNo24 giorniChipNo24


% STEP 2 OF D2D as reported in the additional materials of the
% paper submitted to bioinformatics
%
[mua,ba,valgamma,gamma]=D2DsumII(PMsum_glob,giorniChipNo24);

%save -ascii datiRMA.txt PMsum_glob;
%%mua data are log2
%muaNOLOG=2.^mua;
%save -ascii datiD2D.txt muaNOLOG;

%generate files for clustering and randomize arrays to avoid bias
indarray=randperm(narray);
PMsum_globT=log2(PMsum_glob(:,indarray))';
save -ascii geniRMA.txt PMsum_globT
muaT=mua(:,indarray)';
save -ascii geniD2D.txt muaT

%generate file with array names in accordance to the randomization
fid=fopen('nomiChipNo24.txt','w');
for i=1:length(nomiChipNo24)
    fprintf(fid,'%s\n',nomiChipNo24{indarray(i)});
end
fclose(fid);