/*
* LaGUI: A graphical application framework.
* Copyright (C) 2022-2023 Wu Yiming
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "la_5.h"

extern LA MAIN;

const char* LA_UDF_EXTENSION_STRINGS[]={
    "LA_UDF_EXTENSION_FLOAT32",
    "LA_UDF_EXTENSION_RAW",
    "LA_UDF_EXTENSION_QUICK_SEEK",
    "",
};

int la_IsThisProp(laProp *p, char *id){
    return (!strcmp(p->Identifier, id));
}
laProp *la_PropLookup(laListHandle *lst, char *ID){
    laProp *p = 0, *ip;
    if (!lst) return 0;
    p = lstFindItem(ID, la_IsThisProp, lst);
    if (!p) if (strSame(ID, "identifier")){
            for (ip = lst->pFirst; ip; ip = ip->Item.pNext){
                if (ip->Tag & LA_AS_IDENTIFIER) return ip;
            }
        }
    return p;
}
laProp *la_PropLookupIdentifierItem(laListHandle *lst){
    laProp *p;
    if (!lst) return 0;

    for (p = lst->pFirst; p; p = p->Item.pNext){
        if (p->Tag & LA_AS_IDENTIFIER) return p;
        elif (la_IsThisProp(p, "identifier")) return p;
    }
    return 0;
}

int la_IsThisContainer(laPropContainer *p, char *id){
    return (!strcmp(p->Identifier, id));
}
laPropContainer *la_ContainerLookup(char *ID){
    laPropContainer* pc= lstFindItem(ID, la_IsThisContainer, &MAIN.PropContainers);
    return pc;
}

void la_CopyPropPack(laPropPack* From, laPropPack* To) {
	laPropStep* ps,*fps,*LastPs=0;
	To->RawThis = From->RawThis;
	To->EndInstance = From->EndInstance;

	la_FreePropStepCache(To->Go);
	To->Go = To->LastPs = 0;

	for (fps = From->Go; fps; fps = fps->pNext) {
		ps = memAcquireSimple(sizeof(laPropStep));
		ps->p = fps->p;
		ps->UseInstance = fps->UseInstance;
		ps->Type = fps->Type;
		if (LastPs)LastPs->pNext = ps;
		else {
			To->Go = ps;
		}
		LastPs = ps;
	}
    if(!LastPs){ To->LastPs = From->LastPs; }
    else{ To->LastPs =LastPs; }
}

laListHandle* laGetUserList(void* HyperUserMem, laProp* Which, int* IsLocal){
    laListHandle* users;
    if(Which && Which->Container){
        laPropContainer* pc=Which->Container;
        if(pc->OtherAlloc || (!pc->Hyper)){
            *IsLocal=1;
            return &pc->LocalUsers;
        }
    }
    *IsLocal=0;
    return memGetUserList(HyperUserMem);
}

laItemUserLinker *laUseDataBlock(void *HyperUserMem, laProp *Which, unsigned int FrameDistinguish, void *User, laUserRemoveFunc Remover, int ForceRecalc){
    laItemUserLinker *iul; laItemUserLinkerLocal *iull; int local;
    if (!HyperUserMem) return 0;
    laListHandle* users = laGetUserList(HyperUserMem, Which, &local); if(!users) return 0;
    for (iul = users->pFirst; iul; iul = iul->Pointer.pNext){
        if(local && (iull=iul) && iull->Instance!=HyperUserMem) continue;
        if (iul->Which == Which && iul->Pointer.p == User){
            iul->FrameDistinguish = FrameDistinguish;
            if(ForceRecalc) iul->ForceRecalc = ForceRecalc;
            return iul;
        }
    }
    iul = lstAppendPointerSized(users, User, local?sizeof(laItemUserLinkerLocal):sizeof(laItemUserLinker));
    iul->Which = Which;
    iul->FrameDistinguish = FrameDistinguish;
    iul->Remove = Remover;
    iul->ForceRecalc = ForceRecalc;
    if(local){ iull=iul; iull->Instance=HyperUserMem; }
    return iul;
}
void laStopUsingDataBlock(void *HyperUserMem, laProp *prop, laPanel* p){
    laItemUserLinker *iul,*next_iul; laItemUserLinkerLocal *iull; int local;
    if (!HyperUserMem) return;
    laListHandle* users = laGetUserList(HyperUserMem, prop, &local); if(!users) return;
    for (iul = users->pFirst; iul; iul = next_iul){
        next_iul = iul->Pointer.pNext;
        if(local && (iull=iul) && iull->Instance!=HyperUserMem) continue;
        if (/*prop == iul->Which &&*/ iul->Pointer.p == p||iul->Additional==p){
            lstRemoveItem(users,iul);
            memFree(iul);
        }
    }
}
void laDataBlockNoLongerExists(void *HyperUserMem, laListHandle* UserList){
    laItemUserLinker *iul,*next_iul;
    for (iul = UserList->pFirst; iul; iul = next_iul){
        next_iul = iul->Pointer.pNext;
        iul->Remove(HyperUserMem, iul);
        lstRemoveItem(UserList,iul);
        memFree(iul);
    }
}
void la_PrintUserList(void* HyperUserMem){
    laItemUserLinker* iul, * next_iul; laItemUserLinkerLocal* iull; int local;
    if (!HyperUserMem) return;
    laListHandle* users = laGetUserList(HyperUserMem, 0, &local); if (!users) return;
    for (iul = users->pFirst; iul; iul = next_iul) {
        next_iul = iul->Pointer.pNext;
        printf("p %x  which %s add %x\n", iul->Pointer.p, iul->Which ? iul->Which->Identifier : "-", iul->Additional);
    }
}

//laProp* la_GetGeneralPropFromPath(laProp* General, const char * Path) {
//	laProp* p;
//	laListHandle* lst = &General->Sub;
//	laStringSplitor* ss = strSplitPathByDot(Path);
//	laStringPart* sp = ss->parts.pFirst;
//
//	while (sp) {
//		p = la_PropLookup(lst, sp->Content);
//		lst = &p->Sub;
//		sp = sp->Item.pNext;
//	}
//
//	strDestroyStringSplitor(&ss);
//	return p;
//}

//laProp* la_GetPropFromPath(laPropPack* Base,const char * Path) {
//	laProp* p,*LastP=Base?Base->P:0;
//	laListHandle* lst;
//	laStringSplitor* ss = strSplitPathByDot(Path);
//	laStringPart* sp = ss->parts.pFirst;
//
//	if(!Base || !Base->P)
//		lst = &MAIN.DataRoot.Root->Sub;
//	else lst = &Base->P->Sub;
//
//
//	while (sp) {
// 		p = la_PropLookup(lst, sp->Content);
//		if (!p && LastP) {
//			p = la_PropLookup(&la_GetGeneralProp(LastP)->Sub, sp->Content);
//		}
//		LastP = p;
//		lst = &p->Sub;
//		sp = sp->Item.pNext;
//	}
//
//	strDestroyStringSplitor(&ss);
//
//	return p;
//}

void la_NewPropStep(laPropPack *Self, laProp *P, void *UseInstance, char Type){
    laPropStep *ps = memAcquireSimple(sizeof(laPropStep));

    if (Type == U'.' || Type == U'$'){
        ps->p = P;
        ps->UseInstance = UseInstance;
        ps->Type = Type;
    }elif (Type == U'@' || Type == U'=' || Type == U'#'){
        ps->p = CreateNewBuffer(char, strlen(P) + 1);
        strcpy(ps->p, P);
        ps->UseInstance = UseInstance;
        ps->Type = Type;
    }

    if (!Self->Go){
        Self->Go = ps;
        Self->LastPs = ps;
    }else{
        Self->LastPs->pNext = ps;
        Self->LastPs = ps;
    }
}
void la_FreePropStepCache(laPropStep *GoTarget){
    if (!GoTarget) return;
    if (GoTarget->pNext){
        la_FreePropStepCache(GoTarget->pNext);
    }
    if (GoTarget->Type == U'@' || GoTarget->Type == U'=' || GoTarget->Type == U'#') FreeMem(GoTarget->p);
    memFree(GoTarget);
}
void *la_FindMatchingInstance(void *From, laProp *Sub, laProp *p, laPropStep *Value){
    laPropPack Fake;
    laPropStep FakePs;
    laPropIterator pi = {0};
    void *Inst;
    char _buf[LA_RAW_CSTR_MAX_LEN]={0}; char*buf=_buf;
    int val;

    Fake.LastPs = &FakePs;
    FakePs.p = p;

    Inst = laGetInstance(Sub, From, &pi);

    if (p->PropertyType == LA_PROP_STRING){
        _buf[0] = 0;
        FakePs.UseInstance = Inst;
        laGetString(&Fake, _buf, &buf);
        while (!strSame(buf, Value->p)){
            Inst = laGetNextInstance(Sub, Inst, &pi);
            if (!Inst) return 0;
            _buf[0] = 0;
            FakePs.UseInstance = Inst;
            laGetString(&Fake, _buf, &buf);
        }
        return Inst;
    }elif (p->PropertyType == LA_PROP_INT){
        FakePs.UseInstance = Inst;
        val = laGetInt(&Fake); char buf[64]; int compareval=0;
        int status=sscanf(buf,"%d",&compareval);
        while (status && status!=EOF && val != compareval){
            Inst = laGetNextInstance(Sub, From, &pi);
            if (!Inst) return 0;
            FakePs.UseInstance = Inst;
            val = laGetInt(&Fake);
        }
        return Inst;
    }
}
int la_GetPropFromPath(laPropPack *Self, laPropPack *Base, const char *Path, void **SpecifiedInstance){
    laProp *p = 0;
    laListHandle *lst=0, *lstB = 0;
    laStringSplitor *ss = strSplitPath(Path,0);
    laStringPart *sp = ss ? ss->parts.pFirst : 0;
    int InstanceNum = 0;

    if ((!ss && !Base) || !MAIN.DataRoot.Root){ strDestroyStringSplitor(&ss); return 0; }

    if (!Base || !Base->LastPs){
        lst = &MAIN.DataRoot.Root->Props;
        Self->RawThis = 0;
    }else{
        Self->RawThis = Base;
        if (Base->LastPs->p->PropertyType==LA_PROP_SUB && ((laSubProp*)Base->LastPs->p)->GetType && Base->EndInstance){
            laPropContainer* pc=((laSubProp*)Base->LastPs->p)->GetType(Base->EndInstance);
            lst = &pc->Props;
            lstB = pc ? &pc->Props : 0;
        }
        if(!lst){
            if (!Base->LastPs->p->SubProp){
                laProp *p = Base->LastPs->p;
                p->SubProp = la_ContainerLookup(((laSubProp *)p)->TargetID);
            }
            if(Base->LastPs->p->SubProp) lst = &Base->LastPs->p->SubProp->Props;
        }
        lstB = Base->LastPs->p->SubExtra ? &Base->LastPs->p->SubExtra->Props : 0;

        if (!Path || !Path[0] || !ss){
            if (Base){
                Self->LastPs = Base->LastPs;
                //Self->ReusedPs = 1;
                //la_NewPropStep(Self, Base->LastPs->p,Base->LastPs->UseInstance,Base->LastPs->Type);
            }
        }
    }
    while (sp){
        if (sp->Type == U'.' || sp->Type == U'$'){
            void *inst = 0;
            p = la_PropLookup(lst, sp->Content); 
            if (!p) p = la_PropLookup(lstB, sp->Content);
            if (!p){
                la_FreePropStepCache(Self->Go);
                Self->Go = Self->LastPs = 0;
                strDestroyStringSplitor(&ss);
                return 0; //          |-----------------Here Should Include Dollar Instance
            }             //                      V
            if (sp->Type == U'$'){
                inst = SpecifiedInstance[InstanceNum];
                InstanceNum++;
            }else
                inst = 0;
            /*if(Base == &MAIN.PropMatcherContextP->PropLinkPP)la_NewPropStep(Self, p, inst, '*');
			else */
            la_NewPropStep(Self, p, inst, sp->Type);
            if (p->PropertyType == LA_PROP_SUB && !p->SubProp){
                p->SubProp = la_ContainerLookup(((laSubProp *)p)->TargetID);
            }
            lst = p->SubProp ? &p->SubProp->Props : 0;
            lstB = p->SubExtra ? &p->SubExtra->Props : 0;
        }else{
            if (sp->Type == U'@' || sp->Type == U'=' || sp->Type == U'#'){ // || sp->Type== U'~'
                la_NewPropStep(Self, sp->Content, 0, sp->Type);
            }
        }
        sp = sp->Item.pNext;
    }

    strDestroyStringSplitor(&ss);

    return 1;
}
void la_StepPropPack(laPropPack *pp){
    laPropStep *ps = pp->Go;
    laPropPack *This = pp->RawThis;
    laPropIterator pi;
    laProp *Lookup;
    laPropStep *Value;
    void *UseInstance = 0;

    if (This){
        UseInstance = This->EndInstance;
        if (ps) ps->UseInstance = UseInstance;
    }else{
        if (!ps) return;
        UseInstance = MAIN.DataRoot.RootInstance;
        ps->UseInstance = UseInstance;
    }

    if (This && !ps){
        pp->EndInstance = UseInstance;
        pp->LastPs = This->LastPs;
        return;
    }

    while (ps){
        // Looks like we have these kind of access grammar:
        // sub.prop
        // sub@prop=str_or_int
        // sub#identifier
        // TODO: Add sub~index grammar
        if (ps->p->PropertyType == LA_PROP_SUB){
            if (ps->Type == U'@' || ps->Type == U'#'){
            }
            if (ps->Type == U'$') UseInstance = ps->UseInstance;
            elif (ps->pNext && ps->pNext->Type != U'.'){
                if (ps->pNext->Type == U'@'){
                    Value = ps->pNext->pNext;
                    Lookup = la_PropLookup(&ps->p->SubProp->Props, ps->pNext->p);
                }elif (ps->pNext->Type == U'#'){
                    Value = ps->pNext;
                    Lookup = la_PropLookupIdentifierItem(&ps->p->SubProp->Props);
                }
                if (Value->Type == U'=' || Value->Type == U'#'){ //MUST!
                    UseInstance = la_FindMatchingInstance(ps->UseInstance, ps->p, Lookup, Value);
                }
                Value->UseInstance = UseInstance;
                if(Value->pNext) Value->pNext->UseInstance = UseInstance;
                ps = Value->pNext;
                continue;
            }else{
                void *inst;
                if(((laSubProp*)ps->p)->IsDetached){ UseInstance = ((laSubProp*)ps->p)->Detached; }
                else{
                    inst = laGetActiveInstanceStrict(ps->p, UseInstance);
                    if (!inst) inst = laGetInstance(ps->p, UseInstance, 0);
                    UseInstance = inst;
                }
            }
            if (!ps->pNext){
                pp->EndInstance = UseInstance;
                break;
            }else{
                ps->pNext->UseInstance = UseInstance;
                ps = ps->pNext;
            }
            continue;
        }else{
            ps->UseInstance = UseInstance;
            if (!ps->pNext){
                pp->EndInstance = UseInstance;
                break;
            }else{
                ps->pNext->UseInstance = ps;
                UseInstance = ps;
                ps = ps->pNext;
            }
        }
    }
}

void la_RemovePropUserNode(laPropStep *ps){
    laPropUserPanel *pup = 0;
    laPropUser *pu = 0;
    for (pup = ps->p->UserPanels.pFirst; pup; pup = pup->Item.pNext){
        if (pup->Panel == MAIN.PropMatcherContextP) break;
    }
    if (!pup) return;
    for (pu = pup->UserPacks.pFirst; pu; pu = pu->Item.pNext){
        if (pu->User == ps) break;
    }
    //if (!pu)printf("PROP USER NODE NOT FOUND!\laPropUserPanel:%d,%s,Ps:%s\n",pup->Panel,pup->Panel->Title->Ptr,ps->p->Identifier);
    //else {
    if (pu){
        lstRemoveItem(&pup->UserPacks, pu);
        memFree(pu);
        if (!pup->UserPacks.pFirst){
            lstRemoveItem(&ps->p->UserPanels, pup);
            memFree(pup);
        }
    }
    //}
}
void la_AddPropUserNode(laPropStep *ps){
    laPropUserPanel *pup = 0;
    laPropUser *pu = 0;
    for (pup = ps->p->UserPanels.pFirst; pup; pup = pup->Item.pNext){
        if (pup->Panel == MAIN.PropMatcherContextP) break;
    }
    if (!pup){
        pup = memAcquireSimple(sizeof(laPropUserPanel));
        pup->Panel = MAIN.PropMatcherContextP;
        lstAppendItem(&ps->p->UserPanels, pup);
    }
    for (pu = pup->UserPacks.pFirst; pu; pu = pu->Item.pNext){
        if (pu->User == ps){
            pu->FrameDistinguish = MAIN.PropMatcherContextP->FrameDistinguish;
            return;
        }
    }
    //ELSE
    pu = memAcquireSimple(sizeof(laPropUser));
    pu->User = ps;
    pu->FrameDistinguish = MAIN.PropMatcherContextP->FrameDistinguish;
    lstAppendItem(&pup->UserPacks, pu);
}
void la_UsePropPack(laPropPack *pp, int ForceRecalc){
    laPropStep *ps = 0;
    //if(pp->LastPs && pp->LastPs->p)printf("%s\n",pp->LastPs->p->Identifier);
    if((!pp->Go) && pp->LastPs){
        if (pp->LastPs->Type==U'.'){
            laUseDataBlock(pp->RawThis->LastPs->UseInstance, pp->LastPs->p, MAIN.PropMatcherContextP->FrameDistinguish, MAIN.PropMatcherContextP, la_PropPanelUserRemover, ForceRecalc);
        }
    }
    for (ps = pp->Go; ps; ps = ps->pNext){
        if (ps->Type==U'.'){
            laUseDataBlock(ps->UseInstance, ps->p, MAIN.PropMatcherContextP->FrameDistinguish, MAIN.PropMatcherContextP, la_PropPanelUserRemover, ForceRecalc);
        }
    }
}
void la_StopUsingPropPack(laPropPack *pp){
    laPropStep *ps;
    if((!pp->Go) && pp->LastPs){
        if (pp->LastPs->Type==U'.'&&pp->LastPs->p->Container &&pp->LastPs->p->Container->Hyper){
            laStopUsingDataBlock(pp->RawThis->LastPs->UseInstance, pp->LastPs->p, MAIN.PropMatcherContextP);
        }
    }
    for (ps = pp->Go; ps; ps = ps->pNext){
        if (ps->Type==U'.'&&ps->p->Container&&ps->p->Container->Hyper){
            laStopUsingDataBlock(ps->UseInstance, ps->p, MAIN.PropMatcherContextP);
        }
        //la_RemovePropUserNode(ps);
    }
}

void laNotifyUsersPP(laPropPack *pp){
    if(!pp->LastPs) return;
    void *hi = pp->LastPs->UseInstance;
    laItemUserLinker *iul; laItemUserLinkerLocal *iull; int local;
    if (!hi) return;
    laListHandle* users = laGetUserList(hi, pp->LastPs->p, &local); if(!users) return;
    for (iul = users->pFirst; iul; iul = iul->Pointer.pNext){
        if(local && (iull=iul) && iull->Instance!=hi) continue;
        if (iul->Remove == la_PropPanelUserRemover){
            laPanel *p = iul->Pointer.p;
            if (iul->Which == pp->LastPs->p && iul->FrameDistinguish == p->FrameDistinguish){
                //laSpinLock(&MAIN.csNotifier);
                if ((iul->Which->PropertyType & LA_PROP_SUB) || iul->ForceRecalc) laRecalcPanel(p);
                else laRedrawPanel(p);
                //laSpinUnlock(&MAIN.csNotifier);
            }
        }
    }
}
void laNotifyUsersPPPath(laPropPack *pp, char *path){
    laPropPack PP = {0};
    if(!path){ laNotifyUsersPP(pp); return; }
    la_GetPropFromPath(&PP, pp, path, 0);
    la_StepPropPack(&PP);
    laNotifyUsersPP(&PP);
    la_FreePropStepCache(PP.Go);
}
void laNotifySubPropUsers(laProp *prop, void *Instance){
    void *hi = Instance;
    laItemUserLinker *iul; laItemUserLinkerLocal *iull; int local;
    if (!hi) return;
    laListHandle* users = laGetUserList(hi, prop, &local); if(!users) return;
    for (iul = users->pFirst; iul; iul = iul->Pointer.pNext){
        if(local && (iull=iul) && iull->Instance!=hi) continue;
        if (iul->Remove == la_PropPanelUserRemover){
            laPanel *p = iul->Pointer.p;
            if (iul->Which == prop && iul->FrameDistinguish == p->FrameDistinguish){
                //laSpinLock(&MAIN.csNotifier);
                laRecalcPanel(p);
                //laSpinUnlock(&MAIN.csNotifier);
            }
        }
    }
}
void laNotifyInstanceUsers(void *Instance){
    void *hi = Instance;
    laItemUserLinker *iul; laItemUserLinkerLocal *iull; int local; if (!hi) return;
    laListHandle* users = laGetUserList(hi, 0, &local); if(!users) return;
    for (iul = users->pFirst; iul; iul = iul->Pointer.pNext){
        if(local && (iull=iul) && iull->Instance!=hi) continue;
        if (iul->Remove == la_PropPanelUserRemover){
            laPanel *p = iul->Pointer.p;
            if (iul->FrameDistinguish == p->FrameDistinguish){
                laRedrawPanel(p);
                if(iul->Which&&iul->Which->PropertyType==LA_PROP_SUB){ laRecalcPanel(p); }
            }
        }
    }
}
void laNotifyUsers(char *Path){
    laPropPack PP = {0};
    la_GetPropFromPath(&PP, 0, Path, 0);
    la_StepPropPack(&PP);
    laNotifyUsersPP(&PP);
    la_FreePropStepCache(PP.Go);
}
void laThreadNotifyUsers(char *Path){
    laThreadNotifier *tn = CreateNew(laThreadNotifier);
    strCopyFull(tn->Path, Path);

    //laSpinLock(&MAIN.csNotifier);
    lstAppendItem(&MAIN.ThreadNotifiers, tn);
    //laSpinUnlock(&MAIN.csNotifier);
}
void la_PanelResetDetachedReference(laPanel*p,void*Old,void*New){
    for(laSubProp* sp=p->PropLinkContainer->Props.pFirst;sp;sp=sp->Base.Item.pNext){
        if(sp->Base.PropertyType!=LA_PROP_SUB) continue;
        if(sp->Detached == Old){ memAssignRef(sp, &sp->Detached, New); }
    }
    for(laPanel* sp=p->SubPanels.pFirst;sp;sp=sp->Item.pNext){
        la_PanelResetDetachedReference(sp,Old,New);
    }
}
void la_NotifyDetachedRecursive(laBlock* b, void* Old, void* New){
    if(b->B1){ la_NotifyDetachedRecursive(b->B1,Old,New);la_NotifyDetachedRecursive(b->B2,Old,New); return; }
    for(laPanel* p=b->Panels.pFirst;p;p=p->Item.pNext){
        la_PanelResetDetachedReference(p,Old,New);
    }
}
void laNotifyDetached(void* OldInstance, void* NewInstance){
    for(laWindow* w=MAIN.Windows.pFirst;w;w=w->Item.pNext){
        for(laLayout* l=w->Layouts.pFirst;l;l=l->Item.pNext){
            la_NotifyDetachedRecursive(l->FirstBlock,OldInstance,NewInstance);
        }
        for(laPanel* p=w->Panels.pFirst;p;p=p->Item.pNext){
            la_PanelResetDetachedReference(p,OldInstance,NewInstance);
        }
    }
}
void laDetachedTrySet(char* prop_identifier,void* NewInstance){
    laPanel* p=MAIN.CurrentPanel; for(laSubProp* sp=p->PropLinkContainer->Props.pFirst;sp;sp=sp->Base.Item.pNext){
        if(sp->Base.PropertyType!=LA_PROP_SUB){ continue; }
        if(strSame(sp->Base.Identifier,prop_identifier)){ memAssignRef(sp,&sp->Detached,NewInstance); }
    }
}

void la_SetPropMathcerContext(laPanel *p){
    MAIN.PropMatcherContextP = p;
}

int laget_InstanceHyperLevel(void* instance){
    int level; memGetHead(instance,&level);
    return level;
}
int laget_InstanceModified(void* instance){
    int level; laMemNodeHyper* m=memGetHead(instance,&level);
    if(level==2) return m->Modified?1:0;
    return 0;
}
void* laget_InstanceUDF(void* unused, laPropIterator* unusedpi){
    return MAIN.ManagedUDFs.pFirst;
}
void* laget_InstanceActiveUDF(void* instance){
    int level; laMemNodeHyper* m=memGetHead(instance,&level);
    if(level==2) return m->FromFile;
    return 0;
}
void* laget_DummyManagedUDFSingle(void* unused){
    return MAIN.DummyManageUDFSingle;
}
void* laget_DummyManagedUDFSingleForce(void* unused){
    return MAIN.DummyManageUDFSingleForce;
}
void laset_InstanceUDFFromSingle(void* instance, laUDF* udf){
    if(!MAIN._CONTAINER_SETTING || !MAIN._CONTAINER_SETTING->UDFPropagate || !instance){ return; }
    if(udf == MAIN.DummyManageUDF){
        laInvoke(0, "LA_managed_save_new_file", 0,0,0,0);
    }
    MAIN._CONTAINER_SETTING->UDFPropagate(instance,udf,0);
}
void laset_InstanceUDFFromSingleForce(void* instance, laUDF* udf){
    if(!MAIN._CONTAINER_SETTING || !MAIN._CONTAINER_SETTING->UDFPropagate || !instance){ return; }
    if(udf == MAIN.DummyManageUDF){
        laInvoke(0, "LA_managed_save_new_file", 0,0,0,0);
    }
    MAIN._CONTAINER_SETTING->UDFPropagate(instance,udf,0);
}
void laset_InstanceUDF(void* instance, void* set){
    int level; laMemNodeHyper* m=memGetHead(instance,&level);
    if(level==2) memAssignRef(instance, &m->FromFile, set);
    if(set == MAIN.DummyManageUDF){
        laInvoke(0, "LA_managed_save_new_file", 0,0,0,0);
    }
}
void* laget_InstanceSelf(void* instace){
    return instace;
}
const char* LA_N_A="N/A";
void *la_GetReadDBInstNUID(char *ReferReadNUID);
void laget_InstanceUID(void* instance, char* buf, char** ptr){
    int level; laMemNodeHyper* m=memGetHead(instance,&level);
    if(level!=2||!m) return; *ptr=LA_N_A;
    *ptr=m->NUID.String;
}
void laset_InstanceUID(void* instance, char* buf){
    int level; laMemNodeHyper* m=memGetHead(instance,&level);
    if(level!=2||!m) return;
    char _buf[40];
    if(!buf[0]){ memCreateNUID(_buf,m); buf=_buf; }
    laListHandle *l = hsh65536DoHashNUID(&MAIN.DBInst2, m->NUID.String);
    laMemNodeHyper* im=0;
    for (im = l->pFirst; im; im = m->Item.pNext){ if(im==m) break; }
    if(im){ lstRemoveItem(l,im); laListHandle *nl = hsh65536DoHashNUID(&MAIN.DBInst2, buf); lstAppendItem(nl,im); }else{ im=m; /* Unlikely */ }
    sprintf(m->NUID.String,"%.30s",buf);
}
void* laget_SaverDummy(void* instance, laPropIterator* pi){
    laSubProp* p=MAIN._PROP_SETTING; laListHandle* l = (((char*)instance)+p->ListHandleOffset);
    if(!l->pFirst){
        laSaverDummy* sd=memAcquireHyper(sizeof(laSaverDummy)); lstAppendItem(l,sd);
    }
    while(l->pFirst!=l->pLast){ memLeave(lstPopItem(l)); }
    return l->pFirst;
}
laSaverDummy* laGetSaverDummy(void* instance, laSubProp* p){
    laListHandle* l = (((char*)instance)+p->ListHandleOffset);
    if(!l->pFirst){ laSaverDummy* sd=memAcquireHyper(sizeof(laSaverDummy)); lstAppendItem(l,sd); }
    while(l->pFirst!=l->pLast){ memLeave(lstPopItem(l)); }
    return l->pFirst;
}
void laPurgeSaverDummy(void* instance, laSubProp* p){
    laListHandle* l = (((char*)instance)+p->ListHandleOffset);
    while(l->pFirst){ memLeave(lstPopItem(l)); }
}
void la_FreeProperty(laProp* p){
    laIntProp *ip;laFloatProp *fp;laEnumProp *ep;laSubProp *sp;
    if(p->DetachedPP.Go){
        la_FreePropStepCache(p->DetachedPP.Go);
        switch (p->PropertyType){
        case LA_PROP_INT:
        case LA_PROP_INT | LA_PROP_ARRAY:
            ip = p; free(ip->Detached);
            break;
        case LA_PROP_FLOAT:
        case LA_PROP_FLOAT | LA_PROP_ARRAY:
            fp = p; free(fp->Detached);
            break;
        case LA_PROP_ENUM:
        case LA_PROP_ENUM | LA_PROP_ARRAY:
            ep = p; free(ep->Detached);
        }
    }
    if(p->PropertyType&LA_PROP_ENUM){ ep = p; laEnumItem* ei;  while(ei=lstPopItem(&ep->Items)){ memFree(ei); } }
    memFree(p);
}
void la_FreePropertyContainer(laPropContainer* pc){
    laProp* p;
    while(p=lstPopItem(&pc->Props)){
        la_FreeProperty(p);
    }
    memFree(pc);
}
laPropContainer *laAddPropertyContainer(const char *Identifier, const char *Name, const char *Description, uint32_t IconID,
                                        laUiDefineFunc DefaultUiDefine,
                                        int NodeSize, laContainerPostReadFunc PostRead, laContainerPostReadFunc PostReadIm, int IsHyper){

    laPropContainer *pc = memAcquire(sizeof(laPropContainer));
    pc->Identifier = Identifier;
    pc->Name = Name;
    pc->Description = Description;
    pc->UiDefine = DefaultUiDefine;
    pc->IconID = IconID ? IconID : U'📦';

    pc->OtherAlloc = (IsHyper&LA_PROP_OTHER_ALLOC)?1:0;
    pc->Hyper = pc->OtherAlloc?0:(IsHyper&LA_PROP_HYPER_BITS);
    pc->PostRead = PostRead;
    pc->PostReadIm = PostReadIm;
    pc->NodeSize = NodeSize;

    if (!pc->OtherAlloc){
        laAddSubGroup(pc, "__file", "File", "The file this block came from/saves to", "managed_udf",
            0,LA_WIDGET_COLLECTION_SELECTOR,laui_ManagedUDFItem,-1,laget_InstanceUDF,laget_InstanceActiveUDF,laget_ListNext,laset_InstanceUDF,0,0,0,LA_UDF_REFER|LA_UDF_IGNORE);
        laAddIntProperty(pc, "__hyper", "Hyper", "Hyper level of this data block", 0,0,0,0,0,0,0,0,-1,laget_InstanceHyperLevel,0,0,0,0,0,0,0,0,0,LA_READ_ONLY|LA_UDF_IGNORE);
        laProp* p=laAddEnumProperty(pc, "__modified", "Modified", "Data block is modified", LA_WIDGET_ENUM_ICON_PLAIN,0,0,0,0,-1,laget_InstanceModified,0,0,0,0,0,0,0,0,LA_READ_ONLY|LA_UDF_IGNORE);
        laAddEnumItemAs(p, "MODIFIED", "Modified", "Data block is modified", 1, U'🌑');
        laAddEnumItemAs(p, "CLEAN", "Clean", "Data block is clean", 0, 0);
        laAddStringProperty(pc, "__uid","UID","UID for shared resoure lookup",0,0,0,0,0,-1,0,laget_InstanceUID,laset_InstanceUID,0,LA_UDF_IGNORE);
    }

    laAddSubGroup(pc, "__self", "Self", "Own instance", Identifier,0,0,0,-1,0,laget_InstanceSelf,0,0,0,0,0,LA_UDF_REFER|LA_UDF_IGNORE);   
    lstAppendItem(&MAIN.PropContainers, pc);

    return pc;
}
void laPropContainerExtraFunctions(laPropContainer* pc, laContainerBeforeFreeF BeforeFree, laContainerResetF Reset, laContainerUndoTouchedF Touched, laContainerpUDFPropagateF UDFPropagate, laUiDefineFunc MenuUi){
    pc->BeforeFree=BeforeFree; pc->Reset=Reset; pc->UndoTouched=Touched; pc->UDFPropagate=UDFPropagate; pc->MenuUiDefine=MenuUi;
    if(!pc->OtherAlloc && UDFPropagate){
        laAddOperatorProperty(pc,"__udf_propagate","Propagate","Propagate UDF to all child nodes", "LA_udf_propagate", 0,0);
        laAddSubGroup(pc,"__single_udf_propagate","Save to","Assign file to all child nodes (From a ingle-instanced parent)","managed_udf",
            0,LA_WIDGET_COLLECTION_SELECTOR,laui_ManagedUDFItem,-1,laget_InstanceUDF,laget_DummyManagedUDFSingle,laget_ListNext,laset_InstanceUDFFromSingle,0,0,0,LA_UDF_REFER|LA_UDF_IGNORE);
        //laAddSubGroup(pc,"__single_udf_propagate_force","Force","Assign file to all child nodes (From a ingle-instanced parent)","managed_udf",
        //    0,LA_WIDGET_COLLECTION_SELECTOR,laui_ManagedUDFItem,-1,laget_InstanceUDF,laget_DummyManagedUDFSingleForce,laget_ListNext,laset_InstanceUDFFromSingleForce,0,0,0,LA_UDF_REFER|LA_UDF_IGNORE);
    
    }
}
laProp* laPropContainerManageable(laPropContainer* pc, int offset_of_dummy_list){
    if(!pc || pc->OtherAlloc || !offset_of_dummy_list) return 0;

    if(!MAIN.SaverDummyContainer){
        MAIN.SaverDummyContainer = laAddPropertyContainer("la_saver_dummy","Saver Dummy","Saver dummy",0,0,sizeof(laSaverDummy),0,0,2);
        laAddSubGroup(MAIN.SaverDummyContainer, "__file", "File", "The file this block came from/saves to", "managed_udf",
            0,LA_WIDGET_COLLECTION_SELECTOR,laui_ManagedUDFItem,-1,laget_InstanceUDF,laget_InstanceActiveUDF,laget_ListNext,laset_InstanceUDF,0,0,0,LA_UDF_REFER|LA_UDF_IGNORE);
    }
    pc->SaverDummy=laAddSubGroup(pc,"__single_saver_dummy","Saver","Saver dummy","la_saver_dummy",0,0,0,-1,0,0,0,0,0,0,offset_of_dummy_list,0);
    return pc->SaverDummy;
}

void laContainerAnimationFunctions(laPropContainer* pc, laActionHolderVerifyF ActionHolderVerify){
    pc->ActionHolderVerify=ActionHolderVerify;
}

int la_GetKeyablePropertyStorageSize(laProp* p){
    switch(p->PropertyType){
    case LA_PROP_INT: case LA_PROP_FLOAT: case LA_PROP_ENUM:
        return sizeof(uint64_t);
    case LA_PROP_INT | LA_PROP_ARRAY: case LA_PROP_FLOAT | LA_PROP_ARRAY: case LA_PROP_ENUM | LA_PROP_ARRAY:
        if(p->GetLen){ return 0; }
        return sizeof(uint64_t)*p->Len;
    case LA_PROP_SUB: case LA_PROP_OPERATOR: case LA_PROP_STRING: case LA_PROP_RAW: default:
        return 0;
    }
}

int la_GetPropertySize(int Type){
    switch (Type){
    case LA_PROP_INT:
    case LA_PROP_INT | LA_PROP_ARRAY:
        return sizeof(laIntProp);
    case LA_PROP_FLOAT:
    case LA_PROP_FLOAT | LA_PROP_ARRAY:
        return sizeof(laFloatProp);
    case LA_PROP_ENUM:
    case LA_PROP_ENUM | LA_PROP_ARRAY:
        return sizeof(laEnumProp);
    case LA_PROP_SUB: return sizeof(laSubProp);
    case LA_PROP_OPERATOR: return sizeof(laOperatorProp);
    case LA_PROP_STRING: return sizeof(laStringProp);
    case LA_PROP_RAW: return sizeof(laRawProp);
    }
    return 0;
}
const char LA_PROP_STR_INT[] = "LA_PROP_INT";
const char LA_PROP_STR_INT_ARR[] = "LA_PROP_INT_ARR";
const char LA_PROP_STR_FLOAT[] = "LA_PROP_FLOAT";
const char LA_PROP_STR_FLOAT_ARR[] = "LA_PROP_FLOAT_ARR";
const char LA_PROP_STR_ENUM[] = "LA_PROP_ENUM";
const char LA_PROP_STR_ENUM_ARR[] = "LA_PROP_ENUM_ARR";
const char LA_PROP_STR_ACT[] = "LA_PROP_ACT";
const char LA_PROP_STR_STR[] = "LA_PROP_STR";
const char LA_PROP_STR_SUB[] = "LA_PROP_SUB";

const char *la_GetPropertyTypeString(int Type){
    switch (Type){
    case LA_PROP_INT:
        return LA_PROP_STR_INT;
    case LA_PROP_INT | LA_PROP_ARRAY:
        return LA_PROP_STR_INT_ARR;
    case LA_PROP_FLOAT:
        return LA_PROP_STR_FLOAT;
    case LA_PROP_FLOAT | LA_PROP_ARRAY:
        return LA_PROP_STR_FLOAT_ARR;
    case LA_PROP_ENUM:
        return LA_PROP_STR_ENUM;
    case LA_PROP_ENUM | LA_PROP_ARRAY:
        return LA_PROP_STR_ENUM_ARR;
    case LA_PROP_SUB:
        return LA_PROP_STR_SUB;
    case LA_PROP_OPERATOR:
        return LA_PROP_STR_ACT;
    case LA_PROP_STRING:
        return LA_PROP_STR_STR;
    }
    return 0;
}

void la_AssignPropertyGeneralSub(laProp *p){
    switch (p->PropertyType){
    case LA_PROP_INT: p->SubProp = MAIN.GeneralIntSub; break;
    case LA_PROP_INT | LA_PROP_ARRAY: p->SubProp = MAIN.GeneralIntArraySub;  break;
    case LA_PROP_FLOAT: p->SubProp = MAIN.GeneralFloatSub; break;
    case LA_PROP_FLOAT | LA_PROP_ARRAY: p->SubProp = MAIN.GeneralFloatArraySub; break;
    case LA_PROP_ENUM: p->SubProp = MAIN.GeneralEnumSub; break;
    case LA_PROP_ENUM | LA_PROP_ARRAY: p->SubProp = MAIN.GeneralEnumArraySub; break;
    case LA_PROP_STRING: p->SubProp = MAIN.GeneralStringSub; break;
    case LA_PROP_OPERATOR: p->SubProp = MAIN.GeneralOperatorSub; break;
    case LA_PROP_SUB: p->SubExtra = MAIN.GeneralCollectionSub; break;
    case LA_PROP_RAW: p->SubExtra = MAIN.GeneralRawSub; break;
    }
}

laProp *la_CreateProperty(laPropContainer *Container, int Type, const char *Identifier, const char *Name, const char *Description,
                          const char *Prefix, const char *Unit, laWidget* DefaultWidget, u64bit Tag){
    laProp *p = memAcquire(la_GetPropertySize(Type));

    p->Identifier = Identifier;
    p->Name = Name;
    p->Description = Description;
    p->Prefix = Prefix;
    p->Unit = Unit;
    if(DefaultWidget){ p->DefaultUiType = DefaultWidget->Type; p->DefaultFlags = DefaultWidget->Flags; }
    p->PropertyType = Type;
    p->Tag = Tag;
    p->Container = Container;

    if (Container) lstAppendItem(&Container->Props, p);

    p->UDFIsRefer = (Tag & LA_UDF_REFER) ? 1 : 0;
    p->UDFIgnore = (Tag & LA_UDF_IGNORE) ? 1 : 0;
    p->UDFOnly = (Tag & LA_UDF_ONLY) ? 1 : 0;
    p->ReadOnly = (Tag & LA_READ_ONLY) ? 1 : 0;
    p->IsRadAngle = (Tag & LA_RAD_ANGLE)? 1 : 0;
    p->UDFHideInSave = ((Tag & LA_HIDE_IN_SAVE) || p->UDFIgnore)? 1 : 0;
    p->UDFReadProgress = (Tag & LA_PROP_READ_PROGRESS)?1:0;
    p->CanTranslate = (Tag & LA_TRANSLATE)?1:0;
    if(p->IsRadAngle&&(!p->Unit)) p->Unit="°"; 
    p->Keyable = (Tag & LA_PROP_KEYABLE)? 1 : 0;
    if(Tag&LA_PROP_ROTATION){ p->KeySpecialInterpolation=LA_PROP_KEY_INTERPOLATION_ROTATION; }

    return p;
}
void la_ClearDetachedProp(laPanel* p){
    laProp *np; while(np=lstPopItem(&p->PropLinkContainer->Props)){ free(np->Identifier); memFree(np); }
}
laProp *la_MakeDetachedProp(laPanel* p, const char *From, const char *Rename){
    laIntProp *ip;
    laFloatProp *fp;
    laEnumProp *ep;
    laSubProp *sp;

    laPropPack TempPP = {0};
    int result = 0;

    result = la_GetPropFromPath(&TempPP, 0, From, 0);
    if(!result) return 0;
    
    laProp *np = memAcquire(la_GetPropertySize(TempPP.LastPs->p->PropertyType));
    memcpy(np, TempPP.LastPs->p, la_GetPropertySize(TempPP.LastPs->p->PropertyType));

    np->Identifier = CreateNewBuffer(char, 128);
    strcpy(np->Identifier, Rename);
    np->DetachedPP.Go = 0;
    np->DetachedPP.RawThis = 0;
    np->DetachedPP.LastPs = 0;
    la_CopyPropPack(&TempPP, &np->DetachedPP);

    switch (np->PropertyType){
    case LA_PROP_INT:
    case LA_PROP_INT | LA_PROP_ARRAY:
        ip = np; if(!np->Len){ np->Len=1; }
        ip->Detached = CreateNewBuffer(int, np->Len);
        for(int i=0;i<np->Len;i++){ ((int*)ip->Detached)[i]=ip->DefVal; }
        break;
    case LA_PROP_FLOAT:
    case LA_PROP_FLOAT | LA_PROP_ARRAY:
        fp = np; if(!np->Len){ np->Len=1; }
        fp->Detached = CreateNewBuffer(real, np->Len);
        for(int i=0;i<np->Len;i++){ ((real*)fp->Detached)[i]=fp->DefVal; }
        break;
    case LA_PROP_ENUM:
    case LA_PROP_ENUM | LA_PROP_ARRAY:
        ep = np;
        ep->Detached = CreateNewBuffer(int, 1);
        ep->Detached[0] = ep->DefVal;
        break;
    case LA_PROP_SUB:
        sp=np; sp->GetCategory=((laSubProp*)np)->GetCategory;
        sp->IsDetached=1;
        break;
    }
    lstAppendItem(&p->PropLinkContainer->Props, np);
    la_AssignPropertyGeneralSub(np);
    la_FreePropStepCache(TempPP.Go);
    return np;
}
laProp *laAddIntProperty(laPropContainer *Container, const char *Identifier, const char *Name, const char *Description, laWidget* DefaultWidget,
                         const char *Prefix, const char *Unit, int Max, int Min, int Step, int DefVal, const int *DefArr,
                         int OffsetSize, laIntGetF Get, laIntSetF Set, int ArrayLength, laArrayGetLenF GetLen,
                         laIntArraySetF SetArr, laIntArrayGetAllF GetAll, laIntArraySetAllF SetAll, laIntArraySetAllArrayF SetAllArr,
                         laIntReadF Read, laIntArrayReadAllF ReadAll,
                         u64bit Tag){

    laIntProp *p = la_CreateProperty(Container, LA_PROP_INT, Identifier, Name, Description, Prefix, Unit, DefaultWidget, Tag);

    if (ArrayLength > 1){
        p->Base.Len = ArrayLength;
        p->Base.PropertyType |= LA_PROP_ARRAY;
    }else if (GetLen)
        p->Base.GetLen = GetLen;

    p->Get = Get;
    p->Set = Set;
    p->SetAll = SetAll;
    p->GetAll = GetAll;
    p->SetAllArr = SetAllArr;
    p->SetArr = SetArr;
    p->DefArr = DefArr;
    p->DefVal = DefVal;
    p->Max = Max;
    p->Min = Min;
    p->Step = Step ? Step : 1;
    p->Base.Offset = OffsetSize;
    p->Base.OffsetIsPointer = (Tag&LA_UDF_REFER) ? 1 : 0;

    p->Read = Read;
    p->ReadAll = ReadAll;

    la_AssignPropertyGeneralSub(p);

    return p;
}

laProp *laAddFloatProperty(laPropContainer *Container, const char *Identifier, const char *Name, const char *Description, laWidget* DefaultWidget,
                           const char *Prefix, const char *Unit, real Max, real Min, real Step, real DefVal, const real *DefArr,
                           int OffsetSize, laFloatGetF Get, laFloatSetF Set, int ArrayLength, laArrayGetLenF GetLen,
                           laFloatArraySetF SetArr, laFloatArrayGetAllF GetAll, laFloatArraySetAllF SetAll, laFloatArraySetAllArrayF SetAllArr,
                           laFloatReadF Read, laFloatArrayReadAllF ReadAll,
                           u64bit Tag){

    laFloatProp *p = la_CreateProperty(Container, LA_PROP_FLOAT, Identifier, Name, Description, Prefix, Unit, DefaultWidget, Tag);

    if (ArrayLength > 1){
        p->Base.Len = ArrayLength;
        p->Base.PropertyType |= LA_PROP_ARRAY;
    }else if (GetLen)
        p->Base.GetLen = GetLen;

    p->Get = Get;
    p->Set = Set;
    p->SetAll = SetAll;
    p->GetAll = GetAll;
    p->SetAllArr = SetAllArr;
    p->SetArr = SetArr;
    p->DefArr = DefArr;
    p->DefVal = DefVal;
    p->Max = Max;
    p->Min = Min;
    p->Step = Step ? Step : 0.01;

    p->Base.Offset = OffsetSize;
    p->Base.OffsetIsPointer = (Tag&LA_UDF_REFER) ? 1 : 0;

    p->Read = Read;
    p->ReadAll = ReadAll;

    la_AssignPropertyGeneralSub(p);

    return p;
}

laProp *laAddEnumProperty(laPropContainer *Container, const char *Identifier, const char *Name, const char *Description, laWidget* DefaultWidget,
                          const char *Prefix, const char *Unit, int DefVal, const int *DefArr,
                          int OffsetSize, laEnumGetF Get, laEnumSetF Set, int ArrayLength, laArrayGetLenF GetLen,
                          laEnumArraySetF SetArr, laEnumArrayGetAllF GetAll, laEnumArraySetAllF SetAll,
                          laEnumReadF Read, laEnumArrayReadAllF ReadAll,
                          u64bit Tag){

    laEnumProp *p = la_CreateProperty(Container, LA_PROP_ENUM, Identifier, Name, Description, Prefix, Unit, DefaultWidget, Tag);

    if (ArrayLength > 1){
        p->Base.Len = ArrayLength;
        p->Base.PropertyType |= LA_PROP_ARRAY;
    }else if (GetLen)
        p->Base.GetLen = GetLen;

    p->Get = Get;
    p->Set = Set;
    p->SetAll = SetAll;
    p->GetAll = GetAll;
    p->SetArr = SetArr;
    p->DefArr = DefArr;
    p->DefVal = DefVal;

    p->Base.Offset = OffsetSize;
    p->Base.OffsetIsPointer = (Tag&LA_UDF_REFER) ? 1 : 0;

    p->Read = Read;
    p->ReadAll = ReadAll;

    la_AssignPropertyGeneralSub(p);

    return p;
}

int laAddEnumItem(laProp *p, const char *Identifier, const char *Name, const char *Description, uint32_t IconID){
    laEnumItem *ei = memAcquire(sizeof(laEnumItem));
    laEnumProp *ep = p;

    ei->Identifier = Identifier;
    ei->Name = Name;
    ei->Description = Description;
    ei->IconID = IconID;

    ei->Index = ep->Items.pLast ? ((laEnumItem *)ep->Items.pLast)->Index + 1 : 0;

    lstAppendItem(&ep->Items, ei);

    return 1;
}

int laAddEnumItemAs(laProp *p, const char *Identifier, const char *Name, const char *Description, int Index, uint32_t IconID){
    laEnumItem *ei = memAcquire(sizeof(laEnumItem));
    laEnumProp *ep = p;

    ei->Identifier = Identifier;
    ei->Name = Name;
    ei->Description = Description;
    ei->IconID = IconID;

    ei->Index = Index;

    lstAppendItem(&ep->Items, ei);

    return 1;
}

laProp *laAddStringProperty(laPropContainer *Container, const char *Identifier, const char *Name, const char *Description, laWidget* DefaultWidget,
                            const char *Prefix, const char *Unit, const char *DefStr,
                            int IsSafeString, int OffsetSize, laStringGetLenF GetLen, laStringGetF Get, laStringSetF Set,
                            laStringReadF Read,
                            u64bit Tag){

    laStringProp *p = la_CreateProperty(Container, LA_PROP_STRING, Identifier, Name, Description, Prefix, Unit, DefaultWidget, Tag);

    p->Get = Get;
    p->Set = Set;
    p->Getstrlen = GetLen;
    p->DefStr = DefStr;
    p->Base.Offset = OffsetSize;
    p->Base.OffsetIsPointer = (Tag&LA_UDF_LOCAL) ? 0 : 1;
    p->Read = Read;

    p->IsSafeString = IsSafeString;

    la_AssignPropertyGeneralSub(p);

    return p;
}

laProp *laAddSubGroup(laPropContainer *Container, const char *Identifier, const char *Name, const char *Description,
                      const char *TargetId, laGetNodeTypeFunc GetType, laWidget* DefaultWidget, laUiDefineFunc DefaultUiDef,
                      int OffsetSize, laSubGetInstanceF Get, laSubGetInstanceF GetActive, laSubGetNextF GetNext, laSubSetInstanceF Set,
                      laSubGetStateF GetState, laSubSetStateF SetState, int ListHandleOffset, u64bit Tag){

    laSubProp *p = la_CreateProperty(Container, LA_PROP_SUB, Identifier, Name, Description, 0, 0, DefaultWidget, Tag);

    p->Base.Offset = OffsetSize;
    p->Get = Get;
    p->GetNext = GetNext;
    p->GetActive = GetActive;
    p->Set = Set;
    p->GetState = GetState;
    p->SetState = SetState;
    p->TargetID = TargetId;
    p->Base.OffsetIsPointer = (Tag & LA_UDF_LOCAL) ? 0 : 1;
    p->Base.UiDefine = DefaultUiDef;
    p->GetType = GetType;
    p->ListHandleOffset = ListHandleOffset;
    
    p->Base.UDFNoCreate = (Tag & LA_UDF_LOCAL) ? 1 : 0;

    if (Tag & LA_UDF_SINGLE || (p->Base.OffsetIsPointer && !p->ListHandleOffset && !p->GetNext && !(Tag & LA_UDF_REFER))) p->Base.UDFIsSingle = 1;

    la_AssignPropertyGeneralSub(p);

    return p;
}

void laSubGroupExtraFunctions(laProp* p, laSubUIFilterF* UiFilter, laSubSaveFilterF* SaveFilter, laSubUIThemeF* GetTheme, laSubUIGapF GetGap, laSubUICategoryF GetCategory){
    laSubProp *sp=p;
    sp->UiFilter=UiFilter; sp->SaveFilter=SaveFilter; sp->GetTheme=GetTheme; sp->GetGap=GetGap; sp->GetCategory=GetCategory;
}
void laSubGroupDetachable(laProp *SubProp, laSubTypeDetachedGet DetachedGet, laSubTypeDetachedGetNext DetachedGetNext){
    laSubProp *sp = SubProp;
    SubProp->Tag |= LA_DETACHABLE;
    sp->DetachedGet = DetachedGet;
    sp->DetachedGetNext = DetachedGetNext;
}

laProp *laAddOperatorProperty(laPropContainer *Container, const char *Identifier, const char *Name, const char *Description,
                              const char *OperatorID, uint32_t IconID, laWidget* DefaultWidget){

    laOperatorProp *p = la_CreateProperty(Container, LA_PROP_OPERATOR, Identifier, Name, Description, 0, 0, DefaultWidget, 0);

    p->OperatorID = OperatorID;
    p->Base.IconID = IconID;

    la_AssignPropertyGeneralSub(p);

    return p;
}

laProp *laAddRawProperty(laPropContainer *Container, const char *Identifier, const char *Name, const char *Description, int OffsetSize, laRawGetSizeF GetSize, laRawGetF RawGet, laRawSetF RawSet, u64bit Tag){
    if(!RawGet && !GetSize) return 0;
    laRawProp *p = la_CreateProperty(Container, LA_PROP_RAW, Identifier, Name, Description, 0, 0, 0, Tag);
    p->Base.Offset = OffsetSize;
    p->Base.OffsetIsPointer = (Tag & LA_UDF_LOCAL) ? 0 : 1;
    p->RawGet=RawGet;
    p->RawGetSize=GetSize;
    p->RawSet=RawSet;
    la_AssignPropertyGeneralSub(p);
    return p;
}
void laRawPropertyExtraFunctions(laProp* p, laRawMultiGetF MultiGet, laRawMultiCanGetF CanMultiGet){
    laRawProp *rp=p; rp->RawMultiCanGet=CanMultiGet; rp->RawMultiGet=MultiGet;
}


//void laPropertySignal(laProp* p, int Throw, int Catch) {
//	p->SignalThrow = Throw;
//	p->SignalCatch = Catch;
//}

int laIsPropertyReadOnly(laPropPack *pp){
    if (pp && pp->LastPs && pp->LastPs->p->ReadOnly) return 1;
    return 0;
}

int laGetPrefixP(laPropPack *p, char buf[8][64]){
    char *prefix = transLate(p->LastPs->p->Prefix);
    int i = 0, row = 0;

    if (!prefix) return 0;

    int len=strlen(prefix);
    while ((prefix[i] != U'\0') && (i+=1+strGetStringTerminateBy(&prefix[i], U',', &buf[row]))){
        row++; if(i>=len){break;}
    }

    return 1;
}
int laGetPrefix(laProp *p, char buf[8][64]){
    char *prefix = transLate(p->Prefix);
    int i = 0, row = 0;

    if (!prefix) return 0;

    while ((prefix[i] != U'\0') && (i += 1 + strGetStringTerminateBy(&prefix[i], U',', &buf[row]))) row++;

    return 1;
}

laPropContainer* laGetInstanceType(laPropPack* pp, void* instance){
    if(pp->LastPs->p->PropertyType != LA_PROP_SUB) return 0;
    laSubProp* sp = pp->LastPs->p;
    if(instance && sp->GetType){ return sp->GetType(instance); }
    return pp->LastPs->p->SubProp;
}
laUiDefineFunc laGetPropertyUiDefine(laPropPack* pp, void* instance){
    if(pp->LastPs->p->UiDefine) return pp->LastPs->p->UiDefine;
    laPropContainer* pc=laGetInstanceType(pp, instance);
    if(pc && pc->UiDefine) return pc->UiDefine;
    return laui_SubPropInfoDefault;
}

laPropContainer* la_EnsureSubTarget(laSubProp* sp, void* optional_instance){
    if(sp->Base.PropertyType!=LA_PROP_SUB){return sp->Base.SubProp;}
    if(optional_instance && sp->GetType) return sp->GetType(optional_instance);
    if(sp->Base.SubProp){ return sp->Base.SubProp; }
    if(sp->TargetID)sp->Base.SubProp=la_ContainerLookup(sp->TargetID); return sp->Base.SubProp;
}

int laReadInt(laPropPack *pp, int n){
    if (pp->LastPs->p->PropertyType & LA_PROP_INT){
        laIntProp *p = pp->LastPs->p;
        if (p->Read) p->Read(pp->LastPs->UseInstance, n);
        else
            laSetInt(pp, n);
        laNotifyUsersPP(pp);
        return 1;
    }
    return 0;
}
int laSetInt(laPropPack *pp, int n){
    if (pp->LastPs->p->PropertyType & LA_PROP_INT){
        laIntProp *p = pp->LastPs->p;
        if (p->Max != p->Min){
            n = n > p->Max ? p->Max : (n < p->Min ? p->Min : n);
        }
        if (p->Base.DetachedPP.LastPs){
            p->Detached[0] = n;
            laNotifyUsersPP(pp);
            return 1;
        }
        if (p->Set) p->Set(pp->LastPs->UseInstance, n);
        elif (pp->LastPs->p->Offset>=0){
            if (!p->Base.ElementBytes || p->Base.ElementBytes == 4){
                if (pp->LastPs->p->OffsetIsPointer) (**((int **)((BYTE *)pp->LastPs->UseInstance + pp->LastPs->p->Offset))) = n;
                else (*((int *)((BYTE *)pp->LastPs->UseInstance + pp->LastPs->p->Offset))) = n;
            }elif (p->Base.ElementBytes == 2){
                if (pp->LastPs->p->OffsetIsPointer) (**((short **)((BYTE *)pp->LastPs->UseInstance + pp->LastPs->p->Offset))) = n;
                else (*((short *)((BYTE *)pp->LastPs->UseInstance + pp->LastPs->p->Offset))) = n;
            }elif (p->Base.ElementBytes == 1){
                if (pp->LastPs->p->OffsetIsPointer) (**((char **)((BYTE *)pp->LastPs->UseInstance + pp->LastPs->p->Offset))) = n;
                else (*((BYTE *)((BYTE *)pp->LastPs->UseInstance + pp->LastPs->p->Offset))) = n;
            }
        }
        laNotifyUsersPP(pp);
        return 1;
    }
    return 0;
}
int laGetInt(laPropPack *pp){
    int n;
    if (pp->LastPs->p->PropertyType & LA_PROP_INT){
        laIntProp *p = pp->LastPs->p;
        if (p->Base.DetachedPP.LastPs){
            return p->Detached[0];
        }
        if (!pp->LastPs->UseInstance) return 0;
        if (((laIntProp *)pp->LastPs->p)->Get) return ((laIntProp *)pp->LastPs->p)->Get(pp->LastPs->UseInstance);
        elif (pp->LastPs->p->Offset>=0){
            if (!p->Base.ElementBytes || p->Base.ElementBytes == 4){
                if (pp->LastPs->p->OffsetIsPointer) n = (**((int **)((BYTE *)pp->LastPs->UseInstance + pp->LastPs->p->Offset)));
                else n = (*((int *)((BYTE *)pp->LastPs->UseInstance + pp->LastPs->p->Offset)));
            }elif (p->Base.ElementBytes == 2){
                if (pp->LastPs->p->OffsetIsPointer) n = (**((short **)((BYTE *)pp->LastPs->UseInstance + pp->LastPs->p->Offset)));
                else n = (*((short *)((BYTE *)pp->LastPs->UseInstance + pp->LastPs->p->Offset)));
            }elif (p->Base.ElementBytes == 1){
                if (pp->LastPs->p->OffsetIsPointer) n = (**((char **)((BYTE *)pp->LastPs->UseInstance + pp->LastPs->p->Offset)));
                else n = (*((BYTE *)((BYTE *)pp->LastPs->UseInstance + pp->LastPs->p->Offset)));
            }
            return n;
        }
    }
    return 0;
}
int laReadFloat(laPropPack *pp, real n){
    if (pp->LastPs->p->PropertyType & LA_PROP_FLOAT){
        laFloatProp *p = pp->LastPs->p;
        if (p->Read) p->Read(pp->LastPs->UseInstance, n);
        else
            laSetFloat(pp, n);
        laNotifyUsersPP(pp);
        return 1;
    }
    return 0;
}
int laSetFloat(laPropPack *pp, real n){
    if (pp->LastPs->p->PropertyType & LA_PROP_FLOAT){
        laFloatProp *p = pp->LastPs->p;
        if (p->Max != p->Min){
            n = n > p->Max ? p->Max : (n < p->Min ? p->Min : n);
        }
        if (p->Base.DetachedPP.LastPs){
            p->Detached[0] = n;
            laNotifyUsersPP(pp);
            return 1;
        }
        if (p->Set) p->Set(pp->LastPs->UseInstance, n);
        elif (pp->LastPs->p->Offset>=0){
            if (pp->LastPs->p->OffsetIsPointer) (**((real **)((BYTE *)pp->LastPs->UseInstance + pp->LastPs->p->Offset))) = n;
            else (*((real *)((BYTE *)pp->LastPs->UseInstance + pp->LastPs->p->Offset))) = n;
        }
        laNotifyUsersPP(pp);
        return 1;
    }
    return 0;
}
real laGetFloat(laPropPack *pp){
    if (pp->LastPs->p->PropertyType & LA_PROP_FLOAT){
        laFloatProp *p = pp->LastPs->p;
        if (p->Base.DetachedPP.LastPs){
            return p->Detached[0];
        }
        if (!pp->LastPs->UseInstance) return 0;
        if (((laFloatProp *)pp->LastPs->p)->Get) return ((laFloatProp *)pp->LastPs->p)->Get(pp->LastPs->UseInstance);
        elif (pp->LastPs->p->Offset>=0){
            if (pp->LastPs->p->OffsetIsPointer) return (**((real **)((BYTE *)pp->LastPs->UseInstance + pp->LastPs->p->Offset)));
            else return (*((real *)((BYTE *)pp->LastPs->UseInstance + pp->LastPs->p->Offset)));
        }
    }
    return 0;
}
int laGetArrayLength(laPropPack *pp){
    if (!pp->LastPs->p) return 0;
    if (pp->LastPs->p->GetLen) return pp->LastPs->p->GetLen(pp->LastPs->UseInstance);
    else{
        if(pp->LastPs->p->Len==0) pp->LastPs->p->Len=1;
        return pp->LastPs->p->Len;
    }
}
int laSetIntArraySingle(laPropPack *pp, int index, int n){
    laIntProp *p = pp->LastPs->p;
    if (p->Max != p->Min){
        n = n > p->Max ? p->Max : (n < p->Min ? p->Min : n);
    }
    if (p->Base.DetachedPP.LastPs){
        p->Detached[index] = n;
        laNotifyUsersPP(pp);
        return 1;
    }
    if (!pp->LastPs->UseInstance) return 0;
    if (pp->LastPs->p->PropertyType & LA_PROP_INT){
        if (p->SetArr){
            p->SetArr(pp->LastPs->UseInstance, index, n);
            laNotifyUsersPP(pp);
            return 1;
        }elif(p->SetAllArr){
            int len = laGetArrayLength(pp); int* t=malloc(len*sizeof(int));
            laGetIntArray(pp, t); t[index]=n;
            laSetIntArrayAllArray(pp, t); free(t);
            return 1;
        }elif(p->Set){
            laSetInt(pp, n);
            return 1;
        }elif (pp->LastPs->p->Offset>=0){
            int *src = (pp->LastPs->p->OffsetIsPointer) ? ((int **)((BYTE *)pp->LastPs->UseInstance + pp->LastPs->p->Offset)) : ((int *)((BYTE *)pp->LastPs->UseInstance + pp->LastPs->p->Offset));
            switch(pp->LastPs->p->ElementBytes){
                default: case 4: src[index] = n; break;
                case 2: ((short*)src)[index]=n; break;
                case 1: ((char*)src)[index]=n; break;
            }
            laNotifyUsersPP(pp); return 1;
        }
    }
    return 0;
}
int laSetIntArrayAll(laPropPack *pp, int n){
    laIntProp *p = pp->LastPs->p;
    if (p->Max != p->Min){
        n = n > p->Max ? p->Max : (n < p->Min ? p->Min : n);
    }
    if (p->Base.DetachedPP.LastPs){
        int i = 0, len = laGetArrayLength(pp);
        for (i; i < len; i++){
            p->Detached[i] = n;
        }
        laNotifyUsersPP(pp);
        return 1;
    }
    if (!pp->LastPs->UseInstance) return 0;
    if (pp->LastPs->p->PropertyType & LA_PROP_INT){
        if (p->SetAll) p->SetAll(pp->LastPs->UseInstance, n);
        else if (p->SetArr){
            int i = 0, len = laGetArrayLength(pp);
            for (i; i < len; i++){
                p->SetArr(pp->LastPs->UseInstance, i, n);
            }
        }elif (pp->LastPs->p->Offset>=0){
            int *src = (pp->LastPs->p->OffsetIsPointer) ? ((int **)((BYTE *)pp->LastPs->UseInstance + pp->LastPs->p->Offset)) : ((int *)((BYTE *)pp->LastPs->UseInstance + pp->LastPs->p->Offset));
            int i = 0, len = laGetArrayLength(pp);
            for (i; i < len; i++){ 
                switch(pp->LastPs->p->ElementBytes){
                    default: case 4: src[i] = n; break;
                    case 2: ((short*)src)[i]=n; break;
                    case 1: ((char*)src)[i]=n; break;
                }
            }
        }
        laNotifyUsersPP(pp);
        return 1;
    }
    return 0;
}
int laReadIntArrayAllArray(laPropPack *pp, int *arr){
    if (pp->LastPs->p->PropertyType & LA_PROP_INT){
        if (((laIntProp *)pp->LastPs->p)->Base.DetachedPP.LastPs){
            int i = 0, len = laGetArrayLength(pp);
            for (i; i < len; i++){
                ((laIntProp *)pp->LastPs->p)->Detached[i] = arr[i];
            }
            return 1;
        }
        if (!pp->LastPs->UseInstance) return 0;
        if (((laIntProp *)pp->LastPs->p)->SetAllArr) ((laIntProp *)pp->LastPs->p)->SetAllArr(pp->LastPs->UseInstance, arr);
        else
            laSetIntArrayAllArray(pp, arr);
        laNotifyUsersPP(pp);
        return 1;
    }
    return 0;
}
int laSetIntArrayAllArray(laPropPack *pp, int *arr){
    if (pp->LastPs->p->PropertyType & LA_PROP_INT){
        if (((laIntProp *)pp->LastPs->p)->Base.DetachedPP.LastPs){
            int i = 0, len = laGetArrayLength(pp);
            for (i; i < len; i++){
                ((laIntProp *)pp->LastPs->p)->Detached[i] = arr[i];
            }
            laNotifyUsersPP(pp);
            return 1;
        }
        if (!pp->LastPs->UseInstance) return 0;
        if (((laIntProp *)pp->LastPs->p)->SetAllArr) ((laIntProp *)pp->LastPs->p)->SetAllArr(pp->LastPs->UseInstance, arr);
        else if (((laIntProp *)pp->LastPs->p)->SetArr){
            int i = 0, len = laGetArrayLength(pp);
            for (i; i < len; i++){
                ((laIntProp *)pp->LastPs->p)->SetArr(pp->LastPs->UseInstance, i, arr[i]);
            }
        }else if (pp->LastPs->p->Offset>=0){
            int *src = (pp->LastPs->p->OffsetIsPointer) ? ((int **)((BYTE *)pp->LastPs->UseInstance + pp->LastPs->p->Offset)) : ((int *)((BYTE *)pp->LastPs->UseInstance + pp->LastPs->p->Offset));
            int i = 0, len = laGetArrayLength(pp);
            for (i; i < len; i++){
                switch(pp->LastPs->p->ElementBytes){
                    default: case 4: src[i] =arr[i]; break;
                    case 2: ((short*)src)[i]=arr[i]; break;
                    case 1: ((char*)src)[i]=arr[i]; break;
                }
            }
        }
        laNotifyUsersPP(pp);
        return 1;
    }
    return 0;
}
int laGetIntArray(laPropPack *pp, int *result){
    if (pp->LastPs->p->PropertyType & LA_PROP_INT){
        laIntProp *p = pp->LastPs->p;
        if (p->Base.DetachedPP.LastPs){
            int len = laGetArrayLength(pp);
            memcpy(result, p->Detached, len * sizeof(int));
            return 1;
        }
        if (!pp->LastPs->UseInstance) return 0;
        if (!((laIntProp *)pp->LastPs->p)->GetAll){
            int len = laGetArrayLength(pp);
            if(len==1){ *result=laGetInt(pp); return 1; }
            if(pp->LastPs->p->Offset>=0){
                int *src = (pp->LastPs->p->OffsetIsPointer) ? ((int **)((BYTE *)pp->LastPs->UseInstance + pp->LastPs->p->Offset)) : ((int *)((BYTE *)pp->LastPs->UseInstance + pp->LastPs->p->Offset));
                switch(pp->LastPs->p->ElementBytes){
                    default: case 4: memcpy(result, src, len * sizeof(int)); break;
                    case 2: for(int i=0;i<len;i++){ result[i]=((short*)src)[i]; } break;
                    case 1: for(int i=0;i<len;i++){ result[i]=((char*)src)[i]; } break;
                }
            }else{ *result=0; }
            return 1;
        }else{
            ((laIntProp *)pp->LastPs->p)->GetAll(pp->LastPs->UseInstance, result);
            return 1;
        }
    }
    return 0;
}
int laSetFloatArraySingle(laPropPack *pp, int index, real n){
    laFloatProp *p = pp->LastPs->p;
    if (p->Max != p->Min){
        n = n > p->Max ? p->Max : (n < p->Min ? p->Min : n);
    }
    if (p->Base.DetachedPP.LastPs){
        p->Detached[index] = n;
        laNotifyUsersPP(pp);
        return 1;
    }
    if (!pp->LastPs->UseInstance) return 0;
    if (pp->LastPs->p->PropertyType & LA_PROP_FLOAT){
        if (p->SetArr){
            p->SetArr(pp->LastPs->UseInstance, index, n);
            laNotifyUsersPP(pp);
            return 1;
        }elif(p->SetAllArr){
            int len = laGetArrayLength(pp); real* t=malloc(len*sizeof(real));
            laGetFloatArray(pp, t); t[index]=n;
            laSetFloatArrayAllArray(pp, t); free(t);
            return 1;
        }elif(p->Set){
            laSetFloat(pp, n);
            return 1;
        }elif (pp->LastPs->p->Offset>=0){
            real *src = (pp->LastPs->p->OffsetIsPointer) ? ((real **)((BYTE *)pp->LastPs->UseInstance + pp->LastPs->p->Offset)) : ((real *)((BYTE *)pp->LastPs->UseInstance + pp->LastPs->p->Offset));
            src[index] = n;
            laNotifyUsersPP(pp);
            return 1;
        }
    }
    return 0;
}
int laSetFloatArrayAll(laPropPack *pp, real n){
    laFloatProp *p = pp->LastPs->p;
    if (p->Max != p->Min){
        n = n > p->Max ? p->Max : (n < p->Min ? p->Min : n);
    }
    if (p->Base.DetachedPP.LastPs){
        int i = 0, len = laGetArrayLength(pp);
        for (i; i < len; i++){
            p->Detached[i] = n;
        }
        laNotifyUsersPP(pp);
        return 1;
    }
    if (!pp->LastPs->UseInstance) return 0;
    if (pp->LastPs->p->PropertyType & LA_PROP_FLOAT){
        if (p->SetAll) p->SetAll(pp->LastPs->UseInstance, n);
        else if (p->SetArr){
            int i = 0, len = laGetArrayLength(pp);
            for (i; i < len; i++){
                p->SetArr(pp->LastPs->UseInstance, i, n);
            }
        }else if (pp->LastPs->p->Offset>=0){
            real *src = (pp->LastPs->p->OffsetIsPointer) ? ((real **)((BYTE *)pp->LastPs->UseInstance + pp->LastPs->p->Offset)) : ((real *)((BYTE *)pp->LastPs->UseInstance + pp->LastPs->p->Offset));
            int i = 0, len = laGetArrayLength(pp);
            for (i; i < len; i++){ src[i] = n; }
        }
        laNotifyUsersPP(pp);
        return 1;
    }
    return 0;
}
int laReadFloatArrayAllArray(laPropPack *pp, real *arr){
    if (((laFloatProp *)pp->LastPs->p)->Base.DetachedPP.LastPs){
        int i = 0, len = laGetArrayLength(pp);
        for (i; i < len; i++){
            ((laFloatProp *)pp->LastPs->p)->Detached[i] = arr[i];
        }
        return 1;
    }
    if (!pp->LastPs->UseInstance) return 0;
    if (pp->LastPs->p->PropertyType & LA_PROP_FLOAT){
        if (((laFloatProp *)pp->LastPs->p)->ReadAll) ((laFloatProp *)pp->LastPs->p)->ReadAll(pp->LastPs->UseInstance, arr);
        else if (((laFloatProp *)pp->LastPs->p)->SetArr){
            int i = 0, len = laGetArrayLength(pp);
            for (i; i < len; i++){
                ((laFloatProp *)pp->LastPs->p)->SetArr(pp->LastPs->UseInstance, i, arr[i]);
            }
        }else if (pp->LastPs->p->Offset>=0){
            real *src = (pp->LastPs->p->OffsetIsPointer) ? ((real **)((BYTE *)pp->LastPs->UseInstance + pp->LastPs->p->Offset)) : ((real *)((BYTE *)pp->LastPs->UseInstance + pp->LastPs->p->Offset));
            int i = 0, len = laGetArrayLength(pp);
            for (i; i < len; i++){ src[i] = arr[i]; }
        }
        laNotifyUsersPP(pp);
        return 1;
    }
    return 0;
}
int laSetFloatArrayAllArray(laPropPack *pp, real *arr){
    if (((laFloatProp *)pp->LastPs->p)->Base.DetachedPP.LastPs){
        int i = 0, len = laGetArrayLength(pp);
        for (i; i < len; i++){
            ((laFloatProp *)pp->LastPs->p)->Detached[i] = arr[i];
        }
        laNotifyUsersPP(pp);
        return 1;
    }
    if (!pp->LastPs->UseInstance) return 0;
    if (pp->LastPs->p->PropertyType & LA_PROP_FLOAT){
        if (((laFloatProp *)pp->LastPs->p)->SetAllArr) ((laFloatProp *)pp->LastPs->p)->SetAllArr(pp->LastPs->UseInstance, arr);
        else if (((laFloatProp *)pp->LastPs->p)->SetArr){
            int i = 0, len = laGetArrayLength(pp);
            for (i; i < len; i++){
                ((laFloatProp *)pp->LastPs->p)->SetArr(pp->LastPs->UseInstance, i, arr[i]);
            }
        }else if (pp->LastPs->p->Offset>=0){
            real *src = (pp->LastPs->p->OffsetIsPointer) ? ((real **)((BYTE *)pp->LastPs->UseInstance + pp->LastPs->p->Offset)) : ((real *)((BYTE *)pp->LastPs->UseInstance + pp->LastPs->p->Offset));
            int i = 0, len = laGetArrayLength(pp);
            for (i; i < len; i++){ src[i] = arr[i]; }
        }
        laNotifyUsersPP(pp);
        return 1;
    }
    return 0;
}
int laGetFloatArray(laPropPack *pp, real *result){
    if (pp->LastPs->p->PropertyType & LA_PROP_FLOAT){
        laFloatProp *p = pp->LastPs->p;
        if (p->Base.DetachedPP.LastPs){
            int len = laGetArrayLength(pp);
            memcpy(result, p->Detached, len * sizeof(real));
            return 1;
        }
        if (!pp->LastPs->UseInstance) return 0;
        if (!((laFloatProp *)pp->LastPs->p)->GetAll){
            int len = laGetArrayLength(pp);
            if(len==1){ *result=laGetFloat(pp); return 1; }
            if(pp->LastPs->p->Offset>=0){
                real *src = (pp->LastPs->p->OffsetIsPointer) ? ((real **)((BYTE *)pp->LastPs->UseInstance + pp->LastPs->p->Offset)) : ((real *)((BYTE *)pp->LastPs->UseInstance + pp->LastPs->p->Offset));
                memcpy(result, src, len * sizeof(real));
            }else{ *result=0; }
            return 1;
        }else{
            ((laFloatProp *)pp->LastPs->p)->GetAll(pp->LastPs->UseInstance, result);
            return 1;
        }
    }
    return 0;
}
int laReadEnum(laPropPack *pp, int n){
    if (pp->LastPs->p->PropertyType & LA_PROP_ENUM){
        if (((laEnumProp *)pp->LastPs->p)->Read) ((laEnumProp *)pp->LastPs->p)->Read(pp->LastPs->UseInstance, n);
        else laSetEnum(pp, n);
        laNotifyUsersPP(pp);
        return 1;
    }
    return 0;
}
int laSetEnumExternal(laPropPack *pp, int n){
    if (pp->LastPs->p->PropertyType & LA_PROP_ENUM){
        laEnumProp *ep = pp->LastPs->p;
        laEnumItem *ei;
        int i = 0;
        for (ei = ep->Items.pFirst; ei; ei = ei->Item.pNext){
            if (i == n) break; i++;
        }
        laSetEnum(pp, ei->Index);
    }
    return 0;
}
int laSetEnum(laPropPack *pp, int n){
    if (pp->LastPs->p->PropertyType & LA_PROP_ENUM){
        laEnumProp *p = pp->LastPs->p;
        if (p->Base.DetachedPP.LastPs){
            p->Detached[0] = n;
            laNotifyUsersPP(pp);
            return 1;
        }
        if (!pp->LastPs->UseInstance) return 0;
        if (p->Set) p->Set(pp->LastPs->UseInstance, n);
        elif(p->Base.Offset>=0) {
            if (!p->Base.ElementBytes || p->Base.ElementBytes == 4){
                if (pp->LastPs->p->OffsetIsPointer) (**((int **)((BYTE *)pp->LastPs->UseInstance + pp->LastPs->p->Offset))) = n;
                else (*((int *)((BYTE *)pp->LastPs->UseInstance + pp->LastPs->p->Offset))) = n;
            }elif (p->Base.ElementBytes == 2){
                if (pp->LastPs->p->OffsetIsPointer) (**((short **)((BYTE *)pp->LastPs->UseInstance + pp->LastPs->p->Offset))) = n;
                else (*((short *)((BYTE *)pp->LastPs->UseInstance + pp->LastPs->p->Offset))) = n;
            }elif (p->Base.ElementBytes == 1){
                if (pp->LastPs->p->OffsetIsPointer) (**((char **)((BYTE *)pp->LastPs->UseInstance + pp->LastPs->p->Offset))) = n;
                else (*((BYTE *)((BYTE *)pp->LastPs->UseInstance + pp->LastPs->p->Offset))) = n;
            }
        }
        laNotifyUsersPP(pp);
        return 1;
    }
    return 0;
}
int laReadEnumArrayAll(laPropPack *pp, int *n){
    int i, len = pp->LastPs->p->Len;
    if (pp->LastPs->p->PropertyType & LA_PROP_ENUM){
        if (((laEnumProp *)pp->LastPs->p)->ReadAll) ((laEnumProp *)pp->LastPs->p)->ReadAll(pp->LastPs->UseInstance, n);
        else
            for (i = 0; i < len; i++){
                laSetEnumArrayIndexed(pp, i, n[i]);
            }
        laNotifyUsersPP(pp);
        return 1;
    }
    return 0;
}
int laSetEnumArrayIndexedExternal(laPropPack *pp, int index, int n){
    if (pp->LastPs->p->PropertyType & LA_PROP_ENUM){
        laEnumProp *ep = pp->LastPs->p;
        laEnumItem *ei;
        int i = 0;
        for (ei = ep->Items.pFirst; ei; ei = ei->Item.pNext){
            if (i == n) break;
            i++;
        }
        laSetEnumArrayIndexed(pp, index,ei->Index);
    }
    return 0;
}
int laSetEnumArrayIndexed(laPropPack *pp, int index, int n){
    if (pp->LastPs->p->PropertyType & LA_PROP_ENUM){
        laEnumProp *p = pp->LastPs->p;
        if (p->Base.DetachedPP.LastPs){
            p->Detached[index] = n; 
            laNotifyUsersPP(pp);return 1;
        }
        if (!pp->LastPs->UseInstance) return 0;
        if (p->SetArr) p->SetArr(pp->LastPs->UseInstance, index, n);
        elif(p->Set && index==0){ laSetEnum(pp, n); } 
        elif(p->Base.Offset>=0){
            if (!p->Base.ElementBytes || p->Base.ElementBytes == 4){
                if (pp->LastPs->p->OffsetIsPointer) (**((int **)((BYTE *)pp->LastPs->UseInstance + pp->LastPs->p->Offset + sizeof(int) * index))) = n;
                else (*((int *)((BYTE *)pp->LastPs->UseInstance + pp->LastPs->p->Offset + sizeof(int) * index))) = n;
            }elif (p->Base.ElementBytes == 2){
                if (pp->LastPs->p->OffsetIsPointer) (**((short **)((BYTE *)pp->LastPs->UseInstance + pp->LastPs->p->Offset + sizeof(short) * index))) = n;
                else (*((short *)((BYTE *)pp->LastPs->UseInstance + pp->LastPs->p->Offset + sizeof(short) * index))) = n;
            }elif (p->Base.ElementBytes == 1){
                if (pp->LastPs->p->OffsetIsPointer) (**((char **)((BYTE *)pp->LastPs->UseInstance + pp->LastPs->p->Offset + sizeof(char) * index))) = n;
                else (*((BYTE *)((BYTE *)pp->LastPs->UseInstance + pp->LastPs->p->Offset + sizeof(char) * index))) = n;
            }
        }
        laNotifyUsersPP(pp);
        return 1;
    }
    return 0;
}
int laSetEnumArrayAllArray(laPropPack* pp, laEnumItem** ei){
    int len=laGetArrayLength(pp);
    for(int i=0;i<len;i++){
        laSetEnumArrayIndexed(pp,i,ei[i]->Index);
    }
	return 0;
}
int laSetEnumArrayAll(laPropPack* pp, int EnumN){
    int len=laGetArrayLength(pp);
    laEnumProp *ep = pp->LastPs->p; laEnumItem *ei;
    int i = 0; for (ei = ep->Items.pFirst; ei; ei = ei->Item.pNext){ if (i == EnumN) break; i++; }
    for(int i=0;i<len;i++){
        laSetEnumArrayIndexed(pp,i,ei->Index);
    }
	return 0;
}
laEnumItem *laGetEnum(laPropPack *pp){
    int n;
    laEnumItem *ei;
    if (pp->LastPs->p->PropertyType & LA_PROP_ENUM){
        laEnumProp *p = pp->LastPs->p;
        if (p->Base.DetachedPP.LastPs){
            n = p->Detached[0];
        }elif (!pp->LastPs->UseInstance) return 0;
        elif (p->Get) n = p->Get(pp->LastPs->UseInstance);
        elif(p->Base.Offset>=0){
            if (!pp->LastPs->UseInstance) n = 0;
            elif (!p->Base.ElementBytes || p->Base.ElementBytes == 4){
                if (pp->LastPs->p->OffsetIsPointer) n = (**((int **)((BYTE *)pp->LastPs->UseInstance + pp->LastPs->p->Offset)));
                else n = (*((int *)((BYTE *)pp->LastPs->UseInstance + pp->LastPs->p->Offset)));
            }elif (p->Base.ElementBytes == 2){
                if (pp->LastPs->p->OffsetIsPointer) n = (**((short **)((BYTE *)pp->LastPs->UseInstance + pp->LastPs->p->Offset)));
                else n = (*((short *)((BYTE *)pp->LastPs->UseInstance + pp->LastPs->p->Offset)));
            }elif (p->Base.ElementBytes == 1){
                if (pp->LastPs->p->OffsetIsPointer) n = (**((char **)((BYTE *)pp->LastPs->UseInstance + pp->LastPs->p->Offset)));
                else n = (*((BYTE *)((BYTE *)pp->LastPs->UseInstance + pp->LastPs->p->Offset)));
            }
        }
        for (ei = p->Items.pFirst; ei; ei = ei->Item.pNext){
            if (n == ei->Index) return ei;
        }
    }
    return ((laEnumProp *)pp->LastPs->p)->Items.pFirst;
}
laEnumItem *laGetEnumArrayIndexed(laPropPack *pp, int index){
    int n;
    int i = 0;
    laEnumItem *ei;
    int result[16];
    if (pp->LastPs->p->PropertyType & LA_PROP_ENUM){
        laEnumProp *p = pp->LastPs->p;
        if (p->Base.DetachedPP.LastPs){
            n = p->Detached[index];
        }elif (!p->GetAll){
            if(laGetArrayLength(pp)==1){return laGetEnum(pp);}
            if(p->Base.Offset>=0){
                if (!pp->LastPs->UseInstance) n = 0;
                elif (!p->Base.ElementBytes || p->Base.ElementBytes == 4){
                    if (pp->LastPs->p->OffsetIsPointer) n = (**((int **)((BYTE *)pp->LastPs->UseInstance + pp->LastPs->p->Offset)) + index * sizeof(int));
                    else n = (*((int *)((BYTE *)pp->LastPs->UseInstance + pp->LastPs->p->Offset + index * sizeof(int))));
                }elif (p->Base.ElementBytes == 2){
                    if (pp->LastPs->p->OffsetIsPointer) n = (**((short **)((BYTE *)pp->LastPs->UseInstance + pp->LastPs->p->Offset)) + index * sizeof(short));
                    else n = (*((short *)((BYTE *)pp->LastPs->UseInstance + pp->LastPs->p->Offset + index * sizeof(short))));
                }elif (p->Base.ElementBytes == 1){
                    if (pp->LastPs->p->OffsetIsPointer) n = (**((char **)((BYTE *)pp->LastPs->UseInstance + pp->LastPs->p->Offset)) + index * sizeof(char));
                    else n = (*((BYTE *)((BYTE *)pp->LastPs->UseInstance + pp->LastPs->p->Offset + index * sizeof(char))));
                }
            }
        }else{
            if (!pp->LastPs->UseInstance) n = 0;
            else{
                p->GetAll(pp->LastPs->UseInstance, result);
                n = result[index];
            }
        }
        for (ei = p->Items.pFirst; ei; ei = ei->Item.pNext){
            if (n == ei->Index) return ei;
        }
    }
    return 0;
}
int laGetEnumArray(laPropPack *pp, laEnumItem **result){
    int len = laGetArrayLength(pp);
    int i = 0;
    laEnumItem *ei;
    int Results[16];

    laEnumProp *p = pp->LastPs->p;
    if (p->Base.DetachedPP.LastPs){
        for (int i = 0; i < len; i++){
            Results[i] = p->Detached[i];
            for (ei = ((laEnumProp *)pp->LastPs->p)->Items.pFirst; ei; ei = ei->Item.pNext){
                if (ei->Index == Results[i]){result[i] = ei; break;}
            }
        }
    }elif (!((laEnumProp *)pp->LastPs->p)->GetAll){
        for (i; i < len; i++){
            result[i] = laGetEnumArrayIndexed(pp, i);
        }
        return 1;
    }else{
        int a = 0;
        ((laEnumProp *)pp->LastPs->p)->GetAll(pp->LastPs->UseInstance, Results);
        for (i = 0; i < len; i++){
            for (ei = ((laEnumProp *)pp->LastPs->p)->Items.pFirst; ei; ei = ei->Item.pNext){
                if (ei->Index == Results[i]){ result[i] = ei; break; }
            }
        }
    }
}
laEnumItem *laGetEnumFromIdentifier(laEnumProp *p, char *Identifier){
    laEnumItem *ei;
    for (ei = p->Items.pFirst; ei; ei = ei->Item.pNext){
        if (!strcmp(ei->Identifier, Identifier)) return ei;
    }
    return p->Items.pFirst;
}
int laEnumHasIcon(laPropPack *pp){
    laEnumProp *p = pp->LastPs->p;
    laEnumItem *ei;
    if ((p->Base.PropertyType & LA_PROP_ENUM) != LA_PROP_ENUM) return 0;
    for (ei = p->Items.pFirst; ei; ei = ei->Item.pNext){
        if (ei->IconID) return 1;
    }
    return 0;
}
int laGetEnumEntryLen(laPropPack *pp){
    int i = 0;
    laEnumItem *ei;
    if (pp->LastPs->p->PropertyType & LA_PROP_ENUM){
        if (((laEnumProp *)pp->LastPs->p)->GetLen) return ((laEnumProp *)pp->LastPs->p)->GetLen(pp->LastPs->UseInstance);
        for (ei = ((laEnumProp *)pp->LastPs->p)->Items.pFirst; ei; ei = ei->Item.pNext){
            i += 1;
        }
        return i;
    }
    return 0;
}
int laReadString(laPropPack *pp, char *str){
    if (pp->LastPs->p->PropertyType == LA_PROP_STRING){
        if (((laStringProp *)pp->LastPs->p)->Read) ((laStringProp *)pp->LastPs->p)->Read(pp->LastPs->UseInstance, str);
        else
            laSetString(pp, str);
        laNotifyUsersPP(pp);
        return 1;
    }
    return 0;
}
int laSetString(laPropPack *pp, char *str){
    char **add = 0;
    if (pp->LastPs->p->PropertyType == LA_PROP_STRING){
        laStringProp *p = pp->LastPs->p;
        if (p->Base.DetachedPP.LastPs){
            strCopyFull(p->Detached, str);
            laNotifyUsersPP(pp);
            return 1;
        }

        if (p->Set){
            p->Set(pp->LastPs->UseInstance, str);
            laNotifyUsersPP(pp);
            return 1;
        }

        if (!pp->LastPs->UseInstance) return 0;

        if (p->IsSafeString){
            add = ((char **)((BYTE *)pp->LastPs->UseInstance + pp->LastPs->p->Offset));
            strSafeSet(add, str);
            laNotifyUsersPP(pp);
            return 1;
        }
        if (p->Base.Offset){
            if (p->Base.OffsetIsPointer){
                add = ((char **)((BYTE *)pp->LastPs->UseInstance + pp->LastPs->p->Offset));
                if (!(*add)) return 0;
                strCopyFull(*add, str);
            }else strCopyFull(((BYTE *)pp->LastPs->UseInstance + pp->LastPs->p->Offset), str);
        }
        laNotifyUsersPP(pp);
        return 1;
    }
    return 0;
}
int laGetString(laPropPack *pp, char *result, char** direct_result){
    if (pp->LastPs->p->PropertyType == LA_PROP_STRING){
        laStringProp *p = pp->LastPs->p;
        if (p->Base.DetachedPP.LastPs){
            strCopyFull(result, p->Detached);
            return 1;
        }
        if (!pp->LastPs->UseInstance) return 0;

        if (p->Get){ p->Get(pp->LastPs->UseInstance, result, direct_result); return 1; }

        if (pp->LastPs->p->Offset>=0){
            if (p->IsSafeString){
                laSafeString **add = ((laSafeString **)((BYTE *)pp->LastPs->UseInstance + pp->LastPs->p->Offset));
                //printf(" -- %s\n",p->Base.Identifier);
                if ((!pp->LastPs->UseInstance) || (!*add)) return 0;
                if((*add)->Ptr){ *direct_result = (*add)->Ptr; return 1;}
                return 0;
            }else{
                if (pp->LastPs->p->OffsetIsPointer) *direct_result=*((char **)((BYTE *)pp->LastPs->UseInstance + pp->LastPs->p->Offset));
                else  *direct_result=((BYTE *)pp->LastPs->UseInstance + pp->LastPs->p->Offset);
            }
        }
        return 1;
    }
    return 0;
}
void *laGetInstance(laProp *sub, void *FromInstance, laPropIterator *Iter){
    laSubProp *sp = sub;
    laPropIterator IT = {0};
    if (!Iter) Iter = &IT;
    if (Iter) Iter->Parent = FromInstance;
    if (sub->PropertyType == LA_PROP_SUB){
        if (sp->Base.DetachedPP.LastPs){ if(sp->DetachedGet) return sp->DetachedGet(0, Iter);
            return sp->Detached;
        }
        if (!FromInstance) return 0;
        if (sp->Get) return sp->Get(FromInstance, Iter);
        else if (sp->ListHandleOffset){
            void *address = *((u64bit*)((BYTE *)FromInstance + sp->ListHandleOffset));
            return address;
        }else return laGetActiveInstance(sub, FromInstance, Iter);
    }
    return 0;
}
void *laGetNextInstance(laProp *sub, void *ThisInstance, laPropIterator *Iter){
    laSubProp *sp = sub;
    if (sub->PropertyType == LA_PROP_SUB){
        if (sp->Base.DetachedPP.LastPs && sp->DetachedGetNext) return sp->DetachedGetNext(ThisInstance, Iter);
        if (!ThisInstance) return 0;
        if (sp->GetNext) return (sp->GetNext(ThisInstance, Iter));
        else if (sp->ListHandleOffset){
            laListItem *li = ThisInstance;
            return li->pNext;
        }
    }
    return 0;
}
void *laGetActiveInstanceStrict(laProp *sub, void *FromInstance){
    laSubProp *sp = sub;
    if (sub->PropertyType == LA_PROP_SUB){
        if (sp->Base.DetachedPP.LastPs){
            return sp->Detached;
        }
        if (!FromInstance) return 0;
        if (sp->GetActive) return sp->GetActive(FromInstance, 0);
        if (sub->Offset>=0){
            if (sub->OffsetIsPointer /*&& (sp->Get||sp->ListHandleOffset)*/){
                void **a = (void **)((BYTE *)FromInstance + sub->Offset); return *a;
            }else return ((BYTE *)FromInstance + sub->Offset);
        }
    }
    return 0; // laGetInstance(sub, FromInstance, 0);
}
void *laGetActiveInstance(laProp *sub, void *FromInstance, laPropIterator *Iter){
    laSubProp *sp = sub;
    if (sub->PropertyType == LA_PROP_SUB){
        if (sp->Base.DetachedPP.LastPs){
            return sp->Detached;
        }
        if (!FromInstance) return 0;
        if (sp->GetActive) return sp->GetActive(FromInstance, Iter);
        if (sp->Get) return laGetInstance(sub, FromInstance, Iter);
        if (sub->Offset>=0){
            if (sub->OffsetIsPointer){
                void **a = (void **)((BYTE *)FromInstance + sub->Offset); return *a;
            }else return ((BYTE *)FromInstance + sub->Offset);
        }
    }
    return 0;
}
void laSetActiveInstance(laProp *sub, void *FromInstance, void *Instance){
    laSubProp *sp = sub;
    if (sub->PropertyType == LA_PROP_SUB){
        MAIN._CONTAINER_SETTING=sub->Container;
        MAIN._PROP_SETTING=sub;
        if (sp->Base.DetachedPP.LastPs){
            memAssignRef(sp, &sp->Detached, Instance);
            laNotifySubPropUsers(sp, FromInstance);
            return;
        }
        if (!FromInstance) return;
        if (sp->SetState){
            laNotifySubPropUsers(sp, FromInstance);
            sp->SetState(FromInstance, Instance, LA_UI_ACTIVE);
        }
        if (sp->Set){
            laNotifySubPropUsers(sp, FromInstance);
            sp->Set(FromInstance, Instance);
        }
        if (sub->OffsetIsPointer && sub->Offset>=0){
            void **a = (void **)((BYTE *)FromInstance + sub->Offset);
            laNotifySubPropUsers(sp, FromInstance);
            memAssignRefSafe(sub->Container->Hyper?sp:0,FromInstance, a, Instance);
        }
    }
    return;
}
void laAppendInstance(laSubProp *sub, void *FromInstance, void *Instance){
    if (sub->ListHandleOffset){
        lstAppendItem((BYTE *)FromInstance + sub->ListHandleOffset, Instance);
    }
}
void* laGetRaw(laPropPack *pp, int* r_size, int* return_is_a_copy){
    if (pp->LastPs->p->PropertyType == LA_PROP_RAW){
        laRawProp* rp=pp->LastPs->p; 
        if(rp->RawGet){ return rp->RawGet(pp->LastPs->UseInstance, r_size, return_is_a_copy); }
        int s=rp->RawGetSize(pp->LastPs->UseInstance); void* data=0;
        if(rp->Base.OffsetIsPointer){ data=*((void**)(((char*)pp->LastPs->UseInstance)+rp->Base.Offset)); }
        else{ data=((char*)pp->LastPs->UseInstance)+rp->Base.Offset; }
        *return_is_a_copy=0; if(r_size) *r_size=s;
        return data;
    } return 0;
}
int laGetMultiRaw(laPropPack* pp, int* r_chunks, int* r_sizes, void** pointers){
    if (pp->LastPs->p->PropertyType == LA_PROP_RAW){
        laRawProp* rp=pp->LastPs->p; if(!rp->RawMultiGet){ return 0; }
        rp->RawMultiGet(pp->LastPs->UseInstance,r_chunks,r_sizes,pointers);
        if(*r_chunks>0){ return 1; } return 0;
    }
    return 0;
}
int laSetRaw(laPropPack *pp, void* data, uint32_t _size){
    if (pp->LastPs->p->PropertyType == LA_PROP_RAW){ laRawProp* rp=pp->LastPs->p;
        if(rp->RawSet){ rp->RawSet(pp->LastPs->UseInstance, data, _size); return 1; }
        if(rp->Base.OffsetIsPointer){ void** target=(((char*)pp->LastPs->UseInstance)+rp->Base.Offset); if(*target) free(*target);
            void* newd=_size?calloc(1,_size):0; if(_size)memcpy(newd, data, _size); (*target)=newd;
        }
        else{ memcpy(((char*)pp->LastPs->UseInstance)+rp->Base.Offset,data,_size); }
        return 1;
    } return 0;
}

int laTryGetInstanceIdentifier(void* Instance, laPropContainer* pc, char* identifier, char** here){
    if(!Instance || !pc) return 0;
    laProp* p=la_PropLookupIdentifierItem(&pc->Props);
    if(p){
        laPropPack PP={0}; laPropStep PS={0};
        PS.p=p; PS.Type='.'; PS.UseInstance=Instance; PP.LastPs=&PS; PP.EndInstance=Instance;
        if(p->PropertyType==LA_PROP_STRING){ laGetString(&PP,identifier,here); }
        elif(p->PropertyType&LA_PROP_INT){ int r[16]={0}; laGetIntArray(&PP,r); sprintf("(%s=%d)",p->Identifier,r[0]); }
        elif(p->PropertyType&LA_PROP_FLOAT){ real r[16]={0}; laGetFloatArray(&PP,r); sprintf("(%s=%lf)",p->Identifier,r[0]); }
        elif(p->PropertyType&LA_PROP_ENUM){  laEnumItem *r[16]={0}; laGetEnumArray(&PP,r); sprintf("(%s=%lf)",p->Identifier,r[0]?r[0]->Identifier:"?"); }
        else{ sprintf("(%.6x)",identifier,Instance); }
        return 1;
    }
    return 0;
}

int laGetIntRange(laPropPack *pp, int *min, int *max){
    laIntProp *p = pp->LastPs->p;
    if (p->Max != p->Min){
        *min = p->Min;
        *max = p->Max;
        return 1;
    }
    return 0;
}
int laGetFloatRange(laPropPack *pp, real *min, real *max){
    laFloatProp *p = pp->LastPs->p;
    if (p->Max != p->Min){
        *min = p->Min;
        *max = p->Max;
        return 1;
    }
    return 0;
}

int laCanGetMultiRaw(laProp *p,void* inst){
    laRawProp *rp = p; if (p->PropertyType == LA_PROP_RAW){
        if (rp->RawMultiGet && (!rp->RawMultiCanGet || rp->RawMultiCanGet(inst))) return 1; } return 0;
}
int laCanGetState(laProp *sub){ laSubProp *sp = sub; if (sub->PropertyType == LA_PROP_SUB){ if (sp->GetState) return 1; } return 0; }
int laCanGetTheme(laProp *sub){ laSubProp *sp = sub; if (sub->PropertyType == LA_PROP_SUB){ if (sp->GetTheme) return 1; } return 0; }
int laCanGetGap(laProp *sub){ laSubProp *sp = sub; if (sub->PropertyType == LA_PROP_SUB){ if (sp->GetGap) return 1; } return 0; }
int laCanGetCategory(laProp *sub){ laSubProp *sp = sub; if (sub->PropertyType == LA_PROP_SUB){ if (sp->GetCategory) return 1; } return 0; }
int laGetUiState(laProp *sub, void *Instance){
    laSubProp *sp = sub; if (sub->PropertyType == LA_PROP_SUB){ if (sp->GetState) return sp->GetState(Instance); } return 0;
}
laBoxedTheme* laGetUiTheme(laProp *sub, void* parent, void *Instance){
    laSubProp *sp = sub; if (sub->PropertyType == LA_PROP_SUB){ if (sp->GetTheme) return sp->GetTheme(parent,Instance); } return 0;
}
int laGetUiGap(laProp *sub, void* parent, void *Instance){
    laSubProp *sp = sub; if (sub->PropertyType == LA_PROP_SUB){ if (sp->GetGap) return sp->GetGap(parent,Instance); } return 0;
}
void laGetCategory(laProp *sub, void* parent, void *Instance, char* buf, char** buf_ptr){
    laSubProp *sp = sub; if (sub->PropertyType == LA_PROP_SUB){ if (sp->GetCategory) sp->GetCategory(parent,Instance, buf, buf_ptr); }
}
int laSetState(laProp *sub, void *FromInstance, void *Instance, int State){
    laSubProp *sp = sub;
    if (sub->PropertyType == LA_PROP_SUB){
        if (sp->SetState){
            laNotifySubPropUsers(sub, FromInstance);
            return sp->SetState(FromInstance, Instance, State);
        }
    }
    return 0;
}
int laActuateProp(laPropPack *This, laPropPack *RunPP, laOperator *OptionalFrom, laEvent *e){
    if (RunPP->LastPs->p->PropertyType & LA_PROP_OPERATOR){
        if (!((laOperatorProp *)RunPP->LastPs->p)->OperatorType){
            ((laOperatorProp *)RunPP->LastPs->p)->OperatorType = laGetOperatorType(((laOperatorProp *)RunPP->LastPs->p)->OperatorID);
        }
        return laInvokeP(OptionalFrom, ((laOperatorProp *)RunPP->LastPs->p)->OperatorType, e, This, 0, 0); //ARGS
    }
}

void laMarkPropChanged(laPropPack* pp){
    if(!pp) return;
    if(!pp->Go){ if(pp->LastPs&&pp->LastPs->p->Container && pp->LastPs->p->Container->Hyper==2 && pp->LastPs->UseInstance){ 
            laMemNodeHyper* m=memGetHead(pp->LastPs->UseInstance,0); m->Modified=1; } }
    else for(laPropStep* ps=pp->Go;ps;ps=ps->pNext){
        if(ps->Type=='.' && ps->p->Container->Hyper==2 && ps->UseInstance){ 
            laMemNodeHyper* m=memGetHead(ps->UseInstance,0); m->Modified=1; }
    }
    laMarkPropChanged(pp->RawThis);
}
void laMarkMemChanged(void* memuser){
    int level; laMemNodeHyper* m=memGetHead(memuser,&level); if(level!=2) return;
    m->Modified=1;
}
void laMarkMemClean(void* memuser){
    int level; laMemNodeHyper* m=memGetHead(memuser,&level); if(level!=2) return;
    m->Modified=0;
}

laPropContainer *la_SetGeneralRoot(laPropContainer **GeneralRoot, const char *Identifier, const char *Name, const char *Description){
    laPropContainer* ret =memAcquire(sizeof(laPropContainer));
    *GeneralRoot = ret;
    ret->Identifier = Identifier;
    ret->Name = Name;
    ret->Description = Description;
    ret->OtherAlloc=1;
    lstAppendItem(&MAIN.PropContainers, ret);
    return ret;
}

void laSetRootInstance(void *root){
    MAIN.DataRoot.RootInstance = root;
}

laPropContainer *laDefineRoot(){
    if (!MAIN.DataRoot.Root) MAIN.DataRoot.Root = laAddPropertyContainer("root", "__ROOT__", "Root Node In NUL4.0 Data System", U'🞈', 0, 0, 0, 0, 2|LA_PROP_OTHER_ALLOC);
    return MAIN.DataRoot.Root;
}

void laThrowToTrashBin(void *Data, char *ContainerString){
    laPropContainer *pc = la_ContainerLookup(ContainerString);
    lstAppendItem(&pc->TrashBin, Data);
}

int laValidateHyper2(laPropContainer* pc, laPropContainer* ParentHyper2, laSafeString** errors){
    int pass=1;
    for(laProp* p=pc->Props.pFirst;p;p=p->Item.pNext){
        if(p->PropertyType!=LA_PROP_SUB) continue;
        laSubProp* sp=p;
        if(!p->SubProp && !sp->GetType){ 
            p->SubProp=la_ContainerLookup(sp->TargetID);
            if(!p->SubProp){
                strSafePrint(errors, "Unable to locate property container \"%s\".\n", sp->TargetID); pass=0; continue; }
            laPropContainer* spc=p->SubProp;
            laPropContainer* sNoHyper2 = ParentHyper2;
            if(!ParentHyper2){
                if(pc->Hyper==2 && (!(p->UDFNoCreate||p->UDFIsRefer||p->UDFIsSingle))){ 
                    sNoHyper2=pc; }
            }
            if(sNoHyper2){
                if(spc->Hyper==2 && !sp->Base.UDFIsRefer){ strSafePrint(errors,\
                    "Hyper2 list (\"%s\") under another Hyper2 container (\"%s\") is not allowed.\n",
                    sp->TargetID, sNoHyper2->Identifier); pass=0; }
            }
            if(!laValidateHyper2(p->SubProp, sNoHyper2, errors)){pass=0;}
            if(ParentHyper2) ParentHyper2->validated=1;
        }
    }
    return pass;
}
int laValidateProperties(){
    laSafeString* errors=0; int pass=1;
    for(laPropContainer* pc=MAIN.PropContainers.pFirst;pc;pc=pc->Item.pNext){
        if(pc->validated){continue;}
        if(!laValidateHyper2(pc, 0, &errors)){ pass=0; }
        pc->validated=1;
    }
    if(!pass){
        printf("laValidateHyper2 Failed:\n"); printf("%s",SSTR(errors));
    }
    return pass;
}

//==================================[RW]

void la_GetWorkingDirectoryInternal(){
#ifdef LAGUI_ANDROID
    strSafeSet(&MAIN.WorkingDirectory, ""); return;
#endif
    char mbuf[2048]; getcwd(mbuf,2048);
    int len=strlen(mbuf);if(mbuf[len]!=LA_PATH_SEP){ mbuf[len]=LA_PATH_SEP; mbuf[len+1]=0; }
    strSafeSet(&MAIN.WorkingDirectory, mbuf);
}

int laGetRelativeDirectory(char *FullFrom, char *FullTo, char *Result){
    return 0;
    //WIN32_FIND_DATA fd;
    //HANDLE h;
    //char *PathFrom = 0, *PathTo = 0;
    //char FullFromP[1024], FullToP[1024]={0};
    //char *FileNameOnly = 0;
    //int seg, i;
//
    //Result[0] = 0;
//
    //if (!FullFrom || !FullTo || FullFrom[0] != FullTo[0])
    //    return 0;
//
    //strcpy(FullFromP, FullFrom);
    //strcpy(FullToP, FullTo);
//
    //while (h = FindFirstFile(FullFromP, &fd))
    //{
    //    if (h == INVALID_HANDLE_VALUE || (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)))
    //    {
    //        strDiscardLastSegmentSeperateBy(FullFromP, '/');
    //        continue;
    //    }
    //    break;
    //}
//
    //while (h = FindFirstFile(FullToP, &fd))
    //{
    //    if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
    //    {
    //        FileNameOnly = strGetLastSegment(FullToP, '/');
    //        strDiscardLastSegmentSeperateBy(FullToP, '/');
    //        continue;
    //    }
    //    elif (h == INVALID_HANDLE_VALUE)
    //    {
    //        strDiscardLastSegmentSeperateBy(FullToP, '/');
    //        continue;
    //    }
    //    break;
    //}
//
    //strDiscardSameBeginningSeperatedBy(FullFromP, FullToP, &PathFrom, &PathTo, '/');
//
    //seg = strCountSegmentSeperateBy(PathFrom, '/');
//
    //for (i = 0; i < seg; i++)
    //{
    //    strcat(Result, "../");
    //}
//
    //strcat(Result, PathTo);
//
    //if (FileNameOnly)
    //{
    //    strcat(Result, "/");
    //    strcat(Result, FileNameOnly);
    //}
//
    //return 1;
}
void laGetUDFRelativeDirectory(laUDF *From, laUDF *To, char *Result){
    if (!From || !To) return;
    laGetRelativeDirectory(From->FileName->Ptr, To->FileName->Ptr, Result);
}
void laGetFullPath(char *FullFrom, char *Relative, char *Result){
    //WIN32_FIND_DATA fd;
    //HANDLE h;
    //char *PathFrom = 0, *PathTo = 0;
    //char FullFromP[1024] = {0};
    //int seg, i;
//
    //Result[0] = 0;
//
    //if (!FullFrom)
    //    return 0;
//
    //strcpy(FullFromP, FullFrom);
//
    //while (h = FindFirstFile(FullFromP, &fd))
    //{
    //    if (h == INVALID_HANDLE_VALUE || (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)))
    //    {
    //        strDiscardLastSegmentSeperateBy(FullFromP, '/');
    //        continue;
    //    }
    //    break;
    //}
    //strcpy(Result, FullFromP);
    ////strcat(Result, "/");
    //strcat(Result, Relative);
}

laUDF *laPrepareUDF(char *FileName){
    laUDF *udf = memAcquire(sizeof(laUDF));
    strSafeSet(&udf->FileName, FileName);
    return udf;
}

int laWriteProp(laUDF *udf, char *Path){
    laUDFPropSegment *ps = CreateNew(laUDFPropSegment);
    strSafeSet(&ps->Path, Path);
    la_GetPropFromPath(&ps->PP, 0, Path, 0);
    la_StepPropPack(&ps->PP);
    lstAppendItem(&udf->PropsToOperate, ps);
    udf->NumSegmets++;
}
int laWritePropP(laUDF *udf, laPropPack *pp){
    char buf[LA_RAW_CSTR_MAX_LEN] = {0};
    laUDFPropSegment *ps = CreateNew(laUDFPropSegment);

    ps->PPP = pp;
    udf->NumSegmets++;

    //la_GetPropPackFullPath(pp, Buf);
    //strSafeSet(&ps->Path, Buf);

    lstAppendItem(&udf->PropsToOperate, ps);
}
int la_IncludeHyper2Instance(laUDF *udf, laPropContainer* pc, void* Instance){
    laUDFH2Instance *h2 = memAcquire(sizeof(laUDFH2Instance));
    h2->pc=pc; h2->Instance = Instance;
    lstAppendItem(&udf->H2Instances, h2);
    udf->HasInstances=1;
}
int la_ClearHyper2Instances(laUDF* udf){
    laUDFH2Instance *h2;
    while(h2=lstPopItem(&udf->H2Instances)){ memFree(h2); }
    udf->HasInstances=0;
}

//void la_UDFAppendPointerRecord(void* UseInstance, laSubProp* p, void** PendingReference,void* ReadInstance) {
//	//laUDFPointerRecord* upr = &MAIN.PendingPointers[MAIN.NextPendingPointer];
//	//if (!ReadInstance) return;
//	//upr->ReadInstance = ReadInstance;
//	//upr->PendingReference = PendingReference;
//	//upr->SubProp = p;
//	//upr->UseInstance = UseInstance;
//	//MAIN.NextPendingPointer++;
//}
//void la_UDFAppendNUIDRecord(void* UseInstance, laSubProp* p, void** PendingReference, char * ReadNUID) {
//	//laUDFPointerRecord* upr = &MAIN.PendingPointers[MAIN.NextPendingPointer];
//	//if (!ReadNUID) return;
//	//upr->NUID = CreateNewBuffer(char, 23);
//	//strcpy(upr->NUID, ReadNUID);
//	//upr->PendingReference = PendingReference;
//	//upr->SubProp = p;
//	//upr->UseInstance = UseInstance;
//	//MAIN.NextPendingPointer++;
//}
//void la_UDFAppendPointerSync(void* ReadInstance, void* ActualInstance) {
//	//laUDFPointerSync* ups = CreateNew(laUDFPointerSync);
//	//ups->ReadPointer = ReadInstance;
//	//ups->ActualPointer = ActualInstance;
//	//hsh65536InsertItem(&MAIN.PointerSync, ups, ReadInstance);
//}
//void la_UDFAppendNUIDSync(char * ReadNUID, void* ActualInstance) {
//	//laUDFPointerSync* ups = CreateNew(laUDFPointerSync);
//	//ups->NUID = CreateNewBuffer(char, 23);
//	//memcpy(ups->NUID, ReadNUID,sizeof(char)*23);
//	//ups->ActualPointer = ActualInstance;
//	//hsh65536InsertItem(&MAIN.PointerSync, ups, (long)ReadNUID[15]);
//}

void la_UDFAppendSharedTypePointer(char *ID, void *Pointer){
    laSharedTypeItem *sti = memAcquireSimple(sizeof(laSharedTypeItem));
    strCopyFull(sti->ID, ID);
    sti->Pointer = Pointer;
    lstAppendItem(&MAIN.SharedTypePointerSync, sti);
}

#define la_UseUDF(udf) udf->Used = 1

u64bit la_Tell(laUDF *udf){
    if (udf->DiskFile) return ftell(udf->DiskFile);
    else return udf->Seek;
}
int la_Seek(laUDF *udf, u64bit Offset){
    if (udf->DiskFile) return fseek(udf->DiskFile, Offset, SEEK_SET);
    udf->Seek = Offset;
    return 1;
}
u64bit la_FileSize(laUDF* udf){
    if(udf->DiskFile){ u64bit a=ftell(udf->DiskFile); fseek(udf->DiskFile,0,SEEK_END); u64bit sz=ftell(udf->DiskFile); fseek(udf->DiskFile,a,SEEK_SET); return sz; }
    return udf->FileContentSize;
}
void la_WriteString(laUDF *udf, char *String){
    short size = strlen(String);
    fwrite(&size, sizeof(short), 1, udf->DiskFile);
    if (size) fwrite(String, size*sizeof(char), 1, udf->DiskFile);
}
void la_WriteOnlyString(laUDF *udf, char *String){
    fwrite(String, strlen(String), 1, udf->DiskFile);
}
void la_WriteOnlyMBString(laUDF *udf, char *String){
    fwrite(String, strlen(String), 1, udf->DiskFile);
}
void la_WriteInt(laUDF *udf, int Data){
    fwrite(&Data, sizeof(int), 1, udf->DiskFile);
}
void la_WriteUInt(laUDF *udf, uint32_t Data){
    fwrite(&Data, sizeof(uint32_t), 1, udf->DiskFile);
}
void la_WriteUByte(laUDF *udf, unsigned char Data){
    fwrite(&Data, sizeof(unsigned char), 1, udf->DiskFile);
}
void la_WriteShort(laUDF *udf, short Data){
    fwrite(&Data, sizeof(short), 1, udf->DiskFile);
}
void la_WriteLong(laUDF *udf, u64bit Data){
    fwrite(&Data, sizeof(u64bit), 1, udf->DiskFile);
}
void la_WritePointer(laUDF *udf, void *Data){
    fwrite(&Data, sizeof(void *), 1, udf->DiskFile);
}
void la_WriteFloat(laUDF *udf, real Data){
    fwrite(&Data, sizeof(real), 1, udf->DiskFile);
}
void la_WriteSized(laUDF *udf, void* Data, int size){
    printf("%x %d\n",Data,size);
    fwrite(Data, size, 1, udf->DiskFile);
}
short la_ReadShort(laUDF *udf){
    short result;
    if(!udf->FileContent){ fread(&result, sizeof(short), 1, udf->DiskFile); }
    else{ memcpy(&result, udf->FileContent + udf->Seek, sizeof(short)); udf->Seek += sizeof(short); }
    return result;
}
u8bit la_ReadUByte(laUDF *udf){
    u8bit result;
    if(!udf->FileContent){ fread(&result, sizeof(u8bit), 1, udf->DiskFile); }
    else{ memcpy(&result, udf->FileContent + udf->Seek, sizeof(u8bit)); udf->Seek += sizeof(u8bit); }
    return result;
}
int la_ReadInt(laUDF *udf){
    int result;
    if(!udf->FileContent){ fread(&result, sizeof(int), 1, udf->DiskFile); }
    else{ memcpy(&result, udf->FileContent + udf->Seek, sizeof(int)); udf->Seek += sizeof(int); }
    return result;
}
uint32_t la_ReadUInt(laUDF *udf){
    uint32_t result;
    if(!udf->FileContent){ fread(&result, sizeof(uint32_t), 1, udf->DiskFile); }
    else{ memcpy(&result, udf->FileContent + udf->Seek, sizeof(uint32_t)); udf->Seek += sizeof(uint32_t); }
    return result;
}
u64bit la_ReadLong(laUDF *udf){
    u64bit result;
    if(!udf->FileContent){ fread(&result, sizeof(u64bit), 1, udf->DiskFile); }
    else{ memcpy(&result, udf->FileContent + udf->Seek, sizeof(u64bit)); udf->Seek += sizeof(u64bit); }
    return result;
}
void *la_ReadPointer(laUDF *udf){
    u64bit result = 0;
    if(!udf->FileContent){ fread(&result, sizeof(u64bit), 1, udf->DiskFile); }
    else{ memcpy(&result, udf->FileContent + udf->Seek, sizeof(u64bit)); udf->Seek += sizeof(u64bit); }
    return (void *)result;
}
real la_ReadFloat(laUDF *udf){
    real result;
    if(!udf->FileContent){ fread(&result, sizeof(real), 1, udf->DiskFile); }
    else{ memcpy(&result, udf->FileContent + udf->Seek, sizeof(real)); udf->Seek += sizeof(real); }
    return result;
}
void la_ReadString(laUDF *udf, char *buffer){
    short len = la_ReadShort(udf);
    if (len){
        if(!udf->FileContent){ fread(buffer, sizeof(char) * len, 1, udf->DiskFile); }
        else{ memcpy(buffer, udf->FileContent + udf->Seek, sizeof(char) * len); udf->Seek += sizeof(char) * len; }
    }
    buffer[len] = 0;
}
void la_ReadOnlyString(laUDF *udf, short len, char *buffer){
    if(!udf->FileContent){ fread(buffer, sizeof(char) * len, 1, udf->DiskFile); }
    else{ memcpy(buffer, udf->FileContent + udf->Seek, sizeof(char) * len); udf->Seek += sizeof(char) * len; }
    buffer[len] = 0;
}
void la_ReadHyperData(laUDF *udf, void* HyperUserMem){
    short NumUsers, i;
    //void *CreatorInstance = la_ReadLong(udf);
    laMemNodeHyper h_ = {0};
    laMemNodeHyper *h=HyperUserMem?memGetHead(HyperUserMem, 0):&h_;
    //la_UDFAppendPointerRecord(0, 0, &h->CreatedBy,CreatorInstance);

    la_ReadString(udf, h->NUID.String);

    h->TimeCreated.Year = la_ReadShort(udf);
    h->TimeCreated.Month = la_ReadUByte(udf);
    h->TimeCreated.Day = la_ReadUByte(udf);
    h->TimeCreated.Hour = la_ReadUByte(udf);
    h->TimeCreated.Minute = la_ReadUByte(udf);
    h->TimeCreated.Second = la_ReadUByte(udf);
}
void la_PeekHyperUID(laUDF *udf, char* buf){
    int pos=la_Tell(udf);
    la_ReadString(udf, buf);
    la_Seek(udf, pos);
}
void la_ReadBuffer(laUDF *udf, u64bit Size, void *Result){
    if(!udf->FileContent){ fread(Result, Size, 1, udf->DiskFile); }
    else{ memcpy(Result, udf->FileContent + udf->Seek, Size); udf->Seek += Size; }
}
void* la_ReadRaw(laUDF *udf, uint32_t* _sz){
    uint32_t _size = la_ReadUInt(udf);
    if(_sz){
        if (_size){
            void* data=calloc(1,_size);
            la_ReadBuffer(udf, _size, data);
            if(_sz) *_sz=_size;
            return data;
        } return 0;
    }else{
        la_Seek(udf, la_Tell(udf)+_size); return 0;
    }
}

void la_WriteSingleProperty(laUDF *udf, void *FromInstance, laProp *p){
    la_WriteString(udf, p->Identifier);
}
void la_GetPropPackFullPath(laPropPack *pp, char *result){
    char buf[1024], upbuf[1024]={0}; if(!pp){result[0]=0; return;}
    laPropStep *ps;
    buf[0] = U'\0';
    upbuf[0] = 0;

    if (pp->Go){
        for (ps = pp->Go; ps; ps = ps->pNext){
            //if (!ps->p||!ps->p->Identifier) strcat(buf, "?");
            if(ps->Type=='.') strcat(buf, ps->p->Identifier);
            if(ps->Type=='#' ||ps->Type=='@' ||ps->Type=='=') {char b2[2]={0}; b2[0]= ps->Type; strcat(buf, b2); strcat(buf, ps->p);}
            if (ps->pNext && ps->pNext->Type=='.') strcat(buf, ".");
        }
    }else{
        if(pp->LastPs){ if(pp->LastPs->p->Identifier) strcat(buf, pp->LastPs->p->Identifier); else { strcat(buf,"?"); } }
        if (pp->RawThis && pp->RawThis->LastPs->p != pp->LastPs->p) strcat(buf, pp->LastPs->p->Identifier);
    }

    if (pp->RawThis){
        la_GetPropPackFullPath(pp->RawThis, upbuf);
        if (pp->RawThis->LastPs->p != pp->LastPs->p) strcat(upbuf, ".");
        strcat(upbuf, buf);
        strCopyFull(result, upbuf);
    }else
        strCopyFull(result, buf);
}
void la_GetPropPackPath(laPropPack *pp, char *result){
    char buf[1024], upbuf[1024]={0};
    laPropStep *ps;
    buf[0] = U'\0';
    upbuf[0] = 0;
    char Sep[2] = {0};

    for (ps = pp->Go; ps; ps = ps->pNext){
        if (!ps->p->Identifier) break;
        if (ps->Type == U'.' || !ps->Type) strcat(buf, ps->p->Identifier);
        else
            strcat(buf, ps->p);
        if (ps->pNext) strcat(buf, (Sep[0] = ((laPropStep *)ps->pNext)->Type) ? Sep : ".");
    }
    strCopyFull(result, buf);
}
int la_ReadIntProp(laUDF *udf, laPropPack *pp){
    laProp *p;
    int Data[16] = {0};
    int len = 0;
    int i;
    if (!pp){
        int mode = la_ReadShort(udf);
        if (mode == LA_UDF_ARRAY_MARK_32){
            len = la_ReadShort(udf);
            for (i = 0; i < len; i++)
                la_ReadInt(udf);
        }else
            Data[0] = la_ReadInt(udf);
        return Data[0];
    }
    p = pp->LastPs->p;
    short mark=la_ReadShort(udf);
    if(mark==LA_UDF_ARRAY_MARK_64 || mark==LA_UDF_ARRAY_MARK_32){ len = la_ReadShort(udf);
        for(i=0;i<len;i++){ Data[i] = la_ReadInt(udf); }
    }else{
        Data[0] = la_ReadInt(udf);
    }
    if (p->PropertyType & LA_PROP_ARRAY){
        if (pp) laReadIntArrayAllArray(pp, Data);
    }else{
        if (pp) laReadInt(pp, Data[0]);
    }
    return Data[0];
}
real la_ReadFloatProp(laUDF *udf, laPropPack *pp){
    laProp *p;
    real Data[16] = {0};
    int len = 0; int i;
    if (!pp){
        int mode = la_ReadShort(udf);
        if (mode == LA_UDF_ARRAY_MARK_64){
            len = la_ReadShort(udf);
            for (i = 0; i < len; i++)
                la_ReadFloat(udf);
        }else
            Data[0] = la_ReadFloat(udf);
        return Data[0];
    }
    p = pp->LastPs->p;
    short mark=la_ReadShort(udf);
    if(mark==LA_UDF_ARRAY_MARK_64 || mark==LA_UDF_ARRAY_MARK_32){ len = la_ReadShort(udf);
        for(i=0;i<len;i++){ Data[i] = la_ReadFloat(udf); }
    }else{
        Data[0] = la_ReadFloat(udf);
    }
    if (p->PropertyType & LA_PROP_ARRAY){
        if (pp) laReadFloatArrayAllArray(pp, Data);
    }else{
        if (pp) laReadFloat(pp, Data[0]);
    }
    return Data[0];
}
void la_ReadStringProp(laUDF *udf, laPropPack *pp){
    char buf[LA_RAW_CSTR_MAX_LEN]={0}; //XXX: long string not correct...
    int len = 0;
    int i;
    buf[0] = 0;
    la_ReadShort(udf);
    la_ReadString(udf, buf);
    if (pp) laReadString(pp, buf);
}
void la_ReadStringPropAsIdentifier(laUDF *udf, char *buf){
    //char buf[LA_RAW_CSTR_MAX_LEN]={0};
    int len = 0;
    int i;
    buf[0] = 0;
    la_ReadShort(udf);
    la_ReadString(udf, buf);
}
void la_WriteIntProp(laUDF *udf, laPropPack *pp){
    laProp *p = pp->LastPs->p;
    int Data[16] = {0};
    int len = 0;
    int i;
    if (p->PropertyType & LA_PROP_ARRAY){
        la_WriteShort(udf, LA_UDF_ARRAY_MARK_32);
        laGetIntArray(pp, Data);
        len = laGetArrayLength(pp);
        la_WriteShort(udf, len);
        for (i = 0; i < len; i++){
            la_WriteInt(udf, Data[i]);
        }
    }else{
        la_WriteShort(udf, LA_UDF_REGULAR_MARK_32);
        Data[0] = laGetInt(pp);
        la_WriteInt(udf, Data[0]);
    }
}
void la_WriteFloatProp(laUDF *udf, laPropPack *pp){
    laProp *p = pp->LastPs->p;
    real Data[16] = {0};
    int len = 0;
    int i;
    if (p->PropertyType & LA_PROP_ARRAY){
        la_WriteShort(udf, LA_UDF_ARRAY_MARK_64);
        laGetFloatArray(pp, Data);
        len = laGetArrayLength(pp);
        la_WriteShort(udf, len);
        for (i = 0; i < len; i++){
            la_WriteFloat(udf, Data[i]);
        }
    }else{
        la_WriteShort(udf, LA_UDF_REGULAR_MARK_64);
        Data[0] = laGetFloat(pp);
        la_WriteFloat(udf, Data[0]);
    }
}
void la_WriteStringProp(laUDF *udf, laPropPack *pp){
    laProp *p = pp->LastPs->p;
    char _buf[LA_RAW_CSTR_MAX_LEN]={0}; char* buf=_buf;
    int len = 0;
    int i;
    buf[0] = 0;
    la_WriteShort(udf, LA_UDF_STRING_MARK);
    laGetString(pp, _buf, &buf);
    la_WriteString(udf, buf);
}
void la_ReadEnumProp(laUDF *udf, laPropPack *pp, char* orig_string){
    laProp *p;
    int Data[16] = {0};
    int len = 0;
    int i;
    char buf[LA_RAW_CSTR_MAX_LEN]={0};

    if (!pp){
        int mode = la_ReadShort(udf);
        if (mode == LA_UDF_ARRAY_MARK_32){
            len = la_ReadShort(udf);
            for (i = 0; i < len; i++)
                la_ReadString(udf, buf); //la_ReadInt(udf);
        }else
            la_ReadString(udf, buf); //la_ReadInt(udf);
        if(orig_string)strcpy(orig_string, buf);
        return;
    }
    p = pp->LastPs->p;

    if (p->PropertyType & LA_PROP_ARRAY){
        la_ReadShort(udf);
        len = la_ReadShort(udf);
        for (i = 0; i < len; i++){
            la_ReadString(udf, buf);
            Data[i] = laGetEnumFromIdentifier(p, buf)->Index;
            //Data[i] = la_ReadInt(udf);
        }
        if (pp) laReadEnumArrayAll(pp, Data);
    }else{
        la_ReadShort(udf);
        la_ReadString(udf, buf);
        Data[0] = laGetEnumFromIdentifier(p, buf)->Index;
        //Data[0] = la_ReadInt(udf);
        if (pp) laReadEnum(pp, Data[0]);
    }
}
void la_WriteEnumProp(laUDF *udf, laPropPack *pp){
    laProp *p = pp->LastPs->p;
    laEnumItem *Data[16] = {0};
    int len = 0;
    int i;
    if (p->PropertyType & LA_PROP_ARRAY){
        la_WriteShort(udf, (LA_UDF_ARRAY_MARK_32 | LA_UDF_STRING_MARK));
        laGetEnumArray(pp, Data);
        len = laGetArrayLength(pp);
        la_WriteShort(udf, len);
        for (i = 0; i < len; i++){
            la_WriteString(udf, Data[i]->Identifier);
            //la_WriteInt(udf, Data[i]->Index);
        }
    }else{
        la_WriteShort(udf, LA_UDF_STRING_MARK);
        Data[0] = laGetEnum(pp);
        la_WriteString(udf, Data[0]->Identifier);
        //la_WriteInt(udf, Data[0]->Index);
    }
}
void la_ReadRawProp(laUDF *udf, laPropPack *pp){
    la_ReadShort(udf);//mark
    if (pp) {
        uint32_t _size=0;
        void* data=la_ReadRaw(udf,&_size);
        laSetRaw(pp, data, _size); free(data);
    }else{
        la_ReadRaw(udf,0);
    }
}
void la_WriteRawProp(laUDF *udf, laPropPack *pp){
    laProp *p = pp->LastPs->p;
    la_WriteShort(udf, LA_UDF_RAW_MARK);
    if(laCanGetMultiRaw(p,pp->LastPs->UseInstance)){
        int chunks=0; uint32_t sizes[128]={0}; void* pointers[128]={0};
        uint32_t totalsize=0;
        if(laGetMultiRaw(pp,&chunks,sizes,pointers)){ TNS_CLAMP(chunks,1,128);
            for(int i=0;i<chunks;i++){ totalsize+=sizes[i]; } la_WriteUInt(udf,totalsize);
            if(totalsize){
                for(int i=0;i<chunks;i++){ if(sizes[i] && pointers[i]){ la_WriteSized(udf,pointers[i],sizes[i]); free(pointers[i]); } }
            }
        }else{
            la_WriteUInt(udf,0); // no size
        }
        return;
    }
    void* data; uint32_t _size=0, IsCopy=0;
    data=laGetRaw(pp, &_size, &IsCopy);
    if(!data){ _size=0; }
    la_WriteUInt(udf,_size);
    if(_size){ la_WriteSized(udf,data,_size); }
    if(IsCopy && data){ free(data); }
}
void la_WriteHyperData(laUDF *udf, void *HyperUserMem){
    int loc = 0, res = 0, i = 0;
    laItemUserLinker *iul;
    laMemNodeHyper* h=memGetHead(HyperUserMem, 0);
    //la_WriteLong(udf, h->CreatedBy);

    la_WriteString(udf, h->NUID.String);

    la_WriteShort(udf, h->TimeCreated.Year);
    la_WriteUByte(udf, h->TimeCreated.Month);
    la_WriteUByte(udf, h->TimeCreated.Day);
    la_WriteUByte(udf, h->TimeCreated.Hour);
    la_WriteUByte(udf, h->TimeCreated.Minute);
    la_WriteUByte(udf, h->TimeCreated.Second);
}
laSharedTypeItem *la_ReferringToSharedResource(void *p){
    laSharedTypeItem *sti;
    for (sti = MAIN.SharedTypePointerSync.pFirst; sti; sti = sti->Item.pNext){
        if (sti->Pointer == p)
            return sti;
    }
    return 0;
}
void *la_FindSharedResouce(char *id){
    laSharedTypeItem *sti;
    for (sti = MAIN.SharedTypePointerSync.pFirst; sti; sti = sti->Item.pNext){
        if (strSame(id, sti->ID))
            return sti->Pointer;
    }
    return 0;
}

void la_AppendHyperRecord(laUDF *udf, void *HyperUserMem, laPropContainer* pc, u64bit Seek){
    // this happens when theres a type{base{} ... } like tnsobject, should not be problematic...?
    if(lstHasPointer(&udf->HyperRecords, HyperUserMem)) return;
    laUDFHyperRecordItem *hri = lstAppendPointerSized(&udf->HyperRecords, HyperUserMem, sizeof(laUDFHyperRecordItem));
    hri->Seek = Seek;
    hri->pc = pc;
}

void* la_NextH2Instance(laUDF* udf){
    udf->CurrentH2Instance=(udf->CurrentH2Instance?udf->CurrentH2Instance->Item.pNext:0);
}

int la_WriteProp(laUDF *udf, laPropPack *pp, int FromThis, int UseInstanceList){
    laProp *p = pp->LastPs->p, *subp = 0;
    laPropStep SubPS = {0};
    laPropPack SubPP = {0};
    laPropIterator pi = {0};
    laSharedTypeItem *sti;
    laMemNodeHyper *hi;
    void *inst = 0;
    u64bit pReserve = 0, pContinue = 0;
    int ItemNum = 0, PropNum = 0;
    int counted = 0;
    u64bit pEachCount;

    SubPP.LastPs = &SubPS;

    if (p->PropertyType == LA_PROP_OPERATOR) return 0;

    if ((!pp->RawThis) || FromThis){
        char FullPath[1024]={0};
        FullPath[0] = 0;
        la_GetPropPackFullPath(pp, FullPath);
        la_WriteString(udf, FullPath);
    }else{
        la_WriteString(udf, p->Identifier);
    }

    switch (p->PropertyType){
    case LA_PROP_SUB:
        if (p->UDFIsRefer){
            inst = laGetActiveInstanceStrict(p, pp->LastPs->UseInstance);
            if (sti = la_ReferringToSharedResource(inst)){
                la_WriteShort(udf, LA_UDF_SHARE_RESOURCE);
                la_WriteString(udf, sti->ID);
            }else{
                if (!p->SubProp){
                    p->SubProp = la_ContainerLookup(((laSubProp *)p)->TargetID);
                }
                if (p->SubProp->Hyper == 2){
                    la_WriteShort(udf, LA_UDF_REFER | LA_UDF_HYPER_ITEM);
                    if (!inst) la_WriteString(udf, "");
                    else
                        la_WriteString(udf, ((laMemNodeHyper *)memGetHead(inst,0))->NUID.String);
                    udf->TotalRefs++;
                }else{
                    la_WriteShort(udf, LA_UDF_REFER);
                    la_WritePointer(udf, inst);
                }
                pp->EndInstance = inst;
            }
            udf->TotalRefs++;
        }else{
            la_EnsureSubTarget(p,0);

            la_WriteShort(udf, LA_UDF_COLLECTION);
            pReserve = la_Tell(udf); la_WriteInt(udf, 0);   //num items
            if (((laSubProp*)p)->GetType) la_WriteInt(udf, LA_UDF_VARIABLE_NODE_SIZE);
            else la_WriteInt(udf, LA_UDF_FIXED_NODE_SIZE);
            la_WriteShort(udf, LA_UDF_ACTIVE);
            la_WritePointer(udf, laGetActiveInstance(p, pp->LastPs->UseInstance, &pi));

            if (FromThis){
                inst = pp->EndInstance;
            }else{
                inst = laGetInstance(p, pp->LastPs->UseInstance, &pi);
                pp->EndInstance = inst;
            }

            while (inst){
                if(((laSubProp*)p)->SaveFilter && (!((laSubProp*)p)->SaveFilter(pp->LastPs->UseInstance, inst))){
                    inst = laGetNextInstance(p, inst, &pi); pp->EndInstance = inst; continue;
                }
                laPropContainer* pc=p->SubProp; int need_type=0;
                if (((laSubProp*)p)->GetType){ pc=((laSubProp*)p)->GetType(inst); need_type=1; }

                if (pc->Hyper == 2){
                    void* compare=udf->CurrentH2Instance?udf->CurrentH2Instance->Instance:0;
                    if((!p->UDFIsSingle) && UseInstanceList && inst!=compare){
                        inst = laGetNextInstance(p, inst, &pi); pp->EndInstance = inst; continue;}
                    if(need_type){  la_WriteString(udf, pc->Identifier); }
                    hi = inst;
                    la_WriteShort(udf, LA_UDF_HYPER_ITEM);
                    la_AppendHyperRecord(udf, inst, p->SubProp, la_Tell(udf));
                    la_WriteHyperData(udf, inst);
                    memMarkClean(inst);
                }else{
                    if(need_type){  la_WriteString(udf, pc->Identifier); }
                    la_WriteShort(udf, LA_UDF_ITEM);
                }
                
                ItemNum++;

                la_WritePointer(udf, inst);
                la_WriteInt(udf, laGetUiState(p, pp->LastPs->UseInstance));

                PropNum=0; pEachCount = la_Tell(udf); la_WriteShort(udf, 0);
                for (subp = pc->Props.pFirst; subp; subp = subp->Item.pNext){
                    if (subp->UDFIgnore) continue;
                    SubPP.RawThis = pp;
                    SubPS.p = subp;
                    SubPS.UseInstance = inst;
                    if (la_WriteProp(udf, &SubPP, 0, UseInstanceList)) PropNum++;
                }

                if (FromThis){ inst = 0; }else{
                    inst = laGetNextInstance(p, inst, &pi);
                    pp->EndInstance = inst;
                    if(UseInstanceList&&pc->Hyper==2&&(!p->UDFIsSingle)&&(!p->UDFNoCreate)){
                        la_NextH2Instance(udf); if(!udf->CurrentH2Instance) inst=0; }
                }
                pContinue = la_Tell(udf);
                la_Seek(udf, pEachCount); la_WriteShort(udf, PropNum);
                la_Seek(udf, pContinue);
            }
            pContinue = la_Tell(udf);
            la_Seek(udf, pReserve); la_WriteInt(udf, ItemNum);
            la_Seek(udf, pContinue);
        }
        break;
    case LA_PROP_INT:
    case LA_PROP_ARRAY | LA_PROP_INT:
        la_WriteIntProp(udf, pp);
        break;
    case LA_PROP_FLOAT:
    case LA_PROP_ARRAY | LA_PROP_FLOAT:
        la_WriteFloatProp(udf, pp);
        break;
    case LA_PROP_STRING:
        la_WriteStringProp(udf, pp);
        break;
    case LA_PROP_ENUM:
    case LA_PROP_ARRAY | LA_PROP_ENUM:
        la_WriteEnumProp(udf, pp);
        break;
    case LA_PROP_RAW:
        la_WriteRawProp(udf, pp);
        break;
    default:
        break;
    }
    return 1;
}

void la_AddPostReadNode(void *Instance, laContainerPostReadFunc Func){
    laUDFPostRead *upr = lstAppendPointerSized(&MAIN.PostReadNodes, Instance, sizeof(laUDFPostRead));
    upr->Instance = Instance;
    upr->Func = Func;
}

void *la_GetReadDBInstNUID(char *ReferReadNUID){
    if (!ReferReadNUID) return 0;
    laListHandle *l = hsh65536DoHashNUID(&MAIN.DBInst2, ReferReadNUID);
    for (laMemNodeHyper* m = l->pFirst; m; m = m->Item.pNext){
        if (!strcmp(ReferReadNUID, m->NUID.String))
            return ((unsigned char*)m)+sizeof(laMemNodeHyper);
    }
    return 0;
}
void *la_GetReadDBInstPtr(void *ReferRead){
    if (!ReferRead) return 0;
    laListHandle *l = hsh65536DoHashLongPtr(&MAIN.DBInst1, ReferRead);
    for (laMemNode* m = l->pFirst; m; m = m->Item.pNext){
        if (ReferRead == m->ReadInstance)
            return ((unsigned char*)m)+sizeof(laMemNode);
    }
    return 0;
}
void la_AddDataInst(void *ReadInstance, char *ReadNUID, void *ActualInstance){
    laListHandle* l=0;
    void* head=memGetHead(ActualInstance, 0);

    if (ReadNUID) l = hsh65536DoHashNUID(&MAIN.DBInst2, ReadNUID);
    else { l = hsh65536DoHashLongPtr(&MAIN.DBInst1, ReadInstance); ((laMemNode*)head)->ReadInstance = ReadInstance; }

    lstPushItem(l, head); //always push so we get the latest during ptr sync.
}

laPtrSync *la_AddPtrSyncDirect(void *Refer, void *Parent, laProp *Sub){
    laPtrSync *ps = memAcquireSimple(sizeof(laPtrSync));
    ps->RefDB = Refer;
    ps->Parent = Parent;
    ps->Prop = Sub;

    return ps;
}
laPtrSyncCommand *la_AddPtrSyncCommand(void *ReadRefer, void *ParentInst, char *ReadNUID, laProp *Sub){
    laPtrSyncCommand *psc = memAcquireSimple(sizeof(laPtrSyncCommand));
    psc->Target = la_AddPtrSyncDirect(0, ParentInst, Sub);
    psc->ReadInstance = ReadRefer;
    if (ReadNUID){ strcpy(psc->ReadNUID.String, ReadNUID); lstAppendItem(&MAIN.PtrSyncHyper2Commands, psc); }
    else{ lstAppendItem(&MAIN.PtrSyncAddressCommands, psc); }
    return psc;
}

void la_ResetInstance(void* inst, laPropContainer* pc, int IsListItem);
void laRequestAdditionalRegistry(laUDFRegistry* r);
laUDFOwnHyperItem* laNewHyperResource(char* uid);
laUDFOwnHyperItem* laFindHyperResource(char* uid);

void la_LoadAdditionalRegistries(){
    laUDFRegistry* r;
    while(r=lstPopPointer(&MAIN.PendingResourceRequests)){
        laManagedUDF* m;
        logPrint("[INFO] Loading additional resource: %s\n",r->Path->Ptr);
        laUDF* udf = laOpenUDF(r->Path->Ptr, 1, 0, &m);
        if (udf){ laExtractUDF(udf, m, LA_UDF_MODE_OVERWRITE); laCloseUDF(udf); }else{ logPrint("[WARN] Can't open resource: %s\n",r->Path->Ptr); }
    }
}

void la_ExecutePtrSyncCommand(int Mode){
    int i;
    laPtrSyncCommand *psc,*NextPSC;
    laPtrSync *ps;
    void *dbi;
    laListHandle *lps, *ldbi;
    laListHandle L2 = {0};
    int FailCount = 0, AllCount = 0;

    while (psc = lstPopItem(&MAIN.PtrSyncAddressCommands)){
        ps = psc->Target; dbi=0; if (psc->ReadInstance) dbi = la_GetReadDBInstPtr(psc->ReadInstance);

        if (dbi){
            //if (Mode == LA_udf_read)dbi->ReadInst = dbi->ActualInst; //??
            ps->RefDB = dbi; laSetActiveInstance(ps->Prop, ps->Parent, dbi);
        }else{ FailCount++; }

        AllCount++; memFree(psc);
    }

    laUDFOwnHyperItem* ohi;
    for(psc=MAIN.PtrSyncHyper2Commands.pFirst;psc;psc=NextPSC){
        NextPSC=psc->Item.pNext; ps = psc->Target; dbi=0; if (psc->ReadNUID.String[0]) dbi = la_GetReadDBInstNUID(psc->ReadNUID.String);
        if (dbi){
            //if (Mode == LA_udf_read)dbi->ReadInst = dbi->ActualInst; //??
            ps->RefDB = dbi; laSetActiveInstance(ps->Prop, ps->Parent, dbi);
            lstRemoveItem(&MAIN.PtrSyncHyper2Commands,psc);memFree(psc);
        }else{
            if(!(ohi=laFindHyperResource(psc->ReadNUID.String))){
                logPrint("Can't find resource %s\n", psc->ReadNUID.String);
                lstRemoveItem(&MAIN.PtrSyncHyper2Commands,psc);memFree(psc);
                FailCount++;
            }else{
                laRequestAdditionalRegistry(ohi->Registry);
                lstRemoveItem(&MAIN.PtrSyncHyper2Commands,psc);
                lstPushItem(&MAIN.PtrSyncHyper2Commands,psc); continue;
            }
        }
        AllCount++; 
    }

    logPrint("Reference Match: Total %d, Failed %d\n", AllCount, FailCount);
    la_LoadAdditionalRegistries();
}

int la_ExtractFakeProp(laUDF *udf){
    char buf[LA_RAW_CSTR_MAX_LEN] = {0};
    void *Instance = 0;
    void *ReadInstance;
    int ReadState;
    int NumItems;
    short PropNumPerItem;
    void *ActiveInstance;
    int i, j;
    int ItemType;
    short mode, len;
    int VariableNodeSize;
    short PreMode;

    mode = la_ReadShort(udf);
    switch (mode){
    case LA_UDF_REGULAR_MARK_32:
        la_ReadInt(udf);
        break;
    case LA_UDF_REGULAR_MARK_64:
        la_ReadFloat(udf);
        break;
    case (LA_UDF_ARRAY_MARK_32 | LA_UDF_STRING_MARK):
        len = la_ReadShort(udf);
        for (i = 0; i < len; i++)
            la_ReadString(udf, buf);
        break;
    case LA_UDF_ARRAY_MARK_32:
        len = la_ReadShort(udf);
        for (i = 0; i < len; i++)
            la_ReadInt(udf);
        break;
    case LA_UDF_ARRAY_MARK_64:
        len = la_ReadShort(udf);
        for (i = 0; i < len; i++)
            la_ReadFloat(udf);
        break;
    case LA_UDF_STRING_MARK:
        la_ReadString(udf, buf);
        break;
    case LA_UDF_SHARE_RESOURCE:
        la_ReadString(udf, buf);
        break;
    case LA_UDF_REFER:
        la_ReadPointer(udf);
        break;
    case (short)(LA_UDF_REFER | LA_UDF_HYPER_ITEM):
        la_ReadString(udf, buf);
        break;
    case LA_UDF_COLLECTION:
        NumItems = la_ReadInt(udf);
        VariableNodeSize = la_ReadInt(udf);
        VariableNodeSize = (VariableNodeSize == LA_UDF_VARIABLE_NODE_SIZE) ? 1 : 0;
        la_ReadShort(udf); //active mark
        ActiveInstance = la_ReadPointer(udf);

        for (i = 0; i < NumItems; i++){
            if(VariableNodeSize){ la_ReadString(udf,buf); }
            ItemType = la_ReadShort(udf);
            if (ItemType == LA_UDF_HYPER_ITEM){ la_ReadHyperData(udf, 0); }
            ReadInstance = la_ReadPointer(udf);
            ReadState = la_ReadInt(udf);
            PropNumPerItem=la_ReadShort(udf);
            for (j = 0; j < PropNumPerItem; j++){
                la_ReadString(udf, buf);
                la_ExtractFakeProp(udf);
            }
        }
        break;
    case LA_PROP_RAW:
        la_ReadRawProp(udf, 0);
        break;
    default:
        ReadState = ReadState;
        break;
    }
    return 0;
}
int la_ExtractProp(laUDF *udf, laManagedUDF* mUDF, laPropPack *pp, void *ParentInst, int Mode){
    laPropStep SubPS = {0};
    laPropPack SubPP = {0};
    char buf[LA_RAW_CSTR_MAX_LEN] = {0};
    laProp *p = pp->LastPs->p, *subp;
    short SubMode, ItemType = 0;
    void *Instance = 0;
    void *ReadInstance;
    int ReadState;
    int NumItems;
    short PropNumPerItem;
    void *ActiveInstance;
    short PreReadMode;
    int i, j;
    int VariableNodeSize;
    char NodeType[128]={0};
    int EStatus = 0;
    real ReadF;
    int ReadI;
    int IsExceptionNode = 0;

    SubPP.LastPs = &SubPS;

    switch (p->PropertyType){
    case LA_PROP_SUB:
        la_EnsureSubTarget(p, 0);

        SubMode = la_ReadShort(udf);
        if (SubMode == LA_UDF_SHARE_RESOURCE){
            la_ReadString(udf, buf);
            laSetActiveInstance(p, pp->LastPs->UseInstance, la_FindSharedResouce(buf));
        }elif (SubMode == LA_UDF_REFER){
            Instance = la_ReadPointer(udf);
            if (Instance && p->Offset>=0){
                if (p->OffsetIsPointer) la_AddPtrSyncCommand(Instance, ParentInst, 0, p);
                else la_AddDataInst(Instance, 0, ((BYTE *)pp->LastPs->UseInstance + p->Offset));
            }
        }elif (SubMode == (short)(LA_UDF_REFER | LA_UDF_HYPER_ITEM)){
            char NUID[32]={0};
            NUID[0] = 0;
            la_ReadString(udf, NUID);
            if (NUID[0]){
                la_AddPtrSyncCommand(0, ParentInst, NUID, p);
            }
        }elif (SubMode == LA_UDF_COLLECTION){
            laProp **PreList = 0; void *ThisDBInst = 0;

            NumItems = la_ReadInt(udf);
            VariableNodeSize = la_ReadInt(udf);
            VariableNodeSize = (VariableNodeSize == LA_UDF_VARIABLE_NODE_SIZE) ? 1 : 0;
            la_ReadShort(udf); //active mark
            ActiveInstance = la_ReadPointer(udf);

            if (NumItems == 0) break;

            if (p->UDFNoCreate){
                laPropIterator PI = {0};

                ItemType = la_ReadShort(udf);

                Instance = laGetInstance(p, pp->LastPs->UseInstance, &PI);

                la_ResetInstance(Instance, p->SubProp,0);

                if (ItemType == LA_UDF_HYPER_ITEM){
                    if (p->SubProp->Hyper == 2){
                        if (!IsExceptionNode) la_ReadHyperData(udf, Instance);
                        else la_ReadHyperData(udf, 0);
                        if(mUDF) memAssignRef(Instance, &((laMemNodeHyper*)memGetHead(Instance, 0))->FromFile, mUDF);
                        memMarkClean(Instance);
                    }else la_ReadHyperData(udf, 0);
                    if(Mode==LA_UDF_MODE_APPEND){ lstAppendPointer(&MAIN.RenewHyper2s,Instance); }
                }

                if (p->SubProp->PostRead) la_AddPostReadNode(Instance, p->SubProp->PostRead);

                ReadInstance = la_ReadPointer(udf);
                ReadState = la_ReadInt(udf);

                ThisDBInst=Instance;

                PropNumPerItem = la_ReadShort(udf);
                for (j = 0; j < PropNumPerItem; j++){
                    int result;
                    la_ReadString(udf, buf);
                    subp = la_PropLookup(&p->SubProp->Props, buf);
                    SubPP.RawThis = pp;
                    SubPS.p = subp;
                    SubPS.UseInstance = Instance;
                    if ((!subp) ||subp->UDFIgnore){la_ExtractFakeProp(udf); continue;}
                    if (subp&&!subp->SubProp){ subp->SubProp = la_ContainerLookup(((laSubProp *)subp)->TargetID); }
                    
                    result = (IsExceptionNode||!subp) ? result = la_ExtractFakeProp(udf) : la_ExtractProp(udf, mUDF, &SubPP, ThisDBInst, Mode);
                    
                    EStatus = result ? result : EStatus;
                }
                if (p->SubProp->PostReadIm) p->SubProp->PostReadIm(Instance);
            }else{
                if(Mode==LA_UDF_MODE_APPEND && p->UDFIsSingle){
                    logPrint("[Note] Mode is APPEND but property '%s' only allows one instance, will overwrite.\n", p->Identifier);
                }
                for (i = 0; i < NumItems; i++){
                    int RealSize=0; laUDF *SaveUDF = 0; int SaveItemType = 0;IsExceptionNode = 0; Instance=0;

                    laPropContainer* pc=p->SubProp;
                    if(VariableNodeSize){ la_ReadString(udf, NodeType); pc=la_ContainerLookup(NodeType);
                        if(!pc){pc=p->SubProp;} RealSize=pc->NodeSize; 
                    }

                    ItemType = la_ReadShort(udf);

                    if(p->UDFReadProgress){ laShowProgress((real)i/NumItems,-1); } //printf("add pc %s\n",pc->Identifier);

                    if(pc==LA_PC_SOCKET_OUT || pc==LA_PC_SOCKET_IN){ laGraphRequestRebuild(); }

                    int replaced=0;
                    if (udf){
                        int IsItem=((laSubProp*)p)->ListHandleOffset?1:0;
                        RealSize = RealSize ? RealSize : p->SubProp->NodeSize;
                        if (!IsExceptionNode){
                            if (p->UDFIsSingle && (pp->EndInstance=laGetActiveInstanceStrict(pp->LastPs->p,pp->LastPs->UseInstance))){ 
                                Instance = pp->EndInstance; la_ResetInstance(Instance, pc, IsItem); replaced=1;
                            }
                            else{
                                // if overwrite, find the instance here for hyper2, if not Hyper 2 then notice can't overwrite.
                                if (pc->Hyper == 2){
                                    if(Mode==LA_UDF_MODE_OVERWRITE && ItemType == LA_UDF_HYPER_ITEM){
                                        laUID uid; la_PeekHyperUID(udf, &uid.String);
                                        Instance = la_GetReadDBInstNUID(uid.String);
                                        if(Instance){ la_ResetInstance(Instance, pc,IsItem); replaced=1; }
                                        else{ /*logPrint("[Note] Hyper2 item [%s] from property '%s' hasn't been loaded yet, will append.\n", uid.String, p->Identifier);*/ }
                                    }
                                    if(!Instance) Instance = memAcquireHyperNoAppend(RealSize);
                                    memMarkClean(Instance);
                                }elif (pc->Hyper == 1) Instance = memAcquire(RealSize);
                                else Instance = memAcquireSimple(RealSize);
                            }
                        }

                        if (ItemType == LA_UDF_HYPER_ITEM){
                            if (pc->Hyper == 2){
                                la_ReadHyperData(udf, Instance);
                                if(mUDF) memAssignRef(Instance, &((laMemNodeHyper*)memGetHead(Instance, 0))->FromFile, mUDF);
                            }
                            else la_ReadHyperData(udf, 0);
                            if(Mode==LA_UDF_MODE_APPEND){ lstAppendPointer(&MAIN.RenewHyper2s,Instance); }
                        }
                        if (!IsExceptionNode){
                            if (pc->PostRead) la_AddPostReadNode(Instance, pc->PostRead);
                        }

                        ReadInstance = la_ReadPointer(udf);
                        ReadState = la_ReadInt(udf);

                        if (!IsExceptionNode && !replaced){
                            la_AddDataInst(ReadInstance, pc->Hyper == 2 ? ((laMemNodeHyper *)memGetHead(Instance,0))->NUID.String : 0, Instance);
                        }
                        ThisDBInst = Instance;

                        PropNumPerItem = la_ReadShort(udf);
                        for (j = 0; j < PropNumPerItem; j++){
                            u64bit ThisSeek;
                            la_ReadString(udf, buf);
                            subp = la_PropLookup(&pc->Props, buf);
                            if ((!subp) || subp->UDFIgnore) la_ExtractFakeProp(udf);
                            else{
                                int result;
                                ThisSeek = la_Tell(udf);
                                SubPP.RawThis = pp; SubPS.p = subp; SubPS.UseInstance = Instance;
                                la_EnsureSubTarget(subp, 0);
                                
                                result = IsExceptionNode ? la_ExtractFakeProp(udf) : la_ExtractProp(udf, mUDF, &SubPP, ThisDBInst, Mode);
                                
                                EStatus = result ? result : EStatus;
                            }
                        }

                        if (!IsExceptionNode && !replaced){
                            if (pc->PostReadIm) pc->PostReadIm(Instance);
                            if (pp->LastPs->UseInstance){
                                if (!p->UDFIsSingle){
                                    if (((laSubProp *)p)->ListHandleOffset){
                                        laListHandle* inst_lst=(BYTE *)pp->LastPs->UseInstance + ((laSubProp *)p)->ListHandleOffset;
                                        if(p->Container->SaverDummy && p==p->Container->SaverDummy){ laPurgeSaverDummy(pp->LastPs->UseInstance,p); }
                                        lstAppendItem(inst_lst, Instance);
                                    }else{ lstAppendItem(&pc->FailedNodes, Instance); EStatus = 1; }
                                }else{ if (!p->UDFNoCreate){ laSetActiveInstance(p, pp->LastPs->UseInstance, Instance); } }
                                if (ReadInstance == ActiveInstance) laSetActiveInstance(p, pp->LastPs->UseInstance, Instance);
                            }else{
                                if (!p->UDFIsSingle){ lstAppendItem(&pc->FailedNodes, Instance); EStatus = 1; }
                            }
                        }
                    }
                }
            }
            if (PreList) memFree(PreList);
        }
        break;
    case LA_PROP_INT:
    case LA_PROP_ARRAY | LA_PROP_INT:
        ReadI = la_ReadIntProp(udf, pp);
        break;
    case LA_PROP_FLOAT:
    case LA_PROP_ARRAY | LA_PROP_FLOAT:
        ReadF = la_ReadFloatProp(udf, pp);
        break;
    case LA_PROP_STRING:
        la_ReadStringProp(udf, pp);
        break;
    case LA_PROP_ENUM:
    case LA_PROP_ARRAY | LA_PROP_ENUM:
        la_ReadEnumProp(udf, pp, buf);
        break;
    case LA_PROP_RAW:
        la_ReadRawProp(udf, pp);
        break;
    default:
        break;
    }
    return EStatus;
}

int la_RematchPointers(int Mode){
    laUDFPostRead *uprd;
    void* inst;

    la_ExecutePtrSyncCommand(Mode);

    while(uprd=lstPopItem(&MAIN.PostReadNodes)){ uprd->Func(uprd->Instance); memFree(uprd); }
    while(inst=lstPopPointer(&MAIN.RenewHyper2s)){ laMemNodeHyper* h=memGetHead(inst,0);memMakeHyperData(h);memAssignRef(h,&h->FromFile,0);  }
}


int la_WriteHyperRecords(laUDF *udf){
    int i = 0;
    u64bit CountSeek = la_Tell(udf);
    u64bit EndSeek;
    laUDFHyperRecordItem *hri;
    laMemNodeHyper* h;
    la_WriteLong(udf, 0);
    while (hri = lstPopItem(&udf->HyperRecords)){
        h=memGetHead(hri->HyperUserMem, 0);
        la_WriteString(udf, h->NUID.String);
        if(hri->pc) la_WriteString(udf, hri->pc->Identifier); else la_WriteString(udf, "");
        la_WritePointer(udf, hri->Seek);
        i++; memFree(hri);
    }
    EndSeek = la_Tell(udf);
    la_Seek(udf, CountSeek); la_WriteLong(udf, i); la_Seek(udf, EndSeek);

    return i;
}
int la_WritePropQuickSeek(laUDF *udf){
    for(laUDFPropSegment* ps=udf->PropsToOperate.pFirst;ps;ps=ps->Item.pNext){
        la_WriteString(udf,SSTR(ps->Path)); la_WriteLong(udf,ps->WriteQuickSeek);
    }
}
int laPackUDF(laUDF *udf, int UseInstanceList, int DoBackup){
    laUDFPropSegment *ps;
    short NumSegments = 0;
    u64bit RefPos;
    u64bit nuidSeekRef;
    u64bit nuidActualSeek;
    char Root[1024]={0};
    char FilePath[1024]={0};

    if(DoBackup){
        char BackupPath[1024]; sprintf(BackupPath,"%s~",SSTR(udf->FileName));
        if(laCopyFile(BackupPath,udf->FileName->Ptr)){
            logPrintNew("UDF backup written to \"%s\".\n", BackupPath);
        }else{
            logPrintNew("Error trying to back up \"%s\".\n", SSTR(udf->FileName));
        }
    }

    udf->DiskFile = fopen(udf->FileName->Ptr, "wb");
    if (!udf->DiskFile) return 0;

    la_WriteOnlyMBString(udf, LA_UDF_IDENTIFIER);

    u64bit SizeAndExt=la_Tell(udf);
    // reserved for extension switches and file size verifications.
    la_WritePointer(udf, 0);

    RefPos = la_Tell(udf);
    la_WriteLong(udf, 0); //How Many Refs.
    la_WriteShort(udf, udf->NumSegmets);

    la_WriteLong(udf, LA_UDF_NUID_SEEK);
    nuidSeekRef = la_Tell(udf);
    la_WritePointer(udf, 0); //Seek pos for nuid list;

    logPrint("Packing %s:\n", udf->FileName->Ptr);

    udf->CurrentH2Instance=udf->H2Instances.pFirst;

    for(laUDFPropSegment* ps=udf->PropsToOperate.pFirst;ps;ps=ps->Item.pNext){
        printf("    %-15s\n", ps->Path ? ps->Path->Ptr : ps->PPP->LastPs->p->Identifier);
        ps->WriteQuickSeek = la_Tell(udf);
        la_WriteProp(udf, ps->PPP ? ps->PPP : &ps->PP, ps->PPP ? 1 : 0, UseInstanceList);
    }
    logPrint("[ALL DONE]\n\n");

    nuidActualSeek = la_Tell(udf);

    la_WritePropQuickSeek(udf);
    la_WriteHyperRecords(udf);

    u64bit ActualSize=la_Tell(udf);

    la_Seek(udf, RefPos); la_WriteLong(udf, udf->TotalRefs);
    la_Seek(udf, nuidSeekRef); la_WritePointer(udf, nuidActualSeek);
    la_Seek(udf, SizeAndExt); la_WritePointer(udf, ((ActualSize&(0x0000ffffffffffff))<<16)|LA_UDF_EXTENSIONS_ENABLED);

    udf->Modified = 0;

    while(ps = lstPopItem(&udf->PropsToOperate)){
        la_FreePropStepCache(ps->PP.Go);
        strSafeDestroy(&ps->Path);
        FreeMem(ps);
    }

    laCloseUDF(udf);

    laHideProgress();

    return 1;
}

void laExtractProp(laUDF *udf, char* Path){
    laUDFPropSegment *ps = CreateNew(laUDFPropSegment);
    strSafeSet(&ps->Path, Path);
}
int la_PropIsSelected(laUDF* udf, char* Path){
    if(!udf->PropsToOperate.pFirst) return 1;
    for(laUDFPropSegment* ps=udf->PropsToOperate.pFirst;ps;ps=ps->Item.pNext){
        if(strSame(SSTR(ps->Path),Path)) return 1;
    }
    return 0;
}
int laExtractUDF(laUDF *udf, laManagedUDF* mUDF, int Mode){
    char Identifier[9] = {0};
    char buf[1024]={0};
    short Version, NumSegments;
    //laPropStep SubPS = { 0 };
    int PointerBits;
    laPropPack SubPP = {0};
    int i;
    int EStatus = 0;
    u64bit SeekRef;
    int IsPart;

    ma_device_stop(&MAIN.Audio->AudioDevice);
    if(MAIN.InitArgs.HasAudio) laSpinLock(&MAIN.Audio->AudioStatusLock);

    MAIN.IsReadingUDF = 1;

    la_ReadBuffer(udf, sizeof(LA_UDF_IDENTIFIER) - 1, Identifier);

    // file size verification and extension switches.
    u64bit verification=la_ReadPointer(udf);
    u64bit FileSize=verification>>16; int Extensions=verification&LA_UDF_ALL_EXTENSIONS;
    if(FileSize && FileSize<la_FileSize(udf)){ logPrintNew("UDF verification failed for %s\n", udf->FileName->Ptr); return 0; }

    /*udf->TotalRefs = */ la_ReadLong(udf);
    NumSegments = la_ReadShort(udf);
    la_ReadLong(udf); //seek mark
    SeekRef = la_ReadPointer(udf);

    logPrintNew("Extracting UDF [0x%x] %s:\n", udf->Extensions, udf->FileName->Ptr);

    //MAIN.NextPendingPointer = 0;
    //MAIN.PendingPointers = CreateNewBuffer(laUDFPointerRecord, udf->TotalRefs);

    //SubPP.LastPs = &SubP;

    for (i = 0; i < NumSegments; i++){
        void *dbi = 0;
        int result, LastOffset, selected=0;
        la_ReadString(udf, buf);
        LastOffset = strlen(buf) - 1;
        buf[LastOffset] = buf[LastOffset] == U'.' ? 0 : buf[LastOffset];
        logPrint("    Prop Segment \"%s\" ...", buf);
        selected = la_PropIsSelected(udf, buf);
        la_GetPropFromPath(&SubPP, 0, buf, 0);
        la_StepPropPack(&SubPP);
        dbi = SubPP.EndInstance; //la_GetWriteDBInst(SubPP.EndInstance);
        result = (SubPP.LastPs&&SubPP.LastPs->p&&selected)?
            la_ExtractProp(udf, mUDF, &SubPP, dbi, Mode):
            la_ExtractFakeProp(udf);
        EStatus = result ? result : EStatus;
        //if(SubPP.LastPs->p->PropertyType!=LA_PROP_RAW){
        //    laNotifyUsersPP(&SubPP);
        //}
        logPrint(" [Done]\n", buf);
        la_FreePropStepCache(SubPP.Go);
        SubPP.Go = 0;
    }

    la_RematchPointers(Mode);
    
    laHideProgress();
    
    MAIN.IsReadingUDF = 0;

    laUDFPropSegment* ps; while (ps = lstPopItem(&udf->PropsToOperate)){ strSafeDestroy(&ps->Path); FreeMem(ps); }

    if(MAIN.InitArgs.HasAudio) laSpinUnlock(&MAIN.Audio->AudioStatusLock);

    return EStatus;
}

int laExtractQuickRaw(FILE* fp, char* path, uint8_t** buf, size_t* size){
    laUDF _udf={0},*udf=&_udf; udf->DiskFile = fp;
    char str[128];
    char Identifier[32];
    la_Seek(udf,0);
    la_ReadBuffer(udf, sizeof(LA_UDF_IDENTIFIER) - 1, Identifier);
    u64bit verification=la_ReadPointer(udf);
    u64bit FileSize=verification>>16; int Extensions=verification&LA_UDF_ALL_EXTENSIONS;
    if(FileSize && FileSize<la_FileSize(udf)){ return 0; }
    if(!(Extensions & LA_UDF_EXTENSION_QUICK_SEEK)){ return 0; }

    /*udf->TotalRefs = */ la_ReadLong(udf);
    short NumSegments = la_ReadShort(udf);
    la_ReadLong(udf); //seek mark
    off_t SeekRef = la_ReadPointer(udf);

    la_Seek(udf,SeekRef);

    for(int i=0;i<NumSegments;i++){
        la_ReadString(udf,str);
        int Seek = la_ReadLong(udf);
        if(strSame(str,path)){
            la_Seek(udf,Seek);
            la_ReadString(udf, str); // prop name
            la_ReadShort(udf);// raw mark
            void* data=la_ReadRaw(udf,size);
            *buf=data; if(data){ return 1; }
            break;
        }
    }
    return 0;
}

laManagedUDF* la_FindManagedUDF(char* FileName){
    for(laManagedUDF* m=MAIN.ManagedUDFs.pFirst;m;m=m->Item.pNext){
        if(m->udf&&m->udf->FileName&&!strcmp(m->udf->FileName->Ptr,FileName)) return m;
    }
    return 0;
}
laManagedUDF* la_EnsureManagedUDF(char* FileName, int PutAtTop){
    laManagedUDF* m;
    if(!(m=la_FindManagedUDF(FileName))){
        m=memAcquire(sizeof(laManagedUDF)); strSafeSet(&m->BaseName, strGetLastSegment(FileName,LA_PATH_SEP));
        if(PutAtTop) lstPushItem(&MAIN.ManagedUDFs, m); else lstAppendItem(&MAIN.ManagedUDFs, m);
    }
    return m;
}
void la_MakeDummyManagedUDF(){
    MAIN.DummyManageUDF=la_EnsureManagedUDF("< Save as a new file >", 1);
    if(!MAIN.DummyManageUDFSingle){
        MAIN.DummyManageUDFSingle=memAcquire(sizeof(laManagedUDF)); strSafeSet(&MAIN.DummyManageUDFSingle->BaseName, "< Choose file >");
        MAIN.DummyManageUDFSingleForce=memAcquire(sizeof(laManagedUDF)); strSafeSet(&MAIN.DummyManageUDFSingleForce->BaseName, "< Force >");
    }
}
laManagedSaveProp* laSaveProp(char* path){
    if(!path || !path[0]) return 0; laManagedSaveProp* msp=0;
    for(laManagedSaveProp* m=MAIN.ManagedSaveProps.pFirst;m;m=m->Item.pNext){
        if(!strcmp(m->Path->Ptr,path)){ msp=m; break; }
    }
    if(!msp){ msp=memAcquireSimple(sizeof(laManagedSaveProp)); lstAppendItem(&MAIN.ManagedSaveProps, msp); }
    strSafeSet(&msp->Path, path);
    return msp;
}
void laSaveAlongside(laManagedSaveProp* parent, char* path){
    if(!path || !path[0] || !parent) return; laManagedSaveProp* msp=0;
    for(laManagedSaveProp* m=parent->SaveAlongside.pFirst;m;m=m->Item.pNext){
        if(!strcmp(m->Path->Ptr,path)){ msp=m; break; }
    }
    if(!msp){ msp=memAcquireSimple(sizeof(laManagedSaveProp)); lstAppendItem(&parent->SaveAlongside, msp); }
    strSafeSet(&msp->Path, path);
}
void laSetThumbnailProp(char* path){
    strSafeSet(&MAIN.ThumbnailProp,path);
}
void laClearSaveProp(){
    laManagedSaveProp* m; while(m=lstPopItem(&MAIN.ManagedSaveProps)) {
        laManagedSaveProp* ma; while(ma=lstPopItem(&m->SaveAlongside)){ strSafeDestroy(&ma->Path); memFree(ma); }
        strSafeDestroy(&m->Path); memFree(m);
    }
}

int la_ScanForModifiedRecursive(laPropPack* pp, int ReturnIfAnyMod, int ReturnIfAnyEmpty, int* rempty, int RegisterToUDF){
    int result=0;
    laProp* p=pp->LastPs->p; laPropIterator pi={0};
    if(p->PropertyType!=LA_PROP_SUB || p->UDFIsRefer || p->UDFIgnore || p->UDFOnly) return 0;
    la_EnsureSubTarget(p, 0); //if(p->SubProp && p->SubProp->Hyper!=2) return 0;
    void* inst = laGetInstance(p, pp->LastPs->UseInstance, &pi);
    while(inst){
        laPropContainer* pc=la_EnsureSubTarget(p, inst);
        if(pc->Hyper!=2){
            laPropPack spp={0}; laPropStep sps={0}; spp.LastPs=&sps;
            for(laProp* sp=pc->Props.pFirst;sp;sp=sp->Item.pNext){
                sps.UseInstance=inst; sps.p=sp;
                if(sp->PropertyType==LA_PROP_SUB) {
                    result|=la_ScanForModifiedRecursive(&spp, ReturnIfAnyMod, ReturnIfAnyEmpty, rempty, RegisterToUDF);
                    if((ReturnIfAnyMod||ReturnIfAnyEmpty)&&result)return result;
                }
            }
        }else{
            laMemNodeHyper* m = memGetHead(inst,0);
            if(!m->FromFile || m->FromFile==MAIN.DummyManageUDF){ result|=1; if(rempty)*rempty|=1; if((ReturnIfAnyMod||ReturnIfAnyEmpty)&&result)return result; }
            if((!p->UDFIsSingle)&&(!p->UDFNoCreate)&&RegisterToUDF&&m->FromFile&&m->FromFile->udf){ la_IncludeHyper2Instance(m->FromFile->udf, pc, inst); }
            if(m->Modified){
                if(m->FromFile && m->FromFile->udf){ m->FromFile->udf->Modified=1; }
                result|=1; if(ReturnIfAnyMod&&result)return result;
            }
        }
        inst=laGetNextInstance(p,inst,&pi);
    }
    return result;
}
int laRegisterModifications(int ReturnIfAnyMod, int ReturnIfAnyEmpty, int* rempty, int RegisterToUDF){
    int result=0, registered; if(RegisterToUDF){ReturnIfAnyMod=ReturnIfAnyEmpty=0;}
    for(laManagedUDF* m=MAIN.ManagedUDFs.pFirst;m;m=m->Item.pNext){
        if(!m->udf)continue;
        m->udf->Modified=0; 
        la_ClearHyper2Instances(m->udf);
    }
    for(laManagedSaveProp* msp=MAIN.ManagedSaveProps.pFirst;msp;msp=msp->Item.pNext){
        laPropPack PP={0}; registered=0;
        if(msp->Path&&msp->Path->Ptr&&la_GetPropFromPath(&PP, 0, msp->Path->Ptr, 0)){
            la_StepPropPack(&PP);
            result|=la_ScanForModifiedRecursive(&PP, ReturnIfAnyMod, ReturnIfAnyEmpty, rempty, RegisterToUDF);
            for(laManagedUDF* m=MAIN.ManagedUDFs.pFirst;m;m=m->Item.pNext){
                if(!m->udf)continue;
                if(m->udf->HasInstances){ laWriteProp(m->udf,SSTR(msp->Path));
                    for(laManagedSaveProp* am=msp->SaveAlongside.pFirst;am;am=am->Item.pNext){
                        laWriteProp(m->udf,SSTR(am->Path));
                    }
                    m->udf->HasInstances=0;
                }
            }
            if((ReturnIfAnyMod||ReturnIfAnyEmpty)&&result)return result;
            la_FreePropStepCache(PP.Go);
        }
    }
    return result;
}

void la_ReadUDFToMemory(laUDF *udf){
    if (udf->FileContent)
        return;

    fseek(udf->DiskFile, 0, SEEK_END);
    u64bit SeekEnd = ftell(udf->DiskFile);
    fseek(udf->DiskFile, 0, SEEK_SET);

    udf->FileContent = calloc(1, SeekEnd);
    udf->FileContentSize=SeekEnd;

    fread(udf->FileContent, SeekEnd, 1, udf->DiskFile);

    udf->Seek = 0;
}
void la_ReadOwnHyperItems(laUDF *udf, laUDFRegistry* r){
    int Count, i;
    laUDFOwnHyperItem *ohi;
    Count = la_ReadLong(udf);
    int Seek;
    char name[256]; laUID uid;
    for (i = 0; i < Count; i++){
        la_ReadString(udf, uid.String);
        la_ReadString(udf, name);
        Seek=la_ReadPointer(udf);
        laPropContainer* pc = la_ContainerLookup(name);
        if(!laFindHyperResource(uid.String)){
            ohi = laNewHyperResource(uid.String);
            ohi->Registry = r;
            ohi->Seek = Seek;
            strcpy(ohi->NUID.String, uid.String);
            //logPrint("Found Resource: %s | %s\n",ohi->NUID.String,name);
        } else {logPrint("Duplicated Resource: %s | %s\n",uid.String,name);}
    }
}
int la_ReadPropQuickSeek(laUDF *udf){
    char* buf[128];
    for(int i=0;i<udf->NumSegmets;i++){
        laUDFPropQuickSeek *qs = memAcquireSimple(sizeof(laUDFPropQuickSeek));
        la_ReadString(udf,buf); strSafeSet(&qs->Path,buf);
        qs->QuickSeek = la_ReadLong(udf);
        lstAppendItem(&udf->QuickSeeks,qs);
        //logPrint("    %dx QuickSeeks\n",qs->QuickSeek,SSTR(qs->Path));
    }
}

laUDF *laOpenUDF(char *FileName, int ReadToMemory, laUDFRegistry* ReadRegistryRef, laManagedUDF** UseManaged){
    char Identifier[9] = {0};
    u64bit SeekRef;
    laUDF *udf;
    u64bit extensions;
    char FilePath[1024]={0};

    udf=memAcquire(sizeof(laUDF));

    strSafeSet(&udf->FileName, FileName);

    udf->DiskFile = fopen(SSTR(udf->FileName), "rb");
    if (!udf->DiskFile) return 0;

    if(ReadToMemory){ la_ReadUDFToMemory(udf); fclose(udf->DiskFile); udf->DiskFile = 0; }

    la_ReadBuffer(udf, sizeof(LA_UDF_IDENTIFIER) - 1, Identifier);
    if (!strSame(Identifier, LA_UDF_IDENTIFIER)){ laCloseUDF(udf); logPrintNew("\"%s\" is not a UDF file.\n", FileName); return 0; }

    if(UseManaged){
        laManagedUDF* m=la_EnsureManagedUDF(FileName, 0);
        if(!m->udf) m->udf=udf; udf->Managed=1; *UseManaged=m;
    }

    extensions = la_ReadPointer(udf);
    udf->Extensions = extensions & LA_UDF_ALL_EXTENSIONS;
    if((udf->Extensions | LA_UDF_EXTENSIONS_ENABLED)!=LA_UDF_EXTENSIONS_ENABLED){
        logPrint("Unsupported UDF extension 0x%x (0x%x enabled), it's probably saved with a newer version of the program.\n",
            udf->Extensions,LA_UDF_EXTENSIONS_ENABLED);
        laCloseUDF(udf);
        return 0;
    }

    udf->TotalRefs = la_ReadLong(udf);   //total refs
    udf->NumSegmets = la_ReadShort(udf); //num segments
    la_ReadLong(udf);                    //seek mark
    SeekRef = la_ReadPointer(udf);
    la_Seek(udf, SeekRef);

    if(ReadRegistryRef){
        if(udf->Extensions & LA_UDF_EXTENSION_QUICK_SEEK){
            la_ReadPropQuickSeek(udf);
        }
        la_ReadOwnHyperItems(udf, ReadRegistryRef);
    }

    la_Seek(udf, 0);

    udf->Opened = 1;

    return udf;
}
void laCloseUDF(laUDF *udf){
    laUDFOwnHyperItem *ohi;
    laUDFHyperRecordItem *hri;
    laUDFPropSegment *ps;
    laUDFPropQuickSeek *qs;

    if (udf->DiskFile){ fclose(udf->DiskFile); udf->DiskFile=0; };

    while (lstPopPointer(&udf->OwnHyperItems));
    while (lstPopPointer(&udf->HyperRecords));
    while (qs = lstPopItem(&udf->QuickSeeks)){ strSafeDestroy(&qs->Path); memFree(qs); }

    if(udf->CurrentH2Instance){ logPrint("[WARN] udf->CurrentH2Instance!=0 after UDF packing.\n"); udf->CurrentH2Instance=0; }

    udf->NumSegmets=0;

    la_ClearHyper2Instances(udf);

    if(udf->FileContent) FreeMem(udf->FileContent);

    if(!udf->Managed){ strSafeDestroy(&udf->FileName); memFree(udf); }
}

int laLoadHyperResources(char* uid_search){
    int count=0;
    logPrintNew("Loading extra resources \"%s\"\n",uid_search);
    for(laUDFOwnHyperItem* ohi=MAIN.UDFResources.pFirst;ohi;ohi=ohi->Item.pNext){
        if(strstr(ohi->NUID.String,uid_search)){ laRequestAdditionalRegistry(ohi->Registry); count++; };
    }
    if(count){ la_LoadAdditionalRegistries(); } return count;
}
laUDFOwnHyperItem* laFindHyperResource(char* uid){
    for(laUDFOwnHyperItem* ohi=MAIN.UDFResources.pFirst;ohi;ohi=ohi->Item.pNext){
        if(!strcmp(uid, ohi->NUID.String)) return ohi;
    }
    return 0;
}
laUDFOwnHyperItem* laNewHyperResource(char* uid){
    laUDFOwnHyperItem* ohi = memAcquireSimple(sizeof(laUDFOwnHyperItem));
    lstAppendItem(&MAIN.UDFResources, ohi); return ohi;
}
laUDFRegistry* laFindUDFRegistry(char* Path){
    for(laUDFRegistry* r=MAIN.ResourceRegistries.pFirst;r;r=r->Item.pNext){
        if(r->Path && !strcmp(Path, r->Path->Ptr)) return r;
    }
    return 0;
}
laUDFRegistry* laCreateUDFRegistry(char* Path){
    if(!Path) return 0;
    laUDFRegistry* r = memAcquire(sizeof(laUDFRegistry));
    strSafeSet(&r->Path, Path);
    lstAppendItem(&MAIN.ResourceRegistries, r);
    return r;
}
void laRequestAdditionalRegistry(laUDFRegistry* r){
    if(la_FindManagedUDF(r->Path->Ptr)) return;
    if(lstHasPointer(&MAIN.PendingResourceRequests, r)) return;
    logPrint("[INFO] Request additional resources in: %s\n", r->Path->Ptr);
    lstAppendPointer(&MAIN.PendingResourceRequests,r);
}

void laClearUDFRegistries(){
    laUDFOwnHyperItem* ohi; laUDFRegistry* r;
    while(ohi=lstPopItem(&MAIN.UDFResources)) memFree(ohi);
    while(r=lstPopItem(&MAIN.ResourceRegistries)){
        strSafeDestroy(&r->Path); memFree(r);
    }
}
void laGetSubResourceDirectories(char* rootpath_with_slash, laListHandle* out){
    laSafeString*s=0; strSafePrint(&s, "%sUDFExtra" LA_PATH_SEPSTR, rootpath_with_slash); lstAppendPointer(out,s); 
    char Final[1024];
    sprintf(Final, "%s.udfextra",rootpath_with_slash);
    FILE* f=fopen(Final, "r"); if(!f){ return; }
    char dir[1024];
    while(fgets(dir,1024,f)){ laSafeString*s=0; strSafePrint(&s, "%s%s" LA_PATH_SEPSTR, rootpath_with_slash, dir); lstAppendPointer(out,s); }
    fclose(f);
}
void laRefreshUDFResourcesIn(char* rootpath){
    char Final[2048];
    int NumFiles=-1;
    int len = strlen(rootpath);
    if (len && rootpath[len - 1] != LA_PATH_SEP) strcat(rootpath, LA_PATH_SEPSTR);
#if defined(__linux__) || defined(LAGUI_ANDROID)
    struct dirent **NameList=0;
    NumFiles=scandir(rootpath,&NameList,0,alphasort);

    logPrintNew("%d %s",NumFiles,rootpath);

    for(int i=0;i<NumFiles;i++){
        struct dirent* d = NameList[i]; int dlen;
        char *format = strGetLastSegment(d->d_name, '.'); int file_okay=0;
        for(laExtensionType* et=MAIN.ExtraExtensions.pFirst;et;et=et->Item.pNext){ if(et->FileType==LA_FILETYPE_UDF && strSame(et->Extension,format)){file_okay=1;break;} }
        if(!file_okay) continue;


        struct stat s;
        sprintf(Final, "%s%s",rootpath,d->d_name);
        stat(Final, &s);
        if (!S_ISDIR(s.st_mode)){
            if(!laFindUDFRegistry(Final)){
                laUDFRegistry* r = laCreateUDFRegistry(Final);
                laUDF* udf = laOpenUDF(Final, 0, r, 0);
                if(udf) laCloseUDF(udf);
            }
        }
    }
    for (int i=0;i<NumFiles;i++){ free(NameList[i]); } if(NameList) free(NameList);
#endif
#ifdef _WIN32
    WIN32_FIND_DATA FindFileData;
    HANDLE hFind;
    SYSTEMTIME stUTC, stLocal;
    char Lookup[PATH_MAX];
    strCopyFull(Lookup, rootpath); strcat(Lookup, "*.*");
    hFind = FindFirstFile(Lookup, &FindFileData);
    if (hFind == INVALID_HANDLE_VALUE) return;

    while (1){
        NumFiles++;
        char* format = strGetLastSegment(FindFileData.cFileName, '.'); int file_okay = 0;
        for (laExtensionType* et = MAIN.ExtraExtensions.pFirst; et; et = et->Item.pNext) { if (et->FileType == LA_FILETYPE_UDF && strSame(et->Extension, format)) { file_okay = 1; break; } }
        if (file_okay) {
            sprintf(Final, "%s%s", rootpath, FindFileData.cFileName);
            struct stat s; stat(Final, &s);
            if (!(s.st_mode & S_IFDIR)) {
                if (!laFindUDFRegistry(Final)) {
                    laUDFRegistry* r = laCreateUDFRegistry(Final);
                    laUDF* udf = laOpenUDF(Final, 0, r, 0);
                    if (udf) laCloseUDF(udf);
                }
            }
        }
        if (!FindNextFile(hFind, &FindFileData))
            break;
    }
#endif

    if (NumFiles >= 0) {
        laListHandle additionals = { 0 }; laSafeString* s;
        laGetSubResourceDirectories(rootpath, &additionals);
        while (s = lstPopPointer(&additionals)) { laRefreshUDFResourcesIn(s->Ptr); strSafeDestroy(&s); }
    }
}
void laRefreshUDFRegistries(){
    laClearUDFRegistries();
    char LookupM[PATH_MAX];
    for(laResourceFolder* rf = MAIN.ResourceFolders.pFirst;rf;rf=rf->Item.pNext){
#ifdef LAGUI_ANDROID
        sprintf(LookupM,"%s",SSTR(rf->Path));
        laRefreshUDFResourcesIn(LookupM);
        sprintf(LookupM,"%s/%s",MAIN.ExternalDataPath,SSTR(rf->Path));
        laRefreshUDFResourcesIn(LookupM);
        sprintf(LookupM,"%s/%s",MAIN.InternalDataPath,SSTR(rf->Path));
        laRefreshUDFResourcesIn(LookupM);
#else
        realpath(SSTR(rf->Path), LookupM);
        laRefreshUDFResourcesIn(LookupM);
#endif
    }
}

void laStopManageUDF(laManagedUDF* m){
    if(!m) return;
    lstRemoveItem(&MAIN.ManagedUDFs,m);
    if(m->udf) { m->udf->Managed=0; laCloseUDF(m->udf); };
    strSafeDestroy(&m->BaseName);
    memFree(m);
}
void laClearManagedUDF(){
    laManagedUDF* m;
    while(m=MAIN.ManagedUDFs.pFirst){ laStopManageUDF(m); }
}

void laSaveManagedUDF(int ModifiedOnly){
    laRegisterModifications(0,0,0,1);
    if(MAIN.PreSave){ MAIN.PreSave(); }
    for(laManagedUDF* m=MAIN.ManagedUDFs.pFirst;m;m=m->Item.pNext){
        if(!m->udf) continue;
        if(ModifiedOnly && !m->udf->Modified){ continue; }
        if(m->udf->PropsToOperate.pFirst){ laPackUDF(m->udf, 1, 1); }
        laCloseUDF(m->udf);// just in case
    }
    if(MAIN.PostSave){ MAIN.PostSave(); }
}

void laPropagateUDF(laPropContainer* pc, void* inst, int force){
    if(!pc->UDFPropagate) return;
    void* udf=laget_InstanceActiveUDF(inst); if(udf==MAIN.DummyManageUDF) return;
    pc->UDFPropagate(inst, udf, force);
}

void laSetSaveCallback(laPreSaveF PreSave, laPostSaveF PostSave){
    MAIN.PreSave=PreSave;
    MAIN.PostSave=PostSave;
}

//==========================================================================[Manifest]

void laAddResourceFolder(char* Path){
    laResourceFolder* rf=memAcquire(sizeof(laResourceFolder));
    if(Path) strSafeSet(&rf->Path, Path);
    lstAppendItem(&MAIN.ResourceFolders, rf);
}
void laRemoveResourceFolder(laResourceFolder* rf){
    strSafeDestroy(&rf->Path);
    lstRemoveItem(&MAIN.ResourceFolders, rf);
    memFree(rf);
}

void la_ClearUDFRegistryAndFolders(){
    laResourceFolder* rf; while(rf=MAIN.ResourceFolders.pFirst){ laRemoveResourceFolder(rf); }
    laClearUDFRegistries();
}

//==========================================================================[undo]

void laPushDifferenceOnly(char* Description, u64bit hint){
    laDiff* d=memAcquire(sizeof(laDiff));
    lstAppendItem(&MAIN.Differences, d);
    if(MAIN.HeadDifference && Description) strSafeSet(&MAIN.HeadDifference->Description,Description);
    d->Hint=hint; MAIN.HeadDifference=d;
    laNotifyUsers("la.differences");
}
void laPushDifferences(char* Description, u64bit hint){
    memFreeRemainingLeftNodes();
    laPushDifferenceOnly(Description,hint);
}

void la_FreeInstance(void* inst, laPropContainer* pc, int no_free);
void la_FreeDBInst(laDBInst* dbi, int no_freeinst, int cleanup_only, int SkipInstances);
void la_FreeDBProp(laDBProp* dbp, int cleanup_only, int SkipInstances){
    //printf("free dbp %s %x\n",dbp->p->Identifier,dbp);
    if(dbp->p->PropertyType==LA_PROP_SUB){
        if((((laSubProp*)dbp->p)->ListHandleOffset||dbp->p->UDFNoCreate||dbp->p->UDFIsSingle)&&(!dbp->p->UDFIsRefer)&&(!SkipInstances)){
            laDBSubProp* dsp=dbp; laDBInst* si;
            //printf("fdbp %s %x %x %x\n",dbp->p->Identifier,dsp->Instances.pFirst,dsp->Instances.pLast,((laListItem*)dsp->Instances.pFirst)->pNext);
            while(si=lstPopItem(&dsp->Instances)){ la_FreeDBInst(si,dbp->p->UDFNoCreate||(!dbp->p->OffsetIsPointer),cleanup_only,SkipInstances); }
        } // prevent freeing the data;
    }elif(dbp->p->PropertyType==LA_PROP_STRING && ((laStringProp*)dbp->p)->IsSafeString){
        strSafeSet(&dbp->Data,0);
    }elif(dbp->p->PropertyType==LA_PROP_RAW){
        //printf("raw dbp %s\n",dbp->p->Identifier);
        free(dbp->Data);
    }else{
        //printf("-data- %x\n",dbp->Data);
        memFree(dbp->Data);
    }
    memFree(dbp);
}
void la_FreeDBInst(laDBInst* dbi, int no_freeinst, int cleanup_only, int SkipInstances){
    laListHandle* l=hsh65536DoHashLongPtr(MAIN.DBInstLink,dbi->OriginalInstance); lstRemoveItem(l, &dbi->Item2);
    //printf("free dbi %s %x\n", dbi->pc->Identifier,dbi);
    laDBProp* dbp; while(dbp=lstPopItem(&dbi->Props)){ la_FreeDBProp(dbp, cleanup_only,SkipInstances); }
    if(dbi->OriginalInstance && (!cleanup_only)) la_FreeInstance(dbi->OriginalInstance, dbi->pc, no_freeinst);
    memFree(dbi);
}
void la_FreeDiffCommand(laDiffCommand* dc, laDiff* d, int FromLeft){
    //printf("freedc %s\n",dc->p->Identifier);
    if(dc->p->PropertyType==LA_PROP_SUB && (((laSubProp*)dc->p)->ListHandleOffset||dc->p->UDFNoCreate||dc->p->UDFIsSingle) && (!dc->p->UDFIsRefer)){
        laDiffCommandInst* dci; laDiffCommandSub* dcs=dc;
        while(dci=lstPopItem(&dcs->AddedInst)){ if(!FromLeft) la_FreeDBInst(dci->DBInst,(dc->p->UDFNoCreate||(!dc->p->OffsetIsPointer)),0,0); memFree(dci); }
        while(dci=lstPopItem(&dcs->MovedInst)){ memFree(dci); }
        while(dci=lstPopItem(&dcs->RemovedInst)){ if(FromLeft) la_FreeDBInst(dci->DBInst,(dc->p->UDFNoCreate||(!dc->p->OffsetIsPointer)),0,1); memFree(dci); }
    }elif(dc->p->PropertyType==LA_PROP_STRING && ((laStringProp*)dc->p)->IsSafeString){
        strSafeSet(&dc->Data,0);
    }elif(dc->p->PropertyType==LA_PROP_RAW){
        //printf("raw %s\n",dc->p->Identifier);
        free(dc->Data);
    }
    memFree(dc);
}
void la_FreeDifference(laDiff* d, int FromLeft){
    laDiffCommand* dc; laDiffCommandCustom* dcc; laDiffExtraTouched* det;
    while(dc=lstPopItem(&d->Commands)){ la_FreeDiffCommand(dc,d,FromLeft); }
    while(dcc=lstPopItem(&d->CustomCommands)){ if(dcc->Free) dcc->Free(dcc->Data, FromLeft); }
    while(det=lstPopItem(&d->ExtraTouched)){ memFree(det); }
    //if(d->Description&&d->Description->Ptr){printf("%s\n",d->Description->Ptr);}
    strSafeDestroy(&d->Description);
}
void laFreeNewerDifferences(){
    laDiff* PrevD;
    if(MAIN.HeadDifference==MAIN.Differences.pLast) return;
    for(laDiff* d=MAIN.Differences.pLast;d;d=PrevD){
        PrevD=d->Item.pPrev;
        lstRemoveItem(&MAIN.Differences,d);
        la_FreeDifference(d,0);
        if(MAIN.HeadDifference==d){ MAIN.HeadDifference=PrevD; laPushDifferenceOnly(0,0); break; }
    }
}
void laFreeOlderDifferences(int KeepHowMany){
    laDiff* endd; int count=0;
    for(endd=MAIN.HeadDifference;endd;endd=endd->Item.pPrev){
        if(count>=KeepHowMany) break; count++; 
    }
    if(!endd) return; laDiff* d,*NextD;
    while(d=lstPopItem(&MAIN.Differences)){
        NextD=MAIN.Differences.pFirst;
        la_FreeDifference(d,1);
        if(MAIN.HeadDifference==d){ MAIN.HeadDifference=NextD; laPushDifferenceOnly(0,0); break; }
        if(d==endd){ break; }
    }
}
void la_FreeAllDifferences(){
    laFreeNewerDifferences();
    laFreeOlderDifferences(1);
}
void la_NoLongerRecordUndo(){
    la_FreeAllDifferences();
    laDBProp*dbp; while(dbp=lstPopItem(&MAIN.RootDBInst.Props)){ la_FreeDBProp(dbp,1,0); }
    laDBRecordedProp* p; while(p=lstPopItem(&MAIN.DBRecordedProps)){ strSafeDestroy(&p->OriginalPath); memFree(p); }
    hshFree(&MAIN.DBInstLink);
}

void la_RelinkDBInst(laDBInst* dbi, void* New_OriginalInstance){
    if(dbi->OriginalInstance){
        laListHandle* l=hsh65536DoHashLongPtr(MAIN.DBInstLink,dbi->OriginalInstance); lstRemoveItem(l, &dbi->Item2);
    }
    dbi->OriginalInstance = New_OriginalInstance;
    laListHandle* l=hsh65536DoHashLongPtr(MAIN.DBInstLink,dbi->OriginalInstance); lstPushItem(l, &dbi->Item2);
}
laDBInst* laAddDBInst(laDBProp* parent, void* inst, laPropContainer* pc, laDiff* Begin){
    laDBInst* dbi=memAcquire(sizeof(laDBInst)); if(!Begin) Begin=MAIN.HeadDifference;
    dbi->pc=pc;
    if(parent){ lstAppendItem(&((laDBSubProp*)parent)->Instances, dbi); }
    la_RelinkDBInst(dbi, inst);
    return dbi;
}
laDBProp* laAddDBProp(laDBInst* dbi, laProp* p, void* data){
    int size=sizeof(laDBProp);
    if(p->PropertyType==LA_PROP_SUB && (!p->UDFIsRefer)){size=sizeof(laDBSubProp);}
    elif(p->PropertyType==LA_PROP_RAW){size=sizeof(laDBRawProp);}
    laDBProp* dbp=memAcquire(size);
    dbp->p=p; dbp->Data=data;
    lstAppendItem(&dbi->Props, dbp);
    return dbp;
}
void laAddDBPReferAcquire(laDBProp* dbp){
    if(!dbp->Data) return; if(!lstHasPointer(&MAIN.DBInstPendingAcquireDBP, dbp)) lstAppendPointer(&MAIN.DBInstPendingAcquireDBP, dbp);
}
void laAddDiffCMDReferAcquire(laDiffCommand* ds){
    if(!ds->Data) return; if(!lstHasPointer(&MAIN.DBInstPendingAcquireDiffCMD, ds)) lstAppendPointer(&MAIN.DBInstPendingAcquireDiffCMD, ds);
}

laDiffCommand* la_GiveDiffCommand(laDiff* diff, laDBInst* Instance, laProp* p, void* Data){
    for(laDiffCommand* dc=diff->Commands.pFirst;dc;dc=dc->Item.pNext){
        if(dc->Instance == Instance && dc->p == p) return dc;
    }
    int size=sizeof(laDiffCommand);
    if(p->PropertyType==LA_PROP_SUB && (!(p->UDFIsRefer||p->UDFIsSingle||p->UDFNoCreate))){size=sizeof(laDiffCommandSub);}
    elif(p->PropertyType==LA_PROP_RAW){size=sizeof(laDiffCommandRaw);}
    laDiffCommand* dc = memAcquire(size);
    dc->Instance=Instance; dc->p=p; dc->Data = Data;
    lstAppendItem(&diff->Commands,dc);
    return dc;
}
void la_GiveExtraTouched(laDiff* diff, laDBInst* dbi){
    if(!dbi->pc->UndoTouched) return;
    laDiffExtraTouched* det=memAcquire(sizeof(laDiffExtraTouched));
    det->dbi=dbi; lstAppendItem(&diff->ExtraTouched,det);
}

int la_AddIntDBProp(laDBInst* dbi, laDBProp* dbp, laDiff* diff, laPropPack *pp){
    laProp *p = pp->LastPs->p; int *Data; int len = laGetArrayLength(pp); int ret=0;
    Data= memAcquireSimple(sizeof(int)*len);
    laGetIntArray(pp, Data); if(diff&&dbp){
        if(memcmp(dbp->Data, Data, sizeof(int)*len)){ la_GiveDiffCommand(diff, dbi, p, dbp->Data); dbp->Data=Data; ret=1; } else memFree(Data);
    }
    else laAddDBProp(dbi, p, Data);
    return ret;
}
int la_AddFloatDBProp(laDBInst* dbi, laDBProp* dbp, laDiff* diff, laPropPack *pp){
    laProp *p = pp->LastPs->p; real *Data; int len = laGetArrayLength(pp); int ret=0;
    Data= memAcquireSimple(sizeof(real)*len);
    laGetFloatArray(pp, Data); if(diff&&dbp){
        if(memcmp(dbp->Data, Data, sizeof(real)*len)){ la_GiveDiffCommand(diff, dbi, p, dbp->Data); dbp->Data=Data; ret=1; } else memFree(Data);
    }
    else laAddDBProp(dbi, p, Data);
    return ret;
}
int la_AddStringDBProp(laDBInst* dbi, laDBProp* dbp, laDiff* diff, laPropPack *pp){
    laProp *p = pp->LastPs->p; char _buf[LA_RAW_CSTR_MAX_LEN]={0}; char* buf=_buf; int ret=0;
    laGetString(pp, _buf, &buf); if(diff&&dbp){
        if((!dbp->Data&&buf[0]) || (buf[0] && strcmp(buf, ((laSafeString*)dbp->Data)->Ptr)) || (!buf[0]&&dbp->Data)){
            laDiffCommand* dc=la_GiveDiffCommand(diff, dbi, p, dbp->Data); dbp->Data=0; strSafeSet(&dbp->Data, buf); ret=1; }
    }else{
        laDBProp* dbp=laAddDBProp(dbi, p, 0); strSafeSet(&dbp->Data, buf);
    }
    return ret;
}
int la_AddEnumDBProp(laDBInst* dbi, laDBProp* dbp, laDiff* diff, laPropPack *pp){
    laProp *p = pp->LastPs->p; laEnumItem **Data=0; int len = laGetArrayLength(pp); int ret=0;
    Data= memAcquireSimple(sizeof(laEnumItem*)*len);
    laGetEnumArray(pp, Data); if(diff&&dbp){
        if(memcmp(dbp->Data, Data, sizeof(laEnumItem*)*len)){ la_GiveDiffCommand(diff, dbi, p, dbp->Data); dbp->Data=Data; ret=1; } else memFree(Data);
    }else laAddDBProp(dbi, p, Data);
    return ret;
}
int la_AddRawDBProp(laDBInst* dbi, laDBRawProp* dbp, laDiff* diff, laPropPack *pp){
    laProp *p = pp->LastPs->p; int *Data; int s=0; int ret=0; int IsCopy=0;
    Data=laGetRaw(pp,&s,&IsCopy); if(diff&&dbp){
        if(dbp->DataSize!=s || (!dbp->Data&&Data) || (!Data&&dbp->Data) || (dbp->Data&&Data&&memcmp(dbp->Data, Data, s))){
            //printf("s%d %x %d \n",s,Data,dbp->DataSize);
            void* NewData=(s&&Data)?calloc(1,s):0;
            if(s&&Data)memcpy(NewData, Data, s);
            laDiffCommandRaw* dcr=la_GiveDiffCommand(diff, dbi, p, dbp->Data);
            dcr->DataSize=dbp->DataSize; dbp->Data=NewData; dbp->DataSize=s; ret=1;
        }
    }
    else{
        void* NewData=s?calloc(1,s):0; if(s) memcpy(NewData, Data, s);
        laDBRawProp* dbp=laAddDBProp(dbi, p, NewData); dbp->DataSize=s;
    }
    if(IsCopy){ free(Data); }
    return ret;
}

laDiffCommandInst* la_NewDiffCommandInst(laDBInst* DBInst, laDBInst* Prev, laDBInst* Next){
    laDiffCommandInst* dci=memAcquire(sizeof(laDiffCommandInst));
    dci->DBInst = DBInst; dci->OriginalPrev = Prev; dci->OriginalNext = Next;
    dci->BeforePrev = DBInst->Item.pPrev; dci->BeforeNext = DBInst->Item.pNext;
    return dci;
}
laDBInst* la_GetDiffDBInst(laListHandle* NewAdded, laListHandle* Master, void* instance){
    if(!instance) return 0;
    for(laDiffTemp* dt=NewAdded->pFirst;dt;dt=dt->Item.pNext){
        if(((laDBInst*)dt->p)->OriginalInstance == instance) return dt->p;
    }
    for(laDBInst* dbi=Master->pFirst;dbi;dbi=dbi->Item.pNext){
        if(dbi->OriginalInstance==instance) return dbi;
    }
    return 0;
}

int laIterateDB(laDBInst* parent, laPropPack* pp, laDiff* diff, laDBProp* dp);
int la_GenerateListDifferences(laDBInst* dbi, laDBSubProp* dbp, laPropPack* pp, laDiff* diff){
    laProp *p = pp->LastPs->p, *subp = 0;
    laPropIterator pi={0};
    void* inst; int any=0;
    laListHandle New={0}, NewAdded={0}, NewDeleted={0}, NewMoved={0};

    inst = laGetInstance(p, pp->LastPs->UseInstance, &pi);
    pp->EndInstance = inst;
    while (inst){
        if(p->UDFIsSingle){ memTake(inst); /* For single must take or it will be freed. */ }
        lstAppendPointer(&New, inst);
        inst = laGetNextInstance(p, inst, &pi);
        pp->EndInstance = inst;
    }

    for(laDBInst* dbi=dbp->Instances.pFirst;dbi;dbi=dbi->Item.pNext){
        void* OldPrev=dbi->Item.pPrev?((laDBInst*)dbi->Item.pPrev)->OriginalInstance:0;
        void* OldNext=dbi->Item.pNext?((laDBInst*)dbi->Item.pNext)->OriginalInstance:0;
        int found=0; for(laListItemPointer* lip=New.pFirst;lip;lip=lip->pNext){
            void* NewPrev=lip->pPrev?((laListItemPointer*)lip->pPrev)->p:0;
            void* NewNext=lip->pNext?((laListItemPointer*)lip->pNext)->p:0;
            if(lip->p == dbi->OriginalInstance){
                found=1;
                if(OldPrev==NewPrev && OldNext==NewNext){break;}
                else{ laDiffTemp* dt=lstAppendPointerSized(&NewMoved, dbi, sizeof(laDiffTemp));
                    dt->tPrev=dbi->Item.pPrev; dt->tNext=dbi->Item.pNext; dt->nPrev=NewPrev; dt->nNext=NewNext;break;}
            }
        }
        if(!found){
            laDiffTemp* dt=lstAppendPointerSized(&NewDeleted, dbi, sizeof(laDiffTemp));dt->tPrev=dbi->Item.pPrev;dt->tNext=dbi->Item.pNext; any++;
        }
    }
    for(laListItemPointer* lip=New.pFirst;lip;lip=lip->pNext){
        int found=0; for(laDBInst* dbi=dbp->Instances.pFirst;dbi;dbi=dbi->Item.pNext){
            if(lip->p == dbi->OriginalInstance){ found=1; }
        }
        if(!found){ any++;
            laDiffTemp* dt=lstAppendPointerSized(&NewAdded, lip->p, sizeof(laDiffTemp));
            void* NewPrev=lip->pPrev?((laListItemPointer*)lip->pPrev)->p:0;
            void* NewNext=lip->pNext?((laListItemPointer*)lip->pNext)->p:0;
            dt->tPrev=NewPrev; dt->tNext=NewNext;
            laPropContainer* spc=p->SubProp; if(((laSubProp*)p)->GetType){spc=((laSubProp*)p)->GetType(lip->p);}
            laDBInst* newdbi=laAddDBInst(0, lip->p, spc, diff); dt->p=newdbi;
            for (subp = spc->Props.pFirst; subp; subp = subp->Item.pNext){
                if (subp->UDFIgnore || subp->UDFOnly) continue;
                if (subp->PropertyType == LA_PROP_OPERATOR) continue;
                laPropStep SubPS = {0}; laPropPack SubPP = {0}; laPropIterator pi={0};
                SubPP.RawThis = pp; SubPS.p = subp; SubPS.UseInstance = lip->p; SubPP.LastPs=&SubPS;
                any+=laIterateDB(newdbi, &SubPP, 0, 0);
            }
        }
    }

    for(laDiffTemp* lip=NewAdded.pFirst;lip;lip=lip->Item.pNext){
        laDBInst* newdbi=lip->p;
        lip->tPrev = la_GetDiffDBInst(&NewAdded, &dbp->Instances, lip->tPrev);
        lip->tNext = la_GetDiffDBInst(&NewAdded, &dbp->Instances, lip->tNext);
    }
    for(laDiffTemp* lip=NewMoved.pFirst;lip;lip=lip->Item.pNext){
        laDBInst* newdbi=lip->p;
        lip->tPrev = la_GetDiffDBInst(&NewAdded, &dbp->Instances, lip->nPrev);
        lip->tNext = la_GetDiffDBInst(&NewAdded, &dbp->Instances, lip->nNext);
    }

    laDiffCommandSub* dc=(NewAdded.pFirst||NewDeleted.pFirst||NewMoved.pFirst)?la_GiveDiffCommand(diff, dbi, p, 0):0;
    for(laDiffTemp* lip=NewAdded.pFirst;lip;lip=lip->Item.pNext){
        lstAppendItem(&dc->AddedInst, la_NewDiffCommandInst(lip->p, 0, 0));
        laDBInst* newdbi=lip->p;
        newdbi->Item.pPrev = lip->tPrev; newdbi->Item.pNext = lip->tNext;
        if(!newdbi->Item.pPrev){dbp->Instances.pFirst=newdbi;}
        if(!newdbi->Item.pNext){dbp->Instances.pLast=newdbi;}
    }
    for(laDiffTemp* lip=NewMoved.pFirst;lip;lip=lip->Item.pNext){
        laDBInst* dbi=lip->p; lstAppendItem(&dc->MovedInst, la_NewDiffCommandInst(dbi, lip->tPrev, lip->tNext));
        laDBInst* newdbi=lip->p;
        newdbi->Item.pPrev = lip->tPrev; newdbi->Item.pNext = lip->tNext;
        if(!dbi->Item.pPrev){dbp->Instances.pFirst=dbi;}
        if(!dbi->Item.pNext){dbp->Instances.pLast=dbi;}
    }

    if(!New.pFirst){ dbp->Instances.pFirst=dbp->Instances.pLast=0; }
    
    for(laDiffTemp* lip=NewDeleted.pFirst;lip;lip=lip->Item.pNext){printf("deleted %x %x\n", dbi, dbi->OriginalInstance);
        laDBInst* dbi=lip->p; lstAppendItem(&dc->RemovedInst, la_NewDiffCommandInst(dbi, lip->tPrev, lip->tNext));
        memTake(dbi->OriginalInstance);
        //if(!dbi->Item.pPrev){dbp->Instances.pFirst=dbi->Item.pNext;}
        //if(!dbi->Item.pNext){dbp->Instances.pLast=dbi->Item.pPrev;}
        dbi->Item.pPrev=dbi->Item.pNext=0; //lstRemoveItem(&dbp->Instances, dbi);
        laPropStep SubPS = {0}; laPropPack SubPP = {0}; laPropIterator pi={0}; laDBProp* dpi=0; SubPP.LastPs = &SubPS;
        laPropContainer* spc=p->SubProp; if(((laSubProp*)p)->GetType){spc=((laSubProp*)p)->GetType(dbi->OriginalInstance);}
        dpi=dbi->Props.pFirst;
        for (subp = spc->Props.pFirst; subp; subp = subp->Item.pNext){
            if (subp->PropertyType == LA_PROP_OPERATOR) continue;
            if (subp->UDFIgnore || subp->UDFOnly) continue;

            if((!dpi)||dpi->p!=subp) printf("Prop doesn't match\n");

            SubPP.RawThis = pp; SubPS.p = subp; SubPS.UseInstance = dbi->OriginalInstance;
            int thisany=laIterateDB(dbi, &SubPP, diff, dpi);
            
            dpi=dpi->Item.pNext;
            if(thisany){ any+=thisany; la_GiveExtraTouched(diff,dbi); }
        }
        dbi=dbi->Item.pNext;
    }

    //printf("%x ~ %x\n", dbp->Instances.pFirst, dbp->Instances.pLast);
    //laListItem* item = laGetInstance(p, pp->LastPs->UseInstance, &pi);
    //while (item){
    //    printf("    %x [%x] %x\n",item->pPrev, item, item->pNext);
    //    item = laGetNextInstance(p, item, &pi);
    //}
    return any;
}

int laIterateDB(laDBInst* parent, laPropPack* pp, laDiff* diff, laDBProp* dp){
    laProp *p = pp->LastPs->p, *subp = 0;
    laPropStep SubPS = {0}; laPropPack SubPP = {0}; laPropIterator pi={0};
    laDBProp* dbp; laDBSubProp* dsp; laDBInst* dbi; laDBProp* dpi=0;
    void *inst = 0;
    SubPP.LastPs = &SubPS;
    int any=0;

    switch (p->PropertyType){
    case LA_PROP_SUB:
        if (p->UDFIsRefer){ if(!parent) return 0;
            inst = laGetActiveInstanceStrict(p, pp->LastPs->UseInstance);
            if(diff){
                if(inst!=dp->Data) la_GiveDiffCommand(diff, parent, p, dp->Data); dp->Data=inst; any++;
            }else{
                laDBProp* rdbp=laAddDBProp(parent, p, inst);
            }
        }else{
            if (!p->SubProp) p->SubProp = la_ContainerLookup(((laSubProp *)p)->TargetID);
            if(diff){ any+=la_GenerateListDifferences(parent, dp, pp, diff); dsp=dp; dbi=dsp->Instances.pFirst; dbp=dsp; }
            else{ dbp=laAddDBProp(parent, p, laGetActiveInstance(p, pp->LastPs->UseInstance, &pi)); }

            inst = laGetInstance(p, pp->LastPs->UseInstance, &pi);
            pp->EndInstance = inst;
            while (inst){ //printf("work  %x\n",inst);
                laPropContainer* spc=p->SubProp; if(((laSubProp*)p)->GetType){spc=((laSubProp*)p)->GetType(inst);}
                if(!spc){ inst = laGetNextInstance(p, inst, &pi); continue; } // unlikely, because not registered
                if(diff){
                    if(dbi->OriginalInstance != inst){ 
                        printf("dbi/inst doesn't match.\n"); }
                    dpi=dbi->Props.pFirst;
                }else{ dbi = laAddDBInst(dbp, inst, spc, 0); }
                
                for (subp = spc->Props.pFirst; subp; subp = subp->Item.pNext){
                    if (subp->PropertyType == LA_PROP_OPERATOR) continue;
                    if (subp->UDFIgnore || subp->UDFOnly) continue;

                    if(diff && ((!dpi)||dpi->p!=subp)){
                         printf("Prop doesn't match\n");}

                    SubPP.RawThis = pp; SubPS.p = subp; SubPS.UseInstance = inst;
                    int thisany=laIterateDB(dbi, &SubPP, diff, dpi);
                    
                    if(diff && dpi){ dpi=dpi->Item.pNext;
                        if(thisany){ any+=thisany;
                         la_GiveExtraTouched(diff,dbi); }
                    }
                }
                inst = laGetNextInstance(p, inst, &pi);
                pp->EndInstance = inst;
                if(diff){ dbi=dbi->Item.pNext; }
            }
        }
        break;
    case LA_PROP_INT: case LA_PROP_ARRAY | LA_PROP_INT:
        any+=la_AddIntDBProp(parent, dp, diff, pp); break;
    case LA_PROP_FLOAT: case LA_PROP_ARRAY | LA_PROP_FLOAT:
        any+=la_AddFloatDBProp(parent, dp, diff, pp); break;
    case LA_PROP_STRING:
        any+=la_AddStringDBProp(parent, dp, diff, pp); break;
    case LA_PROP_ENUM:  case LA_PROP_ARRAY | LA_PROP_ENUM:
        any+=la_AddEnumDBProp(parent, dp, diff, pp); break;
    case LA_PROP_RAW:
        any+=la_AddRawDBProp(parent,dp,diff,pp); break;
    default: break;
    }
    return any;
}

void la_RestoreIntDBProp(laDBProp* dbp, laDiffCommand* dc){
    laPropPack pp={0}; laPropStep ps={0}; ps.p=dc->p; pp.LastPs=&ps; ps.UseInstance=dc->Instance->OriginalInstance;
    int *Data; Data=dc->Data; dc->Data=dbp->Data; dbp->Data=Data;
    laSetIntArrayAllArray(&pp, dbp->Data);
}
void la_RestoreFloatDBProp(laDBProp* dbp, laDiffCommand* dc){
    laPropPack pp={0}; laPropStep ps={0}; ps.p=dc->p; pp.LastPs=&ps; ps.UseInstance=dc->Instance->OriginalInstance;
    int *Data; Data=dc->Data; dc->Data=dbp->Data; dbp->Data=Data;
    laSetFloatArrayAllArray(&pp, dbp->Data);
}
void la_RestoreStringDBProp(laDBProp* dbp, laDiffCommand* dc){
    laPropPack pp={0}; laPropStep ps={0}; ps.p=dc->p; pp.LastPs=&ps; ps.UseInstance=dc->Instance->OriginalInstance;
    int *Data; Data=dc->Data; dc->Data=dbp->Data; dbp->Data=Data;
    laSetString(&pp, dbp->Data?((laSafeString*)dbp->Data)->Ptr:0);
}
void la_RestoreEnumDBProp(laDBProp* dbp, laDiffCommand* dc){
    laPropPack pp={0}; laPropStep ps={0}; ps.p=dc->p; pp.LastPs=&ps; ps.UseInstance=dc->Instance->OriginalInstance;
    int *Data; Data=dc->Data; dc->Data=dbp->Data; dbp->Data=Data;
    laSetEnumArrayAllArray(&pp, dbp->Data);
}
void la_RestoreRawDBProp(laDBRawProp* dbp, laDiffCommandRaw* dc){
    laPropPack pp={0}; laPropStep ps={0}; ps.p=dc->p; pp.LastPs=&ps; ps.UseInstance=dc->Instance->OriginalInstance;
    int *Data; Data=dc->Data; dc->Data=dbp->Data; dbp->Data=Data; LA_SWAP(int, dc->DataSize, dbp->DataSize);
    laSetRaw(&pp,dbp->Data,dbp->DataSize);
}

void la_AddUndoPostNode(laDBInst* dbi){
    if((!dbi->pc) || (!dbi->pc->UndoTouched)) return;
    for(laDiffPost* dp=MAIN.DiffTouched.pLast;dp;dp=dp->Item.pPrev){ if(dp->instance==dbi->OriginalInstance&&dp->Touched==dbi->pc->UndoTouched) return; }
    laDiffPost* dp=lstAppendPointerSized(&MAIN.DiffTouched, dbi->OriginalInstance, sizeof(laDiffPost));
    dp->Touched=dbi->pc->UndoTouched;
}

void la_ExecUndoPtrSync(laDiff* d){
    int hint=d->Hint; laDiffPtrSync* dps; laDiffPost* dp; laDBInstPendingRelink* dpr;

    while(dp=lstPopItem(&MAIN.DiffTouched)){
        dp->Touched(dp->instance, hint);
        memFree(dp);
    }
    for(laDiffExtraTouched*det=d->ExtraTouched.pFirst;det;det=det->Item.pNext){
        det->dbi->pc->UndoTouched(det->dbi->OriginalInstance, hint);
    }
}
void la_FreeInstance(void* inst, laPropContainer* pc, int no_free){
    //if(p->PropertyType!=LA_PROP_SUB) return;
    //if(!p->SubProp || ((laSubProp*)p)->TargetID) p->SubProp=la_ContainerLookup(((laSubProp*)p)->TargetID);
    //laPropContainer* pc=p->SubProp; if(((laSubProp*)p)->GetType) pc=((laSubProp*)p)->GetType(inst);
    //printf("freeinst %s %x\n",pc->Name,inst);
    if(pc->BeforeFree) pc->BeforeFree(inst);
    laPropStep SubPS = {0}; laPropPack SubPP = {0}; laPropIterator pi={0}; SubPP.LastPs=&SubPS; 
    for(laProp* p=pc->Props.pFirst;p;p=p->Item.pNext){
        if(p->PropertyType==LA_PROP_STRING && ((laStringProp*)p)->IsSafeString){ SubPS.p=p; SubPS.UseInstance=inst; laSetString(&SubPP, 0); continue; }
        //if(p->PropertyType!=LA_PROP_SUB || p->UDFIsRefer) continue;
        //void* si = laGetInstance(p, SubPP.LastPs->UseInstance, &pi); SubPP.EndInstance = si; void* NextSi=0;
        //printf("freeinst p %s\n",p->Name);
        //while (si){
        //    printf("%x --inst %x\n",SubPP.LastPs->UseInstance,si);
        //    NextSi = laGetNextInstance(p, si, &pi);
        //    if(!p->UDFNoCreate){ laSubProp* sp=p;
        //        if(!sp->ListHandleOffset){ logPrint("[WARN] prop '%s' UDFNoCreate==0 and no ListHandleOffset. Node not removed.\n", p->Identifier); }
        //        else{ lstRemoveItem(inst + sp->ListHandleOffset, si); }
        //    }
        //    la_FreeInstance(si, p, p->UDFNoCreate||(!p->OffsetIsPointer));
        //    si=NextSi; SubPP.EndInstance = si;
        //}
    }
    if(!no_free && !pc->OtherAlloc) memFree(inst);
}
void la_ResetInstance(void* inst, laPropContainer* pc, int IsListItem){
    if(pc->SaverDummy) laMarkMemClean(((char*)inst)+((laSubProp*)pc->SaverDummy)->ListHandleOffset);
    if(pc->Reset) pc->Reset(inst); //else { int a=IsListItem?sizeof(laListItem):0; memset(((char*)inst)+a,0,pc->NodeSize-a); }
}

laListHandle* la_GetOriginalListHandle(laDiffCommandSub* dcs){
    laProp*p =dcs->Base.p;
    if(p->PropertyType!=LA_PROP_SUB||p->UDFIsRefer||!((laSubProp*)p)->ListHandleOffset) return 0;
    laSubProp* sp=dcs->Base.p;
    void* addr=((char*)dcs->Base.Instance->OriginalInstance)+((laSubProp*)p)->ListHandleOffset;
    return addr;
}

void la_UndoListDifferences(laDBSubProp* dsp, laDiffCommandSub* dcs){
    laListHandle* ol=la_GetOriginalListHandle(dcs);
    for(laDiffCommandInst* dci=dcs->AddedInst.pFirst;dci;dci=dci->Item.pNext){
        if(dcs->Base.p->UDFNoCreate){ la_ResetInstance(dci->DBInst->OriginalInstance,dci->DBInst->pc,((laSubProp*)dcs->Base.p)->ListHandleOffset?1:0); continue; }
        dci->OriginalPrev = dci->DBInst->Item.pPrev; dci->OriginalNext = dci->DBInst->Item.pNext;
        //if(dsp->Instances.pFirst == dci->DBInst){ dsp->Instances.pFirst=dci->DBInst->Item.pNext; ol->pFirst=dci->DBInst->Item.pNext?((laDBInst*)dci->DBInst->Item.pNext)->OriginalInstance:0; }
        //if(dsp->Instances.pLast == dci->DBInst){ dsp->Instances.pLast=dci->DBInst->Item.pPrev; ol->pLast=dci->DBInst->Item.pPrev?((laDBInst*)dci->DBInst->Item.pPrev)->OriginalInstance:0; }
        //dci->DBInst->Item.pPrev = dci->DBInst->Item.pNext=0;
    }
    for(laDiffCommandInst* dci=dcs->AddedInst.pFirst;dci;dci=dci->Item.pNext){
        if(dcs->Base.p->UDFNoCreate){  continue; }
        lstRemoveItem(&dsp->Instances, dci->DBInst); lstRemoveItem(ol, dci->DBInst->OriginalInstance); 
        laListItem* li = dci->DBInst->OriginalInstance;
    }
    for(laDiffCommandInst* dci=dcs->RemovedInst.pFirst;dci;dci=dci->Item.pNext){ if(dcs->Base.p->UDFNoCreate) continue;
        dci->DBInst->Item.pPrev = dci->OriginalPrev;
        dci->DBInst->Item.pNext = dci->OriginalNext; printf("add removed %s %x \n",dci->DBInst->pc->Identifier, dci->DBInst->OriginalInstance);
        void* orig = dci->DBInst->OriginalInstance;
    }
    for(laDiffCommandInst* dci=dcs->RemovedInst.pFirst;dci;dci=dci->Item.pNext){ if(dcs->Base.p->UDFNoCreate) continue;
        ((laListItem*)dci->DBInst->OriginalInstance)->pPrev=dci->OriginalPrev?dci->OriginalPrev->OriginalInstance:0;
        ((laListItem*)dci->DBInst->OriginalInstance)->pNext=dci->OriginalNext?dci->OriginalNext->OriginalInstance:0;
        if(!dci->DBInst->Item.pPrev){ dsp->Instances.pFirst=dci->DBInst; ol->pFirst=dci->DBInst->OriginalInstance; }
        if(!dci->DBInst->Item.pNext){ dsp->Instances.pLast=dci->DBInst; ol->pLast=dci->DBInst->OriginalInstance; }
    }
    for(laDiffCommandInst* dci=dcs->MovedInst.pFirst;dci;dci=dci->Item.pNext){
        dci->DBInst->Item.pPrev = dci->BeforePrev; ((laListItem*)dci->DBInst->OriginalInstance)->pPrev=dci->BeforePrev?dci->BeforePrev->OriginalInstance:0;
        dci->DBInst->Item.pNext = dci->BeforeNext; ((laListItem*)dci->DBInst->OriginalInstance)->pNext=dci->BeforeNext?dci->BeforeNext->OriginalInstance:0;
        if(!dci->DBInst->Item.pPrev){ dsp->Instances.pFirst=dci->DBInst; ol->pFirst=dci->DBInst->OriginalInstance; }
        if(!dci->DBInst->Item.pNext){ dsp->Instances.pLast=dci->DBInst; ol->pLast=dci->DBInst->OriginalInstance; }
    }
}
void la_RedoListDifferences(laDBSubProp* dsp, laDiffCommandSub* dcs){
    laListHandle* ol=la_GetOriginalListHandle(dcs);
    for(laDiffCommandInst* dci=dcs->RemovedInst.pFirst;dci;dci=dci->Item.pNext){
        if(dcs->Base.p->UDFNoCreate){ la_ResetInstance(dci->DBInst->OriginalInstance,dci->DBInst->pc,((laSubProp*)dcs->Base.p)->ListHandleOffset?1:0); continue; }
        //dci->OriginalPrev = dci->DBInst->Item.pPrev;
        //dci->OriginalNext = dci->DBInst->Item.pNext;
        lstRemoveItem(&dsp->Instances, dci->DBInst); lstRemoveItem(ol, dci->DBInst->OriginalInstance); 
        laListItem* li = dci->DBInst->OriginalInstance;
        printf("remove %x \n", dci->DBInst->OriginalInstance);
    }
    for(laDiffCommandInst* dci=dcs->AddedInst.pFirst;dci;dci=dci->Item.pNext){ if(dcs->Base.p->UDFNoCreate) continue;
        dci->DBInst->Item.pPrev = dci->OriginalPrev;
        dci->DBInst->Item.pNext = dci->OriginalNext;
        void* orig = dci->DBInst->OriginalInstance;
    }
    for(laDiffCommandInst* dci=dcs->AddedInst.pFirst;dci;dci=dci->Item.pNext){ if(dcs->Base.p->UDFNoCreate) continue;
        ((laListItem*)dci->DBInst->OriginalInstance)->pPrev=dci->OriginalPrev?dci->OriginalPrev->OriginalInstance:0;
        ((laListItem*)dci->DBInst->OriginalInstance)->pNext=dci->OriginalNext?dci->OriginalNext->OriginalInstance:0;
        if(!dci->DBInst->Item.pPrev){ dsp->Instances.pFirst=dci->DBInst; ol->pFirst=dci->DBInst->OriginalInstance; }
        if(!dci->DBInst->Item.pNext){ dsp->Instances.pLast=dci->DBInst; ol->pLast=dci->DBInst->OriginalInstance; }
    }
    for(laDiffCommandInst* dci=dcs->MovedInst.pFirst;dci;dci=dci->Item.pNext){
        dci->DBInst->Item.pPrev = dci->OriginalPrev; ((laListItem*)dci->DBInst->OriginalInstance)->pPrev=dci->OriginalPrev?dci->OriginalPrev->OriginalInstance:0;
        dci->DBInst->Item.pNext = dci->OriginalNext; ((laListItem*)dci->DBInst->OriginalInstance)->pNext=dci->OriginalNext?dci->OriginalNext->OriginalInstance:0;
        if(!dci->DBInst->Item.pPrev){ dsp->Instances.pFirst=dci->DBInst; ol->pFirst=dci->DBInst->OriginalInstance; }
        if(!dci->DBInst->Item.pNext){ dsp->Instances.pLast=dci->DBInst; ol->pLast=dci->DBInst->OriginalInstance; }
    }
}

laDBProp* la_FindDBProp(laDBInst* dbi, laProp* p){
    for(laDBProp* dbp=dbi->Props.pFirst;dbp;dbp=dbp->Item.pNext){
        if(dbp->p==p) return dbp;
    }
    return 0;
}

void tnsPrintMaterials();
laDiff* laSwapDBState(int Redo){
    laDiff* diff=MAIN.HeadDifference; if(!diff) return 0;
    if(Redo){ if(diff==MAIN.Differences.pLast) return 0; }else{ diff=diff->Item.pPrev; if(!diff) return 0; }
    for(laDiffCommand* dc=diff->Commands.pFirst;dc;dc=dc->Item.pNext){
        //printf("do %s\n",dc->p->Identifier);
        laDBProp* dbp=la_FindDBProp(dc->Instance, dc->p);
        if(!dbp){ printf("Can't find dbp from prop!\n");}
        switch (dc->p->PropertyType){
        case LA_PROP_SUB:
            if(dc->p->UDFIsRefer){
                LA_SWAP(void*,dc->Data,dbp->Data);
                laSetActiveInstance(dbp->p, dc->Instance->OriginalInstance, dbp->Data);
            }else{
                if(Redo) la_RedoListDifferences(dbp,dc);
                else     la_UndoListDifferences(dbp,dc);
            }
            la_AddUndoPostNode(dc->Instance);
            break;
        case LA_PROP_INT: case LA_PROP_ARRAY | LA_PROP_INT:
            la_RestoreIntDBProp(dbp, dc); la_AddUndoPostNode(dc->Instance); break;
        case LA_PROP_FLOAT: case LA_PROP_ARRAY | LA_PROP_FLOAT:
            la_RestoreFloatDBProp(dbp, dc); la_AddUndoPostNode(dc->Instance); break;
        case LA_PROP_STRING:
            la_RestoreStringDBProp(dbp, dc); la_AddUndoPostNode(dc->Instance); break;
        case LA_PROP_ENUM: case LA_PROP_ARRAY | LA_PROP_ENUM:
            la_RestoreEnumDBProp(dbp, dc); la_AddUndoPostNode(dc->Instance); break;
        case LA_PROP_RAW:
            la_RestoreRawDBProp(dbp, dc); la_AddUndoPostNode(dc->Instance); break;
        default: break;
        }
        laPropPack PP={0}; laPropStep PS={0}; PP.LastPs=&PS; PS.p=dbp->p; PS.UseInstance=dc->Instance->OriginalInstance;
        laNotifyUsersPP(&PP);
    }
    for(laDiffCommandCustom* dcc=diff->CustomCommands.pFirst;dcc;dcc=dcc->Item.pNext){
        if(Redo){ if(dcc->Redo) dcc->Redo(dcc->Data); } else { if(dcc->Undo) dcc->Undo(dcc->Data); }
    }
    tnsPrintMaterials();
    if(Redo){ MAIN.HeadDifference=diff->Item.pNext; }
    else{ MAIN.HeadDifference=diff; }
    return diff;
}
void laUndo(){ laDiff* d; if(d=laSwapDBState(0)){ la_ExecUndoPtrSync(d); laNotifyUsers("la.differences"); } }
void laRedo(){ laDiff* d; if(d=laSwapDBState(1)){ la_ExecUndoPtrSync(d); laNotifyUsers("la.differences"); } }

void laPrintDBInst(laDBInst* dbi, int Level){
    if(dbi!=&MAIN.RootDBInst){
        printf("%*c", Level, ' ');
        printf("%s  |  %.6x [%.6x] %.6x  |  %.6x [%.6x] %.6x\n",
            dbi->pc->Identifier, dbi->Item.pPrev, dbi, dbi->Item.pNext,
            dbi->Item.pPrev?((laDBInst*)dbi->Item.pPrev)->OriginalInstance:0, dbi->OriginalInstance, dbi->Item.pNext?((laDBInst*)dbi->Item.pNext)->OriginalInstance:0);
    }else{
        printf("Root:\n");
    }
    for(laDBProp* dbp=dbi->Props.pFirst;dbp;dbp=dbp->Item.pNext){
        if(dbp->p->PropertyType==LA_PROP_SUB && !dbp->p->UDFIsRefer){
            laDBSubProp* dsp=dbp;
            for(laDBInst* dbii=dsp->Instances.pFirst;dbii;dbii=dbii->Item.pNext){
                laPrintDBInst(dbii, Level+4);
            }
        }
    }
}
void laPrintDBInstInfo(){
    laPrintDBInst(&MAIN.RootDBInst, 0);
}

void laAddRootDBInst(char* path){
    laPropPack PP={0};
    if(!la_GetPropFromPath(&PP,0,path,0)) return;
    if(!MAIN.DBInstLink){ hsh65536Init(&MAIN.DBInstLink); }
    la_StepPropPack(&PP);
    laIterateDB(&MAIN.RootDBInst, &PP, 0, 0);
    la_FreePropStepCache(PP.Go);
    laDBRecordedProp* rp=lstAppendPointerSized(&MAIN.DBRecordedProps, 0, sizeof(laDBRecordedProp));
    strSafeSet(&rp->OriginalPath,path);
}

void laPropPackToLocal(laPropPack* ToPP, laPropPack* pp){
    if(pp->RawThis) laPropPackToLocal(ToPP, pp->RawThis);
    for(laPropStep* ps=pp->Go;ps;ps=ps->pNext){
        la_NewPropStep(ToPP, ps->p, ps->UseInstance, '.');
    }
    ToPP->EndInstance = pp->EndInstance;
}
laDBProp* laFindDBProp(laDBInst* parent, laProp* p, void* Instance, laDBInst** r_DBInst){
    laDBProp* rp=0;
    for(laDBProp* dp=parent->Props.pFirst;dp;dp=dp->Item.pNext){
        if(dp->p == p) {rp=dp; break;}
    } if(!rp) return 0;
    if(rp->p->PropertyType==LA_PROP_SUB && !rp->p->UDFIsRefer && r_DBInst && Instance){
        laDBSubProp* dsp=rp; for(laDBInst* dbii=dsp->Instances.pFirst;dbii;dbii=dbii->Item.pNext){
            if(dbii->OriginalInstance == Instance) { *r_DBInst=dbii; break; }
        }
    }
    return rp;
}
laDBProp* laFindStartingDBProp(laProp* p, void* Instance, laPropContainer* InstancePC, laDBInst** r_DBInst){
    if(!Instance||Instance==MAIN.DataRoot.RootInstance){
        for(laDBProp*dbp=MAIN.RootDBInst.Props.pFirst;dbp;dbp=dbp->Item.pNext){
            if(dbp->p == p){ *r_DBInst=&MAIN.RootDBInst; return dbp; }
        }
    } /* If root not found try to find it in the hash. */
    if(!MAIN.DBInstLink){ return 0; }
    laListHandle* l=hsh65536DoHashLongPtr(MAIN.DBInstLink, Instance); if(!l) return 0;
    for(laListItem* li=l->pFirst;li;li=li->pNext){
        laDBInst* dbi=(laDBInst*)(((char*)li)-sizeof(laListItem)); if(dbi->OriginalInstance==Instance && dbi->pc==InstancePC){
            if(p){ for(laDBProp*dbp=dbi->Props.pFirst;dbp;dbp=dbp->Item.pNext){ if(dbp->p == p){ *r_DBInst=dbi; return dbp; } } }
            else{ *r_DBInst=dbi; return 0; }
        }
    }
    return 0;
}
void laRecordCustomDifferences(void* Data, laDiffCommandUndoF Undo, laDiffCommandRedoF Redo, laDiffCommandFreeF Free){
    laDiffCommandCustom* dcc=memAcquire(sizeof(laDiffCommandCustom));
    dcc->Data=Data; dcc->Undo=Undo; dcc->Redo=Redo; dcc->Free=Free;
    lstAppendItem(&MAIN.HeadDifference->CustomCommands,dcc);
}
int laRecordDifferences(laPropPack* base, char* path){
    laPropPack PP={0};
    if(!la_GetPropFromPath(&PP,base,path,0)) return 0;
    la_StepPropPack(&PP);
    //laPropPackToLocal(&LocalPP, &PP);
    int success=0;

    laDBInst* FromDBI; //=laSkipDB(&LocalPP, &MAIN.RootDBInst, &dbp);
    laDBProp* dbp=laFindStartingDBProp(PP.LastPs->p, PP.LastPs->UseInstance, PP.LastPs->p->Container, &FromDBI);

    if(FromDBI && dbp){
        laFreeNewerDifferences();
        laIterateDB(FromDBI, &PP, MAIN.HeadDifference, dbp);
        if(MAIN.HeadDifference->Commands.pFirst){ success = 1; }
    }else{
        success = 0; //printf("Prop not recorded as DBInst.\n");
    }

    la_FreePropStepCache(PP.Go);
    return success;
}
int laRecordInstanceDifferences(void* instance, const char* container){
    laPropContainer* pc=la_ContainerLookup(container); if(!pc) return 0;
    laDBInst* FromDBI=0;
    laFindStartingDBProp(0,instance,pc,&FromDBI); if(!FromDBI) return 0;
    laPropPack PP={0}; laPropStep PS={0}; PS.UseInstance=instance; PP.LastPs=&PS; 
    int freed=0, success=0, any=0;
    for(laProp* p=pc->Props.pFirst;p;p=p->Item.pNext){
        PS.p = p; laDBProp* dbp=laFindDBProp(FromDBI, p, 0,0);
        if(FromDBI && dbp){
            if(!freed){ laFreeNewerDifferences(); freed=1; }
            any+=laIterateDB(FromDBI, &PP, MAIN.HeadDifference, dbp);
            if(MAIN.HeadDifference->Commands.pFirst){ success = 1; }
        }
    }
    if(any){ la_GiveExtraTouched(MAIN.HeadDifference,FromDBI); }

    return success;
}
void laRecordAndPush(laPropPack* base, char* path, char* description, uint64_t hint){
    if(laRecordDifferences(base, path)){ laPushDifferences(description, hint); }
}
void laRecordAndPushProp(laPropPack* base, char* path){
    char buf[256]={0};
    if(laRecordDifferences(base, path)){
        la_GetPropPackFullPath(base,&buf[strlen(buf)]);if(path){sprintf(&buf[strlen(buf)],"%s%s",base?".":"",path);}
        laPushDifferences(buf, 0);
    }
}
void laRecordEverythingAndPush(){
    for(laDBRecordedProp* rp=MAIN.DBRecordedProps.pFirst;rp;rp=rp->Item.pNext){
        laRecordAndPushProp(0, rp->OriginalPath->Ptr);
    }
    if(MAIN.PushEverything){ MAIN.PushEverything(); }
}
void laSetDiffCallback(laDiffPushEverythingF PushEverything){
    MAIN.PushEverything=PushEverything;
}