import pysam 
import sys
import click

"""
Jia Jinbu, 2020.09.15.

python lima_bam2fasta.py file_bam file_seq

Input: bam file generated by `lima`.

Ouput: fasta file
sequence name is the first column in bam file, ccs sequence name.
the adapter has been't removed by lima.
if alignment is reverse, the sequence will be reverse complemented too.
Thus the sequence should be strand-specific, same with the mRNA direction.
"""

@click.command()
@click.option('-i', '--infile', help='Input adapter-removed ccs bam file generated by lima', 
                    required=True, type=click.Path(exists=True))
@click.option('-o', '--out', help='Output fasta file', required=True)
def main(infile, out):
    with open(out, 'w') as o:
        bam_obj = pysam.AlignmentFile(infile, "rb", check_sq=False)
        for line_data in bam_obj:
            id_ = line_data.qname
            seq = line_data.get_forward_sequence()
            o.write(f'>{id_}\n{seq}\n')
    
if __name__ == "__main__":
    main()
    
if __name__ == "__main__":
    main()

