#!/usr/bin/env python
from snack import *
import gettext, sys, os, re, string

import partition_data as p_d

sys.path.append('../interface/')
import ri_data

global base_unit
base_unit = 's'

def pretty_unit(num, unit=base_unit):
    num = float(num)
    global num_pretty
    global unit_pretty
    if unit == 'kB':
		if num < 1:
			# < 1k unit is B
			num_pretty = num * 1000
			unit_pretty = 'B'
		elif num < 10*1000:
			# < 10M unit is kB
			num_pretty = num
			unit_pretty = 'kB'
		elif num < 10*1000*1000:
			# < 10G unit is MB
			num_pretty = num/1000
			unit_pretty = 'MB'
		elif num < 10*1000*1000*1000:
			# < 10T unit is GB
			num_pretty = num/1000/1000
			unit_pretty = 'GB'
		return str("%.1f" %num_pretty) + unit_pretty
    if unit == 'B':
		if num < 1000:
			# < 1k unit is B
			num_pretty = num
			unit_pretty = 'B'
		elif num < 10*1000*1000:
			# < 10M unit is kB
			num_pretty = num/1000
			unit_pretty = 'kB'
    		elif num < 10*1000*1000*1000:
			# < 10G unit is MB
        		num_pretty = num/1000/1000
        		unit_pretty = 'MB'
		elif num < 10*1000*1000*1000*1000:
       		# < 10T unit is GB
			num_pretty = num/1000/1000/1000
			unit_pretty = 'GB'
    		return str("%.1f" %num_pretty) + unit_pretty
    if unit == 's':
		if num*512 < 1000:
			# < 1k unit is B
			num_pretty = num*512
			unit_pretty = 'B'
		elif num*512 < 10*1000*1000:
			# < 10M unit is kB
			num_pretty = num*512/1000
			unit_pretty = 'kB'
    		elif num*512 < 10*1000*1000*1000:
			# < 10G unit is MB
        		num_pretty = num*512/1000/1000
        		unit_pretty = 'MB'
		elif num*512 < 10*1000*1000*1000*1000:
       		# < 10T unit is GB
			num_pretty = num*512/1000/1000/1000
			unit_pretty = 'GB'
    		return str("%.1f" %num_pretty) + unit_pretty


def conform_unit(num_unit, unit = base_unit):
    #num = int(filter(str.isdigit, str(num_unit)))
    # because int('10.0') error
    num = float(get_num(str(num_unit)))
    if unit == 'B':
		if re.search('kB', num_unit):
			# unit kB to byte
			num_byte = num*1000
		elif re.search('MB', num_unit):
			# unit MB to byte
			num_byte = num*1000*1000
		elif re.search('GB', num_unit):
			# unit GB to byte
			num_byte = num*1000*1000*1000
		else:
			# unit is B
			num_byte = num
		return num_byte

    if unit == 'kB':
    	if re.search('kB', num_unit):
        	# unit kB to kB
        	num_kb = num
    	elif re.search('MB', num_unit):
        	# unit MB to kB
        	num_kb = num*1000
    	elif re.search('GB', num_unit):
        	# unit GB to kB
        	num_kb = num*1000*1000
        else:
        	# unit B to kB
			if num < 1000:
				num_kb = 1.0
			else:
				num_kb = num/1000
    	return num_kb

    if unit == 's':
    	if re.search('kB', num_unit):
        	# unit kB to s
        	num_s = num*1000/512 
    	elif re.search('MB', num_unit):
        	# unit MB to s
        	num_s = num*1000*1000/512
    	elif re.search('GB', num_unit):
        	# unit GB to s
        	num_s = num*1000*1000*1000/512
        else:
        	# unit B to s
			if num < 512:
				num_s = 1.0
			else:
				num_s = num/512
    	return num_s

def showPartitionWindow():
    global clb
    global bb
    #bb = ButtonBar (screen, (("New", "new"),("Delete", "delete"),("Boot", "boot"),\
    #        ("Raid", "raid"),("OK", "ok", "F12"),("Cancel", "cancel","F11"),('Quit','quit','ESC')))
    bb = ButtonBar (screen, (("New", "new"),("Delete", "delete"),\
            ("OK", "ok", "F12"),("Cancel", "cancel","F11"),('Quit','quit','ESC')))

    clb = CListbox(height=10, cols=6,
            col_widths=[19,11,11,11,10,12],
            scroll=1, returnExit = 1,
            width=85, col_pad=2,
            col_labels=['Device', 'Start', 'End', 'Size', 'Type', 'Flags'],
            col_label_align=[CENTER,CENTER,CENTER,CENTER,CENTER,CENTER])

    for dev in sorted(p_d.Partition.dict.keys()):
        # dev: /dev/sda  dev_name: sda; dev: /dev/cciss/c0d0 dev_name:cciss/c0d0
        dev_name = dev.split('/dev/')[1]
        partition_table = p_d.Partition.dict[dev]['partition_table']
        dev_size = p_d.Partition.dict[dev]['disk_size']

        if re.search('/dev/md/',dev):
            continue

        clb.append(["%s" %(dev),"","","","",""], \
                "dev:%s:%s" %(dev,dev_size), [LEFT, RIGHT, RIGHT, RIGHT, LEFT, LEFT])

        if partition_table == '':
            continue

        if re.search('/cciss/', dev):
            pre_partition_name = dev + 'p'
        else:
            pre_partition_name = dev

        list_partition_all_sorted = p_d.sort_partitions(p_d.Partition.dict, dev, "all")
        for partition in list_partition_all_sorted:
            start = p_d.Partition.dict[dev]['partition'][partition]['start']
            end = p_d.Partition.dict[dev]['partition'][partition]['end']
            size = p_d.Partition.dict[dev]['partition'][partition]['size']
            ptype = p_d.Partition.dict[dev]['partition'][partition]['type']
            flags = p_d.Partition.dict[dev]['partition'][partition]['flags']
            
            try:
                partition_name = partition.split('/dev/')[1]
                if partition_name in ri_data.Raid.dev_in_raid():
                    continue
            except:
                pass

            try:
                if base_unit == 's':
                    if (float(get_num(size)) < 2000000/512.0 and float(get_num(start)) < 2048) \
							or float(get_num(size)) < 2048:
                    	continue
            except:
                pass

            start_pretty = pretty_unit(get_num(str(start)))
            end_pretty = pretty_unit(get_num(str(end)))
            size_pretty = pretty_unit(get_num(str(size)))

            # pretty free space partition
            if re.search('free', partition):
                partition_pretty = 'Free Space'
            else:
                partition_pretty = partition

            clb.append(["  %s" %(partition_pretty),"%s" %(start_pretty),"%s" %(end_pretty),"%s" %(size_pretty),"%s" %(ptype),"%s" %(flags)],\
					"partition:%s:%s:%s:%s:%s:%s:%s:%s:%s" %(partition, dev, size, start, end, partition_table, size_pretty, pre_partition_name, flags),\
                    [LEFT, RIGHT, RIGHT, RIGHT, LEFT, LEFT])

    sg = Grid(2, 3)
    sg.setField(bb, 0, 1, anchorLeft = 1)
    g = Grid(1, 3)
    g.setField(clb, 0, 0)
    g.setField(sg, 0, 2)
    g.place(1, 1)
    screen.gridWrappedWindow(g, "Partitioning")
    f = Form()
    f.add(bb)
    f.add(clb)
    f.addHotKey("F11")
    f.addHotKey("F12")

    global res
    res =f.run()
    screen.refresh

def get_num(size):
    if re.search('kB', size):
        size_num = size.split('kB')[0]
    elif re.search('MB', size):
        size_num = size.split('MB')[0]
    elif re.search('GB', size):
        size_num = size.split('GB')[0]
    elif re.search('s', size):
        size_num = size.split('s')[0]
    else:
        size_num = size.split('B')[0]
    return size_num

def show_error(tips):
    g21 = GridForm(screen, "Error", 1, 2)
    g21.add(Label("%s." %(tips)), 0, 0)
    g21.add(Button("OK"), 0, 1)
    g21.runOnce()

def del_raid(dev):
	md = ''
	try:
		if p_d.Partition.dict[dev]['partition_table'] == '':
			return
		for partition in p_d.sort_partitions(p_d.Partition.dict, dev, 'partition'):
			for raid in ri_data.Raid.dict.keys():
				for p in ri_data.Raid.dict[raid].active_components + ri_data.Raid.dict[raid].spare_components:
					if p == partition.split('/dev/')[1]:
						md = raid
						del ri_data.Raid.dict[md]
						raise StopIteration()
	except StopIteration:
		pass
	try:
		os.system('umount /dev/%s >/dev/null 2>&1' %(md))
	except:
		pass
	try:
		os.system('mdadm --stop /dev/%s >/dev/null 2>&1' %(md))
	except:
		pass

def ask_dialog(tips,dev):
    g21 = GridForm(screen, "Warning", 1, 3)
    g21.add(TextboxReflowed(45, "%s" %(tips)),0,0)
    #g21.add(Label("%s." %(tips)), 0, 0)
    g21.add(Label(''), 0, 1)
    bb4 = ButtonBar(screen, (('Continue','continue'),('Cancel','cancel')))
    g21.add(bb4, 0, 2)
    res4 = g21.runOnce()
    if bb4.buttonPressed(res4) == "continue":
		p_d.Partition.dict[dev]['from_os'] = 'no'
		for p in p_d.sort_partitions(p_d.Partition.dict, dev, 'partition'):
			p_d.Partition.dict[dev]['partition'][p]['from_os'] = 'no'
		del_raid(dev)
		return True
    else:
		return False

def check_size_set(size, maxsize):
    if size == "":
        return ("Must specify a value")
    try:
        if float(size) > float(maxsize):
            return ("Requested value is too large")
    except:
        return ("Requested value is not an number")

def count_primary_extended(dev):
    count_primary = 0
    count_extended = 0
    for p in p_d.sort_partitions(p_d.Partition.dict, dev):
        if p_d.Partition.dict[dev]['partition'][p]['type'] == 'primary':
            count_primary += 1
        if p_d.Partition.dict[dev]['partition'][p]['type'] == 'extended':
            count_extended += 1
    return (count_primary, count_extended)

def get_extended_start_end(dev):
    #extended_start = ''
    #extended_end = ''
    for p in p_d.sort_partitions(p_d.Partition.dict, dev):
        if p_d.Partition.dict[dev]['partition'][p]['type'] == 'extended':
            extended_start = p_d.Partition.dict[dev]['partition'][p]['start']
            extended_end = p_d.Partition.dict[dev]['partition'][p]['end']
            return (extended_start, extended_end)

