code: def index(args):
      
      p = OptionParser(index.__doc__)
      p.add_option("--fasta", dest="fasta", default=None,
              help="add @SQ header to the BAM file [default: %default]")
      p.add_option("--unique", default=False, action="store_true",
              help="only retain uniquely mapped reads [default: %default]")
      p.set_cpus()
      opts, args = p.parse_args(args)
  
      if len(args) != 1:
          sys.exit(p.print_help())
  
      samfile, = args
      cpus = opts.cpus
      fastafile = opts.fasta
      if fastafile:
          assert op.exists(fastafile)
  
      bamfile = samfile.replace(".sam", ".bam")
      if fastafile:
          faifile = fastafile + ".fai"
          if need_update(fastafile, faifile):
              sh("samtools faidx {0}".format(fastafile))
          cmd = "samtools view -bt {0} {1} -o {2}".\
                  format(faifile, samfile, bamfile)
      else:
          cmd = "samtools view -bS {0} -o {1}".\
                  format(samfile, bamfile)
  
      cmd += " -@ {0}".format(cpus)
      if opts.unique:
          cmd += " -q 1"
  
      if samfile.endswith(".sam") and need_update(samfile, bamfile):
          sh(cmd)
  
      # Already sorted?
      if bamfile.endswith(".sorted.bam"):
          sortedbamfile = bamfile
      else:
          prefix = bamfile.replace(".bam", "")
          sortedbamfile = prefix + ".sorted.bam"
  
      if need_update(bamfile, sortedbamfile):
          cmd = "samtools sort {0} -o {1}".format(bamfile, sortedbamfile)
          cmd += " -@ {0}".format(cpus)
          sh(cmd)
  
      baifile = sortedbamfile + ".bai"
      if need_update(sortedbamfile, baifile):
          sh("samtools index {0}".format(sortedbamfile))
  
      return sortedbamfile
docs: %prog index samfile/bamfile
  
      If SAM file, convert to BAM, sort and then index, using SAMTOOLS