+ samfile_t *in = 0, *out = 0;
+ faidx_t *fai;
+ int c, is_bamin = 1, compress_level = -1, is_bamout = 1, is_long_help = 0;
+ char in_mode[5], out_mode[5], *fn_out = 0, *fn_list = 0, *fn_ref = 0;
+ int ret=0;
+
+ /* parse command-line options */
+ strcpy(in_mode, "r"); strcpy(out_mode, "w");
+ while ((c = getopt(argc, argv, "Sso:u1T:?")) >= 0) {
+ switch (c) {
+ case 'S': is_bamin = 0; break;
+ case 's': assert(compress_level == -1); is_bamout = 0; break;
+ case 'o': fn_out = strdup(optarg); break;
+ case 'u': assert(is_bamout == 1); compress_level = 0; break;
+ case '1': assert(is_bamout == 1); compress_level = 1; break;
+ case 'T': fn_ref = strdup(optarg); is_bamin = 0; break;
+ case '?': is_long_help = 1; break;
+ default: return usage(is_long_help);
+ }
+ }
+ if (argc == optind) return usage(is_long_help);
+
+ if (is_bamin) strcat(in_mode, "b");
+ if (is_bamout) strcat(out_mode, "b");
+ strcat(out_mode, "h");
+ if (compress_level >= 0) {
+ char tmp[2];
+ tmp[0] = compress_level + '0'; tmp[1] = '\0';
+ strcat(out_mode, tmp);
+ }
+
+ // Load FASTA reference (also needed for SAM -> BAM if missing header)
+ if (fn_ref) {
+ fn_list = samfaipath(fn_ref);
+ fai = fai_load(fn_ref);
+ }
+ // open file handlers
+ if ((in = samopen(argv[optind], in_mode, fn_list)) == 0) {
+ fprintf(stderr, "[depad] fail to open \"%s\" for reading.\n", argv[optind]);
+ ret = 1;
+ goto depad_end;
+ }
+ if (in->header == 0) {
+ fprintf(stderr, "[depad] fail to read the header from \"%s\".\n", argv[optind]);
+ ret = 1;
+ goto depad_end;
+ }
+ /* TODO - The reference sequence lengths in the BAM + SAM headers should be updated */
+ if ((out = samopen(fn_out? fn_out : "-", out_mode, in->header)) == 0) {
+ fprintf(stderr, "[depad] fail to open \"%s\" for writing.\n", fn_out? fn_out : "standard output");
+ ret = 1;
+ goto depad_end;