def add_partition(ptype='', extended='', label=''):
    free_space = clb.current().split(":")[1]
    dev = clb.current().split(":")[2]
    dev_name = dev.split("/dev/")[1]
    size = clb.current().split(":")[3]
    size_pretty = clb.current().split(":")[7]
    free_space_start = get_num(clb.current().split(":")[4])
    free_space_end = get_num(clb.current().split(":")[5])
    free_space_sn = int(p_d.Partition.dict[dev]['partition'][free_space]['sn'])
    pre_partition_name = clb.current().split(":")[8]
    size_num = get_num(size)
    unit = filter(str.isalpha, size_pretty)
    size_pretty_num = get_num(size_pretty)

    bb2 = ButtonBar(screen, (("OK", "ok"), ("Cancel", "cancel")))
    sg21 = Grid(2,1)
    typeLbl = Label("File System type:   ")
    lb_fstype = Listbox(height=3, scroll=1)
    list_fs = ['ext2', 'ext3', 'ext4', 'linux-swap', 'raid', 'reiserfs', 'xfs', 'jfs']
    for fs in list_fs:
        lb_fstype.append(fs, fs)
    lb_fstype.setCurrent('ext3')
    sg21.setField(typeLbl, 0, 0, anchorLeft=0)
    sg21.setField(lb_fstype, 1, 0)

    sg22 = Grid(2,1)
    sizeLbl = Label("Size(%s):   " %(unit))
    entry_size = Entry(10, size_pretty_num)
    sg22.setField(sizeLbl, 0, 0)
    sg22.setField(entry_size, 1, 0)

    sg23 = Grid(2,1)
    rb_primary = SingleRadioButton("primary", None, 1)
    rb_extended = SingleRadioButton("extended", rb_primary)
    sg23.setField(rb_primary, 0, 0)
    sg23.setField(rb_extended, 1, 0)

    cb_boot = Checkbox("Force to be a bootable partition")

    g2 = GridForm(screen, "New Partition(%s)" %(dev), 1, 9)
    g2.add(sg21,0,0)

    g2.add(Label(""),0,1)
    g2.add(sg22,0,2)
    g2.add(Label(""),0,3)
    g2.add(cb_boot,0,4)
    g2.add(Label(""),0,5)

    if extended == "extended" or label == 'gpt':
        g2.add(bb2, 0, 6)
        res2 = g2.runOnce()
        if label == 'gpt':
            ptype = 'primary'
    else:
        g2.add(sg23,0,6)
        g2.add(Label(""),0,7)
        g2.add(bb2, 0, 8)
        res2 = g2.runOnce()
        if rb_primary.selected():
            ptype = 'primary'
        else:
            ptype = 'extended'

    if bb2.buttonPressed(res2) == "ok":
        fs_set = lb_fstype.current()
        tips = check_size_set(entry_size.value(),size_pretty_num)
        if tips:
            show_error(tips)
        else:
            size_set_pretty = entry_size.value() + unit
            size_set_num = conform_unit(size_set_pretty)
            size_set = str(size_set_num) + base_unit
            #partition_start = free_space_start + base_unit
            partition_end = str(float(free_space_start) + size_set_num) + base_unit
            # 4k align
            if float(free_space_start)/2048.0 == int(float(free_space_start)/2048.0) != 0:
                partition_start = free_space_start + base_unit
            else:
                partition_start = str((int(float(free_space_start)/2048.0)+1)*2048) + base_unit

            if (float(free_space_start)+size_set_num+1)/2048.0 == int((float(free_space_start)+size_set_num+1)/2048.0) != 0:
                pass
            else:
                partition_end = str((int(float(get_num(partition_end))/2048.0)+1)*2048-1) + base_unit

            flags = ''
            if cb_boot.value() == 1:
                if flags == '':
                    flags = 'boot'
                else:
                    flags = 'boot,' + flags
            if fs_set == 'raid':
                if flags == '':
                    flags = 'raid'
                else:
                    flags = flags + ',raid'
        
            partition_num = 0
            list_partition_sorted = p_d.sort_partitions(p_d.Partition.dict,dev,'partition')
            list_free_sorted = p_d.sort_partitions(p_d.Partition.dict,dev,'free')
            if list_partition_sorted == []:
                # an empty disk
                pass
            else:
                if ptype == 'logical':
                    partition_start = str(float(get_num(partition_start))+2048) + base_unit
                    partition_num = 4
                    for p in list_partition_sorted:
                        if int(p_d.Partition.dict[dev]['partition'][p]['num']) > partition_num \
                                and p_d.Partition.dict[dev]['partition'][p]['type'] =='logical':
                            partition_num = int(p_d.Partition.dict[dev]['partition'][p]['num'])
                else:
                    if int(p_d.Partition.dict[dev]['partition'][list_partition_sorted[0]]['num']) != 1:
                        pass
                    else:
                        for i in range(len(list_partition_sorted)):
                            if i == len(list_partition_sorted) - 1 or \
                                    int(p_d.Partition.dict[dev]['partition'][list_partition_sorted[i]]['num']) \
                                    != int(p_d.Partition.dict[dev]['partition'][list_partition_sorted[i+1]]['num']) - 1:
                                partition_num = int(p_d.Partition.dict[dev]['partition'][list_partition_sorted[i]]['num'])
                                break

            partition_num += 1
            partition = pre_partition_name + str(partition_num)
            partition_sn = free_space_sn

            if float(get_num(size_set_pretty)) == float(get_num(size_pretty)):
                partition_end = free_space_end + base_unit
                if len(list_free_sorted) > 1:
                    for p in list_free_sorted:
                        if int(p_d.Partition.dict[dev]['partition'][p]['sn']) >= int(free_space_sn):
                            p_num = int(p_d.Partition.dict[dev]['partition'][p]['num'])
                            p_d.Partition.dict[dev]['partition'][p]['sn'] = p_d.Partition.dict[dev]['partition']['free '+str(p_num+1)]['sn']
                            p_d.Partition.dict[dev]['partition'][p]['start'] = p_d.Partition.dict[dev]['partition']['free '+str(p_num+1)]['start']
                            p_d.Partition.dict[dev]['partition'][p]['end'] = p_d.Partition.dict[dev]['partition']['free '+str(p_num+1)]['end']
                            p_d.Partition.dict[dev]['partition'][p]['size'] = p_d.Partition.dict[dev]['partition']['free '+str(p_num+1)]['size']
                    p_d.delete_one_partition(p_d.Partition.dict, dev, 'free '+str(len(list_free_sorted)+1))
                    p_d.delete_one_partition(p_d.Partition.dict, dev, 'free '+str(len(list_free_sorted)))
                else:
                    del p_d.Partition.dict[dev]['partition'][free_space]
            else:
                list_partition_all_sorted = p_d.sort_partitions(p_d.Partition.dict, dev, 'all')
                p_d.Partition.dict[dev]['partition'][free_space]['start'] = str(float(free_space_start) + size_set_num + 1) + base_unit
                for p in list_partition_all_sorted:
                    if p_d.Partition.dict[dev]['partition'][p]['sn'] > free_space_sn-1:
                        p_d.Partition.dict[dev]['partition'][p]['sn'] = int(p_d.Partition.dict[dev]['partition'][p]['sn']) + 1
                p_d.Partition.dict[dev]['partition'][free_space]['sn'] = int(free_space_sn) + 1
                p_d.Partition.dict[dev]['partition'][free_space]['size'] = \
                        str(float(get_num(p_d.Partition.dict[dev]['partition'][free_space]['end'])) - \
                        float(get_num(p_d.Partition.dict[dev]['partition'][free_space]['start']))) + base_unit

            p_d.Partition.dict[dev]['partition'][partition]['sn'] = int(partition_sn)
            p_d.Partition.dict[dev]['partition'][partition]['num'] = int(partition_num)
            p_d.Partition.dict[dev]['partition'][partition]['start'] = partition_start
            p_d.Partition.dict[dev]['partition'][partition]['end'] = partition_end
            p_d.Partition.dict[dev]['partition'][partition]['size'] = size_set
            p_d.Partition.dict[dev]['partition'][partition]['type'] = ptype
            p_d.Partition.dict[dev]['partition'][partition]['filesystem'] = fs_set
            p_d.Partition.dict[dev]['partition'][partition]['flags'] = flags
            p_d.Partition.dict[dev]['partition'][partition]['from_os'] = 'no'
            p_d.Partition.dict[dev]['partition'][partition]['format'] = 'no'
            p_d.Partition.dict[dev]['partition'][partition]['mount_point'] = ''

            if ptype == 'extended':
                list_partition_all_sorted = p_d.sort_partitions(p_d.Partition.dict,dev, 'all')
                list_free_sorted = p_d.sort_partitions(p_d.Partition.dict,dev,'free')
                extended_free_space_sn = partition_sn + 1
                free_num = 0
                if len(list_partition_all_sorted) == partition_sn:
                    if list_free_sorted != []:
                        for f in list_free_sorted:
                            if p_d.Partition.dict[dev]['partition'][f]['num'] > free_num:
                                free_num = p_d.Partition.dict[dev]['partition'][f]['num']
                else:
                    for p in list_partition_all_sorted[::-1]:
                        p_num = p_d.Partition.dict[dev]['partition'][p]['num']
                        if p_d.Partition.dict[dev]['partition'][p]['sn'] > partition_sn:
                            if re.search('free', p):
                                p_d.Partition.dict[dev]['partition']['free '+str(p_num+1)]['sn'] = \
                                        p_d.Partition.dict[dev]['partition'][p]['sn']+1
                                p_d.Partition.dict[dev]['partition']['free '+str(p_num+1)]['num'] = p_num + 1
                                p_d.Partition.dict[dev]['partition']['free '+str(p_num+1)]['start'] =\
                                        p_d.Partition.dict[dev]['partition'][p]['start']
                                p_d.Partition.dict[dev]['partition']['free '+str(p_num+1)]['end'] =\
                                        p_d.Partition.dict[dev]['partition'][p]['end']
                                p_d.Partition.dict[dev]['partition']['free '+str(p_num+1)]['size'] =\
                                        p_d.Partition.dict[dev]['partition'][p]['size']
                                p_d.Partition.dict[dev]['partition']['free '+str(p_num+1)]['filesystem'] =\
                                        p_d.Partition.dict[dev]['partition'][p]['filesystem']
                                p_d.Partition.dict[dev]['partition']['free '+str(p_num+1)]['type'] = ''
                                p_d.Partition.dict[dev]['partition']['free '+str(p_num+1)]['flags'] = ''
                                p_d.Partition.dict[dev]['partition']['free '+str(p_num+1)]['from_os'] = 'no'
                                p_d.Partition.dict[dev]['partition']['free '+str(p_num+1)]['format'] = 'no'
                                p_d.Partition.dict[dev]['partition']['free '+str(p_num+1)]['mount_point'] = ''
                            else:
                                p_d.Partition.dict[dev]['partition'][p]['sn'] = p_d.Partition.dict[dev]['partition'][p]['sn']+1

                            if p_d.Partition.dict[dev]['partition'][p]['sn'] == partition_sn+1:
                                p_d.delete_one_partition(p_d.Partition.dict, dev, p)
                                if list_free_sorted != []:
                                    for f in list_free_sorted:
                                        if p_d.Partition.dict[dev]['partition'][f]['sn'] < extended_free_space_sn:
                                            if p_d.Partition.dict[dev]['partition'][f]['num'] > free_num:
                                                free_num = p_d.Partition.dict[dev]['partition'][f]['num']
                free_num += 1
                p_d.Partition.dict[dev]['partition']['free '+str(free_num)]['sn'] = int(partition_sn+1)
                p_d.Partition.dict[dev]['partition']['free '+str(free_num)]['num'] = int(free_num)
                #p_d.Partition.dict[dev]['partition']['free '+str(free_num)]['start'] = str(float(get_num(partition_start))+2048) + base_unit
                p_d.Partition.dict[dev]['partition']['free '+str(free_num)]['start'] = partition_start
                p_d.Partition.dict[dev]['partition']['free '+str(free_num)]['end'] = partition_end
                p_d.Partition.dict[dev]['partition']['free '+str(free_num)]['size'] = size_set
                p_d.Partition.dict[dev]['partition']['free '+str(free_num)]['filesystem'] = 'Free Space'
                p_d.Partition.dict[dev]['partition']['free '+str(free_num)]['type'] = ''
                p_d.Partition.dict[dev]['partition']['free '+str(free_num)]['flags'] = ''
                p_d.Partition.dict[dev]['partition']['free '+str(free_num)]['from_os'] = 'no'
                p_d.Partition.dict[dev]['partition']['free '+str(free_num)]['format'] = 'no'
                p_d.Partition.dict[dev]['partition']['free '+str(free_num)]['mount_point'] = ''

            if label == 'msdos' and re.search('boot', p_d.Partition.dict[dev]['partition'][partition]['flags']):
				for p in p_d.sort_partitions(p_d.Partition.dict,dev,'partition'):
					if p != partition and re.search('boot', p_d.Partition.dict[dev]['partition'][p]['flags']):
						if p_d.Partition.dict[dev]['partition'][p]['flags'] == 'boot':
							p_d.Partition.dict[dev]['partition'][p]['flags'] = ''
						else:
							p_d.Partition.dict[dev]['partition'][p]['flags'] = \
									p_d.Partition.dict[dev]['partition'][p]['flags'].split(',')[1].strip() 


