function stats = tchPatternStats(patternName, tchType)
% stats = tchPatternStats(patternName, tchType)
%   Reads the error pattern saved in patternName (IF1 format for tchType) and
%   returns various useful statistics in the struct stats:
%       nFrames total number of frames in the pattern
%       fer     fraction of frames with bfi set
%       rber1   residual bit error rate for class 1b bits
%       rber2   residual bit error rate for class 2 bits
%       clean   1 = no bit errors, 0 = at least one bit error
%
% Copyright 2008, Research In Motion Limited.

    nFrames = 0;
    nBadFrames = 0;
    nBits1 = 0;
    nFlips1 = 0;
    nBits2 = 0;
    nFlips2 = 0;
    nFlips = 0;

    fin = fopen(patternName, 'rb');
    while(true)
        p = tchParam(tchType);
        frame = tchReadFrame(fin, p.tchType);
        if isempty(frame)
            break;
        end
        nFrames = nFrames + 1;
        if frame.bfi == 1
            nBadFrames = nBadFrames + 1;
        end
        cb = frame.classBits;
        nBits1 = nBits1 + length(cb{2});
        nFlips1 = nFlips1 + sum(cb{2});
        nBits2 = nBits2 + length(cb{3});
        nFlips2 = nFlips2 + sum(cb{3});
        nFlips = nFlips + sum(cb{1}) + sum(cb{2}) + sum(cb{3});
    end
    fclose(fin);

    stats = struct();
    stats.nFrames = nFrames;
    stats.fer = nBadFrames / nFrames;
    stats.rber1 = nFlips1 / nBits1;
    if nBits2 > 0
        stats.rber2 = nFlips2 / nBits2;
    else
        stats.rber2 = NaN;
    end
    stats.clean = nFlips == 0;
end
