def do_preprocessing(contrast):

   # Loop across subjects
    for i in range(0,len(SUBJECTS_LIST)):
        subject = SUBJECTS_LIST[i][0]

        # Should check all inputs before starting the processing of the data

        # Create and go to output folder
        print '\nCreate -if not existing- and go to output folder '+ PATH_OUTPUT + '/subjects/'+subject+'/'+contrast
        if not os.path.isdir(PATH_OUTPUT + '/subjects/'+subject):
            os.makedirs(PATH_OUTPUT + '/subjects/'+subject)
        if not os.path.isdir(PATH_OUTPUT + '/subjects/'+subject+'/'+contrast):
            os.makedirs(PATH_OUTPUT + '/subjects/'+subject+'/'+contrast)
        os.chdir(PATH_OUTPUT + '/subjects/'+subject+'/'+contrast)

        # convert to nii
        print '\nChecking if dicoms have already been imported...'
        list_file = os.listdir(PATH_OUTPUT + '/subjects/'+subject+'/'+contrast)
        if 'data.nii.gz' not in list_file:
            print '\nImporting dicoms and converting to nii...'
            if contrast == 'T1':
                sct.run('dcm2nii -o . -r N ' + SUBJECTS_LIST[i][1] + '/*.dcm')
            if contrast == 'T2':
                sct.run('dcm2nii -o . -r N ' + SUBJECTS_LIST[i][2] + '/*.dcm')

            # change file name
            print '\nChanging file name to data.nii.gz...'
            sct.run('mv *.nii.gz data.nii.gz')

        # Convert to RPI
        # Input:
        # - data.nii.gz
        # - data_RPI.nii.gz
        print '\nConverting to RPI...'
        sct.run('sct_image -i data.nii.gz -setorient RPI')

        # Get info from txt file
        print '\nRecover infos from text file' + PATH_INFO + '/' + contrast + '/' + subject+ '/' + 'crop.txt'
        file_name = 'crop.txt'
        os.chdir(PATH_INFO + '/' + contrast + '/' + subject)

        file_results = open(PATH_INFO + '/' + contrast + '/' +subject+ '/' +file_name, 'r')
        ymin_anatomic = None
        ymax_anatomic = None
        for line in file_results:
            line_list = line.split(',')
            zmin_anatomic = line.split(',')[0]
            zmax_anatomic = line.split(',')[1]
            zmin_seg = line.split(',')[2]
            zmax_seg = line.split(',')[3]
            if len(line_list) == 6:
                ymin_anatomic = line.split(',')[4]
                ymax_anatomic = line.split(',')[5]
        file_results.close()

        os.chdir(PATH_OUTPUT + '/subjects/'+subject+ '/' + contrast)

        # Crop image
        print '\nCropping image at L2-L3 and a little above brainstem...'
        if ymin_anatomic == None and ymax_anatomic == None:
            sct.run('sct_crop_image -i data_RPI.nii.gz -o data_RPI_crop.nii.gz -dim 2 -start ' + zmin_anatomic + ' -end ' + zmax_anatomic )
        else: sct.run('sct_crop_image -i data_RPI.nii.gz -o data_RPI_crop.nii.gz -dim 1,2 -start ' + ymin_anatomic +','+zmin_anatomic+ ' -end ' + ymax_anatomic+','+zmax_anatomic )

        # propseg
        # input:
        # - data_RPI_crop.nii.gz
        # - labels_propseg.nii.gz
        # output:
        # - data_RPI_crop_seg.nii.gz
        print '\nExtracting segmentation...'
        list_dir = os.listdir(PATH_INFO + '/' + contrast + '/'+subject)
        centerline_proseg = False
        for k in range(len(list_dir)):
            if list_dir[k] == 'centerline_propseg_RPI.nii.gz':
                centerline_proseg = True
        if centerline_proseg == True:
            if contrast == 'T1':
                sct.run('sct_propseg -i data_RPI_crop.nii.gz -t t1 -init-centerline ' + PATH_INFO + '/' + contrast + '/' + subject + '/centerline_propseg_RPI.nii.gz')
            if contrast == 'T2':
                sct.run('sct_propseg -i data_RPI_crop.nii.gz -t t2 -init-centerline ' + PATH_INFO + '/' + contrast + '/' + subject + '/centerline_propseg_RPI.nii.gz')
        else:
            if contrast == 'T1':
                sct.run('sct_propseg -i data_RPI_crop.nii.gz -t t1')
            if contrast == 'T2':
                sct.run('sct_propseg -i data_RPI_crop.nii.gz -t t2')

        # Erase 3 top and 3 bottom slices of the segmentation to avoid edge effects  (Done because propseg tends to diverge on edges)
        print '\nErasing 3 top and 3 bottom slices of the segmentation to avoid edge effects of propseg...'
        path_seg, file_seg, ext_seg = sct.extract_fname('data_RPI_crop_seg.nii.gz')
        image_seg = nibabel.load('data_RPI_crop_seg.nii.gz')
        from msct_image import Image
        nx, ny, nz, nt, px, py, pz, pt = Image('data_RPI_crop_seg.nii.gz').dim
        data_seg = image_seg.get_data()
        hdr_seg = image_seg.get_header()
           # List slices that contain non zero values
        z_centerline = [iz for iz in range(0, nz, 1) if data_seg[:,:,iz].any() ]
        for k in range(0,3):
            data_seg[:,:,z_centerline[-1]-k] = 0
            if z_centerline[0]+k < nz:
                data_seg[:,:,z_centerline[0]+k] = 0
        img_seg = nibabel.Nifti1Image(data_seg, None, hdr_seg)
        nibabel.save(img_seg, file_seg + '_mod' + ext_seg)

        # crop segmentation (but keep same dimension)
        # input:
        # - data_crop_denoised_seg_mod.nii.gz
        # - crop.txt
        # output:
        # - data_crop_denoised_seg_mod_crop.nii.gz
        print '\nCropping segmentation...'
        if zmax_seg == 'max':
            nx, ny, nz, nt, px, py, pz, pt = Image('data_RPI_crop_seg.nii.gz').dim
            sct.run('sct_crop_image -i data_RPI_crop_seg_mod.nii.gz -o data_RPI_crop_seg_mod_crop.nii.gz -start ' + zmin_seg + ' -end ' + str(nz) + ' -dim 2 -b 0')
        else:
            sct.run('sct_crop_image -i data_RPI_crop_seg_mod.nii.gz -o data_RPI_crop_seg_mod_crop.nii.gz -start ' + zmin_seg + ' -end ' + zmax_seg + ' -dim 2 -b 0')

        # Concatenate segmentation and labels_updown if labels_updown is inputed. If not, it concatenates the segmentation and centerline_propseg_RPI.
        print '\nConcatenating segmentation and label files...'
        labels_updown = False
        list_file_info = os.listdir(PATH_INFO+ '/' + contrast + '/' + subject)
        for k in range(0,len(list_file_info)):
            if list_file_info[k] == 'labels_updown.nii.gz':
                labels_updown = True
        if centerline_proseg == False and labels_updown == False:
            print '\nERROR: No label file centerline_propseg_RPI.nii.gz or labels_updown.nii.gz in '+PATH_INFO+ '/' + contrast + '/' + subject +'. There must be at least one. Check '+ path_sct+'/dev/template_preprocessing/Readme.md for necessary inputs.'
            sys.exit(2)
        if labels_updown:
            # Creation of centerline from seg and labels for intensity normalization.
            print '\nExtracting centerline for intensity normalization...'
            sct.run('sct_get_centerline -i data_RPI_crop_seg_mod_crop.nii.gz -method labels -l ' + PATH_INFO + '/' + contrast + '/' + subject + '/labels_updown.nii.gz')
            sct.run('fslmaths data_RPI_crop_seg_mod_crop.nii.gz -add '+ PATH_INFO + '/' + contrast + '/' + subject + '/labels_updown.nii.gz seg_and_labels.nii.gz')
        else:
            sct.run('sct_get_centerline -i data_RPI_crop_seg_mod_crop.nii.gz -method labels -l ' + PATH_INFO + '/' + contrast + '/' + subject + '/centerline_propseg_RPI.nii.gz')
            sct.run('fslmaths data_RPI_crop_seg_mod_crop.nii.gz -add '+ PATH_INFO + '/' + contrast + '/' + subject + '/centerline_propseg_RPI.nii.gz seg_and_labels.nii.gz')




        # Normalisation of intensity with centerline before straightening (pb of brainstem with bad centerline)
        print '\nNormalizing intensity...'
        sct.run('sct_normalize.py -i data_RPI_crop.nii.gz -c generated_centerline.nii.gz')

        # straighten image using the concatenation of the segmentation and the labels
        # function: sct_straighten_spinalcord (option: nurbs)
        # input:
        # - data_crop_normalized.nii.gz
        # output:
        # - warp_curve2straight.nii.gz
        # - data_RPI_crop_normalized_straight.nii.gz
        print '\nStraightening image using centerline...'
        cmd_straighten = ('sct_straighten_spinalcord -i data_RPI_crop_normalized.nii.gz -s ' + PATH_OUTPUT + '/subjects/' + subject + '/' + contrast + '/seg_and_labels.nii.gz -o data_RPI_crop_normalized_straight.nii.gz '+straightening_parameters)
        #sct.printv(cmd_straighten)
        sct.run(cmd_straighten)

        # # # normalize intensity
        # print '\nNormalizing intensity of the straightened image...'
        # sct.run('sct_normalize.py -i data_RPI_crop_straight.nii.gz')

        # Crop labels_vertebral file
        print '\nCropping labels_vertebral file...'
        if ymin_anatomic == None and ymax_anatomic == None:
            sct.run('sct_crop_image -i '+PATH_INFO + '/' + contrast + '/' + subject+ '/labels_vertebral.nii.gz -o labels_vertebral_crop.nii.gz -start ' + zmin_anatomic + ' -end ' + zmax_anatomic + ' -dim 2')
        else: sct.run('sct_crop_image -i '+PATH_INFO + '/' + contrast + '/' + subject+ '/labels_vertebral.nii.gz -o labels_vertebral_crop.nii.gz -start ' + ymin_anatomic+','+zmin_anatomic + ' -end ' + ymax_anatomic+','+ zmax_anatomic + ' -dim 1,2')
        # Dilate labels from labels_vertebral file before straightening
        print '\nDilating labels from labels_vertebral file...'
        sct.run('fslmaths '+ PATH_OUTPUT + '/subjects/' + subject+ '/' + contrast + '/labels_vertebral_crop.nii.gz -dilF labels_vertebral_dilated.nii.gz')

        # apply straightening to labels_vertebral_dilated.nii.gz and to seg_and_labels.nii.gz
        # function: sct_apply_transfo
        # input:
        # - labels_vertebral_dilated.nii.gz
        # - warp_curve2straight.nii.gz
        # output:
        # - labels_vertebral_dilated_reg.nii.gz
        print '\nApplying straightening to labels_vertebral_dilated.nii.gz...'
        sct.run('sct_apply_transfo -i labels_vertebral_dilated.nii.gz -d data_RPI_crop_normalized_straight.nii.gz -w warp_curve2straight.nii.gz -x nn')

        # Select center of mass of labels volume due to past dilatation
        # REMOVE IF NOT REQUIRED
        print '\nSelecting center of mass of labels volume due to past dilatation...'
        sct.run('sct_label_utils -i labels_vertebral_dilated_reg.nii.gz -o labels_vertebral_dilated_reg_2point.nii.gz -t cubic-to-point')

        # Apply straightening to seg_and_labels.nii.gz
        print'\nApplying transfo to seg_and_labels.nii.gz ...'
        sct.run('sct_apply_transfo -i seg_and_labels.nii.gz -d data_RPI_crop_normalized_straight.nii.gz -w warp_curve2straight.nii.gz -x nn')

        ##Calculate the extrem non zero points of the straightened centerline file to crop image one last time
        file = nibabel.load('seg_and_labels_reg.nii.gz')
        data_c = file.get_data()

        X,Y,Z = (data_c>0).nonzero()

        z_max = max(Z)

        z_min = min(Z)

        # Crop image one last time
        print'\nCrop image one last time and create cross to push into template space...'
        sct.run('sct_crop_image -i data_RPI_crop_normalized_straight.nii.gz -o data_RPI_crop_normalized_straight_crop.nii.gz -dim 2 -start '+ str(z_min)+' -end '+ str(z_max))

        # Crop labels_vertebral_reg.nii.gz
        print'\nCrop labels_vertebral_reg.nii.gz and use cross to push into template space...'
        sct.run('sct_crop_image -i labels_vertebral_dilated_reg_2point.nii.gz -o labels_vertebral_dilated_reg_2point_crop.nii.gz -dim 2 -start '+ str(z_min)+' -end '+ str(z_max))


# Create cross at the first and last labels for each subject. This cross will be used to push the subject into the template space using affine transfo.
dataset/ETHPy150Open neuropoly/spinalcordtoolbox/dev/template_preprocessing/pipeline_template.py/do_preprocessing/original