Example #1
0
int main(int argc, char *argv[])
/* Process command line. */
{
cgiSpoof(&argc, argv);
if (argc != 3)
    usage();
doTarget = !cgiBoolean("query");
noHead = (cgiBoolean("nohead") || cgiBoolean("noHead"));
maxPile = cgiOptionalInt("maxPile", maxPile);
minPile = cgiOptionalInt("minPile", minPile);
pslUnpile(argv[1], argv[2]);
return 0;
}
Example #2
0
int main(int argc, char *argv[])
/* Process command line. */
{
cgiSpoof(&argc, argv);
userCount = cgiOptionalInt("userCount", userCount);
randSeed = cgiOptionalInt("randSeed", (int)getpid());
verboseSetLevel(cgiOptionalInt("verbose", 1));
readOnly = cgiVarExists("readOnly");
srand(randSeed);
if (argc != 7)
    usage();
cartSimNoInsert(argv[1], argv[2], argv[3], argv[4], argv[5], argv[6]);
return 0;
}
void checkArguments() 
/** setup our parameters depending on whether we've been called as a
    cgi script or from the command line */ 
{
hgTest = cgiBoolean("hgTest");
numTests = cgiOptionalInt("numTests",0);
origDb = cgiOptionalString("origDb");
origGenome = cgiOptionalString("origGenome");
newGenome = cgiOptionalString("newGenome");
position = cgiOptionalString("position");
chrom = cgiOptionalString("chrom");
chromStart = cgiOptionalInt("chromStart", -1);
chromEnd = cgiOptionalInt("chromEnd", -1);
calledSelf = cgiBoolean("calledSelf");

/* if we're testing we don't need to worry about UI errors */
if(hgTest)
    return;

/* parse the position string and make sure that it makes sense */
if (position != NULL && position[0] != 0)
    {
    parsePosition(cloneString(position), &chrom, &chromStart, &chromEnd);
    }
if (chromStart > chromEnd)
    { 
    webAbort("Error:", "Start of range is greater than end. %d > %d", chromStart, chromEnd);
    }

/* convert the genomes requested to hgN format */
if(origGenome != NULL)
    origGenome = ccFreezeDbConversion(NULL, origGenome, organism);
if(newGenome != NULL) 
    newGenome = ccFreezeDbConversion(NULL, newGenome, organism);

/* make sure that we've got valid arguments */
if((newGenome == NULL || origGenome == NULL || chrom == NULL || chromStart == -1 || chromEnd == -1) && (calledSelf)) 
    webAbort("Error:", "Missing some inputs.");

if( origGenome != NULL && sameString(origGenome, newGenome))
    {
    struct dyString *warning = newDyString(1024);
    dyStringPrintf(warning, "Did you really want to convert from %s to %s (the same genome)?", 
		   ccFreezeDbConversion(origGenome, NULL, organism), \
		   ccFreezeDbConversion(newGenome, NULL, organism));
    appendWarningMsg(warning->string);
    dyStringFree(&warning);
    }
}
int countCassetteExons(struct altGraphX *agList, float minConfidence, FILE *outfile, FILE *bedOutFile)
/* count up the number of cassette exons that have a certain
   confidence, returns number of edges. If outfile != NULL will output fasta sequences
   to outfile. */
{
struct altGraphX *ag = NULL;
int edge =0;
int cassetteCount = 0;
int i =0;
int mod3 = 0;
int counter =0;
boolean outputted = FALSE;
float estPrior = cgiOptionalDouble("estPrior", 10);
FILE *log = mustOpen("confidences.log", "w");
FILE *html = mustOpen("confidences.html", "w");
FILE *sizes = mustOpen("sizes.log", "w");
int minSize = cgiOptionalInt("minSize", 0);
startHtml(html);
for(ag = agList; ag != NULL; ag = ag->next)
    {
    outputted = FALSE;
    for(i=0;i<ag->edgeCount; i++)
	{
	if(ag->edgeTypes[i] == ggCassette)
	    {
	    float conf = altGraphCassetteConfForEdge(ag, i, estPrior);
	    struct bed *bed, *bedList = altGraphGetExonCassette(ag, i);
	    char buff[256];
	    int size = ag->vPositions[ag->edgeEnds[i]] - ag->vPositions[ag->edgeStarts[i]];
	    boolean filtersOk = FALSE;
	    if(ag->name == NULL)
		ag->name = cloneString("");

	    slSort(&bedList, bedCmpMaxScore);
	    for(bed=bedList; bed != NULL; bed = bed->next)
		{
		snprintf(buff, sizeof(buff), "%s.%d", ag->name, counter);
		bed->name = cloneString(buff);
		fprintf(log, "%f\n", conf);
		fprintf(sizes, "%d\n%d\n%d\n", bed->blockSizes[0], bed->blockSizes[1], bed->blockSizes[2]);
		filtersOk = bedPassFilters(bed, ag, i);
		if(conf >= minConfidence && size >= minSize && filtersOk) 
		    {
		    writeCassetteExon(bed, ag, i, &outputted, bedOutFile, outfile, html, conf);
		    cassetteCount++;
		    if((size % 3) == 0)
			mod3++;
		    }
		counter++;
		}
	    bedFreeList(&bedList);
	    }
	}
    }
endHtml(html);
carefulClose(&html);
carefulClose(&log);
warn("%d cassettes are mod 3", mod3);
return cassetteCount;
}
Example #5
0
int main(int argc, char *argv[])
/* Process command line. */
{
cgiSpoof(&argc, argv);
clTest = cgiBoolean("test");
clDots = cgiOptionalInt("dots", clDots);
if (argc != 9)
    usage();
proteinDB = argv[8];
hgRefSeqMrna(argv[1], argv[2], argv[3], argv[4], argv[5], argv[6], argv[7]);
return 0;
}
Example #6
0
/** main html generating function for htmShell */
void doHtml()
{
struct sageExp *seList;
struct sage *sgList;
struct slName *unis = cgiStringList("u");
if(unis == NULL)
    usage();
dataValCeiling = cgiOptionalInt("md",50);
seList = loadSageExps("sageExp", unis);
sgList = loadSageData("sage", unis);
doCountsPage(seList, sgList);
sageExpFreeList(&seList);
sageFreeList(&sgList);
slFreeList(&unis);
}
int main(int argc, char *argv[])
{
struct altGraphX *agList = NULL;
int cassetteCount = 0;
float minConfidence = 0;
char *bedFileName = NULL;
char *faFile = NULL;
FILE *faOut = NULL;
FILE *bedOut = NULL;
boolean mrnaFilter = FALSE;
float estPrior = 0.0;
int minSize = 0;
if(argc < 4)
    usage();
cgiSpoof(&argc, argv);
warn("Loading graphs.");
agList = altGraphXLoadAll(argv[1]);
bedFileName = cgiOptionalString("bedFile");
minConfidence = cgiDouble("minConf");
db = cgiString("db");
faFile = cgiOptionalString("faFile");
estPrior = cgiOptionalDouble("estPrior", 10);
minSize = cgiOptionalInt("minSize", 0);
mrnaFilter = cgiBoolean("mrnaFilter");
if(mrnaFilter)
    loadMrnaHash();
warn("Counting cassette exons from %d clusters above confidence: %f", slCount(agList), minConfidence);
if(bedFileName != NULL)
    {
    bedOut = mustOpen(bedFileName, "w");
    printCommandState(argc, argv, bedOut);
    fprintf(bedOut, "track name=cass_conf-%4.2f_est-%3.2f description=\"spliceStats minConf=%4.2f estPrior=%3.2f minSize=%d\"\n", 
	    minConfidence, estPrior, minConfidence, estPrior, minSize);
    }
if(faFile != NULL)
    faOut = mustOpen(faFile, "w");
cassetteCount = countCassetteExons(agList, minConfidence, faOut,bedOut );
carefulClose(&faOut);
carefulClose(&bedOut);
warn("%d cassette exons out of %d clusters in %s", cassetteCount, slCount(agList), argv[1]);
altGraphXFreeList(&agList);
return 0;
}
Example #8
0
void jsInit()
/* If this is the first call, set window.onload to the operations
 * performed upon loading a page and print supporting javascript.
 * Currently this just sets the page vertical position if specified on
 * CGI, and includes jsHelper.js.
 * Subsequent calls do nothing, so this can be called many times. */
{
if (! jsInited)
    {
    // jsh_pageVertPos trick taken from
    // http://www.softcomplex.com/docs/get_window_size_and_scrollbar_position.html
    puts("<INPUT TYPE=HIDDEN NAME=\"jsh_pageVertPos\" VALUE=0>");
    int pos = cgiOptionalInt("jsh_pageVertPos", 0);
    if (pos > 0)
	{
	jsInlineF("window.onload = function () { window.scrollTo(0, %d); }\n", pos);
	}
    jsInited = TRUE;
    jsIncludeFile("jsHelper.js", NULL);
    }
}
Example #9
0
void jsInit()
/* If this is the first call, set window.onload to the operations
 * performed upon loading a page and print supporting javascript.
 * Currently this just sets the page vertical position if specified on
 * CGI, and also calls jsWriteFunctions.
 * Subsequent calls do nothing, so this can be called many times. */
{
if (! jsInited)
    {
    puts(

"<INPUT TYPE=HIDDEN NAME=\"jsh_pageVertPos\" VALUE=0>\n"
"<script language=\"javascript\">\n"
"// f_scrollTop and f_filterResults taken from\n"
"// http://www.softcomplex.com/docs/get_window_size_and_scrollbar_position.html\n"
"function f_scrollTop() {\n"
"	return f_filterResults (\n"
"		window.pageYOffset ? window.pageYOffset : 0,\n"
"		document.documentElement ? document.documentElement.scrollTop : 0,\n"
"		document.body ? document.body.scrollTop : 0\n"
"	);\n"
"}\n"
"function f_filterResults(n_win, n_docel, n_body) {\n"
"	var n_result = n_win ? n_win : 0;\n"
"	if (n_docel && (!n_result || (n_result > n_docel)))\n"
"		n_result = n_docel;\n"
"	return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;\n"
"}\n"
"</script>\n");
    int pos = cgiOptionalInt("jsh_pageVertPos", 0);
    if (pos > 0)
	printf("\n<script language=\"javascript\">"
	       "window.onload = function () { window.scrollTo(0, %d); }"
	       "</script>\n", pos);
    jsWriteFunctions();
    jsInited = TRUE;
    }
}
Example #10
0
int main(int argc, char *argv[])
{
long enteredMainTime = clock1000();

char *prefix = cgiOptionalString("prefix");
char *database = cgiOptionalString("db");

int exact = cgiOptionalInt("exact", 0);
struct sqlConnection *conn;
char query[2048];
char **row;
struct sqlResult *sr;
int count = 0;
boolean hasKnownCanonical;
struct dyString *str = newDyString(10000);
char *table;

if(prefix == NULL || database == NULL)
    fail("Missing prefix or database parameter");

conn = hAllocConn(database);
table = connGeneSuggestTable(conn);
if(table == NULL)
    fail("gene autosuggest is not supported for this assembly");

hasKnownCanonical = sameString(table, "knownCanonical");

puts("Content-Type:text/plain");
puts("\n");

dyStringPrintf(str, "[\n");

if(exact)
    {
    // NOTE that exact is no longer used by the UI as of v271, but there are still some robots using it so we still support it.
    if(hasKnownCanonical)
        sqlSafef(query, sizeof(query), "select x.geneSymbol, k.chrom, kg.txStart, kg.txEnd, x.kgID, x.description "
              "from knownCanonical k, knownGene kg, kgXref x where k.transcript = x.kgID and k.transcript = kg.name "
              "and x.geneSymbol = '%s' order by x.geneSymbol, k.chrom, kg.txEnd - kg.txStart desc", prefix);
    else
        sqlSafef(query, sizeof(query), "select r.name2, r.chrom, r.txStart, r.txEnd, r.name, description.name "
              "from %s r, gbCdnaInfo, description where r.name2 = '%s' and gbCdnaInfo.acc = r.name "
              "and gbCdnaInfo.description = description.id order by r.name2, r.chrom, r.txEnd - r.txStart desc", table, prefix);
    }
else
    {
    // We use a LIKE query b/c it uses the geneSymbol index (substr queries do not use indices in mysql).
    // Also note that we take advantage of the fact that searches are case-insensitive in mysql.
    // Unfortunately, knownCanonical sometimes has multiple entries for a given gene (e.g. 2 TTn's in mm9 knownCanonical;
    // 3 POU5F1's in hg19); we return all of them (#5962).
    if(hasKnownCanonical)
        sqlSafef(query, sizeof(query), "select x.geneSymbol, k.chrom, kg.txStart, kg.txEnd, x.kgID, x.description "
              "from knownCanonical k, knownGene kg, kgXref x where k.transcript = x.kgID and k.transcript = kg.name "
              "and x.geneSymbol LIKE '%s%%' order by x.geneSymbol, k.chrom, kg.txStart", prefix);
    else
        sqlSafef(query, sizeof(query), "select r.name2, r.chrom, r.txStart, r.txEnd, r.name, description.name "
              "from %s r, gbCdnaInfo, description where r.name2 LIKE '%s%%' and gbCdnaInfo.acc = r.name "
              "and gbCdnaInfo.description = description.id order by r.name2, r.chrom, r.txStart", table, prefix);
    }
sr = sqlGetResult(conn, query);
while ((row = sqlNextRow(sr)) != NULL)
    {
    // ignore funny chroms (e.g. _hap chroms. See redmine #4257.
    if(!strchr(row[1], '_'))
        {
        count++;
        dyStringPrintf(str, "%s{\"value\": \"%s (%s)\", \"id\": \"%s:%d-%s\", \"internalId\": \"%s\"}", count == 1 ? "" : ",\n",
                       row[0], javaScriptLiteralEncode(row[5]), row[1], atoi(row[2])+1, row[3], javaScriptLiteralEncode(row[4]));
        }
    }

dyStringPrintf(str, "\n]\n");
puts(dyStringContents(str));
cgiExitTime("hgSuggest", enteredMainTime);
return 0;
}
Example #11
0
void suggestGene(char *database, char *table, char *prefix)
/* Print out a Javascript list of objects describing genes that start with prefix. */
{
struct dyString *str = newDyString(10000);
dyStringPrintf(str, "[\n");

int exact = cgiOptionalInt("exact", 0);
boolean hasKnownCanonical = sameString(table, "knownCanonical");
initGenbankTableNames(database);
char query[2048];
if(exact)
    {
    // NOTE that exact is no longer used by the UI as of v271, but there are still some robots
    // using it so we still support it.
    if(hasKnownCanonical)
        sqlSafef(query, sizeof(query),
                 "select x.geneSymbol, k.chrom, kg.txStart, kg.txEnd, x.kgID, x.description "
                 "from knownCanonical k, knownGene kg, kgXref x "
                 "where k.transcript = x.kgID and k.transcript = kg.name and x.geneSymbol = '%s' "
                 "order by x.geneSymbol, k.chrom, kg.txEnd - kg.txStart desc", prefix);
    else
        sqlSafef(query, sizeof(query),
                 "select r.name2, r.chrom, r.txStart, r.txEnd, r.name, d.name "
                 "from %s r, %s g, %s d "
                 "where r.name2 = '%s' and g.acc = r.name and g.description = d.id "
                 "order by r.name2, r.chrom, r.txEnd - r.txStart desc",
                 table, gbCdnaInfoTable, descriptionTable, prefix);
    }
else
    {
    // We use a LIKE query b/c it uses the geneSymbol index (substr queries do not use indices in mysql).
    // Also note that we take advantage of the fact that searches are case-insensitive in mysql.
    // Unfortunately, knownCanonical sometimes has multiple entries for a given gene (e.g. 2 TTn's in mm9 knownCanonical;
    // 3 POU5F1's in hg19); we return all of them (#5962).
    if(hasKnownCanonical)
        sqlSafef(query, sizeof(query),
                 "select x.geneSymbol, k.chrom, kg.txStart, kg.txEnd, x.kgID, x.description "
                 "from knownCanonical k, knownGene kg, kgXref x "
                 "where k.transcript = x.kgID and k.transcript = kg.name "
                 "and x.geneSymbol LIKE '%s%%' "
                 "order by x.geneSymbol, k.chrom, kg.txStart", prefix);
    else
        sqlSafef(query, sizeof(query), "select r.name2, r.chrom, r.txStart, r.txEnd, r.name, d.name "
                 "from %s r, %s g, %s d "
                 "where r.name2 LIKE '%s%%' and g.acc = r.name and g.description = d.id "
                 "order by r.name2, r.chrom, r.txStart",
                 table, gbCdnaInfoTable, descriptionTable, prefix);
    }
struct sqlConnection *conn = hAllocConn(database);
struct sqlResult *sr = sqlGetResult(conn, query);
char **row;
int count = 0;
while ((row = sqlNextRow(sr)) != NULL)
    {
    // ignore funny chroms (e.g. _hap chroms. See redmine #4257.
    if(!strchr(row[1], '_'))
        {
        // We have some very long descriptions, e.g. 4277 chars for hg38 CLOCK, so truncate:
        const int maxDesc = 120;
        char *description = row[5];
        if (strlen(description) > maxDesc + 4)
            strcpy(description + maxDesc, "...");
        count++;
        dyStringPrintf(str, "%s{\"value\": \"%s (%s)\", "
                       "\"id\": \"%s:%d-%s\", "
                       "\"geneSymbol\": \"%s\", "
                       "\"internalId\": \"%s\"}",
                       count == 1 ? "" : ",\n", row[0], jsonStringEscape(description),
                       row[1], atoi(row[2])+1, row[3],
                       jsonStringEscape(row[0]),
                       jsonStringEscape(row[4]));
        }
    }
hFreeConn(&conn);
dyStringPrintf(str, "\n]\n");
puts(dyStringContents(str));
}
static void hgSeqConcatRegionsDb(char *db, char *chrom, int chromSize, char strand, char *name,
                                 int rCount, unsigned *rStarts, unsigned *rSizes,
                                 boolean *exonFlags, boolean *cdsFlags)
