import csv


def read_biotab(biotab_file, replace_not_available=True, replace_not_applicable=True):
    """
    Reads TCGA Biotab file and returns it as a list of dictionaries.
    Additionally, replaces all [Not Available] fields with None for
    easier parsing later
    """
    assert isinstance(biotab_file, str)
    retval = []
    with open(biotab_file, 'r') as filehandle:
        lines = filehandle.readlines()
    # Remove the 2nd and 3rd lines of the file which are just additional metadata and do not
    # contain useful information
    lines.pop(1)
    lines.pop(1)
    parser = csv.DictReader(lines, delimiter="\t")
    for entry in parser:
        # Replace values in the dictionary that are not available/applicable for easy
        # parsing later on
        for key, value in entry.items():
            if value == "[Not Available]" and replace_not_available:
                entry[key] = None
            elif value == "[Not Applicable]" and replace_not_applicable:
                entry[key] = None
        assert 'bcr_patient_barcode' in entry # Make sure the TCGA barcode is there
        retval.append(entry)
    return retval