def get_n_message_grids(nbits_per_map, ngrids):
    """
    nbits_per_map is list, specifying the number of non-trash bits in each grid if it were a conj_map (given its shape)
    ngrids is the total number of grids, be they message or conj_map

    want to find x, the number of message grids, and y, the number of conj_map grids
        s.t. ngrids=x+y and sum(nbits_per_map[-(y-1)]) < x <= sum(nbits_per_map[-y:])
    e.g. if x=34, and nbits_per_map=64 for each conj_map, then ngrids=35, x=34, and y=1 because 0 < 34 < 64
    e.g. if x=160, and nbits_per_map=60 for each conj_map, then ngrids=163, x=160, and y=3 because 2*60 < 160 < 3*60
    """
    x, y = ngrids-1, 1
    is_valid = lambda x, y, ngrids, nbits_per_map: ngrids==x+y and sum(nbits_per_map[-(y-1):]) < x <= sum(nbits_per_map[-y:])
    while not is_valid(x, y, ngrids, nbits_per_map) and x > 0:
        x, y = x-1, y+1
    if x <= 0 and ngrids == 2:
        # edge case
        return 1
    assert x > 0
    assert y > 0
    return x