#!/usr/bin/python

import sys, os
sys.path.append('/Library/Python/2.6/site-packages/')
from bin import read, proc, analysis, gui, locate, parsers

import numpy as np

if __name__ == '__main__':
    parser = parsers.get_damage_quant_parser()

    args = parser.parse_args()

    """ READ DATA """
    sys.stdout.write('reading pre...\n')
    preinfo, prestack = read.get_data(args.pre, args.z_thickness, 
                                      args.channel)
    sys.stdout.write('reading post...\n')
    postinfo, postack = read.get_data(args.post, args.z_thickness, 
                                      args.channel)

    """ PROCESS """
    avgmpp = (postinfo['ympp'] + postinfo['xmpp']) / 2
    probesize = (int(np.ceil(args.probesize[0] / avgmpp)), 
                 int(np.ceil(args.probesize[1] / avgmpp)))

    """ ELICIT INPUT """
    sys.stdout.write('making gui...\n')
    locs, rots = gui.make_damage_gui(postack, probesize)

    """ CROSS LOCATE """
    maxloc = locate.nccfft(postack.mean(0), prestack.mean(0), args.room)

    offset = (np.array((maxloc[0][0], maxloc[1][0])) 
              - np.array(postack[0].shape) / args.room)

    offset = gui.make_locate_gui(prestack, postack, offset)

    sys.stdout.write('offset: '+str(offset)+'\n')

    prelocs = locs + offset

    if (prelocs.min() < 0 
        or prelocs[:, 0].max() > prestack.shape[1] 
        or prelocs[:, 1].max() > prestack.shape[2]):
        sys.stderr.write('RuntimeError: Match to pre-data has one or more '
                         'probe locations out of bounds\n')
        sys.exit(1)

    """ ANALYZE """
    precount, prelines, masks = analysis.damage_profiles(prestack, prelocs, 
                                                         rots, probesize,
                                                         args)
    
    postcount, postlines, masks = analysis.damage_profiles(postack, locs, 
                                                           rots, probesize,
                                                           args)
    """ PRINT """
    print precount
    print postcount
    analysis.print_damage_stats((args.pre, precount), (args.post, postcount), 
                                masks)
    sys.exit(0)