/* Concatenate and print out dna for a series of regions. */
{
// Note: this code use to generate different sequence ids if the global
// database in hdb was different than the db parameter.  This functionality
// has been removed since the global database was removed and it didn't
// appear to be used.

    struct dnaSeq *rSeq = NULL;
    struct dnaSeq *cSeq = NULL;
    char recName[256];
    int seqStart, seqEnd;
    int offset, cSize;
    int i;
    boolean isRc     = (strand == '-') || cgiBoolean("hgSeq.revComp");
    boolean maskRep  = cgiBoolean("hgSeq.maskRepeats");
    int padding5     = cgiOptionalInt("hgSeq.padding5", 0);
    int padding3     = cgiOptionalInt("hgSeq.padding3", 0);
    char *casing     = cgiString("hgSeq.casing");
    char *repMasking = cgiString("hgSeq.repMasking");
    char *granularity  = cgiOptionalString("hgSeq.granularity");
    boolean concatRegions = granularity && sameString("gene", granularity);

    if (rCount < 1)
        return;

    /* Don't support padding if granularity is gene (i.e. concat'ing all). */
    if (concatRegions)
    {
        padding5 = padding3 = 0;
    }

    i = rCount - 1;
    seqStart = rStarts[0]             - (isRc ? padding3 : padding5);
    seqEnd   = rStarts[i] + rSizes[i] + (isRc ? padding5 : padding3);
    /* Padding might push us off the edge of the chrom; if so, truncate: */
    if (seqStart < 0)
    {
        if (isRc)
            padding3 += seqStart;
        else
            padding5 += seqStart;
        seqStart = 0;
    }

    /* if we know the chromSize, don't pad out beyond it */
    if ((chromSize > 0) && (seqEnd > chromSize))
    {
        if (isRc)
            padding5 += (chromSize - seqEnd);
        else
            padding3 += (chromSize - seqEnd);
        seqEnd = chromSize;
    }
    if (seqEnd <= seqStart)
    {
        printf("# Null range for %s_%s (range=%s:%d-%d 5'pad=%d 3'pad=%d) (may indicate a query-side insert)\n",
               db,
               name,
               chrom, seqStart+1, seqEnd,
               padding5, padding3);
        return;
    }
    if (maskRep)
    {
        rSeq = hDnaFromSeq(db, chrom, seqStart, seqEnd, dnaMixed);
        if (sameString(repMasking, "N"))
            lowerToN(rSeq->dna, strlen(rSeq->dna));
        if (!sameString(casing, "upper"))
            tolowers(rSeq->dna);
    }
    else if (sameString(casing, "upper"))
        rSeq = hDnaFromSeq(db, chrom, seqStart, seqEnd, dnaUpper);
    else
        rSeq = hDnaFromSeq(db, chrom, seqStart, seqEnd, dnaLower);

    /* Handle casing and compute size of concatenated sequence */
    cSize = 0;
    for (i=0;  i < rCount;  i++)
    {
        if ((sameString(casing, "exon") && exonFlags[i]) ||
                (sameString(casing, "cds") && cdsFlags[i]))
        {
            int rStart = rStarts[i] - seqStart;
            toUpperN(rSeq->dna+rStart, rSizes[i]);
        }
        cSize += rSizes[i];
    }
    cSize += (padding5 + padding3);
    AllocVar(cSeq);
    cSeq->dna = needLargeMem(cSize+1);
    cSeq->size = cSize;

    offset = 0;
    for (i=0;  i < rCount;  i++)
    {
        int start = rStarts[i] - seqStart;
        int size  = rSizes[i];
        if (i == 0)
        {
            start -= (isRc ? padding3 : padding5);
            assert(start == 0);
            size  += (isRc ? padding3 : padding5);
        }
        if (i == rCount-1)
        {
            size  += (isRc ? padding5 : padding3);
        }
        memcpy(cSeq->dna+offset, rSeq->dna+start, size);
        offset += size;
    }
    assert(offset == cSeq->size);
    cSeq->dna[offset] = 0;
    freeDnaSeq(&rSeq);

    if (isRc)
        reverseComplement(cSeq->dna, cSeq->size);

    safef(recName, sizeof(recName),
          "%s_%s range=%s:%d-%d 5'pad=%d 3'pad=%d "
          "strand=%c repeatMasking=%s",
          db,
          name,
          chrom, seqStart+1, seqEnd,
          padding5, padding3,
          (isRc ? '-' : '+'),
          (maskRep ? repMasking : "none"));
    faWriteNext(stdout, recName, cSeq->dna, cSeq->size);
    freeDnaSeq(&cSeq);
}
Example #13
0
boolean doCellRow(struct hash *ra, char *org)
// print one cell row
{
char *s;

s = hashFindVal(ra, ORGANISM);
if (s != NULL)
    {
    char *cellOrg = cloneString(s);
    strLower(cellOrg);
    if (differentString(cellOrg, org))
        return FALSE;
    }

// pathBuffer for new protocols not in human
char pathBuffer[PATH_LEN];
safef(pathBuffer, sizeof(pathBuffer), "/ENCODE/protocols/cell/%s/",org);

if (sameWord(org, ORG_HUMAN))
    {
    if (cgiOptionalInt("tier",0))
        {
        if (hashFindVal(ra,"tier") == NULL)
            return FALSE;
        if (atoi(hashFindVal(ra,"tier"))!=cgiOptionalInt("tier",0))
            return FALSE;
        }
    if (cgiOptionalString("tiers"))
        {
        if (hashFindVal(ra,"tier") == NULL)
            return FALSE;
        boolean found=FALSE;
        char *tiers=cloneString(cgiOptionalString("tiers"));
        char *tier;
        (void)strSwapChar(tiers,',',' ');
        while ((tier=nextWord(&tiers)))
            {
            if (atoi(hashFindVal(ra,"tier"))==atoi(tier))
                {
                found=TRUE;
                break;
                }
            }
        if (!found)
            return FALSE;
        }
    puts("<TR>");
    char *term = printTerm(ra);

    printSetting(ra, "tier");
    printDescription(ra,NULL,-1);
    printSetting(ra,"lineage");
    printSetting(ra,"tissue");
    printSetting(ra,"karyotype");
    printSetting(ra,"sex");
    printDocumentLink(ra,term,"protocol",pathBuffer,NULL,TRUE);
    printSettingsWithUrls(ra,"orderUrl","vendorName","vendorId");
    printSettingsWithUrls(ra,"termUrl","termId",NULL);
    printLabel(ra,term);
    puts("</TR>");
    }
else        // non-human cell type
    {
    puts("<TR>");
    char *term = printTerm(ra);

    printDescription(ra,NULL,8);
    printSetting(ra,"category");
    printSetting(ra,"tissue");
    printSetting(ra,"sex");
    //printSetting(ra,"karyotype");
    printDocumentLink(ra,term,"protocol",pathBuffer,NULL,TRUE);
    printSettingsWithUrls(ra,"orderUrl","vendorName","vendorId");
    printSettingsWithUrls(ra,"termUrl","termId",NULL);
    printLabel(ra,term);
    puts("</TR>");

    }
return TRUE;
}
Example #14
0
int main(int argc, char *argv[])
{
long enteredMainTime = clock1000();
struct dyString *output = newDyString(10000);

setUdcCacheDir();
cgiSpoof(&argc, argv);
pushWarnHandler(htmlVaBadRequestAbort);
pushAbortHandler(htmlVaBadRequestAbort);

char *database = cgiString("db");
char *cmd = cgiString("cmd");
char *jsonp = cgiOptionalString("jsonp");
if (!hDbExists(database))
    errAbort("Invalid database '%s'", database);

if (!strcmp(cmd, "defaultPos"))
    {
    dyStringPrintf(output, "{\"pos\": \"%s\"}", hDefaultPos(database));
    }
else if (!strcmp(cmd, "metaDb"))
    {
    // Return list of values for given metaDb var
    // e.g. http://genome.ucsc.edu/hgApi?db=hg18&cmd=metaDb&var=cell

    struct sqlConnection *conn = hAllocConn(database);
    boolean metaDbExists = sqlTableExists(conn, "metaDb");
    if (metaDbExists)
        {
        char *var = cgiOptionalString("var");
        if (!var)
            errAbort("Missing var parameter");
        boolean fileSearch = (cgiOptionalInt("fileSearch",0) == 1);
        struct slPair *pairs = mdbValLabelSearch(conn, var, MDB_VAL_STD_TRUNCATION, FALSE,
                                                 !fileSearch, fileSearch);
        struct slPair *pair;
        dyStringPrintf(output, "[\n");
        for (pair = pairs; pair != NULL; pair = pair->next)
            {
            if (pair != pairs)
                dyStringPrintf(output, ",\n");
            dyStringPrintf(output, "['%s','%s']", javaScriptLiteralEncode(mdbPairLabel(pair)),
                           javaScriptLiteralEncode(mdbPairVal(pair)));
            }
        dyStringPrintf(output, "\n]\n");
        }
    else
        errAbort("Assembly does not support metaDb");
    }
// TODO: move to lib since hgTracks and hgApi share
#define METADATA_VALUE_PREFIX    "hgt_mdbVal"
else if (startsWith(METADATA_VALUE_PREFIX, cmd))
    {
    // Returns metaDb value control: drop down or free text, with or without help link.
    // e.g. http://genome.ucsc.edu/hgApi?db=hg18&cmd=hgt_mdbVal3&var=cell

    // TODO: Move guts to lib, so that hgTracks::searchTracks.c and hgApi.c can share

    struct sqlConnection *conn = hAllocConn(database);
    boolean metaDbExists = sqlTableExists(conn, "metaDb");
    if (metaDbExists)
        {
        char *var = cgiOptionalString("var");
        if (!var)
            errAbort("Missing var parameter");

        int ix = atoi(cmd+strlen(METADATA_VALUE_PREFIX)); // 1 based index
        if (ix == 0) //
            errAbort("Unsupported 'cmd' parameter");

        enum cvSearchable searchBy = cvSearchMethod(var);
        char name[128];
        safef(name,sizeof name,"%s%i",METADATA_VALUE_PREFIX,ix);
        if (searchBy == cvSearchBySingleSelect || searchBy == cvSearchByMultiSelect)
            {
            boolean fileSearch = (cgiOptionalInt("fileSearch",0) == 1);
            struct slPair *pairs = mdbValLabelSearch(conn, var, MDB_VAL_STD_TRUNCATION, FALSE,
                                                     !fileSearch, fileSearch);
            if (slCount(pairs) > 0)
                {
                char *dropDownHtml =
                                cgiMakeSelectDropList((searchBy == cvSearchByMultiSelect),
                                                      name, pairs, NULL, ANYLABEL, "mdbVal",
                                                      "style='min-width: 200px; font-size: .9em;' "
                                                      "onchange='findTracksMdbValChanged(this);'");
                if (dropDownHtml)
                    {
                    dyStringAppend(output,dropDownHtml);
                    freeMem(dropDownHtml);
                    }
                slPairFreeList(&pairs);
                }
            }
        else if (searchBy == cvSearchByFreeText)
            {
            dyStringPrintf(output,"<input type='text' name='%s' value='' class='mdbVal freeText' "
                           "onchange='findTracksMdbValChanged(this);' style='max-width:310px; "
                           "width:310px; font-size:.9em;'>", name);
            }
        else if (searchBy == cvSearchByWildList)
            {
            dyStringPrintf(output,"<input type='text' name='%s' value='' class='mdbVal wildList' "
                           "title='enter comma separated list of values' "
                           "onchange='findTracksMdbValChanged(this);' style='max-width:310px; "
                           "width:310px; font-size:.9em;'>", name);
            }
        else if (searchBy == cvSearchByDateRange || searchBy == cvSearchByIntegerRange)
            {
            // TO BE IMPLEMENTED
            }
        else
            errAbort("Metadata variable not searchable");

        dyStringPrintf(output,"<span id='helpLink%i'>&nbsp;</span>",ix);
        }
    else
        errAbort("Assembly does not support metaDb");
    }
else if (!strcmp(cmd, "tableMetadata"))
    { // returns an html table with metadata for a given track
    char *trackName = cgiOptionalString("track");
    boolean showLonglabel = (NULL != cgiOptionalString("showLonglabel"));
    boolean showShortLabel = (NULL != cgiOptionalString("showShortLabel"));
    if (trackName != NULL)
        {
        // hTrackDbForTrackAndAncestors avoids overhead of getting whole track list!
        struct trackDb *tdb = hTrackDbForTrackAndAncestors(database, trackName);
        if (tdb != NULL)
            {
            char * html = metadataAsHtmlTable(database,tdb,showLonglabel,showShortLabel);
            if (html)
                {
                dyStringAppend(output,html);
                freeMem(html);
                }
            else
                dyStringPrintf(output,"No metadata found for track %s.",trackName);
            }
        else
            dyStringPrintf(output,"Track %s not found",trackName);
        }
    else
        dyStringAppend(output,"No track variable found");
    }
else if (sameString(cmd, "codonToPos") || sameString(cmd, "exonToPos"))
    {
    char query[256];
    struct sqlResult *sr;
    char **row;
    struct genePred *gp;
    char *name = cgiString("name");
    char *table = cgiString("table");
    int num = cgiInt("num");
    struct sqlConnection *conn = hAllocConn(database);
    sqlSafef(query, sizeof(query), "select name, chrom, strand, txStart, txEnd, cdsStart, cdsEnd, exonCount, exonStarts, exonEnds from %s where name = '%s'", table, name);
    sr = sqlGetResult(conn, query);
    if ((row = sqlNextRow(sr)) != NULL)
        {
        gp = genePredLoad(row);
        boolean found;
        int start, end;
        if (sameString(cmd, "codonToPos"))
            found = codonToPos(gp, num, &start, &end);
        else
            found = exonToPos(gp, num, &start, &end);
        if (found)
            dyStringPrintf(output, "{\"pos\": \"%s:%d-%d\"}", gp->chrom, start + 1, end);
        else
            dyStringPrintf(output, "{\"error\": \"%d is an invalid %s for this gene\"}", num, sameString(cmd, "codonToPos") ? "codon" : "exon");
        }
    else
        dyStringPrintf(output, "{\"error\": \"Couldn't find item: %s\"}", name);
    sqlFreeResult(&sr);
    hFreeConn(&conn);
    }
else
    {
    warn("unknown cmd: %s",cmd);
    errAbort("Unsupported 'cmd' parameter");
    }

apiOut(dyStringContents(output), jsonp);
cgiExitTime("hgApi", enteredMainTime);
return 0;
}
Example #15
0
int main(int argc, char *argv[])
{
long enteredMainTime = clock1000();

cgiSpoof(&argc, argv);
char *prefix = cgiOptionalString("prefix");
char *database = cgiOptionalString("db");

initGenbankTableNames(database);

int exact = cgiOptionalInt("exact", 0);
struct sqlConnection *conn;
char query[2048];
char **row;
struct sqlResult *sr;
int count = 0;
boolean hasKnownCanonical;
struct dyString *str = newDyString(10000);
char *table;

pushAbortHandler(htmlVaBadRequestAbort);
if(prefix == NULL || database == NULL)
    errAbort("%s", "Missing prefix and/or db CGI parameter");

conn = hAllocConn(database);
table = connGeneSuggestTable(conn);
if(table == NULL)
    errAbort("gene autosuggest is not supported for db '%s'", database);
popAbortHandler();

hasKnownCanonical = sameString(table, "knownCanonical");

puts("Content-Type:text/plain");
puts("\n");

dyStringPrintf(str, "[\n");

if(exact)
    {
    // NOTE that exact is no longer used by the UI as of v271, but there are still some robots using it so we still support it.
    if(hasKnownCanonical)
        sqlSafef(query, sizeof(query), "select x.geneSymbol, k.chrom, kg.txStart, kg.txEnd, x.kgID, x.description "
              "from knownCanonical k, knownGene kg, kgXref x where k.transcript = x.kgID and k.transcript = kg.name "
              "and x.geneSymbol = '%s' order by x.geneSymbol, k.chrom, kg.txEnd - kg.txStart desc", prefix);
    else
        sqlSafef(query, sizeof(query), "select r.name2, r.chrom, r.txStart, r.txEnd, r.name, d.name "
              "from %s r, %s g, %s d where r.name2 = '%s' and g.acc = r.name "
              "and g.description = d.id order by r.name2, r.chrom, r.txEnd - r.txStart desc", table, gbCdnaInfoTable, descriptionTable, prefix);
    }
else
    {
    // We use a LIKE query b/c it uses the geneSymbol index (substr queries do not use indices in mysql).
    // Also note that we take advantage of the fact that searches are case-insensitive in mysql.
    // Unfortunately, knownCanonical sometimes has multiple entries for a given gene (e.g. 2 TTn's in mm9 knownCanonical;
    // 3 POU5F1's in hg19); we return all of them (#5962).
    if(hasKnownCanonical)
        sqlSafef(query, sizeof(query), "select x.geneSymbol, k.chrom, kg.txStart, kg.txEnd, x.kgID, x.description "
              "from knownCanonical k, knownGene kg, kgXref x where k.transcript = x.kgID and k.transcript = kg.name "
              "and x.geneSymbol LIKE '%s%%' order by x.geneSymbol, k.chrom, kg.txStart", prefix);
    else
        sqlSafef(query, sizeof(query), "select r.name2, r.chrom, r.txStart, r.txEnd, r.name, d.name "
              "from %s r, %s g, %s d where r.name2 LIKE '%s%%' and g.acc = r.name "
              "and g.description = d.id order by r.name2, r.chrom, r.txStart", table, gbCdnaInfoTable, descriptionTable, prefix);
    }
sr = sqlGetResult(conn, query);
while ((row = sqlNextRow(sr)) != NULL)
    {
    // ignore funny chroms (e.g. _hap chroms. See redmine #4257.
    if(!strchr(row[1], '_'))
        {
        // We have some very long descriptions, e.g. 4277 chars for hg38 CLOCK, so truncate:
        const int maxDesc = 120;
        char *description = row[5];
        if (strlen(description) > maxDesc + 4)
            strcpy(description + maxDesc, "...");
        count++;
        dyStringPrintf(str, "%s{\"value\": \"%s (%s)\", "
                       "\"id\": \"%s:%d-%s\", "
                       "\"geneSymbol\": \"%s\", "
                       "\"internalId\": \"%s\"}",
                       count == 1 ? "" : ",\n", row[0], jsonStringEscape(description),
                       row[1], atoi(row[2])+1, row[3],
                       jsonStringEscape(row[0]),
                       jsonStringEscape(row[4]));
        }
    }

dyStringPrintf(str, "\n]\n");
puts(dyStringContents(str));
cgiExitTime("hgSuggest", enteredMainTime);
return 0;
}
int main(int argc, char *argv[])
{
char *genoListName;
char *otherListName;
char *oocFileName;
char *typeName;
char *outName;
struct patSpace *patSpace;
long startTime, endTime;
char **genoList;
int genoListSize;
char *genoListBuf;
char **otherList;
int otherListSize;
char *otherListBuf;
char *genoName;
int i;
int blockCount = 0;
struct dnaSeq **seqListList = NULL, *seq = NULL;
char *outRoot;
struct sqlConnection *conn;
enum ffStringency stringency = ffCdna;
int seedSize = 10;
FILE *out;
boolean noHead = FALSE;
struct repeatTracker *rt;
struct hash *repeatHash = newHash(10);

hostName = getenv("HOST");
pushWarnHandler(warnHandler);

startTime = clock1();
cgiSpoof(&argc, argv);
minMatch = cgiOptionalInt("minMatch", minMatch);
maxBad = cgiOptionalInt("maxBad", maxBad);
minBases = cgiOptionalInt("minBases", minBases);

dnaUtilOpen();

#ifdef DEBUG
/* Hard wire command line input so don't have to type it in each 
 * time run the stupid Gnu debugger. */

genoListName = "pFoo/geno.lst";
otherListName = "pFoo/bacend.lst";
typeName = "genomic";
oocFileName = "/d/biodata/human/10.ooc";
outName = "pFoo/pFoo.psl";

#else

if (argc != 6 && argc != 7)
    usage();

genoListName = argv[1];
otherListName = argv[2];
typeName = argv[3];
oocFileName = argv[4];
if (sameWord(oocFileName, "none"))
    oocFileName = NULL;
outName = argv[5];
if (argc == 7)
    {
    if (sameWord("noHead", argv[6]))
	noHead = TRUE;
    else
	usage();
    }

#endif 

if (sameWord(typeName, "mRNA") || sameWord(typeName, "cDNA"))
    {
    stringency = ffCdna;
    }
else if (sameWord(typeName, "genomic"))
    {
    stringency = ffTight;
    }
else if (sameWord(typeName, "g2g"))
    {
    stringency = ffTight;
    veryTight = TRUE;
    seedSize = 11;
    }
else if (sameString(typeName, "asm"))
    {
    stringency = ffTight;
    avoidSelfSelf = TRUE;
    }
else
    {
    warn("Unrecognized otherType %s\n", typeName);
    usage();
    }

readAllWordsOrFa(genoListName, &genoList, &genoListSize, &genoListBuf);
filterMissingFiles(genoList, &genoListSize);
if (genoListSize <= 0)
    errAbort("There are no files that exist in %s\n", genoListName);
readAllWordsOrFa(otherListName, &otherList, &otherListSize, &otherListBuf);
if (otherListSize <= 0)
    errAbort("There are no files that exist in %s\n", otherListName);
filterMissingFiles(otherList, &otherListSize);
out = mustOpen(outName, "w");
if (!noHead)
    pslWriteHead(out);

AllocArray(seqListList, genoListSize);
for (i=0; i<genoListSize; ++i)
    {
    genoName = genoList[i];
    if (!startsWith("#", genoName)  )
        seqListList[i] = seq = faReadAllDna(genoName);
    for (;seq != NULL; seq = seq->next)
	{
	int size = seq->size;
	char *name = seq->name;
	struct hashEl *hel;
	AllocVar(rt);
	AllocArray(rt->repBytes, size);
	rt->seq = seq;
	if ((hel = hashLookup(repeatHash, name)) != NULL)
	    errAbort("Duplicate %s in %s\n", name, genoName);
	hashAdd(repeatHash, name, rt);
	}
    storeMasked(repeatHash, genoName);
    }

patSpace = makePatSpace(seqListList, genoListSize, seedSize, oocFileName, minMatch, 2000);
endTime = clock1();
printf("Made index in %ld seconds\n",  (endTime-startTime));
startTime = endTime;

for (i=0; i<otherListSize; ++i)
    {
    FILE *f;
    char *otherName;
    int c;
    int dotCount = 0;
    struct dnaSeq otherSeq;
    ZeroVar(&otherSeq);

    otherName = otherList[i];
    if (startsWith("#", otherName)  )
	continue;
    f = mustOpen(otherName, "r");
    while ((c = fgetc(f)) != EOF)
	if (c == '>')
	    break;
    printf("%s\n", otherName);
    fflush(stdout);
    while (faFastReadNext(f, &otherSeq.dna, &otherSeq.size, &otherSeq.name))
        {
	aliSeqName = otherSeq.name;
	oneStrand(patSpace, repeatHash, &otherSeq, FALSE, stringency, out);
	reverseComplement(otherSeq.dna, otherSeq.size);
	oneStrand(patSpace, repeatHash, &otherSeq, TRUE, stringency, out);
	aliSeqName = NULL;
        }
    fclose(f);
    }
freePatSpace(&patSpace);
endTime = clock1();
printf("Alignment time is %ld sec\n", (endTime-startTime));
startTime = endTime;
fclose(out);
return 0;
}
int hgSeqBed(char *db, struct hTableInfo *hti, struct bed *bedList)
/* Print out dna sequence from the given database of all items in bedList.
 * hti describes the bed-compatibility level of bedList items.
 * Returns number of FASTA records printed out. */
{
    struct bed *bedItem;
    char itemName[128];
    boolean isRc;
    int count;
    unsigned *starts = NULL;
    unsigned *sizes = NULL;
    boolean *exonFlags = NULL;
    boolean *cdsFlags = NULL;
    int i, rowCount, totalCount;
    boolean promoter   = cgiBoolean("hgSeq.promoter");
    boolean intron     = cgiBoolean("hgSeq.intron");
    boolean utrExon5   = cgiBoolean("hgSeq.utrExon5");
    boolean utrIntron5 = utrExon5 && intron;
    boolean cdsExon    = cgiBoolean("hgSeq.cdsExon");
    boolean cdsIntron  = cdsExon && intron;
    boolean utrExon3   = cgiBoolean("hgSeq.utrExon3");
    boolean utrIntron3 = utrExon3 && intron;
    boolean downstream = cgiBoolean("hgSeq.downstream");
    int promoterSize   = cgiOptionalInt("hgSeq.promoterSize", 0);
    int downstreamSize = cgiOptionalInt("hgSeq.downstreamSize", 0);
    char *granularity  = cgiOptionalString("hgSeq.granularity");
    boolean concatRegions = granularity && sameString("gene", granularity);
    boolean concatAdjacent = (cgiBooleanDefined("hgSeq.splitCDSUTR") &&
                              (! cgiBoolean("hgSeq.splitCDSUTR")));
    boolean isCDS, doIntron;
    boolean canDoUTR, canDoIntrons;

    /* catch a special case: introns selected, but no exons -> include all introns
     * instead of qualifying intron with exon flags. */
    if (intron && !(utrExon5 || cdsExon || utrExon3))
    {
        utrIntron5 = cdsIntron = utrIntron3 = TRUE;
    }

    canDoUTR = hti->hasCDS;
    canDoIntrons = hti->hasBlocks;

    rowCount = totalCount = 0;
    for (bedItem = bedList;  bedItem != NULL;  bedItem = bedItem->next)
    {
        if (bedItem->blockCount == 0) /* An intersection may have made hti unreliable. */
            canDoIntrons = FALSE;
        rowCount++;
        int chromSize = hgSeqChromSize(db, bedItem->chrom);
        // bed: translate relative starts to absolute starts
        for (i=0;  i < bedItem->blockCount;  i++)
        {
            bedItem->chromStarts[i] += bedItem->chromStart;
        }
        isRc = (bedItem->strand[0] == '-');
        // here's the max # of feature regions:
        if (canDoIntrons)
            count = 4 + (2 * bedItem->blockCount);
        else
            count = 5;
        maxStartsOffset = count-1;
        starts    = needMem(sizeof(unsigned) * count);
        sizes     = needMem(sizeof(unsigned) * count);
        exonFlags = needMem(sizeof(boolean) * count);
        cdsFlags  = needMem(sizeof(boolean) * count);
        // build up a list of selected regions
        count = 0;
        if (!isRc && promoter && (promoterSize > 0))
        {
            addFeature(&count, starts, sizes, exonFlags, cdsFlags,
                       (bedItem->chromStart - promoterSize), promoterSize,
                       FALSE, FALSE, chromSize);
        }
        else if (isRc && downstream && (downstreamSize > 0))
        {
            addFeature(&count, starts, sizes, exonFlags, cdsFlags,
                       (bedItem->chromStart - downstreamSize), downstreamSize,
                       FALSE, FALSE, chromSize);
        }
        if (canDoIntrons && canDoUTR)
        {
            for (i=0;  i < bedItem->blockCount;  i++)
            {
                if ((bedItem->chromStarts[i] + bedItem->blockSizes[i]) <=
                        bedItem->thickStart)
                {
                    if ((!isRc && utrExon5)   || (isRc && utrExon3))
                    {
                        addFeature(&count, starts, sizes, exonFlags, cdsFlags,
                                   bedItem->chromStarts[i], bedItem->blockSizes[i],
                                   TRUE, FALSE, chromSize);
                    }
                    if (((!isRc && utrIntron5) || (isRc && utrIntron3)) &&
                            (i < bedItem->blockCount - 1))
                    {
                        addFeature(&count, starts, sizes, exonFlags, cdsFlags,
                                   (bedItem->chromStarts[i] +
                                    bedItem->blockSizes[i]),
                                   (bedItem->chromStarts[i+1] -
                                    bedItem->chromStarts[i] -
                                    bedItem->blockSizes[i]),
                                   FALSE, FALSE, chromSize);
                    }
                }
                else if (bedItem->chromStarts[i] < bedItem->thickEnd)
                {
                    if ((bedItem->chromStarts[i] < bedItem->thickStart) &&
                            ((bedItem->chromStarts[i] + bedItem->blockSizes[i]) >
                             bedItem->thickEnd))
                    {
                        if ((!isRc && utrExon5)	  || (isRc && utrExon3))
                        {
                            addFeature(&count, starts, sizes, exonFlags, cdsFlags,
                                       bedItem->chromStarts[i],
                                       (bedItem->thickStart -
                                        bedItem->chromStarts[i]),
                                       TRUE, FALSE, chromSize);
                        }
                        if (cdsExon)
                        {
                            addFeature(&count, starts, sizes, exonFlags, cdsFlags,
                                       bedItem->thickStart,
                                       (bedItem->thickEnd - bedItem->thickStart),
                                       TRUE, TRUE, chromSize);
                        }
                        if ((!isRc && utrExon3)	  || (isRc && utrExon5))
                        {
                            addFeature(&count, starts, sizes, exonFlags, cdsFlags,
                                       bedItem->thickEnd,
                                       (bedItem->chromStarts[i] +
                                        bedItem->blockSizes[i] -
                                        bedItem->thickEnd),
                                       TRUE, FALSE, chromSize);
                        }
                    }
                    else if (bedItem->chromStarts[i] < bedItem->thickStart)
                    {
                        if ((!isRc && utrExon5)	  || (isRc && utrExon3))
                        {
                            addFeature(&count, starts, sizes, exonFlags, cdsFlags,
                                       bedItem->chromStarts[i],
                                       (bedItem->thickStart -
                                        bedItem->chromStarts[i]),
                                       TRUE, FALSE, chromSize);
                        }
                        if (cdsExon)
                        {
                            addFeature(&count, starts, sizes, exonFlags, cdsFlags,
                                       bedItem->thickStart,
                                       (bedItem->chromStarts[i] +
                                        bedItem->blockSizes[i] -
                                        bedItem->thickStart),
                                       TRUE, TRUE, chromSize);
                        }
                    }
                    else if ((bedItem->chromStarts[i] + bedItem->blockSizes[i]) >
                             bedItem->thickEnd)
                    {
                        if (cdsExon)
                        {
                            addFeature(&count, starts, sizes, exonFlags, cdsFlags,
                                       bedItem->chromStarts[i],
                                       (bedItem->thickEnd -
                                        bedItem->chromStarts[i]),
                                       TRUE, TRUE, chromSize);
                        }
                        if ((!isRc && utrExon3)	  || (isRc && utrExon5))
                        {
                            addFeature(&count, starts, sizes, exonFlags, cdsFlags,
                                       bedItem->thickEnd,
                                       (bedItem->chromStarts[i] +
                                        bedItem->blockSizes[i] -
                                        bedItem->thickEnd),
                                       TRUE, FALSE, chromSize);
                        }
                    }
                    else if (cdsExon)
                    {
                        addFeature(&count, starts, sizes, exonFlags, cdsFlags,
                                   bedItem->chromStarts[i], bedItem->blockSizes[i],
                                   TRUE, TRUE, chromSize);
                    }
                    isCDS = ! ((bedItem->chromStarts[i] + bedItem->blockSizes[i]) >
                               bedItem->thickEnd);
                    doIntron = (isCDS ? cdsIntron :
                                ((!isRc) ? utrIntron3 : utrIntron5));
                    if (doIntron && (i < bedItem->blockCount - 1))
                    {
                        addFeature(&count, starts, sizes, exonFlags, cdsFlags,
                                   (bedItem->chromStarts[i] +
                                    bedItem->blockSizes[i]),
                                   (bedItem->chromStarts[i+1] -
                                    bedItem->chromStarts[i] -
                                    bedItem->blockSizes[i]),
                                   FALSE, isCDS, chromSize);
                    }
                }
                else
                {
                    if ((!isRc && utrExon3)   || (isRc && utrExon5))
                    {
                        addFeature(&count, starts, sizes, exonFlags, cdsFlags,
                                   bedItem->chromStarts[i], bedItem->blockSizes[i],
                                   TRUE, FALSE, chromSize);
                    }
                    if (((!isRc && utrIntron3) || (isRc && utrIntron5)) &&
                            (i < bedItem->blockCount - 1))
                    {
                        addFeature(&count, starts, sizes, exonFlags, cdsFlags,
                                   (bedItem->chromStarts[i] +
                                    bedItem->blockSizes[i]),
                                   (bedItem->chromStarts[i+1] -
                                    bedItem->chromStarts[i] -
                                    bedItem->blockSizes[i]),
                                   FALSE, FALSE, chromSize);
                    }
                }
            }
        }
        else if (canDoIntrons)
        {
            for (i=0;  i < bedItem->blockCount;  i++)
            {
                if (cdsExon)
                {
                    addFeature(&count, starts, sizes, exonFlags, cdsFlags,
                               bedItem->chromStarts[i], bedItem->blockSizes[i],
                               TRUE, FALSE, chromSize);
                }
                if (cdsIntron && (i < bedItem->blockCount - 1))
                {
                    addFeature(&count, starts, sizes, exonFlags, cdsFlags,
                               (bedItem->chromStarts[i] + bedItem->blockSizes[i]),
                               (bedItem->chromStarts[i+1] -
                                bedItem->chromStarts[i] -
                                bedItem->blockSizes[i]),
                               FALSE, FALSE, chromSize);
                }
            }
        }
        else if (canDoUTR)
        {
            if (bedItem->thickStart == 0 && bedItem->thickEnd == 0)
                bedItem->thickStart = bedItem->thickEnd = bedItem->chromStart;
            if ((!isRc && utrExon5)   || (isRc && utrExon3))
            {
                addFeature(&count, starts, sizes, exonFlags, cdsFlags,
                           bedItem->chromStart,
                           (bedItem->thickStart - bedItem->chromStart),
                           TRUE, FALSE, chromSize);
            }
            if (cdsExon)
            {
                addFeature(&count, starts, sizes, exonFlags, cdsFlags,
                           bedItem->thickStart,
                           (bedItem->thickEnd - bedItem->thickStart),
                           TRUE, TRUE, chromSize);
            }
            if ((!isRc && utrExon3)   || (isRc && utrExon5))
            {
                addFeature(&count, starts, sizes, exonFlags, cdsFlags,
                           bedItem->thickEnd,
                           (bedItem->chromEnd - bedItem->thickEnd),
                           TRUE, FALSE, chromSize);
            }
        }
        else
        {
            addFeature(&count, starts, sizes, exonFlags, cdsFlags,
                       bedItem->chromStart,
                       (bedItem->chromEnd - bedItem->chromStart),
                       TRUE, FALSE, chromSize);
        }
        if (!isRc && downstream && (downstreamSize > 0))
        {
            addFeature(&count, starts, sizes, exonFlags, cdsFlags,
                       bedItem->chromEnd, downstreamSize, FALSE, FALSE, chromSize);
        }
        else if (isRc && promoter && (promoterSize > 0))
        {
            addFeature(&count, starts, sizes, exonFlags, cdsFlags,
                       bedItem->chromEnd, promoterSize, FALSE, FALSE, chromSize);
        }
        snprintf(itemName, sizeof(itemName), "%s_%s", hti->rootName, bedItem->name);
        hgSeqRegionsAdjDb(db, bedItem->chrom, chromSize, bedItem->strand[0], itemName,
                          concatRegions, concatAdjacent,
                          count, starts, sizes, exonFlags, cdsFlags);
        totalCount += count;
        freeMem(starts);
        freeMem(sizes);
        freeMem(exonFlags);
        freeMem(cdsFlags);
    }
    return totalCount;
}