#!/usr/bin/env python
import glob
import hashlib
import os
import sys
import tempfile
import tarfile
import subprocess
import shutil

VOL_DIRS = ['mri', 'mri/orig', 'mri/tranforms']
SURFACE_DIRS = ['surf']
VOLUMES = ['rawavg.mgz',
           'orig.mgz',
           'nu.mgz',
           'T1.mgz',
           'brainmask.mgz']
APARCS = ['aparc.a2009s', 'aparc']
STATS_FILES = ['aseg.stats']


def run_command(command):
    """
    Run a command and return results
    :param command: command to run
    :return: a tuple (signal, exit code)
    """
    dev_null = open(os.devnull, 'w')
    retval = subprocess.call(command, stdout=dev_null, stderr=dev_null, shell=True)
    return get_exitcode(retval)


def get_exitcode(return_code):
    """
    Calculate and return exit code from a return code

    :param return_code: code in os.wait format
    :return: a tuple (signal, exit code)
    """

    signal = return_code & 0x00FF
    exitcode = (return_code & 0xFF00) >> 8
    return signal, exitcode


def compare_volumes(subject1_dir, subject2_dir):
    """
    Compare the volumes generated by Freesurfer for two inputs and
    indicate whether they are the same or different

    :param subject1_dir: path to files for first subject
    :param subject2_dir: path to files for second subject
    :return: True if files have different volumes, False otherwise
    """
    differences = False
    sys.stdout.write("Comparing volumes\n")
    subj1_files = os.listdir(subject1_dir)
    subj2_files = os.listdir(subject2_dir)
    if len(subj1_files) != len(subj2_files):
        sys.stdout.write("Number of files in " +
                         "{0} ".format(subject1_dir) +
                         "and {0} differ\n".format(subject2_dir))
    for volume in VOLUMES:
            sys.stdout.write("Comparing volume {0}... ".format(volume))
            volume_1 = os.path.join(subject1_dir,
                                    "mri",
                                    "{0}".format(volume))
            volume_2 = os.path.join(subject2_dir,
                                    "mri",
                                    "{0}".format(volume))
            cmd = "mri_diff --thresh 0 "
            cmd += "{0} {1}".format(volume_1, volume_2)
            signal, exit_code = run_command(cmd)
            if signal != 0:
                differences = True
                sys.stdout.write("Signal {0} occurred\n".format(signal))
            if exit_code != 0:
                differences = True
            if exit_code == 0:
                sys.stdout.write("OK\n")
            elif exit_code == 1:
                sys.stdout.write("An error occurred\n")
            elif exit_code == 101:
                sys.stdout.write("Files differ in dimension\n")
            elif exit_code == 102:
                sys.stdout.write("Files differ in resolution\n")
            elif exit_code == 103:
                sys.stdout.write("Files differ in acquisition parameters\n")
            elif exit_code == 104:
                sys.stdout.write("Files differ in geometry\n")
            elif exit_code == 105:
                sys.stdout.write("Files differ in precision\n")
            elif exit_code == 106:
                sys.stdout.write("Files differ in pixel data\n")
            elif exit_code == 107:
                sys.stdout.write("Files differ in orientation\n")
            else:
                differences = True
                sys.stdout.write("Files differ, "
                                 "exit code: {0}\n".format(exit_code))
    sys.stdout.write("Comparing seg overlap... ")
    return differences


def main(work_dir):
    """
    Compare two MRI results and list any differences

    :param work_dir:  directory to use as a working directory
    :return: exit code (0 on success, 1 on failure)
    """
    sys.stdout.write("Using {0} as scratch dir\n".format(work_dir))
    input_1 = sys.argv[1]
    input_2 = sys.argv[2]
    sys.stdout.write("Extracting tarballs from {0} and {1}\n".format(input_1,
                                                                     input_2))
    input_1_tarball = tarfile.open(input_1, 'r:*')
    input_2_tarball = tarfile.open(input_2, 'r:*')
    subject1 = input_1_tarball.getmembers()[0].path
    subject2 = input_2_tarball.getmembers()[0].path
    subject1_dir = os.path.join(work_dir, 'input1')
    subject2_dir = os.path.join(work_dir, 'input2')
    input_1_tarball.extractall(subject1_dir)
    input_2_tarball.extractall(subject2_dir)
    input_1_dir = os.path.join(subject1_dir, subject1)
    input_2_dir = os.path.join(subject2_dir, subject2)

    # setup symlinks for parcellation comparisons
    subjects_dir = os.path.join(work_dir, "subjects")
    os.mkdir(subjects_dir)
    os.symlink(input_1_dir, os.path.join(subjects_dir, 'subject1'))
    os.symlink(input_2_dir, os.path.join(subjects_dir, 'subject2'))

    # Do comparisons
    inputs_different = False
    inputs_different |= compare_volumes(input_1_dir, input_2_dir)
    if inputs_different:
        sys.stdout.write("Differences between the two files!")
    else:
        sys.stdout.write("Files check out!")
    return 0

if __name__ == '__main__':
    try:
        scratch_dir = tempfile.mkdtemp()
        sys.exit(main(scratch_dir))
    finally:
        shutil.rmtree(scratch_dir)


@@ -5155,16 +5155,39 @@
 ain__':%0A
+    scratch_dir = None%0A
     try:
@@ -5277,16 +5277,44 @@
 inally:%0A
+        if scratch_dir:%0A    
         
@@ -5340,9 +5340,8 @@
 ch_dir)%0A
-%0A

Make sure var is assigned