# Library functions for the scripting library (scrib)
#
# File: scrib/lib/loops.tcl
#
# $Revision$ on $Date$
# 
# Copyright (c) 1993-2003 ICEM CFD Engineering
#
#--------------------------------------------------------------------


proc scrib_lib_loops_find_smart_loop_surfs {surflist meshsize boxheight {factor 1}} {

    #find surfaces that are small and could cause problems
    #first case is surfaces without surface area less than  meshsize ^ 2
    set tiny_surfs ""
    foreach surf $surflist {
	if {[ic_geo_srf_area $surf] > [expr $meshsize * $meshsize * $factor]} continue
	lappend tiny_surfs $surf 
    }
    if {$tiny_surfs == ""} return ""
    set tiny_surf_list "" 
    foreach surf $tiny_surfs {
	set tiny_surf_list_add $surf
	set crvs [ic_geo_boundary surface $surf] 
	set nsrfs($surf) ""
	foreach c $crvs {
	    foreach srf [ic_geo_incident curve $c] {
		if {$srf == $surf} continue
		if {[lsearch $tiny_surfs $srf] != -1} {lappend nsrfs($surf) $srf}
	    }
	    
	}
	#lappend tiny_surf_list_add $nsrfs($surf) 
	lappend tiny_surf_list_add	[llength $nsrfs($surf)] 
	lappend tiny_surf_list $tiny_surf_list_add
    }
    set tiny_surf_ordered_list [lsort -index 1 -decreasing $tiny_surf_list]

    #mess "tiny surf ordered  list is $tiny_surf_ordered_list\n" blue
    set used ""
    set grouped_surfs ""
    while [llength $tiny_surf_ordered_list]  {
	if {$tiny_surf_ordered_list == ""} break
	set surf [lindex [lindex $tiny_surf_ordered_list 0] 0]
	set tiny_surf_ordered_list [lreplace $tiny_surf_ordered_list 0 0]
	if {[lsearch $used $surf] != -1} continue
	lappend used $surf
	set group $surf
	set crvs [ic_geo_boundary surface $surf]
	while [llength $nsrfs($surf)] {
	    if {$nsrfs($surf) == ""} break
	    set s [lindex $nsrfs($surf) 0]
#mess "s is $s; surf is $surf\n"
	    set nsrfs($surf) [lreplace $nsrfs($surf) 0 0]
	    if {[lsearch $used $s] != -1} continue
	    set temp_group [concat $group $s]
	    set temp_crvs [scrib_lib_utils_list_remove_duplicated \
		[concat $crvs [ic_geo_boundary surface $s]]]
#mess "temp_group is $temp_group temp_curve is $temp_crvs\n"
	    set container_group [scrib_lib_feature_find_container "$temp_crvs" "$temp_group"] 
#mess "container_group is $container_group\n"
	    if {[lindex $container_group 2] > $boxheight} {
	        continue
	    }
 	    set group $temp_group
	    set crvs $temp_crvs
	    lappend used $s
	    foreach ss $nsrfs($s) {
		if {[lsearch $used $ss] == -1} {lappend nsrfs($surf) $ss}
	    }
	}
	lappend grouped_surfs $group
    } 
    return $grouped_surfs
}







