% File packer for Dario D'Orazio anechoic recordings 
% into SPS-12 multich WAV format
% (C) Angelo Farina, 01 July 2022

% the original recordings were in separate files, each is stereo, each 
% containing twice the same microphone signal repeated in the two channels
% there are 12 of these files in each subfolder
% this script removes the duplicate channels and saves a single 12-channels
% WAV file

clear all;
rootdir = 'Verdi';
filelist = dir(fullfile(rootdir, '**\*.*'));  %get list of files and folders in any subfolder
filelist = filelist(~[filelist.isdir]);  %remove folders from list
ssz=size(filelist);
sz =ssz(1);
disp(strcat('Number of individual files found: ', string(sz)));
for i=1:sz
    fn=filelist(i).name;
    if(size(fn,2)>6)
        ffn=fn(end-6:end);
    else
        ffn='';
    end
    if strcmp(ffn,'001.wav')
        disp(strcat('Processing file n. ', string(i),' - name:',' ',fn));
        fname=fn(1:end-7);
        path=filelist(i).folder;
        ffname= fullfile(path,fname);
        [w01,fs]=audioread(strcat(ffname,'001.wav'));
        [w02,fs]=audioread(strcat(ffname,'002.wav'));
        [w03,fs]=audioread(strcat(ffname,'003.wav'));
        [w04,fs]=audioread(strcat(ffname,'004.wav'));
        [w05,fs]=audioread(strcat(ffname,'005.wav'));
        [w06,fs]=audioread(strcat(ffname,'006.wav'));
        [w07,fs]=audioread(strcat(ffname,'007.wav'));
        [w08,fs]=audioread(strcat(ffname,'008.wav'));
        [w09,fs]=audioread(strcat(ffname,'009.wav'));
        [w10,fs]=audioread(strcat(ffname,'010.wav'));
        [w11,fs]=audioread(strcat(ffname,'011.wav'));
        [w12,fs]=audioread(strcat(ffname,'012.wav'));
        y=[w01(:,1),w02(:,1),w03(:,1),w04(:,1),w05(:,1),w06(:,1),w07(:,1),w08(:,1),w09(:,1),w10(:,1),w11(:,1),w12(:,1)];
        outfile=strcat(rootdir,'\',fname,'SPS12.wav');
        audiowrite(outfile,y,fs,'BitsPerSample',32);
        disp(['Saved a 12ch WAV file named ', outfile]);
    end
end