def del_msdos_partition(partition,dev):
    bb3 = ButtonBar(screen, (("Cancel", "cancel"), ("Delete", "delete")))
    g3 = GridForm(screen, "Del Partition", 1, 3)
    g3.add(TextboxReflowed(45, 'You are about to delete the partition "%s".' \
            %(partition)), 0, 0)
    g3.add(Label(""),0,1)
    g3.add(bb3, 0, 2)
    res3 = g3.runOnce()

    if bb3.buttonPressed(res3) == "delete":
        pre_partition_name = clb.current().split(":")[8]
        list_partition_all_sorted = p_d.sort_partitions(p_d.Partition.dict, dev, "all")
        partition_sn = p_d.Partition.dict[dev]['partition'][partition]['sn']
        partition_num = p_d.Partition.dict[dev]['partition'][partition]['num']
        partition_start = p_d.Partition.dict[dev]['partition'][partition]['start']
        partition_end = p_d.Partition.dict[dev]['partition'][partition]['end']
        partition_size = p_d.Partition.dict[dev]['partition'][partition]['size']
        partition_type = p_d.Partition.dict[dev]['partition'][partition]['type']

        p_d.delete_one_partition(p_d.Partition.dict, dev, partition)

        if partition_type == 'extended':
            del_partition_count = 0
            del_free_count = 0
            for p in p_d.sort_partitions(p_d.Partition.dict, dev, "all"):
            #for p in list_partition_all_sorted:
                p_start = p_d.Partition.dict[dev]['partition'][p]['start']
                p_end = p_d.Partition.dict[dev]['partition'][p]['end']
                if float(get_num(p_start)) >= float(get_num(partition_start)) and \
                        float(get_num(p_end)) <= float(get_num(partition_end)):
                    p_d.delete_one_partition(p_d.Partition.dict, dev, p)
                    del_partition_count += 1
                    if re.search('free', p):
                        del_free_count += 1
            for p in p_d.sort_partitions(p_d.Partition.dict, dev, "all"):
                p_sn = p_d.Partition.dict[dev]['partition'][p]['sn']
                if p_sn > partition_sn:
                    p_d.Partition.dict[dev]['partition'][p]['sn'] = p_sn - del_partition_count
                    if re.search('free', p):
                        p_sn = p_d.Partition.dict[dev]['partition'][p]['sn']
                        p_num = p_d.Partition.dict[dev]['partition'][p]['num']
                        p_start = p_d.Partition.dict[dev]['partition'][p]['start']
                        p_end = p_d.Partition.dict[dev]['partition'][p]['end']
                        p_size = p_d.Partition.dict[dev]['partition'][p]['size']
                        p_d.delete_one_partition(p_d.Partition.dict, dev, p)
                        p_d.Partition.dict[dev]['partition']['free '+str(p_num-del_free_count)]['num'] = p_num - del_free_count
                        p_d.Partition.dict[dev]['partition']['free '+str(p_num-del_free_count)]['sn'] = p_sn
                        p_d.Partition.dict[dev]['partition']['free '+str(p_num-del_free_count)]['start'] = p_start
                        p_d.Partition.dict[dev]['partition']['free '+str(p_num-del_free_count)]['end'] = p_end
                        p_d.Partition.dict[dev]['partition']['free '+str(p_num-del_free_count)]['size'] = p_size
                        p_d.Partition.dict[dev]['partition']['free '+str(p_num-del_free_count)]['filesystem'] = 'Free Space'
                        p_d.Partition.dict[dev]['partition']['free '+str(p_num-del_free_count)]['type'] = ''
                        p_d.Partition.dict[dev]['partition']['free '+str(p_num-del_free_count)]['flags'] = ''
                        p_d.Partition.dict[dev]['partition']['free '+str(p_num-del_free_count)]['from_os'] = 'no'
                        p_d.Partition.dict[dev]['partition']['free '+str(p_num-del_free_count)]['format'] = 'no'
                        p_d.Partition.dict[dev]['partition']['free '+str(p_num-del_free_count)]['mount_point'] = ''

        list_partition_all_sorted = p_d.sort_partitions(p_d.Partition.dict, dev, "all")
        for p in list_partition_all_sorted:
            p_sn =  p_d.Partition.dict[dev]['partition'][p]['sn']
            if p_sn == partition_sn - 1:
                pre_partition = p
            elif p_sn == partition_sn + 1:
                next_partition = p

        try:
            (extended_start, extended_end) = get_extended_start_end(dev)
        except:
            pass

        if partition_type == 'logical':
            # pre_partition must exist 
            if locals().has_key('next_partition'):
                if re.search('free',next_partition) and \
                        float(get_num(p_d.Partition.dict[dev]['partition'][next_partition]['end']))\
                        <= float(get_num(extended_end)):
                    if re.search('free', pre_partition):
                        p_d.Partition.dict[dev]['partition'][pre_partition]['end'] = \
                                p_d.Partition.dict[dev]['partition'][next_partition]['end']
                        p_d.Partition.dict[dev]['partition'][pre_partition]['size'] = \
                                str(float(get_num(p_d.Partition.dict[dev]['partition'][next_partition]['end']))-\
                                float(get_num(p_d.Partition.dict[dev]['partition'][pre_partition]['start'])))+\
                                base_unit
                        p_d.delete_one_partition(p_d.Partition.dict, dev, next_partition)
                        for p in p_d.sort_partitions(p_d.Partition.dict, dev, "all"):
                            if p_d.Partition.dict[dev]['partition'][p]['sn'] > partition_sn + 1:
                                p_d.Partition.dict[dev]['partition'][p]['sn'] -= 2
                        for p in p_d.sort_partitions(p_d.Partition.dict, dev, "all"):
                            p_num = p_d.Partition.dict[dev]['partition'][p]['num']
                            if p_num > partition_num and not re.search('free', p):
                                p_num -= 1
                                p_d.Partition.dict[dev]['partition'][pre_partition_name+str(p_num)]['num'] = \
                                        p_num
                                p_d.Partition.dict[dev]['partition'][pre_partition_name+str(p_num)]['sn'] = \
                                        p_d.Partition.dict[dev]['partition'][p]['sn']
                                p_d.Partition.dict[dev]['partition'][pre_partition_name+str(p_num)]['start'] = \
                                        p_d.Partition.dict[dev]['partition'][p]['start']
                                p_d.Partition.dict[dev]['partition'][pre_partition_name+str(p_num)]['end'] = \
                                        p_d.Partition.dict[dev]['partition'][p]['end']
                                p_d.Partition.dict[dev]['partition'][pre_partition_name+str(p_num)]['size'] = \
                                        p_d.Partition.dict[dev]['partition'][p]['size']
                                p_d.Partition.dict[dev]['partition'][pre_partition_name+str(p_num)]['type'] = \
                                        p_d.Partition.dict[dev]['partition'][p]['type']
                                p_d.Partition.dict[dev]['partition'][pre_partition_name+str(p_num)]['filesystem'] = \
                                        p_d.Partition.dict[dev]['partition'][p]['filesystem']
                                p_d.Partition.dict[dev]['partition'][pre_partition_name+str(p_num)]['flags'] = \
                                        p_d.Partition.dict[dev]['partition'][p]['flags']
                                p_d.Partition.dict[dev]['partition'][pre_partition_name+str(p_num)]['from_os'] = \
                                        p_d.Partition.dict[dev]['partition'][p]['from_os']
                                p_d.Partition.dict[dev]['partition'][pre_partition_name+str(p_num)]['mount_point'] = \
                                        p_d.Partition.dict[dev]['partition'][p]['mount_point']
                                p_d.Partition.dict[dev]['partition'][pre_partition_name+str(p_num)]['format'] = \
                                        p_d.Partition.dict[dev]['partition'][p]['format']
                            if p_num > partition_num and re.search('free',p):
                                p_num -= 1
                                p_d.Partition.dict[dev]['partition']['free '+ str(p_num)]['num'] = \
                                        p_num
                                p_d.Partition.dict[dev]['partition']['free '+ str(p_num)]['sn'] = \
                                        p_d.Partition.dict[dev]['partition'][p]['sn']
                                p_d.Partition.dict[dev]['partition']['free '+ str(p_num)]['start'] = \
                                        p_d.Partition.dict[dev]['partition'][p]['start']
                                p_d.Partition.dict[dev]['partition']['free '+ str(p_num)]['end'] = \
                                        p_d.Partition.dict[dev]['partition'][p]['end']
                                p_d.Partition.dict[dev]['partition']['free '+ str(p_num)]['size'] = \
                                        p_d.Partition.dict[dev]['partition'][p]['size']
                                p_d.Partition.dict[dev]['partition']['free '+ str(p_num)]['filesystem'] = \
                                        p_d.Partition.dict[dev]['partition'][p]['filesystem']
                                p_d.Partition.dict[dev]['partition']['free '+ str(p_num)]['type'] = \
                                        p_d.Partition.dict[dev]['partition'][p]['type']
                                p_d.Partition.dict[dev]['partition']['free '+ str(p_num)]['flags'] = \
                                        p_d.Partition.dict[dev]['partition'][p]['flags']
                                p_d.Partition.dict[dev]['partition']['free '+ str(p_num)]['from_os'] = \
                                        p_d.Partition.dict[dev]['partition'][p]['from_os']
                                p_d.Partition.dict[dev]['partition']['free '+ str(p_num)]['format'] = \
                                        p_d.Partition.dict[dev]['partition'][p]['format']
                                p_d.Partition.dict[dev]['partition']['free '+ str(p_num)]['mount_point'] = \
                                        p_d.Partition.dict[dev]['partition'][p]['mount_point']
                        p_num_max = 1
                        for p in p_d.sort_partitions(p_d.Partition.dict, dev, "partition"):
                            if p_d.Partition.dict[dev]['partition'][p]['num'] > p_num_max:
                                p_num_max = p_d.Partition.dict[dev]['partition'][p]['num']
                        if p_num_max > partition_num:
                            p_d.delete_one_partition(p_d.Partition.dict, dev, pre_partition_name+str(p_num_max))
                        f_num_max = 1
                        for f in p_d.sort_partitions(p_d.Partition.dict, dev, "free"):
                            if p_d.Partition.dict[dev]['partition'][f]['num'] > f_num_max:
                                f_num_max = p_d.Partition.dict[dev]['partition'][f]['num']
                        if f_num_max > p_d.Partition.dict[dev]['partition'][pre_partition]['num']:
                            p_d.delete_one_partition(p_d.Partition.dict, dev, 'free '+str(f_num_max))
                    else:
                        p_d.Partition.dict[dev]['partition'][next_partition]['start'] = partition_start
                        p_d.Partition.dict[dev]['partition'][next_partition]['sn'] = partition_sn
                        p_d.Partition.dict[dev]['partition'][next_partition]['size'] = \
                                str(float(get_num(p_d.Partition.dict[dev]['partition'][next_partition]['end']))-\
                                float(get_num(partition_start))) + base_unit
                        for p in p_d.sort_partitions(p_d.Partition.dict, dev, "all"):
                            p_num = p_d.Partition.dict[dev]['partition'][p]['num']
                            if p_d.Partition.dict[dev]['partition'][p]['sn'] > partition_sn:
                                p_d.Partition.dict[dev]['partition'][p]['sn'] -= 1
                            if p_num > partition_num and not re.search('free', p):
                                p_num -= 1
                                p_d.Partition.dict[dev]['partition'][pre_partition_name+str(p_num)]['num'] = \
                                        p_num
                                p_d.Partition.dict[dev]['partition'][pre_partition_name+str(p_num)]['sn'] = \
                                        p_d.Partition.dict[dev]['partition'][p]['sn']
                                p_d.Partition.dict[dev]['partition'][pre_partition_name+str(p_num)]['start'] = \
                                        p_d.Partition.dict[dev]['partition'][p]['start']
                                p_d.Partition.dict[dev]['partition'][pre_partition_name+str(p_num)]['end'] = \
                                        p_d.Partition.dict[dev]['partition'][p]['end']
                                p_d.Partition.dict[dev]['partition'][pre_partition_name+str(p_num)]['size'] = \
                                        p_d.Partition.dict[dev]['partition'][p]['size']
                                p_d.Partition.dict[dev]['partition'][pre_partition_name+str(p_num)]['filesystem'] = \
                                        p_d.Partition.dict[dev]['partition'][p]['filesystem']
                                p_d.Partition.dict[dev]['partition'][pre_partition_name+str(p_num)]['type'] = \
                                        p_d.Partition.dict[dev]['partition'][p]['type']
                                p_d.Partition.dict[dev]['partition'][pre_partition_name+str(p_num)]['flags'] = \
                                        p_d.Partition.dict[dev]['partition'][p]['flags']
                                p_d.Partition.dict[dev]['partition'][pre_partition_name+str(p_num)]['from_os'] = \
                                        p_d.Partition.dict[dev]['partition'][p]['from_os']
                                p_d.Partition.dict[dev]['partition'][pre_partition_name+str(p_num)]['mount_point'] = \
                                        p_d.Partition.dict[dev]['partition'][p]['mount_point']
                                p_d.Partition.dict[dev]['partition'][pre_partition_name+str(p_num)]['format'] = \
                                        p_d.Partition.dict[dev]['partition'][p]['format']
                        p_num_max = 1
                        for p in p_d.sort_partitions(p_d.Partition.dict, dev, "partition"):
                            if p_d.Partition.dict[dev]['partition'][p]['num'] > p_num_max:
                                p_num_max = p_d.Partition.dict[dev]['partition'][p]['num']
                        if p_num_max > partition_num:
                            p_d.delete_one_partition(p_d.Partition.dict, dev, pre_partition_name+str(p_num_max))
                else:
                    if re.search('free', pre_partition):
                        p_d.Partition.dict[dev]['partition'][pre_partition]['end'] = partition_end
                        p_d.Partition.dict[dev]['partition'][pre_partition]['size'] = \
                                str(float(get_num(partition_end)) - \
                                float(get_num(p_d.Partition.dict[dev]['partition'][pre_partition]['start'])))+base_unit
                        for p in p_d.sort_partitions(p_d.Partition.dict, dev, "all"):
                            p_num = p_d.Partition.dict[dev]['partition'][p]['num']
                            if p_d.Partition.dict[dev]['partition'][p]['sn'] > partition_sn:
                                p_d.Partition.dict[dev]['partition'][p]['sn'] -= 1
                            if p_num > partition_num and not re.search('free', p):
                                p_num -= 1
                                p_d.Partition.dict[dev]['partition'][pre_partition_name+str(p_num)]['num'] = \
                                        p_num
                                p_d.Partition.dict[dev]['partition'][pre_partition_name+str(p_num)]['sn'] = \
                                        p_d.Partition.dict[dev]['partition'][p]['sn']
                                p_d.Partition.dict[dev]['partition'][pre_partition_name+str(p_num)]['start'] = \
                                        p_d.Partition.dict[dev]['partition'][p]['start']
                                p_d.Partition.dict[dev]['partition'][pre_partition_name+str(p_num)]['end'] = \
                                        p_d.Partition.dict[dev]['partition'][p]['end']
                                p_d.Partition.dict[dev]['partition'][pre_partition_name+str(p_num)]['size'] = \
                                        p_d.Partition.dict[dev]['partition'][p]['size']
                                p_d.Partition.dict[dev]['partition'][pre_partition_name+str(p_num)]['filesystem'] = \
                                        p_d.Partition.dict[dev]['partition'][p]['filesystem']
                                p_d.Partition.dict[dev]['partition'][pre_partition_name+str(p_num)]['type'] = \
                                        p_d.Partition.dict[dev]['partition'][p]['type']
                                p_d.Partition.dict[dev]['partition'][pre_partition_name+str(p_num)]['flags'] = \
                                        p_d.Partition.dict[dev]['partition'][p]['flags']
                                p_d.Partition.dict[dev]['partition'][pre_partition_name+str(p_num)]['from_os'] = \
                                        p_d.Partition.dict[dev]['partition'][p]['from_os']
                                p_d.Partition.dict[dev]['partition'][pre_partition_name+str(p_num)]['mount_point'] = \
                                        p_d.Partition.dict[dev]['partition'][p]['mount_point']
                                p_d.Partition.dict[dev]['partition'][pre_partition_name+str(p_num)]['format'] = \
                                        p_d.Partition.dict[dev]['partition'][p]['format']
                        p_num_max = 1
                        for p in p_d.sort_partitions(p_d.Partition.dict, dev, "partition"):
                            if p_d.Partition.dict[dev]['partition'][p]['num'] > p_num_max:
                                p_num_max = p_d.Partition.dict[dev]['partition'][p]['num']
                        if p_num_max > partition_num:
                            p_d.delete_one_partition(p_d.Partition.dict, dev, pre_partition_name+str(p_num_max))

                    else:
                        free_num = 0
                        list_free_sorted = p_d.sort_partitions(p_d.Partition.dict, dev, "free")
                        if list_free_sorted == [] or p_d.Partition.dict[dev]['partition'][list_free_sorted[0]]['sn'] > partition_sn:
                            pass
                        else:
                            for i in range(len(list_free_sorted)):
                                if i == len(list_free_sorted) - 1 or \
                                    ( p_d.Partition.dict[dev]['partition'][list_free_sorted[i]]['sn'] \
                                    < partition_sn and p_d.Partition.dict[dev]['partition'][list_free_sorted[i+1]]['sn']\
                                    >partition_sn):
                                    free_num = int(p_d.Partition.dict[dev]['partition'][list_free_sorted[i]]['num'])
                                    break
                        for f in p_d.sort_partitions(p_d.Partition.dict, dev, "free")[::-1]:
                            if p_d.Partition.dict[dev]['partition'][f]['sn'] > partition_sn:
                                f_num = p_d.Partition.dict[dev]['partition'][f]['num']
                                f_num += 1
                                p_d.Partition.dict[dev]['partition']['free '+str(f_num)]['num']= \
                                        f_num
                                p_d.Partition.dict[dev]['partition']['free '+str(f_num)]['sn']= \
                                        p_d.Partition.dict[dev]['partition'][f]['sn']
                                p_d.Partition.dict[dev]['partition']['free '+str(f_num)]['start']= \
                                        p_d.Partition.dict[dev]['partition'][f]['start']
                                p_d.Partition.dict[dev]['partition']['free '+str(f_num)]['end']= \
                                        p_d.Partition.dict[dev]['partition'][f]['end']
                                p_d.Partition.dict[dev]['partition']['free '+str(f_num)]['size']= \
                                        p_d.Partition.dict[dev]['partition'][f]['size']
                                p_d.Partition.dict[dev]['partition']['free '+str(f_num)]['filesystem']= \
                                        p_d.Partition.dict[dev]['partition'][f]['filesystem']
                                p_d.Partition.dict[dev]['partition']['free '+str(f_num)]['type']= \
                                        p_d.Partition.dict[dev]['partition'][f]['type']
                                p_d.Partition.dict[dev]['partition']['free '+str(f_num)]['flags']= \
                                        p_d.Partition.dict[dev]['partition'][f]['flags']
                                p_d.Partition.dict[dev]['partition']['free '+str(f_num)]['from_os']= \
                                        p_d.Partition.dict[dev]['partition'][f]['from_os']
                                p_d.Partition.dict[dev]['partition']['free '+str(f_num)]['mount_point']= \
                                        p_d.Partition.dict[dev]['partition'][f]['mount_point']
                                p_d.Partition.dict[dev]['partition']['free '+str(f_num)]['format']= \
                                        p_d.Partition.dict[dev]['partition'][f]['format']
                        for p in p_d.sort_partitions(p_d.Partition.dict, dev, "partition"):
                            p_num = p_d.Partition.dict[dev]['partition'][p]['num']
                            if p_d.Partition.dict[dev]['partition'][p]['sn'] >partition_sn \
                                    and p_num > 4:
                                p_num -= 1
                                p_d.Partition.dict[dev]['partition'][pre_partition_name+str(p_num)]['num']=\
                                        p_num
                                p_d.Partition.dict[dev]['partition'][pre_partition_name+str(p_num)]['sn']=\
                                        p_d.Partition.dict[dev]['partition'][p]['sn']
                                p_d.Partition.dict[dev]['partition'][pre_partition_name+str(p_num)]['start']=\
                                        p_d.Partition.dict[dev]['partition'][p]['start']
                                p_d.Partition.dict[dev]['partition'][pre_partition_name+str(p_num)]['end']=\
                                        p_d.Partition.dict[dev]['partition'][p]['end']
                                p_d.Partition.dict[dev]['partition'][pre_partition_name+str(p_num)]['size']=\
                                        p_d.Partition.dict[dev]['partition'][p]['size']
                                p_d.Partition.dict[dev]['partition'][pre_partition_name+str(p_num)]['type']=\
                                        p_d.Partition.dict[dev]['partition'][p]['type']
                                p_d.Partition.dict[dev]['partition'][pre_partition_name+str(p_num)]['filesystem']=\
                                        p_d.Partition.dict[dev]['partition'][p]['filesystem']
                                p_d.Partition.dict[dev]['partition'][pre_partition_name+str(p_num)]['flags']=\
                                        p_d.Partition.dict[dev]['partition'][p]['flags']
                                p_d.Partition.dict[dev]['partition'][pre_partition_name+str(p_num)]['from_os']=\
                                        p_d.Partition.dict[dev]['partition'][p]['from_os']
                                p_d.Partition.dict[dev]['partition'][pre_partition_name+str(p_num)]['mount_point']=\
                                        p_d.Partition.dict[dev]['partition'][p]['mount_point']
                                p_d.Partition.dict[dev]['partition'][pre_partition_name+str(p_num)]['format']=\
                                        p_d.Partition.dict[dev]['partition'][p]['format']
                        p_d.delete_one_partition(p_d.Partition.dict, dev, \
                                p_d.sort_partitions(p_d.Partition.dict,dev,"partition")[::-1][0])

                        free_num += 1
                        p_d.Partition.dict[dev]['partition']['free '+str(free_num)]['num'] = free_num
                        p_d.Partition.dict[dev]['partition']['free '+str(free_num)]['sn'] = partition_sn
                        p_d.Partition.dict[dev]['partition']['free '+str(free_num)]['start'] = partition_start
                        p_d.Partition.dict[dev]['partition']['free '+str(free_num)]['end'] = partition_end
                        p_d.Partition.dict[dev]['partition']['free '+str(free_num)]['size'] = partition_size
                        p_d.Partition.dict[dev]['partition']['free '+str(free_num)]['type'] = ''
                        p_d.Partition.dict[dev]['partition']['free '+str(free_num)]['flags'] = ''
                        p_d.Partition.dict[dev]['partition']['free '+str(free_num)]['from_os'] = 'no'
                        p_d.Partition.dict[dev]['partition']['free '+str(free_num)]['format'] = 'no'
                        p_d.Partition.dict[dev]['partition']['free '+str(free_num)]['mount_point'] = ''
                        p_d.Partition.dict[dev]['partition']['free '+str(free_num)]['filesystem'] = 'Free Space'

            else:
                free_num_max = 1
                for p in p_d.sort_partitions(p_d.Partition.dict, dev, "free"):
                    if p_d.Partition.dict[dev]['partition'][p]['num'] > free_max_num:
                        free_max_num = p_d.Partition.dict[dev]['partition'][p]['num']
                p_d.Partition.dict[dev]['partition']['free '+str(free_num_max)]['sn'] = partition_sn
                p_d.Partition.dict[dev]['partition']['free '+str(free_num_max)]['num'] = free_max_num
                p_d.Partition.dict[dev]['partition']['free '+str(free_num_max)]['start'] = partition_start
                p_d.Partition.dict[dev]['partition']['free '+str(free_num_max)]['end'] = partition_end
                p_d.Partition.dict[dev]['partition']['free '+str(free_num_max)]['size'] = partition_size
                p_d.Partition.dict[dev]['partition']['free '+str(free_num_max)]['filesystem'] = 'Free Space'
                p_d.Partition.dict[dev]['partition']['free '+str(free_num_max)]['type'] = ''
                p_d.Partition.dict[dev]['partition']['free '+str(free_num_max)]['flag'] = ''
                p_d.Partition.dict[dev]['partition']['free '+str(free_num_max)]['from_os'] = 'no'
                p_d.Partition.dict[dev]['partition']['free '+str(free_num_max)]['format'] = 'no'
                p_d.Partition.dict[dev]['partition']['free '+str(free_num_max)]['mount_point'] = ''

        else:
            if locals().has_key('pre_partition') and locals().has_key('next_partition'):
                if re.search('free', pre_partition) and re.search('free', next_partition):
                    if locals().has_key('extended_start') and \
                            (float(get_num(p_d.Partition.dict[dev]['partition'][pre_partition]['start']))\
                            >= float(get_num(extended_start)) and \
                            float(get_num(p_d.Partition.dict[dev]['partition'][pre_partition]['end']))\
                            <= float(get_num(extended_end))):
                        p_d.Partition.dict[dev]['partition'][next_partition]['start'] = partition_start
                        p_d.Partition.dict[dev]['partition'][next_partition]['size'] = \
                            str(float(get_num(p_d.Partition.dict[dev]['partition'][next_partition]['end']))-\
                            float(get_num(partition_start))) + base_unit
                        for p in p_d.sort_partitions(p_d.Partition.dict, dev, "all"):
                            if p_d.Partition.dict[dev]['partition'][p]['sn'] > partition_sn:
                                p_d.Partition.dict[dev]['partition'][p]['sn'] -= 1

                    else:
                        p_d.Partition.dict[dev]['partition'][pre_partition]['end'] = \
                            p_d.Partition.dict[dev]['partition'][next_partition]['end']
                        p_d.Partition.dict[dev]['partition'][pre_partition]['size'] = \
                            str(float(get_num(p_d.Partition.dict[dev]['partition'][next_partition]['end']))-\
                            float(get_num(p_d.Partition.dict[dev]['partition'][pre_partition]['start'])))+\
                            base_unit
                        for p in p_d.sort_partitions(p_d.Partition.dict, dev, "all"):
                            if p_d.Partition.dict[dev]['partition'][p]['sn'] > partition_sn + 1:
                                if re.search('free', p):
                                    p_num = p_d.Partition.dict[dev]['partition'][p]['num']
                                    p_d.Partition.dict[dev]['partition']['free '+str(p_num-1)]['num']\
                                        = p_num -1
                                    p_d.Partition.dict[dev]['partition']['free '+str(p_num-1)]['sn']\
                                        = p_d.Partition.dict[dev]['partition'][p]['sn']-2
                                    p_d.Partition.dict[dev]['partition']['free '+str(p_num-1)]['start']\
                                        = p_d.Partition.dict[dev]['partition'][p]['start']
                                    p_d.Partition.dict[dev]['partition']['free '+str(p_num-1)]['end']\
                                        = p_d.Partition.dict[dev]['partition'][p]['end']
                                    p_d.Partition.dict[dev]['partition']['free '+str(p_num-1)]['size']\
                                        = p_d.Partition.dict[dev]['partition'][p]['size']
                                    p_d.Partition.dict[dev]['partition']['free '+str(p_num-1)]['filesystem']\
                                        = p_d.Partition.dict[dev]['partition'][p]['filesystem']
                                    p_d.Partition.dict[dev]['partition']['free '+str(p_num-1)]['type']\
                                        = p_d.Partition.dict[dev]['partition'][p]['type']
                                    p_d.Partition.dict[dev]['partition']['free '+str(p_num-1)]['flags']\
                                        = p_d.Partition.dict[dev]['partition'][p]['flags']
                                    p_d.Partition.dict[dev]['partition']['free '+str(p_num-1)]['from_os']\
                                        = p_d.Partition.dict[dev]['partition'][p]['from_os']
                                    p_d.Partition.dict[dev]['partition']['free '+str(p_num-1)]['format']\
                                        = p_d.Partition.dict[dev]['partition'][p]['format']
                                    p_d.Partition.dict[dev]['partition']['free '+str(p_num-1)]['mount_point']\
                                        = p_d.Partition.dict[dev]['partition'][p]['mount_point']
                                else:
                                    p_d.Partition.dict[dev]['partition'][p]['sn'] -= 2
                        if len(p_d.sort_partitions(p_d.Partition.dict, dev,"free")) > 1:
                            free_last = p_d.sort_partitions(p_d.Partition.dict, dev,"free")[::-1][0]
                            p_d.delete_one_partition(p_d.Partition.dict,dev,free_last)

                elif re.search('free', pre_partition) and not re.search('free', next_partition):
                    if locals().has_key('extended_start') and \
                            (float(get_num(p_d.Partition.dict[dev]['partition'][pre_partition]['start']))\
                            >= float(get_num(extended_start)) and \
                            float(get_num(p_d.Partition.dict[dev]['partition'][pre_partition]['end']))\
                            <= float(get_num(extended_end))):
                        len_free_list = len(p_d.sort_partitions(p_d.Partition.dict, dev, "free"))
                        free_num_mid = 0
                        for i in range(len_free_list)[::-1]:
                            if p_d.Partition.dict[dev]['partition'] ['free '+str(i+1)]['sn'] > partition_sn:
                                p_d.Partition.dict[dev]['partition'] ['free '+str(i+2)]['sn'] = \
                                    p_d.Partition.dict[dev]['partition'] ['free '+str(i+1)]['sn']
                                p_d.Partition.dict[dev]['partition'] ['free '+str(i+2)]['num'] = \
                                    p_d.Partition.dict[dev]['partition'] ['free '+str(i+1)]['num']
                                p_d.Partition.dict[dev]['partition'] ['free '+str(i+2)]['start'] = \
                                    p_d.Partition.dict[dev]['partition'] ['free '+str(i+1)]['start']
                                p_d.Partition.dict[dev]['partition'] ['free '+str(i+2)]['end'] = \
                                    p_d.Partition.dict[dev]['partition'] ['free '+str(i+1)]['end']
                                p_d.Partition.dict[dev]['partition'] ['free '+str(i+2)]['size'] = \
                                    p_d.Partition.dict[dev]['partition'] ['free '+str(i+1)]['size']
                                p_d.Partition.dict[dev]['partition'] ['free '+str(i+2)]['filesystem'] = \
                                    p_d.Partition.dict[dev]['partition'] ['free '+str(i+1)]['filesystem']
                                p_d.Partition.dict[dev]['partition'] ['free '+str(i+2)]['type'] = \
                                    p_d.Partition.dict[dev]['partition'] ['free '+str(i+1)]['type']
                                p_d.Partition.dict[dev]['partition'] ['free '+str(i+2)]['flags'] = \
                                    p_d.Partition.dict[dev]['partition'] ['free '+str(i+1)]['flags']
                                p_d.Partition.dict[dev]['partition'] ['free '+str(i+2)]['from_os'] = \
                                    p_d.Partition.dict[dev]['partition'] ['free '+str(i+1)]['from_os']
                                p_d.Partition.dict[dev]['partition'] ['free '+str(i+2)]['format'] = \
                                    p_d.Partition.dict[dev]['partition'] ['free '+str(i+1)]['format']
                                p_d.Partition.dict[dev]['partition'] ['free '+str(i+2)]['mount_point'] = \
                                    p_d.Partition.dict[dev]['partition'] ['free '+str(i+1)]['mount_point']
                            if p_d.Partition.dict[dev]['partition'] ['free '+str(i+1)]['sn'] < partition_sn:
                                free_num_mid = p_d.Partition.dict[dev]['partition']['free '+str(i+1)]['num']
                                break
                        p_d.Partition.dict[dev]['partition'] ['free '+str(free_num_mid+1)]['sn'] = partition_sn
                        p_d.Partition.dict[dev]['partition'] ['free '+str(free_num_mid+1)]['num'] = free_num_mid+1
                        p_d.Partition.dict[dev]['partition'] ['free '+str(free_num_mid+1)]['start'] = partition_start
                        p_d.Partition.dict[dev]['partition'] ['free '+str(free_num_mid+1)]['end'] = partition_end
                        p_d.Partition.dict[dev]['partition'] ['free '+str(free_num_mid+1)]['size'] = partition_size
                        p_d.Partition.dict[dev]['partition'] ['free '+str(free_num_mid+1)]['filesystem'] = 'Free Space'
                        p_d.Partition.dict[dev]['partition'] ['free '+str(free_num_mid+1)]['type'] = ''
                        p_d.Partition.dict[dev]['partition'] ['free '+str(free_num_mid+1)]['flags'] = ''
                        p_d.Partition.dict[dev]['partition'] ['free '+str(free_num_mid+1)]['from_os'] = ''
                        p_d.Partition.dict[dev]['partition'] ['free '+str(free_num_mid+1)]['format'] = ''
                        p_d.Partition.dict[dev]['partition'] ['free '+str(free_num_mid+1)]['mount_point'] = ''
                    else:
                        p_d.Partition.dict[dev]['partition'][pre_partition]['end'] = partition_end
                        p_d.Partition.dict[dev]['partition'][pre_partition]['size'] = \
                            str(float(get_num(partition_end)) - \
                            float(get_num(p_d.Partition.dict[dev]['partition'][pre_partition]['start'])))+\
                            base_unit
                        for p in p_d.sort_partitions(p_d.Partition.dict, dev, "all"):
                            if p_d.Partition.dict[dev]['partition'][p]['sn'] > partition_sn:
                                p_d.Partition.dict[dev]['partition'][p]['sn'] -= 1

                elif not re.search('free', pre_partition) and re.search('free',next_partition):
                    p_d.Partition.dict[dev]['partition'][next_partition]['start'] = partition_start
                    p_d.Partition.dict[dev]['partition'][next_partition]['size'] = \
                            str(float(get_num(p_d.Partition.dict[dev]['partition'][next_partition]['end']))-\
                            float(get_num(partition_start))) + base_unit
                    for p in p_d.sort_partitions(p_d.Partition.dict, dev, "all"):
                        if p_d.Partition.dict[dev]['partition'][p]['sn'] > partition_sn:
                            p_d.Partition.dict[dev]['partition'][p]['sn'] -= 1
                else:
                    len_free_list = len(p_d.sort_partitions(p_d.Partition.dict, dev, "free"))
                    free_num_mid = 0
                    for i in range(len_free_list)[::-1]:
                        if p_d.Partition.dict[dev]['partition'] ['free '+str(i+1)]['sn'] > partition_sn:
                            p_d.Partition.dict[dev]['partition'] ['free '+str(i+2)]['sn'] = \
                                    p_d.Partition.dict[dev]['partition'] ['free '+str(i+1)]['sn']
                            p_d.Partition.dict[dev]['partition'] ['free '+str(i+2)]['num'] = \
                                    p_d.Partition.dict[dev]['partition'] ['free '+str(i+1)]['num']+1
                            p_d.Partition.dict[dev]['partition'] ['free '+str(i+2)]['start'] = \
                                    p_d.Partition.dict[dev]['partition'] ['free '+str(i+1)]['start']
                            p_d.Partition.dict[dev]['partition'] ['free '+str(i+2)]['end'] = \
                                    p_d.Partition.dict[dev]['partition'] ['free '+str(i+1)]['end']
                            p_d.Partition.dict[dev]['partition'] ['free '+str(i+2)]['size'] = \
                                    p_d.Partition.dict[dev]['partition'] ['free '+str(i+1)]['size']
                            p_d.Partition.dict[dev]['partition'] ['free '+str(i+2)]['filesystem'] = \
                                    p_d.Partition.dict[dev]['partition'] ['free '+str(i+1)]['filesystem']
                            p_d.Partition.dict[dev]['partition'] ['free '+str(i+2)]['type'] = \
                                    p_d.Partition.dict[dev]['partition'] ['free '+str(i+1)]['type']
                            p_d.Partition.dict[dev]['partition'] ['free '+str(i+2)]['flags'] = \
                                    p_d.Partition.dict[dev]['partition'] ['free '+str(i+1)]['flags']
                            p_d.Partition.dict[dev]['partition'] ['free '+str(i+2)]['from_os'] = \
                                    p_d.Partition.dict[dev]['partition'] ['free '+str(i+1)]['from_os']
                            p_d.Partition.dict[dev]['partition'] ['free '+str(i+2)]['format'] = \
                                    p_d.Partition.dict[dev]['partition'] ['free '+str(i+1)]['format']
                            p_d.Partition.dict[dev]['partition'] ['free '+str(i+2)]['mount_point'] = \
                                    p_d.Partition.dict[dev]['partition'] ['free '+str(i+1)]['mount_point']

                        if p_d.Partition.dict[dev]['partition'] ['free '+str(i+1)]['sn'] < partition_sn:
                            free_num_mid = p_d.Partition.dict[dev]['partition']['free '+str(i+1)]['num']
                            break
                    p_d.Partition.dict[dev]['partition'] ['free '+str(free_num_mid+1)]['sn'] = partition_sn
                    p_d.Partition.dict[dev]['partition'] ['free '+str(free_num_mid+1)]['num'] = free_num_mid+1
                    p_d.Partition.dict[dev]['partition'] ['free '+str(free_num_mid+1)]['start'] = partition_start
                    p_d.Partition.dict[dev]['partition'] ['free '+str(free_num_mid+1)]['end'] = partition_end
                    p_d.Partition.dict[dev]['partition'] ['free '+str(free_num_mid+1)]['size'] = partition_size
                    p_d.Partition.dict[dev]['partition'] ['free '+str(free_num_mid+1)]['filesystem'] = 'Free Space'
                    p_d.Partition.dict[dev]['partition'] ['free '+str(free_num_mid+1)]['type'] = ''
                    p_d.Partition.dict[dev]['partition'] ['free '+str(free_num_mid+1)]['flags'] = ''
                    p_d.Partition.dict[dev]['partition'] ['free '+str(free_num_mid+1)]['from_os'] = ''
                    p_d.Partition.dict[dev]['partition'] ['free '+str(free_num_mid+1)]['format'] = ''
                    p_d.Partition.dict[dev]['partition'] ['free '+str(free_num_mid+1)]['mount_point'] = ''

            elif locals().has_key('pre_partition') and not locals().has_key('next_partition'):
                if re.search('free', pre_partition) and ((locals().has_key('extended_start') and\
                        float(get_num(p_d.Partition.dict[dev]['partition'][pre_partition]['start']))\
                        >= float(get_num(extended_end))) or \
                        not locals().has_key('extended_start')) :
                    free = p_d.sort_partitions(p_d.Partition.dict, dev,"free")[::-1][0]
                    p_d.Partition.dict[dev]['partition'][free]['end'] = partition_end
                    p_d.Partition.dict[dev]['partition'][free]['size'] = \
                            str(float(get_num(partition_end)) - \
			   				float(get_num(p_d.Partition.dict[dev]['partition'][free]['start']))) + base_unit
                else:
                    free_num_max = 0
                    for f in p_d.sort_partitions(p_d.Partition.dict, dev, "free"):
                        f_num = p_d.Partition.dict[dev]['partition'][f]['num']
                        if f_num > free_num_max:
                            free_num_max = f_num
                    p_d.Partition.dict[dev]['partition']['free '+str(free_num_max+1)]['num']\
                            = free_num_max+1
                    p_d.Partition.dict[dev]['partition']['free '+str(free_num_max+1)]['sn']\
                            = partition_sn
                    p_d.Partition.dict[dev]['partition']['free '+str(free_num_max+1)]['start']\
                            = partition_start
                    p_d.Partition.dict[dev]['partition']['free '+str(free_num_max+1)]['end']\
                            = partition_end
                    p_d.Partition.dict[dev]['partition']['free '+str(free_num_max+1)]['size']\
                            = partition_size
                    p_d.Partition.dict[dev]['partition']['free '+str(free_num_max+1)]['filesystem']\
                            = 'Free Space'
                    p_d.Partition.dict[dev]['partition']['free '+str(free_num_max+1)]['type']\
                            = ''
                    p_d.Partition.dict[dev]['partition']['free '+str(free_num_max+1)]['flags']\
                            = ''
                    p_d.Partition.dict[dev]['partition']['free '+str(free_num_max+1)]['from_os']\
                            = 'no'
                    p_d.Partition.dict[dev]['partition']['free '+str(free_num_max+1)]['format']\
                            = 'no'
                    p_d.Partition.dict[dev]['partition']['free '+str(free_num_max+1)]['mount_point']\
                            = ''

            elif not locals().has_key('pre_partition') and locals().has_key('next_partition'):
                if re.search('free', next_partition):
                    for p in p_d.sort_partitions(p_d.Partition.dict, dev,"all"):
                        p_d.Partition.dict[dev]['partition'][p]['sn'] -= 1
                    p_d.Partition.dict[dev]['partition']['free 1']['num'] = partition_num
                    p_d.Partition.dict[dev]['partition']['free 1']['sn'] = partition_sn
                    p_d.Partition.dict[dev]['partition']['free 1']['start'] = partition_start
                    p_d.Partition.dict[dev]['partition']['free 1']['size'] = \
                            str(float(get_num(p_d.Partition.dict[dev]['partition']['free 1']['end']))\
                            - float(get_num(partition_start))) + base_unit
                    p_d.Partition.dict[dev]['partition']['free 1']['filesystem'] = 'Free Space'
                    p_d.Partition.dict[dev]['partition']['free 1']['type'] = ''
                    p_d.Partition.dict[dev]['partition']['free 1']['flags'] = ''
                    p_d.Partition.dict[dev]['partition']['free 1']['from_os'] = 'no'
                    p_d.Partition.dict[dev]['partition']['free 1']['format'] = 'no'
                    p_d.Partition.dict[dev]['partition']['free 1']['mount_point'] = ''
                else:
                    for f in p_d.sort_partitions(p_d.Partition.dict, dev,"free")[::-1]:
                        free_num = p_d.Partition.dict[dev]['partition'][f]['num']
                        p_d.Partition.dict[dev]['partition']['free '+str(free_num+1)]['num']\
                                = free_num + 1
                        p_d.Partition.dict[dev]['partition']['free '+str(free_num+1)]['sn']\
                                = p_d.Partition.dict[dev]['partition'][f]['sn']
                        p_d.Partition.dict[dev]['partition']['free '+str(free_num+1)]['start']\
                                = p_d.Partition.dict[dev]['partition'][f]['start']
                        p_d.Partition.dict[dev]['partition']['free '+str(free_num+1)]['end']\
                                = p_d.Partition.dict[dev]['partition'][f]['end']
                        p_d.Partition.dict[dev]['partition']['free '+str(free_num+1)]['size']\
                                = p_d.Partition.dict[dev]['partition'][f]['size']
                        p_d.Partition.dict[dev]['partition']['free '+str(free_num+1)]['filesystem']\
                                = p_d.Partition.dict[dev]['partition'][f]['filesystem']
                        p_d.Partition.dict[dev]['partition']['free '+str(free_num+1)]['type']\
                                = p_d.Partition.dict[dev]['partition'][f]['type']
                        p_d.Partition.dict[dev]['partition']['free '+str(free_num+1)]['flags']\
                                = p_d.Partition.dict[dev]['partition'][f]['flags']
                        p_d.Partition.dict[dev]['partition']['free '+str(free_num+1)]['from_os']\
                                = p_d.Partition.dict[dev]['partition'][f]['from_os']
                        p_d.Partition.dict[dev]['partition']['free '+str(free_num+1)]['format']\
                                = p_d.Partition.dict[dev]['partition'][f]['format']
                        p_d.Partition.dict[dev]['partition']['free '+str(free_num+1)]['mount_point']\
                                = p_d.Partition.dict[dev]['partition'][f]['mount_point']

                    p_d.Partition.dict[dev]['partition']['free 1']['num'] = partition_num
                    p_d.Partition.dict[dev]['partition']['free 1']['sn'] = partition_sn
                    p_d.Partition.dict[dev]['partition']['free 1']['start'] = partition_start
                    p_d.Partition.dict[dev]['partition']['free 1']['end'] = partition_end
                    p_d.Partition.dict[dev]['partition']['free 1']['size'] = partition_size
                    p_d.Partition.dict[dev]['partition']['free 1']['filesystem'] = 'Free Space'
                    p_d.Partition.dict[dev]['partition']['free 1']['type'] = ''
                    p_d.Partition.dict[dev]['partition']['free 1']['flags'] = ''
                    p_d.Partition.dict[dev]['partition']['free 1']['from_os'] = 'no'
                    p_d.Partition.dict[dev]['partition']['free 1']['format'] = 'no'
                    p_d.Partition.dict[dev]['partition']['free 1']['mount_point'] = ''

            else:
                p_d.delete_all_partitions(p_d.Partition.dict, dev)
                
