def PIG2Stream(fname, beam=0, time_unit=0.5, fixtempo=0):
    """
    Convert a PIG text file to a music21 Stream object.

    time_unit must be multiple of 2.
    beam = 0, right hand
    beam = 1, left hand.
    """
    from music21 import stream, note, chord
    from music21.articulations import Fingering
    import numpy as np
    f = open(fname, 'r')
    lines = f.readlines()
    f.close()
    durations = []
    firstonset = 0
    blines = []
    for l in lines:
        if l.startswith('//'):
            continue
        _, onset, offset, name, _, _, channel, _ = l.split()
        onset, offset = float(onset), float(offset)
        if beam != int(channel):
            continue
        if not firstonset:
            firstonset = onset
        if offset - onset < 0.0001:
            continue
        durations.append(offset - onset)
        blines.append(l)
    durations = np.array(durations)
    logdurs = -np.log2(durations)
    mindur = np.min(logdurs)
    expos = (logdurs - mindur).astype(int)
    if np.max(expos) > 3:
        mindur = mindur + 1
    sf = stream.Part()
    sf.id = beam
    if not fixtempo and firstonset:
        r = note.Rest()
        logdur = -np.log2(firstonset)
        r.duration.quarterLength = 1.0 / time_unit / pow(2, int(logdur -
            mindur))
        sf.append(r)
    n = len(blines)
    for i in range(n):
        if blines[i].startswith('//'):
            continue
        _, onset, offset, name, _, _, _, finger = blines[i].split()
        onset, offset = float(onset), float(offset)
        name = name.replace('b', '-')
        chordnotes = [name]
        for j in range(1, 5):
            if i + j < n:
                noteid1, onset1, offset1, name1, _, _, _, finger1 = blines[
                    i + j].split()
                onset1 = float(onset1)
                if onset1 == onset:
                    name1 = name1.replace('b', '-')
                    chordnotes.append(name1)
        if len(chordnotes) > 1:
            an = chord.Chord(chordnotes)
        else:
            an = note.Note(name)
            if '_' not in finger:
                x = Fingering(abs(int(finger)))
                x.style.absoluteY = 20
            an.articulations.append(x)
        if fixtempo:
            an.duration.quarterLength = fixtempo
        else:
            logdur = -np.log2(offset - onset)
            an.duration.quarterLength = 1.0 / time_unit / pow(2, int(logdur -
                mindur))
        sf.append(an)
        if i + 1 < n:
            _, onset1, _, _, _, _, _, _ = blines[i + 1].split()
            onset1 = float(onset1)
            if onset1 - offset > 0:
                r = note.Rest()
                if fixtempo:
                    r.duration.quarterLength = fixtempo
                logdur = -np.log2(onset1 - offset)
                d = int(logdur - mindur)
                if d < 4:
                    r.duration.quarterLength = 1.0 / time_unit / pow(2, d)
                    sf.append(r)
    return sf
