goto error;
        if (option && !uci_validate_name(option))
                goto error;
-       if ((rename || !delete) && !uci_validate_name(value))
+       if ((rename || (!option && !delete)) && !uci_validate_name(value))
                goto error;
 
        if (rename)
 
                free(ctx->savedir);
 
        UCI_TRAP_SAVE(ctx, ignore);
+       ctx->internal = true;
        uci_cleanup(ctx);
        uci_foreach_element_safe(&ctx->root, tmp, e) {
                struct uci_package *p = uci_to_package(e);
 
                return;
 
        if (value)
-               size += strlen(section) + 1;
+               size += strlen(value) + 1;
 
        h = uci_alloc_element(ctx, history, option, size);
        ptr = uci_dataptr(h);
                goto notfound;
 
        s = uci_to_section(e);
-       if (ctx->pctx)
+       if (ctx->pctx && ctx->pctx->merge)
                ctx->pctx->section = s;
 
        if (option) {
                uci_alloc_option(s, option, value);
        else {
                s = uci_alloc_section(p, value, section);
-               if (ctx->pctx)
+               if (ctx->pctx && ctx->pctx->merge)
                        ctx->pctx->section = s;
        }