def del_gpt_partition(partition,dev):
    bb3 = ButtonBar(screen, (("Cancel", "cancel"), ("Delete", "delete")))
    g3 = GridForm(screen, "Del Partition", 1, 3)
    g3.add(TextboxReflowed(45, 'You are about to delete the partition "%s".' \
            %(partition)), 0, 0)
    g3.add(Label(""),0,1)
    g3.add(bb3, 0, 2)
    res3 = g3.runOnce()

    if bb3.buttonPressed(res3) == "delete":
    	pre_partition_name = clb.current().split(":")[8]
        list_partition_all_sorted = p_d.sort_partitions(p_d.Partition.dict, dev, "all")
        partition_sn = p_d.Partition.dict[dev]['partition'][partition]['sn']
        partition_num = p_d.Partition.dict[dev]['partition'][partition]['num']
        partition_start = p_d.Partition.dict[dev]['partition'][partition]['start']
        partition_end = p_d.Partition.dict[dev]['partition'][partition]['end']
        partition_size = p_d.Partition.dict[dev]['partition'][partition]['size']
        partition_type = p_d.Partition.dict[dev]['partition'][partition]['type']

        p_d.delete_one_partition(p_d.Partition.dict, dev, partition)

        list_partition_all_sorted = p_d.sort_partitions(p_d.Partition.dict, dev, "all")
        for p in list_partition_all_sorted:
            p_sn =  p_d.Partition.dict[dev]['partition'][p]['sn']
            if p_sn == partition_sn -1:
                pre_partition = p
            elif p_sn == partition_sn + 1:
                next_partition = p

        if locals().has_key('pre_partition') and locals().has_key('next_partition'):
            if re.search('free', pre_partition) and re.search('free', next_partition):
                p_d.Partition.dict[dev]['partition'][pre_partition]['end'] = \
                        p_d.Partition.dict[dev]['partition'][next_partition]['end']
                p_d.Partition.dict[dev]['partition'][pre_partition]['size'] = \
                        str(float(get_num(p_d.Partition.dict[dev]['partition'][next_partition]['end']))-\
                        float(get_num(p_d.Partition.dict[dev]['partition'][pre_partition]['start'])))+\
                        base_unit
                for p in p_d.sort_partitions(p_d.Partition.dict, dev, "all"):
                    if p_d.Partition.dict[dev]['partition'][p]['sn'] > partition_sn + 1:
                        if re.search('free', p):
                            p_num = p_d.Partition.dict[dev]['partition'][p]['num']
                            p_d.Partition.dict[dev]['partition']['free '+str(p_num-1)]['num']\
                                    = p_num -1
                            p_d.Partition.dict[dev]['partition']['free '+str(p_num-1)]['sn']\
                                    = p_d.Partition.dict[dev]['partition'][p]['sn']-2
                            p_d.Partition.dict[dev]['partition']['free '+str(p_num-1)]['start']\
                                    = p_d.Partition.dict[dev]['partition'][p]['start']
                            p_d.Partition.dict[dev]['partition']['free '+str(p_num-1)]['end']\
                                    = p_d.Partition.dict[dev]['partition'][p]['end']
                            p_d.Partition.dict[dev]['partition']['free '+str(p_num-1)]['size']\
                                    = p_d.Partition.dict[dev]['partition'][p]['size']
                            p_d.Partition.dict[dev]['partition']['free '+str(p_num-1)]['filesystem']\
                                    = p_d.Partition.dict[dev]['partition'][p]['filesystem']
                            p_d.Partition.dict[dev]['partition']['free '+str(p_num-1)]['type']\
                                    = p_d.Partition.dict[dev]['partition'][p]['type']
                            p_d.Partition.dict[dev]['partition']['free '+str(p_num-1)]['flags']\
                                    = p_d.Partition.dict[dev]['partition'][p]['flags']
                            p_d.Partition.dict[dev]['partition']['free '+str(p_num-1)]['from_os']\
                                    = p_d.Partition.dict[dev]['partition'][p]['from_os']
                            p_d.Partition.dict[dev]['partition']['free '+str(p_num-1)]['format']\
                                    = p_d.Partition.dict[dev]['partition'][p]['format']
                            p_d.Partition.dict[dev]['partition']['free '+str(p_num-1)]['mount_point']\
                                    = p_d.Partition.dict[dev]['partition'][p]['mount_point']
                        else:
                            p_d.Partition.dict[dev]['partition'][p]['sn'] -= 2
                if len(p_d.sort_partitions(p_d.Partition.dict, dev,"free")) > 1:
                    free_last = p_d.sort_partitions(p_d.Partition.dict, dev,"free")[::-1][0]
                    p_d.delete_one_partition(p_d.Partition.dict,dev,free_last)
            elif re.search('free', pre_partition) and not re.search('free', next_partition):
                p_d.Partition.dict[dev]['partition'][pre_partition]['end'] = partition_end
                p_d.Partition.dict[dev]['partition'][pre_partition]['size'] = \
                        str(float(get_num(partition_end)) - \
                        float(get_num(p_d.Partition.dict[dev]['partition'][pre_partition]['start'])))+\
                        base_unit
                for p in p_d.sort_partitions(p_d.Partition.dict, dev, "all"):
                    if p_d.Partition.dict[dev]['partition'][p]['sn'] > partition_sn:
                        p_d.Partition.dict[dev]['partition'][p]['sn'] -= 1
            elif not re.search('free', pre_partition) and re.search('free',next_partition):
                p_d.Partition.dict[dev]['partition'][next_partition]['start'] = partition_start
                p_d.Partition.dict[dev]['partition'][next_partition]['size'] = \
                        str(float(get_num(p_d.Partition.dict[dev]['partition'][next_partition]['end']))-\
                        float(get_num(partition_start))) + base_unit
                for p in p_d.sort_partitions(p_d.Partition.dict, dev, "all"):
                    if p_d.Partition.dict[dev]['partition'][p]['sn'] > partition_sn:
                        p_d.Partition.dict[dev]['partition'][p]['sn'] -= 1
            else:
                len_free_list = len(p_d.sort_partitions(p_d.Partition.dict, dev, "free"))
                free_num_mid = 0
                for i in range(len_free_list)[::-1]:
                    if p_d.Partition.dict[dev]['partition'] ['free '+str(i+1)]['sn'] > partition_sn:
                        p_d.Partition.dict[dev]['partition'] ['free '+str(i+2)]['sn'] = \
                                p_d.Partition.dict[dev]['partition'] ['free '+str(i+1)]['sn']
                        p_d.Partition.dict[dev]['partition'] ['free '+str(i+2)]['num'] = \
                                p_d.Partition.dict[dev]['partition'] ['free '+str(i+1)]['num']+1
                        p_d.Partition.dict[dev]['partition'] ['free '+str(i+2)]['start'] = \
                                p_d.Partition.dict[dev]['partition'] ['free '+str(i+1)]['start']
                        p_d.Partition.dict[dev]['partition'] ['free '+str(i+2)]['end'] = \
                                p_d.Partition.dict[dev]['partition'] ['free '+str(i+1)]['end']
                        p_d.Partition.dict[dev]['partition'] ['free '+str(i+2)]['size'] = \
                                p_d.Partition.dict[dev]['partition'] ['free '+str(i+1)]['size']
                        p_d.Partition.dict[dev]['partition'] ['free '+str(i+2)]['filesystem'] = \
                                p_d.Partition.dict[dev]['partition'] ['free '+str(i+1)]['filesystem']
                        p_d.Partition.dict[dev]['partition'] ['free '+str(i+2)]['type'] = \
                                p_d.Partition.dict[dev]['partition'] ['free '+str(i+1)]['type']
                        p_d.Partition.dict[dev]['partition'] ['free '+str(i+2)]['flags'] = \
                                p_d.Partition.dict[dev]['partition'] ['free '+str(i+1)]['flags']
                        p_d.Partition.dict[dev]['partition'] ['free '+str(i+2)]['from_os'] = \
                                p_d.Partition.dict[dev]['partition'] ['free '+str(i+1)]['from_os']
                        p_d.Partition.dict[dev]['partition'] ['free '+str(i+2)]['format'] = \
                                p_d.Partition.dict[dev]['partition'] ['free '+str(i+1)]['format']
                        p_d.Partition.dict[dev]['partition'] ['free '+str(i+2)]['mount_point'] = \
                                p_d.Partition.dict[dev]['partition'] ['free '+str(i+1)]['mount_point']

                    if p_d.Partition.dict[dev]['partition'] ['free '+str(i+1)]['sn'] < partition_sn:
                        free_num_mid = p_d.Partition.dict[dev]['partition']['free '+str(i+1)]['num']
                        break
                p_d.Partition.dict[dev]['partition'] ['free '+str(free_num_mid+1)]['sn'] = partition_sn
                p_d.Partition.dict[dev]['partition'] ['free '+str(free_num_mid+1)]['num'] = free_num_mid+1
                p_d.Partition.dict[dev]['partition'] ['free '+str(free_num_mid+1)]['start'] = partition_start
                p_d.Partition.dict[dev]['partition'] ['free '+str(free_num_mid+1)]['end'] = partition_end
                p_d.Partition.dict[dev]['partition'] ['free '+str(free_num_mid+1)]['size'] = partition_size
                p_d.Partition.dict[dev]['partition'] ['free '+str(free_num_mid+1)]['filesystem'] = 'Free Space'
                p_d.Partition.dict[dev]['partition'] ['free '+str(free_num_mid+1)]['type'] = ''
                p_d.Partition.dict[dev]['partition'] ['free '+str(free_num_mid+1)]['flags'] = ''
                p_d.Partition.dict[dev]['partition'] ['free '+str(free_num_mid+1)]['from_os'] = 'no'
                p_d.Partition.dict[dev]['partition'] ['free '+str(free_num_mid+1)]['format'] = 'no'
                p_d.Partition.dict[dev]['partition'] ['free '+str(free_num_mid+1)]['mount_point'] = ''

        elif locals().has_key('pre_partition') and not locals().has_key('next_partition'):
            if re.search('free', pre_partition):
                free = p_d.sort_partitions(p_d.Partition.dict, dev,"free")[::-1][0]
                p_d.Partition.dict[dev]['partition'][free]['end'] = partition_end
                p_d.Partition.dict[dev]['partition'][free]['size'] = \
                        partition_end - p_d.Partition.dict[dev]['partition'][free]['start']
            else:
                free_num_max = 0
                for f in p_d.sort_partitions(p_d.Partition.dict, dev, "free"):
                    f_num = p_d.Partition.dict[dev]['partition'][f]['num']
                    if f_num > free_num_max:
                        free_num_max = f_num
                p_d.Partition.dict[dev]['partition']['free '+str(free_num_max+1)]['num']\
                        = free_num_max+1
                p_d.Partition.dict[dev]['partition']['free '+str(free_num_max+1)]['sn']\
                        = partition_sn
                p_d.Partition.dict[dev]['partition']['free '+str(free_num_max+1)]['start']\
                        = partition_start
                p_d.Partition.dict[dev]['partition']['free '+str(free_num_max+1)]['end']\
                        = partition_end
                p_d.Partition.dict[dev]['partition']['free '+str(free_num_max+1)]['size']\
                        = partition_size
                p_d.Partition.dict[dev]['partition']['free '+str(free_num_max+1)]['filesystem']\
                        = 'Free Space'
                p_d.Partition.dict[dev]['partition']['free '+str(free_num_max+1)]['type']\
                        = ''
                p_d.Partition.dict[dev]['partition']['free '+str(free_num_max+1)]['flags']\
                        = ''
                p_d.Partition.dict[dev]['partition']['free '+str(free_num_max+1)]['from_os']\
                        = 'no'
                p_d.Partition.dict[dev]['partition']['free '+str(free_num_max+1)]['format']\
                        = 'no'
                p_d.Partition.dict[dev]['partition']['free '+str(free_num_max+1)]['mount_point']\
                        = ''

        elif not locals().has_key('pre_partition') and locals().has_key('next_partition'):
            if re.search('free', next_partition):
                for p in p_d.sort_partitions(p_d.Partition.dict, dev,"all"):
                    p_d.Partition.dict[dev]['partition'][p]['sn'] -= 1
                p_d.Partition.dict[dev]['partition']['free 1']['num'] = partition_num
                p_d.Partition.dict[dev]['partition']['free 1']['sn'] = partition_sn
                p_d.Partition.dict[dev]['partition']['free 1']['start'] = partition_start
                p_d.Partition.dict[dev]['partition']['free 1']['size'] = \
                        str(float(get_num(p_d.Partition.dict[dev]['partition']['free 1']['end']))\
                        - float(get_num(partition_start))) + base_unit
                p_d.Partition.dict[dev]['partition']['free 1']['filesystem'] = 'Free Space'
                p_d.Partition.dict[dev]['partition']['free 1']['type'] = ''
                p_d.Partition.dict[dev]['partition']['free 1']['flags'] = ''
                p_d.Partition.dict[dev]['partition']['free 1']['from_os'] = 'no'
                p_d.Partition.dict[dev]['partition']['free 1']['format'] = 'no'
                p_d.Partition.dict[dev]['partition']['free 1']['mount_point'] = ''
            else:
                for f in p_d.sort_partitions(p_d.Partition.dict, dev,"free")[::-1]:
                    free_num = p_d.Partition.dict[dev]['partition'][f]['num']
                    p_d.Partition.dict[dev]['partition']['free '+str(free_num+1)]['num']\
                            = free_num + 1
                    p_d.Partition.dict[dev]['partition']['free '+str(free_num+1)]['sn']\
                            = p_d.Partition.dict[dev]['partition'][f]['sn']
                    p_d.Partition.dict[dev]['partition']['free '+str(free_num+1)]['start']\
                            = p_d.Partition.dict[dev]['partition'][f]['start']
                    p_d.Partition.dict[dev]['partition']['free '+str(free_num+1)]['end']\
                            = p_d.Partition.dict[dev]['partition'][f]['end']
                    p_d.Partition.dict[dev]['partition']['free '+str(free_num+1)]['size']\
                            = p_d.Partition.dict[dev]['partition'][f]['size']
                    p_d.Partition.dict[dev]['partition']['free '+str(free_num+1)]['filesystem']\
                            = p_d.Partition.dict[dev]['partition'][f]['filesystem']
                    p_d.Partition.dict[dev]['partition']['free '+str(free_num+1)]['type']\
                            = p_d.Partition.dict[dev]['partition'][f]['type']
                    p_d.Partition.dict[dev]['partition']['free '+str(free_num+1)]['flags']\
                            = p_d.Partition.dict[dev]['partition'][f]['flags']
                    p_d.Partition.dict[dev]['partition']['free '+str(free_num+1)]['from_os']\
                            = p_d.Partition.dict[dev]['partition'][f]['from_os']
                    p_d.Partition.dict[dev]['partition']['free '+str(free_num+1)]['format']\
                            = p_d.Partition.dict[dev]['partition'][f]['format']
                    p_d.Partition.dict[dev]['partition']['free '+str(free_num+1)]['mount_point']\
                            = p_d.Partition.dict[dev]['partition'][f]['mount_point']

                p_d.Partition.dict[dev]['partition']['free 1']['num'] = partition_num
                p_d.Partition.dict[dev]['partition']['free 1']['sn'] = partition_sn
                p_d.Partition.dict[dev]['partition']['free 1']['start'] = partition_start
                p_d.Partition.dict[dev]['partition']['free 1']['end'] = partition_end
                p_d.Partition.dict[dev]['partition']['free 1']['size'] = partition_size
                p_d.Partition.dict[dev]['partition']['free 1']['filesystem'] = 'Free Space'
                p_d.Partition.dict[dev]['partition']['free 1']['type'] = ''
                p_d.Partition.dict[dev]['partition']['free 1']['flags'] = ''
                p_d.Partition.dict[dev]['partition']['free 1']['from_os'] = 'no'
                p_d.Partition.dict[dev]['partition']['free 1']['format'] = 'no'
                p_d.Partition.dict[dev]['partition']['free 1']['mount_point'] = ''
            
        else:
            p_d.delete_all_partitions(p_d.Partition.dict, dev)

