Пример #1
0
int main(int argc, char *argv[])
/* Process command line. */
{
cgiSpoof(&argc, argv);
if (argc != 4)
    usage();
if (!isdigit(argv[2][0]))
    usage();
splitFile(argv[1], atoi(argv[2]), argv[3], cgiOptionalString("head"), cgiOptionalString("tail"));
return 0;
}
Пример #2
0
int main(int argc, char *argv[])
{
cgiSpoof(&argc, argv);
seqIdent = cgiOptionalDouble("seqIdent",.9);
basePct = cgiOptionalDouble("basePct", .9);
pslIn = cgiOptionalString("in");
pslOut = cgiOptionalString("out");
if(pslIn == NULL || pslOut==NULL)
    usage();
filterPsls();
return 0;
}
int main(int argc, char *argv[])
/* Process command line. */
{
cgiSpoof(&argc, argv);
if (argc < 2)
    usage();
recurse = cgiBoolean("r");
suffix = cgiOptionalString("suffix");
wildCard = cgiOptionalString("wild");
nonz = cgiBoolean("nonz");
catDir(argc-1, argv+1);
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);
    }
}
Пример #5
0
void doGenePredPal(struct sqlConnection *conn)
/* Output genePred protein alignment. */
{
if (doGalaxy() && !cgiOptionalString(hgtaDoGalaxyQuery))
    {
    sendParamsToGalaxy(hgtaDoPalOut, "submit");
    return;
    }

/* get rid of pesky cookies that would bring us back here */
cartRemove(cart, hgtaDoPal);
cartRemove(cart, hgtaDoPalOut);

if (anyIntersection() && intersectionIsBpWise())
    errAbort("Can't do CDS FASTA output when bit-wise intersection is on. "
    "Please go back and select another output type, or clear the intersection.");
checkNoGenomeDisabled(database, curTable);

struct lm *lm = lmInit(64*1024);
int fieldCount;
struct bed *bedList = cookedBedsOnRegions(conn, curTable, getRegions(),
	lm, &fieldCount);

//lmCleanup(&lm);

textOpen();

int outCount = palOutPredsInBeds(conn, cart, bedList, curTable);

/* Do some error diagnostics for user. */
if (outCount == 0)
    explainWhyNoResults(NULL);
}
Пример #6
0
void cartJsonExecute(struct cartJson *cj)
/* Get commands from cgi, print Content-type, execute commands, print results as JSON. */
{
cartJsonPushErrHandlers();
puts("Content-Type:text/javascript\n");

// Initialize response JSON object:
jsonWriteObjectStart(cj->jw, NULL);
// Always send back hgsid:
jsonWriteString(cj->jw, cartSessionVarName(), cartSessionId(cj->cart));

char *commandJson = cgiOptionalString(CARTJSON_COMMAND);
if (commandJson)
    {
    struct jsonElement *commandObj = jsonParse(commandJson);
    struct hash *commandHash = jsonObjectVal(commandObj, "commandObj");
    // change* commands need to go first!  Really we need an ordered map type here...
    // for now, just make a list and sort to put change commands at the front.
    struct slPair *commandList = NULL, *cmd;
    struct hashCookie cookie = hashFirst(commandHash);
    struct hashEl *hel;
    while ((hel = hashNext(&cookie)) != NULL)
        slAddHead(&commandList, slPairNew(hel->name, hel->val));
    slSort(&commandList, commandCmp);
    for (cmd = commandList;  cmd != NULL;  cmd = cmd->next)
	doOneCommand(cj, cmd->name, (struct jsonElement *)cmd->val);
    }

cartJsonPrintWarnings(cj->jw);
jsonWriteObjectEnd(cj->jw);
puts(cj->jw->dy->string);
cartJsonPopErrHandlers();
}
Пример #7
0
void printOrgAssemblyListAxtInfo(char *dbCgi, char *javascript)
/* Find all the organisms/assemblies that are referenced in axtInfo,
 * and print the dropdown list. */
{
struct dbDb *dbList = hGetAxtInfoDbs(dbCgi);
char *assemblyList[128];
char *values[128];
int numAssemblies = 0;
struct dbDb *cur = NULL;
char *assembly = cgiOptionalString(dbCgi);
char orgAssembly[256];

for (cur = dbList; ((cur != NULL) && (numAssemblies < 128)); cur = cur->next)
    {
    safef(orgAssembly, sizeof(orgAssembly), "%s %s",
	  cur->organism, cur->description);
    assemblyList[numAssemblies] = cloneString(orgAssembly);
    values[numAssemblies] = cur->name;
    numAssemblies++;
    }

#ifdef OLD
// Have to use the "menu" name, not the value, to mark selected:
if (assembly != NULL)
    {
    char *selOrg    = hOrganism(assembly);
    char *selFreeze = hFreezeFromDb(assembly);
    safef(orgAssembly, sizeof(orgAssembly), "%s %s", selOrg, selFreeze);
    assembly = cloneString(orgAssembly);
    }
#endif /* OLD */

cgiMakeDropListFull(dbCgi, assemblyList, values, numAssemblies, assembly,
		    javascript);
}
Пример #8
0
void doMiddle(struct cart *theCart)
/* Set up globals and make web page */
{
char *database = cgiOptionalString("db");
char *rtdbServer = cfgOption("rtdb.server");
char *rtdbPort = cfgOption("rtdb.port");
char *rtdbChoices = cfgOption("rtdb.databases");
struct slName *dbs = slNameListFromComma(rtdbChoices);
cart = theCart;
cartWebStart(cart, database, "MGC RTDB Update");
if (!rtdbServer)
    errAbort("rtdb.update not defined in the hg.conf file. "
	     "Chances are this CGI isn't meant for this machine.");
if (!rtdbPort)
    errAbort("rtdb.update not defined in the hg.conf file. "
	     "Chances are this CGI isn't meant for this machine.");
/* create HMTL form if button wasn't pressed.  Otherwise, run the update */
if (!cgiVarExists("RTDBSubmit"))
    makeForm(dbs);
else if ((database == NULL) || (!slNameInList(dbs, database)))
    {
    makeForm(dbs);
    printf("<br>Error: Select one of databases listed.");
    }
else
    updateServer(rtdbServer, rtdbPort, database);
cartWebEnd();
slNameFreeList(&dbs);
}
int main(int argc, char *argv[])
/* Process command line. */
{
oldVars = hashNew(10);
cgiSpoof(&argc, argv);

/* org has precedence over db when changeInfo='orgChange' */
orgChange = sameOk(cgiOptionalString("changeInfo"),"orgChange");
if (orgChange)
    {
    cgiVarSet("db", hDefaultDbForGenome(cgiOptionalString("org"))); 
    }

htmlSetBackground(hBackgroundImage());
cartEmptyShell(doMiddle, hUserCookie(), excludeVars, oldVars);
return 0;
}
Пример #10
0
void doMiddle(struct cart *theCart)
/* Write header and body of html page. */
{
char *userSeq;
char *db, *organism;
boolean clearUserSeq = cgiBoolean("Clear");

cart = theCart;
dnaUtilOpen();

orgChange = sameOk(cgiOptionalString("changeInfo"),"orgChange");
if (orgChange)
    {
    cgiVarSet("db", hDefaultDbForGenome(cgiOptionalString("org"))); 
    }
getDbAndGenome(cart, &db, &organism, oldVars);
char *oldDb = cloneString(db);
findClosestServer(&db, &organism);

/* Get sequence - from userSeq variable, or if 
 * that is empty from a file. */
if (clearUserSeq)
    {
    cartSetString(cart, "userSeq", "");
    cartSetString(cart, "seqFile", "");
    }
userSeq = cartUsualString(cart, "userSeq", "");
if (isEmpty(userSeq))
    {
    userSeq = cartOptionalString(cart, "seqFile");
    }
if (isEmpty(userSeq) || orgChange)
    {
    cartWebStart(theCart, db, "%s BLAT Search", trackHubSkipHubName(organism));
    if (differentString(oldDb, db))
	printf("<HR><P><EM><B>Note:</B> BLAT search is not available for %s %s; "
	       "defaulting to %s %s</EM></P><HR>\n",
	       hGenome(oldDb), hFreezeDate(oldDb), organism, hFreezeDate(db));
    askForSeq(organism,db);
    cartWebEnd();
    }
else 
    {
    blatSeq(skipLeadingSpaces(userSeq), organism);
    }
}
Пример #11
0
void doMiddle()
/* Create middle of html form. */
{
char *nt = cgiOptionalString("NT");
if (nt != NULL)
    alignNt(nt);
else
    showAllNts();
}
Пример #12
0
void checkForGeoMirrorRedirect(struct cart *cart)
// Implement Geo/IP based redirection.
{
char *thisNodeStr = geoMirrorNode();
if (thisNodeStr)   // if geo-mirroring is enabled
    {
    char *redirectCookie = findCookieData("redirect");
    char *redirect = cgiOptionalString("redirect");

    // if we're not already redirected
    if (redirect == NULL && redirectCookie == NULL) 
        {
        int thisNode = sqlUnsigned(thisNodeStr);
        struct sqlConnection *centralConn = hConnectCentral();
        char *ipStr = cgiRemoteAddr();
        int node = defaultNode(centralConn, ipStr);

        // if our node is not the node that's closest.
        if (thisNode != node)
            {
	    char *geoSuffix = cfgOptionDefault("browser.geoSuffix","");
            char query[1056];
            sqlSafef(query, sizeof query, "select domain from gbNode%s where node = %d", geoSuffix, node);
            char *newDomain = sqlQuickString(centralConn, query);
            char *oldDomain = cgiServerName();
            char *port = cgiServerPort();
            char *uri = cgiRequestUri();
            char *sep = strchr(uri, '?') ? "&" : "?";
            int newUriSize = strlen(uri) + 1024;
            char *newUri = needMem(newUriSize);
            char *oldUri = needMem(newUriSize);
            safef(oldUri, newUriSize, "http%s://%s:%s%s%sredirect=manual&source=%s", 
		cgiServerHttpsIsOn() ? "s" : "", oldDomain, port, uri, sep, oldDomain);
            safef(newUri, newUriSize, "http%s://%s:%s%s%sredirect=manual&source=%s", 
		cgiServerHttpsIsOn() ? "s" : "", newDomain, port, uri, sep, oldDomain);

	    printf("<TR><TD COLSPAN=3 id='redirectTd' onclick=\"javascript:document.getElementById('redirectTd').innerHTML='';\">"
	    "<div style=\"margin: 10px 25%%; border-style:solid; border-width:thin; border-color:#97D897;\">"
	    "<h3 style=\"background-color: #97D897; text-align: left; margin-top:0px; margin-bottom:0px;\">"
	    "&nbsp;You might want to navigate to your nearest mirror - %s"
	    "</h3> "
	    "<ul style=\"margin:5px;\">",
	    newDomain);
	    
	    printf("<li>User settings (sessions and custom tracks) <B>will differ</B> between sites."
		"<idiv style=\"float:right;\"><a href=\"../goldenPath/help/genomeEuro.html#sessions\">Read more.</a></idiv>");
	    printf("<li>Take me to  <a href=\"%s\">%s</a> </li>",
		newUri, newDomain);
	    printf("<li>Let me stay here   <a href=\"%s\">%s</a>",
		oldUri, oldDomain );
	    printf("</div></TD></TR>\n");
            exit(0);
            }
        hDisconnectCentral(&centralConn);
        }
    }
}
Пример #13
0
void doMiddle(struct cart *theCart)
/* Depending on invocation, either perform a query and print out results
 * or display the main page. */
{
cart = theCart;
if (cgiOptionalString(CARTJSON_COMMAND))
    doCartJson();
else
    doMainPage();
}
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;
}
int main(int argc, char *argv[])
/* Process command line. */
{
cgiSpoof(&argc, argv);
stretch = cgiBoolean("stretch");
if (argc != 4)
    usage();
uniqSize(argv[1], argv[2], argv[3], cgiOptionalString("altFile"));
return 0;
}
Пример #16
0
int main(int argc, char *argv[])
/* Process command line. */
{
cgiSpoof(&argc, argv);
chromName = cgiOptionalString("chrom");
if (argc != 3)
    usage();
intronEnds(argv[1], argv[2]);
return 0;
}
int main(int argc, char *argv[])
/* Process command line. */
{
cgiSpoof(&argc, argv);
if (cgiVarExists("db"))
    {
    database=cgiOptionalString("db");
    }

cartEmptyShell(doMiddle, hUserCookie(), excludeVars, oldVars);
return 0;
}
Пример #18
0
static char *getSearchTermUpperCase()
/* If we don't have the SEARCH_TERM cgi param, exit with an HTTP Bad Request response.
 * If we do, convert it to upper case for case-insensitive matching and return it. */
{
pushAbortHandler(htmlVaBadRequestAbort);
char *term = cgiOptionalString(SEARCH_TERM);
touppers(term);
if (isEmpty(term))
    errAbort("Missing required CGI parameter %s", SEARCH_TERM);
popAbortHandler();
return term;
}
Пример #19
0
int main(int argc, char *argv[])
{
long enteredMainTime = clock1000();

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

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

if (sameOk(type, ALT_OR_PATCH))
    suggestAltOrPatch(database, prefix);
else
    suggestGene(database, table, prefix);

cgiExitTime("hgSuggest", enteredMainTime);
return 0;
}
Пример #20
0
void doGenePredSequence(struct sqlConnection *conn)
/* Output genePred sequence. */
{
char *type = cartString(cart, hgtaGeneSeqType);

if (sameWord(type, "protein"))
    {
    if (doGalaxy() && !cgiOptionalString(hgtaDoGalaxyQuery))
        sendParamsToGalaxy(hgtaDoGenePredSequence, "submit");
    else
        doGenePredNongenomic(conn, 1);
    }
else if (sameWord(type, "mRNA"))
    {
    if (doGalaxy() && !cgiOptionalString(hgtaDoGalaxyQuery))
        sendParamsToGalaxy(hgtaDoGenePredSequence, "submit");
    else
        doGenePredNongenomic(conn, 2);
    }
else
    genomicFormatPage(conn);
}
int main(int argc, char *argv[]) 
{
char *outputFormat = NULL;
if(argc < 4)
    usage();
cgiSpoof(&argc, argv);
dnaUtilOpen();
outputFormat = cgiOptionalString("output");
if(outputFormat == NULL)
    outputFormat = "sample";
mergeAffyFiles(argv[1], argv[2], argc-3, argv+3, outputFormat);
return 0;
}
Пример #22
0
void getUrl(struct sqlConnection *conn)
/* Put up URL. */
{
edwMustGetUserFromEmail(conn, userEmail);
printf("Please enter a URL for a validated manifest file:<BR>");
printf("URL ");
cgiMakeTextVar("url", emptyForNull(cgiOptionalString("url")), 80);
cgiMakeButton("submitUrl", "submit");
printf("<BR>\n");
cgiMakeCheckBox("update", FALSE);
printf(" Update information associated with files that have already been uploaded.");
printf("<BR>Submission by %s", userEmail);
edwPrintLogOutButton();
}
Пример #23
0
int main(int argc, char *argv[])
/* Process CGI / command line. */
{
/* Null terminated list of CGI Variables we don't want to save
 * permanently. */
char *excludeVars[] = {SEARCH_TERM, CARTJSON_COMMAND, NULL,};
cgiSpoof(&argc, argv);
setUdcCacheDir();
if (cgiOptionalString(SEARCH_TERM))
    // Skip the cart for speedy searches
    lookupTerm();
else
    {
    oldVars = hashNew(10);
    cartEmptyShellNoContent(doMiddle, hUserCookie(), excludeVars, oldVars);
    }
return 0;
}
Пример #24
0
static void activatePslTrackIfCgi(struct track *tg)
/* the publications hgc creates links back to the browser with 
 * the cgi param pubsFilterArticleId to show only a single type
 * of feature for the pubsBlatPsl track. 
 * If the parameter was supplied, we save it here 
 * into the cart and activate the track.
 */
{
char *articleId = cgiOptionalString(PUBSFILTERNAME);
//if (articleId==NULL) 
    //articleId = cartOptionalString(cart, PUBSFILTERNAME);

if (articleId!=NULL) 
{
    cartSetString(cart, PUBSFILTERNAME, articleId);
    tdbSetCartVisibility(tg->tdb, cart, hCarefulTrackOpenVis(database, tg->track));
    tg->visibility=tvPack;
}
}
Пример #25
0
void jsMakeSetClearButton(struct cart *cart,
			  char *form, char *buttonVar, char *buttonLabel,
			  char *cartVarPrefix, struct slName *cartVarSuffixList,
			  char *anchor, boolean currentPos, boolean isSet)
