

  function(map_decycle val)
    map_new()
    ans(visited_nodes)
    map_set(global ref_count 0)
    set(map_decycle_flatten true)
    function(decycle_successors result node)
      message("getting successors")
      
      map_isvalid(${node} )
      ans(ismap)
      ref_isvalid(${node})
      ans(isref)
      set(potential_successors)
      if(ismap)
        map_keys(${node} )
        ans(keys)
        foreach(key ${keys})
          map_get(${node}  ${key} )
          ans(val)
          ref_isvalid(${val})
          ans(isref)
          if(isref)

            map_tryget(${visited_nodes}  "${val}")
            ans(ref_id)
            if(ref_id)
              set(val ${ref_id})
              map_set(${node} ${key} ${ref_id})
            endif()
          endif()

          list(APPEND potential_successors ${val})
        endforeach()
      elseif(isref)
        ref_get(${node})
        ans(res)
        set(transformed_res)
        foreach(element ${res})
          ref_isvalid(${element})
          ans(isref)
          if(isref)
            map_tryget(${visited_nodes}  "${element}")
            ans(ref_id)
            if(ref_id)
              set(element ${ref_id})
            endif()
          endif()
          list(APPEND transformed_res ${element})
        endforeach()
        ref_set(${node} "${transformed_res}")
        list(APPEND potential_successors ${res})
      endif()

      set(successors)  
      foreach(potential_successor ${potential_successors})
        ref_isvalid(${potential_successor})
        ans(isref)
        if(isref)
         # ref_print(${visited_nodes})
          map_has(${visited_nodes} "${potential_successor}")
          ans(was_visited)
          if(NOT was_visited)
            list(APPEND successors ${potential_successor})
          
          endif()

          else()
        endif()
      endforeach()

      set(${result} ${successors} PARENT_SCOPE)
    endfunction()


    function(decycle_visit cancel value)
      message("visiting")
      map_isvalid(${value} )
      ans(ismap)
      ref_isvalid(${value})
      ans(isref)
      if(isref)
        map_tryget(global ref_count)
        ans(ref_count)
        
        math(EXPR ref_count "${ref_count} + 1")
        map_set(global ref_count ${ref_count})
        map_set(${visited_nodes} ${value} "\$${ref_count}")   
        if(ismap)
          map_set(${value} "\$id" "\$${ref_count}")
          
        endif()


        message("found ref")
      endif()

    endfunction()

    map_graphsearch(VISIT decycle_visit SUCCESSORS decycle_successors ${val})

    #ref_print(${visited_nodes})
    #ref_print(${val})
  endfunction()