forked from samtools/htslib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
header.c
2803 lines (2345 loc) · 80 KB
/
header.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright (c) 2018-2020, 2023 Genome Research Ltd.
Authors: James Bonfield <[email protected]>, Valeriu Ohan <[email protected]>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the names Genome Research Ltd and Wellcome Trust Sanger
Institute nor the names of its contributors may be used to endorse or promote
products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY GENOME RESEARCH LTD AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL GENOME RESEARCH LTD OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#define HTS_BUILDING_LIBRARY // Enables HTSLIB_EXPORT, see htslib/hts_defs.h
#include <config.h>
#include <string.h>
#include <assert.h>
#include <errno.h>
#include "textutils_internal.h"
#include "header.h"
// Hash table for removing multiple lines from the header
KHASH_SET_INIT_STR(rm)
// Used for long refs in SAM files
KHASH_DECLARE(s2i, kh_cstr_t, int64_t)
typedef khash_t(rm) rmhash_t;
static int sam_hdr_link_pg(sam_hdr_t *bh);
static int sam_hrecs_vupdate(sam_hrecs_t *hrecs, sam_hrec_type_t *type, va_list ap);
static int sam_hrecs_update(sam_hrecs_t *hrecs, sam_hrec_type_t *type, ...);
#define MAX_ERROR_QUOTE 320 // Prevent over-long error messages
static void sam_hrecs_error(const char *msg, const char *line, size_t len, size_t lno) {
int j;
if (len > MAX_ERROR_QUOTE)
len = MAX_ERROR_QUOTE;
for (j = 0; j < len && line[j] != '\n'; j++)
;
hts_log_error("%s at line %zd: \"%.*s\"", msg, lno, j, line);
}
/* ==== Static methods ==== */
static int sam_hrecs_init_type_order(sam_hrecs_t *hrecs, char *type_list) {
if (!hrecs)
return -1;
if (!type_list) {
hrecs->type_count = 5;
hrecs->type_order = calloc(hrecs->type_count, 3);
if (!hrecs->type_order)
return -1;
memcpy(hrecs->type_order[0], "HD", 2);
memcpy(hrecs->type_order[1], "SQ", 2);
memcpy(hrecs->type_order[2], "RG", 2);
memcpy(hrecs->type_order[3], "PG", 2);
memcpy(hrecs->type_order[4], "CO", 2);
}
return 0;
}
static int sam_hrecs_add_ref_altnames(sam_hrecs_t *hrecs, int nref, const char *list) {
const char *token;
ks_tokaux_t aux;
if (!list)
return 0;
for (token = kstrtok(list, ",", &aux); token; token = kstrtok(NULL, NULL, &aux)) {
if (aux.p == token)
continue;
char *name = string_ndup(hrecs->str_pool, token, aux.p - token);
if (!name)
return -1;
int r;
khint_t k = kh_put(m_s2i, hrecs->ref_hash, name, &r);
if (r < 0) return -1;
if (r > 0)
kh_val(hrecs->ref_hash, k) = nref;
else if (kh_val(hrecs->ref_hash, k) != nref)
hts_log_warning("Duplicate entry AN:\"%s\" in sam header", name);
}
return 0;
}
static void sam_hrecs_remove_ref_altnames(sam_hrecs_t *hrecs, int expected, const char *list) {
const char *token, *sn;
ks_tokaux_t aux;
kstring_t str = KS_INITIALIZE;
if (expected < 0 || expected >= hrecs->nref)
return;
sn = hrecs->ref[expected].name;
for (token = kstrtok(list, ",", &aux); token; token = kstrtok(NULL, NULL, &aux)) {
kputsn(token, aux.p - token, ks_clear(&str));
khint_t k = kh_get(m_s2i, hrecs->ref_hash, str.s);
if (k != kh_end(hrecs->ref_hash)
&& kh_val(hrecs->ref_hash, k) == expected
&& strcmp(sn, str.s) != 0)
kh_del(m_s2i, hrecs->ref_hash, k);
}
free(str.s);
}
/* Updates the hash tables in the sam_hrecs_t structure.
*
* Returns 0 on success;
* -1 on failure
*/
static int sam_hrecs_update_hashes(sam_hrecs_t *hrecs,
khint32_t type,
sam_hrec_type_t *h_type) {
/* Add to reference hash? */
if (type == TYPEKEY("SQ")) {
sam_hrec_tag_t *tag = h_type->tag;
int nref = hrecs->nref;
const char *name = NULL;
const char *altnames = NULL;
hts_pos_t len = -1;
int r;
khint_t k;
while (tag) {
if (tag->str[0] == 'S' && tag->str[1] == 'N') {
assert(tag->len >= 3);
name = tag->str+3;
} else if (tag->str[0] == 'L' && tag->str[1] == 'N') {
assert(tag->len >= 3);
len = strtoll(tag->str+3, NULL, 10);
} else if (tag->str[0] == 'A' && tag->str[1] == 'N') {
assert(tag->len >= 3);
altnames = tag->str+3;
}
tag = tag->next;
}
if (!name) {
hts_log_error("Header includes @SQ line with no SN: tag");
return -1; // SN should be present, according to spec.
}
if (len == -1) {
hts_log_error("Header includes @SQ line \"%s\" with no LN: tag",
name);
return -1; // LN should be present, according to spec.
}
// Seen already?
k = kh_get(m_s2i, hrecs->ref_hash, name);
if (k < kh_end(hrecs->ref_hash)) {
nref = kh_val(hrecs->ref_hash, k);
int ref_changed_flag = 0;
// Check for hash entry added by sam_hrecs_refs_from_targets_array()
if (hrecs->ref[nref].ty == NULL) {
// Attach header line to existing stub entry.
hrecs->ref[nref].ty = h_type;
// Check lengths match; correct if not.
if (len != hrecs->ref[nref].len) {
char tmp[32];
snprintf(tmp, sizeof(tmp), "%" PRIhts_pos,
hrecs->ref[nref].len);
if (sam_hrecs_update(hrecs, h_type, "LN", tmp, NULL) < 0)
return -1;
ref_changed_flag = 1;
}
if (sam_hrecs_add_ref_altnames(hrecs, nref, altnames) < 0)
return -1;
if (ref_changed_flag && (hrecs->refs_changed < 0 || hrecs->refs_changed > nref))
hrecs->refs_changed = nref;
return 0;
}
// Check to see if an existing entry is being updated
if (hrecs->ref[nref].ty == h_type) {
if (hrecs->ref[nref].len != len) {
hrecs->ref[nref].len = len;
ref_changed_flag = 1;
}
if (!hrecs->ref[nref].name || strcmp(hrecs->ref[nref].name, name)) {
hrecs->ref[nref].name = name;
ref_changed_flag = 1;
}
if (sam_hrecs_add_ref_altnames(hrecs, nref, altnames) < 0)
return -1;
if (ref_changed_flag && (hrecs->refs_changed < 0 || hrecs->refs_changed > nref))
hrecs->refs_changed = nref;
return 0;
}
// If here, the name is a duplicate.
// Check to see if it matches the SN: tag from the earlier record.
if (strcmp(hrecs->ref[nref].name, name) == 0) {
hts_log_error("Duplicate entry \"%s\" in sam header",
name);
return -1;
}
// Clash with an already-seen altname
// As SN: should be preferred to AN: add this as a new
// record and update the hash entry to point to it.
hts_log_warning("Ref name SN:\"%s\" is a duplicate of an existing AN key", name);
nref = hrecs->nref;
}
if (nref == hrecs->ref_sz) {
size_t new_sz = hrecs->ref_sz >= 4 ? hrecs->ref_sz + (hrecs->ref_sz / 4) : 32;
sam_hrec_sq_t *new_ref = realloc(hrecs->ref, sizeof(*hrecs->ref) * new_sz);
if (!new_ref)
return -1;
hrecs->ref = new_ref;
hrecs->ref_sz = new_sz;
}
hrecs->ref[nref].name = name;
hrecs->ref[nref].len = len;
hrecs->ref[nref].ty = h_type;
k = kh_put(m_s2i, hrecs->ref_hash, hrecs->ref[nref].name, &r);
if (-1 == r) return -1;
kh_val(hrecs->ref_hash, k) = nref;
if (sam_hrecs_add_ref_altnames(hrecs, nref, altnames) < 0)
return -1;
if (hrecs->refs_changed < 0 || hrecs->refs_changed > hrecs->nref)
hrecs->refs_changed = hrecs->nref;
hrecs->nref++;
}
/* Add to read-group hash? */
if (type == TYPEKEY("RG")) {
sam_hrec_tag_t *tag = sam_hrecs_find_key(h_type, "ID", NULL);
int nrg = hrecs->nrg, r;
khint_t k;
if (!tag) {
hts_log_error("Header includes @RG line with no ID: tag");
return -1; // ID should be present, according to spec.
}
assert(tag->str && tag->len >= 3);
// Seen already?
k = kh_get(m_s2i, hrecs->rg_hash, tag->str + 3);
if (k < kh_end(hrecs->rg_hash)) {
nrg = kh_val(hrecs->rg_hash, k);
assert(hrecs->rg[nrg].ty != NULL);
if (hrecs->rg[nrg].ty != h_type) {
hts_log_warning("Duplicate entry \"%s\" in sam header",
tag->str + 3);
} else {
hrecs->rg[nrg].name = tag->str + 3;
hrecs->rg[nrg].name_len = tag->len - 3;
}
return 0;
}
if (nrg == hrecs->rg_sz) {
size_t new_sz = hrecs->rg_sz >= 4 ? hrecs->rg_sz + hrecs->rg_sz / 4 : 4;
sam_hrec_rg_t *new_rg = realloc(hrecs->rg, sizeof(*hrecs->rg) * new_sz);
if (!new_rg)
return -1;
hrecs->rg = new_rg;
hrecs->rg_sz = new_sz;
}
hrecs->rg[nrg].name = tag->str + 3;
hrecs->rg[nrg].name_len = tag->len - 3;
hrecs->rg[nrg].ty = h_type;
hrecs->rg[nrg].id = nrg;
k = kh_put(m_s2i, hrecs->rg_hash, hrecs->rg[nrg].name, &r);
if (-1 == r) return -1;
kh_val(hrecs->rg_hash, k) = nrg;
hrecs->nrg++;
}
/* Add to program hash? */
if (type == TYPEKEY("PG")) {
sam_hrec_tag_t *tag;
sam_hrec_pg_t *new_pg;
int npg = hrecs->npg;
if (npg == hrecs->pg_sz) {
size_t new_sz = hrecs->pg_sz >= 4 ? hrecs->pg_sz + hrecs->pg_sz / 4 : 4;
new_pg = realloc(hrecs->pg, sizeof(*hrecs->pg) * new_sz);
if (!new_pg)
return -1;
hrecs->pg = new_pg;
hrecs->pg_sz = new_sz;
}
tag = h_type->tag;
hrecs->pg[npg].name = NULL;
hrecs->pg[npg].name_len = 0;
hrecs->pg[npg].ty = h_type;
hrecs->pg[npg].id = npg;
hrecs->pg[npg].prev_id = -1;
while (tag) {
if (tag->str[0] == 'I' && tag->str[1] == 'D') {
/* Avoid duplicate ID tags coming from other applications */
if (!hrecs->pg[npg].name) {
assert(tag->len >= 3);
hrecs->pg[npg].name = tag->str + 3;
hrecs->pg[npg].name_len = tag->len - 3;
} else {
hts_log_warning("PG line with multiple ID tags. The first encountered was preferred - ID:%s", hrecs->pg[npg].name);
}
} else if (tag->str[0] == 'P' && tag->str[1] == 'P') {
// Resolve later if needed
khint_t k;
k = kh_get(m_s2i, hrecs->pg_hash, tag->str+3);
if (k != kh_end(hrecs->pg_hash)) {
int p_id = kh_val(hrecs->pg_hash, k);
hrecs->pg[npg].prev_id = hrecs->pg[p_id].id;
/* Unmark previous entry as a PG termination */
if (hrecs->npg_end > 0 &&
hrecs->pg_end[hrecs->npg_end-1] == p_id) {
hrecs->npg_end--;
} else {
int i;
for (i = 0; i < hrecs->npg_end; i++) {
if (hrecs->pg_end[i] == p_id) {
memmove(&hrecs->pg_end[i], &hrecs->pg_end[i+1],
(hrecs->npg_end-i-1)*sizeof(*hrecs->pg_end));
hrecs->npg_end--;
}
}
}
} else {
hrecs->pg[npg].prev_id = -1;
}
}
tag = tag->next;
}
if (hrecs->pg[npg].name) {
khint_t k;
int r;
k = kh_put(m_s2i, hrecs->pg_hash, hrecs->pg[npg].name, &r);
if (-1 == r) return -1;
kh_val(hrecs->pg_hash, k) = npg;
} else {
return -1; // ID should be present, according to spec.
}
/* Add to npg_end[] array. Remove later if we find a PP line */
if (hrecs->npg_end >= hrecs->npg_end_alloc) {
int *new_pg_end;
int new_alloc = hrecs->npg_end_alloc ? hrecs->npg_end_alloc*2 : 4;
new_pg_end = realloc(hrecs->pg_end, new_alloc * sizeof(int));
if (!new_pg_end)
return -1;
hrecs->npg_end_alloc = new_alloc;
hrecs->pg_end = new_pg_end;
}
hrecs->pg_end[hrecs->npg_end++] = npg;
hrecs->npg++;
}
return 0;
}
static int sam_hrecs_remove_hash_entry(sam_hrecs_t *hrecs, khint32_t type, sam_hrec_type_t *h_type) {
if (!hrecs || !h_type)
return -1;
sam_hrec_tag_t *tag;
const char *key = NULL;
khint_t k;
/* Remove name and any alternative names from reference hash */
if (type == TYPEKEY("SQ")) {
const char *altnames = NULL;
tag = h_type->tag;
while (tag) {
if (tag->str[0] == 'S' && tag->str[1] == 'N') {
assert(tag->len >= 3);
key = tag->str + 3;
} else if (tag->str[0] == 'A' && tag->str[1] == 'N') {
assert(tag->len >= 3);
altnames = tag->str + 3;
}
tag = tag->next;
}
if (key) {
k = kh_get(m_s2i, hrecs->ref_hash, key);
if (k != kh_end(hrecs->ref_hash)) {
int idx = kh_val(hrecs->ref_hash, k);
if (idx + 1 < hrecs->nref)
memmove(&hrecs->ref[idx], &hrecs->ref[idx+1],
sizeof(sam_hrec_sq_t)*(hrecs->nref - idx - 1));
if (altnames)
sam_hrecs_remove_ref_altnames(hrecs, idx, altnames);
kh_del(m_s2i, hrecs->ref_hash, k);
hrecs->nref--;
if (hrecs->refs_changed < 0 || hrecs->refs_changed > idx)
hrecs->refs_changed = idx;
for (k = 0; k < kh_end(hrecs->ref_hash); k++) {
if (kh_exist(hrecs->ref_hash, k)
&& kh_value(hrecs->ref_hash, k) > idx) {
kh_value(hrecs->ref_hash, k)--;
}
}
}
}
}
/* Remove from read-group hash */
if (type == TYPEKEY("RG")) {
tag = h_type->tag;
while (tag) {
if (tag->str[0] == 'I' && tag->str[1] == 'D') {
assert(tag->len >= 3);
key = tag->str + 3;
k = kh_get(m_s2i, hrecs->rg_hash, key);
if (k != kh_end(hrecs->rg_hash)) {
int idx = kh_val(hrecs->rg_hash, k);
if (idx + 1 < hrecs->nrg)
memmove(&hrecs->rg[idx], &hrecs->rg[idx+1], sizeof(sam_hrec_rg_t)*(hrecs->nrg - idx - 1));
kh_del(m_s2i, hrecs->rg_hash, k);
hrecs->nrg--;
for (k = 0; k < kh_end(hrecs->rg_hash); k++) {
if (kh_exist(hrecs->rg_hash, k)
&& kh_value(hrecs->rg_hash, k) > idx) {
kh_value(hrecs->rg_hash, k)--;
}
}
}
break;
}
tag = tag->next;
}
}
return 0;
}
/** Add a header record to the global line ordering
*
* If @p after is not NULL, the new record will be inserted after this one,
* otherwise it will go at the end.
*
* An exception is an HD record, which will always be put first unless
* one is already present.
*/
static void sam_hrecs_global_list_add(sam_hrecs_t *hrecs,
sam_hrec_type_t *h_type,
sam_hrec_type_t *after) {
const khint32_t hd_type = TYPEKEY("HD");
int update_first_line = 0;
// First line seen
if (!hrecs->first_line) {
hrecs->first_line = h_type->global_next = h_type->global_prev = h_type;
return;
}
// @HD goes at the top (unless there's one already)
if (h_type->type == hd_type && hrecs->first_line->type != hd_type) {
after = hrecs->first_line->global_prev;
update_first_line = 1;
}
// If no instructions given, put it at the end
if (!after)
after = hrecs->first_line->global_prev;
h_type->global_prev = after;
h_type->global_next = after->global_next;
h_type->global_prev->global_next = h_type;
h_type->global_next->global_prev = h_type;
if (update_first_line)
hrecs->first_line = h_type;
}
/*! Add header record with a va_list interface.
*
* Adds a single record to a SAM header.
*
* This takes a header record type, a va_list argument and one or more
* key,value pairs, ending with the NULL key.
*
* Eg. sam_hrecs_vadd(h, "SQ", args, "ID", "foo", "LN", "100", NULL).
*
* The purpose of the additional va_list parameter is to permit other
* varargs functions to call this while including their own additional
* parameters; an example is in sam_hdr_add_pg().
*
* Note: this function invokes va_arg at least once, making the value
* of ap indeterminate after the return. The caller should call
* va_start/va_end before/after calling this function or use va_copy.
*
* @return
* Returns >= 0 on success;
* -1 on failure
*/
static int sam_hrecs_vadd(sam_hrecs_t *hrecs, const char *type, va_list ap, ...) {
va_list args;
sam_hrec_type_t *h_type;
sam_hrec_tag_t *h_tag, *last=NULL;
int new;
khint32_t type_i = TYPEKEY(type), k;
if (!strncmp(type, "HD", 2) && (h_type = sam_hrecs_find_type_id(hrecs, "HD", NULL, NULL)))
return sam_hrecs_vupdate(hrecs, h_type, ap);
if (!(h_type = pool_alloc(hrecs->type_pool)))
return -1;
k = kh_put(sam_hrecs_t, hrecs->h, type_i, &new);
if (new < 0)
return -1;
h_type->type = type_i;
// Form the ring, either with self or other lines of this type
if (!new) {
sam_hrec_type_t *t = kh_val(hrecs->h, k), *p;
p = t->prev;
assert(p->next == t);
p->next = h_type;
h_type->prev = p;
t->prev = h_type;
h_type->next = t;
} else {
kh_val(hrecs->h, k) = h_type;
h_type->prev = h_type->next = h_type;
}
h_type->tag = NULL;
// Add to global line ordering after any existing line of the same type,
// or at the end if no line of this type exists yet.
sam_hrecs_global_list_add(hrecs, h_type, !new ? h_type->prev : NULL);
// Check linked-list invariants
assert(h_type->prev->next == h_type);
assert(h_type->next->prev == h_type);
assert(h_type->global_prev->global_next == h_type);
assert(h_type->global_next->global_prev == h_type);
// Any ... varargs
va_start(args, ap);
for (;;) {
char *key, *val = NULL, *str;
if (!(key = (char *)va_arg(args, char *)))
break;
if (strncmp(type, "CO", 2) && !(val = (char *)va_arg(args, char *)))
break;
if (*val == '\0')
continue;
if (!(h_tag = pool_alloc(hrecs->tag_pool)))
return -1;
if (strncmp(type, "CO", 2)) {
h_tag->len = 3 + strlen(val);
str = string_alloc(hrecs->str_pool, h_tag->len+1);
if (!str || snprintf(str, h_tag->len+1, "%2.2s:%s", key, val) < 0)
return -1;
h_tag->str = str;
} else {
h_tag->len = strlen(key);
h_tag->str = string_ndup(hrecs->str_pool, key, h_tag->len);
if (!h_tag->str)
return -1;
}
h_tag->next = NULL;
if (last)
last->next = h_tag;
else
h_type->tag = h_tag;
last = h_tag;
}
va_end(args);
// Plus the specified va_list params
for (;;) {
char *key, *val = NULL, *str;
if (!(key = (char *)va_arg(ap, char *)))
break;
if (strncmp(type, "CO", 2) && !(val = (char *)va_arg(ap, char *)))
break;
if (!(h_tag = pool_alloc(hrecs->tag_pool)))
return -1;
if (strncmp(type, "CO", 2)) {
h_tag->len = 3 + strlen(val);
str = string_alloc(hrecs->str_pool, h_tag->len+1);
if (!str || snprintf(str, h_tag->len+1, "%2.2s:%s", key, val) < 0)
return -1;
h_tag->str = str;
} else {
h_tag->len = strlen(key);
h_tag->str = string_ndup(hrecs->str_pool, key, h_tag->len);
if (!h_tag->str)
return -1;
}
h_tag->next = NULL;
if (last)
last->next = h_tag;
else
h_type->tag = h_tag;
last = h_tag;
}
if (-1 == sam_hrecs_update_hashes(hrecs, TYPEKEY(type), h_type))
return -1;
if (!strncmp(type, "PG", 2))
hrecs->pgs_changed = 1;
hrecs->dirty = 1;
return 0;
}
// As sam_hrecs_vadd(), but without the extra va_list parameter
static int sam_hrecs_add(sam_hrecs_t *hrecs, const char *type, ...) {
va_list args;
int res;
va_start(args, type);
res = sam_hrecs_vadd(hrecs, type, args, NULL);
va_end(args);
return res;
}
/*
* Function for deallocating a list of tags
*/
static void sam_hrecs_free_tags(sam_hrecs_t *hrecs, sam_hrec_tag_t *tag) {
if (!hrecs || !tag)
return;
if (tag->next)
sam_hrecs_free_tags(hrecs, tag->next);
pool_free(hrecs->tag_pool, tag);
}
static int sam_hrecs_remove_line(sam_hrecs_t *hrecs, const char *type_name, sam_hrec_type_t *type_found, int remove_hash) {
if (!hrecs || !type_name || !type_found)
return -1;
khint32_t itype = TYPEKEY(type_name);
khint_t k = kh_get(sam_hrecs_t, hrecs->h, itype);
if (k == kh_end(hrecs->h))
return -1;
// Remove from global list (remembering it could be the only line)
if (hrecs->first_line == type_found) {
hrecs->first_line = (type_found->global_next != type_found
? type_found->global_next : NULL);
}
type_found->global_next->global_prev = type_found->global_prev;
type_found->global_prev->global_next = type_found->global_next;
/* single element in the list */
if (type_found->prev == type_found || type_found->next == type_found) {
kh_del(sam_hrecs_t, hrecs->h, k);
} else {
type_found->prev->next = type_found->next;
type_found->next->prev = type_found->prev;
if (kh_val(hrecs->h, k) == type_found) { //first element
kh_val(hrecs->h, k) = type_found->next;
}
}
if (remove_hash && (!strncmp(type_name, "SQ", 2) || !strncmp(type_name, "RG", 2)))
sam_hrecs_remove_hash_entry(hrecs, itype, type_found);
sam_hrecs_free_tags(hrecs, type_found->tag);
pool_free(hrecs->type_pool, type_found);
hrecs->dirty = 1;
return 0;
}
// Paste together a line from the parsed data structures
static int build_header_line(const sam_hrec_type_t *ty, kstring_t *ks) {
sam_hrec_tag_t *tag;
int r = 0;
char c[2]= { ty->type >> 8, ty->type & 0xff };
r |= (kputc_('@', ks) == EOF);
r |= (kputsn(c, 2, ks) == EOF);
for (tag = ty->tag; tag; tag = tag->next) {
r |= (kputc_('\t', ks) == EOF);
r |= (kputsn(tag->str, tag->len, ks) == EOF);
}
return r;
}
static int sam_hrecs_rebuild_lines(const sam_hrecs_t *hrecs, kstring_t *ks) {
const sam_hrec_type_t *t1, *t2;
if (!hrecs->first_line)
return kputsn("", 0, ks) >= 0 ? 0 : -1;
t1 = t2 = hrecs->first_line;
do {
if (build_header_line(t1, ks) != 0)
return -1;
if (kputc('\n', ks) < 0)
return -1;
t1 = t1->global_next;
} while (t1 != t2);
return 0;
}
static int sam_hrecs_parse_lines(sam_hrecs_t *hrecs, const char *hdr, size_t len) {
size_t i, lno;
if (!hrecs || len > SSIZE_MAX)
return -1;
if (!len)
len = strlen(hdr);
if (len < 3) {
if (len == 0 || *hdr == '\0') return 0;
sam_hrecs_error("Header line too short", hdr, len, 1);
return -1;
}
for (i = 0, lno = 1; i < len - 3 && hdr[i] != '\0'; i++, lno++) {
khint32_t type;
khint_t k;
int l_start = i, new;
sam_hrec_type_t *h_type;
sam_hrec_tag_t *h_tag, *last;
if (hdr[i] != '@') {
sam_hrecs_error("Header line does not start with '@'",
&hdr[l_start], len - l_start, lno);
return -1;
}
if (!isalpha_c(hdr[i+1]) || !isalpha_c(hdr[i+2])) {
sam_hrecs_error("Header line does not have a two character key",
&hdr[l_start], len - l_start, lno);
return -1;
}
type = TYPEKEY(&hdr[i+1]);
i += 3;
if (i == len || hdr[i] == '\n')
continue;
// Add the header line type
if (!(h_type = pool_alloc(hrecs->type_pool)))
return -1;
k = kh_put(sam_hrecs_t, hrecs->h, type, &new);
if (new < 0)
return -1;
h_type->type = type;
// Add to end of global list
sam_hrecs_global_list_add(hrecs, h_type, NULL);
// Form the ring, either with self or other lines of this type
if (!new) {
sam_hrec_type_t *t = kh_val(hrecs->h, k), *p;
p = t->prev;
assert(p->next == t);
p->next = h_type;
h_type->prev = p;
t->prev = h_type;
h_type->next = t;
} else {
kh_val(hrecs->h, k) = h_type;
h_type->prev = h_type->next = h_type;
}
// Parse the tags on this line
last = NULL;
if (type == TYPEKEY("CO")) {
size_t j;
if (i == len || hdr[i] != '\t') {
sam_hrecs_error("Missing tab",
&hdr[l_start], len - l_start, lno);
return -1;
}
for (j = ++i; j < len && hdr[j] != '\0' && hdr[j] != '\n'; j++)
;
if (!(h_type->tag = h_tag = pool_alloc(hrecs->tag_pool)))
return -1;
h_tag->str = string_ndup(hrecs->str_pool, &hdr[i], j-i);
h_tag->len = j-i;
h_tag->next = NULL;
if (!h_tag->str)
return -1;
i = j;
} else {
do {
size_t j;
if (i == len || hdr[i] != '\t') {
sam_hrecs_error("Missing tab",
&hdr[l_start], len - l_start, lno);
return -1;
}
for (j = ++i; j < len && hdr[j] != '\0' && hdr[j] != '\n' && hdr[j] != '\t'; j++)
;
if (j - i < 3 || hdr[i + 2] != ':') {
sam_hrecs_error("Malformed key:value pair",
&hdr[l_start], len - l_start, lno);
return -1;
}
if (!(h_tag = pool_alloc(hrecs->tag_pool)))
return -1;
h_tag->str = string_ndup(hrecs->str_pool, &hdr[i], j-i);
h_tag->len = j-i;
h_tag->next = NULL;
if (!h_tag->str)
return -1;
if (last)
last->next = h_tag;
else
h_type->tag = h_tag;
last = h_tag;
i = j;
} while (i < len && hdr[i] != '\0' && hdr[i] != '\n');
}
/* Update RG/SQ hashes */
if (-1 == sam_hrecs_update_hashes(hrecs, type, h_type))
return -1;
}
return 0;
}
/*! Update sam_hdr_t target_name and target_len arrays
*
* @return 0 on success; -1 on failure
*/
int sam_hdr_update_target_arrays(sam_hdr_t *bh, const sam_hrecs_t *hrecs,
int refs_changed) {
if (!bh || !hrecs)
return -1;
if (refs_changed < 0)
return 0;
// Grow arrays if necessary
if (bh->n_targets < hrecs->nref) {
char **new_names = realloc(bh->target_name,
hrecs->nref * sizeof(*new_names));
if (!new_names)
return -1;
bh->target_name = new_names;
uint32_t *new_lens = realloc(bh->target_len,
hrecs->nref * sizeof(*new_lens));
if (!new_lens)
return -1;
bh->target_len = new_lens;
}
// Update names and lengths where changed
// hrecs->refs_changed is the first ref that has been updated, so ones
// before that can be skipped.
int i;
khint_t k;
khash_t(s2i) *long_refs = (khash_t(s2i) *) bh->sdict;
for (i = refs_changed; i < hrecs->nref; i++) {
if (i >= bh->n_targets
|| strcmp(bh->target_name[i], hrecs->ref[i].name) != 0) {
if (i < bh->n_targets)
free(bh->target_name[i]);
bh->target_name[i] = strdup(hrecs->ref[i].name);
if (!bh->target_name[i])
return -1;
}
if (hrecs->ref[i].len < UINT32_MAX) {
bh->target_len[i] = hrecs->ref[i].len;
if (!long_refs)
continue;
// Check if we have an old length, if so remove it.
k = kh_get(s2i, long_refs, bh->target_name[i]);
if (k < kh_end(long_refs))
kh_del(s2i, long_refs, k);
} else {
bh->target_len[i] = UINT32_MAX;
if (bh->hrecs != hrecs) {
// Called from sam_hdr_dup; need to add sdict entries
if (!long_refs) {
if (!(bh->sdict = long_refs = kh_init(s2i)))
return -1;
}
// Add / update length
int absent;
k = kh_put(s2i, long_refs, bh->target_name[i], &absent);
if (absent < 0)
return -1;
kh_val(long_refs, k) = hrecs->ref[i].len;
}
}
}
// Free up any names that have been removed
for (; i < bh->n_targets; i++) {
if (long_refs) {
k = kh_get(s2i, long_refs, bh->target_name[i]);
if (k < kh_end(long_refs))
kh_del(s2i, long_refs, k);
}
free(bh->target_name[i]);
}
bh->n_targets = hrecs->nref;
return 0;
}
static int rebuild_target_arrays(sam_hdr_t *bh) {
if (!bh || !bh->hrecs)
return -1;
sam_hrecs_t *hrecs = bh->hrecs;
if (hrecs->refs_changed < 0)
return 0;
if (sam_hdr_update_target_arrays(bh, hrecs, hrecs->refs_changed) != 0)
return -1;
hrecs->refs_changed = -1;
return 0;
}
/// Populate hrecs refs array from header target_name, target_len arrays