%   tseYUVvideo computes the TSE between two YUV-Files.
%
%	tseYUVvideo('Filename1','Filename1', width, height, format,parameter) reads
%	the specified files using width and height for resolution and format 
%   for YUV-subsampling. With parameter you can chose if you want to
%   compute the TSE between the y, the u, the v, or the yuv part of the
%   videos
%	
%	Filename1 --> Name of File one (e.g. 'Test1.yuv')
%   Filename2 --> Name of File two (e.g. 'Test2.yuv')
%   width    --> width of a frame  (e.g. 352)
%   height   --> height of a frame (e.g. 280)
%   format   --> subsampling rate ('400','411','420','422' or '444')
%   parameter -->chose the components of the video which are used to compute 
%                 the psnr ('y', 'u', 'v', 'yuv') 
%
%   example: tse = tseYUVvideo('Test1.yuv','Test2.yuv',352,288,'420','y');

function tse = tseYUVvideo(File1,File2,width,height,format,parameter)

%set factor for UV-sampling
    fwidth = 0.5;
    fheight= 0.5;
    if strcmp(format,'400')
        fwidth = 0;
        fheight= 0;
    elseif strcmp(format,'411')
        fwidth = 0.25;
        fheight= 1;
    elseif strcmp(format,'420')
        fwidth = 0.5;
        fheight= 0.5;
    elseif strcmp(format,'422')
        fwidth = 0.5;
        fheight= 1;
    elseif strcmp(format,'444')
        fwidth = 1;
        fheight= 1;
    else
        display('Error: wrong format');
    end
    %get Filesize and Framenumber
    filep = dir(File1); 
    fileBytes = filep.bytes; %Filesize1
    clear filep
    framenumber1 = fileBytes/(width*height*(1+2*fheight*fwidth)); %Framenumber1
    filep = dir(File1); 
    fileBytes = filep.bytes; %Filesize2
    clear filep
    total_error = 0;
    framenumber2 = fileBytes/(width*height*(1+2*fheight*fwidth)); %Framenumber2
    if mod(framenumber1,1) ~= 0 | mod(framenumber2,1) ~= 0 | framenumber1~=framenumber2
        display('Error: wrong resolution, format, filesize or different video lengths');
    else
%         h = waitbar(0,'Please wait ...');
        for cntf = 1:framenumber1
%             waitbar(cntf/framenumber1,h);
            %load data of frames
            YUV1 = loadFileYUV(width,height,cntf,File1,fheight,fwidth);
            YUV2 = loadFileYUV(width,height,cntf,File2,fheight,fwidth);
            
            total_error_frame = sum(sum((YUV1-YUV2).^2)); % calculate TSE by summing the squared difference
            total_error = total_error + total_error_frame(:,1)+ total_error_frame(:,2)+total_error_frame(:,3); 
        end
        tse = total_error/framenumber1;
%        close(h);
    end