/* Make a button for setting or clearing all of a list of boolean
 * cart variables (i.e. checkboxes).  If this button was just pressed,
 * set or clear those cart variables.
 * Optional html anchor is appended to the form's action if given.
 * If currentPos, anchor is ignored and jsSetVerticalPosition is used so
 * that the new page gets the same vertical offset as the current page. */
{
struct slName *suffix;
char javascript[2048];
char *vertPosJs = "";
if (currentPos)
    {
    anchor = NULL;
    jsInit();
    vertPosJs = jsSetVerticalPosition(form);
    }
cgiMakeHiddenVar(buttonVar, "");
safef(javascript, sizeof javascript,
      "document.%s.action = '%s%s%s'; document.%s.%s.value='%s'; %s"
      "document.%s.submit();",
      form, cgiScriptName(),
      (isNotEmpty(anchor) ? "#" : ""), (isNotEmpty(anchor) ? anchor : ""),
      form, buttonVar, buttonLabel, vertPosJs, form);
cgiMakeOnClickButton(javascript, buttonLabel);

if (isNotEmpty(cgiOptionalString(buttonVar)))
    {
    char option[1024];
    if (cartVarPrefix == NULL)
	cartVarPrefix = "";
    for (suffix = cartVarSuffixList;  suffix != NULL;  suffix = suffix->next)
        {
        safef(option, sizeof(option), "%s%s", cartVarPrefix, suffix->name);
        cartSetBoolean(cart, option, isSet);
        }
    }
}
Пример #26
0
void dispatch(struct sqlConnection *conn)
/* Dispatch page after to routine depending on cdwCommand variable */
{
char *userName = wikiLinkUserName();
if (userName==NULL)
    user = NULL;
else
    user = cdwUserFromUserName(conn, userName);

char *acc = cgiOptionalString("acc");
char *path = getenv("PATH_INFO"); // CGI gets trailing /x/y/z like path via this env. var.

if (acc != NULL)
    sendFileByAcc(conn, acc);
else if (path != NULL)
    sendFileByPath(conn, path);
else
    errExit("Need at least the HTTP GET parameter 'acc' with an accession ID " 
    "or a file path directly after the CGI name, "
    "separated by '/', e.g. cdwGetFile/valData/ce10/ce10.2bit';", NULL);

}
Пример #27
0
void cartMain(struct cart *theCart)
/* We got the persistent/CGI variable cart.  Now
 * set up the globals and make a web page. */
{
struct sqlConnection *conn = NULL;
cart = theCart;
getDbAndGenome(cart, &database, &genome, oldCart);

/* !!! force database to hiv1 until move to server hiv1 is complete
   and the default database of hgcentral on it point to hiv1. */

conn = hAllocConn(database);

curSubjId = cgiOptionalString("hgs_subj");
if (curSubjId == NULL) curSubjId = strdup("");

cartHtmlStart("HIV Vaccine Subject View");
webMain(conn);

hFreeConn(&conn);

cartHtmlEnd();
}
Пример #28
0
void doMiddle()
/* Write HTML file to stdout. */
{
char *mapName;
if ((mapName = cgiOptionalString("map")) != NULL)
    {
    printf("<TT>\n");
    doMap(mapName);
    }
else if (cgiVarExists("contig"))
    {
    doFuzzyFind();
    }
else
    {
    char *bacAcc = cgiString("bacAcc");
    char *repeatMask = cgiString("repeatMask");
    int trim = cgiInt("trim");
    if (trim < 0)
        trim = 0;
    bacTrack(bacAcc, trim, repeatMask);
    }
}
Пример #29
0
int main(int argc, char *argv[])
/* Process command line */
{
long enteredMainTime = clock1000();
cgiSpoof(&argc, argv);
termOpt = cgiOptionalString(CV_TERM);
tagOpt = cgiOptionalString(CV_TAG);
typeOpt = cgiOptionalString(CV_TYPE);
targetOpt = cgiOptionalString(CV_TARGET);
labelOpt = cgiOptionalString(CV_LABEL);
organismOpt = cgiUsualString(ORGANISM, organismOpt);
if (organismOpt != NULL)
    {
    organismOptLower=cloneString(organismOpt);
    strLower(organismOptLower);
    }
char *bgColor = cgiOptionalString("bgcolor");
if (bgColor)
    htmlSetBgColor(strtol(bgColor, 0, 16));
htmlSetStyle(htmlStyleUndecoratedLink);
htmShell("ENCODE Controlled Vocabulary", doMiddle, "get");
cgiExitTime("hgEncodeVocab", enteredMainTime);
return 0;
}
Пример #30
0
void doMiddle(struct cart *theCart)
/* Print the body of an html file.   */
{
char cond_str[255];
struct sqlConnection *conn;
char *proteinAC;
char *chp, *chp1, *chp9;
char *debugTmp = NULL;
char *chromStr, *cdsStartStr, *cdsEndStr, posStr[255];

char *supportedGenomeDatabase;

char *answer;
char *queryID;

/* Initialize layout and database. */
cart = theCart;

/* Uncomment this to see parameters for debugging. */
/* Be careful though, it breaks if custom track
 * is more than 4k */
/*
{ struct dyString *state = cgiUrlString();
  hPrintf("State: %s\n", state->string);
}
*/

queryID = cartOptionalString(cart, "proteinID");
if (sameString(queryID, ""))
    {
    hUserAbort("Please go back and enter a gene symbol or a Swiss-Prot/TrEMBL protein ID.\n");
    }

if (cgiVarExists("db"))
    {
    /* if db is known, get key variables set */
    proteinInSupportedGenome = TRUE;
    database = cgiOptionalString("db");
    organism = hDbOrganism(database);
    protDbName = hPdbFromGdb(database);
    proteinID  = strdup(queryID);
    }
else
    {
    protCntInSwissByGene = searchProteinsInSwissProtByGene(queryID);
    /* no CGI 'db' variable means it did not come in from GB but from pbGateway */
    /* search existing GB databases to see if this protein can be found */
    protCntInSupportedGenomeDb =
        searchProteinsInSupportedGenomes(queryID, &supportedGenomeDatabase);
    if ((protCntInSupportedGenomeDb > 1) || protCntInSwissByGene >= 1)
        {
	/* more than 1 proteins match the query ID, present selection web page */
	proteinInSupportedGenome = 1;
	presentProteinSelections(queryID, protCntInSwissByGene, protCntInSupportedGenomeDb);
	return;
	}
    else
        {
	if (protCntInSupportedGenomeDb == 1)
	    {
	    /* one and only one protein found in a genome DB that support KG and PB */
	    proteinInSupportedGenome = TRUE;
	    database = strdup(supportedGenomeDatabase);
	    organism = hDbOrganism(database);
	    protDbName = hPdbFromGdb(database);
            proteinID=strdup(queryID);
	    }
	else
	    {
	    /* not found in genome DBs that support KG/PB */
	    /* now search PROTEOME_DB_NAMES to see if this protein is there. */

	    answer = uniProtFindPrimAcc(queryID);
	    if (answer == NULL)
		{
	        hUserAbort("'%s' does not seem to be a valid UniProtKB protein ID or a gene "
	                   "symbol.<br><br>Click <A HREF=\"../cgi-bin/pbGateway\">here</A> "
	                   "to start another query.", queryID);
                }

	    proteinInSupportedGenome = FALSE;
	    database = strdup(GLOBAL_PB_DB);
	    organism = strdup("");
            protDbName = strdup(PROTEOME_DB_NAME);
	    proteinID = strdup(answer);
	    }
	}

    if (proteinInSupportedGenome)
        {
        spConn = sqlConnect(database);
        sqlSafefFrag(cond_str, sizeof(cond_str), "alias='%s'", queryID);
        proteinID = sqlGetField(database, "kgSpAlias", "spID", cond_str);

        sqlSafefFrag(cond_str, sizeof(cond_str), "spID='%s'", proteinID);
        answer = sqlGetField(database, "kgXref", "spDisplayID", cond_str);

	sqlSafefFrag(cond_str, sizeof(cond_str), "proteinID='%s'", answer);
        chromStr    = sqlGetField(database, "knownGene", "chrom", cond_str);
	if (chromStr)
	    {
	    cdsStartStr = sqlGetField(database, "knownGene", "cdsStart", cond_str);
	    cdsEndStr   = sqlGetField( database, "knownGene", "cdsEnd", cond_str);
	    safef(posStr, sizeof(posStr), "%s:%s-%s", chromStr, cdsStartStr, cdsEndStr);
	    positionStr = strdup(posStr);
	    cartSetString(cart, "position", positionStr);
	    cartSetString(cart, "organism", organism);
	    }
	}
    }
/* print out key variables for debugging */
/* printf("<br>before enter main section: <br>proteinInSupportedGenome=%d<br>proteinID=%s <br>database=%s <br>organism=%s <br>protDbName=%s\n",
proteinInSupportedGenome, proteinID, database, organism, protDbName);fflush(stdout);
*/

if (hTableExists(database, "kgProtMap2"))
    {
    kgVersion = KG_III;
    strcpy(kgProtMapTableName, "kgProtMap2");
    }

debugTmp = cartUsualString(cart, "hgDebug", "off");
if(sameString(debugTmp, "on"))
    hgDebug = TRUE;
else
    hgDebug = FALSE;
conn  = hAllocConn(database);
hgsid     = cartOptionalString(cart, "hgsid");
if (hgsid != NULL)
    {
    safef(hgsidStr, sizeof(hgsidStr), "&hgsid=%s", hgsid);
    }
else
    {
    strcpy(hgsidStr, "");
    }

/* check proteinID to see if it is a valid SWISS-PROT/TrEMBL accession or display ID */
/* then assign the accession number to global variable proteinID */
sqlSafefFrag(cond_str, sizeof(cond_str), "accession='%s'", proteinID);
proteinAC = sqlGetField(protDbName, "spXref3", "accession", cond_str);
if (proteinAC == NULL)
    {
    sqlSafefFrag(cond_str, sizeof(cond_str), "displayID='%s'", proteinID);
    proteinAC = sqlGetField(protDbName, "spXref3", "accession", cond_str);
    if (proteinAC == NULL)
	{
	hUserAbort("'%s' does not seem to be a valid Swiss-Prot/TrEMBL protein ID or gene symbol.<br><br>Click <A HREF=\"../cgi-bin/pbGateway\">here</A> to start another query."
	, proteinID);
	}
    else
	{
	protDisplayID = proteinID;
	proteinID = proteinAC;
	}
    }
else
    {
    sqlSafefFrag(cond_str, sizeof(cond_str), "accession='%s'", proteinID);
    protDisplayID = sqlGetField(protDbName, "spXref3", "displayID", cond_str);
    }

if (proteinInSupportedGenome)
    {
    if (kgVersion == KG_III)
        {
        sqlSafefFrag(cond_str, sizeof(cond_str), "spId='%s'", proteinID);
        mrnaID = sqlGetField(database, "kgXref", "kgId", cond_str);
	}
    else
        {
        sqlSafefFrag(cond_str, sizeof(cond_str), "proteinID='%s'", protDisplayID);
        mrnaID = sqlGetField(database, "knownGene", "name", cond_str);
        }
    }
else
    {
    mrnaID = NULL;
    positionStr = NULL;
    }

sqlSafefFrag(cond_str, sizeof(cond_str), "accession='%s'", proteinID);
description = sqlGetField(protDbName, "spXref3", "description", cond_str);

if (positionStr != NULL)
    {
    chp = strstr(positionStr, ":");
    *chp = '\0';
    prevGBChrom = cloneString(positionStr);

    chp1 = chp + 1;
    chp9 = strstr(chp1, "-");
    *chp9 = '\0';
    prevGBStartPos = atoi(chp1);
    chp1 = chp9 + 1;
    prevGBEndPos   = atoi(chp1);
    }
else
    {
    prevGBChrom    = NULL;
    prevGBStartPos = -1;
    prevGBEndPos   = -1;
    }

/* Do main display. */
if (cgiVarExists("pbt.psOutput"))
    handlePostscript();
else
    {
    doTrackForm(NULL, NULL);
    }
}