
format long;
format compact;
clear;


[originalAudio,Fs,bits]=wavread('../encoder/matlab/Suzanne_Vega_-_Toms_Diner_mono');

debugging = 1; 

% When debugging, only use a fragment of the sound
if (debugging==1)
    previewLength = 3; % in Seconds
    offset = 14; % in Seconds
    offsetSamples = offset * Fs;
    previewSamples = previewLength*Fs;
    originalAudio = originalAudio((offsetSamples+1):(previewSamples+offsetSamples));
end; 


norm = max(max(originalAudio),-min(originalAudio));
originalAudio = originalAudio ./ norm;



%//fac1 = 1.8;
%#fac2 = -0.9;

fac1 = 0.14;
fac2 = 0.84;

inp = 0:1/255:1;
outp = inp * fac1 + inp .* inp .* fac2;

plot(inp, outp);



% Now it's time to make the volume tables
% Let's make them volume independent, that is
% First make the distortion, then apply the volume.

inp_int = 0:1:128;
inp_f = inp_int ./ 128.0;
ref = inp_f .* fac1 + inp_f .* inp_f .* fac2
referenceTable = [-ref(128:-1:2) ref];
size(referenceTable)

figure(2);
inp_int = -127:1:128;
plot(inp_int, referenceTable);



% Dump the volume tables into a file

fid = fopen('tube_distortion_table.s','w');
fprintf(fid,'; Tube Distortion table generated by TubeDistortion.m\n');
fprintf(fid,'; this table contains 16*256 values\n');
fprintf(fid,'; Generated on the %s\n',date);
fprintf(fid,'; Pex Mahoney Tufvesson, 2010\n');
fprintf(fid,'\n');
for ta=1:16,
    fprintf(fid,'; Table number %d begins here:\n',ta);
    fprintf(fid,'tube_table_%d:\n',ta);
    for i=1:256,
        volume = 7 + (ta-1)*7.5;
        byte=round(referenceTable(i)*volume);
        if (byte<0),
            byte = byte+256;
        end
        fprintf(fid,'  .byte %d\n',byte);
    end
    fprintf(fid,'; Table number %d ends here.\n',ta);
end
fprintf(fid,'; End of generated data\n');
fprintf(fid,'\n');
fclose(fid);

 






distAudio=zeros(length(originalAudio),1);
for i=1:length(originalAudio),
       distAudio(i) = referenceTable(128+round(originalAudio(i)*127));
end

%distAudio = originalAudio .* fac1 + originalAudio .* originalAudio .* fac2;

sound(originalAudio, Fs);
sound(distAudio, Fs);

