dofB = len(open("%s/../copesB.txt" %(input_directory),"r").readlines())-2
except: 
    dofB = 44

for groupB in groupB_maps:
    mrB = nib.load(groupB)
    mrB = IT.t_to_z(mrB,dofB)    
    contrast_task_B = os.path.basename(groupB).replace("_groupB_tstat1.nii.gz","")
    for thresh in thresholds:
	    print "Processing threshold %s" %(thresh)
	    for absolute_value in ["pos","posneg"]:
		if absolute_value == "posneg": 
		    # Group A is always unthresholded, B is thresholded
		    mrthresh = IT.threshold_abs(mrB,thresholds=[thresh])[thresh]
		else: 
		    mrthresh = IT.threshold_pos(mrB,thresholds=[thresh])[thresh]
                ids.append(contrast_task_B)
                thresh_id.append(thresh)
		# 3/12/2015: confirmed that first returns +/- values, second returns only positive  
		# If the image is empty thresholded, we append NaN
		if len(np.unique(mrthresh.get_data()))==1:
		    cca_pearson.append(np.nan)
		    svi_pearson.append(np.nan)
		    cca_spearman.append(np.nan)
		    svi_spearman.append(np.nan)
		    sizes.loc[idx] = [0,0]
		    nanlog_cca.append("nan_mrthresh_empty")
		    nanlog_svi.append("nan_mrthresh_empty")
		    size_ids.append("%s_%s" %(thresh,absolute_value))
		else:
		    # Generate a union (svi) and intersection (cca) mask
max = 0
min = 0
for input_map in input_maps:
    img = nibabel.load(input_map)
    img = IT.t_to_z(img, 46).get_data()
    if img.max() > max:
        max = img.max()
    if img.min() < min:
        min = img.min()


for i in range(0, len(input_maps)):
    print "Processing %s of %s" % (i, len(input_maps))
    input_map = input_maps[i]
    mapname = os.path.basename(input_map).replace("_groupA_tstat1.nii.gz", "")
    task = lookup.task[lookup.id == mapname].tolist()[0]
    contrast = lookup.contrasts[lookup.id == mapname].tolist()[0]
    title = "%s_%s" % (task, contrast)
    image = nibabel.load(input_map)
    Z = IT.t_to_z(image, 46)
    for thresh in range(0, 10):
        print thresh
        pos = IT.threshold_pos(image, thresholds=[thresh])[thresh]
        posneg = IT.threshold_abs(image, thresholds=[thresh])[thresh]
        fig = plot_stat_map(pos, vmax=max, title="%s Positive Only" % title, cut_coords=(0, 0, 0))
        fig.savefig("%s/%s_%s_pos.png" % (outdir, thresh, mapname))
        fig.close()
        fig = plot_stat_map(posneg, vmax=max, title="%s Positive and Negative" % title, cut_coords=(0, 0, 0))
        fig.savefig("%s/%s_%s_posneg.png" % (outdir, thresh, mapname))
        fig.close()