from typing import Dict


def icf_regions_to_ld_regions(icf_regions: Dict) -> Dict:
    """Converts .icf regions to .ld regions

    The .icf format specifies the beginning and end of each region, while
    .ld expects the beginning and a length string.

    Args:
        icf_regions: icf_regions parsed with `parse_icf()`

    Returns:
        A map from `region_name` -> (start_hex, length_str)
    """
    ld_regions = {}
    for region, (start, end) in icf_regions.items():
        start_dec = int(start, 16)
        end_dec = int(end, 16)
        length = end_dec - start_dec + 1
        length_str = str(length)
        if length % 1024 == 0:
            length_str = f'{int(length/1024)}K'

        # Some icf scripts incorrectly have an exclusive region end.
        # This corrects for that.
        elif (length - 1) % 1024 == 0:
            length_str = f'{int((length-1)/1024)}K'

        # ST's gcc linker scripts generally use FLASH instead of ROM
        if region == 'ROM':
            region = 'FLASH'

        ld_regions[region] = (start, length_str)

    return ld_regions