
;////////////////////////////////////////////////////////////////////////////
;//                                                                        //
;//                 COPYRIGHT ANSYS. ALL RIGHTS RESERVED.                  //
;//                                                                        //
;// This file contains proprietary software licensed from ANSYS Inc.       //
;// This header must remain in any source code despite modifications or    //
;// enhancements by any party.                                             //
;//                                                                        //
;////////////////////////////////////////////////////////////////////////////

;This file consist of the utility functions used for Incylinder setup  maintained by wb-ice team

;checks and captures the images at given frequency
(define wb_ice_only_smoothing? #f)
(define wb-ice-cal-act-transient-flow)

(define wb-ice-capture-images)

(define wb-ice-transient-flow-capture-mesh-images)

(define wb-ice-cal-act-port-flow)

(define wb-ice-write-iterations-per-time-step)
;calc activity for combustion
(define wb-ice-write-AHRR)

;based on how convergence is progressing increase or decrease the time step 
(define wb-ice-adapt-time-step)
(define wb-ice-set-min-max-itn-counter)
(define  wb-ice-write-monitor-file) ;only for transient flow




 ;this method if executed at every time step, returns #t or #f based on the input start-crank-angle and frequency
 
(define wb-ice-execute-command-based-on-crank-angle)



(define wb-ice-get-no-of-time-steps)

(define order-events-based-on-crank-angle)

(define insert-element-in-list)

(define wb-ice-mesh-replace-initial)

(define wb-ice-mesh-replace-final)

; for key grid mesh replacement 

(define wb-ice-mesh-replace)

(define wb-ice-plot-residual)

; if user starts from wb-ice we will define this with respect to case file ../Report all paths will use this scheme so user runs in stand alone we will dump the files in same directory.

(define WB-ICE-REPORT-DIR-PATH "")

(define wb-ice-report-dir)

(define wb-ice-calculate-dpm-parameters)

; following function returns all the chamber zones like fluid-ch, fluid-piston, fluid-layer-cylinder, fluid-ch-upper/lower etc
(define wb-ice-get-all-chamber-zones)

; following function is defined to reset-EGR one deg before invalve-open
(define wb-ice-inert-egr-reset)
;for making valve interface as matching
(define wb-ice-define-valve-open-event)
(define wb-ice-deactivate-cell-zones)
(define wb-ice-activate-cell-zones)
(define wb-ice-convert-units)
(define wb-ice-calc-ahrr-condition)
(define wb-ice-start-smoothing-before-valve-close)
(define wb-ice-stop-smoothing-at-valve-open)
(define wb-ice-start-smoothing-at-valve-open)
(define wb-ice-changeBC)
(define wb-ice-kg-zone-names-check-new-topology)
(define wb-ice-find-non-matching-zones)
(define wb-ice-get-zones-for-vlayer-layering)
(define wb-ice-get-zones-for-ib-layering)
(define wb-ice-get-valve-names-from-stem)
;defines rigid motion for invalve1-ib, -ob, -ch, -seat, -stem , fluid-ib, vlayer
(define wb-ice-kg-define-dyn-settings-new-topology)
(define wb-ice-get-valve-names-from-ch)
(define wb-ice-query-if-ib-layering)
(define wb-ice-query-if-vlayer-layering)
(define wb-ice-kg-define-smoothing-remeshing-parameters)
; defines settings when user replace new topology with ICE topology
(define wb-ice-kg-set-ICE-mesh-topology)
(define wb-ice-kg-define-ib-ob-interfaces)
(define wb-ice-kg-define-zone-motions)
(define wb-ice-kg-create-valve-interfaces)
(define wb-ice-string-split-by-delimiter)
(define wb-ice-kg-register-monitors-before-mesh-replace)
(define wb-ice-update-monitor-zones)
(define wb-ice-kg-update-volume-monitors)
(define wb-ice-get-new-fluid-zones-after-replace-mesh)
(define wb-ice-get-new-surface-zones-after-replace-mesh)
(define wb-ice-query-if-layer-cylinder-layering)
; deforming valve interfaces remeshing settings if present in dynamic settings
(define wb-ice-kg-define-valve-ch-interfaces-deforming)
; global remeshing setting, cyl-tri, symm-cyl-tri, int-piston, crevice
(define wb-ice-kg-define-dyn-settings-canted-valve-engine)
(define wb-ice-kg-remshing-settings-for-deforming-zones)
(define wb-ice-kg-query-if-it-is-ice-topology)
(define wb-ice-kg-query-if-layering-possible)
(define wb-ice-kg-define-zone-motions-new-topology)
;; Keygrid mesh topologies
;; topology1 : default ICE decomposition
;; topology2 : only vlayer & port present (IB is absent)
;; topology3 : vlayer and ib are absent. Only port is present
;; topology4 : single body (CFX topology)
(define wb-ice-kg-define-mesh-interfaces-for-mesh-topology-2)
(define wb-ice-kg-define-get-min-required-zones-for-mesh-topo-2)
(define wb-ice-get-port-zones-from-valve-name)
(define wb-ice-remesh-cell-zones)
(define wb-ice-get-deforming-cell-thread-ids)
(define wb-ice-set-display-after-mesh-replace)
(define wb-ice-kg-get-smoothing-string)
(define wb-ice-plot-last-monitor-values)
(define wb-ice-overlay-with-velocity-vectors)
(define wb-ice-kg-manage-remesh-calc-activity)
(define wb-ice-set-element-in-list)
;; when case is with single mesh topology and in deactivated zones 'fluid-invalve1-port is present. 
;; Now if user replace mesh with ice-default topology then fluent will deactivate only 'fluid-invalve1-port zone
;; while fluid-invalve1-ib and -vlayer will remain active which is not correct. So this is taken care in below method
(define wb-ice-activate-all-deativated-zones)
(define wb-ice-kg-deactivate-zones-afer-mesh-replace)
(define wb-ice-write-case-data-solution-point)

(set! wb-ice-report-dir
  (lambda ()
    (define icedir "./")
    (define report-dir)
    (if (wb-get-dir)
      (set! icedir (directory (wb-get-dir)))
      (if (client-default-basename "r")
        (set! icedir (directory (directory (client-default-basename "r"))))
      )
    )
    (set! report-dir (string-append icedir "/Report"))
    (if (not (file-exists? report-dir))
      (begin
        (define cortex_dir (cortex-pwd))
        (chdir icedir)
        (system "mkdir Report")
        (chdir cortex_dir)
      )
    )
  )
)

(set! wb-ice-execute-command-based-on-crank-angle
  (lambda(start-CA freq)
    (define real-remainder
      (lambda (a b)
	(if (= b 0)
	  (begin
	    (+ b a)
	    )
	  (begin
	    (let loop ((i 1))
	      (if (or  (< (* b i) a) (= (* b i) a))
		(loop (+ 1 i))
		(+  0 (- a (* b (- i 1))))
		)
	      )
	    )
	  )
	)
      )    
    (let
      (
       (return #f)
       (frequency freq)
       )

       (if  (and 
		(<  (real-remainder (- (- (time->absolute-crank-angle (rpgetvar 'flow-time)) start-CA) (* 0.9 (rpgetvar 'dynamesh/in-cyn/delta-angle))) frequency)  frequency)
		(>  (+ (real-remainder (- (- (time->absolute-crank-angle (rpgetvar 'flow-time)) start-CA) (* 0.9 (rpgetvar 'dynamesh/in-cyn/delta-angle))) frequency) (rpgetvar 'dynamesh/in-cyn/delta-angle))  frequency)
	      )
	 (begin
	   (set! return #t)
	   return
	   )
	 (begin
	   return
	   )
	 )

       )

      )
    )





(set! wb-ice-write-monitor-file
  (lambda(file-name title x-axis y-axis x-value y-value)
    (let
      (
       (file-port #f)
       (space " ")
       )
    (if (not (file-exists? file-name)) 
      (begin
	(set! file-port (open-output-file file-name))
	(if file-port
	  (begin
	    (write title  file-port)
	    (newline file-port)
	    (write x-axis file-port) (write (string->symbol space) file-port) (write  y-axis file-port)
	    (newline file-port)
	    (close-output-port file-port)
	    )
	  )
	)
      )

    (if (file-exists? file-name)
      (begin
	(set! file-port (open-file file-name "a"))
	(write x-value file-port)
	(write (string->symbol space) file-port)
	(write y-value file-port)
	(newline file-port)
	(close-output-port file-port)
	)
      )          
    )
    )
  )

(set! wb-ice-adapt-time-step
  (lambda ()
    (let
      (
       (ice-start-ca 0)
       (ice-current-ca 0)
       (ice-max-ca-step-size 0.5)
       (ice-min-ca-step-size 0.0625)
       (ice-stablize-CA 0.5)
       )

       (wb-ice-set-min-max-itn-counter)

       ;;To Do: convert the max or min iteration counter to CA based on the current time step
     

      (if (> (rpgetvar 'ice/max-iteration-counter) ice-stablize-CA)
	(begin

	  (pp "decrease time step by factor of 2 if target is not less than min step size else min step size")
	  )
	)

       (if (> (rpgetvar 'ice/min-iteration-counter) ice-stablize-CA)
	(begin

	  (pp "increase time step by factor of 2 if it is more than the max step size set it to max")
	  )
	)

	) 
    ))

(set! wb-ice-set-min-max-itn-counter
  (lambda()
    (let
      (

       (ice-max-itn-counter 0)
       (ice-min-itn-counter 0)
       )
       (if (not (rp-var-object 'ice/max-iteration-counter))
        (rp-var-define 'ice/max-iteration-counter  0 'int 1) )
        
       (if (not (rp-var-object 'ice/min-iteration-counter))
        (rp-var-define 'ice/min-iteration-counter  0 'int 1) )

       (set! ice-max-itn-counter (rpgetvar 'ice/max-iteration-counter))
       (set! ice-min-itn-counter (rpgetvar 'ice/min-iteration-counter))


       ;; To Do: also track if time step has been changed from any other source then reset the max-min iteration counter
       ;this method will update the iteration per time step
       (wb-ice-write-iterations-per-time-step)
  
       (if (= (rpgetvar 'ice/iterations-per-time-step-written) (rpgetvar 'max-iterations-per-step))
	   (set! ice-max-itn-counter (+ ice-max-itn-counter 1))
	   (set! ice-max-itn-counter 0)
	   )
       (if (< (rpgetvar 'ice/iterations-per-time-step-written) (/(rpgetvar 'max-iterations-per-step) 2))
	   (set! ice-min-itn-counter (+ ice-min-itn-counter 1))
	   (set! ice-min-itn-counter 0)
	   )
       (rpsetvar 'ice/max-iteration-counter ice-max-itn-counter)
       (rpsetvar 'ice/min-iteration-counter ice-min-itn-counter)
       ice-max-itn-counter

    )
  ))
(set! wb-ice-write-iterations-per-time-step
  (lambda()
    (let
      (
       (previous_no_of_iterations 0)
       (current_no_of_iterations 0)
       (iterations_per_time_step 1)
       (space " ")
       )
      (if (not (rp-var-object 'ice/history-of-no-iterations))
        (rp-var-define 'ice/history-of-no-iterations  0 'int 1) )
      
      (if (not (rp-var-object 'ice/iterations-per-time-step-written))
        (rp-var-define 'ice/iterations-per-time-step-written  0 'int 1))
      (if (not (rp-var-object 'ice/flow-time-written))
        (rp-var-define 'ice/flow-time-written  0 'number 1))
        
      (set! previous_no_of_iterations (rpgetvar 'ice/history-of-no-iterations))
      (set! current_no_of_iterations (client-inquire-iteration))
      (set! iterations_per_time_step (- current_no_of_iterations previous_no_of_iterations))
      (if (not (= iterations_per_time_step 0))
        (begin 
          (rpsetvar 'ice/history-of-no-iterations current_no_of_iterations)
          (if (= (client-inquire-flow-time) (rpgetvar 'ice/flow-time-written))
            (set! iterations_per_time_step (+ (rpgetvar 'ice/iterations-per-time-step-written) iterations_per_time_step)) )
          (rpsetvar 'ice/flow-time-written (client-inquire-flow-time))
          (wb-ice-write-monitor-file  "ice-iter-per-timestep.out" "Number of Iterations per Time Step" "Flow Time" "Iterations" (client-inquire-flow-time) iterations_per_time_step)
          (rpsetvar 'ice/iterations-per-time-step-written iterations_per_time_step)          
        )
      )
      iterations_per_time_step
    )
  )
)


(set! wb-ice-write-AHRR
  (lambda(zones)
    (if (wb-ice-calc-ahrr-condition)
      (begin
    (let
      (
       (P1 0)
       (P2 0)
       (V1 0)
       (V2 0)
       (A1 0)
       (A2 0)
       (dP 1)
       (dV 1)
       (dA 1)
       (Y 1.35)
       (AHRR 0)
       (space " ")
       (ice-AHRR-file-port #f)
       (all-zones (map thread-name (sort-threads-by-name (get-threads-of-type 'fluid))))
       (new-zones '())
	   (N 1)
       )
      (do ((i 0 (+ i 1))) ((= i (length zones)))
	(if (member (list-ref zones i)  all-zones)
	  (set! new-zones (append new-zones (list (list-ref zones i)))	  )
	  )
	)
      (if (and (not (member 'fluid-layer-cylinder new-zones )) (thread-name->id  "fluid-ch"))
	(if (thread-name->id  "fluid-layer-cylinder") 
	  (set! new-zones (append new-zones (list 'fluid-layer-cylinder)	  ))
	  )
	)
      (if (and (not (member 'fluid-piston new-zones )) (thread-name->id  "fluid-ch"))
	(if (thread-name->id  "fluid-piston") 
	  (set! new-zones (append new-zones (list 'fluid-piston)	  ))
	  )
	)

      (if (not (rp-var-object 'ice/ahrr-P1))
	(rp-var-define 'ice/ahrr-P1  0 'int 1)
	)
      (if (not (rp-var-object 'ice/ahrr-V1))
	(rp-var-define 'ice/ahrr-V1  0 'int 1)
	)
      (if (not (rp-var-object 'ice/ahrr-A1))
	(rp-var-define 'ice/ahrr-A1  0 'int 1)
	)
	(if (not (rp-var-object 'ice/ahrr-Y))
	(rp-var-define 'ice/ahrr-Y  0 'int 1)
	)

      (rpsetvar 'monitor/compute-node-values? #f)
      (client-fill-node-values 'absolute-pressure)
      (rpsetvar 'monitor/compute-node-values? #t)

      (set! P1 (rpgetvar 'ice/ahrr-P1))
      (set! P2 (%volume-integrals 'mass-average (map thread-name->id new-zones)) )

      (set! V1 (rpgetvar 'ice/ahrr-V1))
      (set! V2 (%volume-integrals 'volume (map thread-name->id new-zones)) )

      (set! A1 (rpgetvar 'ice/ahrr-A1))
      (set! A2 (time->absolute-crank-angle (rpgetvar 'flow-time)))
	  
	  (rpsetvar 'monitor/compute-node-values? #f)
      (client-fill-node-values 'gamma)
      (rpsetvar 'monitor/compute-node-values? #t)
	  (set! Y (rpgetvar 'ice/ahrr-Y))
      (set! Y (%volume-integrals 'mass-average (map thread-name->id new-zones)) )

      ;store the current values for next time step
      (rpsetvar 'ice/ahrr-P1 P2)
      (rpsetvar 'ice/ahrr-V1 V2)
      (rpsetvar 'ice/ahrr-A1 A2)
	  (rpsetvar 'ice/ahrr-Y Y)
	  
	  (if (not (null? (rpgetvar 'sliding-interfaces)))
      (begin 
         (if (assoc 'angle (car (rpgetvar 'sliding-interfaces)))
                 (set! N (/ 360 (/ (* 180 (cdr (assoc 'angle (car (rpgetvar 'sliding-interfaces))))) 3.14159265358979323846))))
          )
      )
	  (if (or (thread-name->id "symm-cyl-quad") (thread-name->id "symm-cyl-tri"))
            (set! N 2))
      (set! AHRR (* N (+  (* (/ Y (- Y 1)) P2 (/ (- V2 V1) (- A2 A1)) )  (* (/ 1 (- Y 1)) V2 (/ (- P2 P1) (- A2 A1)) ) ) ))
      
          (wb-ice-write-monitor-file  "ice-AHRR.out" (format #f "Apparent Heat Release Rate on ~s" new-zones) "Flow Time" "AHRR" (client-inquire-flow-time) AHRR)  
      )
        )
      )
    )
  )

(set! wb-ice-transient-flow-capture-mesh-images
  (lambda(post-plane)
   ; (define post-plane)
   ; (set! post-plane  (read-var solver-set-file 'post_planes))
    (do ((i 0 (+ i 1))) ((= i (length post-plane)))

      (let* 
	(
	; (name (list-ref (list-ref post-plane i) 0))
	 (name (list-ref post-plane i))
   (images-name "")
	 ) 
	(ti-menu-load-string "/dis set pic driver jpeg")
	(ti-menu-load-string "/dis set cont filled-cont yes")
	(ti-menu-load-string (format #f "/dis set ms (~s)" (string->symbol name)))
        (ti-menu-load-string "/dis s-m , ,") 
	(ti-menu-load-string (format #f "/dis view r-v ~s-view" (string->symbol name)))
  (ti-menu-load-string "/display/set/mesh-display-configuration classic") 
    (set! images-name (string-append name "-CA_" (ice-padd-zeros (format #f "~0.3F"(time->absolute-crank-angle (rpgetvar 'flow-time))) 8)))
	(ti-menu-load-string (format #f "dis hc ~aice-anim-mesh-on-~s.jpg" wb-ice-report-dir-path (string->symbol images-name)))
	)
      ) 
    )
  )

(set! wb-ice-capture-images
  (lambda (images-name list-surfaces list-quantities view . arg)
    (let
      (
       (dpm #f)
       (ice_solution_type "")
       (overlay #f)
       )
      (if (rp-var-object 'ice/solution-type)
        (set! ice_solution_type (rpgetvar 'ice/solution-type))
        (set! ice_solution_type "cold-flow")
      )
      (define surface-string "")
      (do ((j 0 (+ j 1))) ((= j (length list-surfaces)))
	(set! surface-string (string-append surface-string (list-ref list-surfaces j)" ") )    
	)
      (if arg
	(begin
	  (if (assoc 'dpm arg)
	    (if (cadr (assoc 'dpm arg))
	      (set! dpm #t)
	      )
	    )
    (if (assoc 'overlay arg)
	    (if (cadr (assoc 'overlay arg))
	      (set! overlay #t)
	      )
	    )
	  )
	)

      (do ((j 0 (+ j 1))) ((= j (length list-quantities))) 
	(if dpm
	  (begin
	    (ti-menu-load-string "/dis s-w 2")
	    (ti-menu-load-string (format #f "/dis set m-s ~s " (map surface-name->id (map string->symbol list-surfaces))))
	    (ti-menu-load-string "/dis set r-m yes")
	    (ti-menu-load-string "/dis set r-o surface-edge-visibility yes no yes no")
	    (ti-menu-load-string (format #f "/dis s-m ~s " (map surface-name->id (map string->symbol list-surfaces))))	    
	    (ti-menu-load-string (format #f "/dis view rv ~s" (string->symbol view) ))
	    (if (assoc 'injection arg)
	      (ti-menu-load-string (format #f "/dis pt pt ~s ~s , ," (string->symbol (list-ref list-quantities j)) (cadr (assoc 'injection arg)) ))
	      )
	    (ti-menu-load-string (format #f "/dis view rv ~s" (string->symbol view) ))
	    (ti-menu-load-string "/dis set r-m no")
	    (ti-menu-load-string "/dis set r-o surface-edge-visibility yes no no no")
	    (ti-menu-load-string "/dis set r-o surface-edge-visibility yes yes")
      	(ti-menu-load-string "(cxg-stitch-shells)") ;; this is required to make partition edges off
	    )
	  (begin
	    (ti-menu-load-string "/dis s-w 2")
	    (ti-menu-load-string (format #f "/dis set cont surf ( ~s )" (string->symbol surface-string)))
	    (ti-menu-load-string "/dis set pic driver jpeg")
	    (ti-menu-load-string "/dis set cont filled-cont yes")
      	(ti-menu-load-string "/dis set lights lights-on? no")
      	(ti-menu-load-string "/dis set lights headlight-on? no")
	    (ti-menu-load-string (format #f "/dis cont ~s , ," (string->symbol (list-ref list-quantities j))))
	    (ti-menu-load-string (format #f "/dis view rv ~s" (string->symbol view) ))
      (if overlay
        (wb-ice-overlay-with-velocity-vectors) )
	    )
	  )

	(if (or (string-ci=? ice_solution_type "cold-flow") (and (string-ci=? ice_solution_type "combustion") (not dpm)) )
	  (begin
        (set! images-name (string-append images-name "-CA_" (ice-padd-zeros (format #f "~0.3F"(time->absolute-crank-angle (rpgetvar 'flow-time))) 8)))
	     (ti-menu-load-string (format #f "/dis hc ~aice-~s-on-~s.jpg" wb-ice-report-dir-path (string->symbol (list-ref list-quantities j)) (string->symbol images-name) )) 	       
	    )
	  )

	(if (and (string-ci=? ice_solution_type "combustion") dpm)
	  (begin 
        (set! images-name (string-append images-name "-CA_" (ice-padd-zeros (format #f "~0.3F"(time->absolute-crank-angle (rpgetvar 'flow-time))) 8)))
	    (ti-menu-load-string (format #f "/dis hc ~aice-pt-~s-on-~s.jpg" wb-ice-report-dir-path (string->symbol (list-ref list-quantities j)) (string->symbol images-name) )) 	       
	    )
	  )     

	(if (string-ci=? ice_solution_type "port-flow")
	  (begin
	    (ti-menu-load-string (format #f "/dis hc ~aice-~s-on-~s-%i.jpg" wb-ice-report-dir-path (string->symbol (list-ref list-quantities j)) (string->symbol images-name)))
	    )
	  )
	)   
      )

    )
  )


;----------gives you the remainder even if the inputs are real values
(define (ice-remainder a b)
    (if (= b 0)
      (begin
	(+ b a)
	)
      (begin
	(let loop ((i 1))
	  (if (or  (< (* b i) a) (= (* b i) a))
	    (loop (+ 1 i))
	    (+  0 (- a (* b (- i 1))))
	    )
	  )
	)
      )
    )

;beign refered from calculation activities in ice files

(set! wb-ice-cal-act-transient-flow
  (lambda(images-name startCA endCA frequency surface-list quantity-list view . arg)
    (let
      (
       (crank-period (rpgetvar 'dynamesh/in-cyn/crank-period))
       (absCA (time->absolute-crank-angle (rpgetvar 'flow-time)))
       (currCA (time->absolute-crank-angle (rpgetvar 'flow-time)))
       (tolerance (* 0.5 (rpgetvar 'dynamesh/in-cyn/delta-angle) ) )
       (sol-start-angle (rpgetvar 'dynamesh/in-cyn/crank-start-angle))
       (sol-time-step (rpgetvar 'dynamesh/in-cyn/delta-angle))
       (plot_start_angle startCA)
       (plot_end_angle endCA)
       (dpm #f)
       (injection #f)
       (overlay #f)
       
       )
      (if arg
	(begin
	 (if (assoc 'dpm arg)
	   (set! dpm (assoc 'dpm arg))
	   )	
	 (if (assoc 'injection arg)
	   (set! injection (assoc 'injection arg))
	   )
   (if (assoc 'overlay arg)
	   (set! overlay (assoc 'overlay arg))
	   )	
	  )
	)
      (if (>= (- plot_end_angle plot_start_angle) crank-period)
	(set! plot_end_angle (+ plot_start_angle (- crank-period tolerance))))
      (set! currCA (ice-remainder currCA crank-period))
      (set! plot_end_angle (ice-remainder plot_end_angle crank-period))
      (set! plot_start_angle (ice-remainder plot_start_angle crank-period))
      (set! sol-start-angle (ice-remainder sol-start-angle crank-period))

      (if (or (and (<= plot_end_angle plot_start_angle) (or (<= currCA plot_end_angle) (>= currCA plot_start_angle)))
	      (and (> plot_end_angle plot_start_angle)  (and (<= currCA plot_end_angle) (>= currCA plot_start_angle))))
	(begin
	  (if (< (- absCA sol-start-angle) (+ sol-time-step tolerance) )
	    ;this condition is only for pre-iteration when the solution starts, and sol-start-angle is equal to image-start-angle
	     (wb-ice-capture-images images-name surface-list quantity-list view dpm injection overlay)
	    )
	  (if (< (ice-remainder (+ (ice-remainder currCA plot_start_angle) tolerance) frequency) sol-time-step ) 
	    (wb-ice-capture-images images-name surface-list quantity-list view dpm injection overlay)
	    )
	  )
	)
      )
    )
  )

(set! wb-ice-cal-act-port-flow
  (lambda(images-name start-iter end-iter frequency surface-list quantity-list view . arg)
    (let
      (
       (curr-iter (%iterate 0))
       (overlay #f)
       )
      (if arg
        (begin
          (if (assoc 'overlay arg)
          (set! overlay (assoc 'overlay arg)))
        )
       )
      (if (and start-iter end-iter frequency) 
	(if (and (or (> curr-iter start-iter) (= curr-iter start-iter)) (or (< curr-iter end-iter) (= curr-iter end-iter)))
	  (begin
	    (if (= (remainder (remainder curr-iter start-iter) frequency) 0) 
	      (wb-ice-capture-images images-name surface-list quantity-list view overlay)
	      )
	    )
	  )
	)
      (if (and (not start-iter) (not end-iter) frequency) 
	(wb-ice-capture-images images-name surface-list quantity-list view overlay)
	)
      )

    )
  )

  
(set! wb-ice-get-no-of-time-steps
  (lambda(ca_to_run)
    (let 
      (
        (event '())
        (current_event_list (rpgetvar 'dynamesh/in-cyn/event-list) )
        (final_dt_event_list '())
        (curr_delta_angle (rpgetvar 'dynamesh/in-cyn/delta-angle))
        (curr_ca (rpgetvar 'dynamesh/in-cyn/crank-angle))
        (cnt 1)
        (angle_remained 0)
        (dt_event_list '())
        (next_cycle_dt_event_list '())
        (all_dt_event_list '())
        (required_ca 0)
        (no_of_time_steps 0)
      )
      (order-events-based-on-crank-angle)
      (set! required_ca (+ curr_ca ca_to_run))
      (if (> required_ca curr_ca)
        (begin
          ;; get events from start-ca to (start-ca+720)  
          (do ((i 0 (+ i 1))) ((= i (length current_event_list)))
           (set! event (list-ref current_event_list i))
            (if (and (= (cadr (assoc 'action event))  5) (cdr (assoc 'active event)))
              (begin 
                 (if (> (cdr (assoc 'start event))  curr_ca)
                   (set! dt_event_list (list-add dt_event_list event))
                   (set! next_cycle_dt_event_list (list-add next_cycle_dt_event_list event))
                  )
              )
            )
          )
          ; add +720 to each event present in  next_cycle_dt_event_list
          (do ((i 0 (+ i 1))) ((= i (length next_cycle_dt_event_list)))
            (let* 
              (
                (event (list-ref next_cycle_dt_event_list i))
                (l '())
                (x (+ (cdr (assoc 'start event)) 720))
              )
              (set! l (list-add l (assoc 'active event)) )
              (set! l (list-add l (assoc 'name event))) 
              (set! l (list-add l (cons 'start  x) ))
              (set! l (list-add l (assoc 'action event)) )
              (set! all_dt_event_list (list-add all_dt_event_list l))
            )     
          )
          ;;  all_dt_event_list has events from start-ca to start-ca+720
          (set! all_dt_event_list (append dt_event_list all_dt_event_list))
          ;(format "all_dt_event_list is = ~s" all_dt_event_list)
          (set! cnt (quotient ca_to_run 720))
          (if (= cnt 0)
            (begin 
              (do ((i 0 (+ i 1))) ((= i (length all_dt_event_list)))
                (set! event (list-ref all_dt_event_list i))
                (if (< (cdr (assoc 'start event)) required_ca)
                  (set! final_dt_event_list (list-add final_dt_event_list event)))     
              )
            )
          )
          (if (or (> cnt 1) (= cnt 1))
            (begin
              (do ((i 0 (+ i 1))) ((= i cnt))
                (set! final_dt_event_list (append final_dt_event_list all_dt_event_list)))
              (set! angle_remained (- ca_to_run (* cnt 720)))
              (do ((i 0 (+ i 1))) ((= i (length all_dt_event_list)))
                (set! event (list-ref all_dt_event_list i))
                (if  (< (cdr (assoc 'start event)) (+ angle_remained curr_ca))
                  (set! final_dt_event_list (list-add final_dt_event_list event)))
              )
            )
          )
          ;(format  "final_dt_event_list is = ~s" final_dt_event_list)
          (if (null? final_dt_event_list)
            (set! no_of_time_steps (round (/ (- required_ca curr_ca) curr_delta_angle) )))
          ;;; suppose events of time step change are (100 0.125) (200 0.25) (300 .125) (400 0.25)...
          ;;; do-loop: here the no of intermediate time steps will be (200 -100) * 0.125. So this is done in below loop
          (if (> (length final_dt_event_list) 1)
            (begin
              (set! no_of_time_steps (round (abs (/ (- (cdr (assoc 'start (list-ref final_dt_event_list 0))) curr_ca) curr_delta_angle) ) ))
              (do ((i 0 (+ i 1))) ((= i (- (length final_dt_event_list) 1)))
                (set! event (list-ref final_dt_event_list i))
                (if (< (cdr (assoc 'start (list-ref final_dt_event_list (+ i 1)))) (cdr (assoc 'start event)) )
                  (set! no_of_time_steps (round (+ no_of_time_steps (abs (/ (- (+ 720 (cdr (assoc 'start (list-ref final_dt_event_list (+ i 1))))) (cdr (assoc 'start event))) (caddr (assoc 'action event))) ) )))
                  (set! no_of_time_steps (round (+ no_of_time_steps (abs (/ (- (cdr (assoc 'start (list-ref final_dt_event_list (+ i 1)))) (cdr (assoc 'start event))) (caddr (assoc 'action event))) ) )))
                )
              )
              ;; calculate time steps from last ca in event file to required_ca
              (set! angle_remained (- required_ca (* cnt 720)))
              (if (< (cdr (assoc 'start (list-ref final_dt_event_list (- (length final_dt_event_list) 1)))) angle_remained)
                (set! no_of_time_steps (round (+ no_of_time_steps (abs (/ (- angle_remained (cdr (assoc 'start (list-ref final_dt_event_list (- (length final_dt_event_list) 1))))) (caddr (assoc 'action (list-ref final_dt_event_list (- (length final_dt_event_list) 1)))))))))
                (set! no_of_time_steps (round (+ no_of_time_steps (abs (/ (- (+ angle_remained 720) (cdr (assoc 'start (list-ref final_dt_event_list (- (length final_dt_event_list) 1))))) (caddr (assoc 'action (list-ref final_dt_event_list (- (length final_dt_event_list) 1)))))))))
              )
            )
          )
        )
      )no_of_time_steps
    )
  )
)

(set! order-events-based-on-crank-angle
  (lambda()
    (let
      (
        (event-list (rpgetvar 'dynamesh/in-cyn/event-list))
        (CA-list '())
        (temp-event-list '())
        (event-list-ordered '())
        (start-CA 0)
        (start-CA-ordered 0)
        (insert-flag 0)
      )
      (set! event-list-ordered (insert-element-in-list (list-ref event-list 0) 0 event-list-ordered))
      (set! temp-event-list event-list-ordered)
      (do ((i 1 (+ i 1))) ((= i  (length  event-list)))
        (set! insert-flag 0)
        (set! start-CA (cdr (assoc 'start (list-ref event-list i))) )
        (do ((j 0 (+ j 1))) ((= j  (length  event-list-ordered)))
          (set! start-CA-ordered (cdr (assoc 'start (list-ref event-list-ordered j))) )
          (if (< start-CA start-CA-ordered)
            (begin
              (set! temp-event-list (insert-element-in-list (list-ref event-list i) j  temp-event-list))
              (set! insert-flag 1)
              (set! j (- (length  event-list-ordered) 1))		
            )
          )	   
        )
        (if (= insert-flag 0)
          (set! temp-event-list (insert-element-in-list (list-ref event-list i) (length  event-list-ordered) temp-event-list)))
          
        (set! event-list-ordered temp-event-list)
      )    
      (rpsetvar 'dynamesh/in-cyn/event-list event-list-ordered)
    )
  )
)

(set! insert-element-in-list
  ;this method insert an element in the specific location, in the list
  (lambda(element location-index current-list) 
    (let
      (
       (temp-list '())
       )
      (do ((i 0 (+ i 1))) ((= i  (length  current-list)))
	(if (= i location-index)
	  (begin
	    (set! temp-list (append temp-list (list element) ))
	    (set! temp-list (append temp-list (list (list-ref current-list i)) ))   
	    )
	  (begin
	    (set! temp-list (append temp-list (list (list-ref current-list i)) )) 
	    )
	  )
	)
      (if (= location-index (length  current-list))
	(set! temp-list (append temp-list (list element) ))
	)
      (append temp-list '())
      )
    )
  )
 


 
(define ice-padd-zeros
  (lambda (str trg-length)
    (define result str)
    (do ((i (string-length str) (+ i 1))) ((= i trg-length))
        (set! result (string-append "0" result)))
    result))


;being referred from events

(set! wb-ice-plot-residual
  (lambda()
    (format  "\n\n\t\t ___________plot residual _____________\t\n\n")
    (if (rp-var-object 'ice/solution-type)
      (define ice_solution_type (rpgetvar 'ice/solution-type))
      (define ice_solution_type "cold-flow")
    )

    (if (string-ci=? ice_solution_type "cold-flow")
      (begin
        (let
          (
            (last-iter 0)
            (curr-iter (client-inquire-iteration))
            (n-display 1000)
            (CA (time->absolute-crank-angle (rpgetvar 'flow-time)))
          )
          (if (> curr-iter 0)
            (begin
              (if (not (rp-var-object 'ice/residual-iteration-history))
                (rp-var-define 'ice/residual-iteration-history 0 'integer #f))
              (set! last-iter (rpgetvar 'ice/residual-iteration-history))
              (set! n-display (- curr-iter last-iter))
              (if (< n-display 0)
                 (set! n-display curr-iter)
		)
              (if (> n-display 0)
                (begin
                  (rpsetvar 'ice/residual-iteration-history curr-iter)
                  (ti-menu-load-string (format #f "/sol mon res n-display ~s" (string->symbol (number->string n-display))))
                  (ti-menu-load-string "/plot residual")
		(ti-menu-load-string (format #f "/dis hc ~aice-residual-~s.jpg" wb-ice-report-dir-path CA))
                )
              )
            )
          )
        )

      )
    )
  )
)

(set! wb-ice-mesh-replace-initial 
  (lambda ()
    (if (not (rp-var-object 'ice/fluid-list))
      (rp-var-define 'ice/fluid-list  '() 'list 1)
      )
    (if (not (rp-var-object 'ice/interior-list))
      (rp-var-define 'ice/interior-list  '() 'list 1)
      )
    (if (not (rp-var-object 'ice/wall-list))
      (rp-var-define 'ice/wall-list  '() 'list 1)
      )
    (if (not (rp-var-object 'ice/sliding-interfaces))
      (rp-var-define 'ice/sliding-interfaces  '() 'list 1)
      )
    (if (not (rp-var-object 'ice/monitor-volume))
      (rp-var-define 'ice/monitor-volume  '() 'list 1))
    (if (not (rp-var-object 'ice/monitor-surfaces))
      (rp-var-define 'ice/monitor-surfaces  '() 'list 1))

    (rpsetvar 'ice/fluid-list (map thread-name (sort-threads-by-name (get-threads-of-type 'fluid))))
    (rpsetvar 'ice/interior-list (map thread-name (sort-threads-by-name (get-threads-of-type 'interior))))
    (rpsetvar 'ice/wall-list (map thread-name (sort-threads-by-name (get-threads-of-type 'wall))))
    (rpsetvar 'ice/sliding-interfaces (rpgetvar 'sliding-interfaces)) 
    (rpsetvar 'ice/monitor-volume '())
    (rpsetvar 'ice/monitor-surfaces '())    
    )
  )

(set! wb-ice-mesh-replace
  (lambda(file-name interpolate-data . args)
    (if (file-exists? file-name)
      (begin
        (if (and (thread-name->id  "zone1") (thread-name->id  "zone2"))
          (begin
            (format "\n___Changing zone name zone2 to int-piston, zone1 to interior-fluid-layer-cylinder-fluid-piston____\n")
            (ti-menu-load-string (string-append "/def/b-c/zone-name zone2  int-piston"))
            (ti-menu-load-string (string-append "/def/b-c/zone-name zone1  interior-fluid-layer-cylinder-fluid-piston"))
            (format "\n")
            ;(ti-menu-load-string (format #f "/mesh/replace ~s ~s" file-name  (string->symbol interpolate-data)))
            (replace-mesh-callback file-name '(#t))
            (format "\n")
            (format "\n___Changing zone name int-piston to zone2, interior-fluid-layer-cylinder-fluid-piston to zone1____\n")
            (ti-menu-load-string (string-append "/def/b-c/zone-name int-piston zone2"))
            (ti-menu-load-string (string-append "/def/b-c/zone-name interior-fluid-layer-cylinder-fluid-piston zone1"))
          )
          (begin
            (wb-ice-activate-all-deativated-zones)
            (wb-ice-mesh-replace-initial)
            (define kg_zone_list '())
            (if (string-ci=? interpolate-data "program-controlled")
              (begin
                (if (pair? args)
                  (if (not (null? args))
                    (set! kg_zone_list (car args))))
                ;(format "keygrid zone list : ~s " kg_zone_list)
                (format " \n No. of zones in keygrid mesh : ~a \t no of zones in present mesh : ~a \n" (length kg_zone_list) (length (rpgetvar 'ice/fluid-list)))
                (if (= (length kg_zone_list) (length (rpgetvar 'ice/fluid-list)))
                  (set! interpolate-data "no")
                  (set! interpolate-data "yes")
                )
                (if (string-ci=? interpolate-data "no")
                  (begin
                    (define not_found #f)
                    (for-each
                      (lambda(x)
                        (if (not (member x (rpgetvar 'ice/fluid-list)))
                          (set! not_found #t))
                      ) kg_zone_list
                    )
                    (if not_found
                      (set! interpolate-data "yes"))
                  )
                )
              )
            )
            (wb-ice-kg-register-monitors-before-mesh-replace)
            ;(ti-menu-load-string (format #f "/mesh/replace ~s ~s" file-name  (string->symbol interpolate-data)))
            (if (string-ci=? interpolate-data "yes")
              (begin
                (format "\n\n interpolating across zones true for interpolate-data values as ~a \n\n" interpolate-data)
                (replace-mesh-callback file-name '(#t))
              )
              (begin
                (format "\n\n interpolating across zones false for interpolate-data values as ~a \n\n" interpolate-data)
                (replace-mesh-callback file-name)
                
              )
            )
            (if (and (null? (rpgetvar 'sliding-interfaces)) (rp-var-object 'ice/sliding-interfaces) (> (length (get-threads-of-type 'fluid)) 1))
              (wb-ice-define-sliding-interfaces)
            )
            (wb-ice-kg-zone-names-check-new-topology)
            (if (not (thread-name->id  "fluid-ch-upper"))
              (wb-ice-mesh-replace-final)
            )
            (wb-ice-kg-update-volume-monitors)
          )

        )
        (wb-ice-kg-manage-remesh-calc-activity)
        ;;calling dynamic mesh set-up code here
        (wb-ice-kg-define-smoothing-remeshing-parameters) ; set smoothing type, controls, remeshing controls, layering?
        (if (wb-ice-kg-query-if-it-is-ice-topology)
          (begin
            ; defines settings when user replace new topology with ICE topology
            (wb-ice-kg-set-ICE-mesh-topology)
          )
          (begin
            ;defines rigid motion for invalve1-ib, -ob, -ch, -seat, -stem , fluid-ib, vlayer
            (wb-ice-kg-define-dyn-settings-new-topology)
          )
        )
        
        ; global remeshing setting, cyl-tri, symm-cyl-tri, int-piston, crevice
        (if (not (thread-name->id  "fluid-ch-upper"))
          (wb-ice-kg-define-dyn-settings-canted-valve-engine)) 
        
        ; defines mesh parameters for valve deforming interface
        (wb-ice-kg-define-valve-ch-interfaces-deforming)
        (wb-ice-kg-deactivate-zones-afer-mesh-replace)
        (wb-ice-set-display-after-mesh-replace)
        
      )
      (format "error file\n")
    )
  )
)

(set! wb-ice-mesh-replace-final
  (lambda ()
    (let 
      ( 
        (new-fluid-names '())
        (new-interior-names '() )
        (new-ineriros '())
        (fluid-ch-id  0)
        (fluid-piston-layer1-id 0)
        (fluid-piston-layer2-id 0)
        (zone1-name "")
        (zone2-name "")
        (final-fluids '())
        (new-interiors '())
        (final-walls '())
        (cylinder-axis '(0 0 1))
        (lpiston-full-prof #f)
        (ave_scale 0.0005)
        (new-chamber-zone-ids '())
        (new-walls '())
        (new-chamber-wall-ids '())
        (cyl-quad "")
        (cyl-piston "")
        (cyl-tri "")
        (profile "**piston-limit**")
      )
      (if (assoc 'geom-axis (assoc (thread-name->id "cyl-tri") (rpgetvar 'dynamesh/dynamic-zones)))
        (set! cylinder-axis (cadr (assoc 'geom-axis (assoc (thread-name->id "cyl-tri") (rpgetvar 'dynamesh/dynamic-zones)))))
        (format  "\n\n\t\t_____________ Warning: cyl-tri axis not found in dynamic settings so setting it to default (0 0 1). Please correct the axis if required___________\t\n\n"))
      (if (assoc 'udf (assoc (thread-name->id "piston") (rpgetvar 'dynamesh/dynamic-zones)))
        (set! lpiston-full-prof (cadr (assoc 'udf (assoc (thread-name->id "piston") (rpgetvar 'dynamesh/dynamic-zones)))))
        (format  "\n\n\t\t_____________ Warning: piston-full-profile not found in dynamic settings ___________\t\n\n"))
      (set! final-fluids (map thread-name (sort-threads-by-name (get-threads-of-type 'fluid))))
      (set! new-interiors (map thread-name (sort-threads-by-name (get-threads-of-type 'interior))))
      (set! final-walls (map thread-name (sort-threads-by-name (get-threads-of-type 'wall))))
      
      (do ((i 0 (+ i 1))) ((= i (length final-fluids)))
        (if (not (member (list-ref final-fluids i)  (rpgetvar 'ice/fluid-list)))
          (set! new-fluid-names (append  new-fluid-names (list (list-ref final-fluids i))))	  
        )
      )
      ;;get new interior zone names
      (do ((i 0 (+ i 1))) ((= i (length  new-interiors )))
        (if (not (member (list-ref new-interiors  i)   (rpgetvar 'ice/interior-list)))
          (set! new-interior-names (append new-interior-names (list (list-ref  new-interiors i))))
        )
      )
      (do ((i 0 (+ i 1))) ((= i (length final-walls)))
        (if (not (member (list-ref final-walls i)  (rpgetvar 'ice/wall-list)))
          (set! new-walls (append  new-walls (list (list-ref final-walls i))))
        )
      )
      (rpsetvar 'dynamesh/method/layering? #t)
      (if (> (length new-fluid-names) 1)
        (begin
          (if (and (not (thread-name->id "fluid-layer-cylinder")) (not (thread-name->id "fluid-piston")))
            (begin
              ;putting the splitted fluid-ch in a list
              (set! new-chamber-zone-ids (list-add (list-add (list-add '() (thread-name->id (car new-fluid-names))) (thread-name->id (cadr new-fluid-names)) ) (thread-name->id "fluid-ch")))

              ;;; check for original ch
              (if (thread-name->id "fluid-ch")
                (ti-menu-load-string (format #f "/def bc z-n ~s ~s" (thread-name->id "fluid-ch") (string->symbol "ice-fluid-ch-temp")))
              )
              ;finding fluid-ch, fluid-layer-cylinder and fluid-piston
              (if (thread-name->id "cyl-head")
                (begin
                  (set! fluid-ch-id (car (inquire-adjacent-threads (thread-name->id "cyl-head"))))
                  (ti-menu-load-string (format #f "/def bc z-n ~s ~s" fluid-ch-id (string->symbol "fluid-ch")))
                )
              )
              (if (thread-name->id "piston")
                (begin 
                  (set! fluid-piston-layer2-id  (car (inquire-adjacent-threads (thread-name->id "piston"))))
                  (ti-menu-load-string (format #f "/def bc z-n ~s ~s" fluid-piston-layer2-id (string->symbol "fluid-piston")))
                )
              )

              (do ((i 0 (+ i 1))) ((= i (length  new-chamber-zone-ids )))
                (if (and (not (= (list-ref new-chamber-zone-ids i) fluid-ch-id)) (not (= (list-ref new-chamber-zone-ids i) fluid-piston-layer2-id)) )
                  (set! fluid-piston-layer1-id (list-ref new-chamber-zone-ids i))
                )
              )
              (ti-menu-load-string (format #f "/def bc z-n ~s ~s" fluid-piston-layer1-id (string->symbol "fluid-layer-cylinder")))

              ;finding two new interiors and naming them zone1 and zone2
              (do ((i 0 (+ i 1))) ((= i (length  new-interior-names )))
                (define adjthreads)
                (set! adjthreads (inquire-adjacent-threads (thread-name->id  (list-ref new-interior-names  i))))
                (if (and (member fluid-ch-id adjthreads) (member  fluid-piston-layer1-id adjthreads))
                  (set! zone2-name  (list-ref new-interior-names  i))
                )
                (if (and (member fluid-piston-layer2-id adjthreads) (member  fluid-piston-layer1-id adjthreads))
                  (set! zone1-name  (list-ref new-interior-names  i))
                )
              )
              (if (or (eq? zone1-name "") (eq? zone2-name ""))
                (pp "some error in zone assignment; unable to get the new interior zones")
              )
              ;;find the new cyl-quad and cyl-piston and define the regid-body motion with exculde boundary option yes

              (if ( not (= 2 (length new-walls)))
                (pp "some error in zone assign ment; there should be only 2 new cylinder wall zones")
              )

              ;putting the splitted cyl-tri in a list
              (set! new-chamber-wall-ids (list-add (list-add (list-add '() (thread-name->id (car new-walls))) (thread-name->id (cadr new-walls)) ) (thread-name->id "cyl-tri")))

              ;finding cyl-tri, cyl-quad and cyl-piston
              (do ((i 0 (+ i 1))) ((= i (length new-chamber-wall-ids)))
                (if (= (car (inquire-adjacent-threads (list-ref new-chamber-wall-ids i))) fluid-piston-layer1-id)
                  (begin
                    (set! cyl-quad  (list-ref new-chamber-wall-ids i))
                    (ti-menu-load-string (format #f "/def bc z-n ~s ~s" cyl-quad (string->symbol "cyl-quad")))
                  )
                )
                (if (= (car (inquire-adjacent-threads (list-ref new-chamber-wall-ids i))) fluid-piston-layer2-id)
                  (begin
                    (set! cyl-piston (list-ref new-chamber-wall-ids i))
                    (ti-menu-load-string (format #f "/def bc z-n ~s ~s" cyl-piston (string->symbol "cyl-piston")))
                  )
                )
              )
              (do ((i 0 (+ i 1))) ((= i (length  new-chamber-wall-ids )))
                (if (and (not (= (list-ref new-chamber-wall-ids i) cyl-quad)) (not (= (list-ref new-chamber-zone-ids i) cyl-piston)) )
                  (set! cyl-tri (list-ref new-chamber-wall-ids i))
                )
              )
              (if (thread-id->name cyl-tri)
                (ti-menu-load-string (format #f "/def bc z-n ~s ~s" cyl-tri (string->symbol "cyl-tri")))
              )
            )
            (begin
              (if (thread-name->id "cyl-head")
                (begin
                  (set! fluid-ch-id (car (inquire-adjacent-threads (thread-name->id "cyl-head"))))
                  (if (thread-id->name fluid-ch-id)
                    (ti-menu-load-string (format #f "/def bc z-n ~s ~s" fluid-ch-id (string->symbol "fluid-ch"))))
                )
              )                  
              (set! fluid-piston-layer2-id (thread-name->id "fluid-piston"))
              (set! fluid-piston-layer1-id (thread-name->id "fluid-layer-cylinder"))
            )
          )
          (if (and (thread-name->id "fluid-layer-cylinder")(thread-name->id "fluid-piston"))
            (begin
              (set! new-chamber-zone-ids (append '() (list (thread-name->id "fluid-layer-cylinder") (thread-name->id "fluid-piston"))))
              (if (thread-name->id "cyl-quad")
                (set! cyl-quad (thread-name->id "cyl-quad"))
              )
              (if (thread-name->id "cyl-piston")
                (set! cyl-piston (thread-name->id "cyl-piston"))
              )
              (if (thread-name->id "int-piston")
                (set! zone2-name (string->symbol "int-piston"))
              )
              (if (thread-name->id "interior-fluid-layer-cylinder-fluid-piston")
                (set! zone1-name (string->symbol "interior-fluid-layer-cylinder-fluid-piston"))
              )
             ; (wb-ice-update-monitor-after-thread-split-or-merge (list (thread-name->id "fluid-ch")) (list (thread-name->id "fluid-layer-cylinder") (thread-name->id "fluid-piston")))
            )
          )
          ;setting rigid body motion to fluid-layer-cylinder and fluid-piston
          (do ((i 0 (+ i 1))) ((= i (length new-chamber-zone-ids)))
            (if (not (= (list-ref new-chamber-zone-ids i) fluid-ch-id)) 
              (ti-menu-load-string (format #f "\n/def d-m zones create ~s rigid-body ~s  ~s ~s ~s" (list-ref new-chamber-zone-ids i) (string->symbol lpiston-full-prof) (list-ref cylinder-axis 0) (list-ref cylinder-axis 1) (list-ref cylinder-axis 2)))
            )
          )
          ;;Changes in 14.5 to take care of corrections from thomas  DE40230 for exclude boundary conditions
          (if (thread-id->name cyl-quad)
            (ti-menu-load-string (format #f "\n/def d-m zones create ~s rigid-body ~s  yes  ~s  ~s ~s" cyl-quad (string->symbol lpiston-full-prof) (list-ref cylinder-axis 0) (list-ref cylinder-axis 1) (list-ref cylinder-axis 2)))
          )
          (if (thread-id->name cyl-piston)
            (ti-menu-load-string (format #f "\n/def d-m zones create ~s rigid-body ~s   yes  ~s  ~s ~s" cyl-piston (string->symbol lpiston-full-prof) (list-ref cylinder-axis 0) (list-ref cylinder-axis 1) (list-ref cylinder-axis 2)))
          )
          ;;changes end
          (if (thread-name->id  zone2-name)
            (begin
              (set! ave_scale (+ (* 0.5 (car (%get-min-max-length-scale-on-zone (thread-name->id  zone2-name) #t))) (* 0.5 (car (cdr (%get-min-max-length-scale-on-zone (thread-name->id  zone2-name) #t))))))
              (set! ave_scale (string-append "(wb-ice-convert-units " (number->string ave_scale) " " ")" ))
              (if (rp-var-object 'ice/engine-piston-type)
                (if (= (rpgetvar 'ice/engine-piston-type) 1)
                  (ti-menu-load-string (format #f "\n/def d-m zones create int-piston rigid-body ~s ~s ~s ~s ~s constant 0 ~s constant ~s no " (string->symbol profile) (list-ref cylinder-axis 0) (list-ref cylinder-axis 1) (list-ref cylinder-axis 2) fluid-ch-id fluid-piston-layer1-id (string->symbol ave_scale) ))
              (ti-menu-load-string (format #f "\n/def d-m zones create ~s stationary ~s , 0 ~s , ~s" zone2-name fluid-ch-id fluid-piston-layer1-id (string->symbol ave_scale)))
            )
                (ti-menu-load-string (format #f "\n/def d-m zones create ~s stationary ~s , 0 ~s , ~s" zone2-name fluid-ch-id fluid-piston-layer1-id (string->symbol ave_scale)))
              )
            )
          )
          (if (thread-name->id zone1-name)
            (if (member (string->symbol zone1-name) (map thread-id->name (map car (rpgetvar 'dynamesh/dynamic-zones ))))
            (ti-menu-load-string (format #f "\n/def d-m zones delete ~s" zone1-name)))
          )
        )
      )
    )
  )
)

(set! wb-ice-calculate-dpm-parameters
  (lambda(inj-name)
    (let
      (
       (inj-index 0)
       (ref-x 0)
       (ref-y 0)
       (ref-z 0)
	     
       (start-CA 0)
       (frequency 0)
       (max-length 0)
       (total-p-m 0)
       (penetration-length 0)
       (percentage-p-m 0.9)
	     )
      
      (if (not (rp-var-object 'ice/dpm-cal-freq))
      (rp-var-define 'ice/dpm-cal-freq  1 'int 1)
      )

      (set! frequency (rpgetvar 'ice/dpm-cal-freq))
      (if (> frequency 0)
	(begin
	  (if (member inj-name (map symbol->string (map car (rpgetvar 'dpm/injections-list))))
	    (begin
	      (set! inj-index (- (length (rpgetvar 'dpm/injections-list)) (length (member inj-name (map symbol->string (map car (rpgetvar 'dpm/injections-list)) )))))
	      (set! ref-x (cdr (assv 'x-pos (cadr (list-ref (rpgetvar 'dpm/injections-list) inj-index)  ))))	  
	      (set! ref-y (cdr (assv 'y-pos (cadr (list-ref (rpgetvar 'dpm/injections-list) inj-index)  ))))
	      (set! ref-z (cdr (assv 'z-pos (cadr (list-ref (rpgetvar 'dpm/injections-list) inj-index)  ))))
	      (set! start-CA (cdr (assv 'unsteady-ca-start (cadr (list-ref (rpgetvar 'dpm/injections-list) inj-index)  ))))
	      )
	    )


	  (if (wb-ice-execute-command-based-on-crank-angle start-CA frequency )
	    (begin
	      ;(wb-ice-report-dir)

	      (let* ((penlenbins (%get-penetration-length-bins
				   (list 'injections inj-name)
				   (list 'origin ref-x ref-y ref-z))))
		(set! max-length (cadr (assv 'range-max (car penlenbins))))
		(set! total-p-m  (cadr (assv 'total-amount (cadr penlenbins))))
		(plot-penetration-length-bins '(filename "myfile.xy") penlenbins)
		(set! penetration-length (get-penetration-length
					   (list 'criterion percentage-p-m)
					   penlenbins))

		(format #t "\nMax Particle Distance = ~s m\n" max-length)
		(format #t "Particle Penetration Length = ~s m\n" penetration-length)

		(format "\nCalculation of DPM parameters is done!\n")
		;write particle data
		(wb-ice-write-monitor-file  (format #f "ice-penetration-length-by-jos-~s.out" (string->symbol inj-name)) (format #f "Penetration length of ~s per Time Step"(string->symbol inj-name)) "Flow time" "Penetration Length" (client-inquire-flow-time) penetration-length)

		)

	      )
	    )
	  )
	)
      )
    )

  )
  
  ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; global remeshing setting, cyl-tri, symm-cyl-tri, int-piston, crevice
(set! wb-ice-kg-define-dyn-settings-canted-valve-engine
  (lambda()
    (format  "\n\t\t_____________ defining dynamic mesh settings for canted valve engine after mesh replacement ___________\t\n")  
    (let
      (
       (min_scale 0)
       (max_scale 0)
       (ave_scale 0)
       (piston_layer_height 0)
       (zone_name "")
       (zone_dyn_mesh_settings '())
       (origin '())
       (axis '())
       (radius "")
       (motion_type "stationary")
       (profile "**piston-limit**")
       (all_fluid_zones (map thread-name (sort-threads-by-name (get-threads-of-type 'fluid))))
       (layering? #t)
       (smoothing_string "")
       (smoothing_type (if wb_ice_only_smoothing?  "diffusion" "spring"))
       (cylinder_axis '(0 1 0))
       (lpiston_full_prof "**piston-full**")
      )
      (if (assoc 'geom-axis (assoc (thread-name->id "cyl-tri") (rpgetvar 'dynamesh/dynamic-zones)))
        (set! cylinder_axis (cadr (assoc 'geom-axis (assoc (thread-name->id "cyl-tri") (rpgetvar 'dynamesh/dynamic-zones)))) ))
      (if (assoc 'udf (assoc (thread-name->id "piston") (rpgetvar 'dynamesh/dynamic-zones)))
        (set! lpiston_full_prof (cadr (assoc 'udf (assoc (thread-name->id "piston") (rpgetvar 'dynamesh/dynamic-zones))))))
      ;defining global min and max length scales remeshing parmaeters
      (if (= (length all_fluid_zones) 1)
        (set! smoothing_type "diffusion"))
          
      (if (and (thread-name->id  "fluid-ch") (not wb_ice_only_smoothing?))
        (begin
          (format  "\n\t\t _____________Defining global min and max length scales remeshing parameters_____________ \t\n\n")
          (set! min_scale (* 0.95 (car (%get-min-max-length-scale-on-zone (thread-name->id  "fluid-ch") #f))))
          (set! max_scale (* 1.1 (car (cdr (%get-min-max-length-scale-on-zone (thread-name->id  "fluid-ch") #f)))))
          (ti-menu-load-string (string-append "/def/d-m/c/r-p/length-min " (number->string min_scale)))
          (ti-menu-load-string (string-append "/def/d-m/c/r-p/length-max "  (number->string max_scale)))
        )
      )
          
          ;;cyl-tri deforming zone for piston-type1 and piston-type3 engines
      (if (thread-name->id  "cyl-tri")
        (begin
          (set! zone_name "cyl-tri")
          
          (set! zone_dyn_mesh_settings (assoc (thread-name->id zone_name) (dynamic-thread-list)))
          (if zone_dyn_mesh_settings
            (begin
          (set! origin (cadr (assoc 'geom-origin zone_dyn_mesh_settings)))
          (set! axis (cadr (assoc 'geom-axis zone_dyn_mesh_settings)))
          (set! radius (cadr (assoc 'radius zone_dyn_mesh_settings)))
          (format  "\n\n\t\t_____________ Defining remeshing parameters for cyl-tri ___________\t\n\n")  
          (set! ave_scale (+ (* 0.5 (car (%get-min-max-length-scale-on-zone (thread-name->id  "cyl-tri") #f))) (* 0.5 (cadr (%get-min-max-length-scale-on-zone (thread-name->id  "cyl-tri") #f)))))
          (set! min_scale (* 0.5 ave_scale))
          (set! max_scale (* 1.5 ave_scale))
          (set! smoothing_string (wb-ice-kg-get-smoothing-string))
          (ti-menu-load-string (string-append  "/def d-m z c " zone_name " deforming cylinder " (number->string radius) " " (number->string (car origin)) " " (number->string (cadr origin)) " " (number->string (caddr origin)) " " (number->string (car axis)) " " (number->string (cadr axis)) " " (number->string (caddr axis)) " " smoothing_string " " (number->string min_scale) " " (number->string max_scale) " 0.6"))
        )
             (format  "\n\t ============Warning: Can not define \"cyl-tri\" deforming as the dynamic settings are missing from dynamic-thread-list=========== 
            ============This might be because in previous mesh \"cyl-tri\" dynamic zone was not present============
            ============This is serious issue and mesh might fail during mesh motion============\t\n\n")
          )
        )
      )
     (if (thread-name->id  "int-piston")
        (begin
          (set! zone_name "int-piston")
          (set! zone_dyn_mesh_settings (assoc (thread-name->id zone_name) (dynamic-thread-list)))
          (if zone_dyn_mesh_settings  
        (begin
          ;layer height for fluid-layer-cylinder
              (if (assoc (thread-name->id zone_name) (rpgetvar 'dynamesh/dynamic-zones))
                (if (= (cadr (assoc 'type (assoc (thread-name->id zone_name) (rpgetvar 'dynamesh/dynamic-zones)))) 1) 
            (set! motion_type "rigid-body")
            (set! motion_type "stationary")
          )
              )
              (set! axis (cadr (assoc 'axis (assoc (thread-name->id zone_name) (dynamic-thread-list)))))
              (set! profile (cadr (assoc 'udf (assoc (thread-name->id zone_name) (dynamic-thread-list)))))
          (format  "\n\n\t\t_____________ Defining remeshing parameters for int-piston___________\t\n\n")  
              (set! ave_scale (+ (* 0.5 (car (%get-min-max-length-scale-on-zone (thread-name->id zone_name) #f))) (* 0.5 (car (cdr (%get-min-max-length-scale-on-zone (thread-name->id  "int-piston") #f))))))
          (set! piston_layer_height (* 1.2 ave_scale))
          (if (string=? motion_type "rigid-body")
            (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create int-piston rigid-body  " profile " " (number->string (car axis)) " " (number->string (cadr axis)) " " (number->string (caddr axis)) "  " (number->string (thread-name->id  "fluid-ch")) " constant 0 " (number->string (thread-name->id  "fluid-layer-cylinder")) " constant " (number->string ave_scale) " no"))
            (ti-menu-load-string (format #f "/define/dynamic-mesh/zones/create int-piston stationary ~s constant 0 ~s constant ~s " (thread-name->id  "fluid-ch") (thread-name->id  "fluid-layer-cylinder") ave_scale ))
          )
        )
      )
        )
      )
  
          ;for symmetry-cyl-tri deforming zone
          ;(set! symmetryengine             (read-var ICDyMeshSetFile 'symmetry_engine))
      (if (thread-name->id  "symm-cyl-tri")
        (begin
          (set! zone_name "symm-cyl-tri")
          
          (set! zone_dyn_mesh_settings (assoc (thread-name->id zone_name) (dynamic-thread-list)))
          (if zone_dyn_mesh_settings
            (begin
          (set! origin (cadr (assoc 'geom-origin zone_dyn_mesh_settings)))
          (set! axis (cadr (assoc 'geom-axis zone_dyn_mesh_settings)))
          
          (format  "\n\n\t\t_____________ Defining remeshing parameters for symm-cyl-tri___________\t\n\n")  
          (set! ave_scale (caddr  (%get-min-max-length-scale-on-zone (thread-name->id  (string-append "symm-cyl-tri")) #f)))
          (set! min_scale (* 0.4 ave_scale))
          (set! max_scale (* 1.4 ave_scale))
          (set! smoothing_string (wb-ice-kg-get-smoothing-string))
          (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create symm-cyl-tri deforming plane " (number->string (car origin)) " " (number->string (cadr origin)) " " (number->string (caddr origin)) " " (number->string (car axis)) " "  (number->string (cadr axis)) " " (number->string (caddr axis)) " " smoothing_string " " (number->string min_scale) " " (number->string max_scale) " 0.65"))
        )
            (format  "\n\t ============Warning: Can not define \"symm-cyl-tri\" deforming as the dynamic settings are missing from dynamic-thread-list=========== 
            ============This might be because in previous mesh \"symm-cyl-tri\" dynamic zone was not present============
            ============This is serious issue and mesh might fail during mesh motion============\t\n\n")
          )
        )
      )
      (if (thread-name->id  "fluid-crevice")
        (begin
          (format  "\n\n\t\t_____________ Defining rigid body motion for fluid-crevice___________\t\n\n")
          (ti-menu-load-string (format #f "/def d-m zones create fluid-crevice rigid-body ~s  ~s ~s ~s" (string->symbol lpiston_full_prof) (list-ref cylinder_axis 0) (list-ref cylinder_axis 1) (list-ref cylinder_axis 2)))
        )
      )
      (if (thread-name->id  "cyl-crevice")
        (begin
          (format  "\n\n\t\t_____________ Defining rigid body motion for cyl-crevice___________\t\n\n")
          (ti-menu-load-string (format #f "/def d-m zones create cyl-crevice rigid-body ~s  yes  ~s  ~s ~s" (string->symbol lpiston_full_prof) (list-ref cylinder_axis 0) (list-ref cylinder_axis 1) (list-ref cylinder_axis 2)))
        )
      )
    )      
  )
)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define wb-ice-get-valve-names
  (lambda ()
    (let 
      ( (all_walls '())
       (seat_walls '())
       (valve_name ""))
      
      (set! all_walls (map thread-name (sort-threads-by-name (get-threads-of-type 'wall))))
      (for-each 
        (lambda (wall) 
          (set! wall (symbol->string wall)) 
          (if (string=? (substring wall (- (string-length wall) 4) (string-length wall) ) "seat" ) 
            (begin
              (set! valve_name (substring wall 0 (- (string-length wall) 5)))
              (set! seat_walls (append seat_walls (cons valve_name '()))))) 
            )
      all_walls)
          seat_walls)
  )
)
; deforming valve interfaces remeshing settings if present in dynamic settings
(set! wb-ice-kg-define-valve-ch-interfaces-deforming
  (lambda()
    (let
      (
        (ave_scale 0)
        (min_scale 0)
        (max_scale 0)
        (valve_name '())
        (zone_name "")
        (zone_dyn_mesh_settings '())
        (origin '())
        (axis '())
        (radius "")
        (profile "**piston-full**")
        (smoothing_string "")
        (valve_value "")
        (smoothing_type (if wb_ice_only_smoothing?  "diffusion" "spring"))
      )
      (set! valve_name (wb-ice-get-valve-names-from-ch))
      (set! smoothing_string (wb-ice-kg-get-smoothing-string))
      (if (not (thread-name->id  "fluid-ch-upper"))
        (begin
          (for-each 
            (lambda (valve_list)
              (set! valve_value (list-ref valve_list 1))
              (for-each 
                (lambda (zone_name)
                  (if (thread-name->id zone_name)
                    (begin                   
                      (set! ave_scale (caddr  (%get-min-max-length-scale-on-zone (thread-name->id  zone_name) #f)))
                      (set! min_scale (* 0.4 ave_scale))
                      (set! max_scale (* 1.4 ave_scale))
                      
                      (set! zone_dyn_mesh_settings (assoc (thread-name->id zone_name) (dynamic-thread-list)))
                      (if zone_dyn_mesh_settings
                        (begin
                          (format  "\n\t\t_____________ set deforming remeshing parameters for zone ~a ___________\t\n\n" zone_name )  
                          (set! origin (cadr (assoc 'geom-origin zone_dyn_mesh_settings)))
                          (set! axis (cadr (assoc 'geom-axis zone_dyn_mesh_settings)))
                          (set! radius (cadr (assoc 'radius zone_dyn_mesh_settings)))
                          
                          (ti-menu-load-string (string-append  "/def d-m z c " zone_name " deforming cylinder " (number->string radius) " " (number->string (car origin)) " " (number->string (cadr origin)) " " (number->string (caddr origin)) " " (number->string (car axis)) " " (number->string (cadr axis)) " " (number->string (caddr axis)) " " smoothing_string " " (number->string min_scale) " " (number->string max_scale) " 0.6"))
                        )
                        (begin
                          (format  "\n\t\t_____________ set deforming remeshing parameters for zone ~a ___________\t\n\n" zone_name )
                          (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create " zone_name " deforming cylinder " (number->string (list-ref valve_list 5)) " " (number->string (list-ref (list-ref valve_list 7) 0)) " " (number->string (list-ref (list-ref valve_list 7) 1)) " " (number->string (list-ref (list-ref valve_list 7) 2)) " " (number->string (list-ref (list-ref valve_list 6) 0)) " " (number->string (list-ref (list-ref valve_list 6) 1)) " " (number->string (list-ref (list-ref valve_list 6) 2)) " " smoothing_string " " (number->string min_scale) " " (number->string max_scale) " 0.6"))
                        )
                      )
                    )
                  )
                ) (list (string-append "intf-" valve_value "-ob-fluid-ch") (string-append "intf-" valve_value "-port-fluid-ch") (string-append "intf-" valve_value "-ch-fluid-port") (string-append "interior-" valve_value "-port-fluid-ch") )
              )
            ) (rpgetvar 'ice/setup-valve-list)
          )
        )
        (begin
          (format  "\n\t\t_____________ Defining cell height for fluid-ch-lower__________\t\n\n")  
          (if (and (thread-name->id  "intf-piston-ch") (thread-name->id  "intf-deck-fluid-ch-lower"))
            (begin
              (set! zone_name "intf-deck-fluid-ch-lower")
	      (set! zone_dyn_mesh_settings (assoc (thread-name->id zone_name) (dynamic-thread-list)))

	      (set! axis (cadr (assoc 'axis (assoc (thread-name->id "intf-piston-ch") (dynamic-thread-list)))))
	      (set! profile (cadr (assoc 'udf (assoc (thread-name->id "intf-piston-ch") (dynamic-thread-list)))))

              (set! ave_scale (caddr  (%get-min-max-length-scale-on-zone (thread-name->id  zone_name) #f)))
              
              (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create intf-piston-ch rigid-body  " profile "  no " (number->string (car axis)) " " (number->string (cadr axis)) " " (number->string (caddr axis)) " ,, " (number->string ave_scale)))
              (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create intf-deck-fluid-ch-lower stationary , , "  (number->string ave_scale)))
            )
          )
        )
      
      )
    ) 
  )
)

(define wb-ice-define-sliding-interfaces
  (lambda ()
    (format  "\n\n\t\t ___________Defining mesh interfaces after mesh replacement _____________\t\n\n")  
    (let
      (
        (si (rpgetvar 'ice/sliding-interfaces))
        (non_present_interfaces '())
      )
      (for-each 
        (lambda (ssi) 
          (let
            ((name (car ssi))
             (sb1-id (map thread-id->name (cdr (assoc 'sb1-id ssi))))
             (sb2-id (map thread-id->name (cdr (assoc 'sb2-id ssi))))
             (coupled? (cdr (assoc 'coupled ssi)))
             (periodic? (cdr (assoc 'face-periodic ssi)))
             (matching? (cdr (assoc 'matching ssi)))
             (angle-shift 0)
             
            )
           ;(create-si-callback name sb1-id sb2-id)
           (if (and periodic? (assoc 'angle ssi))
             (begin 
              (set! angle-shift (cdr (assoc 'angle ssi)))
              (set! angle-shift (/ (* angle-shift 180.) 3.14159265358979323846 ))
             )
           )
           (if (and (car sb1-id) (car sb2-id))
            (wb-ice-create-Mesh-Interfaces name sb1-id sb2-id coupled? periodic? matching? angle-shift)
            (set! non_present_interfaces (append non_present_interfaces (list name))))
            
          )
        )
        si
      )
      (if (not (null? non_present_interfaces))
          (format " info : zones for following interface are absent in replaced mesh : \n ~a " non_present_interfaces ))
    )
  )
)

(define wb-ice-create-Mesh-Interfaces
  (lambda(intf-name intf-zone-1 intf-zone-2 coupled? periodic? matching? angle-shift)
    (let
      (
      (option-string "")
      )
      (if (or (> (length intf-zone-1) 1) (> (length intf-zone-2) 1))
        (begin
          (if matching? 
            (set! option-string "no yes")
            (set! option-string "no no")
          )
        )
        (begin
          (if matching?
            (set! option-string "no no yes")
            (set! option-string "no no no")
          )
        )
      )
        ;for periodic interface
      (if periodic?
        (ti-menu-load-string (format #f  "/def/m-i/make-periodic ~s ~s yes ~s yes no ~s" (string->symbol (car intf-zone-1)) (string->symbol (car intf-zone-2))  angle-shift (string->symbol intf-name)))
        (ti-menu-load-string (format #f "/def/m-i/create ~s ~s ~s ~s" intf-name intf-zone-1 intf-zone-2 (string->symbol option-string) ))
      )
      
    )
  )
)
; following function returns all the chamber zones for ICE case like fluid-ch, fluid-piston, fluid-layer-cylinder, fluid-ch-upper/lower etc
(set! wb-ice-get-all-chamber-zones
  (lambda()
    (let
      (
       (zones (map thread-name (sort-threads-by-name (get-threads-of-type 'fluid))))
       (ch-zones '())
       )
      (if (not (string-ci=? (rpgetvar 'ice/combustion-simulation-type) "sector"))
	(begin 
	  (for-each (lambda (ls1)
		      (if (or (substring? "fluid-ch" (symbol->string ls1)) (substring? "fluid-piston" (symbol->string ls1)) (substring? "fluid-layer-cylinder" (symbol->string ls1)) (substring? "fluid-crevice" (symbol->string ls1)) )
			(set! ch-zones (append ch-zones (cons ls1 '())))
			)) zones )
	  )
	(set! ch-zones zones)
	)ch-zones
      )
    )
  )

; following function is defined to reset-EGR one deg before invalve-open. Here we are calling fluent function inert-egr-reset with "chamber-zones" as argument. These chamber zones will be pulled dynamically at that event point. This is the reason we are using this through already available in-cylinder event
(set! wb-ice-inert-egr-reset
  (lambda (zones)
    (let* ((threads (map get-thread zones))
           (ids (map thread-id threads)))
          (inert-egr-reset threads ids))
    
    )
)

(set! wb-ice-define-valve-open-event
  (lambda (intf_name zone1_id zone2_id start_angle matching?)
    (let ()
      (if matching?
        (define matching_string " no no no yes")
        (define matching_string " no")
      )
      (if (and (thread-name->id zone1_id) (thread-name->id zone2_id))
        (begin
          (format "\n\n\t\t ___________  Defining mesh interface ~a _____________\t\n\n " intf_name)
          (wb-ice-changeBC zone1_id "interface")
          (wb-ice-changeBC zone2_id "interface")
          (if (not (assoc (string->symbol  intf_name) (rpgetvar 'sliding-interfaces)))
            (ti-menu-load-string (string-append "define mi create " (symbol->string intf_name) " " zone1_id " () " zone2_id " () " matching_string ))
            (format "\n\n Info: Interface ~a already exist so could not create another with the same name \n " intf_name)
          )
        )
        (format "\n\n Warning: Zones not present. Unable to create interface between ~a and ~a " zone1_id zone2_id)
      )
    )
  )
)

(set! wb-ice-deactivate-cell-zones
  (lambda (zone_list)
    (let 
      (
        (all_zones (map thread-name (get-threads-of-type 'fluid)))
        (non_present_zones '())
        (final_zones '())
      )
      (format "\n\n zones to deactivate \n ~s " zone_list)
      (set! zone_list (map string->symbol zone_list))
      (for-each 
        (lambda (zone)
          (if (member zone all_zones)
            (set! final_zones (append final_zones (list zone)))
            (set! non_present_zones  (append non_present_zones (list zone)))
          )
        ) zone_list
      )
      (set! zone_list (map string->symbol final_zones))
      (if (not (null? zone_list))
        (if (in-wb?)
        (ti-menu-load-string (format #f "/mesh mod-zone deactivate-cell-zone y ~s" zone_list) ) 
          (ti-menu-load-string (format #f "/mesh mod-zone deactivate-cell-zone ~s" zone_list) ) 
        )
      )
      (if (not (null? non_present_zones))
        (format "\n\nFollowing zones can not be de-activated as their names do not match with existing zones or it is already deactivated. Check the zone names \n ~s " non_present_zones)
      )
    )
  )
)

(set! wb-ice-activate-cell-zones
  (lambda (zone_list)
    (let
      (
        (final_zones '())
        (non_present_zones '())
        (deactivated_zones '())
       
      )
      (if (assq 'deactivated-zones (rpgetvar 'deactivated-original-state))
        (begin
          (set! deactivated_zones (map thread-name (get-nosolve-face-cell-threads)))
          (set! zone_list (map string->symbol zone_list))
          (for-each 
            (lambda (zone)
              (if (member zone deactivated_zones)
                (set! final_zones (append final_zones (list zone)))
                (set! non_present_zones  (append non_present_zones (list zone)))
              )
            ) zone_list
          )
          (if (not (null? final_zones))
            (ti-menu-load-string (format #f "/mesh mod-zone activate-cell-zone y ~s" final_zones) ))
          (if (not (null? non_present_zones))
            (format "\n\nFollowing zones can not be activated as there names do not match with existing zones \n ~s " non_present_zones)
          )
        )
        (format "\n\nFollowing zones can not be activated as there names do not match with existing zones \n ~s " zone_list)
      )
    )
  )
)

(set! wb-ice-convert-units
  (lambda (cell_height)
    (let
      (
        (current_unit_list (cx-lookup-units 'length))     
      )
      (if (not (= (cadr current_unit_list) 1))
        (set! cell_height (/ cell_height (cadr current_unit_list))))     
    )
    cell_height
  )
)

(set! wb-ice-calc-ahrr-condition
  (lambda ()
    (let 
      (
        (current_ca (ice-remainder (rpgetvar 'dynamesh/in-cyn/crank-angle) 720))
        (return_value #f)
      )
      (if (and (rp-var-object 'ice/combustion-simulation-type) (rp-var-object 'ice/ahrr-min-open-angle))
        (begin
          (if (or
                (string=? (rpgetvar 'ice/combustion-simulation-type) "sector") (string=? (rpgetvar 'ice/combustion-simulation-type) "full_engine_ivc_to_evo")
                (or (< current_ca (rpgetvar 'ice/ahrr-min-open-angle)) (> current_ca (rpgetvar 'ice/ahrr-max-close-angle)))
              )
              (set! return_value #t)
          )
        )
        (set! return_value #t) ;this is for r15 cases where these rpvars are not defined
      )
      return_value
    )
  )
)
;; mesh topology methods starts here 
(set! wb-ice-kg-zone-names-check-new-topology
  (lambda ()
    (let 
      (
        (dyn_zone_check_list '())
        (all_fluid_zones (map thread-name (sort-threads-by-name (get-threads-of-type 'fluid))))
        (valve_names '())
        (non_matching_zone_list '())
        (symmetryengine? #f)
      )
      ;(set! symmetryengine? (read-var ICDyMeshSetFile 'symmetry_engine))
      (set! dyn_zone_check_list (list "cyl-tri" "piston" "fluid-ch"))
      (if symmetryengine? 
        (set! dyn_zone_check_list (append dyn_zone_check_list (list "symm-cyl-tri" ))))
      
      (set! valve_names (wb-ice-get-valve-names-from-stem))
      (if (null? valve_names)
        (format "\n\n\t\t ___________  No valve zones are present in this mesh If you continue with this mesh after valve opens \n\t\t then you may face issues. For valve movement <valve_name>-stem zone is required.___________ \t\n\n " )
        (begin
          (for-each 
            (lambda (valve)
              (set! dyn_zone_check_list (append dyn_zone_check_list (list (string-append valve "-stem"))))
              (set! dyn_zone_check_list (append dyn_zone_check_list (list (string-append valve "-ch"))))        
            ) valve_names
          )
        )
      )
      (if (> (length all_fluid_zones) 1)
        (begin
           (for-each 
            (lambda (zone)
              (if (string-ci=? "fluid-layer-cylinder" (symbol->string zone))
                (begin 
                  (set! dyn_zone_check_list (append dyn_zone_check_list (list "fluid-layer-cylinder")))
                  (set! dyn_zone_check_list (append dyn_zone_check_list (list "int-piston")))
                  (set! dyn_zone_check_list (append dyn_zone_check_list (list "fluid-piston")))
                  (set! dyn_zone_check_list (append dyn_zone_check_list (list "fluid-ch")))
                )
              )
              (if (and (substring? "fluid-" (symbol->string zone)) (substring? "-vlayer" (symbol->string zone))  )
                (if (wb-ice-query-if-vlayer-layering (symbol->string zone))
                  (set! dyn_zone_check_list (append dyn_zone_check_list (wb-ice-get-zones-for-vlayer-layering zone ))) )
              )
              (if (and (substring? "fluid-" (symbol->string zone)) (substring? "-ib" (symbol->string zone))  )
                (if (wb-ice-query-if-ib-layering (symbol->string zone))
                  (set! dyn_zone_check_list (append dyn_zone_check_list (wb-ice-get-zones-for-ib-layering zone ))) )
              )

              (if (string-ci=? "fluid-crevice" (symbol->string zone))
                (set! dyn_zone_check_list (append dyn_zone_check_list (list "intf-crevice-on-piston" "intf-piston-on-crevice" "fluid-crevice")))
              )
              (if (and (string-ci=? "fluid-ch-lower" (symbol->string  zone)) (thread-name->id "intf-deck-fluid-ch-lower" ))
                (if (%zone-is-adjacent-to-hex-or-prism-cells (thread-name->id "intf-deck-fluid-ch-lower" ))
                  (set! dyn_zone_check_list (append dyn_zone_check_list "intf-deck-fluid-ch-lower")))
              )
            )all_fluid_zones
          )
        )
      )
      (set! non_matching_zone_list (wb-ice-find-non-matching-zones dyn_zone_check_list))
      (if (not (null? non_matching_zone_list))
        (begin
          (format "\n\n\t\t ___________Warning: Following zones did not match in replace mesh \n \t\t ___________ Correct the dynamic mesh settings of these zones otherwise mesh might fail _____________\t\n\n ~s\n" non_matching_zone_list )
        )
        (begin
          (format "\n\n\t\t ___________  Following zones are matched successfully ___________ \t\n\n ~s\n" dyn_zone_check_list )
        )
      )     
    )
  )
)

(set! wb-ice-find-non-matching-zones
  (lambda (dyn_zone_check_list)
    (let 
      (
        (all_surfaces (inquire-surface-names))
        (all_fluid_zones (map thread-name (sort-threads-by-name (get-threads-of-type 'fluid))))
        (surface_counter 0)
        (final_list '())
        (matched #f)
      )
      (set!  all_surfaces (append all_surfaces (inquire-zone-names)))
      (for-each
        (lambda (dyn_zone)
          (if dyn_zone
            (begin      
              (set! matched #f)
              (for-each
                (lambda (surfacename)
                  (if (string-ci=? (symbol->string surfacename) dyn_zone)
                    (begin 
                      (set! surface_counter (+ surface_counter 1))
                      (set! matched #t)
                    )
                  ) 
                ) all_surfaces
              )
              (if (not matched)
                (set! final_list (append final_list (list dyn_zone )))
              )
            )
          )    
        ) dyn_zone_check_list
      )
      final_list
    )
  )
)

(set! wb-ice-get-zones-for-vlayer-layering
  (lambda (vlayer_zone_name)
    (let 
      (
        (vlayer_list '())
        (valve "")
        (valve_names (wb-ice-get-valve-names-from-stem))
        (name_list '())
      )
      (set! name_list (wb-ice-string-split-by-delimiter (symbol->string vlayer_zone_name) "-"))
      (if (>= (length name_list) 2)
        (set! valve (symbol->string (cadr name_list))))
      (if (member valve valve_names)
        (begin
          (set! vlayer_list (append vlayer_list (list (string-append valve "-seat"))))
          (set! vlayer_list (append vlayer_list (list (string-append "intf-int-" valve "-ob-fluid-vlayer"))))
          (set! vlayer_list (append vlayer_list (list (string-append "intf-int-" valve "-ob-fluid-port"))))
          (set! vlayer_list (append vlayer_list (list (string-append valve "-ob"))))
          (set! vlayer_list (append vlayer_list (list (string-append "intf-" valve "-ib-fluid-ob-quad"))))
          (set! vlayer_list (append vlayer_list (list (string-append "intf-" valve "-ob-fluid-vlayer"))))
          (set! vlayer_list (append vlayer_list (list (string-append "intf-" valve "-ob-fluid-ch"))))
        )
        (format "\n\n\t\t ___________  vlayer cell zone name is not in proper format. cell zone name = ~a ; \t valve name = ~a ___________ \t\n\n " vlayer_zone_name valve )
      )
      vlayer_list
    )
  )
)

(set! wb-ice-get-zones-for-ib-layering
  (lambda (ib_zone_name)
    (let
      (
        (ib_list '())
        (valve "")
        (valve_names (wb-ice-get-valve-names-from-stem))
        (name_list '())
      )
      (set! name_list (wb-ice-string-split-by-delimiter (symbol->string ib_zone_name) "-"))
      (if (>= (length name_list) 2)
        (set! valve (symbol->string (cadr name_list))))
      (if (member valve valve_names)
        (begin
          (set! ib_list (append ib_list (list (string-append valve "-ib"))))
          (set! ib_list (append ib_list (list (string-append "intf-int-" valve "-ib-fluid-ib"))))
          (set! ib_list (append ib_list (list (string-append "intf-" valve "-ib-fluid-ib"))))
          (set! ib_list (append ib_list (list (string-append "intf-" valve "-ib-fluid-ob-tri"))))
          (set! ib_list (append ib_list (list (string-append "intf-int-" valve "-ib-fluid-port"))))
        )
        (format "\n\n\t\t ___________  ib cell zone name is not in proper format. cell zone name = ~a ; \t valve name = ~a ___________ \t\n\n " ib_zone_name valve )
      )
      ib_list
    )
  )
)
(set! wb-ice-get-valve-names-from-stem
  (lambda ()
    (let 
      ( (all_walls '())
       (stem_walls '())
       (valve_name ""))
      
      (set! all_walls (map thread-name (sort-threads-by-name (get-threads-of-type 'wall))))
      (for-each 
        (lambda (wall) 
          (set! wall (symbol->string wall)) 
          (if (substring? "-stem" wall)
            (begin
              (set! valve_name (substring wall 0 (- (string-length wall) 5)))
              (set! stem_walls (append stem_walls (cons valve_name '()))))) 
            )
      all_walls)
          stem_walls)
  )
)
;defines rigid motion for invalve1-ib, -ob, -ch, -seat, -stem , fluid-ib, vlayer
(set! wb-ice-kg-define-dyn-settings-new-topology
  (lambda ()
    (let 
      (
        (ave_scale 0)
        (min_scale 0)
        (max_scale 0)      
        (valve_names '())
        (zone_name "")
        (smoothing_type (if wb_ice_only_smoothing?  "diffusion" "spring"))
        (smoothing_string "")
        (all_fluid_zones (map thread-name (sort-threads-by-name (get-threads-of-type 'fluid))))
      )
      (format  "\n\n\t\t ___________ Changing to Non-ICE mesh topology and defining dynamic settings _____________\t\n\n")
      (set! valve_names (wb-ice-get-valve-names-from-ch))
      (if (= (length all_fluid_zones) 1)
        (begin
          (ti-menu-load-string (format #f "/def d-m c layering no"))
          (set! smoothing_type "diffusion")
        )
      )
      ;defines rigid motion for invalve1-ib, -ob, -ch, -seat, -stem , fluid-ib, vlayer
      (wb-ice-kg-define-zone-motions-new-topology)
      ;if current_angle > valve_open_angle then defines valve matching interface
      (wb-ice-kg-create-valve-interfaces)
      (if (not (null? valve_names))
        (begin
          (for-each 
            (lambda (valve)
              ;mesh topology -2 
              (if (and  (thread-name->id (string-append "fluid-" valve "-vlayer")) 
                        (not (null? (wb-ice-get-port-zones-from-valve-name valve))) 
                        (not (thread-name->id (string-append "fluid-" valve "-ib"))))
                (let
                  (
                    (seat_zone_id (thread-name->id (string-append valve "-seat")))
                    (vlayer_zone_name (string-append "fluid-" valve "-vlayer"))
                  )
                  (if seat_zone_id
                    (if (%zone-is-adjacent-to-hex-or-prism-cells seat_zone_id)
                      (wb-ice-kg-define-mesh-interfaces-for-mesh-topology-2 vlayer_zone_name)
                      (format "\n\n\t\t ___________  ~a zone does not have adjacent hex/prism layers, so zone ~a can not be layered ___________ \t\n\n" (thread-id->name seat_zone_id) (string-append "fluid-" valve "-vlayer") )
                    )
                  )
                )
              )
              ;;mesh topology 3
              (if (and  (not (thread-name->id (string-append "fluid-" valve "-vlayer")) )
                        (not (null? (wb-ice-get-port-zones-from-valve-name valve))) 
                        (not (thread-name->id (string-append "fluid-" valve "-ib"))))
                (for-each
                  (lambda (zone_name)
                    (if (thread-name->id zone_name)
                      (let*
                        (
                          (zone_id (thread-name->id zone_name))
                          (adjacent-threads (if zone_id (inquire-adjacent-threads zone_id) #f))
                          (id0 (if adjacent-threads (car adjacent-threads) #f))
                          (id1 (if adjacent-threads (cadr adjacent-threads) #f))
                        )
                        (if (and id0 id1)
                          (begin
                            (format "\n\n\t\t ___________  changing ~a zone type to interior as mesh between port and chamber is conformal ___________ \t\n\n" zone_name)
                            (set-thread-type! (get-thread zone_id) 'interior)
                          )
                        )
                      )
                    )
                    ;(format "\n\n  Warning: no face zone ~a in replacement mesh \n\n" zone_name)
                  ) (list (string-append "intf-" valve "-ob-fluid-ch") (string-append "intf-" valve "-ch-fluid-port") (string-append "intf-" valve "-port-fluid-ch"))
                )
              )
            ) valve_names
          )
        )
      )
    )
  )
)

(set! wb-ice-get-valve-names-from-ch
  (lambda ()
    (let 
      ( 
        (all_walls '())
        (ch_walls '())
        (valve_names "")
      )      
      (set! all_walls (map thread-name (sort-threads-by-name (get-threads-of-type 'wall))))
      (for-each 
        (lambda (wall) 
          (set! wall (symbol->string wall)) 
          (if (and (not (substring? "intf-" wall)) (string=? (substring wall (- (string-length wall) 3) (string-length wall) ) "-ch" ) )
            (begin
              (set! valve_names (substring wall 0 (- (string-length wall) 3)))
              (set! ch_walls (append ch_walls (cons valve_names '())))
            )
          ) 
        ) all_walls
      ) ch_walls
    )
  )
)

(set! wb-ice-query-if-ib-layering
  (lambda (zone)
    (let
      (
        (valve "")
        (ib_hex_mesh? #f)
        (name_list '())
      )
      (set! name_list (wb-ice-string-split-by-delimiter (symbol->string zone) "-"))
      (if (>= (length name_list) 2)
        (set! valve (symbol->string (cadr name_list))))
      (if (thread-name->id (string-append "intf-int-" valve "-ib-fluid-ib"))
        (if (%zone-is-adjacent-to-hex-or-prism-cells (thread-name->id (string-append "intf-int-" valve "-ib-fluid-ib")))
          (set! ib_hex_mesh? #t) ))         
      ib_hex_mesh?
    )
  )
)

(set! wb-ice-query-if-vlayer-layering
  (lambda (vlayer_zone_name)
    (let
      (
        (valve "")
        (vlayer_hex_mesh? #f)
        (name_list '())
      )
      (set! name_list (wb-ice-string-split-by-delimiter (symbol->string vlayer_zone_name) "-"))
      (if (>= (length name_list) 2)
        (set! valve (symbol->string (cadr name_list))))
      (if (thread-name->id (string-append "intf-int-" valve "-ob-fluid-vlayer"))
        (if (%zone-is-adjacent-to-hex-or-prism-cells (thread-name->id (string-append "intf-int-" valve "-ob-fluid-vlayer")))
          (set! vlayer_hex_mesh? #t) ))
      (if (thread-name->id (string-append valve "-seat"))
        (if (%zone-is-adjacent-to-hex-or-prism-cells (thread-name->id (string-append valve "-seat")))
          (set! vlayer_hex_mesh? #t) ))
      vlayer_hex_mesh?
    )
  )
)

(set! wb-ice-kg-define-smoothing-remeshing-parameters
  (lambda ()
    (let*
      ( 
        (all_fluid_zones (map thread-name (sort-threads-by-name (get-threads-of-type 'fluid))))
        (smoothing_type (if (or wb_ice_only_smoothing? (= (length all_fluid_zones) 1)) "diffusion" "spring"))
        (layering? #f)
      )
      (format  "\n\n\t\t ___________ Defining smoothing, remeshing, layering parameters after mesh replace. Using ~a smoothing type _____________\t\n\n" smoothing_type)
      (if (wb-ice-kg-query-if-layering-possible)
        (set! layering? #t))
      (if (string-ci=? smoothing_type "spring")
        (begin
          (ti-menu-load-string (format #f "/def dm c smoothing? yes"))
          (ti-menu-load-string (format #f "/def dm c s-p s-m spring"))
          (ti-menu-load-string (format #f "/define/dynamic-mesh/controls/smoothing-parameters/spring-on-all-shapes? y"))
          (ti-menu-load-string "/def/dynamic-mesh/controls/smoothing-parameters/constant-factor 0.05")
          (ti-menu-load-string "/def/dynamic-mesh/controls/smoothing-parameters/max-iter 25")
          (if layering?
          (ti-menu-load-string (format #f "/def d-m c layering yes"))
            (ti-menu-load-string (format #f "/def d-m c layering no")))
          (if wb_ice_only_smoothing?
            (ti-menu-load-string (format #f "/def dm c remeshing? no"))
            (begin
              (ti-menu-load-string (format #f "/def dm c remeshing? yes"))
              (ti-menu-load-string (format #f "/def dm c r-p r-m yes yes yes no no")) 
            )
          )
        )
        (begin
          (ti-menu-load-string (format #f "/def dm c smoothing? yes"))
          (ti-menu-load-string (format #f "/def dm c s-p s-m diffusion"))
          (ti-menu-load-string (format #f "/def dm c s-p diffusion-coeff-function boundary-distance"))
          (ti-menu-load-string (format #f "/def dm c s-p d-c-p 1"))
          (if layering?
            (ti-menu-load-string (format #f "/def d-m c layering yes"))
            (ti-menu-load-string (format #f "/def d-m c layering no")))
          (if wb_ice_only_smoothing?
            (ti-menu-load-string (format #f "/def dm c remeshing? no"))
            (begin
              (ti-menu-load-string (format #f "/def dm c remeshing? yes"))
              (ti-menu-load-string (format #f "/def dm c r-p r-m yes yes yes no no")) 
            )
          )
        )
      )
      (if (= (length all_fluid_zones) 1)
        (ti-menu-load-string (format #f "/def d-m c layering no")))
    )
  )
)
; defines settings when user replace new topology with ICE topology
(set! wb-ice-kg-set-ICE-mesh-topology
  (lambda()  
    (format  "\n\n\t\t ___________ Changing to ICE mesh topology and defining dynamic settings _____________\t\n\n")
    ;(wb-ice-kg-define-smoothing-remeshing-parameters)
    (wb-ice-kg-define-ib-ob-interfaces)
    (wb-ice-kg-define-zone-motions (rpgetvar 'ice/setup-valve-list))
    (wb-ice-kg-create-valve-interfaces)
  )
)

(set! wb-ice-kg-define-ib-ob-interfaces
  (lambda ()
    (format  "\n\n\t\t ___________ Changing zone types to Interface for ib, ob bodies _____________\t\n\n")
    (let
      (
        (matching_interface #t)
        (matching_string "")
        (valve_list '())
      
      )
      (set! valve_list (wb-ice-get-valve-names))
      (for-each
        (lambda (valve_name)
          (if (and (thread-name->id (string-append "fluid-" valve_name "-ib")) (thread-name->id (string-append "fluid-" valve_name "-vlayer")))
            (begin
              (format  "\n\n\t\t ___________ Creating Grid Interfaces for ib and ob bodies_____________\t\n\n")
              (ti-menu-load-string (string-append  "/def/bc/zt intf-" valve_name "-ib-fluid-ib interface"))
              (ti-menu-load-string (string-append  "/def/bc/zt intf-" valve_name "-ib-fluid-ob-quad interface"))
              (ti-menu-load-string (string-append  "/def/bc/zt intf-" valve_name "-ib-fluid-ob-tri interface"))
              (ti-menu-load-string (string-append  "/def/bc/zt intf-" valve_name "-ob-fluid-vlayer wall"))
              (ti-menu-load-string (string-append  "/def/bc/zt intf-int-" valve_name "-ib-fluid-ib interface"))
              (ti-menu-load-string (string-append  "/def/bc/zt intf-int-" valve_name "-ib-fluid-port interface"))
              (ti-menu-load-string (string-append  "/def/bc/zt intf-int-" valve_name "-ob-fluid-port interface"))
              (ti-menu-load-string (string-append  "/def/bc/zt intf-int-" valve_name "-ob-fluid-vlayer interface"))
              (if matching_interface
                (define matching_string " no no yes")
                (define matching_string " no")
              )
              (ti-menu-load-string (string-append  "/def/gi/create intf-" valve_name " intf-" valve_name "-ib-fluid-ib () intf-" valve_name "-ib-fluid-ob-quad intf-" valve_name "-ib-fluid-ob-tri () " matching_string ))          
             
              (if matching_interface
                (define matching_string " no no no yes")
                (define matching_string " no")
              )
              (ti-menu-load-string (string-append  "/def/gi/create intf-int-" valve_name "-ib intf-int-" valve_name "-ib-fluid-ib () intf-int-" valve_name "-ib-fluid-port () " matching_string))
              (ti-menu-load-string (string-append  "/def/gi/create intf-int-" valve_name "-ob intf-int-" valve_name "-ob-fluid-port () intf-int-" valve_name "-ob-fluid-vlayer () " matching_string))
            )
          )
        ) valve_list
      )
    )
  )
)

(set! wb-ice-kg-define-zone-motions
  (lambda (setup-valve-list)
    (let
      (
        (ib_cell_height 1)
        (ob_cell_height 1)
        (smoothing-on #f)
        (min_scale 1)
        (max_scale 1)
        (ave_scale 1)
        (current_ca (ice-remainder (rpgetvar 'dynamesh/in-cyn/crank-angle) 720))
        (valve "")
        (profile "")
        (axis_x "")
        (axis_y "")
        (axis_z "")
        (origin_x "")
        (origin_y "")
        (origin_z "")
        (zone_name "")
        (radius "")
      )    
      (for-each 
        (lambda (valve_list)          
         (format "\n\n\t\t ___________ Setting Dynamic Mesh Zones for ~s _____________\t\n\n " (list-ref valve_list 1) )
          (if (and (thread-name->id (string-append "fluid-" (list-ref valve_list 1) "-ib")) (thread-name->id (string-append "fluid-" (list-ref valve_list 1) "-vlayer")))
            (begin
              (set! valve (list-ref valve_list 1))
              (set! profile (list-ref valve_list 2))
              (set! axis_x (list-ref (list-ref valve_list 6) 0))
              (set! axis_y (list-ref (list-ref valve_list 6) 1))
              (set! axis_z (list-ref (list-ref valve_list 6) 2))
              (set! ave_scale (+ (* 0.5 (car (%get-min-max-length-scale-on-zone (thread-name->id  (string-append valve "-ch")) #f))) (* 0.5 (car (cdr (%get-min-max-length-scale-on-zone (thread-name->id  (string-append valve "-ch")) #f))))))
              (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create fluid-" valve "-vlayer rigid-body " profile " " (number->string axis_x) " " (number->string axis_y) " " (number->string axis_z)))
              (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create fluid-" valve "-ib rigid-body " profile " " (number->string axis_x) " " (number->string axis_y) " " (number->string axis_z)))
              (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create " valve "-ib rigid-body " profile " no " (number->string axis_x) " " (number->string axis_y) " " (number->string axis_z) " ,, 0"))
              (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create " valve "-ob rigid-body " profile " no " (number->string axis_x) " " (number->string axis_y) " " (number->string axis_z) " ,, 0"))
              (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create " valve "-ch rigid-body " profile " no " (number->string axis_x) " " (number->string axis_y) " " (number->string axis_z) " ,, " (number->string ave_scale)))
              
              (set! zone_name (string-append "intf-int-" valve "-ib-fluid-ib"))
              (set! ib_cell_height  (+ (* 0.5 (car (%get-min-max-length-scale-on-zone (thread-name->id  zone_name) #f))) (* 0.5 (car (cdr (%get-min-max-length-scale-on-zone (thread-name->id zone_name) #f))))))          
              (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create intf-int-" (list-ref valve_list 1) "-ib-fluid-ib stationary " (string-append "fluid-" valve  "-ib") " ," (number->string ib_cell_height)))
              
              (set! zone_name (string-append "intf-int-" valve "-ob-fluid-vlayer"))
              (set! ob_cell_height  (+ (* 0.25 (car (%get-min-max-length-scale-on-zone (thread-name->id  zone_name) #f))) (* 0.25 (car (cdr (%get-min-max-length-scale-on-zone (thread-name->id  zone_name) #f))))))
          
              (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create " zone_name " stationary " (string-append "fluid-" valve  "-vlayer") " ," (number->string ob_cell_height)))
              (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create " valve "-seat stationary ,, " (number->string ob_cell_height)))
              (if (thread-name->id (string-append (symbol->string valve) "-stem"))
                (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create " valve "-stem stationary , , ," )))
            )
          )
          (ic-all-dz-update-cg-position) ;this is to update all the values in the dynamic mesh zones 
        ) setup-valve-list
      )
    )
  )
)
(set! wb-ice-kg-create-valve-interfaces
  (lambda()
    (let
      (
        (valve_list (rpgetvar 'ice/setup-valve-list))
        (current_ca (ice-remainder (rpgetvar 'dynamesh/in-cyn/crank-angle) 720))
        (open_angle 0)
        (close_angle 0)
        (zone1 "")
        (zone2 "")
        (zone3 "")
        (zone4 "")
      )
      (for-each 
        (lambda (valve)
          (set! open_angle (list-ref valve 3))
          (set! close_angle (list-ref valve 4))
          (set! zone1 (string-append "intf-" (list-ref valve 1) "-ob-fluid-ch"))
          (set! zone2 (string-append "intf-" (list-ref valve 1) "-ob-fluid-vlayer"))
          (set! zone3 (string-append "intf-" (list-ref valve 1) "-port-fluid-ch"))
          (set! zone4 (string-append "intf-" (list-ref valve 1) "-ch-fluid-port"))
          (if (and (> current_ca open_angle) (< current_ca close_angle) (thread-name->id zone1) (thread-name->id zone2))
            (wb-ice-define-valve-open-event  (list-ref valve 1) zone1 zone2 open_angle #t))          
          (if (and (> current_ca open_angle) (< current_ca close_angle) 
                  (not (thread-name->id zone1)) (not (thread-name->id zone2)) 
                  (thread-name->id zone3)  (thread-name->id zone4))
            (wb-ice-define-valve-open-event  (list-ref valve 1) zone3 zone4 open_angle #t)
          )
        ) valve_list
      )
    )
  )
)
(set! wb-ice-string-split-by-delimiter
  (lambda (str delimiter)
    (let 
      (
        (output_list '())
        (str1 "")      
      )      
      (do ((i 0 (+ i 1))) ((= i (string-length str)))
        (if (string-ci=? (make-string 1 (string-ref str i)) delimiter)
          (begin 
            (set! output_list (append output_list (list str1)))
            (set! str1 "")
          )
          (set! str1 (string-append str1 (make-string 1 (string-ref str i))))
        )      
      ) output_list
    )
  )
)
(set! wb-ice-changeBC
  (lambda (zone-name BC-type)
    (if (thread-name->id zone-name) 
      (if (not (equal? (symbol->string (zone-type (get-thread zone-name))) bc-type))
        (ti-menu-load-string (string-append  "/def/b-c/z-t " zone-name " " bc-type)))
      (format "\n  Warning: no face zone ~a in this mesh\n" zone-name))
    
	)
)
(set! wb-ice-start-smoothing-at-valve-open
  (lambda (valve_no)
    (let 
      (
        (valve_list '())
        (zone_id "")
        (adj_cell_zone "")
        (cell_height 0)
        (valve_id "")
        (min_len_scale 0)
        (max_len_scale 0)
      )
      (if  (rp-var-object 'ice/setup-valve-list)
        (if (not (null? (rpgetvar  'ice/setup-valve-list)))
          (set! valve_list (list-ref (rpgetvar 'ice/setup-valve-list) (- valve_no 1) ))))
      (if (not (null? valve_list))
        (begin
          (set! valve_id (list-ref valve_list 1))
          (set! zone_id (thread-name->id (string-append "intf-" valve_id "-ob-fluid-vlayer")))
          (if zone_id
            (begin
              (set! min_len_scale (* 0.4 (caddr (%get-min-max-length-scale-on-zone zone_id #f))))
              (set! max_len_scale  (* 1.4 (caddr (%get-min-max-length-scale-on-zone zone_id #f))))
              (ti-menu-load-string (format #f "/def d-m z create ~s deforming , , , , no ~s ~s 0.6 \n" zone_id  min_len_scale  max_len_scale ))
            )
            (format "\n Smoothing event for ~a zone not set. Check the zone name. \n" (thread-id->name zone_id) )
          )
          (set! zone_id (thread-name->id  (string-append "intf-" valve_id "-ib-fluid-ob-quad")))
          (if zone_id
            (begin
              (set! min_len_scale (* 0.4 (caddr (%get-min-max-length-scale-on-zone zone_id #f))))
              (set! max_len_scale  (* 1.4 (caddr (%get-min-max-length-scale-on-zone zone_id #f))))
              (ti-menu-load-string (format #f "/def d-m z create ~s deforming , , , , no ~s ~s 0.6 \n" zone_id  min_len_scale  max_len_scale ))
            )
            (format "\n Smoothing event for ~a zone not set. Check the zone name. \n" (thread-id->name zone_id) )
          )
          (set! zone_id (thread-name->id  (string-append "intf-int-" valve_id "-ob-fluid-vlayer")))
          (if zone_id
            (begin
              (set! adj_cell_zone (string->symbol (string-append "fluid-" valve_id "-vlayer")))
              (set! cell_height 0)
              (ti-menu-load-string (format #f "/def d-m z create ~s stationary ~s , ~s \n" zone_id  adj_cell_zone cell_height))
            )
            (format "\n Smoothing event for ~a zone not set. Check the zone name. \n" (thread-id->name zone_id) )
          )
          (set! zone_id (thread-name->id (string-append valve_id "-seat")))
          (if zone_id
            (begin
              (set! adj_cell_zone  (string->symbol (string-append "fluid-" valve_id "-vlayer")))
              (set! cell_height 0)
              (ti-menu-load-string (format #f "/def d-m z create ~s stationary ~s , ~s \n" zone_id  adj_cell_zone cell_height))
            )
            (format "\n Smoothing event for ~a zone not set. Check the zone name. \n" (thread-id->name zone_id) )
          )

          (set! zone_id (thread-name->id (string-append "fluid-" valve_id "-vlayer")))
          (if zone_id
            (ti-menu-load-string (format #f "define dynamic-mesh zones delete ~s \n" zone_id ))
            (format "\n Smoothing event for ~a zone not set. Check the zone name. \n" (thread-id->name zone_id) )
          )
        )
      )
    )
  )
)

(set! wb-ice-stop-smoothing-at-valve-open
  (lambda (valve_no vlayer-mesh-size)
    (let 
      (
        (valve_list '())
        (zone_id "")
        (adj_cell_zone "")
        (cell_height 0)
        (valve_id "")
        (valve_profile "")
        (valve_axis '())
      )
      (if  (rp-var-object 'ice/setup-valve-list)
        (if (not (null? (rpgetvar  'ice/setup-valve-list)))
          (set! valve_list (list-ref (rpgetvar 'ice/setup-valve-list) (- valve_no 1) ))))
      (if (not (null? valve_list))
        (begin
          (set! valve_id (list-ref valve_list 1))
          (set! zone_id (thread-name->id (string-append "intf-" valve_id "-ob-fluid-vlayer")))
          (if zone_id
            (ti-menu-load-string (format #f "define dynamic-mesh zones delete ~s \n" zone_id ))
            (format "\n Smoothing event for ~a zone not set. Check the zone name. \n" (thread-id->name zone_id) )
          )

          (set! zone_id (thread-name->id (string-append "intf-" valve_id "-ib-fluid-ob-quad")))
          (if zone_id
            (ti-menu-load-string (format #f "define dynamic-mesh zones delete ~s \n" zone_id ))
            (format "\n Smoothing event for ~a zone not set. Check the zone name. \n" (thread-id->name zone_id) )
          )

          (set! zone_id (thread-name->id (string-append "fluid-" valve_id "-vlayer")))
          (if zone_id
            (begin
              (set! valve_profile (list-ref valve_list 2))
              (set! valve_axis (list-ref valve_list 6 ))
              (ti-menu-load-string (format #f "/def d-m z create ~s rigid-body  ~s ~s ~s  ~s \n" zone_id  valve_profile (car valve_axis)  (cadr valve_axis)  (caddr valve_axis) ))
            )
            (format "\n Smoothing event for ~a zone not set. Check the zone name. \n" (thread-id->name zone_id) )
          )
          (set! zone_id (thread-name->id (string-append "intf-int-" valve_id "-ob-fluid-vlayer")))
          (if zone_id
            (begin
              (set! adj_cell_zone (string->symbol (string-append "fluid-" valve_id "-vlayer")))
              (set! cell_height vlayer-mesh-size)
              (ti-menu-load-string (format #f "/def d-m z create ~s stationary ~s , ~s \n" zone_id  adj_cell_zone cell_height))
            )
            (format "\n Smoothing event for ~a zone not set. Check the zone name. \n" (thread-id->name zone_id) )
          )
          (set! zone_id (thread-name->id (string-append valve_id "-seat")))
          (if zone_id
            (begin
              (set! adj_cell_zone (string->symbol (string-append "fluid-" valve_id "-vlayer")))
              (ti-menu-load-string (format #f "/def d-m z create ~s stationary ~s , ~s \n" zone_id  adj_cell_zone cell_height))
            )
            (format "\n Smoothing event for ~a zone not set. Check the zone name. \n" (thread-id->name zone_id) )
          )
        )
      )
    )
  )
)
  
(set! wb-ice-start-smoothing-before-valve-close
  (lambda (valve_no)
    (let 
      (
        (valve_list '())
        (zone_id "")
        (adj_cell_zone "")
        (cell_height 0)
        (valve_id "")
        (min_len_scale 0)
        (max_len_scale 0)
      )
      (if  (rp-var-object 'ice/setup-valve-list)
        (if (not (null? (rpgetvar  'ice/setup-valve-list)))
          (set! valve_list (list-ref (rpgetvar 'ice/setup-valve-list) (- valve_no 1) ))))
      (if (not (null? valve_list))
        (begin
          (set! valve_id (list-ref valve_list 1))
          (set! zone_id (thread-name->id (string-append "intf-" valve_id "-ob-fluid-vlayer")))
          (if zone_id
            (begin
              (set! min_len_scale (* 0.4 (caddr (%get-min-max-length-scale-on-zone zone_id #f))))
              (set! max_len_scale  (* 1.4 (caddr (%get-min-max-length-scale-on-zone zone_id #f))))
              (ti-menu-load-string (format #f "/def d-m z create ~s deforming , , , , no ~s ~s 0.6 \n" zone_id  min_len_scale  max_len_scale ))
            )
            (format "\n Smoothing event for ~a zone not set. Check the zone name. \n" (thread-id->name zone_id) )
          )
          (set! zone_id (thread-name->id (string-append "intf-" valve_id "-ib-fluid-ob-quad")))
          (if zone_id
            (begin
              (set! min_len_scale (* 0.4 (caddr (%get-min-max-length-scale-on-zone zone_id #f))))
              (set! max_len_scale  (* 1.4 (caddr (%get-min-max-length-scale-on-zone zone_id #f))))
              (ti-menu-load-string (format #f "/def d-m z create ~s deforming , , , , no ~s ~s 0.6 \n" zone_id  min_len_scale  max_len_scale ))
            )
            (format "\n Smoothing event for ~a zone not set. Check the zone name. \n" (thread-id->name zone_id) )
          )
          (set! zone_id (thread-name->id (string-append "intf-int-" valve_id "-ob-fluid-vlayer")))
          (if zone_id
            (begin
              (set! adj_cell_zone (string->symbol (string-append "fluid-" valve_id "-vlayer")))
              (set! cell_height 0)
              (ti-menu-load-string (format #f "/def d-m z create ~s stationary ~s , ~s \n" zone_id  adj_cell_zone cell_height))
            )
            (format "\n Smoothing event for ~a zone not set. Check the zone name. \n" (thread-id->name zone_id) )
          )
          (set! zone_id (thread-name->id (string-append valve_id "-seat")))
          (if zone_id
            (begin
              (set! adj_cell_zone (string->symbol (string-append "fluid-" valve_id "-vlayer")))
              (set! cell_height 0)
              (ti-menu-load-string (format #f "/def d-m z create ~s stationary ~s , ~s \n" zone_id  adj_cell_zone cell_height))
            )
            (format "\n Smoothing event for ~a zone not set. Check the zone name. \n" (thread-id->name zone_id) )
          )
          (set! zone_id (thread-name->id (string-append "fluid-" valve_id "-vlayer")))
          (if zone_id
            (ti-menu-load-string (format #f "define dynamic-mesh zones delete ~s \n" zone_id ))
            (format "\n Smoothing event for ~a zone not set. Check the zone name. \n" (thread-id->name zone_id) )
          )
        )
      )
    )
  )
)

(set! wb-ice-kg-register-monitors-before-mesh-replace
  (lambda ()
    (if (and (rp-var-object 'ice/monitor-volume) (rp-var-object 'ice/monitor-surfaces))
      (begin      
        (rpsetvar 'ice/monitor-volume '())
        (rpsetvar 'ice/monitor-surfaces '())
        (for-each 
          (lambda (mon)  
            (let 
              ((zones  
                (map thread-name 
                  (map get-thread (cdr (assoc 'zones mon) )))
              ))
              (rpsetvar 'ice/monitor-volume (list-add (rpgetvar 'ice/monitor-volume) (list-add mon (cons 'ice-zones zones))))
            )
          )(rpgetvar 'monitor/volume)
        )
        (for-each 
          (lambda (mon)  
            (let 
              ((surfaces  
                (map surface-id->name  
                   (cdr (assoc 'surfaces mon) ))
              ))
              (rpsetvar 'ice/monitor-surfaces (list-add (rpgetvar 'ice/monitor-surfaces) (list-add mon (cons 'ice-surfaces surfaces))))
            )
          )(rpgetvar 'monitor/surfaces)
        )
      )
    )
  )
)

(set! wb-ice-update-monitor-zones
  (lambda (mon field initial_zone_list)
    (let ((zones (assq field (cdr mon))))
      (if zones
        (set-cdr! zones initial_zone_list)
        (set-cdr! mon (cons (cons field initial_zone_list)
                  (cdr mon)))
      )
    )
  )
)
(set! wb-ice-kg-update-volume-monitors
  (lambda ()
    (let 
      ((monitor_list '()))
      (if (and (rp-var-object 'monitor/volume) (rp-var-object 'ice/monitor-volume))
        (begin
          (format "\nUpdating volume monitors after mesh replace\n")
          (for-each 
            (lambda (mon ice_mon)
              (let ((initial_zone_list '()))
                (for-each 
                  (lambda (x) 
                    (if (thread-name->id x) 
                      (set! initial_zone_list (list-add initial_zone_list (thread-name->id x))))
                  )(cdr (assoc 'ice-zones ice_mon))
                )
                (if (not (null? initial_zone_list))
                  (begin
                    (if (and (member (thread-name->id "fluid-ch") initial_zone_list)
                                    (not (member (thread-name->id "fluid-layer-cylinder") initial_zone_list))
                                    (not (member (thread-name->id "fluid-piston") initial_zone_list))
                                    (member 'fluid-layer-cylinder (wb-ice-get-new-fluid-zones-after-replace-mesh))
                                    (member 'fluid-piston (wb-ice-get-new-fluid-zones-after-replace-mesh)))
                      (if (and (thread-name->id "fluid-layer-cylinder") (thread-name->id "fluid-piston"))
                        (set! initial_zone_list (append initial_zone_list (map thread-name->id '("fluid-layer-cylinder" "fluid-piston")))))
                    )
                    ;(pp initial_zone_list)
                    (wb-ice-update-monitor-zones mon 'zones initial_zone_list)
                    ;(wb-ice-update-monitor-zones mon 'unit '())
                    (set! monitor_list (list-add monitor_list mon))
                  )
                  (format "\n\n Deleting volume monitor \"~a\" after mesh-replace \n Zones ~a are absent in new mesh\n" (car ice_mon) (cdr (assoc 'ice-zones ice_mon)))
                )
              )
            )(rpgetvar 'monitor/volume) (rpgetvar 'ice/monitor-volume) 
          )
        )
      )
      (ti-menu-load-string (format #f "solve mon volume list-monitor"))
      (ti-menu-load-string (format #f "solve mon volume clear-monitor"))
      (rpsetvar 'monitor/volume monitor_list)
    )
  )
)

(set! wb-ice-get-new-fluid-zones-after-replace-mesh
  (lambda ()
    (let 
      ( 
        (new_fluid_names '())        
        (final_fluids '())        
      )
      (set! final_fluids (map thread-name (sort-threads-by-name (get-threads-of-type 'fluid))))
      (for-each 
        (lambda (zone)
          (if (not (member zone (rpgetvar 'ice/fluid-list)))
            (set! new_fluid_names (append  new_fluid_names (list zone))))
        ) final_fluids
      )
      new_fluid_names
    )
  )
)
(set! wb-ice-get-new-surface-zones-after-replace-mesh
  (lambda ()
    (let 
      ( 
        (final_walls '())
        (new_walls_names '())        
      )
      (set! final_walls (map thread-name (sort-threads-by-name (get-threads-of-type 'wall))))
      (for-each 
        (lambda (zone)
          (if (not (member zone (rpgetvar 'ice/wall-list)))
            (set! new_walls_names (append  new_walls_names (list zone))))
        ) final_walls
      )
      new_walls_names
    )
  )
)
(set! wb-ice-query-if-layer-cylinder-layering
  (lambda ()
    (let
      ((layer_cyl_hex_mesh? #f))
      (if (and (thread-name->id "fluid-layer-cylinder") (thread-name->id "int-piston"))
        (if (%zone-is-adjacent-to-hex-or-prism-cells (thread-name->id "int-piston"))
          (set! layer_cyl_hex_mesh? #t) ))         
      layer_cyl_hex_mesh?
    )
  )
)
(set! wb-ice-get-deforming-cell-thread-ids
  (lambda ()
    (let 
      (
        (deforming_cell_thread_ids  '())
      )
      (for-each
        (lambda (dz) 
          (let 
            (
              (tid (car dz))
              (type (get-dz-attr dz 'type))
              (deforming 3)
            )
            (if (and (= type deforming) (not (member (car (inquire-adjacent-threads tid)) deforming_cell_thread_ids)))
              (set! deforming_cell_thread_ids (append deforming_cell_thread_ids (list (car (inquire-adjacent-threads tid))))) )
          )
        )(dynamic-thread-list)
      ) deforming_cell_thread_ids
    )
  )
)
(set! wb-ice-remesh-cell-zones
  (lambda (deforming_cell_thread_ids max_cell_skewness)
    (let 
      (
        ;(max_cell_skewness 0.965)
        (max_skewed_cell_zone_ids '())
        (include-dynamic-face-threads? #t)
      )
      (for-each
        (lambda (id)
          (let ((t_max_skew (%get-max-skewness-on-zone id #f)))
            (if (and (cell-thread? id) (> t_max_skew max_cell_skewness))
              (set! max_skewed_cell_zone_ids (append max_skewed_cell_zone_ids (list id))))
          )
        )deforming_cell_thread_ids
      )
      (if (not (null? max_skewed_cell_zone_ids))
        (begin
          (format "\n\n\t\t___________________________Automatic cell zone remeshing  ___________________________\n\n\t\t" )
          (format " \n Skewness > ~a found in cell zones ~a " max_cell_skewness (map thread-id->name max_skewed_cell_zone_ids))
          (wb-ice-kg-remshing-settings-for-deforming-zones #t)
          (remesh-local-cells)
          (wb-ice-kg-remshing-settings-for-deforming-zones #f)
        )
        (format " \n Max skewness is under ~a so no remeshing is called" max_cell_skewness)
      )
    )
  )
)

(set! wb-ice-get-port-zones-from-valve-name
  (lambda (compare_string)
    (let*
      (
        (all_zones (map thread-name (get-threads-of-type 'fluid)))
        (port_zones '())
        (valve_name_prefix (substring compare_string 0 (- (string-length compare_string) 1)))
        (port_no (substring compare_string (- (string-length compare_string) 1) (string-length compare_string)))
        (port_string "")
      )
      (set! port_string (string-append "-" port_no "-" ))
      (for-each
        (lambda (zone)
          (set! zone (symbol->string zone))
            (if (and (not (substring? "fluid-ch" zone)) (substring? valve_name_prefix zone) (substring? port_string zone) (substring? "-port" zone))
              (set! port_zones (append port_zones(list zone)))
            )
        ) all_zones 
      )port_zones
    )
  )
)

(set! wb-ice-kg-define-get-min-required-zones-for-mesh-topo-2
  (lambda (port_zone_name vlayer_zone_name)
    (let 
      (
        (min_required_zones '())
        (valve "")
        (valve_names (wb-ice-get-valve-names-from-stem))
        (name_list '())
      )
      (set! name_list (wb-ice-string-split-by-delimiter (symbol->string vlayer_zone_name) "-"))
      (if (>= (length name_list) 2)
        (set! valve (symbol->string (cadr name_list))))
      (if (member valve valve_names)
        (begin
          (set! min_required_zones (append min_required_zones (list (string-append valve "-seat")
                                                                    (string-append "intf-" valve "-vlayer-fluid-port")
                                                                    (string-append "intf-" valve "-vlayer-fluid-vlayer")
                                                                    (string-append valve "-ib")
                                                                    (string-append valve "-ob")
                                                                    (string-append valve "-ch")
                                                                    (string-append "intf-" valve "-ob-fluid-vlayer")
                                                                    (string-append "intf-" valve "-ob-fluid-ch"))))
        )
        (format "\n\n\t\t ___________  vlayer cell zone name is not in proper format. cell zone name = ~a ; \t valve name = ~a ___________ \t\n\n ~s\n" vlayer_zone_name valve )
      )
      min_required_zones
    )
  )
)
(set! wb-ice-kg-define-mesh-interfaces-for-mesh-topology-2
  (lambda (vlayer_zone_name)
    (let 
      (
        (valve "")
        (valve_names (wb-ice-get-valve-names-from-ch))
        (name_list '())
        (zone_name "")
        (ave_scale 0)
        (min_scale 0)
        (max_scale 0)
        (matching? #t)
        (matching_string "")
        (smoothing_string (wb-ice-kg-get-smoothing-string))
      )
      (if matching?
        (define matching_string " no no no yes")
        (define matching_string " no")
      )
      (set! name_list (wb-ice-string-split-by-delimiter (symbol->string vlayer_zone_name) "-"))
      (if (>= (length name_list) 2)
        (set! valve (symbol->string (cadr name_list))))
      (if (member valve valve_names)
        (begin
          (if (thread-name->id (string-append (symbol->string valve) "-stem"))
            (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create " valve "-stem stationary , , ," )))
          (set! zone_name (string-append "intf-" valve "-vlayer-fluid-port"))   
          (if (thread-name->id zone_name)
            (begin
              (set! ave_scale (caddr  (%get-min-max-length-scale-on-zone (thread-name->id  zone_name) #f)))
              (set! min_scale (* 0.4 ave_scale))
              (set! max_scale (* 1.4 ave_scale))
              (ti-menu-load-string (string-append  "\n /define/dynamic-mesh/zones/create " zone_name " deforming faceted "  smoothing_string " " (number->string min_scale) " " (number->string max_scale) " 0.6"))
            )
            (format "\n\n  Warning: no face zone ~a in replacement mesh \n\n" zone_name)
          )
          (let
            (
              (zone1_name (string-append "intf-" valve "-vlayer-fluid-port"))
              (zone2_name (string-append "intf-" valve "-port-fluid-vlayer") )
              (intf_name (string-append "intf-" valve "-vlayer"))
            )
            (wb-ice-changeBC zone1_name "interface")
            (wb-ice-changeBC zone2_name "interface")
            (format  "\n\n\t\t ___________ Creating Grid Interface ~a_____________\t\n\n" intf_name)
            (if (not (assoc (string->symbol intf_name) (rpgetvar 'sliding-interfaces)))
              (ti-menu-load-string (string-append "define mi create " (symbol->string intf_name) " " zone1_name " () " zone2_name " () " matching_string ))
              (format "\n\n Info: Interface ~a already exist so could not create another with the same name \n " intf_name)
            )
          )
         
        )
      )
      (ic-all-dz-update-cg-position)
    )
  )
)

(set! wb-ice-kg-define-zone-motions-new-topology
  (lambda ()
    (let
      (
        (ib_cell_height 1)
        (ob_cell_height 1)
        (smoothing-on #f)
        (min_scale 1)
        (max_scale 1)
        (ave_scale 1)
        (current_ca (ice-remainder (rpgetvar 'dynamesh/in-cyn/crank-angle) 720))
        (valve "")
        (profile "")
        (axis_x "")
        (axis_y "")
        (axis_z "")
        (origin_x "")
        (origin_y "")
        (origin_z "")
        (zone_name "")
        (radius "")
        (smoothing_type (if wb_ice_only_smoothing?  "diffusion" "spring"))
        (smoothing_string "")
      )    
      (for-each 
        (lambda (valve_list)          
          (format "\n\n\t\t ___________ Setting Dynamic Mesh Zones for ~s _____________\t\n\n " (list-ref valve_list 1) )
          (set! valve (list-ref valve_list 1))
          (set! profile (list-ref valve_list 2))
          (set! axis_x (list-ref (list-ref valve_list 6) 0))
          (set! axis_y (list-ref (list-ref valve_list 6) 1))
          (set! axis_z (list-ref (list-ref valve_list 6) 2))
          (if (thread-name->id (string-append "fluid-" (list-ref valve_list 1) "-vlayer"))
            (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create fluid-" valve "-vlayer rigid-body " profile " " (number->string axis_x) " " (number->string axis_y) " " (number->string axis_z))))
          (if (thread-name->id (string-append "fluid-" (list-ref valve_list 1) "-ib"))
            (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create fluid-" valve "-ib rigid-body " profile " " (number->string axis_x) " " (number->string axis_y) " " (number->string axis_z))))
          (if (thread-name->id (string-append valve "-ib"))
            (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create " valve "-ib rigid-body " profile " no " (number->string axis_x) " " (number->string axis_y) " " (number->string axis_z) " ,, 0")))
          (if (thread-name->id (string-append valve "-ob"))
            (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create " valve "-ob rigid-body " profile " no " (number->string axis_x) " " (number->string axis_y) " " (number->string axis_z) " ,, 0")))
          (if (thread-name->id (string-append valve "-ch"))
            (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create " valve "-ch rigid-body " profile " no " (number->string axis_x) " " (number->string axis_y) " " (number->string axis_z) " ,,," )))
          
          (set! zone_name (string-append valve "-seat"))
          (if (thread-name->id (string-append valve "-seat"))
            (begin
              (set! ob_cell_height  (+ (* 0.25 (car (%get-min-max-length-scale-on-zone (thread-name->id  zone_name) #f))) (* 0.25 (car (cdr (%get-min-max-length-scale-on-zone (thread-name->id  zone_name) #f))))))
              (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create " valve "-seat stationary ,, " (number->string ob_cell_height)))
            )
          )
           
          (set! zone_name (string-append "intf-int-" valve "-ib-fluid-ib"))
          (if (thread-name->id zone_name)
            (begin
              (set! ib_cell_height  (+ (* 0.5 (car (%get-min-max-length-scale-on-zone (thread-name->id  zone_name) #f))) (* 0.5 (car (cdr (%get-min-max-length-scale-on-zone (thread-name->id zone_name) #f))))))          
              (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create intf-int-" (list-ref valve_list 1) "-ib-fluid-ib stationary " (string-append "fluid-" valve  "-ib") " ," (number->string ib_cell_height)))
            )
          )
          
          (set! zone_name (string-append "intf-int-" valve "-ob-fluid-vlayer"))
          (if (thread-name->id zone_name)
            (begin
              (set! ob_cell_height  (+ (* 0.25 (car (%get-min-max-length-scale-on-zone (thread-name->id  zone_name) #f))) (* 0.25 (car (cdr (%get-min-max-length-scale-on-zone (thread-name->id  zone_name) #f))))))
      
              (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create " zone_name " stationary " (string-append "fluid-" valve  "-vlayer") " ," (number->string ob_cell_height)))
            )
          )
          (set! zone_name (string-append valve "-stem"))
          (if (thread-name->id zone_name)
            (if (thread-name->id (string-append "fluid-" valve "-ib"))
              (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create " valve "-stem stationary , , ," ))
              (begin
                
                (set! ave_scale (caddr  (%get-min-max-length-scale-on-zone (thread-name->id  zone_name) #f)))
                (set! min_scale (* 0.4 ave_scale))
                (set! max_scale (* 1.4 ave_scale))
                (if (string-ci=? smoothing_type "diffusion")
                  (if wb_ice_only_smoothing?
                    (set! smoothing_string " no yes no ")
                    (set! smoothing_string " no yes yes no no "))
                  (set! smoothing_string " no yes no no "))
                (ti-menu-load-string (string-append  "/define/d-m zones c " zone_name " " " deforming faceted " smoothing_string " " (number->string min_scale) " "  (number->string max_scale) " 0.6"))
              )
            )
          )
        ) (rpgetvar 'ice/setup-valve-list)
      )
    )
  )
)

(set! wb-ice-kg-query-if-layering-possible
  (lambda ()
    (let
      (   
        (valve "")
        (layering? #f)
      )
      (if (wb-ice-query-if-layer-cylinder-layering)
        (set! layering? #t))
      (if (not layering?)
        (for-each 
          (lambda (valve_list)
            (if (not layering?)
              (begin
                (set! valve (list-ref valve_list 1))
                (if (thread-name->id (string-append "fluid-" (list-ref valve_list 1) "-vlayer"))
                  (set! layering? (wb-ice-query-if-vlayer-layering (string-append "fluid-" (list-ref valve_list 1) "-vlayer"))))
                (if (thread-name->id  (string-append "fluid-" (list-ref valve_list 1) "-ib"))
                  (set! layering? (wb-ice-query-if-ib-layering (string-append "fluid-" (list-ref valve_list 1) "-ib"))))
              )
            )
          )(rpgetvar 'ice/setup-valve-list)
        )
      ) layering?
    )
  )
)
(set! wb-ice-kg-query-if-it-is-ice-topology
  (lambda()  
    (let
      (
        (valve_name '())
        (zone_name "")
        (is_ice_mesh_topology? #f)
      )
      (for-each 
        (lambda (valve_value)
          (set! valve_name (list-ref valve_value 1))
          (set! zone_name (string-append "intf-int-" valve_name "-ob-fluid-vlayer"))
          (if (thread-name->id zone_name) 
            (if (not (assoc (thread-name->id zone_name) (dynamic-thread-list))) 
              (set! is_ice_mesh_topology? #t)))
        ) (rpgetvar 'ice/setup-valve-list)
      ) is_ice_mesh_topology?
    )
  )
)
(set! wb-ice-kg-remshing-settings-for-deforming-zones
  (lambda(apply_remesh_settings?)
    (if apply_remesh_settings?
      (format  "\n\n\t\t_____________ Enabling remeshing on deforming zones due to high skewness cells___________\t\n\n")  
      (format  "\n\n\t\t_____________ Disabling remeshing on deforming zones___________\t\n\n")  
    )
    (let
      (
       (min_scale 0)
       (max_scale 0)
       (ave_scale 0)
       (zone_name "")
       (zone_dyn_mesh_settings '())
       (origin '())
       (axis '())
       (radius "")
       (smoothing_string "")
       (valve "")
      )
      (if apply_remesh_settings?
        (set! smoothing_string "no yes yes yes yes")
        (set! smoothing_string "no yes no")
      )
      ;;making global remeshing on before calling fluent's (remesh-local-cells)
			(ti-menu-load-string (format #f "/def dyn-mesh controls remeshing? yes"))
			(ti-menu-load-string (format #f "/def dyn-mesh controls remeshing-param  remeshing-methods yes yes yes no no"))
      ;;cyl-tri deforming zone for piston-type1 and piston-type3 engines
      (if (thread-name->id  "cyl-tri")
        (begin
          (set! zone_name "cyl-tri")
          
          (set! zone_dyn_mesh_settings (assoc (thread-name->id zone_name) (dynamic-thread-list)))
          (set! origin (cadr (assoc 'geom-origin zone_dyn_mesh_settings)))
          (set! axis (cadr (assoc 'geom-axis zone_dyn_mesh_settings)))
          (set! radius (cadr (assoc 'radius zone_dyn_mesh_settings)))
          (format  "\n\n\t\t_____________ Defining remeshing parameters for cyl-tri ___________\t\n\n")  
          (set! ave_scale (+ (* 0.5 (car (%get-min-max-length-scale-on-zone (thread-name->id  "cyl-tri") #f))) (* 0.5 (cadr (%get-min-max-length-scale-on-zone (thread-name->id  "cyl-tri") #f)))))
          (set! min_scale (* 0.5 ave_scale))
          (set! max_scale (* 1.5 ave_scale))
          (ti-menu-load-string (string-append  "/def d-m z c " zone_name " deforming cylinder " (number->string radius) " " (number->string (car origin)) " " (number->string (cadr origin)) " " (number->string (caddr origin)) " " (number->string (car axis)) " " (number->string (cadr axis)) " " (number->string (caddr axis)) " " smoothing_string " " (number->string min_scale) " " (number->string max_scale) " 0.6"))
        )
      )
      (if (thread-name->id  "symm-cyl-tri")
        (begin
          (set! zone_name "symm-cyl-tri")
          (set! zone_dyn_mesh_settings (assoc (thread-name->id zone_name) (dynamic-thread-list)))
          (set! origin (cadr (assoc 'geom-origin zone_dyn_mesh_settings)))
          (set! axis (cadr (assoc 'geom-axis zone_dyn_mesh_settings)))
          
          (format  "\n\n\t\t_____________ Defining remeshing parameters for symm-cyl-tri___________\t\n\n")  
          (set! ave_scale (caddr  (%get-min-max-length-scale-on-zone (thread-name->id  (string-append "symm-cyl-tri")) #f)))
          (set! min_scale (* 0.4 ave_scale))
          (set! max_scale (* 1.4 ave_scale))
          (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create symm-cyl-tri deforming plane " (number->string (car origin)) " " (number->string (cadr origin)) " " (number->string (caddr origin)) " " (number->string (car axis)) " "  (number->string (cadr axis)) " " (number->string (caddr axis)) " " smoothing_string " " (number->string min_scale) " " (number->string max_scale) " 0.65"))
        )
      )
      (for-each 
        (lambda (valve_list)          
          (set! valve (list-ref valve_list 1))
          (set! zone_name (string-append valve "-stem"))
          (if (thread-name->id zone_name)
            (if (thread-name->id (string-append "fluid-" valve "-ib"))
              (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create " valve "-stem stationary , , ," ))
              (begin
                (format  "\n\n\t\t_____________ set deforming remeshing parameters for zone ~a ___________\t\n\n" zone_name )
                (set! ave_scale (caddr  (%get-min-max-length-scale-on-zone (thread-name->id  zone_name) #f)))
                (set! min_scale (* 0.4 ave_scale))
                (set! max_scale (* 1.4 ave_scale))
                (ti-menu-load-string (string-append  "/define/d-m zones c " zone_name " " " deforming faceted " smoothing_string " " (number->string min_scale) " "  (number->string max_scale) " 0.6"))
              )
            )
          )
          (for-each 
            (lambda (zone_name)
              (if (thread-name->id zone_name)
                (begin                   
                  (set! ave_scale (caddr  (%get-min-max-length-scale-on-zone (thread-name->id  zone_name) #f)))
                  (set! min_scale (* 0.4 ave_scale))
                  (set! max_scale (* 1.4 ave_scale))
                  (format  "\n\n\t\t_____________ set deforming remeshing parameters for zone ~a ___________\t\n\n" zone_name )
                  (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create " zone_name " deforming cylinder " (number->string (list-ref valve_list 5)) " " (number->string (list-ref (list-ref valve_list 7) 0)) " " (number->string (list-ref (list-ref valve_list 7) 1)) " " (number->string (list-ref (list-ref valve_list 7) 2)) " " (number->string (list-ref (list-ref valve_list 6) 0)) " " (number->string (list-ref (list-ref valve_list 6) 1)) " " (number->string (list-ref (list-ref valve_list 6) 2)) " " smoothing_string " " (number->string min_scale) " " (number->string max_scale) " 0.6"))
                )
              )
            ) (list (string-append "intf-" valve "-ob-fluid-ch") (string-append "intf-" valve "-port-fluid-ch") (string-append "intf-" valve "-ch-fluid-port") (string-append "interior-" valve "-port-fluid-ch") )
          )
        ) (rpgetvar 'ice/setup-valve-list)
      )
			(ti-menu-load-string (format #f "/def dyn-mesh controls remeshing? no"))
    )      
  )
)
(set! wb-ice-set-display-after-mesh-replace
  (lambda ()
     (ti-menu-load-string  "/display/set/mesh-display-configuration/post-processing")
    (ti-menu-load-string  "/display/set/r-o surface-edge-visibility yes no no no ")
    (ti-menu-load-string  "/display/set/r-o surface-edge-visibility yes yes ")
    (ti-menu-load-string  "/display/s-m , , ")
    (ti-menu-load-string  "/display/view restore-view ice_ ")
  )
)
(set! wb-ice-kg-get-smoothing-string
  (lambda ()
    (let 
      (
        (smoothing_type (if wb_ice_only_smoothing?  "diffusion" "spring"))
        (smoothing_string "")
      )
      (if (string-ci=? smoothing_type "diffusion")
        (if wb_ice_only_smoothing?
          (set! smoothing_string "no yes no")
          (set! smoothing_string "no yes yes yes yes"))
        (if wb_ice_only_smoothing?
          (set! smoothing_string "no yes no")
          (set! smoothing_string "no no yes yes no"))
      )
      smoothing_string
    )
  )
)
(set! wb-ice-plot-last-monitor-values
  (lambda ()
    (let
      (
        (monitors_to_plot_standard_list '())
        (previous_time_step (- (rpgetvar 'time-step) 1))
        (CA (time->absolute-crank-angle (rpgetvar 'flow-time)))
        (previous_CA 0)
      )
      (set! previous_CA (- CA (rpgetvar 'dynamesh/in-cyn/delta-angle)))
      (set! monitors_to_plot_standard_list '(continuity x-velocity y-velocity z-velocity energy k epsilon ))
      
      (if (not (null? (inquire-species-names)))
        (if (assoc 'fmean (solver-residuals))
          (if (assoc 'premixc (solver-residuals))
            (set! monitors_to_plot_standard_list (append monitors_to_plot_standard_list (list 'fmean 'fvar 'premixc)))
            (set! monitors_to_plot_standard_list (append monitors_to_plot_standard_list (list 'fmean 'fvar))))
          (set! monitors_to_plot_standard_list (append monitors_to_plot_standard_list (list (car (inquire-species-names)))))
        )
      )
      (for-each
        (lambda (mon)
          (if (assoc mon (solver-residuals))
            (let
              ((mon_of (symbol->string (car (assoc mon (solver-residuals)))))
              (mon_value (cdr (assoc mon (solver-residuals)))) )
              (wb-ice-write-monitor-file (string-append "ice-last-residual-monitor-" mon_of ".out") (string-append "Time step's last Residual Monitor values for " mon_of) "CA" "monitor_values" previous_CA mon_value)
            )
          )
        ) monitors_to_plot_standard_list
      )
    )
  )
)
(set! wb-ice-overlay-with-velocity-vectors
  (lambda ()
    (let
      (
        (skip_vectors 
          (if (rpgetvar 'ice/solution-type)
            (if (string-ci=? (rpgetvar 'ice/solution-type) "port-flow")
              2 5)))
        (scale_vectors 
          (if (rpgetvar 'ice/solution-type)
            (if (string-ci=? (rpgetvar 'ice/solution-type) "port-flow")
              20 10)))
      )
      (ti-menu-load-string (format #f "/dis set overlays? yes" ))
      (ti-menu-load-string (format #f "/dis set velocity-vectors scale 10" ))
      (ti-menu-load-string (format #f "/dis set velocity-vectors scale-head 0.01" ))
      (ti-menu-load-string (format #f "/dis set velocity-vectors in-plane? yes" ))
      (ti-menu-load-string (format #f "/dis set velocity-vectors color \"black\" " ))
      (ti-menu-load-string (format #f "/dis vector velocity velocity-magnitude , , ~a ~a " scale_vectors skip_vectors  ))
      (ti-menu-load-string (format #f "/dis set overlays? no" ))
    )
  )
)
(set! wb-ice-kg-manage-remesh-calc-activity
  (lambda ()
    (let
      (
        (calc_act_name 'remesh-cell-zone)
      )
      (if wb_ice_only_smoothing?
        (ti-menu-load-string (format #f "/solv exe-comm enable ~a " calc_act_name))
        (ti-menu-load-string (format #f "/solv exe-comm disable ~a " calc_act_name))              
      )
    )
  )
)
(set! wb-ice-set-element-in-list
  (lambda(current_list location_index element) 
    (let
      (
        (new_list '())
      )
      
      (do ((i 0 (+ i 1))) ((= i  (length  current_list)))
        (if (= i location_index)
          (set! new_list (append new_list (list element) ))
          (set! new_list (append new_list (list (list-ref current_list i )) ) )
        )
      ) 
      new_list
	  ) 
	)
)

      
;; before mesh replace store all deactivated zones information in rpvar 'ice/kg-deactivated-threads  
(set! wb-ice-activate-all-deativated-zones
  (lambda ()
    (let
      (
        (all_deactivated_thread_ids '())
        (all_deactivated_thread_names '())
      )
      (if (assq 'deactivated-zones (rpgetvar 'deactivated-original-state))
        (for-each
          (lambda (zone_list)
            ;(if (cell-thread? id)
            (set! all_deactivated_thread_ids (append all_deactivated_thread_ids zone_list))
          )(cdr (assq 'deactivated-zones (rpgetvar 'deactivated-original-state)))
        )
      )
      (if (not (rp-var-object 'ice/kg-deactivated-threads))
        (rp-var-define 'ice/kg-deactivated-threads '() 'list 1))
        
      (rpsetvar 'ice/kg-deactivated-threads (map nosolve-thread-id->name all_deactivated_thread_ids))
      (set! all_deactivated_thread_names (map nosolve-thread-id->name all_deactivated_thread_ids))
      (if (not (null? all_deactivated_thread_names))
        (begin
          (format  "\n\n\t\t_____________ activating following zones before mesh replace \n ~a___________\t\n\n" all_deactivated_thread_names)
          (if (in-wb?)
            (ti-menu-load-string (format #f "/mesh mod-zone activate-cell-zone y ~s" all_deactivated_thread_names))
            (ti-menu-load-string (format #f "/mesh mod-zone activate-cell-zone ~s" all_deactivated_thread_names)))
          )
      )
      
    )
  )
)
;;> (wb-ice-activate-all-deativated-zones)
;;(fluid-exvalve-1-port fluid-exvalve1-ib fluid-exvalve1-vlayer fluid-invalve-1-port fluid-invalve1-ib fluid-invalve1-vlayer fluid-layer-cylinder fluid-piston)

(set! wb-ice-kg-deactivate-zones-afer-mesh-replace
  (lambda ()
    (let
      (
        (valve_names '())
        (prev_deactivated_zones '())
        (zones_to_deactivate '())
        (zones_to_deactivate_list '())
      )
      ;'ice/kg-deactivated-threads
      (set! valve_names (wb-ice-get-valve-names-from-ch))
      (set! prev_deactivated_zones (rpgetvar 'ice/kg-deactivated-threads))
      (for-each
        (lambda (valve)
          (let
            (
              (port_zone_list '())
              (ib_zone_name "")
              (vlayer_zone_name "")
              (port_zone "")
            )
            (for-each
              (lambda(zone)
                (if (and (substring? "-port" (symbol->string zone)) (substring? (substring valve 0 (- (string-length valve) 1)) (symbol->string zone) ))
                  (set! port_zone_list (append port_zone_list (list zone))))
              ) prev_deactivated_zones
            )
            (if (not (null? port_zone_list))
              (begin
                (set! port_zone (string->symbol (car port_zone_list)))
                (set! ib_zone_name (string-append "fluid-" valve "-ib"))
                (set! vlayer_zone_name (string-append "fluid-" valve "-vlayer"))
              )
            )
            (if (member port_zone prev_deactivated_zones) 
              (set! zones_to_deactivate (append zones_to_deactivate (list (list port_zone ib_zone_name vlayer_zone_name )))))
    
          )
        )  valve_names
      )
      (for-each
        (lambda (x)
          (for-each
            (lambda (y)
              (set! zones_to_deactivate_list (append zones_to_deactivate_list (list y)))
            ) x
          )
        ) zones_to_deactivate
      )
      ;(format "\nzones_to_deactivate_list : ~a" zones_to_deactivate_list) 
      (for-each
        (lambda (zone)
          (if (not (member (symbol->string zone) zones_to_deactivate_list))
            (set! zones_to_deactivate (append zones_to_deactivate (list (list zone )))))
        ) (rpgetvar 'ice/kg-deactivated-threads)
      )
      ;(format "\zones_to_deactivate : ~a" zones_to_deactivate) 
        
      (if (not (null? zones_to_deactivate))
        (begin
          (format "\n\n Deactivating port related zones after mesh replace ~a \n  " zones_to_deactivate )
          (for-each
            (lambda(zone_list)
              (wb-ice-deactivate-cell-zones zone_list)
            )zones_to_deactivate
          ) 
        )
      )
    )
  )
)
(set! wb-ice-write-case-data-solution-point
  (lambda (file_name)
    (let
      (
        (case_file_name (string-append file_name ".cas.gz"))
        (data_file_name (string-append file_name ".dat.gz"))
      )
      (sm-manage-solution-file-list 'case-file case_file_name)
      (write-case case_file_name #t)
      (%save-case-id)
      (activate-deactivated-zones #t)
      ((case-modified-protect write-data) data_file_name #t)
      (if (not (null? (rpgetvar 'deactivated-original-state)))
          (deactivate-activated-zones))
      (%save-data-id)
    )
  )
)

(define wb-ice-remove-duplicates-from-list
  (lambda (org_list)
    (let
      (
        (temp_list '())
      )
      (for-each 
        (lambda (x)
          (if (not (member x temp_list))
            (set! temp_list (append temp_list (list x)))
          )
        ) org_list
      )
      temp_list
    )
  )
)
