#! /usr/bin/env python
"""
pkz-subtract [OPTIONS] OUTFILE.pkz FILE-A.pkz FILE-B.pkz

Computes OUTFILE.pkz = FILE-A.pkz - FILE-B.pkz
"""

import os, pnt, sys, optparse, pickle, gzip, unbuffer
import numpy as np
from error import Error

unbuffer.stdout()

def main():
    parser = optparse.OptionParser(__doc__)
    parser.add_option("-q", '--quiet',
                      help='supress normal progress message(s)',
                      dest='quiet', default=False, action='store_true')

    (opts, args) = parser.parse_args()

    if len(args) < 3:
        parser.print_help()
        sys.exit(0)

    outfile = args[0]
    file_a_name = args[1]
    file_b_name = args[2]

    if not os.path.isfile(file_a_name):
        raise Error("File not found: %s" % file_a_name)
    if not os.path.isfile(file_b_name):
        raise Error("File not found: %s" % file_b_name)

    if not opts.quiet: print "loading %s ..." % file_a_name,
    file_a = pnt.PntGrid.load_pkzfile( file_a_name )
    if not opts.quiet: print "loading %s ..." % file_b_name,
    file_b = pnt.PntGrid.load_pkzfile( file_b_name )
    if not opts.quiet: print "subtracting ...",
    g = pnt.PntGrid.subtract(file_a, file_b)
    with gzip.open(outfile, "wb") as f:
        pickle.dump(g, f)
    if not opts.quiet: print "wrote %s." % outfile

if __name__ == "__main__":
    try:
        main()
    except Error as e:
        print "Error: %s" % e.message
