@follows( buildGeneRegions )
@files( [ ("%s.bed" % x, "%s.readcounts" % x ) for x in TRACKS_NOT_UNSTIM ] )
def buildIntervalCounts( infile, outfile ):
    '''count read density in bed files.
    '''
    track = outfile[:-len(".readcounts")]

    cellline, condition, replicate = splitTrack( track )

    samfiles_fg, samfiles_bg = [], []

    # save original, because condition is later assigned to
    one = cellline and condition
    two = condition

    if REPLICATES:
        if one:
            for replicate in REPLICATES:
                samfiles_fg.append( FILEPATTERN % locals() + BAM_SUFFIX )
            condition = "Unstim"
            for replicate in REPLICATES:
                samfiles_bg.append( FILEPATTERN % locals() + BAM_SUFFIX )
        elif two:
            for cellline in CELLLINES:
                for replicate in REPLICATES:
                    samfiles_fg.append( FILEPATTERN % locals() + BAM_SUFFIX )
            condition = "Unstim"
            for cellline in CELLLINES:
                for replicate in REPLICATES:
                    samfiles_bg.append( FILEPATTERN % locals() + BAM_SUFFIX )

    else:
        samfiles_fg.append( FILEPATTERN % locals() + BAM_SUFFIX )
        condition = "Unstim"
        if os.path.exists(FILEPATTERN % locals() + BAM_SUFFIX ):
            samfiles_bg.append( FILEPATTERN % locals() + BAM_SUFFIX )
        else:
            samfiles_bg = samfiles_fg
            
    samfiles_fg = ",".join(samfiles_fg)
    samfiles_bg = ",".join(samfiles_bg)

    tmpfile1 = P.getTempFilename( os.getcwd() ) + ".fg"
    tmpfile2 = P.getTempFilename( os.getcwd() ) + ".bg"

    to_cluster = True

    statement = """
    cat < %(infile)s |\
        python %(scriptsdir)s/bed2gff.py --as-gtf |\
	python %(scriptsdir)s/gtf2table.py \
		--counter=read-coverage \
		--log=%(outfile)s.log \
		--bam-file=%(samfiles_fg)s \
	> %(tmpfile1)s"""

    P.run( **dict( locals().items() + PARAMS.items() ) )

    statement = """
    cat < %(infile)s |\
        python %(scriptsdir)s/bed2gff.py --as-gtf |\
	python %(scriptsdir)s/gtf2table.py \
		--counter=read-coverage \
		--log=%(outfile)s.log \
		--bam-file=%(samfiles_bg)s \
	> %(tmpfile2)s"""

    P.run( **dict( locals().items() + PARAMS.items() ) )

    statement = '''
    python %(toolsdir)s/combine_tables.py \
           --add-file-prefix \
           --regex-filename="[.](\S+)$" \
    %(tmpfile1)s %(tmpfile2)s > %(outfile)s
    '''

    P.run( **dict( locals().items() + PARAMS.items() ) )
    os.unlink( tmpfile1 )
    os.unlink( tmpfile2 )
dataset/ETHPy150Open CGATOxford/cgat/obsolete/pipeline_vitaminD.py/buildIntervalCounts/original