'Calculate an erase size given a specific size in bytes.
Provides a workaround for the bootloader erase bug.'

def get_erase_size(self, offset, size):

    sectors_per_block = 16
    sector_size = self.FLASH_SECTOR_SIZE
    num_sectors = (((size + sector_size) - 1) // sector_size)
    start_sector = (offset // sector_size)
    head_sectors = (sectors_per_block - (start_sector % sectors_per_block))
    if (num_sectors < head_sectors):
        head_sectors = num_sectors
    if (num_sectors < (2 * head_sectors)):
        return (((num_sectors + 1) // 2) * sector_size)
    else:
        return ((num_sectors - head_sectors) * sector_size)