def main():
	global screen
	screen = SnackScreen()
	screen.drawRootText(0, 0, "Welcome to Rocky Security OS")
	screen.pushHelpLine( ("<Tab>/<Alt-Tab> between elments  |  <Space> selects  |  <F11> Cancel  |  <F12> OK  |  <ESC> Quit"))
	
	while(1):
		global ret
		showPartitionWindow()
		if bb.buttonPressed(res) == "cancel":
			ret = 1
			break
		if bb.buttonPressed(res) == "ok":
			ret = 0
			break
		if bb.buttonPressed(res) == "quit":
			screen.finish()
			sys.exit(-1)

#		if bb.buttonPressed(res) == "raid" and re.search('dev:', clb.current()) == None \
#				and re.search('extended',clb.current()) == None and \
#				re.search('Free Space',clb.current()) == None:
#			partition = clb.current().split(":")[1]
#			dev = clb.current().split(":")[2]
#			flags = clb.current().split(":")[9]
#			if re.search('raid',flags):
#				flags = '' if flags == 'raid' else flags.split(',')[0]
#			else:
#				flags = 'raid' if flags == '' else flags + ',raid'
#			
#			p_d.Partition.dict[dev]['partition'][partition]['flags'] = flags
#
#		if bb.buttonPressed(res) == "boot" and re.search('dev:', clb.current()) == None \
#				and re.search('extended',clb.current()) == None and \
#				re.search('Free Space',clb.current()) == None:
#			partition = clb.current().split(":")[1]
#			dev = clb.current().split(":")[2]
#			label = clb.current().split(":")[6]
#			flags = clb.current().split(":")[9]
#			if re.search('boot',flags):
#				flags = '' if flags == 'boot' else flags.split(',')[1]
#			else:
#				flags = 'boot' if flags == '' else 'boot,' + flags
#			p_d.Partition.dict[dev]['partition'][partition]['flags'] = flags
#			if label == 'msdos' and re.search('boot', p_d.Partition.dict[dev]['partition'][partition]['flags']):
#				for p in p_d.sort_partitions(p_d.Partition.dict,dev,'partition'):
#					if p != partition and re.search('boot', p_d.Partition.dict[dev]['partition'][p]['flags']):
#						if p_d.Partition.dict[dev]['partition'][p]['flags'] == 'boot':
#							p_d.Partition.dict[dev]['partition'][p]['flags'] = ''
#						else:
#							p_d.Partition.dict[dev]['partition'][p]['flags'] = \
#									p_d.Partition.dict[dev]['partition'][p]['flags'].split(',')[1].strip() 

		# assign label(msdos or gpt) of  dev
		if re.search("dev:", clb.current()) and bb.buttonPressed(res) == "new":
			dev = clb.current().split(":")[1]
			dev_size = clb.current().split(":")[2]
			rb = RadioBar(screen, (("gpt", "gpt", 0),("msdos", "msdos", 1)))
			bb1 = ButtonBar(screen, (("Cancel", "cancel"), ("OK", "ok")))
			g = GridForm(screen, "Partition table", 1, 4)
			g.add(TextboxReflowed(25, 'Warning! A new partition table will be created on "%s" and the data on it will be cleared.' \
					%(dev)), 0, 0)
			g.add(Label(""),0,1)
			g.add(rb,0,2,(0,0,0,1))
			g.add(bb1, 0, 3)
			res1 = g.runOnce()
			if bb1.buttonPressed(res1) == "ok":
				del_raid(dev)
				label = rb.getSelection()
				p_d.Partition.dict[dev]['partition_table'] = label

				#os.system('parted -s %s mklabel %s' %(dev,label))
				p_d.delete_all_partitions(p_d.Partition.dict, dev)

		# add partition when dev's label is msdos
		elif re.search("partition:free", clb.current()) and \
				clb.current().split(':')[6] == 'msdos'and \
				bb.buttonPressed(res) == "new":
			dev = clb.current().split(":")[2]
			dev_name = dev.split("/dev/")[1]
			free_space_start = clb.current().split(":")[4]
			free_space_end = clb.current().split(":")[5]
			free_space_size = clb.current().split(":")[3]
			pre_partition_name = clb.current().split(':')[8]
			(count_primary, count_extended) = count_primary_extended(dev)
			# add logical partition when an extended partition exists
			if re.search('extended', str(p_d.Partition.dict[dev])):
				(extended_start, extended_end) = get_extended_start_end(dev)
				if float(get_num(free_space_start)) >= float(get_num(extended_start)) \
						and float(get_num(free_space_end)) <= float(get_num(extended_end)):
					ptype = 'logical'
					add_partition(ptype, 'extended', 'msdos')
				#elif float(get_num(free_space_start)) >= float(get_num(extended_end)):
				#	show_error("Bad partition scheme ! This free space can't be used any more !")
				else:
					if count_primary == 3:
						show_error('You can not add new primary or extended partition any more !')
					else:
						ptype = 'primary'
						add_partition(ptype, 'extended', 'msdos')
			else:
				if count_primary == 4:
					show_error("You can't add partitions any more !")
				else:
					add_partition(ptype='', extended='', label='msdos')
		elif re.search("partition:free", clb.current()) and \
				clb.current().split(':')[6] == 'gpt'and \
				bb.buttonPressed(res) == "new":
			dev = clb.current().split(":")[2]
			free_space_start = clb.current().split(":")[4]
			free_space_end = clb.current().split(":")[5]
			free_space_size = clb.current().split(":")[3]
			pre_partition_name = clb.current().split(':')[8]
			add_partition(ptype='primary', extended='', label='gpt')
		elif re.search("partition:free", clb.current()) == None and \
				re.search("dev:", clb.current()) == None and \
				bb.buttonPressed(res) == "delete":
			dev = clb.current().split(":")[2]
			partition = clb.current().split(":")[1]
			if p_d.Partition.dict[dev]['from_os'] != 'no' and p_d.Partition.dict[dev]['partition'][partition]['from_os'] != 'no':
				if not ask_dialog('Changing the partition will damage the data on the disk %s,do you want to continue?' %(dev,),dev):
					continue
			msdos_or_gpt = clb.current().split(':')[6]
			pre_partition_name = clb.current().split(':')[8]
			if msdos_or_gpt == 'msdos':
				del_msdos_partition(partition, dev)
			elif msdos_or_gpt == 'gpt':
				del_gpt_partition(partition, dev)

	screen.finish()
	#p_d.write_to_xml_file()
	return ret


#p_d.Partition.init_from_os(unit='s')
#main()
