1 #include "sam_header.h"
9 KHASH_MAP_INIT_STR(str, const char *)
13 struct _HeaderList *next;
16 typedef struct _HeaderList list_t;
17 typedef list_t HeaderDict;
33 const char *o_hd_tags[] = {"SO","GO",NULL};
34 const char *r_hd_tags[] = {"VN",NULL};
36 const char *o_sq_tags[] = {"AS","M5","UR","SP",NULL};
37 const char *r_sq_tags[] = {"SN","LN",NULL};
38 const char *u_sq_tags[] = {"SN",NULL};
40 const char *o_rg_tags[] = {"LB","DS","PU","PI","CN","DT","PL",NULL};
41 const char *r_rg_tags[] = {"ID",NULL};
42 const char *u_rg_tags[] = {"ID",NULL};
44 const char *o_pg_tags[] = {"VN","CL",NULL};
45 const char *r_pg_tags[] = {"ID",NULL};
47 const char *types[] = {"HD","SQ","RG","PG","CO",NULL};
48 const char **optional_tags[] = {o_hd_tags,o_sq_tags,o_rg_tags,o_pg_tags,NULL,NULL};
49 const char **required_tags[] = {r_hd_tags,r_sq_tags,r_rg_tags,r_pg_tags,NULL,NULL};
50 const char **unique_tags[] = {NULL, u_sq_tags,u_rg_tags,NULL,NULL,NULL};
53 static void debug(const char *format, ...)
57 vfprintf(stderr, format, ap);
61 static list_t *list_prepend(list_t *root, void *data)
63 list_t *l = malloc(sizeof(list_t));
69 static list_t *list_append(list_t *root, void *data)
76 l->next = malloc(sizeof(list_t));
81 l = malloc(sizeof(list_t));
89 static void list_free(list_t *root)
102 // Look for a tag "XY" in a predefined const char *[] array.
103 static int tag_exists(const char *tag, const char **tags)
106 if ( !tags ) return -1;
109 if ( tags[itag][0]==tag[0] && tags[itag][1]==tag[1] ) return itag;
117 // Mimics the behaviour of getline, except it returns pointer to the next chunk of the text
118 // or NULL if everything has been read. The lineptr should be freed by the caller. The
119 // newline character is stripped.
120 static const char *nextline(char **lineptr, size_t *n, const char *text)
123 const char *to = text;
125 if ( !*to ) return NULL;
127 while ( *to && *to!='\n' && *to!='\r' ) to++;
132 // Advance the pointer for the next call
133 if ( *to=='\n' ) to++;
134 else if ( *to=='\r' && *(to+1)=='\n' ) to+=2;
141 *lineptr = malloc(len);
146 *lineptr = realloc(*lineptr, len);
150 debug("[nextline] Insufficient memory!\n");
154 memcpy(*lineptr,text,len);
155 (*lineptr)[len-1] = 0;
160 // name points to "XY", value_from points to the first character of the value string and
161 // value_to points to the last character of the value string.
162 static HeaderTag *new_tag(const char *name, const char *value_from, const char *value_to)
164 HeaderTag *tag = malloc(sizeof(HeaderTag));
165 int len = value_to-value_from+1;
167 tag->key[0] = name[0];
168 tag->key[1] = name[1];
169 tag->value = malloc(len+1);
170 memcpy(tag->value,value_from,len+1);
175 static HeaderTag *header_line_has_tag(HeaderLine *hline, const char *key)
177 list_t *tags = hline->tags;
180 HeaderTag *tag = tags->data;
181 if ( tag->key[0]==key[0] && tag->key[1]==key[1] ) return tag;
189 // 0 .. different types or unique tags differ or conflicting tags, cannot be merged
190 // 1 .. all tags identical -> no need to merge, drop one
191 // 2 .. the unique tags match and there are some conflicting tags (same tag, different value) -> error, cannot be merged nor duplicated
192 // 3 .. there are some missing complementary tags and no unique conflict -> can be merged into a single line
193 static int sam_header_compare_lines(HeaderLine *hline1, HeaderLine *hline2)
197 if ( hline1->type[0]!=hline2->type[0] || hline1->type[1]!=hline2->type[1] )
200 int itype = tag_exists(hline1->type,types);
202 debug("[sam_header_compare_lines] Unknown type [%c%c]\n", hline1->type[0],hline1->type[1]);
203 return -1; // FIXME (lh3): error; I do not know how this will be handled in Petr's code
206 if ( unique_tags[itype] )
208 t1 = header_line_has_tag(hline1,unique_tags[itype][0]);
209 t2 = header_line_has_tag(hline2,unique_tags[itype][0]);
210 if ( !t1 || !t2 ) // this should never happen, the unique tags are required
213 if ( strcmp(t1->value,t2->value) )
214 return 0; // the unique tags differ, cannot be merged
216 if ( !required_tags[itype] && !optional_tags[itype] )
218 t1 = hline1->tags->data;
219 t2 = hline2->tags->data;
220 if ( !strcmp(t1->value,t2->value) ) return 1; // identical comments
224 int missing=0, itag=0;
225 while ( required_tags[itype] && required_tags[itype][itag] )
227 t1 = header_line_has_tag(hline1,required_tags[itype][itag]);
228 t2 = header_line_has_tag(hline2,required_tags[itype][itag]);
230 return 2; // this should never happen
231 else if ( !t1 || !t2 )
232 missing = 1; // there is some tag missing in one of the hlines
233 else if ( strcmp(t1->value,t2->value) )
235 if ( unique_tags[itype] )
236 return 2; // the lines have a matching unique tag but have a conflicting tag
238 return 0; // the lines contain conflicting tags, cannot be merged
243 while ( optional_tags[itype] && optional_tags[itype][itag] )
245 t1 = header_line_has_tag(hline1,optional_tags[itype][itag]);
246 t2 = header_line_has_tag(hline2,optional_tags[itype][itag]);
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
263 if ( missing ) return 3; // there are some missing complementary tags with no conflicts, can be merged
268 static HeaderLine *sam_header_line_clone(const HeaderLine *hline)
271 HeaderLine *out = malloc(sizeof(HeaderLine));
272 out->type[0] = hline->type[0];
273 out->type[1] = hline->type[1];
279 HeaderTag *old = tags->data;
281 HeaderTag *new = malloc(sizeof(HeaderTag));
282 new->key[0] = old->key[0];
283 new->key[1] = old->key[1];
284 new->value = strdup(old->value);
285 out->tags = list_append(out->tags, new);
292 static int sam_header_line_merge_with(HeaderLine *out_hline, const HeaderLine *tmpl_hline)
296 if ( out_hline->type[0]!=tmpl_hline->type[0] || out_hline->type[1]!=tmpl_hline->type[1] )
299 tmpl_tags = tmpl_hline->tags;
302 HeaderTag *tmpl_tag = tmpl_tags->data;
303 HeaderTag *out_tag = header_line_has_tag(out_hline, tmpl_tag->key);
306 HeaderTag *tag = malloc(sizeof(HeaderTag));
307 tag->key[0] = tmpl_tag->key[0];
308 tag->key[1] = tmpl_tag->key[1];
309 tag->value = strdup(tmpl_tag->value);
310 out_hline->tags = list_append(out_hline->tags,tag);
312 tmpl_tags = tmpl_tags->next;
318 static HeaderLine *sam_header_line_parse(const char *headerLine)
322 const char *from, *to;
325 if ( *from != '@' ) {
326 debug("[sam_header_line_parse] expected '@', got [%s]\n", headerLine);
331 while (*to && *to!='\t') to++;
332 if ( to-from != 2 ) {
333 debug("[sam_header_line_parse] expected '@XY', got [%s]\n", headerLine);
337 hline = malloc(sizeof(HeaderLine));
338 hline->type[0] = from[0];
339 hline->type[1] = from[1];
342 int itype = tag_exists(hline->type, types);
345 while (*to && *to=='\t') to++;
346 if ( to-from != 1 ) {
347 debug("[sam_header_line_parse] multiple tabs on line [%s] (%d)\n", headerLine,(int)(to-from));
353 while (*to && *to!='\t') to++;
355 if ( !required_tags[itype] && !optional_tags[itype] )
357 // CO is a special case, it can contain anything, including tabs
358 if ( *to ) { to++; continue; }
359 tag = new_tag(" ",from,to-1);
362 tag = new_tag(from,from+3,to-1);
364 if ( header_line_has_tag(hline,tag->key) )
365 debug("The tag '%c%c' present (at least) twice on line [%s]\n", tag->key[0],tag->key[1], headerLine);
366 hline->tags = list_append(hline->tags, tag);
369 while (*to && *to=='\t') to++;
370 if ( *to && to-from != 1 ) {
371 debug("[sam_header_line_parse] multiple tabs on line [%s] (%d)\n", headerLine,(int)(to-from));
381 // Must be of an existing type, all tags must be recognised and all required tags must be present
382 static int sam_header_line_validate(HeaderLine *hline)
388 // Is the type correct?
389 itype = tag_exists(hline->type, types);
392 debug("The type [%c%c] not recognised.\n", hline->type[0],hline->type[1]);
396 // Has all required tags?
398 while ( required_tags[itype] && required_tags[itype][itag] )
400 if ( !header_line_has_tag(hline,required_tags[itype][itag]) )
402 debug("The tag [%c%c] required for [%c%c] not present.\n", required_tags[itype][itag][0],required_tags[itype][itag][1],
403 hline->type[0],hline->type[1]);
409 // Are all tags recognised?
414 if ( !tag_exists(tag->key,required_tags[itype]) && !tag_exists(tag->key,optional_tags[itype]) )
416 debug("Unknown tag [%c%c] for [%c%c].\n", tag->key[0],tag->key[1], hline->type[0],hline->type[1]);
426 static void print_header_line(FILE *fp, HeaderLine *hline)
428 list_t *tags = hline->tags;
431 fprintf(fp, "@%c%c", hline->type[0],hline->type[1]);
437 if ( tag->key[0]!=' ' || tag->key[1]!=' ' )
438 fprintf(fp, "%c%c:", tag->key[0],tag->key[1]);
439 fprintf(fp, "%s", tag->value);
447 static void sam_header_line_free(HeaderLine *hline)
449 list_t *tags = hline->tags;
452 HeaderTag *tag = tags->data;
457 list_free(hline->tags);
461 void sam_header_free(void *_header)
463 HeaderDict *header = (HeaderDict*)_header;
464 list_t *hlines = header;
467 sam_header_line_free(hlines->data);
468 hlines = hlines->next;
473 HeaderDict *sam_header_clone(const HeaderDict *dict)
475 HeaderDict *out = NULL;
478 HeaderLine *hline = dict->data;
479 out = list_append(out, sam_header_line_clone(hline));
485 // Returns a newly allocated string
486 char *sam_header_write(const void *_header)
488 const HeaderDict *header = (const HeaderDict*)_header;
491 const list_t *hlines;
493 // Calculate the length of the string to allocate
497 len += 4; // @XY and \n
499 HeaderLine *hline = hlines->data;
500 list_t *tags = hline->tags;
503 HeaderTag *tag = tags->data;
504 len += strlen(tag->value) + 1; // \t
505 if ( tag->key[0]!=' ' || tag->key[1]!=' ' )
506 len += strlen(tag->value) + 3; // XY:
509 hlines = hlines->next;
517 HeaderLine *hline = hlines->data;
519 nout += sprintf(out+nout,"@%c%c",hline->type[0],hline->type[1]);
521 list_t *tags = hline->tags;
524 HeaderTag *tag = tags->data;
525 nout += sprintf(out+nout,"\t");
526 if ( tag->key[0]!=' ' || tag->key[1]!=' ' )
527 nout += sprintf(out+nout,"%c%c:", tag->key[0],tag->key[1]);
528 nout += sprintf(out+nout,"%s", tag->value);
531 hlines = hlines->next;
532 nout += sprintf(out+nout,"\n");
538 void *sam_header_parse2(const char *headerText)
540 list_t *hlines = NULL;
550 while ( (text=nextline(&buf, &nbuf, text)) )
552 hline = sam_header_line_parse(buf);
553 if ( hline && sam_header_line_validate(hline) )
554 hlines = list_prepend(hlines, hline);
557 if (hline) sam_header_line_free(hline);
558 sam_header_free(hlines);
559 if ( buf ) free(buf);
563 if ( buf ) free(buf);
568 void *sam_header2tbl(const void *_dict, char type[2], char key_tag[2], char value_tag[2])
570 const HeaderDict *dict = (const HeaderDict*)_dict;
571 const list_t *l = dict;
572 khash_t(str) *tbl = kh_init(str);
576 if (_dict == 0) return tbl; // return an empty (not null) hash table
579 HeaderLine *hline = l->data;
580 if ( hline->type[0]!=type[0] || hline->type[1]!=type[1] )
586 HeaderTag *key, *value;
587 key = header_line_has_tag(hline,key_tag);
588 value = header_line_has_tag(hline,value_tag);
589 if ( !key || !value )
595 k = kh_get(str, tbl, key->value);
596 if ( k != kh_end(tbl) )
597 debug("[sam_header_lookup_table] They key %s not unique.\n", key->value);
598 k = kh_put(str, tbl, key->value, &ret);
599 kh_value(tbl, k) = value->value;
606 char **sam_header2list(const void *_dict, char type[2], char key_tag[2], int *_n)
608 const HeaderDict *dict = (const HeaderDict*)_dict;
609 const list_t *l = dict;
613 ret = 0; *_n = max = n = 0;
616 HeaderLine *hline = l->data;
617 if ( hline->type[0]!=type[0] || hline->type[1]!=type[1] )
624 key = header_line_has_tag(hline,key_tag);
632 max = max? max<<1 : 4;
633 ret = realloc(ret, max * sizeof(void*));
635 ret[n++] = key->value;
643 const char *sam_tbl_get(void *h, const char *key)
645 khash_t(str) *tbl = (khash_t(str)*)h;
647 k = kh_get(str, tbl, key);
648 return k == kh_end(tbl)? 0 : kh_val(tbl, k);
651 int sam_tbl_size(void *h)
653 khash_t(str) *tbl = (khash_t(str)*)h;
654 return h? kh_size(tbl) : 0;
657 void sam_tbl_destroy(void *h)
659 khash_t(str) *tbl = (khash_t(str)*)h;
660 kh_destroy(str, tbl);
663 void *sam_header_merge(int n, const void **_dicts)
665 const HeaderDict **dicts = (const HeaderDict**)_dicts;
666 HeaderDict *out_dict;
669 if ( n<2 ) return NULL;
671 out_dict = sam_header_clone(dicts[0]);
673 for (idict=1; idict<n; idict++)
675 const list_t *tmpl_hlines = dicts[idict];
677 while ( tmpl_hlines )
679 list_t *out_hlines = out_dict;
683 status = sam_header_compare_lines(tmpl_hlines->data, out_hlines->data);
686 out_hlines = out_hlines->next;
692 print_header_line(stderr,tmpl_hlines->data);
693 print_header_line(stderr,out_hlines->data);
694 debug("Conflicting lines, cannot merge the headers.\n");
698 sam_header_line_merge_with(out_hlines->data, tmpl_hlines->data);
704 out_dict = list_append(out_dict, sam_header_line_clone(tmpl_hlines->data));
706 tmpl_hlines = tmpl_hlines->next;