1 #include "sam_header.h"
9 KHASH_MAP_INIT_STR(str, const char *)
13 struct _HeaderList *last; // Hack: Used and maintained only by list_append_to_end. Maintained in the root node only.
14 struct _HeaderList *next;
17 typedef struct _HeaderList list_t;
18 typedef list_t HeaderDict;
34 const char *o_hd_tags[] = {"SO","GO",NULL};
35 const char *r_hd_tags[] = {"VN",NULL};
37 const char *o_sq_tags[] = {"AS","M5","UR","SP",NULL};
38 const char *r_sq_tags[] = {"SN","LN",NULL};
39 const char *u_sq_tags[] = {"SN",NULL};
41 const char *o_rg_tags[] = {"LB","DS","PU","PI","CN","DT","PL",NULL};
42 const char *r_rg_tags[] = {"ID",NULL};
43 const char *u_rg_tags[] = {"ID",NULL};
45 const char *o_pg_tags[] = {"VN","CL",NULL};
46 const char *r_pg_tags[] = {"ID",NULL};
48 const char *types[] = {"HD","SQ","RG","PG","CO",NULL};
49 const char **optional_tags[] = {o_hd_tags,o_sq_tags,o_rg_tags,o_pg_tags,NULL,NULL};
50 const char **required_tags[] = {r_hd_tags,r_sq_tags,r_rg_tags,r_pg_tags,NULL,NULL};
51 const char **unique_tags[] = {NULL, u_sq_tags,u_rg_tags,NULL,NULL,NULL};
54 static void debug(const char *format, ...)
58 vfprintf(stderr, format, ap);
63 // Replaced by list_append_to_end
64 static list_t *list_prepend(list_t *root, void *data)
66 list_t *l = malloc(sizeof(list_t));
73 // Relies on the root->last being correct. Do not use with the other list_*
74 // routines unless they are fixed to modify root->last as well.
75 static list_t *list_append_to_end(list_t *root, void *data)
77 list_t *l = malloc(sizeof(list_t));
90 static list_t *list_append(list_t *root, void *data)
97 l->next = malloc(sizeof(list_t));
102 l = malloc(sizeof(list_t));
110 static void list_free(list_t *root)
123 // Look for a tag "XY" in a predefined const char *[] array.
124 static int tag_exists(const char *tag, const char **tags)
127 if ( !tags ) return -1;
130 if ( tags[itag][0]==tag[0] && tags[itag][1]==tag[1] ) return itag;
138 // Mimics the behaviour of getline, except it returns pointer to the next chunk of the text
139 // or NULL if everything has been read. The lineptr should be freed by the caller. The
140 // newline character is stripped.
141 static const char *nextline(char **lineptr, size_t *n, const char *text)
144 const char *to = text;
146 if ( !*to ) return NULL;
148 while ( *to && *to!='\n' && *to!='\r' ) to++;
153 // Advance the pointer for the next call
154 if ( *to=='\n' ) to++;
155 else if ( *to=='\r' && *(to+1)=='\n' ) to+=2;
162 *lineptr = malloc(len);
167 *lineptr = realloc(*lineptr, len);
171 debug("[nextline] Insufficient memory!\n");
175 memcpy(*lineptr,text,len);
176 (*lineptr)[len-1] = 0;
181 // name points to "XY", value_from points to the first character of the value string and
182 // value_to points to the last character of the value string.
183 static HeaderTag *new_tag(const char *name, const char *value_from, const char *value_to)
185 HeaderTag *tag = malloc(sizeof(HeaderTag));
186 int len = value_to-value_from+1;
188 tag->key[0] = name[0];
189 tag->key[1] = name[1];
190 tag->value = malloc(len+1);
191 memcpy(tag->value,value_from,len+1);
196 static HeaderTag *header_line_has_tag(HeaderLine *hline, const char *key)
198 list_t *tags = hline->tags;
201 HeaderTag *tag = tags->data;
202 if ( tag->key[0]==key[0] && tag->key[1]==key[1] ) return tag;
210 // 0 .. different types or unique tags differ or conflicting tags, cannot be merged
211 // 1 .. all tags identical -> no need to merge, drop one
212 // 2 .. the unique tags match and there are some conflicting tags (same tag, different value) -> error, cannot be merged nor duplicated
213 // 3 .. there are some missing complementary tags and no unique conflict -> can be merged into a single line
214 static int sam_header_compare_lines(HeaderLine *hline1, HeaderLine *hline2)
218 if ( hline1->type[0]!=hline2->type[0] || hline1->type[1]!=hline2->type[1] )
221 int itype = tag_exists(hline1->type,types);
223 debug("[sam_header_compare_lines] Unknown type [%c%c]\n", hline1->type[0],hline1->type[1]);
224 return -1; // FIXME (lh3): error; I do not know how this will be handled in Petr's code
227 if ( unique_tags[itype] )
229 t1 = header_line_has_tag(hline1,unique_tags[itype][0]);
230 t2 = header_line_has_tag(hline2,unique_tags[itype][0]);
231 if ( !t1 || !t2 ) // this should never happen, the unique tags are required
234 if ( strcmp(t1->value,t2->value) )
235 return 0; // the unique tags differ, cannot be merged
237 if ( !required_tags[itype] && !optional_tags[itype] )
239 t1 = hline1->tags->data;
240 t2 = hline2->tags->data;
241 if ( !strcmp(t1->value,t2->value) ) return 1; // identical comments
245 int missing=0, itag=0;
246 while ( required_tags[itype] && required_tags[itype][itag] )
248 t1 = header_line_has_tag(hline1,required_tags[itype][itag]);
249 t2 = header_line_has_tag(hline2,required_tags[itype][itag]);
251 return 2; // this should never happen
252 else if ( !t1 || !t2 )
253 missing = 1; // there is some tag missing in one of the hlines
254 else if ( strcmp(t1->value,t2->value) )
256 if ( unique_tags[itype] )
257 return 2; // the lines have a matching unique tag but have a conflicting tag
259 return 0; // the lines contain conflicting tags, cannot be merged
264 while ( optional_tags[itype] && optional_tags[itype][itag] )
266 t1 = header_line_has_tag(hline1,optional_tags[itype][itag]);
267 t2 = header_line_has_tag(hline2,optional_tags[itype][itag]);
274 missing = 1; // there is some tag missing in one of the hlines
275 else if ( strcmp(t1->value,t2->value) )
277 if ( unique_tags[itype] )
278 return 2; // the lines have a matching unique tag but have a conflicting tag
280 return 0; // the lines contain conflicting tags, cannot be merged
284 if ( missing ) return 3; // there are some missing complementary tags with no conflicts, can be merged
289 static HeaderLine *sam_header_line_clone(const HeaderLine *hline)
292 HeaderLine *out = malloc(sizeof(HeaderLine));
293 out->type[0] = hline->type[0];
294 out->type[1] = hline->type[1];
300 HeaderTag *old = tags->data;
302 HeaderTag *new = malloc(sizeof(HeaderTag));
303 new->key[0] = old->key[0];
304 new->key[1] = old->key[1];
305 new->value = strdup(old->value);
306 out->tags = list_append(out->tags, new);
313 static int sam_header_line_merge_with(HeaderLine *out_hline, const HeaderLine *tmpl_hline)
317 if ( out_hline->type[0]!=tmpl_hline->type[0] || out_hline->type[1]!=tmpl_hline->type[1] )
320 tmpl_tags = tmpl_hline->tags;
323 HeaderTag *tmpl_tag = tmpl_tags->data;
324 HeaderTag *out_tag = header_line_has_tag(out_hline, tmpl_tag->key);
327 HeaderTag *tag = malloc(sizeof(HeaderTag));
328 tag->key[0] = tmpl_tag->key[0];
329 tag->key[1] = tmpl_tag->key[1];
330 tag->value = strdup(tmpl_tag->value);
331 out_hline->tags = list_append(out_hline->tags,tag);
333 tmpl_tags = tmpl_tags->next;
339 static HeaderLine *sam_header_line_parse(const char *headerLine)
343 const char *from, *to;
346 if ( *from != '@' ) {
347 debug("[sam_header_line_parse] expected '@', got [%s]\n", headerLine);
352 while (*to && *to!='\t') to++;
353 if ( to-from != 2 ) {
354 debug("[sam_header_line_parse] expected '@XY', got [%s]\nHint: The header tags must be tab-separated.\n", headerLine);
358 hline = malloc(sizeof(HeaderLine));
359 hline->type[0] = from[0];
360 hline->type[1] = from[1];
363 int itype = tag_exists(hline->type, types);
366 while (*to && *to=='\t') to++;
367 if ( to-from != 1 ) {
368 debug("[sam_header_line_parse] multiple tabs on line [%s] (%d)\n", headerLine,(int)(to-from));
374 while (*to && *to!='\t') to++;
376 if ( !required_tags[itype] && !optional_tags[itype] )
378 // CO is a special case, it can contain anything, including tabs
379 if ( *to ) { to++; continue; }
380 tag = new_tag(" ",from,to-1);
383 tag = new_tag(from,from+3,to-1);
385 if ( header_line_has_tag(hline,tag->key) )
386 debug("The tag '%c%c' present (at least) twice on line [%s]\n", tag->key[0],tag->key[1], headerLine);
387 hline->tags = list_append(hline->tags, tag);
390 while (*to && *to=='\t') to++;
391 if ( *to && to-from != 1 ) {
392 debug("[sam_header_line_parse] multiple tabs on line [%s] (%d)\n", headerLine,(int)(to-from));
402 // Must be of an existing type, all tags must be recognised and all required tags must be present
403 static int sam_header_line_validate(HeaderLine *hline)
409 // Is the type correct?
410 itype = tag_exists(hline->type, types);
413 debug("The type [%c%c] not recognised.\n", hline->type[0],hline->type[1]);
417 // Has all required tags?
419 while ( required_tags[itype] && required_tags[itype][itag] )
421 if ( !header_line_has_tag(hline,required_tags[itype][itag]) )
423 debug("The tag [%c%c] required for [%c%c] not present.\n", required_tags[itype][itag][0],required_tags[itype][itag][1],
424 hline->type[0],hline->type[1]);
430 // Are all tags recognised?
435 if ( !tag_exists(tag->key,required_tags[itype]) && !tag_exists(tag->key,optional_tags[itype]) )
437 debug("Unknown tag [%c%c] for [%c%c].\n", tag->key[0],tag->key[1], hline->type[0],hline->type[1]);
447 static void print_header_line(FILE *fp, HeaderLine *hline)
449 list_t *tags = hline->tags;
452 fprintf(fp, "@%c%c", hline->type[0],hline->type[1]);
458 if ( tag->key[0]!=' ' || tag->key[1]!=' ' )
459 fprintf(fp, "%c%c:", tag->key[0],tag->key[1]);
460 fprintf(fp, "%s", tag->value);
468 static void sam_header_line_free(HeaderLine *hline)
470 list_t *tags = hline->tags;
473 HeaderTag *tag = tags->data;
478 list_free(hline->tags);
482 void sam_header_free(void *_header)
484 HeaderDict *header = (HeaderDict*)_header;
485 list_t *hlines = header;
488 sam_header_line_free(hlines->data);
489 hlines = hlines->next;
494 HeaderDict *sam_header_clone(const HeaderDict *dict)
496 HeaderDict *out = NULL;
499 HeaderLine *hline = dict->data;
500 out = list_append(out, sam_header_line_clone(hline));
506 // Returns a newly allocated string
507 char *sam_header_write(const void *_header)
509 const HeaderDict *header = (const HeaderDict*)_header;
512 const list_t *hlines;
514 // Calculate the length of the string to allocate
518 len += 4; // @XY and \n
520 HeaderLine *hline = hlines->data;
521 list_t *tags = hline->tags;
524 HeaderTag *tag = tags->data;
525 len += strlen(tag->value) + 1; // \t
526 if ( tag->key[0]!=' ' || tag->key[1]!=' ' )
527 len += strlen(tag->value) + 3; // XY:
530 hlines = hlines->next;
538 HeaderLine *hline = hlines->data;
540 nout += sprintf(out+nout,"@%c%c",hline->type[0],hline->type[1]);
542 list_t *tags = hline->tags;
545 HeaderTag *tag = tags->data;
546 nout += sprintf(out+nout,"\t");
547 if ( tag->key[0]!=' ' || tag->key[1]!=' ' )
548 nout += sprintf(out+nout,"%c%c:", tag->key[0],tag->key[1]);
549 nout += sprintf(out+nout,"%s", tag->value);
552 hlines = hlines->next;
553 nout += sprintf(out+nout,"\n");
559 void *sam_header_parse2(const char *headerText)
561 list_t *hlines = NULL;
571 while ( (text=nextline(&buf, &nbuf, text)) )
573 hline = sam_header_line_parse(buf);
574 if ( hline && sam_header_line_validate(hline) )
575 // With too many (~250,000) reference sequences the header parsing was too slow with list_append.
576 hlines = list_append_to_end(hlines, hline);
579 if (hline) sam_header_line_free(hline);
580 sam_header_free(hlines);
581 if ( buf ) free(buf);
585 if ( buf ) free(buf);
590 void *sam_header2tbl(const void *_dict, char type[2], char key_tag[2], char value_tag[2])
592 const HeaderDict *dict = (const HeaderDict*)_dict;
593 const list_t *l = dict;
594 khash_t(str) *tbl = kh_init(str);
598 if (_dict == 0) return tbl; // return an empty (not null) hash table
601 HeaderLine *hline = l->data;
602 if ( hline->type[0]!=type[0] || hline->type[1]!=type[1] )
608 HeaderTag *key, *value;
609 key = header_line_has_tag(hline,key_tag);
610 value = header_line_has_tag(hline,value_tag);
611 if ( !key || !value )
617 k = kh_get(str, tbl, key->value);
618 if ( k != kh_end(tbl) )
619 debug("[sam_header_lookup_table] They key %s not unique.\n", key->value);
620 k = kh_put(str, tbl, key->value, &ret);
621 kh_value(tbl, k) = value->value;
628 char **sam_header2list(const void *_dict, char type[2], char key_tag[2], int *_n)
630 const HeaderDict *dict = (const HeaderDict*)_dict;
631 const list_t *l = dict;
635 ret = 0; *_n = max = n = 0;
638 HeaderLine *hline = l->data;
639 if ( hline->type[0]!=type[0] || hline->type[1]!=type[1] )
646 key = header_line_has_tag(hline,key_tag);
654 max = max? max<<1 : 4;
655 ret = realloc(ret, max * sizeof(void*));
657 ret[n++] = key->value;
665 const char *sam_tbl_get(void *h, const char *key)
667 khash_t(str) *tbl = (khash_t(str)*)h;
669 k = kh_get(str, tbl, key);
670 return k == kh_end(tbl)? 0 : kh_val(tbl, k);
673 int sam_tbl_size(void *h)
675 khash_t(str) *tbl = (khash_t(str)*)h;
676 return h? kh_size(tbl) : 0;
679 void sam_tbl_destroy(void *h)
681 khash_t(str) *tbl = (khash_t(str)*)h;
682 kh_destroy(str, tbl);
685 void *sam_header_merge(int n, const void **_dicts)
687 const HeaderDict **dicts = (const HeaderDict**)_dicts;
688 HeaderDict *out_dict;
691 if ( n<2 ) return NULL;
693 out_dict = sam_header_clone(dicts[0]);
695 for (idict=1; idict<n; idict++)
697 const list_t *tmpl_hlines = dicts[idict];
699 while ( tmpl_hlines )
701 list_t *out_hlines = out_dict;
705 status = sam_header_compare_lines(tmpl_hlines->data, out_hlines->data);
708 out_hlines = out_hlines->next;
714 print_header_line(stderr,tmpl_hlines->data);
715 print_header_line(stderr,out_hlines->data);
716 debug("Conflicting lines, cannot merge the headers.\n");
720 sam_header_line_merge_with(out_hlines->data, tmpl_hlines->data);
726 out_dict = list_append(out_dict, sam_header_line_clone(tmpl_hlines->data));
728 tmpl_hlines = tmpl_hlines->next;