fbc3c816cdff6d474ca3d880b214c9d0007791e4
ceisenhart
  Mon May 26 13:20:06 2014 -0700
Merges multiple bam files into a single bam file, for testing bamSplitByChrom
diff --git src/utils/bamMerge/bamMerge.c src/utils/bamMerge/bamMerge.c
new file mode 100644
index 0000000..622bc7c
--- /dev/null
+++ src/utils/bamMerge/bamMerge.c
@@ -0,0 +1,76 @@
+/* bamMerge -  Merges multiple bam files into a single bam file . */
+/* The header data for the output comes from the first bam file. */
+#include "common.h"
+#include "linefile.h"
+#include "hash.h"
+#include "options.h"
+#include "bamFile.h"
+
+void usage()
+/* Explain usage and exit. */
+{
+errAbort(
+  "bamMerge -  Merges multiple bam files into a single bam file \n"
+  "usage:\n"
+  "   bamMerge input1.bam input2.bam ... inputn.bam\n"
+  "options:\n"
+  "   \n"
+  );
+}
+
+/* Command line validation table. */
+static struct optionSpec options[] = {
+   {NULL, 0},
+};
+
+samfile_t *samMustOpen(char *fileName, char *mode, void *extraHeader)
+/* Open up samfile or die trying. */
+{
+samfile_t *sf = samopen(fileName, mode, extraHeader);
+if (sf == NULL)
+    errnoAbort("Couldn't open %s.\n", fileName);
+return sf;
+}
+
+void bamMerge(char *fileNames[], int files)
+/* bamMerge -  Merges multiple bam files into a single bam file . */
+{
+samfile_t *chromHead =samMustOpen(fileNames[1], "rb", NULL);
+char *outBam = "merged.bam";
+bam_header_t *head = chromHead->header;
+samfile_t *out = bamMustOpenLocal(outBam, "wb", head);
+samclose(chromHead);
+/* Opens the output and sets the header to be the same as the first input. */
+int i;
+for (i = 1; i<files; ++i)
+/* Loop through all input files */
+    {
+    samfile_t *in = samMustOpen(fileNames[i], "rb", NULL);
+    bam1_t one;
+    ZeroVar(&one);	// This seems to be necessary!
+    /* Open an input file */
+    for (;;)
+        {
+        if (samread(in, &one) < 0)
+            {
+	    break;
+	    }
+        samwrite(out, &one);
+        /* Copy the input to the output */
+	}
+    samclose(in);
+    }
+samclose(out);
+}
+
+
+int main(int argc, char *argv[])
+/* Process command line. */
+{
+optionInit(&argc, argv, options);
+if (argc < 2)
+    usage();   
+bamMerge(argv,argc);
+return 0;
+
+}