import logging


def write_all_sams(samlist, outfile):
    """
    Writes all lines of SAM files included in list to output file,
    while excluding any lines with headers (start with @). Filters
    out alignments with 'illegal' tags (de:f:-inf).
    
    :param samlist: list of SAM file names
    :param outfile: name of output SAM file to write to
    :return alncount: count of all legal alignments in SAM
    """
    alncount = int(0)
    for infile in samlist:
        with open(infile, 'r') as fhin, open(outfile, 'a') as fhout:
            for line in fhin:
                if not line.startswith("@") and len(line.split()) > 5:
                    if 'de:f:-inf' in line:
                        logging.info("write_all_sams: found illegal line - {}".format(line))
                    else:
                        fhout.write(line)
                        alncount += 1
        logging.info("write_all_sams: Finished adding SAM: {}".format(infile))
    return alncount