import re


def is_valid_trace(trace):
    """Verify that the trace file being run is well written.
    Each line of the trace must be in the format "(L|S) addr,len"
    """

    try:
        with open(trace) as f:
            trace_data = f.read()
    except:
        print("Could not open {}".format(trace))
        return False

    # Check for empty file
    if not trace_data:
        print("{} is empty, trace contents expected.".format(trace))
        return False

    # Check each line in the file is a valid instruction
    instructions = trace_data.rstrip().splitlines()
    for i, instr in enumerate(instructions, start=1):
        # Note: extra characters at the end of the line are probably ok
        if re.match(r"[LS] [0-9a-fA-F]+,[0-9]+", instr) is None:
            print("\"{}\" is not a well written instruction (line {})".format(instr, i))
            return False

    return True