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 void debug(const char *format, ...)
57 vfprintf(stderr, format, ap);
61 void error(const char *format, ...)
65 vfprintf(stderr, format, ap);
70 list_t *list_append(list_t *root, void *data)
77 l->next = malloc(sizeof(list_t));
82 l = malloc(sizeof(list_t));
90 void list_free(list_t *root)
103 // Look for a tag "XY" in a predefined const char *[] array.
104 int tag_exists(const char *tag, const char **tags)
107 if ( !tags ) return -1;
110 if ( tags[itag][0]==tag[0] && tags[itag][1]==tag[1] ) return itag;
118 // Mimics the behaviour of getline, except it returns pointer to the next chunk of the text
119 // or NULL if everything has been read. The lineptr should be freed by the caller. The
120 // newline character is stripped.
121 const char *nextline(char **lineptr, size_t *n, const char *text)
124 const char *to = text;
126 if ( !*to ) return NULL;
128 while ( *to && *to!='\n' && *to!='\r' ) to++;
133 // Advance the pointer for the next call
134 if ( *to=='\n' ) to++;
135 else if ( *to=='\r' && *(to+1)=='\n' ) to+=2;
142 *lineptr = malloc(len);
147 *lineptr = realloc(*lineptr, len);
153 memcpy(*lineptr,text,len);
154 (*lineptr)[len-1] = 0;
159 // name points to "XY", value_from points to the first character of the value string and
160 // value_to points to the last character of the value string.
161 HeaderTag *new_tag(const char *name, const char *value_from, const char *value_to)
163 HeaderTag *tag = malloc(sizeof(HeaderTag));
164 int len = value_to-value_from+1;
166 tag->key[0] = name[0];
167 tag->key[1] = name[1];
168 tag->value = malloc(len+1);
169 memcpy(tag->value,value_from,len+1);
174 HeaderTag *header_line_has_tag(HeaderLine *hline, const char *key)
176 list_t *tags = hline->tags;
179 HeaderTag *tag = tags->data;
180 if ( tag->key[0]==key[0] && tag->key[1]==key[1] ) return tag;
188 // 0 .. different types or unique tags differ or conflicting tags, cannot be merged
189 // 1 .. all tags identical -> no need to merge, drop one
190 // 2 .. the unique tags match and there are some conflicting tags (same tag, different value) -> error, cannot be merged nor duplicated
191 // 3 .. there are some missing complementary tags and no unique conflict -> can be merged into a single line
192 int sam_header_compare_lines(HeaderLine *hline1, HeaderLine *hline2)
196 if ( hline1->type[0]!=hline2->type[0] || hline1->type[1]!=hline2->type[1] )
199 int itype = tag_exists(hline1->type,types);
200 if ( itype==-1 ) error("[sam_header_compare_lines] Unknown type [%c%c]\n", hline1->type[0],hline1->type[1]);
202 if ( unique_tags[itype] )
204 t1 = header_line_has_tag(hline1,unique_tags[itype][0]);
205 t2 = header_line_has_tag(hline2,unique_tags[itype][0]);
206 if ( !t1 || !t2 ) // this should never happen, the unique tags are required
209 if ( strcmp(t1->value,t2->value) )
210 return 0; // the unique tags differ, cannot be merged
212 if ( !required_tags[itype] && !optional_tags[itype] )
214 t1 = hline1->tags->data;
215 t2 = hline2->tags->data;
216 if ( !strcmp(t1->value,t2->value) ) return 1; // identical comments
220 int missing=0, itag=0;
221 while ( required_tags[itype] && required_tags[itype][itag] )
223 t1 = header_line_has_tag(hline1,required_tags[itype][itag]);
224 t2 = header_line_has_tag(hline2,required_tags[itype][itag]);
226 return 2; // this should never happen
227 else if ( !t1 || !t2 )
228 missing = 1; // there is some tag missing in one of the hlines
229 else if ( strcmp(t1->value,t2->value) )
231 if ( unique_tags[itype] )
232 return 2; // the lines have a matching unique tag but have a conflicting tag
234 return 0; // the lines contain conflicting tags, cannot be merged
239 while ( optional_tags[itype] && optional_tags[itype][itag] )
241 t1 = header_line_has_tag(hline1,optional_tags[itype][itag]);
242 t2 = header_line_has_tag(hline2,optional_tags[itype][itag]);
249 missing = 1; // there is some tag missing in one of the hlines
250 else if ( strcmp(t1->value,t2->value) )
252 if ( unique_tags[itype] )
253 return 2; // the lines have a matching unique tag but have a conflicting tag
255 return 0; // the lines contain conflicting tags, cannot be merged
259 if ( missing ) return 3; // there are some missing complementary tags with no conflicts, can be merged
264 HeaderLine *sam_header_line_clone(const HeaderLine *hline)
267 HeaderLine *out = malloc(sizeof(HeaderLine));
268 out->type[0] = hline->type[0];
269 out->type[1] = hline->type[1];
275 HeaderTag *old = tags->data;
277 HeaderTag *new = malloc(sizeof(HeaderTag));
278 new->key[0] = old->key[0];
279 new->key[1] = old->key[1];
280 new->value = strdup(old->value);
281 out->tags = list_append(out->tags, new);
288 int sam_header_line_merge_with(HeaderLine *out_hline, const HeaderLine *tmpl_hline)
292 if ( out_hline->type[0]!=tmpl_hline->type[0] || out_hline->type[1]!=tmpl_hline->type[1] )
295 tmpl_tags = tmpl_hline->tags;
298 HeaderTag *tmpl_tag = tmpl_tags->data;
299 HeaderTag *out_tag = header_line_has_tag(out_hline, tmpl_tag->key);
302 HeaderTag *tag = malloc(sizeof(HeaderTag));
303 tag->key[0] = tmpl_tag->key[0];
304 tag->key[1] = tmpl_tag->key[1];
305 tag->value = strdup(tmpl_tag->value);
306 out_hline->tags = list_append(out_hline->tags,tag);
308 tmpl_tags = tmpl_tags->next;
314 HeaderLine *sam_header_line_parse(const char *headerLine)
318 const char *from, *to;
321 if ( *from != '@' ) error("[sam_header_line_parse] expected '@', got [%s]\n", headerLine);
324 while (*to && *to!='\t') to++;
325 if ( to-from != 2 ) error("[sam_header_line_parse] expected '@XY', got [%s]\n", headerLine);
327 hline = malloc(sizeof(HeaderLine));
328 hline->type[0] = from[0];
329 hline->type[1] = from[1];
332 int itype = tag_exists(hline->type, types);
335 while (*to && *to=='\t') to++;
337 error("[sam_header_line_parse] multiple tabs on line [%s] (%d)\n", headerLine,(int)(to-from));
341 while (*to && *to!='\t') to++;
343 if ( !required_tags[itype] && !optional_tags[itype] )
344 tag = new_tag(" ",from,to-1);
346 tag = new_tag(from,from+3,to-1);
348 if ( header_line_has_tag(hline,tag->key) )
349 debug("The tag '%c%c' present (at least) twice on line [%s]\n", tag->key[0],tag->key[1], headerLine);
350 hline->tags = list_append(hline->tags, tag);
353 while (*to && *to=='\t') to++;
354 if ( *to && to-from != 1 )
355 error("[sam_header_line_parse] multiple tabs on line [%s] (%d)\n", headerLine,(int)(to-from));
363 // Must be of an existing type, all tags must be recognised and all required tags must be present
364 int sam_header_line_validate(HeaderLine *hline)
370 // Is the type correct?
371 itype = tag_exists(hline->type, types);
374 debug("The type [%c%c] not recognised.\n", hline->type[0],hline->type[1]);
378 // Has all required tags?
380 while ( required_tags[itype] && required_tags[itype][itag] )
382 if ( !header_line_has_tag(hline,required_tags[itype][itag]) )
384 debug("The tag [%c%c] required for [%c%c] not present.\n", required_tags[itype][itag][0],required_tags[itype][itag][1],
385 hline->type[0],hline->type[1]);
391 // Are all tags recognised?
396 if ( !tag_exists(tag->key,required_tags[itype]) && !tag_exists(tag->key,optional_tags[itype]) )
398 debug("Unknown tag [%c%c] for [%c%c].\n", tag->key[0],tag->key[1], hline->type[0],hline->type[1]);
408 void print_header_line(FILE *fp, HeaderLine *hline)
410 list_t *tags = hline->tags;
413 fprintf(fp, "@%c%c", hline->type[0],hline->type[1]);
419 if ( tag->key[0]!=' ' || tag->key[1]!=' ' )
420 fprintf(fp, "%c%c:", tag->key[0],tag->key[1]);
421 fprintf(fp, "%s", tag->value);
429 void sam_header_line_free(HeaderLine *hline)
431 list_t *tags = hline->tags;
434 HeaderTag *tag = tags->data;
439 list_free(hline->tags);
443 void sam_header_free(void *_header)
445 HeaderDict *header = (HeaderDict*)_header;
446 list_t *hlines = header;
449 sam_header_line_free(hlines->data);
450 hlines = hlines->next;
455 HeaderDict *sam_header_clone(const HeaderDict *dict)
457 HeaderDict *out = NULL;
460 HeaderLine *hline = dict->data;
461 out = list_append(out, sam_header_line_clone(hline));
467 // Returns a newly allocated string
468 char *sam_header_write(const void *_header)
470 const HeaderDict *header = (const HeaderDict*)_header;
473 const list_t *hlines;
475 // Calculate the length of the string to allocate
479 len += 4; // @XY and \n
481 HeaderLine *hline = hlines->data;
482 list_t *tags = hline->tags;
485 HeaderTag *tag = tags->data;
486 len += strlen(tag->value) + 1; // \t
487 if ( tag->key[0]!=' ' || tag->key[1]!=' ' )
488 len += strlen(tag->value) + 3; // XY:
491 hlines = hlines->next;
499 HeaderLine *hline = hlines->data;
501 nout += sprintf(out+nout,"@%c%c",hline->type[0],hline->type[1]);
503 list_t *tags = hline->tags;
506 HeaderTag *tag = tags->data;
507 nout += sprintf(out+nout,"\t");
508 if ( tag->key[0]!=' ' || tag->key[1]!=' ' )
509 nout += sprintf(out+nout,"%c%c:", tag->key[0],tag->key[1]);
510 nout += sprintf(out+nout,"%s", tag->value);
513 hlines = hlines->next;
514 nout += sprintf(out+nout,"\n");
520 void *sam_header_parse2(const char *headerText)
522 list_t *hlines = NULL;
532 while ( (text=nextline(&buf, &nbuf, text)) )
534 hline = sam_header_line_parse(buf);
535 if ( sam_header_line_validate(hline) )
536 hlines = list_append(hlines, hline);
539 sam_header_line_free(hline);
540 sam_header_free(hlines);
541 if ( buf ) free(buf);
545 if ( buf ) free(buf);
550 void *sam_header2tbl(const void *_dict, char type[2], char key_tag[2], char value_tag[2])
552 const HeaderDict *dict = (const HeaderDict*)_dict;
553 const list_t *l = dict;
554 khash_t(str) *tbl = kh_init(str);
560 HeaderLine *hline = l->data;
561 if ( hline->type[0]!=type[0] || hline->type[1]!=type[1] )
567 HeaderTag *key, *value;
568 key = header_line_has_tag(hline,key_tag);
569 value = header_line_has_tag(hline,value_tag);
570 if ( !key || !value )
576 k = kh_get(str, tbl, key->value);
577 if ( k != kh_end(tbl) )
578 debug("[sam_header_lookup_table] They key %s not unique.\n", key->value);
579 k = kh_put(str, tbl, key->value, &ret);
580 kh_value(tbl, k) = value->value;
587 char **sam_header2list(const void *_dict, char type[2], char key_tag[2], int *_n)
589 const HeaderDict *dict = (const HeaderDict*)_dict;
590 const list_t *l = dict;
594 ret = 0; *_n = max = n = 0;
597 HeaderLine *hline = l->data;
598 if ( hline->type[0]!=type[0] || hline->type[1]!=type[1] )
605 key = header_line_has_tag(hline,key_tag);
613 max = max? max<<1 : 4;
614 ret = realloc(ret, max * sizeof(void*));
616 ret[n++] = key->value;
624 const char *sam_tbl_get(void *h, const char *key)
626 khash_t(str) *tbl = (khash_t(str)*)h;
628 k = kh_get(str, tbl, key);
629 return k == kh_end(tbl)? 0 : kh_val(tbl, k);
632 int sam_tbl_size(void *h)
634 khash_t(str) *tbl = (khash_t(str)*)h;
635 return h? kh_size(tbl) : 0;
638 void sam_tbl_destroy(void *h)
640 khash_t(str) *tbl = (khash_t(str)*)h;
641 kh_destroy(str, tbl);
644 void *sam_header_merge(int n, const void **_dicts)
646 const HeaderDict **dicts = (const HeaderDict**)_dicts;
647 HeaderDict *out_dict;
650 if ( n<2 ) return NULL;
652 out_dict = sam_header_clone(dicts[0]);
654 for (idict=1; idict<n; idict++)
656 const list_t *tmpl_hlines = dicts[idict];
658 while ( tmpl_hlines )
660 list_t *out_hlines = out_dict;
664 status = sam_header_compare_lines(tmpl_hlines->data, out_hlines->data);
667 out_hlines = out_hlines->next;
673 print_header_line(stderr,tmpl_hlines->data);
674 print_header_line(stderr,out_hlines->data);
675 error("Conflicting lines, cannot merge the headers.\n");
678 sam_header_line_merge_with(out_hlines->data, tmpl_hlines->data);
684 out_dict = list_append(out_dict, sam_header_line_clone(tmpl_hlines->data));
686 tmpl_hlines = tmpl_hlines->next;