Skip to content

Instantly share code, notes, and snippets.

@mtholder
Last active August 29, 2015 14:13
Show Gist options
  • Select an option

  • Save mtholder/035eed5d9ed3e4ff6816 to your computer and use it in GitHub Desktop.

Select an option

Save mtholder/035eed5d9ed3e4ff6816 to your computer and use it in GitHub Desktop.
a GBParsy-based program that takes a GenBank flat file and writes to standard out one line per record containing: Accession.Version TAB gi TAB Organism
/* Most of this code is from GBParsy which available from https://code.google.com/p/gbfp/
T.-H. Lee, Y.-K. Kim and B.H. Nahm (2008) GBParsy: A GenBank flatfile parser library with high speed. BMC Bioinformatics, 9:321.
That code is released under the GPL (see bottom of file).
Mark T. Holder only wrote the slight modification to parsing of the GI and a simpliefied main
function (based on the example seqext.c from gbfpy)
*/
#define LINELEN 65536
#define MEGA 1048576
#define INITGBFSEQNUM 4
#define INITREFERENCENUM 16
#define INITFEATURENUM 64
#define INITQUALIFIERNUM 128
#define FIELDLEN 16
#define FEATURELEN 16
#define QUALIFIERLEN 16
#define LOCUSLEN 16
#define TYPELEN 9
#define TOPOLOGYSTRLEN 8
#define DIVISIONCODELEN 3
#define DATESTRLEN 11
#define QUALIFIERSTART 21
#define INELSE 0
#define INFEATURE 1
#define INQUALIFIER 2
#define NORMAL 'N'
#define REVCOM 'C'
#define LINEAR 'L'
#define CIRCULAR 'C'
#define CHARACTER 'C'
#define LONG 'L'
#define STRING 'S'
typedef char *gb_string;
typedef struct tReference {
gb_string sAuthors;
gb_string sConsrtm;
gb_string sTitle;
gb_string sJournal;
gb_string sMedline;
gb_string sPubMed;
gb_string sRemark;
unsigned int iNum;
} gb_reference;
typedef struct tLocation {
unsigned long lStart;
unsigned long lEnd;
} gb_location;
typedef struct tQualifier {
gb_string sQualifier;
gb_string sValue;
} gb_qualifier;
typedef struct tFeature {
gb_location *ptLocation;
gb_qualifier *ptQualifier;
unsigned long lStart;
unsigned long lEnd;
unsigned int iNum;
unsigned int iLocationNum;
unsigned int iQualifierNum;
char sFeature[FEATURELEN + 1];
char cDirection;
} gb_feature;
typedef struct tGBFFData {
gb_string sAccession;
gb_string sComment;
gb_string sDef;
gb_string sGI;
gb_string sKeywords;
gb_string sLineage;
gb_string sOrganism;
gb_string sSequence;
gb_string sSource;
gb_string sVersion;
gb_reference *ptReferences;
gb_feature *ptFeatures;
unsigned int iFeatureNum;
unsigned int iReferenceNum;
unsigned long lLength;
unsigned long lRegion[2];
char sLocusName[LOCUSLEN + 1];
char sType[TYPELEN + 1];
char sTopology[TOPOLOGYSTRLEN + 1];
char sDivisionCode[DIVISIONCODELEN + 1];
char sDate[DATESTRLEN + 1];
} gb_data;
gb_data **parseGBFF(gb_string spFileName);
void freeGBData(gb_data **pptGBFFData);
gb_string getSequence(gb_string sSequence, gb_feature *ptFeature);
#define __EXTENSIONS__
#include <stdio.h>
#include <stdlib.h>
#include <regex.h>
#include <unistd.h>
#include <string.h>
#include <ctype.h>
#include <limits.h>
#include <sys/types.h>
const char sVer[] = "0.6.1";
const char sNorBase[] = "ACGTRYMKWSBDHVNacgtrymkwsbdhvn";
const char sComBase[] = "TGCAYRKMWSVHDBNtgcayrkmwsvhdbn";
const unsigned int iBaseLen = 30;
char sTempLine[LINELEN] = {'\0',};
regex_t ptRegExLocus;
regex_t ptRegExOneLine;
regex_t ptRegExAccession;
regex_t ptRegExVersion;
regex_t ptRegExRegion;
regex_t ptRegExGI;
#define skipSpace( x ) for (; isspace(*x); x++)
#define putLine( x ) strcpy(sTempLine, x)
#define getLine_w_rtrim( x, y ) \
getLine(x, y); \
rtrim(x)
/* Initializes regular expression */
void initRegEx(void) {
const char sLocus[] = "^LOCUS +([a-z|A-Z|0-9|_]+) +([0-9]+) bp +([a-z|A-Z|-| ]+) ([a-z| ]{8}) ([A-Z| ]{3}) ([0-9]+-[A-Z]+-[0-9]+)";
const char sOneLine[] = "^ *([A-Z]+) +(.+)";
const char sAccession[] = "^ACCESSION +([a-z|A-Z|0-9|_]+) ?";
const char sRegion[] = " +REGION: ?([0-9]+)\\.\\.([0-9]+)";
const char sVersion[] = "^VERSION +([a-z|A-Z|0-9|_.]+) ?";
const char sGI[] = " +GI: ?([0-9]+)";
regcomp(&ptRegExLocus, sLocus, REG_EXTENDED | REG_ICASE);
regcomp(&ptRegExOneLine, sOneLine, REG_EXTENDED | REG_ICASE);
regcomp(&ptRegExAccession, sAccession, REG_EXTENDED | REG_ICASE);
regcomp(&ptRegExVersion, sVersion, REG_EXTENDED | REG_ICASE);
regcomp(&ptRegExRegion, sRegion, REG_EXTENDED | REG_ICASE);
regcomp(&ptRegExGI, sGI, REG_EXTENDED | REG_ICASE);
}
void freeRegEx(void) {
regfree(&ptRegExLocus);
regfree(&ptRegExOneLine);
regfree(&ptRegExAccession);
regfree(&ptRegExVersion);
regfree(&ptRegExRegion);
regfree(&ptRegExGI);
}
/* Removes white spaces at end of a string */
static void rtrim(gb_string sLine) {
register int i;
for (i = (strlen(sLine) - 1); i >= 0; i--) if (! isspace(*(sLine + i))) break;
*(sLine + i + 1) = '\0';
}
/* Removes a specific character at end of a string */
static void removeRChar(gb_string sLine, char cRemove) {
register int i;
for (i = (strlen(sLine) - 1); i >= 0; i--) {
if (sLine[i] == cRemove) {
sLine[i] = '\0';
break;
}
}
}
/* Gets a line from either the line buffer or the file */
static gb_string getLine(gb_string sLine, FILE *FSeqFile) {
gb_string sReturn;
if (*sTempLine != '\0') {
sReturn = strcpy(sLine, sTempLine);
*sTempLine = '\0';
} else {
sReturn = fgets(sLine, LINELEN, FSeqFile);
}
return sReturn;
}
/* Concatenates lines which start with specific white spaces */
static gb_string joinLines(FILE *FSeqFile, unsigned int iSpaceLen) {
char sLine[LINELEN];
gb_string sTemp, sJoinedLine;
sJoinedLine = malloc(sizeof(char) * LINELEN);
getLine_w_rtrim(sLine, FSeqFile);
strcpy(sJoinedLine, sLine + iSpaceLen);
while (fgets(sLine, LINELEN, FSeqFile)) {
sTemp = sLine;
skipSpace(sTemp);
if ((sTemp - sLine) < iSpaceLen) break;
rtrim(sTemp);
sJoinedLine = strcat(sJoinedLine, sTemp - 1); /* '- 1' in order to insert a space character at the juncation */
}
putLine(sLine);
return realloc(sJoinedLine, sizeof(char) * (strlen(sJoinedLine) + 1));
}
static int parseLocus(gb_string sLocusStr, gb_data *ptGBData) {
/*
01-05 'LOCUS'
06-12 spaces
13-28 Locus name
29-29 space
30-40 Length of sequence, right-justified
41-41 space
42-43 bp
44-44 space
45-47 spaces, ss- (single-stranded), ds- (double-stranded), or
ms- (mixed-stranded)
48-53 NA, DNA, RNA, tRNA (transfer RNA), rRNA (ribosomal RNA),
mRNA (messenger RNA), uRNA (small nuclear RNA), snRNA,
snoRNA. Left justified.
54-55 space
56-63 'linear' followed by two spaces, or 'circular'
64-64 space
65-67 The division code (see Section 3.3)
68-68 space
69-79 Date, in the form dd-MMM-yyyy (e.g., 15-MAR-1991)
*/
char sTemp[LINELEN];
unsigned int i, iErr, iLen;
regmatch_t ptRegMatch[7];
struct tData {
char cType;
void *Pointer;
} tDatas[] = {
{STRING, NULL},
{LONG, NULL},
{STRING, NULL},
{STRING, NULL},
{STRING, NULL},
{STRING, NULL}};
tDatas[0].Pointer = ptGBData->sLocusName;
tDatas[1].Pointer = &(ptGBData->lLength);
tDatas[2].Pointer = ptGBData->sType;
tDatas[3].Pointer = ptGBData->sTopology;
tDatas[4].Pointer = ptGBData->sDivisionCode;
tDatas[5].Pointer = ptGBData->sDate;
rtrim(sLocusStr);
if ((iErr = regexec(&ptRegExLocus, sLocusStr, 7, ptRegMatch, 0)) == 0) {
for (i = 0; i < 6; i++) {
iLen = ptRegMatch[i + 1].rm_eo - ptRegMatch[i + 1].rm_so;
switch (tDatas[i].cType) {
case STRING:
memcpy(tDatas[i].Pointer, (sLocusStr + ptRegMatch[i + 1].rm_so), iLen);
*((gb_string) tDatas[i].Pointer + iLen) = '\0';
rtrim((gb_string) tDatas[i].Pointer);
break;
case LONG:
memcpy(sTemp, (sLocusStr + ptRegMatch[i + 1].rm_so), iLen);
sTemp[iLen] = '\0';
*((unsigned long *) tDatas[i].Pointer) = atol(sTemp);
break;
default:
perror("Unknown Data Type!");
}
}
} else {
/* regerror(iErr, &ptRegExLocus, sTemp, LINELEN); */
/* perror("Invalid LOCUS line!"); */
fprintf(stderr, "Invalid LOCUS line! - '%s\n'", sLocusStr);
return 1;
}
return 0;
}
static void parseDef(FILE *FSeqFile, gb_data *ptGBData) {
char sLine[LINELEN];
regmatch_t ptRegMatch[3];
getLine_w_rtrim(sLine, FSeqFile);
regexec(&ptRegExOneLine, sLine, 3, ptRegMatch, 0);
ptGBData->sDef = strdup(sLine + ptRegMatch[2].rm_so);
}
static void parseKeywords(FILE *FSeqFile, gb_data *ptGBData) {
char sLine[LINELEN];
regmatch_t ptRegMatch[3];
getLine_w_rtrim(sLine, FSeqFile);
regexec(&ptRegExOneLine, sLine, 3, ptRegMatch, 0);
ptGBData->sKeywords = strdup(sLine + ptRegMatch[2].rm_so);
}
static void parseAccession(FILE *FSeqFile, gb_data *ptGBData) {
char sLine[LINELEN];
regmatch_t ptRegMatch[3];
getLine_w_rtrim(sLine, FSeqFile);
if (regexec(&ptRegExAccession, sLine, 2, ptRegMatch, 0) == 0) {
*(sLine + ptRegMatch[1].rm_eo) = '\0';
ptGBData->sAccession = strdup(sLine + ptRegMatch[1].rm_so);
}
if (regexec(&ptRegExRegion, sLine + ptRegMatch[1].rm_eo + 1, 3, ptRegMatch, 0) == 0) {
*(sLine + ptRegMatch[1].rm_eo) = '\0';
(ptGBData->lRegion)[0] = atol(sLine + ptRegMatch[1].rm_so);
*(sLine + ptRegMatch[2].rm_eo) = '\0';
(ptGBData->lRegion)[1] = atol(sLine + ptRegMatch[2].rm_so);
}
}
static void parseVersion(FILE *FSeqFile, gb_data *ptGBData) {
char sLine[LINELEN];
int offset;
char prev;
regmatch_t ptRegMatch[2];
regmatch_t ntRegMatch[2];
getLine_w_rtrim(sLine, FSeqFile);
if (regexec(&ptRegExVersion, sLine, 2, ptRegMatch, 0) == 0) {
offset = ptRegMatch[1].rm_eo;
prev = sLine[offset];
*(sLine + offset) = '\0';
ptGBData->sVersion = strdup(sLine + ptRegMatch[1].rm_so);
sLine[offset] = prev;
if (regexec(&ptRegExGI, sLine + offset, 2, ntRegMatch, 0) == 0) {
*(sLine + offset + ntRegMatch[1].rm_eo) = '\0';
ptGBData->sGI = strdup(sLine + offset + ntRegMatch[1].rm_so);
}
}
}
static void parseComment(FILE *FSeqFile, gb_data *ptGBData) {
ptGBData->sComment = joinLines(FSeqFile, 12);
}
static void parseSource(FILE *FSeqFile, gb_data *ptGBData) {
char sLine[LINELEN];
regmatch_t ptRegMatch[3];
getLine_w_rtrim(sLine, FSeqFile);
regexec(&ptRegExOneLine, sLine, 3, ptRegMatch, 0);
ptGBData->sSource = strdup(sLine + ptRegMatch[2].rm_so);
getLine_w_rtrim(sLine, FSeqFile);
regexec(&ptRegExOneLine, sLine, 3, ptRegMatch, 0);
ptGBData->sOrganism = strdup(sLine + ptRegMatch[2].rm_so);
ptGBData->sLineage = joinLines(FSeqFile, 12);
}
#define processRef( x, y ) \
y = NULL; \
getLine_w_rtrim(sLine, FSeqFile); \
putLine(sLine); \
if (strstr(sLine, x) != NULL) y = joinLines(FSeqFile, 12)
static void parseReference(FILE *FSeqFile, gb_data *ptGBData) {
char sLine[LINELEN];
regmatch_t ptRegMatch[3];
gb_reference *ptReferences = NULL;
gb_reference *ptReference = NULL;
unsigned int iReferenceNum = 0;
ptReferences = ptGBData->ptReferences;
iReferenceNum = ptGBData->iReferenceNum;
ptReferences = realloc(ptReferences, sizeof(gb_reference) * (iReferenceNum + 1));
ptReference = ptReferences + iReferenceNum;
getLine_w_rtrim(sLine, FSeqFile);
regexec(&ptRegExOneLine, sLine, 3, ptRegMatch, 0);
ptReference->iNum = atoi(sLine + ptRegMatch[2].rm_so);
processRef(" AUTHORS ", ptReference->sAuthors);
processRef(" CONSRTM ", ptReference->sConsrtm);
processRef(" TITLE ", ptReference->sTitle);
processRef(" JOURNAL ", ptReference->sJournal);
processRef(" MEDLINE ", ptReference->sMedline);
processRef(" PUBMED ", ptReference->sPubMed);
processRef(" REMARK ", ptReference->sRemark);
ptGBData->ptReferences = ptReferences;
ptGBData->iReferenceNum = iReferenceNum + 1;
}
static gb_string checkComplement(gb_string sLocation) {
gb_string sPosition;
skipSpace(sLocation);
for (sPosition = sLocation; *sPosition; sPosition++) {
/* Check the 1st and the 2nd characters of 'complement' */
if (*sPosition == 'c' && *(sPosition + 1) == 'o') {
removeRChar(sLocation, ')');
return sPosition + 11;
}
}
return sLocation;
}
static gb_string checkJoin(gb_string sLocation) {
gb_string sPosition;
skipSpace(sLocation);
for (sPosition = sLocation; *sPosition; sPosition++) {
/* Check the 1st and the 2nd characters of 'complement' */
if (*sPosition == 'j' && *(sPosition + 1) == 'o') {
removeRChar(sLocation, ')');
return sPosition + 5;
}
}
return sLocation;
}
static int convertPos2Num(gb_string sPositions, unsigned long *lStart, unsigned long *lEnd) {
register int i;
int aiPositions[4] = {-2,};
int iNum = 0;
for (i = strlen(sPositions); i >= 0; i--) {
if (isdigit(*(sPositions + i))) aiPositions[(aiPositions[iNum] - 1 == i) ? iNum : ++iNum] = i;
else *(sPositions + i) = '\0';
}
if (iNum == 2) {
*lStart = atol(sPositions + aiPositions[2]);
*lEnd = atol(sPositions + aiPositions[1]);
return 1;
} else if (iNum == 1) {
*lStart = *lEnd = atol(sPositions + aiPositions[1]);
return 1;
} else {
fprintf(stderr, "Warning: cannot parse '%s'\n", sPositions);
return 0;
}
}
/* Parsing a gb_string that contains gb_location information */
static void parseLocation(gb_string sLocation, gb_feature *pFeature) {
gb_string sTemp;
gb_string sString = NULL;
unsigned int iLocationNum = 1;
/* Evalue sequence direction
sString has gb_location and join informations
*/
sString = checkComplement(sLocation);
if (sLocation == sString) pFeature->cDirection = NORMAL;
else pFeature->cDirection = REVCOM;
/* Remove 'join' gb_string
sString has gb_location informations
*/
sString = checkJoin(sString);
sTemp = sString - 1;
while((sTemp = strchr((sTemp + 1), ','))) iLocationNum++;
pFeature->ptLocation = malloc(iLocationNum * sizeof(*(pFeature->ptLocation)));
iLocationNum = 0;
sLocation = strtok_r(sString, ",", &sTemp);
if (convertPos2Num(sLocation,
&(((pFeature->ptLocation)+iLocationNum)->lStart),
&(((pFeature->ptLocation)+iLocationNum)->lEnd)) == 1) iLocationNum++;
while((sLocation = strtok_r(NULL, ",", &sTemp))) {
if (convertPos2Num(sLocation,
&(((pFeature->ptLocation)+iLocationNum)->lStart),
&(((pFeature->ptLocation)+iLocationNum)->lEnd)) == 1) iLocationNum++;
}
pFeature->lStart = (pFeature->ptLocation)->lStart;
pFeature->lEnd = ((pFeature->ptLocation)+(iLocationNum - 1))->lEnd;
pFeature->iLocationNum = iLocationNum;
}
static gb_string _parseQualifier(gb_string sQualifier, gb_string *psValue) {
gb_string sPosition;
skipSpace(sQualifier);
if ((sPosition = strchr(sQualifier, '=')) == NULL) {
*psValue = sQualifier + strlen(sQualifier);
return sQualifier;
}
*sPosition++ = '\0';
skipSpace(sQualifier);
if (*sPosition == '"') removeRChar(++sPosition, '"');
*psValue = sPosition;
return sQualifier;
}
static void parseQualifier(gb_string sQualifier, gb_feature *pFeature) {
gb_string sValue;
gb_string sTemp = NULL;
gb_string sString = NULL;
gb_qualifier *ptQualifier;
ptQualifier = malloc(INITQUALIFIERNUM * sizeof(gb_qualifier));
pFeature->ptQualifier = ptQualifier;
/* Parse the 1st gb_qualifier gb_string */
sString = strtok_r(sQualifier, "\n", &sTemp);
ptQualifier->sQualifier = _parseQualifier(sString, &sValue);
ptQualifier->sValue = sValue;
ptQualifier++;
/* Parse the rest gb_qualifier gb_string */
while((sString = strtok_r(NULL, "\n", &sTemp)) != NULL) {
ptQualifier->sQualifier = _parseQualifier(sString, &sValue);
ptQualifier->sValue = sValue;
ptQualifier++;
}
/* Determine the number of actual qualifier data */
pFeature->iQualifierNum = ptQualifier - pFeature->ptQualifier;
pFeature->ptQualifier = realloc(pFeature->ptQualifier, pFeature->iQualifierNum * sizeof(gb_qualifier));
/*
ptQualifier = malloc(pFeature->iQualifierNum * sizeof(gb_qualifier));
memcpy(ptQualifier, pFeature->ptQualifier, pFeature->iQualifierNum * sizeof(gb_qualifier));
free(pFeature->ptQualifier);
pFeature->ptQualifier = ptQualifier;
*/
}
static void parseFeature(FILE *FSeqFile, gb_data *ptGBData) {
char sLine[LINELEN] = {'\0',};
char sLocation[LINELEN] = {'\0',};
gb_string sQualifier = NULL;
gb_string sQualifierTemp = NULL;
unsigned int iReadPos = INELSE;
unsigned int iFeatureNum = 0;
unsigned int iFeatureMem = INITFEATURENUM;
unsigned int i = 0;
gb_feature *pFeatures = NULL;
gb_feature *pFeature = NULL;
pFeatures = (gb_feature *) malloc(iFeatureMem * sizeof(gb_feature));
/* Parse FEATURES */
while(fgets(sLine, LINELEN, FSeqFile)) {
if (! isspace(*sLine)) {
putLine(sLine);
break;
}
rtrim(sLine);
if (memcmp(sLine + 5, " ", 15) != 0) {
if (iFeatureNum == iFeatureMem) {
iFeatureMem += INITFEATURENUM;
pFeatures = realloc(pFeatures, sizeof(gb_feature) * iFeatureMem);
}
if (strlen(sLocation) != 0) parseLocation(sLocation, (pFeatures + iFeatureNum - 1));
if (sQualifier < sQualifierTemp) {
*sQualifierTemp++ = '\n';
*sQualifierTemp = '\0';
sQualifierTemp = malloc((sQualifierTemp - sQualifier + 1) * sizeof(*sQualifier));
strcpy(sQualifierTemp, sQualifier);
free(sQualifier);
sQualifier = sQualifierTemp;
parseQualifier(sQualifier, (pFeatures + iFeatureNum - 1));
} else {
free(sQualifier);
sQualifier = NULL;
}
*sLocation = '\0';
sQualifier = malloc(sizeof(*sQualifier) * MEGA);
sQualifierTemp = sQualifier;
iReadPos = INFEATURE;
memcpy((pFeatures + iFeatureNum)->sFeature, (sLine + 5), 15);
*(((pFeatures + iFeatureNum)->sFeature) + 15) = '\0';
rtrim((pFeatures + iFeatureNum)->sFeature);
strcpy(sLocation, (sLine + 21));
/* Feature Initalize */
pFeature = pFeatures + iFeatureNum;
pFeature->iNum = iFeatureNum;
pFeature->cDirection = NORMAL;
pFeature->iLocationNum = 0;
pFeature->lStart = 0;
pFeature->lEnd = 0;
pFeature->iQualifierNum = 0;
pFeature->ptLocation = NULL;
pFeature->ptQualifier = NULL;
iFeatureNum++;
} else if (*(sLine + QUALIFIERSTART) == '/') {
iReadPos = INQUALIFIER;
if (sQualifier < sQualifierTemp) *sQualifierTemp++ = '\n';
i = strlen(sLine) - (QUALIFIERSTART + 1);
memcpy(sQualifierTemp, sLine + (QUALIFIERSTART + 1), i);
sQualifierTemp += i;
} else {
if (iReadPos == INFEATURE) {
strcpy((sLocation + strlen(sLocation)), (sLine + QUALIFIERSTART));
} else if (iReadPos == INQUALIFIER) {
i = strlen(sLine) - QUALIFIERSTART;
memcpy(sQualifierTemp, sLine + QUALIFIERSTART, i);
sQualifierTemp += i;
}
}
}
/* Finishing of the parsing */
if (iFeatureNum == iFeatureMem) {
iFeatureMem += INITFEATURENUM;
pFeatures = realloc(pFeatures, sizeof(gb_feature) * iFeatureMem);
}
if (strlen(sLocation) != 0) parseLocation(sLocation, (pFeatures + iFeatureNum - 1));
if (sQualifier < sQualifierTemp) {
*sQualifierTemp++ = '\n';
*sQualifierTemp = '\0';
sQualifierTemp = malloc((sQualifierTemp - sQualifier + 1) * sizeof(*sQualifier));
strcpy(sQualifierTemp, sQualifier);
free(sQualifier);
sQualifier = sQualifierTemp;
parseQualifier(sQualifier, (pFeatures + iFeatureNum - 1));
} else {
free(sQualifier);
sQualifier = NULL;
}
ptGBData->iFeatureNum = iFeatureNum;
ptGBData->ptFeatures = pFeatures;
}
/* Parse sequences */
static void parseSequence(FILE *FSeqFile, gb_data *ptGBData) {
register char c;
char sLine[LINELEN] = {'\0',};
gb_string sSequence, sSequence2;
ptGBData->sSequence = malloc((ptGBData->lLength + 1) * sizeof(char));
sSequence2 = ptGBData->sSequence;
while(fgets(sLine, LINELEN, FSeqFile)) {
if (*sLine == '/' && *(sLine + 1) == '/') {
putLine(sLine);
break;
}
sSequence = sLine + 9; /* '+ 9' in order to skip a numbers */
while((c = *(sSequence++)) != '\0') if (isalpha(c)) *(sSequence2++) = c;
}
*(sSequence2) = '\0';
}
static void initGBData(gb_data *ptGBData) {
ptGBData->sAccession = NULL;
ptGBData->sComment = NULL;
ptGBData->sDef = NULL;
ptGBData->sGI = NULL;
ptGBData->sKeywords = NULL;
ptGBData->sLineage = NULL;
ptGBData->sOrganism = NULL;
ptGBData->sSequence = NULL;
ptGBData->sSource = NULL;
ptGBData->sVersion = NULL;
ptGBData->ptReferences = NULL;
ptGBData->ptFeatures = NULL;
ptGBData->iFeatureNum = 0;
ptGBData->iReferenceNum = 0;
ptGBData->lLength = 0;
ptGBData->lRegion[0] = 0;
ptGBData->lRegion[1] = 0;
ptGBData->sLocusName[0] = '\0';
ptGBData->sType[0] = '\0';
ptGBData->sTopology[0] = '\0';
ptGBData->sDivisionCode[0] = '\0';
ptGBData->sDate[0] = '\0';
}
static gb_data *_parseGBFF(FILE *FSeqFile) {
int i;
char sLine[LINELEN] = {'\0',};
gb_data *ptGBData = NULL;
struct tField {
char sField[FIELDLEN + 1];
void (*vFunction)(FILE *FSeqFile, gb_data *ptGBData);
} atFields[] = {
{"DEFINITION", parseDef},
{"ACCESSION", parseAccession},
{"VERSION", parseVersion},
{"KEYWORDS", parseKeywords},
{"SOURCE", parseSource},
{"REFERENCE", parseReference},
{"COMMENT", parseComment},
{"FEATURE", parseFeature},
{"ORIGIN", parseSequence},
{"", NULL} /* To terminate seeking */
};
/* Confirming GBFF File with LOCUS line */
while(fgets(sLine, LINELEN, FSeqFile)) {
if (strstr(sLine, "LOCUS") == sLine) {
ptGBData = malloc(sizeof(gb_data));
initGBData(ptGBData);
break;
}
}
/* If there is a no LOCUS line, next statement return NULL value to end parsing */
if (ptGBData == NULL) return NULL;
/* Parse LOCUS line */
if (parseLocus(sLine, ptGBData) != 0) {
free(ptGBData);
return NULL;
}
while(getLine(sLine, FSeqFile)) {
if (*sLine == '/' && *(sLine + 1) == '/') break;
for(i = 0; *((atFields + i)->sField); i++) {
if (strstr(sLine, (atFields + i)->sField) == sLine) {
putLine(sLine);
((atFields + i)->vFunction)(FSeqFile, ptGBData);
break;
}
}
}
return ptGBData;
}
/* parse sequence datas in a GBF file */
gb_data **parseGBFF(gb_string spFileName) {
int iGBFSeqPos = 0;
unsigned int iGBFSeqNum = INITGBFSEQNUM;
gb_data **pptGBDatas;
FILE *FSeqFile;
if (spFileName == NULL) {
FSeqFile = stdin;
} else {
if (access(spFileName, F_OK) != 0) {
/* perror(spFileName); */
return NULL;
} else {
FSeqFile = fopen(spFileName, "r");
}
}
initRegEx(); /* Initalize for regular expression */
pptGBDatas = malloc(iGBFSeqNum * sizeof(gb_data *));
do {
if (iGBFSeqNum == iGBFSeqPos) {
iGBFSeqNum += INITGBFSEQNUM;
pptGBDatas = realloc(pptGBDatas, iGBFSeqNum * sizeof(gb_data *));
}
*(pptGBDatas + iGBFSeqPos) = _parseGBFF(FSeqFile);
} while (*(pptGBDatas + iGBFSeqPos++) != NULL);
if (spFileName) fclose(FSeqFile);
freeRegEx();
return pptGBDatas;
}
void freeGBData(gb_data **pptGBData) {
int i;
gb_data *ptGBData = NULL;
gb_feature *ptFeatures = NULL;
gb_reference *ptReferences = NULL;
unsigned int iFeatureNum = 0;
unsigned int iReferenceNum = 0;
unsigned int iSeqPos = 0;
for (iSeqPos = 0; *(pptGBData + iSeqPos) != NULL; iSeqPos++) {
ptGBData = *(pptGBData + iSeqPos);
ptFeatures = ptGBData->ptFeatures;
iFeatureNum = ptGBData->iFeatureNum;
/* Release memory space for features */
for (i = 0; i < iFeatureNum; i++) {
free((ptFeatures + i)->ptLocation);
if ((ptFeatures + i)->ptQualifier != NULL) {
free(((ptFeatures + i)->ptQualifier)->sQualifier);
free((ptFeatures + i)->ptQualifier);
}
}
free(ptFeatures);
/* Release memory space for References */
ptReferences = ptGBData->ptReferences;
iReferenceNum = ptGBData->iReferenceNum;
for (i = 0; i < iReferenceNum; i++) {
free((ptReferences + i)->sAuthors);
free((ptReferences + i)->sConsrtm);
free((ptReferences + i)->sTitle);
free((ptReferences + i)->sJournal);
free((ptReferences + i)->sMedline);
free((ptReferences + i)->sPubMed);
free((ptReferences + i)->sRemark);
}
free(ptReferences);
free(ptGBData->sDef);
free(ptGBData->sAccession);
free(ptGBData->sComment);
free(ptGBData->sGI);
free(ptGBData->sKeywords);
free(ptGBData->sLineage);
free(ptGBData->sOrganism);
free(ptGBData->sSequence);
free(ptGBData->sSource);
free(ptGBData->sVersion);
free(ptGBData);
}
free(pptGBData);
}
static void getRevCom(gb_string sSequence) {
char c;
unsigned int k;
unsigned long i, j;
for (i = 0, j = strlen(sSequence) - 1; i < j; i++, j--) {
c = *(sSequence + i);
*(sSequence + i) = 'X';
for (k = 0; k < iBaseLen; k++)
if (*(sNorBase + k) == *(sSequence + j)) {
*(sSequence + i) = *(sComBase + k);
break;
}
*(sSequence + j) = 'X';
for (k = 0; k < iBaseLen; k++)
if (*(sNorBase + k) == c) {
*(sSequence + j) = *(sComBase + k);
break;
}
}
}
gb_string getSequence(gb_string sSequence, gb_feature *ptFeature) {
unsigned long lSeqLen = 1; /* For the '\0' characher */
unsigned long lStart, lEnd;
unsigned int i;
gb_string sSequenceTemp;
for (i = 0; i < ptFeature->iLocationNum; i++)
lSeqLen += (((ptFeature->ptLocation) + i)->lEnd - ((ptFeature->ptLocation) + i)->lStart + 1);
sSequenceTemp = malloc(lSeqLen * sizeof(char));
lSeqLen = 0;
for (i = 0; i < ptFeature->iLocationNum; i++) {
lStart = ((ptFeature->ptLocation) + i)->lStart;
lEnd = ((ptFeature->ptLocation) + i)->lEnd;
strncpy(sSequenceTemp + lSeqLen, sSequence + lStart - 1, lEnd - lStart + 1);
lSeqLen += (lEnd - lStart + 1);
}
*(sSequenceTemp + lSeqLen) = '\0';
if (ptFeature->cDirection == REVCOM) getRevCom(sSequenceTemp);
return sSequenceTemp;
}
#define __EXTENSIONS__
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <regex.h>
#include <unistd.h>
#include <string.h>
static void help(void) {
printf("Extract:\nAccession <tab> GI <tab> ORGANISM\nfrom a GenBank flatfile.\n");
}
int startswith(const char * prefix, const char *test) {
unsigned n = strlen(prefix);
unsigned nn = strlen(test);
if (nn < n) {
return 0;
}
return (strncmp(prefix, test, n) == 0 ? 1 : 0);
}
static unsigned scanSourceForTaxonomyID(gb_feature *pf) {
gb_qualifier *i;
const unsigned offset = 6; /* length of "taxon:" */
unsigned int nMatches = 0;
for (i = pf->ptQualifier; (i - pf->ptQualifier) < pf->iQualifierNum; i++) {
if (strcmp(i->sQualifier, "db_xref") == 0
&& startswith("taxon:", i->sValue)) {
printf("\t%s", i->sValue + offset);
++nMatches;
}
}
return nMatches;
}
int main(int argc, char *argv[]) {
int i, j;
char *sFileName = NULL;
gb_data **pptSeqData, *ptSeqData;
gb_feature * ptFeature;
unsigned int nMatches = 0;
if (argc != 2) {
help();
return 1;
}
sFileName = argv[1];
pptSeqData = parseGBFF(sFileName); /* parse a GBF file which contains more than one GBF sequence data */
for (i = 0; (ptSeqData = *(pptSeqData + i)) != NULL; i++) { /* ptSeqData points a parsed data of a GBF sequence data */
printf("%s\t%s\t%s",
ptSeqData->sVersion,
ptSeqData->sGI,
ptSeqData->sOrganism);
nMatches = 0;
for (j = 0; j < ptSeqData->iFeatureNum; j++) {
ptFeature = (ptSeqData->ptFeatures + j);
if (strcmp(ptFeature->sFeature, "source") == 0) {
nMatches += scanSourceForTaxonomyID(ptFeature);
} else {
/*printf("skipping %s", ptF */
}
}
printf("\n");
if (nMatches != 1) {
fprintf(stderr, "%s had %u matches!\n", ptSeqData->sVersion, nMatches);
}
}
freeGBData(pptSeqData); /* release memory space */
return 0;
}
/*
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.
675 Mass Ave, Cambridge, MA 02139, USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Library General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
Appendix: How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) 19yy <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) 19yy name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Library General
Public License instead of this License.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment