#include once "window9.bi"

sub RecursionPushIndex(byval tree As hwnd , ByVal Item As Integer)
    dim as integer iChild = Cast(Integer,SendMessage(tree,TVM_GETNEXTITEM,TVGN_CHILD,Cast(LPARAM,Item)))
    if iChild then
        RecursionPushIndex(tree , iChild)
    endif
    iChild = Cast(Integer,SendMessage(tree,TVM_GETNEXTITEM,TVGN_NEXT,Cast(LPARAM,Item)))
    if iChild then
        RecursionPushIndex(tree , iChild)
    EndIf
    dim as any ptr pStackIndexes = GetProp(tree, "stackindexes")
    if pStackIndexes then
        Dim TV_ITEM_ As TV_ITEM
        TV_ITEM_.mask=TVIF_IMAGE Or TVIF_SELECTEDIMAGE
        TV_ITEM_.hItem = cast(any ptr ,Item)
        SendMessage(tree,TVM_GETITEM,0,Cast(lparam,@TV_ITEM_))
        if TV_ITEM_.iImage <> -2 then
            PushStackFreeIndexes(pStackIndexes , TV_ITEM_.iImage)
        EndIf
        if TV_ITEM_.iSelectedImage <> -2 then
            PushStackFreeIndexes(pStackIndexes , TV_ITEM_.iSelectedImage)
        EndIf
    EndIf
End Sub

Sub DeleteTreeViewItem(ByVal gadget As Long , ByVal Item As Integer)
    dim as hwnd tree = GadgetID(gadget)
    dim as integer imgList = Cast(Integer,GetHimageCombo_(gadget))
    if imgList andalso ImageList_GetImageCount(cast(any ptr ,imgList)) then
        Dim TV_ITEM_ As TV_ITEM
        TV_ITEM_.mask=TVIF_IMAGE Or TVIF_SELECTEDIMAGE
        TV_ITEM_.hItem = cast(any ptr ,Item)
        if SendMessage(tree,TVM_GETITEM,0,Cast(lparam,@TV_ITEM_)) then
            dim as integer iChild = Cast(Integer,SendMessage(tree,TVM_GETNEXTITEM,TVGN_CHILD,Cast(LPARAM,Item)))
            dim as integer iParent = Cast(Integer,SendMessage(tree,TVM_GETNEXTITEM,TVGN_PARENT,Cast(LPARAM,Item)))
            dim as integer iBrother = Cast(Integer,SendMessage(tree,TVM_GETNEXTITEM,TVGN_NEXT,Cast(LPARAM,Item)))
            dim as any ptr pStackIndexes = GetProp(tree, "stackindexes")
            if iParent = 0 andalso iBrother = 0 then
                if pStackIndexes then
                    FreeStackFreeIndexes(pStackIndexes)
                EndIf
                ImageList_RemoveAll(cast(any ptr ,imgList))
            else
                if iChild then
                    RecursionPushIndex(tree , iChild)
                EndIf
                if pStackIndexes then
                    if TV_ITEM_.iImage <> -2 then
                        PushStackFreeIndexes(pStackIndexes , TV_ITEM_.iImage)
                    EndIf
                    if TV_ITEM_.iSelectedImage <> -2 then
                        PushStackFreeIndexes(pStackIndexes , TV_ITEM_.iSelectedImage)
                    EndIf
                endif
            EndIf
        endif
    EndIf
    SendMessage(tree,TVM_DELETEITEM,0,Cast(lparam,item))
End Sub