#!/usr/bin/env python3

import argparse
import sys

import nibabel
import numpy

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("inputs", metavar="input", nargs="+")
    parser.add_argument("output")
    arguments = parser.parse_args()

    image = nibabel.load(arguments.inputs[0])
    shape, affine = image.shape, image.affine
    merged = numpy.zeros(shape)

    for path in arguments.inputs:
        image = nibabel.load(path)
        if image.shape != merged.shape:
            parser.error("Image shapes mismatch")
        if not numpy.allclose(image.affine, affine):
            parser.error("Image transforms mismatch")
        merged += image.get_fdata()
        del image

    nibabel.save(nibabel.Nifti1Image(merged, affine), arguments.output)

if __name__ == "__main__":
    sys.exit(main())
