#include <getopt.h>
#include <unistd.h>
#include <htslib/sam.h>
static void print_usage(FILE *fp)
{
fprintf(fp, "Usage: read_header infile header [id val] [tag]\n\
This shows given tag from given header or the whole line\n");
return;
}
int main(int argc, char *argv[])
{
const char *inname = NULL, *header = NULL, *tag = NULL, *idval = NULL;
char *id = NULL;
int c = 0, ret = EXIT_FAILURE, linecnt = 0;
samFile *infile = NULL;
sam_hdr_t *in_samhdr = NULL;
kstring_t data = KS_INITIALIZE;
if (argc < 3 || argc > 6) {
print_usage(stderr);
goto end;
}
inname = argv[1];
header = argv[2];
if (argc == 4) { tag = argv[3];
if (header[0] == 'H' && header[1] == 'D') {
id = NULL;
}
else if (header[0] == 'S' && header[1] == 'Q') {
id = "SN";
}
else if (header[0] == 'R' && header[1] == 'G') {
id = "ID";
}
else if (header[0] == 'P' && header[1] == 'G') {
id = "ID";
}
else if (header[0] == 'C' && header[1] == 'O') {
id = "";
}
else {
printf("Invalid header type\n");
goto end;
}
}
else if (argc == 5) { id = argv[3];
idval = argv[4];
}
else if (argc == 6) { id = argv[3];
idval = argv[4];
tag = argv[5];
}
if (!(infile = sam_open(inname, "r"))) {
printf("Could not open %s\n", inname);
goto end;
}
if (!(in_samhdr = sam_hdr_read(infile))) {
printf("Failed to read header from file!\n");
goto end;
}
if (id && idval) {
if (tag) {
ret = sam_hdr_find_tag_id(in_samhdr, header, id, idval, tag, &data);
}
else {
ret = sam_hdr_find_line_id(in_samhdr, header, id, idval, &data);
}
if (ret == 0) {
printf("%s\n", data.s);
}
else if (ret == -1) {
printf("No matching tag found\n");
goto end;
}
else {
printf("Failed to find header line\n");
goto end;
}
}
else {
linecnt = sam_hdr_count_lines(in_samhdr, header);
if (linecnt == 0) {
printf("No matching line found\n");
goto end;
}
for (c = 0; c < linecnt; ++c ) {
if (tag) {
ret = sam_hdr_find_tag_pos(in_samhdr, header, c, tag, &data);
}
else {
ret = sam_hdr_find_line_pos(in_samhdr, header, c, &data);
}
if (ret == 0) {
printf("%s\n", data.s);
continue;
}
else if (ret == -1) {
printf("Tag not present\n");
continue;
}
else {
printf("Failed to get tag\n");
goto end;
}
}
}
ret = EXIT_SUCCESS;
end:
if (in_samhdr) {
sam_hdr_destroy(in_samhdr);
}
if (infile) {
sam_close(infile);
}
ks_free(&data);
return ret;
}