# -*- encoding: utf-8 -*-
import sys
import os
import os.path
import glob
import logging
import utils

def raw_counting( T, configs, audit ):
	logging.info( "Performing raw count..." )
	
	# create the directory if it doesn't exist
	if not audit:
		utils.create_directory( configs['RAW_COUNTER_PATH'] )
	
	# read aligned
	read_aligned_files = glob.glob( configs['READ_ALIGNER_PATH'] + "/" + "*.sorted.bam" )
	
	# for each BAM file
	for bamfile in read_aligned_files:
		bamfile_name = os.path.basename( bamfile )
		
		# check whether it has been quantified (whether a folder exists)
		present_files = glob.glob( configs['RAW_COUNTER_PATH'] + "/" + bamfile_name[:-4] + "*" )
		
		# if so skip
		if len( present_files ) > 0:
			logging.warn( "Found quantified files: %s" % ", ".join( present_files ))
			continue
		# else quantify
		else:
			logging.debug( "No quantified files. Proceeding..." )
		
		# get the gtf number to use from the *ebwt<no>.sam name of the SAM file
		e = os.path.basename( bamfile ).split( "." )[0].split( "ebwt" )[1]
		
		# htseq-count --format bam --order name --samout SRR065458_bowtie_ebwt1.txt ../aligned/SRR065458_bowtie_ebwt1.sorted.bam ~/bioinf/Resources/H_sapiens/hg19.chr.gtf > SRR065458_bowtie_ebwt1.count
		cmd = "%s %s --samout %s.txt %s %s > %s" % (
		configs['RAW_COUNTER'],
		configs['RAW_COUNTER_PARAMS'],
		configs['RAW_COUNTER_PATH'] + "/" + bamfile_name[:-4],
		bamfile,
		configs['GTF_PATH' + e],
		configs['RAW_COUNTER_PATH'] + "/" + "%s.count" % bamfile_name )
		
		logging.debug( cmd )
		
		if not audit:
			utils.run_command( cmd )
	

