;////////////////////////////////////////////////////////////////////////////
;//                                                                        //
;//                 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.                                             //
;//                                                                        //
;////////////////////////////////////////////////////////////////////////////

(define  ice-chemkin-file "")
(define  ice-therm-data-file "")
(define  ice-injection-list '())
(define  ice-injection-properties '())
(define  ice-swirl-number 1)
(define  ice-spark-list '())
(define ice-pdf-file-param "")
(define ice-flamespeed-model-param '())
(define ice-combustion-model-param '())
(define ice-boundary-species-param '())
(define ice-inert-model-param '())
(define ice_nox_model_params_list '())
(define ice_soot_model_params_list '())
(define ice-combustion-model)
(define wb-ice-get-all-chamber-zones)


(define  wb-ice-combustion-rpvars)
(define  wb-ice-sector-case-setup)
(define  wb-ice-combustion-solver-setup)
(define  wb-ice-create-periodic-bc-for-sector)
(define  wb-ice-dyn-mesh-setup-for-sector)
(define  wb-ice-sector-in-cylinder-settings)
(define  wb-ice-combustion-viscous-model-setup)
(define  wb-ice-combustion-species-model-setup)
(define  wb-ice-combustion-dpm-model-setup)
(define  wb-ice-define-combustion-dpm-model)
(define  wb-ice-setup-injections)
(define  wb-ice-setup-dpm-injection)
(define  wb-ice-read-combustion-data)
(define  wb-ice-combustion-set-solution-methods)
(define  wb-ice-create-cff-for-swirl)
(define  wb-ice-patch-swirl-velocity)
(define  wb-ice-combustion-initialization)
(define  wb-ice-create-view-for-sector-planes)
(define  wb-ice-create-injection-time-step-size-event)
(define  wb-ice-create-ice-top-view)
(define  wb-ice-combustion-swirl-data)
(define  wb-ice-cal-act-for-AHRR)
(define  wb-ice-cal-act-for-iter-per-time-step)
(define  wb-ice-get-montor-data)

(define wb-ice-set-solution-methods)
(define wb-ice-report-events-table)


(define wb-ice-data-sampling)



(define wb-ice-cal-act-for-particle-tracking)


(define wb-ice-sparks-setup)
(define wb-ice-setup-partially-premixed-model)
(define wb-ice-setup-DUFL-model)
(define wb-ice-setup-Laminar-finite-rate-model)
(define wb-ice-setup-inert-model)
(define wb-ice-inert-model-event-setup)

;;---------------Utility Functions--------------------;;
(define wb-ice-diasble-unrequired-events-between-CA)
(define wb-ice-flushout-unused-events)
(define wb-ice-delete-unrequired-events-between-CA)
(define wb-ice-delete-valve-related-dynamic-zones)
(define wb-ice-deactivate-valve-related-cell-zones)
(define wb-ice-copy-bc-from-cyl-head-to-valve-wall-faces)
(define wb-ice-is-zone-under-deactivated-fluid-zone?)
(define wb-ice-port-deactivation-related-events)
(define wb-ice-define-spark-parameters-combustion)
(define wb-ice-define-injection-parameters-combustion)
(define wb-ice-solver-equations-control-events)
(define wb-ice-phi-calculation)
(define wb-setup-ic-define-parameters)
(define wb-ice-define-nox-model)
(define wb-ice-define-soot-model)
(define wb-ice-calc-acti-for-dpm-monitors)
(define wb-ice-get-injection-min-start-ca)



(set! wb-ice-combustion-rpvars
  (lambda()
    (if (not (rp-var-object 'ice/injection/start-angle))
      (rp-var-define 'ice/injection/start-angle  355.2324 'real 1)
      )
    (if (not (rp-var-object 'ice/injection/stop-angle))
      (rp-var-define 'ice/injection/stop-angle  399.1587 'real 1)
      )

    (if (not (rp-var-object 'ice/dpm-cal-freq))
      (rp-var-define 'ice/dpm-cal-freq  1 'int 1)
      )
    (if (not (rp-var-object 'ice/injection-pen-len-rad-factor))
      (rp-var-define 'ice/injection-pen-len-rad-factor  .25 'real 1) ;this rpvar can be changed anytime during Fluent run, by creating an event, inorder to change the step-size of bin used in the calculation of penetration length 
      )    
    (if (not (rp-var-object 'ice/spark_parameter_list))
      (rp-var-define 'ice/spark_parameter_list  '() 'list '())
    )
    (if (not (rp-var-object 'ice/injection_parameter_list))
      (rp-var-define 'ice/injection_parameter_list  '() 'list '())
    )
    (if (not (rp-var-object 'ice/injection_monitor_def))
      (rp-var-define 'ice/injection_monitor_def  '() 'list '())
    )
    
    )
  )

(wb-ice-combustion-rpvars)


(set! wb-ice-get-montor-data
  (lambda(quantity report-type zones)
    (if (not (or (eq? report-type 'volume) (eq? report-type 'mass) ) )
      (begin
	(rpsetvar 'monitor/compute-node-values? #f)
	(client-fill-node-values quantity)
	(rpsetvar 'monitor/compute-node-values? #t)
	)
      )
      (%volume-integrals report-type (map thread-name->id zones)) 
    )
  )


(define (wb-ice-split lst at)
  ; splits the list
  ; n - new list
  ; l - an old
  ; i - a counter
  (define (iter n l i)
    (if (or (null? l) (= i at))
      (cons (reverse n) l)
      (iter (cons (car l) n) (cdr l) (+ i 1))
    )
  )
  (iter () lst 0)
)  




(set! wb-ice-cal-act-for-particle-tracking
  (lambda()
    (let
      (
       (inj-list '())
       (p-t-file-path "wb-ice-particle-data-")       
       (p-t-file-name "")
       (inj-name "")
       (cal-act-string "")

       (start-CA 0)
       (end-CA 0)
       (event '())
       (cur-event-list '())
       (pre-event-list '())
       (frequency 1)
       (exported_var "particle-mass particle-diameter color-by")
       (color_by 'particle-resid-time)
       (phd_write_freq 10)

       )
      (set! inj-list (map symbol->string (map car (rpgetvar 'dpm/injections-list))))
      (do ((i 0 (+ i 1))) ((= i (length inj-list)))
	(set! inj-name (list-ref inj-list i))
	(if (assv 'unsteady-ca-start (cadr (list-ref  (rpgetvar 'dpm/injections-list) i))) 
	  (set! start-CA (cdr (assv 'unsteady-ca-start (cadr (list-ref  (rpgetvar 'dpm/injections-list) i)))))
	  )
	(if (assv 'unsteady-ca-stop (cadr (list-ref  (rpgetvar 'dpm/injections-list) i))) 
	  (set! end-CA (cdr (assv 'unsteady-ca-stop (cadr (list-ref  (rpgetvar 'dpm/injections-list) i)))))
	  )	
	(set! p-t-file-name (string-append p-t-file-path inj-name)) 
	(set! cal-act-string (format #f "(wb-ice-calculate-dpm-parameters ~s)" inj-name))
	(ti-menu-load-string (format #f "/file t-e p-h-d ~s cfdpost ~s (~s) ~s () ~s ~s 0 " (string->symbol inj-name) p-t-file-name inj-name (string->symbol exported_var) color_by  phd_write_freq ))
	(ti-menu-load-string (format #f "/solv exe-comm a-e cal-act-for-~s 1 ~s ~s"  (string->symbol inj-name) "time-step" cal-act-string))  
	(if (or (< start-crank-angle start-CA) (> start-crank-angle end-CA)) (ti-menu-load-string (format #f "/sol e-c disable cal-act-for-~s" (string->symbol inj-name))))

	(set! event (list '(active . #t) (cons 'name (format #f "enable-pt-cal-act-for-~s"(string->symbol inj-name))) (cons 'start start-CA) (list 'action 15 (format #f "/sol e-c enable cal-act-for-~s"(string->symbol inj-name))))) 
	(set! cur-event-list (list-add cur-event-list event))
	(set! event (list '(active . #t) (cons 'name (format #f "disable-pt-cal-act-for-~s"(string->symbol inj-name))) (cons 'start end-CA) (list 'action 15 (format #f "/sol e-c disable cal-act-for-~s"(string->symbol inj-name))))) 
	(set! cur-event-list (list-add cur-event-list event))	
	)
      (set! pre-event-list (rpgetvar 'dynamesh/in-cyn/event-list))
      (rpsetvar 'dynamesh/in-cyn/event-list (append pre-event-list cur-event-list))      


      )
    (wb-changedir (string-append (directory case-dir-name) "/Fluent")) ;A report dir is created inside Fluent dir because of writing pt file, to avoid we are doing this 
    )
  )






(set! wb-ice-cal-act-for-iter-per-time-step
  (lambda()
    (let
      (
       (cal-act-string "(wb-ice-write-iterations-per-time-step)")
       )

      (ti-menu-load-string (format #f "/solv exe-comm a-e cal-act-for-iter-per-time-step 1 ~s ~s"  "time-step" cal-act-string))  
      )
    )
  )


(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=? 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
      )
    )
  )
  
(set! wb-ice-cal-act-for-AHRR
  (lambda()
    (let
      ((cal-act-string "")
       (ch-zones '())
       )
      (set! ch-zones (wb-ice-get-all-chamber-zones))
      (set! cal-act-string (format #f "(wb-ice-write-AHRR '~s)" ch-zones))

      (ti-menu-load-string (format #f "/solv exe-comm a-e cal-act-for-AHRR 1 ~s ~s"  "time-step" cal-act-string))
      (if (not (or (string-ci=? combustion-simulation-type "full_engine_ivc_to_evo") (string-ci=? combustion-simulation-type "sector")))
        (wb-ice-get-min-max-angles-for-ahrr)
      )
      )
    )
  )

  (set! wb-ice-data-sampling
	(lambda()
		(let
			( 
				(species "")
			)
		(do
		    (
		     (i 1 (+ i 1))
		     )
		    (( = i (length (inquire-species-names)) ))
				(set! species  (string-append  species ","))


		)
			(ti-menu-load-string (string-append "/solv set data-sampl yes , yes yes yes  no yes " species))
	)
  )
  )
  

(set! wb-ice-create-injection-time-step-size-event
  (lambda(injection reduced-value increased-value)
    (let
      (
       (name "injection")
       (start-name "reduce-dt-injection0")
       (end-name "increase-dt-injection0")
       (pre-event-list (rpgetvar 'dynamesh/in-cyn/event-list ) )
       (curr-event-list '() )
       (event-01 '())
       (event-02 '())
       (inject-start-CA (rpgetvar 'ice/injection/start-angle))
       (inject-end-CA (rpgetvar 'ice/injection/stop-angle))
       ;(dCA (* 0.5 (rpgetvar 'dynamesh/in-cyn/delta-angle)))
       )
      (if (assoc 'injection-name injection )
	(set! name          (cadr (assoc 'injection-name injection ) ))
	)
      (set! start-name (string-append "reduce-dt-" name))
      (set! end-name (string-append "increase-dt-" name))

      (set! event-01 (list '(active . #t) (cons 'name  start-name) (cons 'start inject-start-CA) (list 'action 5  reduced-value)))
      (set! event-02 (list '(active . #t) (cons 'name end-name) (cons 'start inject-end-CA) (list 'action 5 increased-value)))

      (set! curr-event-list (list event-01 event-02))
      (rpsetvar 'dynamesh/in-cyn/event-list (append pre-event-list curr-event-list))
      )

    )
  )
(set! wb-ice-create-ice-top-view
  (lambda(up-vector-x up-vector-y up-vector-z)
    (let
      (
       (name "ice-top-view")
       (px 0)
       (py 0)
       (pz 0)
       (tx 0)
       (ty 0)
       (tz 1)
       )
      (define cyl-origin  (read-var ICDyMeshSetFile 'cylinder_axis_origin))
      (set! tx (car cyl-origin))
      (set! ty (cadr cyl-origin))
      (set! tz (caddr cyl-origin))

      (define cyl-rad  (read-var ICDyMeshSetFile 'cylinder_radius))

      (define cyl-axis  (get-unit-vector (read-var ICDyMeshSetFile 'cylinder_axis)))
      (set! px (+ tx (* cyl-rad (car cyl-axis))))
      (set! py (+ ty (* cyl-rad (cadr cyl-axis))))
      (set! pz (+ tz (* cyl-rad (caddr cyl-axis))))


      ;top view
      (ti-menu-load-string (format #f "/dis view camera po ~s ~s ~s" px py pz))
      (ti-menu-load-string (format #f "/dis view camera target ~s ~s ~s"  tx ty tz ))
      (ti-menu-load-string (format #f "/dis view camera u-v ~s ~s ~s" up-vector-x up-vector-y up-vector-z)) 
      (ti-menu-load-string (format #f "view auto"))
      (ti-menu-load-string (format #f "/dis view s-v ~s" (string->symbol name)))
      )

    )
  )
(set! wb-ice-create-view-for-sector-planes

  (lambda ()
    (format  "\n\n\t\t ___________ Defining Views for User Planes _____________\t\n\n") 
    (ti-menu-load-string "/dis view r-v iso")
    (ti-menu-load-string "/dis view s-v ice-iso-view")

    (define post-plane)


    (set! post-plane  (read-var solver-set-file 'post_planes))
    (if post-plane
      (begin 

    (define cyl-axis  (get-unit-vector (read-var ICDyMeshSetFile 'cylinder_axis)))
    (define up-vectorx (car cyl-axis))
    (define up-vectory (cadr cyl-axis))
    (define up-vectorz (caddr cyl-axis))

    (define cyl-origin  (read-var ICDyMeshSetFile 'cylinder_axis_origin))
    (define ox (car cyl-origin))
    (define oy (cadr cyl-origin))
    (define oz (caddr cyl-origin))

    (define cyl-rad  (read-var ICDyMeshSetFile 'cylinder_radius))

	(define sym-engine #f)
	(define sym-norm '(1 0 0))
	(if (read-var ICDyMeshSetFile 'symmetry_engine)
	  (set! sym-engine (read-var ICDyMeshSetFile 'symmetry_engine))
	  )
	(if sym-engine 
	  (set! sym-norm (read-var ICDyMeshSetFile 'symm_normal))
	  )

	(define crank-radius .05)
	(if (read-var ICDyMeshSetFile 'crank_radius)
	  (set! crank-radius (read-var ICDyMeshSetFile 'crank_radius))
	  )

	(define piston-max-dist .30)
	(if (read-var ICDyMeshSetFile 'crank_radius)
	  (set! piston-max-dist ( * 2 crank-radius ))
	  )

	(define top-pt '())
	(define top-margin piston-max-dist)
	(define margin 0)	
	(define field-y .2)
	(if (string-ci=? solution-type "combustion")
	  (begin
	    (if (surface-name->id 'ice-sector-top-faces)
	      (set! top-pt (list-ref (list-ref (surface-coordinates  (surface-name->id 'ice-sector-top-faces) ) 0)0) )
	      )

	    ;top margin is the vertical distance of topmost point to cyl-orig along cyl-axis
	    (if (> (length top-pt) 0)
	      (set! top-margin (abs (+ (* up-vectorx (- ox (car top-pt))) (* up-vectory (- oy (cadr top-pt))) (* up-vectorz (- oz (caddr top-pt))) )))
	      )

	    (set! margin (- (* 0.5 (+ top-margin piston-max-dist)) top-margin))

	    ;now we shift cyl-orig to vertical center of the BDC geom	
	    (set! ox  (- ox (* margin up-vectorx)))
	    (set! oy  (- oy (* margin up-vectory)))
	    (set! oz  (- oz (* margin up-vectorz)))


	    ;this is the minimum field value which will capture the entire geom, even at BDC
	    (set! field-y (* 1.3 (+ top-margin piston-max-dist)))
	    )
	  )
	;(wb-ice-report-dir)


	(define l1 (list-ref (assoc 'front (cx-get-views)) 1))
	(define position (car l1))
	(define target (cadr l1))
	(define px (car position))
	(define py (cadr position))
	(define pz (caddr position))
	(define tx (car target))
	(define ty (cadr target))
	(define tz (cadr target))
	(define pos-dis (sqrt (+ (* (- px tx) (- px tx)) (* (- py ty) (- py ty)) (* (- pz tz) (- pz tz)))) )

	(do ((i 0 (+ i 1))) ((= i (length post-plane)))
	  (let 
	    (
	     (x0 (list-ref (list-ref (list-ref post-plane i) 1) 0))
	     (y0 (list-ref (list-ref (list-ref post-plane i) 1) 1))
	     (z0 (list-ref (list-ref (list-ref post-plane i) 1) 2))
	     (x1 (list-ref (list-ref (list-ref post-plane i) 2) 0))
	     (y1 (list-ref (list-ref (list-ref post-plane i) 2) 1))
	     (z1 (list-ref (list-ref (list-ref post-plane i) 2) 2))
	     (x2 (list-ref (list-ref (list-ref post-plane i) 3) 0))
	     (y2 (list-ref (list-ref (list-ref post-plane i) 3) 1))
	     (z2 (list-ref (list-ref (list-ref post-plane i) 3) 2))
	     (name (list-ref (list-ref post-plane i) 0))
	     ( x-coeff 1)
	     ( y-coeff 1)
	     ( z-coeff 1)
	     ( unit-x 1)
	     ( unit-y 1)
	     ( unit-z 1)	
	     ( px1 1)
	     ( py1 1)
	     ( pz1 1)
	     (cyl-orig-margin 1)
	     (mod 1)

	     (hor-dir '(1 1 1))

	     )

	    (set! hor-dir (get-unit-vector (list (- x2 x0) (- y2 y0) (- z2 z0))))

	    (set! ox  (+ ox (* (* 0.5 cyl-rad) (car hor-dir))))
	    (set! oy  (+ oy (* (* 0.5 cyl-rad) (cadr hor-dir))))
	    (set! oz  (+ oz (* (* 0.5 cyl-rad) (caddr hor-dir))))
	    

	    (set! x-coeff (- (* (- y2 y0) (- z1 z0)) (* (- y1 y0) (- z2 z0))))
	    (set! y-coeff (- (* (- x1 x0) (- z2 z0)) (* (- x2 x0) (- z1 z0))))
	    (set! z-coeff (- (* (- x2 x0) (- y1 y0)) (* (- x1 x0) (- y2 y0))))   
	    (set! mod (sqrt (+ (* x-coeff x-coeff) (* y-coeff y-coeff) (* z-coeff z-coeff))))

	   
	    ;reverse the direction of normal 
	    (set! unit-x (- 0 (/ x-coeff mod)))
	    (set! unit-y (- 0 (/ y-coeff mod)))
	    (set! unit-z (- 0 (/ z-coeff mod)))

	    ;for top view
	    (if (= i 0)
	      (wb-ice-create-ice-top-view (car hor-dir) (cadr hor-dir) (caddr hor-dir))
	      )

	    ;this margin is the distance between cyl-orig and the cutplane
	    (set! cyl-orig-margin  (+ (* (- ox x0) unit-x) (* (- oy y0) unit-y)(* (- oz z0) unit-z) ) )

	    (set! tx  (- ox (* cyl-orig-margin unit-x)))
	    (set! ty  (- oy (* cyl-orig-margin unit-y)))
	    (set! tz  (- oz (* cyl-orig-margin unit-z)))

	    (set! px1 (+ tx (* pos-dis unit-x)))
	    (set! py1 (+ ty (* pos-dis unit-y)))
	    (set! pz1 (+ tz (* pos-dis unit-z)))




	    (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 camera po ~s ~s ~s" px1 py1 pz1))
	    (if (string-ci=? solution-type "combustion")
	      (begin

		(ti-menu-load-string (format #f "/dis view camera target ~s ~s ~s"  tx ty tz ))
		(ti-menu-load-string (format #f "/dis view camera u-v ~s ~s ~s" up-vectorx up-vectory up-vectorz))
		(ti-menu-load-string (format #f "/dis view camera field , ~s" field-y))
		(let
		  (
		   (temp-tx (car (cx-show-camera-target))) (temp-ty (cadr (cx-show-camera-target))) (temp-tz (caddr (cx-show-camera-target) ))
		   (temp-cyl-orig-marg-x 0)
		   )
		  ;this margin is the distance between initial target and the current target, as the target has changed due to change of field
		  (set! temp-cyl-orig-marg-x  (+ (* (- tx temp-tx ) unit-x) (* (- ty temp-ty) unit-y)(* (- tz temp-tz) unit-z) ) )
		  
		  (set! tx  (- tx (* temp-cyl-orig-marg-x unit-x)))
		  (set! ty  (- ty (* temp-cyl-orig-marg-x unit-y)))
		  (set! tz  (- tz (* temp-cyl-orig-marg-x unit-z)))		

		  (ti-menu-load-string (format #f "/dis view camera po ~s ~s ~s" px1 py1 pz1))
		  (ti-menu-load-string (format #f "/dis view camera target ~s ~s ~s"  tx ty tz ))
		  )

		(ti-menu-load-string (format #f "/dis view s-v ~s-view" (string->symbol name)))
		)
	      )	    
	    )
	  )))
    )
  )

(set! wb-ice-combustion-swirl-data
  (lambda()
    (let
      (
       (zone-names '('ice-fluid-piston 'ice-fluid-chamber))
       (cylinder_axis (get-unit-vector (read-var ICDyMeshSetFile 'cylinder_axis)))     
       )

      (if (read-var solver-set-file 'swirl_data)
	(set! zone-names  (read-var solver-set-file 'swirl_data)
	  )
	)
      
    (ti-menu-load-string (format #f "/def d-m c ico yes 1 ~s ice-incylinder-output.txt cg ~s ~s ~s , , , , , ,"  zone-names (car cylinder_axis) (cadr cylinder_axis) (caddr cylinder_axis)))  
    )
  )
)
(set! wb-ice-patch-swirl-velocity
  (lambda()
    ;; patch the property x y and z velocity with cff u v and w

    (wb-ice-create-cff-for-swirl)
    (ti-menu-load-string (format #f "/sol patch ~s x-velocity , yes ice-swirl-vel-x" (map thread-name (get-threads-of-type 'fluid))))
    (ti-menu-load-string (format #f "/sol patch ~s y-velocity , yes ice-swirl-vel-y" (map thread-name (get-threads-of-type 'fluid))))
    (ti-menu-load-string (format #f "/sol patch ~s z-velocity , yes ice-swirl-vel-z" (map thread-name (get-threads-of-type 'fluid))))    
    )
  )

(set! wb-ice-combustion-initialization

  (lambda ()
    (format  "\n\n\t\t ___________Initializing the FLow_____________\t\n\n")  
    (if (read-var solver-set-file 'ice-initialization-values) 
      (set! ice-initialization-values           (read-var solver-set-file 'ice-initialization-values))
      )
    (if (not (null? ice-initialization-values))
      (begin 
	(define ice-species '())
	(let 
	  (
	   (all-species (inquire-species-names))
	   (init-var "")
	   )
	  (do ((i 0 (+ i 1))) ((= i (length all-species)))
	    (set! init-var  (list-ref all-species i))
	    (set! ice-species (list-add ice-species (cons  init-var (cons (string-append "species-" (number->string i) ) '()))))
	    )
	  )
	(do ((i 0 (+ i 1))) ((= i (length ice-initialization-values)))
	  (let 
	    (
	     (init-var (car (list-ref ice-initialization-values i)) )
	     (init-value (cadr (list-ref ice-initialization-values i)))
	     (all-species (inquire-species-names))
	     )
	    (if (assoc init-var ice-species)
	      (set! init-var (cadr (assoc init-var ice-species)))
	      )

	    (ti-menu-load-string (format #f "/solve init set-defa ~s ~s " (string->symbol init-var) init-value) )


	    )
	  )
	)
      )

    (if (not (data-valid?))
      (ti-menu-load-string "/solve init init")
      )
    (begin
      (wb-ice-patch-swirl-velocity)
      (set! patching-values (read-var solver-set-file 'patching_values))
      (if patching-values
	(do ((i 0 (+ i 1))) ((= i (length patching-values)))
	  (let
	    (
	     (patch-parts1 ())
	     (patch-value (list-ref (list-ref patching-values i) 1))
	     (patch-variable (list-ref (list-ref patching-values i) 0))
	     (patch-parts (list-ref (list-ref patching-values i) 2))
	     )

	    (do ((j 0 (+ j 1))) ((= j (length patch-parts)))
	      (let 
		((p (thread-name->id (list-ref patch-parts j))))
		(if p
      (set! patch-parts1 (append patch-parts1 (list p))))
		)
	      )

	    (ti-menu-load-string (format #f "/solve patch ~s ~s no ~s " patch-parts1 (string->symbol patch-variable) patch-value))
	    ))
	))

    ;(wb-ic-update-time-steps)


    )
  )
(set! wb-ice-create-cff-for-swirl
  (lambda()
;;___________________________  we are using the given udf to create CFF for swirl initialize _________________________________________
;;                                        DEFINE_INIT(swirl_init, domain)
;;                                        {
;;                                          cell_t c;
;;                                          Thread *t;
;;                                          real xc[ND_ND],r,cyl_axis[3],cyl_orig[3],hyp,base,ri,rj,rk,omega_i,omega_j,omega_k;
;;                                          real swirl = 1.3;
;;                                          real rpm = RP_Get_Real ("dynamesh/in-cyn/crank-rpm");
;;                                          real omega = swirl*rpm*2.*M_PI/60.;
;;                                        
;;                                          thread_loop_c (t,domain)
;;                                            {
;;                                              begin_c_loop_all (c,t)
;;                                        	{
;;                                        	  C_CENTROID(xc,c,t);
;;                                        	  ri = (xc[0]-cyl_orig[0]) - (cyl_axis[0]*(xc[0]-cyl_orig[0])) ;
;;                                        	  rj = (xc[1]-cyl_orig[1]) - (cyl_axis[1]*(xc[1]-cyl_orig[1])) ;	  
;;                                        	  rk = (xc[2]-cyl_orig[2]) - (cyl_axis[2]*(xc[2]-cyl_orig[2])) ;
;;                                        	  
;;                                        	  omega_i = omega*cyl_axis[0];
;;                                        	  omega_j = omega*cyl_axis[1];
;;                                        	  omega_k = omega*cyl_axis[2];
;;                                        	  
;;                                        	  C_U(c,t) = rk*omega_j - rj*omega_k;
;;                                        	  C_V(c,t) = ri*omega_k - rk*omega_i;
;;                                        	  C_W(c,t) = rj*omega_i - ri*omega_j;
;;                                        
;;                                        	}
;;                                              end_c_loop_all (c,t)
;;                                        }
;;                                        }
;;____________________________________________________________________________________________________________________________________                                        
    
    (let
      (
       ( rpm (rpgetvar 'dynamesh/in-cyn/crank-rpm))
       ( omega (* ice-swirl-number (/ (* 2 3.14 rpm) 60)))
       ( temp-cyl-axis (get-unit-vector cylinder_axis))
       ( temp-cyl-origin '())
       )



      (do ((i 0 (+ i 1))) ((= i 3))
	(set! temp-cyl-origin (list-add temp-cyl-origin (- (list-ref cylinder_axis_origin i) (* (list-ref temp-cyl-axis i) 10 crank_radius)))) 
	)

      (format  "\n\n\t\t ___________Creating CFF_____________\t\n\n")
      (ti-menu-load-string (string-append 
			     "(custom-field-function/define
				'(((name ice-cyl-orig-x) (display \""(number->string (car temp-cyl-origin))"\") (syntax-tree "(number->string (car temp-cyl-origin))") (code "(number->string (car temp-cyl-origin))"))
				  ((name ice-cyl-orig-y) (display \""(number->string (cadr temp-cyl-origin))"\") (syntax-tree "(number->string (cadr temp-cyl-origin))") (code "(number->string (cadr temp-cyl-origin))"))
				  ((name ice-cyl-orig-z) (display \""(number->string (caddr temp-cyl-origin))"\") (syntax-tree "(number->string (caddr temp-cyl-origin))") (code "(number->string (caddr temp-cyl-origin))"))
				  ((name ice-cyl-axis-x) (display \""(number->string (car temp-cyl-axis))"\") (syntax-tree "(number->string (car temp-cyl-axis))") (code "(number->string (car temp-cyl-axis))"))
				  ((name ice-cyl-axis-y) (display \""(number->string (cadr temp-cyl-axis))"\") (syntax-tree "(number->string (cadr temp-cyl-axis))") (code "(number->string (cadr temp-cyl-axis))"))
				  ((name ice-cyl-axis-z) (display \""(number->string (caddr temp-cyl-axis))"\") (syntax-tree "(number->string (caddr temp-cyl-axis))") (code "(number->string (caddr temp-cyl-axis))"))
				  ((name ice-omega-mag) (display \""(number->string omega)"\") (syntax-tree "(number->string omega)") (code "(number->string omega)"))
				  ))"
			     )
			     )

	(custom-field-function/define
	  '(
	    ((name ice-cell-rad-x) (display "(x - ice-cyl-orig-x) - (ice-cyl-axis-x * (x - ice-cyl-orig-x))") (syntax-tree ("-" ("-" "x-coordinate" "ice-cyl-orig-x") ("*" "ice-cyl-axis-x" ("-" "x-coordinate" "ice-cyl-orig-x")))) (code (field-- (field-- (field-load "x-coordinate") (cx-field-eval "ice-cyl-orig-x")) (field-* (cx-field-eval "ice-cyl-axis-x") (field-- (field-load "x-coordinate") (cx-field-eval "ice-cyl-orig-x"))))))
	    ((name ice-cell-rad-y) (display "(y - ice-cyl-orig-y) - (ice-cyl-axis-y * (y - ice-cyl-orig-y))") (syntax-tree ("-" ("-" "y-coordinate" "ice-cyl-orig-y") ("*" "ice-cyl-axis-y" ("-" "y-coordinate" "ice-cyl-orig-y")))) (code (field-- (field-- (field-load "y-coordinate") (cx-field-eval "ice-cyl-orig-y")) (field-* (cx-field-eval "ice-cyl-axis-y") (field-- (field-load "y-coordinate") (cx-field-eval "ice-cyl-orig-y"))))))
	    ((name ice-cell-rad-z) (display "(z - ice-cyl-orig-z) - (ice-cyl-axis-z * (z - ice-cyl-orig-z))") (syntax-tree ("-" ("-" "z-coordinate" "ice-cyl-orig-z") ("*" "ice-cyl-axis-z" ("-" "z-coordinate" "ice-cyl-orig-z")))) (code (field-- (field-- (field-load "z-coordinate") (cx-field-eval "ice-cyl-orig-z")) (field-* (cx-field-eval "ice-cyl-axis-z") (field-- (field-load "z-coordinate") (cx-field-eval "ice-cyl-orig-z"))))))
	    ((name ice-omega-x) (display "ice-cyl-axis-x * ice-omega-mag") (syntax-tree ("*" "ice-cyl-axis-x" "ice-omega-mag")) (code (field-* (cx-field-eval "ice-cyl-axis-x") (cx-field-eval "ice-omega-mag"))))
	    ((name ice-omega-y) (display "ice-cyl-axis-y * ice-omega-mag") (syntax-tree ("*" "ice-cyl-axis-y" "ice-omega-mag")) (code (field-* (cx-field-eval "ice-cyl-axis-y") (cx-field-eval "ice-omega-mag"))))
	    ((name ice-omega-z) (display "ice-cyl-axis-z * ice-omega-mag") (syntax-tree ("*" "ice-cyl-axis-z" "ice-omega-mag")) (code (field-* (cx-field-eval "ice-cyl-axis-z") (cx-field-eval "ice-omega-mag"))))
	    ((name ice-swirl-vel-x) (display "ice-cell-rad-z * ice-omega-y - ice-cell-rad-y * ice-omega-z") (syntax-tree ("-" ("*" "ice-cell-rad-z" "ice-omega-y") ("*" "ice-cell-rad-y" "ice-omega-z"))) (code (field-- (field-* (cx-field-eval "ice-cell-rad-z") (cx-field-eval "ice-omega-y")) (field-* (cx-field-eval "ice-cell-rad-y") (cx-field-eval "ice-omega-z")))))
	    ((name ice-swirl-vel-y) (display "ice-cell-rad-x * ice-omega-z - ice-cell-rad-z * ice-omega-x") (syntax-tree ("-" ("*" "ice-cell-rad-x" "ice-omega-z") ("*" "ice-cell-rad-z" "ice-omega-x"))) (code (field-- (field-* (cx-field-eval "ice-cell-rad-x") (cx-field-eval "ice-omega-z")) (field-* (cx-field-eval "ice-cell-rad-z") (cx-field-eval "ice-omega-x")))))
	    ((name ice-swirl-vel-z) (display "ice-cell-rad-y * ice-omega-x - ice-cell-rad-x * ice-omega-y") (syntax-tree ("-" ("*" "ice-cell-rad-y" "ice-omega-x") ("*" "ice-cell-rad-x" "ice-omega-y"))) (code (field-- (field-* (cx-field-eval "ice-cell-rad-y") (cx-field-eval "ice-omega-x")) (field-* (cx-field-eval "ice-cell-rad-x") (cx-field-eval "ice-omega-y")))))
	    )) 
	)
      )
    )


(set! wb-ice-read-combustion-data 
  (lambda()
    (if (read-var solver-set-file 'ice-swirl-number)
      (set! ice-swirl-number (read-var solver-set-file 'ice-swirl-number))
      )
    (if (read-var solver-set-file 'ice-chemkin-file)
      (begin
	(define str "..")
	(set! ice-chemkin-file (read-var solver-set-file 'ice-chemkin-file))
	(if (wb-get-dir) (set! str (directory (directory (wb-get-dir)))) (set! str (directory (directory (directory (client-default-basename "r"))))))
	(set! ice-chemkin-file (string-append (path-with-forward-slash str) "/" (path-with-forward-slash ice-chemkin-file)))
	)
      )
    (if (read-var solver-set-file 'ice-therm-data-file)
      (begin
	(define str "..")
	(set! ice-therm-data-file (read-var solver-set-file 'ice-therm-data-file))
	(if (wb-get-dir) (set! str (directory (directory (wb-get-dir)))) (set! str (directory (directory (directory (client-default-basename "r"))))))
	(set! ice-therm-data-file (string-append (path-with-forward-slash str) "/" (path-with-forward-slash ice-therm-data-file)))
	)
      ) 
    (if (read-var solver-set-file 'ice-injection)
      (set! ice-injection-list (read-var solver-set-file 'ice-injection))
      (set! ice-injection-list '())
      )

    (if (read-var solver-set-file 'ice-boundary-species-param)
      (set! ice-boundary-species-param (read-var solver-set-file 'ice-boundary-species-param))
      )
      
    (if (read-var solver-set-file 'ice-inert-model-param)
      (set! ice-inert-model-param (read-var solver-set-file 'ice-inert-model-param))
      )
      
    (if (read-var solver-set-file 'ice-combustion-model-param)
      (begin 
	(set! ice-combustion-model-param (read-var solver-set-file 'ice-combustion-model-param))
	(set! ice-combustion-model (cadr (assoc 'model-name ice-combustion-model-param)))
	)
      )

    (if (read-var solver-set-file 'ice-flamespeed-model-param)
      (set! ice-flamespeed-model-param (read-var solver-set-file 'ice-flamespeed-model-param))
      )
    (if (read-var solver-set-file 'ice-spark-list)
      (set! ice-spark-list (read-var solver-set-file 'ice-spark-list))
      )

    (if (read-var solver-set-file 'ice-pdf-file-param)
      (set! ice-pdf-file-param (read-var solver-set-file 'ice-pdf-file-param))
      )


    )
  )
(set!  wb-ice-create-periodic-bc-for-sector
  (lambda()

    (format  "\n\n\t\t ___________Setting Periodic Boundary Conditions_____________\t\n\n")
    (if (and (thread-name->id "ice-periodic-faces1-chamber-bottom") (thread-name->id "ice-periodic-faces2-chamber-bottom"))
      (begin
	(changeBC "ice-periodic-faces1-chamber-bottom" "interface")
	(changeBC "ice-periodic-faces2-chamber-bottom" "interface")
	
	(createmeshinterface "sector-chamber-bottom-periodic-interface" "ice-periodic-faces1-chamber-bottom" "ice-periodic-faces2-chamber-bottom" '(periodic #t)) 
	  )
	 )
	 (if (and (thread-name->id "ice-periodic-faces1-chamber-top") (thread-name->id "ice-periodic-faces2-chamber-top"))
      (begin
	(changeBC "ice-periodic-faces1-chamber-top" "interface")
	(changeBC "ice-periodic-faces2-chamber-top" "interface")
	
	(createmeshinterface "sector-chamber-top-periodic-interface" "ice-periodic-faces1-chamber-top" "ice-periodic-faces2-chamber-top" '(periodic #t)) 
	  )
	 )
	
	(if (and (thread-name->id "ice-periodic-faces1-piston") (thread-name->id "ice-periodic-faces2-piston"))
	(begin
	(changeBC "ice-periodic-faces1-piston" "interface")
	(changeBC "ice-periodic-faces2-piston" "interface")
	(createmeshinterface "sector-piston-periodic-interface" "ice-periodic-faces1-piston" "ice-periodic-faces2-piston" '(periodic #t)) 
	)
	)

	(ti-menu-load-string "/def m-i list")

	)
  )


(set!  wb-ice-dyn-mesh-setup-for-sector
  (lambda()
    (format  "\n\n\t\t ___________Setting Dynamic Mesh Zones_____________\t\n\n")
    (let
      (
       (ave_scale .001)
       )
      (if (thread-name->id  "ice-fluid-chamber-bottom")
	(createRigidBodyDynMeshZone "ice-fluid-chamber-bottom" piston-full-prof cylinder_axis )
	)

      (if (thread-name->id  "ice-fluid-piston")
	(createRigidBodyDynMeshZone "ice-fluid-piston" piston-full-prof cylinder_axis )
	)    

    (if (thread-name->id  "ice-fluid-chamber-top")
	 (begin
		(if (thread-name->id  "ice-int-chamber-top-bottom")
			(begin
				(set! ave_scale (+ (* 0.5 (car (%get-min-max-length-scale-on-zone (thread-name->id  "ice-int-chamber-top-bottom") #f))) (* 0.5 (car (cdr (%get-min-max-length-scale-on-zone (thread-name->id  "ice-int-chamber-top-bottom") #f))))))
				(createStationaryDynMeshZone "ice-int-chamber-top-bottom" ave_scale #f) 
			)
		)
	 )
	 (begin
	   (if (thread-name->id  "ice-fluid-chamber-bottom")
		(begin
			(set! ave_scale (+ (* 0.5 (car (%get-min-max-length-scale-on-zone (thread-name->id  "ice-sector-top-faces") #f))) (* 0.5 (car (cdr (%get-min-max-length-scale-on-zone (thread-name->id  "ice-sector-top-faces") #f))))))
			(createStationaryDynMeshZone "ice-sector-top-faces" ave_scale #f) 
		)
	   )
	 )
	)
    (if (thread-name->id  "ice-cyl-chamber-bottom")
	(begin
	  (createRigidBodyDynMeshZone "ice-cyl-chamber-bottom" piston-full-prof cylinder_axis '(exclude-bc "yes"))
	  )
	)

      (if (thread-name->id  "ice-cyl-piston")
	(begin
	  (createRigidBodyDynMeshZone "ice-cyl-piston" piston-full-prof cylinder_axis '(exclude-bc "yes"))
	  )
	)

      )
    )
  )



(set!  wb-ice-sector-in-cylinder-settings
  (lambda()
    (let
      (
       (period 720)

       )

      (format  "\n\n\t\t ___________Setting In Cylinder Parameters_____________\t\n\n")
      (ti-menu-load-string "/def/mod/unsteady-1st-order yes")
      (ti-menu-load-string "/def d-m d-m yes yes , , , ,")

      (rpsetvar 'dynamesh/in-cyn/crank-rpm rpm)
      (rpsetvar 'dynamesh/in-cyn/crank-start-angle start-crank-angle)
      ;(rpsetvar 'dynamesh/in-cyn/crank-angle (rpgetvar 'dynamesh/in-cyn/crank-start-angle))
      (rpsetvar 'dynamesh/in-cyn/crank-period period)
      (rpsetvar 'dynamesh/in-cyn/piston-data (list Connecting_rod_length crank_radius piston_pin_offset))

      (rpsetvar 'dynamesh/in-cyn/delta-angle dCA)
      (ic-update-flow-time-from-angle ( rpgetvar 'dynamesh/in-cyn/crank-start-angle))

      (ti-menu-load-string "/def/dynamic-mesh/controls/layering y\n")
      (ti-menu-load-string "/def/dynamic-mesh/controls/layering-parameter/constant-height no\n")
      (ti-menu-load-string "/def/dynamic-mesh/controls/layering-parameter/collapse-factor 0.2\n")      

      (format #t "crank-rpm = ~s \n crank-period = ~s \n connecting_rod_length = ~s \n crank_radius = ~s \n crank-start-angle = ~s \n crank-angle-step-size = ~s" rpm period Connecting_rod_length crank_radius start-crank-angle dCA)

      )
    )
  )
(set! wb-ice-sector-case-setup
  (lambda()

    ;setting up cell zones axis and origins
    (wb-ice-set-cell-zone-conditions)
    ;creates periodic bc and correspong mesh interfaces for periodic zones
    (wb-ice-create-periodic-bc-for-sector)

    ;setting in-cylinder, and mesh control parameters
    (wb-ice-sector-in-cylinder-settings)

    ;setting dyn-mesh zones
    (wb-ice-dyn-mesh-setup-for-sector)

    )
  )

(set! wb-ice-combustion-viscous-model-setup
  (lambda()
    (format  #t "\n\n\t\t ___________Setting Up Viscous Models_____________\t\n\n")
    (ti-menu-load-string "/def mode vis ke-standa yes\n")
    (ti-menu-load-string "/dis set pic driver jpeg\n")

    )
  )

(set! wb-ice-combustion-species-model-setup
  (lambda()
    (format  #t "\n\n\t\t ___________Setting Up Species Models_____________\t\n\n")
    (let
      (
       (mixture-name "")
       (mixture-index 0)
       )

      (if (and ice-chemkin-file ice-therm-data-file)
	(begin
	  (if (and (file-exists? ice-chemkin-file) (file-exists? ice-therm-data-file))      
	    (ti-menu-load-string (format #f "/file import chemkin-mechanism , ~s ~s , ,\n"ice-chemkin-file ice-therm-data-file ))
	    (format #t "\n No chemkin-file or therm-data-file specified by user \n\n")
	    )   
	  )
	)
      (if (assoc 'mixture-material ice-combustion-model-param)
	(set! mixture-name (cadr (assoc 'mixture-material ice-combustion-model-param)))
	)
      (if (member "mixture" (map symbol->string (map cadr (get-all-materials))))
	(begin
	  (set! mixture-index (- (length (get-all-materials)) (length (member "mixture" (map symbol->string (map cadr (get-all-materials))))) ) )
	  (set! mixture-name (symbol->string (car (list-ref (get-all-materials) mixture-index) )))
	  (ti-menu-load-string (format #f "/def model species s-t y ~s\n"(string->symbol mixture-name)))
	  )
	(begin
	  (if (and (string-ci=? ice-combustion-model "CI-LFR") (assoc 'mixture-material ice-combustion-model-param))
	    (begin 
	      ;(ti-menu-load-string (format #f "/def model species s-t y n-heptane-air\n"))
	      (ti-menu-load-string (format #f "/def model species s-t y ~s\n" (string->symbol mixture-name)))
	      (ti-menu-load-string (format #f "/def materials change-create ~s , , yes ideal-gas , yes mass-weighted-mixing-law yes mass-weighted-mixing-law , ,\n" (string->symbol mixture-name)))
	      )
	    )
	  (if (and (string-ci=? ice-combustion-model "SI-LFR") (assoc 'mixture-material ice-combustion-model-param))
	    (begin 
	      (ti-menu-load-string (format #f "/def model species s-t y ~s\n" (string->symbol mixture-name)))
	      (ti-menu-load-string (format #f "/def materials change-create ~s , , yes ideal-gas , yes mass-weighted-mixing-law yes mass-weighted-mixing-law , ,\n" (string->symbol mixture-name)))
	      )
	    )
	  (if (not (assoc 'mixture-material ice-combustion-model-param))
	    (begin 
	      (format #t "\n No material is specified by user so setting default mixture material as \"n-heptane-air\"\n")
	      (ti-menu-load-string (format #f "/def model species s-t y n-heptane-air\n"))
	      (ti-menu-load-string (format #f "/def materials change-create n-heptane-air , , yes ideal-gas , yes mass-weighted-mixing-law yes mass-weighted-mixing-law , ,\n"))
	      )
	    )
	  ;(ti-menu-load-string (format #f "/def model species s-t y n-heptane-air\n"))
	  ;(ti-menu-load-string (format #f "/def materials change-create n-heptane-air , , yes ideal-gas , , , , ,\n"))
	  )

	)
      )

    (ti-menu-load-string "/def model species volumetric-reactions? y\n")
    (ti-menu-load-string "/def model species inlet-diffusion?  y\n")
    ;(ti-menu-load-string "/def model species thermal-diffusion?  y\n") ;DE64305:patching takes more time when thermal difuusivity is on
    (rpsetvar 'stiff-chem-seg? #t)
    (ti-menu-load-string "/def model species integration-parameters , , , , , 500 , , yes 0.02 ,\n")    



    )
  )
(set! wb-ice-combustion-dpm-model-setup
  (lambda()
    (format  #t "\n\n\t\t ___________Setting Up DPM Models_____________\t\n\n")
    (ti-menu-load-string "/def model dpm interaction coupled-calculations? y\n")
    (ti-menu-load-string "/def model dpm interaction update y\n")
    (ti-menu-load-string "/def model dpm s-m droplet-breakup? y , ,\n")   
    (ti-menu-load-string "/def model dpm s-m khrt-model , , , , ,\n")
    (rpsetvar 'dpm/max-steps 5000)
    (rpsetvar 'dpm/drag-law "dynamic-drag")
    (rpsetvar 'dpm/spray-suite-consts '(8 5 0.5 0.333333 3.333333 1 0.188 18 0.61 0 30 0.5 2.5))  

    )
  )
(set! wb-ice-define-combustion-dpm-model
  (lambda ()
    ;define DPM model settings
    (ti-menu-load-string "/define/models/dpm/unsteady-tracking yes yes ")
    (ti-menu-load-string "/define/models/dpm/interaction/coupled-calculations yes ")
    (ti-menu-load-string "/define/models/dpm/interaction/update-dpm-sources-every-flow-iteration yes ")
    (ti-menu-load-string "/define/models/dpm/interaction/no.-of-cont-phase-iters-per-dpm-iter 1 ")
    (ti-menu-load-string "/define/models/dpm/numerics/tracking-parameters 5000 no 5 ")
    (ti-menu-load-string "/define/models/dpm/numerics/enable-node-based-averaging yes ")
    (ti-menu-load-string "/define/models/dpm/numerics/error-control no ")
    (ti-menu-load-string "/define/models/dpm/numerics/tracking-scheme analytic ")
    )
  )

(set! wb-ice-setup-partially-premixed-model
  (lambda()
    (format  #t "\n\n\t\t ___________Setting Up Partially Premixed Model _____________\t\n\n")
    (let
      ( 
	(premixed-eqn "g-eqn")
	(flame-speed-model "zimont")
	(turb-len-scale-const "" )
	(turb-flame-speed-const "" )
	(wall-damping-coeff "" )
	(turb-schmidt-no "" )
	(B1-coeff "" )
	(B3-coeff "" )
	(cs-coeff "" )
	(ewald-corr-exp "" )
	(stretch-factor-coeff "" )
  (blint-modifier "yes")
  (flame-curvature "no")
  (ewald-corrector "yes")
  
  (l "")
	(l1 '())
	(l3 '())
	(l4 '())
  (ope-pressure 101325)
  (lam_flame_speed_m_k_mixture_law "isooctane-air")
  (excluded_species (string-append " \"c<s>\" \"no\"  \"no2\"  \"n2o\"  \"h2o<l>\"  \"n\"  \"nh\"  \"nh2\"  \"nh3\"  \"nnh\"  \"hcn\"  \"hno\"  \"cn\"  \"h2cn\"  \"hcnn\"  \"hcno\"  \"hocn\"  \"hnco\"  , "  ))
  (pdf_file_name (path-with-forward-slash (string-append (directory (directory (client-default-basename "r"))) "\Fluent\ICE.pdf" )))
	)
      (set! premixed-eqn (cadr (assoc 'premixed-eqn ice-combustion-model-param)))
      ;(pp premixed-eqn)
      (set! flame-speed-model (cadr (assoc 'model ice-flamespeed-model-param) ))

      (if (equal? flame-speed-model "zimont")
	(begin
	  (set! turb-len-scale-const (cadr (assoc 'turb-len-scale-const ice-flamespeed-model-param) ))
	  (set! turb-flame-speed-const (cadr (assoc 'turb-flame-speed-const ice-flamespeed-model-param) ))
	  (set! stretch-factor-coeff (cadr (assoc 'stretch-factor-coeff ice-flamespeed-model-param) ))
	  (set! wall-damping-coeff (cadr (assoc 'wall-damping-coeff ice-flamespeed-model-param) ))
	  (set! turb-schmidt-no (cadr (assoc 'turb-schmidt-no ice-flamespeed-model-param) ))
	  )
	)
      (if (equal? flame-speed-model "peters") 
	(begin
	  (set! B1-coeff (cadr (assoc 'B1-coeff ice-flamespeed-model-param) ))
	  (set! B3-coeff (cadr (assoc 'B3-coeff ice-flamespeed-model-param) ))
	  (set! cs-coeff (cadr (assoc 'cs-coeff ice-flamespeed-model-param) ))
	  (if (assoc 'ewald-corr-exp ice-flamespeed-model-param)
      (set! ewald-corr-exp (cadr (assoc 'ewald-corr-exp ice-flamespeed-model-param) )))
	  (set! wall-damping-coeff (cadr (assoc 'wall-damping-coeff ice-flamespeed-model-param) ))
	  (set! turb-schmidt-no (cadr (assoc 'turb-schmidt-no ice-flamespeed-model-param) ))
    (if (assoc 'blint-modifier ice-flamespeed-model-param) 
      (set! blint-modifier (cadr (assoc 'blint-modifier ice-flamespeed-model-param) )))
    (if (assoc 'ewald-corrector ice-flamespeed-model-param)
      (set! ewald-corrector (cadr (assoc 'ewald-corrector ice-flamespeed-model-param) )))
    (if (and (equal? premixed-eqn "g-eqn") (assoc 'flame-curvature ice-flamespeed-model-param))
      (set! flame-curvature (cadr (assoc 'flame-curvature ice-flamespeed-model-param) )))
	  )
	)

      ;define DPM
      (wb-ice-define-combustion-dpm-model)
    (if (not (null? ice-boundary-species-param))
	(begin ;(for-each (lambda (ls2) (set! ls (append ls ls2)) )ice-boundary-species-param)

	  (set! l1 (append l1 (map car ice-boundary-species-param)))
	  (set! l3 (append l3 (map cadr ice-boundary-species-param))) 
	  (set! l4 (append l4 (map caddr ice-boundary-species-param))) 

	  (do ((j 0 (+ j 1))) ((= j (length l1) ))
      (if (string-ci=? (list-ref l1 j) "c8h18")
      (set! l (string-append l " \"" "c8h18<iso>" "\" " " "  (list-ref l3 j) " " (list-ref l4 j) ) ) 
	    (set! l (string-append l " \"" (list-ref l1 j) "\" " " "  (list-ref l3 j) " " (list-ref l4 j) ) ) 
      )      
	    )
       (if (assoc "ch4" ice-boundary-species-param)
       (if (> (string->number (cadr (assoc "ch4" ice-boundary-species-param))) 0.5)
          (set! lam_flame_speed_m_k_mixture_law "methane-air")
       )
     )
	  )
	(format "\n \t No boundary species is set by user..... \n")
	)

      ;define partially premixed combustion
      (if (file-exists? ice-pdf-file-param)
	(begin
	  (ti-menu-load-string (format #f "/define/models/species/partially-premixed-combustion yes no ~s"ice-pdf-file-param ))
	  (ti-menu-load-string "/define/models/species/partially-premixed-combustion-parameters yes 100000 no ")
	  ;(ti-menu-load-string "/define/models/species/premixed-model \"g-eqn\" \"peters\" yes 2 1 2 0.66 1 0.7 ")
	  )

	(begin
	  ;(ti-menu-load-string (format #f "/define/models/species/partially-premixed-combustion yes yes yes yes , no no , , , yes  \" ch4 \" 1 ,  \" o2 \"  , 1 , , , yes , , , , , , , "))
    (ti-menu-load-string (format #f "/define/models/species/partially-premixed-combustion yes yes yes yes , no no , , , yes  ~s , ~s , yes , , , , , no ~s , \n" (string->symbol l) (string->symbol excluded_species) pdf_file_name ))
  )
	)
      (if (equal? flame-speed-model "zimont")
	(ti-menu-load-string (format #f "/def model spe p-m ~s ~s ~s ~s ~s ~s ~s " premixed-eqn flame-speed-model turb-len-scale-const turb-flame-speed-const stretch-factor-coeff wall-damping-coeff turb-schmidt-no ))
	)
      (if (equal? flame-speed-model "peters")
        (begin
          (if (string-ci=? ewald-corrector "yes")
            (ti-menu-load-string (format #f "/def model spe p-m ~s ~s ~s ~s ~s ~s ~s ~s ~s ~s" premixed-eqn flame-speed-model (string->symbol ewald-corrector) (string->symbol blint-modifier) B1-coeff B3-coeff cs-coeff ewald-corr-exp wall-damping-coeff turb-schmidt-no ))
            (ti-menu-load-string (format #f "/def model spe p-m ~s ~s ~s ~s ~s ~s ~s ~s ~s" premixed-eqn flame-speed-model (string->symbol ewald-corrector) (string->symbol blint-modifier) B1-coeff B3-coeff cs-coeff wall-damping-coeff turb-schmidt-no ))
          )
         (if (equal? premixed-eqn "g-eqn")
          (if (string-ci=? flame-curvature "yes")
            (ti-menu-load-string (format #f "/def model spe set-prem-comb yes , ~s , , , " (string->symbol flame-curvature )))))
        )
	)
  (ti-menu-load-string (format #f "/define/models/species/partially-premixed-combustion-parameters yes ~s no "ope-pressure))
  (ti-menu-load-string "/def model species inlet-diffusion?  y\n")
  (ti-menu-load-string (format #f "/def materials c-c pdf-mixture , no no no no no no no no yes metghalchi-keck-law ~s no " lam_flame_speed_m_k_mixture_law))
      )
    )
  )

(set! wb-ice-setup-DUFL-model
  (lambda()
    (format  #t "\n\n\t\t ___________Setting Up DUFL Non Premixed Model_____________\t\n\n")
    (let (
	  (ope-pressure 101325)
	  (l "")
	  (l1 '())
	  (l3 '())
	  (l4 '())
	  (flamelet-string " ")
	  (flamelet-list '())
	  (no-of-flamelets 1)

	  )

      ;define DPM model settings
      (wb-ice-define-combustion-dpm-model)
      (if (not (null? ice-boundary-species-param))
	(begin ;(for-each (lambda (ls2) (set! ls (append ls ls2)) )ice-boundary-species-param)

	  (set! l1 (append l1 (map car ice-boundary-species-param)))
	  (set! l3 (append l3 (map cadr ice-boundary-species-param))) 
	  (set! l4 (append l4 (map caddr ice-boundary-species-param))) 

	  (do ((j 0 (+ j 1))) ((= j (length l1) ))
     (if (string-ci=? (list-ref l1 j) "c8h18")
	      (set! l (string-append l " \"" "c8h18<iso>" "\" " " "  (list-ref l3 j) " " (list-ref l4 j) ) ) 
	      (set! l (string-append l " \"" (list-ref l1 j) "\" " " "  (list-ref l3 j) " " (list-ref l4 j) ) )    
	    )
	  )
   )
	(format "\n \t No boundary species is set by user..... \n")
	)
      (if (assoc 'flamelet-params ice-combustion-model-param)
	(begin
	  (set! no-of-flamelets (length (assoc 'flamelet-params ice-combustion-model-param)) )
	  (set! flamelet-list (cdr (assoc 'flamelet-params ice-combustion-model-param)))
	  (do ((i 0 (+ i 1))) ((= i  (- no-of-flamelets 1)))
        (set! flamelet-string (string-append flamelet-string " " (number->string (cadr (list-ref flamelet-list i)))))
     )
	    )
	  )
	
      ;(define l " "nc7h16" 1 0 "o2" 0 1 ")

      ;define Non premixed combustion
      (if (and (file-exists? ice-chemkin-file) (file-exists? ice-therm-data-file))
	(begin
	  (if (> no-of-flamelets 1)
	    (ti-menu-load-string (format #f "/define/models/species/non-premixed-combustion yes yes no no no ~s ~s yes ~s , , , , , ~s ~s no , , , , \n" ice-chemkin-file ice-therm-data-file (string->symbol l) no-of-flamelets (string->symbol flamelet-string)  ))
	    (ti-menu-load-string (format #f "/define/models/species/non-premixed-combustion yes yes no no no ~s ~s yes ~s , , , , , 1 , , , , \n" ice-chemkin-file ice-therm-data-file (string->symbol l)))
	    )
	  )
	(format "\n \t Chemkin/ther-data file not found\n")
	)

      )
    )

  )

(set! wb-ice-setup-Laminar-finite-rate-model
  (lambda()
    (format  #t "\n\n\t\t ___________Setting Up LFR with detailed checmistry Species Models_____________\t\n\n")
    (let
      (
       (mixture-name "")
       (mixture-index 0)
       )

      (if (and ice-chemkin-file ice-therm-data-file)
	(begin
	  (if (and (file-exists? ice-chemkin-file) (file-exists? ice-therm-data-file))      
	    (ti-menu-load-string (format #f "/file import chemkin-mechanism , ~s ~s , ,\n"ice-chemkin-file ice-therm-data-file ))
	    (format #t "\n\n________________chemkin-file or therm-data-file  not found____________________\n\n")
	    )   
	  )
	)


      (if (member "mixture" (map symbol->string (map cadr (get-all-materials))))
	(begin
	  (set! mixture-index (- (length (get-all-materials)) (length (member "mixture" (map symbol->string (map cadr (get-all-materials))))) ) )
	  (set! mixture-name (symbol->string (car (list-ref (get-all-materials) mixture-index) )))
	  (ti-menu-load-string (format #f "/def model species s-t y ~s\n"(string->symbol mixture-name)))
	  )
	(begin
	  (ti-menu-load-string (format #f "/def model species s-t y n-heptane-air\n"))
	  (ti-menu-load-string (format #f "/def materials change-create n-heptane-air , , yes ideal-gas , , , , ,\n"))

	  )
	)

      )
    (ti-menu-load-string "/def model species volumetric-reactions? y\n")
    (ti-menu-load-string "/def model species inlet-diffusion?  y\n")
    ;(ti-menu-load-string "/def model species thermal-diffusion?  y\n")
    (rpsetvar 'stiff-chem-seg? #t)
    (ti-menu-load-string "/def model species integration-parameters , , , , , 500 , , yes 0.02 ,\n")    



    )
  )


(set! wb-ice-setup-injections
  (lambda()
    (format  #t "\n\n\t\t ___________Setting Up Injections_____________\t\n\n")
    (let
      (
       (injection '())
       )

      (do ((i 0 (+ i 1))) ((= i (length ice-injection-list)))
	(set! injection (list-ref ice-injection-list i)) 
	;(wb-ice-setup-dpm-injection (list-ref injection 0) (list-ref injection 1) (list-ref injection 2) (list-ref injection 3) (list-ref injection 4) (list-ref injection 5) (list-ref injection 6))
	(wb-ice-setup-dpm-injection injection)
;; following line moved to (wb-ice-set-time-step-change-events-previous-support)
	;(wb-ice-create-injection-time-step-size-event injection 0.05 0.25)
	)
      )
    (ti-menu-load-string "/def model dpm s-m droplet-collision? y\n")
    )
  )
(set! wb-ice-setup-dpm-injection
  (lambda(injection)
    (let
      (
       (name                     "injection")
       (location                 '(0 0 0))
       (x-position                0)
       (y-position                0)
       (z-position                0)
       (axis                      '(1 1 1))
       (x-axis                    1)
       (y-axis                    1)
       (z-axis                    1)
       ;injection properties
       (injection-type           "solid-cone")
       (particle-type            "droplet")
       (material                 "diesel-liquid")
       (no-of-particle-streams   50)
       (evaporating-species      "c7h16")
       (diameter-distribution    "rosin-rammler");uniform or rosin-rammler
       (diameter                 0.000302)
       (temperature              366.7)
       (start-CA                 355.2)
       (end-CA                   399.1587)

       (dpm-init-udf             #f)

       (velocity-prof            #f) ; field-name(profile-name) 
       (vel-magnitude            5)


       (cone-angle-profile       #f) ; field-name(profile-name) 
       (cone-angle               8)

       (cone-radius              0.0001507558)

       (mass-flow-rate-prof      #f) ; field-name(profile-name) 
       (total-flow-rate          1.3333e-05)

       (min-dia                  7.2e-07)  
       (max-dia                  1.944e-05)
       (mean-dia                 1.073e-05)
       (spread-param             3.45)
       (num-of-dia               14)

       ;some other variables, not user concerned
       (prof/constant (lambda (isProf?) (if isProf? (string->symbol "profile") (begin (if (> (length (profile-list)) 0) (string->symbol "constant") (string->symbol ""))))))
       (prof-name/mangnitude (lambda (isProf? value) (if isProf? (string-append isProf? "") (+ value 0))))  
       (udf (lambda (isUdf?) (if isUdf? (string->symbol (string-append "yes " "\""isUdf? "\""))(string->symbol "no"))))
       (rosin-rammler-option "")
       (dia-details "")
       (inj-dia "") 
       (species-list (map symbol->string (inquire-species-names)))
       )

      (if (assoc 'injection-name injection )
	(set! name          (cadr (assoc 'injection-name injection ) ))
	)
      (if (assoc 'injection-location injection )
	(begin
	  (set! location          (cadr (assoc 'injection-location injection ) ))
	  (set! x-position (car location))
	  (set! y-position (cadr location))
	  (set! z-position (caddr location))
	  )
	)
      (if (assoc 'injection-axis injection )
	(begin
	  (set! axis          (cadr (assoc 'injection-axis injection ) ))
	  (set! x-axis (car axis))
	  (set! y-axis (cadr axis))
	  (set! z-axis (caddr axis))
	  )
	)

  ;;----------------------------------------------------------------     
       (if (assoc 'injection-material injection )
	 (set! material          (cadr (assoc 'injection-material injection ) ))
	 )

       (if (assoc 'injection-evaporating-species injection)
	 (if (member  (cadr (assoc 'injection-evaporating-species injection)) species-list)
	   (set! evaporating-species          (cadr (assoc 'injection-evaporating-species injection ) ))
	   )
	 )

       (if (assoc 'injection-diameter-distribution injection )
	 (set! diameter-distribution          (cadr (assoc 'injection-diameter-distribution injection ) ))
	 )
       (if (assoc 'injection-diameter injection )
	 (set! diameter          (cadr (assoc 'injection-diameter injection ) ))
	 )
       (if (assoc 'injection-temperature injection ) 
	 (set! temperature          (cadr (assoc 'injection-temperature injection ) ))
	 )

       (if (assoc 'injection-start-CA injection ) 
	 (set! start-CA          (cadr (assoc 'injection-start-CA injection ) ))
	 )
       (if (assoc 'injection-end-CA injection ) 
	 (set! end-CA          (cadr (assoc 'injection-end-CA injection ) ))
	 )
       (if (assoc 'injection-dpm-init-udf injection ) 
	 (set! dpm-init-udf          (cadr (assoc 'injection-dpm-init-udf injection ) ))
	 )
       (if (assoc 'injection-velocity-prof injection )
	 (set! velocity-prof          (cadr (assoc 'injection-velocity-prof injection ) ))
	 )
       (if (assoc 'injection-vel-magnitude injection )
	 (set! vel-magnitude          (cadr (assoc 'injection-vel-magnitude injection ) ))
	 )

       (if (assoc 'injection-cone-angle-profile injection )
	 (set! cone-angle-profile          (cadr (assoc 'injection-cone-angle-profile injection ) ))
	 )
       (if (assoc 'injection-cone-angle injection ) 
	 (set! cone-angle          (cadr (assoc 'injection-cone-angle injection ) ))
	 )
       (if (assoc 'injection-cone-radius injection ) 
	 (set! cone-radius          (cadr (assoc 'injection-cone-radius injection ) ))
	 )
       (if (assoc 'injection-mass-flow-rate-prof injection ) 
	 (set! mass-flow-rate-prof          (cadr (assoc 'injection-mass-flow-rate-prof injection ) ))
	 )
       (if (assoc 'injection-total-flow-rate injection ) 
	 (set! total-flow-rate          (cadr (assoc 'injection-total-flow-rate injection ) ))
	 )
       (if (assoc 'injection-min-dia injection )
	 (set! min-dia          (cadr (assoc 'injection-min-dia injection ) ))
	 )
       (if (assoc 'injection-max-dia injection )
	 (set! max-dia          (cadr (assoc 'injection-max-dia injection ) ) )
	 )
       (if (assoc 'injection-mean-dia injection )
	 (set! mean-dia          (cadr (assoc 'injection-mean-dia injection ) ))
	 )
       (if (assoc 'injection-spread-param injection )
	 (set! spread-param          (cadr (assoc 'injection-spread-param injection ) ) )
	 )
       (if (assoc 'injection-num-of-dia injection )
	 (set! num-of-dia          (cadr (assoc 'injection-num-of-dia injection ) ))
	 )

       (if (string-ci=? diameter-distribution "rosin-rammler")
	 (begin
	   (set! rosin-rammler-option "yes no")
	   (set! dia-details (string-append (number->string min-dia) " " (number->string max-dia) " " (number->string mean-dia) " " (number->string spread-param) " " (number->string num-of-dia)))
	   (set! inj-dia "")
	   )
	 (begin
	   (set! rosin-rammler-option "no")
	   (set! inj-dia (number->string diameter))	
	   )
	 )

       (rpsetvar 'ice/injection/start-angle start-CA)
       (rpsetvar 'ice/injection/stop-angle end-CA)

       (ti-menu-load-string (format #f "/def/models/dpm/injection/create ~s y ~s y ~s ~s ~s y y , , , ~s , , ~s ~s ~s ~s ~s ~s ~s ~s ~s , , ~s ~s ~s ~s ~s ~s ~s ~s ~s ~s ~s"(string->symbol name) (string->symbol particle-type) (string->symbol injection-type) (string->symbol material) no-of-particle-streams (udf dpm-init-udf) (string->symbol evaporating-species) (string->symbol rosin-rammler-option) x-position y-position z-position (string->symbol inj-dia) temperature start-CA end-CA x-axis y-axis z-axis (prof/constant velocity-prof) (prof-name/mangnitude velocity-prof vel-magnitude)   (prof/constant cone-angle-profile) (prof-name/mangnitude cone-angle-profile cone-angle) cone-radius (prof/constant mass-flow-rate-prof) (prof-name/mangnitude mass-flow-rate-prof total-flow-rate) (string->symbol dia-details)))
       (if (string-ci=? material "diesel-liquid")
         (ti-menu-load-string (format #f "/def materials c-c diesel-liquid , yes constant 840 no no no no no no no no no no yes piecewise-polynomial , , , , , , , , ")))
     )
      (add-missing-inj-props) ;;DE86001 injeciton panel car-cdr error work-around
  )
)

(set! wb-ice-sparks-setup
  (lambda ()
    (if (not (null? ice-spark-list))
      (begin
        (format  #t "\n\n\t\t ___________Define spark model_____________\t\n\n")
        ;;format of spark list is 
        ;;'(((no 1) (name "Spark-0") (start-ca 7)  (x-loc 0.3) (y-loc 0.3) (z-loc 0.3)  (radius 0.00011) (fix-rtrans? #t) (radius-final 0.00066) (r150-energy 3) (duration 0.0021) (flame-speed-model "Turbulent Curvature")) .... )
        (for-each
          (lambda (spark)
            (let
              (
                (spark-number (if (assoc 'no spark) (cadr (assoc 'no spark)) 1))
                (spark-name (if (assoc 'name spark) (cadr (assoc 'name spark)) "Spark-0"))
                (spark_location (if (assoc 'spark-location spark) (cadr (assoc 'spark-location spark)) '(0 0 0)))
                (x-position  0.001)
                (y-position  0.001)
                (z-position  0.001)
                (spark-radius 
                  (if (assoc 'radius spark) 
                    (cadr (assoc 'radius spark)) 
                    (if (assoc 'spark-rad spark) 
                      (cadr (assoc 'spark-rad spark)) 0.0005)))
                (spark-energy 
                  (if (assoc 'r150-energy spark) 
                    (cadr (assoc 'r150-energy spark)) 
                    (if (assoc 'spark-energy spark) 
                      (cadr (assoc 'spark-energy spark)) 5)))
                (spark-start-CA 
                  (if (assoc 'start-ca spark) 
                    (cadr (assoc 'start-ca spark))
                    (if (assoc 'spark-start-ca spark) 
                      (cadr (assoc 'spark-start-ca spark)) 0)))
                (fix_trans_rad? 
                  (if (assoc 'fix-rtrans? spark) 
                    (cadr (assoc 'fix-rtrans? spark)) 
                    (if (assoc 'fix-trans-rad? spark) 
                      (cadr (assoc 'fix-trans-rad? spark)) #f)))
                (trans_rad 
                  (if (assoc 'radius-final spark) 
                    (cadr (assoc 'radius-final spark)) 
                    (if (assoc 'trans-rad spark)
                      (cadr (assoc 'trans-rad spark)) 0.0007)))
                (spark-duration (if (assoc 'duration spark) (cadr (assoc 'duration spark)) 0.001))
                (spark-model 
                  (if (assoc 'flame-speed-model spark) 
                    (cadr (assoc 'flame-speed-model spark)) 
                  (if (assoc 'model spark) 
                    (cadr (assoc 'model spark)) "Turbulent Curvature")))
                (spark-model1 0)
                (transition_rad_string " no ")
              )
              (set! x-position (if (assoc 'x-loc spark) (cadr (assoc 'x-loc spark)) 0.001))
              (set! y-position (if (assoc 'y-loc spark) (cadr (assoc 'y-loc spark)) 0.001))
              (set! z-position (if (assoc 'z-loc spark) (cadr (assoc 'z-loc spark)) 0.001))
              ;legacy settings
              (if (assoc 'spark-location spark)
                (begin
                  (set! x-position (car spark_location))
                  (set! y-position (cadr spark_location))
                  (set! z-position (caddr spark_location))
                )
              )
              (set! transition_rad_string 
                (if fix_trans_rad? 
                  (string->symbol (string-append " yes " (number->string trans_rad ) ))
                  (string->symbol (string-append " no " )))
              )
              (if (string-ci=?  spark-model "Turbulent Curvature")
                (set! spark-model1 0))
              (if (string-ci=? spark-model "Turbulent Length")
                (set! spark-model1 1))
              (if (string-ci=? spark-model "Herweg-Maly")
                (set! spark-model1 2))
              (if (string-ci=? spark-model "Laminar")
                (set! spark-model1 3))

              (if (file-exists? ice-therm-data-file)
                (ti-menu-load-string (format #f "/def model species s-m no ~s ~s yes ~s ~s ~s ~s ~s ~s ~s ~s ~s ~s ~s no \n" spark-number spark-number spark-name x-position y-position z-position spark-radius transition_rad_string spark-energy spark-start-CA spark-duration spark-model1 ice-therm-data-file) )
                (begin
                  (if (string-ci=? ice-combustion-model "SI-LFR")   
                    (ti-menu-load-string (format #f "/def model species s-m no ~s ~s yes ~s ~s ~s ~s ~s ~s ~s ~s ~s ~s \" \" no \n" spark-number spark-number spark-name x-position y-position z-position spark-radius transition_rad_string spark-energy spark-start-CA spark-duration spark-model1) )
                    (ti-menu-load-string (format #f "/def model species s-m no ~s ~s yes ~s ~s ~s ~s ~s ~s ~s ~s ~s ~s no \n" spark-number spark-number spark-name x-position y-position z-position spark-radius transition_rad_string  spark-energy spark-start-CA spark-duration spark-model1) )
                  )
                )
              )
            )
          ) ice-spark-list
        )
      )
      (begin
        (format  #t "\n\n\t\t ___________No spark defined by user_____________\t\n\n")
      )
    )
  )
)



(set! wb-ice-combustion-set-solution-methods
  (lambda()
    (format  #t "\n\n\t\t ___________Setting Up Solution methods_____________\t\n\n")
	(ti-menu-load-string "/solve set p-v-coupling 22")
    (ti-menu-load-string "/solve set p-v-controls 1 1 no")
    (ti-menu-load-string "/solve set gradient-scheme yes")
    (ti-menu-load-string "/solve set discretization-scheme pressure 10")
    (if (string-ci=? ice-chemkin-file "")
      (ti-menu-load-string "/solve set discretization-scheme density 1"))
    (ti-menu-load-string "/solve set discretization-scheme mom 1")
    (ti-menu-load-string "/solve set discretization-scheme k 1")
    (ti-menu-load-string "/solve set discretization-scheme epsilon 0")
    (if (or (string-ci=? ice-combustion-model "SI-Partially-Premixed") (string-ci=? ice-combustion-model "CI-DUFL"))
      (begin
        (ti-menu-load-string "/solve set discretization-scheme enthalpy 1")
      )
      (begin 
        (ti-menu-load-string "/solve set discretization-scheme temp 1")
        (ti-menu-load-string "/solve set set-all-species-together yes yes\n")
      )
    )
	(ti-menu-load-string "/solve set high-order-term-relaxation enable? yes\n")
    (ti-menu-load-string "/solve set under-rel pressure 0.3")
    (ti-menu-load-string "/solve set under-rel mom 0.5")
    (ti-menu-load-string "/solve set under-rel k 0.4")
    (ti-menu-load-string "/solve set under-rel epsilon 0.4")
    (ti-menu-load-string "/solve set under-rel density 1")
    (ti-menu-load-string "/solve set under-rel b-f 1")
    (ti-menu-load-string "/solve set under-rel temp 1")
	(ti-menu-load-string "/solve set under-rel dpm 1")

    (ti-menu-load-string "/sol/set/limits 1000 5e7 150 4000 ,,,")
    (ti-menu-load-string "(rpsetvar 'max-iterations-per-step 50)")
    )
  )

(set! wb-ice-report-events-table
  (lambda()
    ;(wb-ice-report-dir)
    (gui-events)
    (cx-gui-do cx-activate-item "Dynamic Mesh Events*PanelButtons*PushButton1(Cancel)")	
    (ti-menu-load-string (format #f  "/def dm eve eef ~aice-event_file" wb-ice-report-dir-path))
    )
  )

(set! wb-ice-set-solution-methods
  (lambda()
    (format  #t "\n\n\t\t ___________Setting Up Solution methods_____________\t\n\n")
    (ti-menu-load-string "/sol set dis-scheme pressure 10\n ")
    (ti-menu-load-string "/sol set dis-scheme mom 1\n ")
    (ti-menu-load-string "/sol set dis-scheme temp 1\n ")
    (ti-menu-load-string "/sol set dis-scheme k 0\n ")
    (ti-menu-load-string "/sol set dis-scheme epsilon 0\n ")
    )
  )
(set! wb-ice-combustion-solver-setup
  (lambda()
    (let (
	  (initialize-flow? (read-var solver-set-file 'initialize-flow?))
	  (report-mesh?  (read-var solver-set-file 'report-mesh? ))
	  (set-default-urf? (read-var solver-set-file 'set-default-urf? ))
	  (set-default-models?  (read-var solver-set-file 'set-default-models? ))
	  (set-bc?  (read-var solver-set-file 'set-bc? ))
	  (report-urf?  (read-var solver-set-file 'report-urf? ))
	  (post-planes?  (read-var solver-set-file 'post_planes ))
	  (swirl-data?  (read-var solver-set-file 'swirl_data ))
	  (user-monitor?  (read-var solver-set-file 'monitor_def ))
	  (auto-save-freq (read-var solver-set-file 'auto-save-freq))
    (auto-save-type (read-var solver-set-file 'auto-save-type))
	  (swirl-def?  (read-var solver-set-file 'swirl_def ))
	  (data-sampling?  (read-var solver-set-file 'data-sampling? ))
    (spark_parameter_list (read-var solver-set-file 'spark_parameter_list ))
    (injection_parameter_list (read-var solver-set-file 'injection_parameter_list ))
    (in_cylinder_parameter_list (read-var solver-set-file 'in_cylinder_parameter_list ))
    (ice_nox_model_params_list (read-var solver-set-file 'nox_model_params ))
    (ice_soot_model_params_list (read-var solver-set-file 'soot_model_params ))
    (inlet_outlet_bc_list (read-var solver-set-file 'inlet_outlet_bc_list ))
    (wall_bc_list (read-var solver-set-file 'wall_bc_list ))
    (injection_monitor_def (read-var solver-set-file 'injection_monitor_def ))
	  )


      ;reading combustion related data
      (wb-ice-read-combustion-data)

      ;setting up  models
      (if set-default-models?
	(begin
	  (if (string-ci=? solution-type "combustion") 
	    (begin
	      (wb-ice-combustion-viscous-model-setup)
        (if (or (string-ci=? ice-combustion-model "CI-LFR") (string-ci=? ice-combustion-model "SI-LFR") (string-ci=? ice-combustion-model "CI-DUFL"))
          (wb-ice-combustion-species-model-setup))
        (if (string-ci=? ice-combustion-model "SI-Partially-Premixed")
		(begin 
		  (wb-ice-setup-partially-premixed-model)
		  (wb-ice-sparks-setup)
		  )
		)
	      (wb-ice-combustion-dpm-model-setup)
	      (wb-ice-setup-injections)
	      (if (string-ci=? ice-combustion-model "CI-DUFL") 
		(wb-ice-setup-DUFL-model)
		)

	      
	      (if (string-ci=? ice-combustion-model "SI-LFR")
		(begin 
		  ;(wb-ice-setup-partially-premixed-model)
		  (wb-ice-sparks-setup)
		  )
		)
    (if (and (not (null? ice-inert-model-param)) (or (string-ci=? ice-combustion-model "SI-Partially-Premixed") (string-ci=? ice-combustion-model "CI-DUFL") ))
      (begin
        (wb-ice-setup-inert-model)
        (wb-ice-inert-model-event-setup)
      )
    )
	      ;reducing time size event
	      ;(wb-ice-create-injection-time-step-size-event 0.1 0.25)
         ;setting solution mehtods
      (wb-ice-combustion-set-solution-methods)

	      )
	    )
	  )
	)
      (if set-bc?
	(begin
	  (wb-ice-inlet-outlet-bc)
	  (if (string-ci=? solution-type "combustion")
	    (wb-ice-wall-bc)
	    )
	  )
	)

     
      
      (if auto-save-type
       (if (string-ci=? auto-save-type "CA")
	      (wb-ice-ca-based-case-data-save-frequency auto-save-freq)
        (ti-menu-load-string (format #f "/file/auto-save/data-frequency ~s " auto-save-freq))
	      )
       )
  (if (and ice_nox_model_params_list (string-ci=? userSettingFile? "no") (not (null? ice_nox_model_params_list)))
    (wb-ice-define-nox-model ice_nox_model_params_list)
  )
  (if (and ice_soot_model_params_list (string-ci=? userSettingFile? "no") (not (null? ice_soot_model_params_list)))
    (wb-ice-define-soot-model ice_soot_model_params_list)
  )
   


      ;initialize flow
      (if initialize-flow?
	(wb-ice-combustion-initialization)
	)

      ;monitor definition
      
      (if data-sampling?
	(wb-ice-data-sampling)
	)

      ;creating planes and views for images
      (if post-planes?
	(begin
	  (wb-ice-create-planes)
	  (if (read-var solver-set-file 'combustion_simulation_type) 	(set! combustion-simulation-type   (read-var solver-set-file 'combustion_simulation_type)))
	  (if (string-ci=? combustion-simulation-type "sector")
	    (wb-ice-create-view-for-sector-planes)
	    (wb-ice-create-view-for-planes)
	    )
	  
	  (wb-ice-transientflow-create-default-images-on-planes)
	  )
	)
      (if report-mesh? 
	(wb-ice-report-mesh)
	)
  (if (string-ci=? userSettingFile? "no")
    (wb-ice-phi-calculation)
  )
  (if user-monitor?
    (wb-ice-postproc-monitors-user)
	)
  

      ;swirl data
      (if (string-ci=? userSettingFile? "no")
      (wb-ice-combustion-swirl-data)
      )
      
      (if (string-ci=? userSettingFile? "no")
        (begin
          (wb-ice-read-keygrid-data)
          (if (> (length wb-ice-keygrid-mesh-list) 0) 
            (begin
              (wb-ice-keygrid-events wb-ice-keygrid-mesh-list)
            )
          )
          (if (rp-var-object 'ice/engine-piston-type)
            (if (rpgetvar 'ice/engine-piston-type)
              (if (= 3 (rpgetvar 'ice/engine-piston-type))
                (wb-ice-define-piston-type3-insert-delete-angle-events))))
        ) 
      )
	    ;calculation activities
      (if (string-ci=? userSettingFile? "no")
       (begin 
          (wb-ice-cal-act-for-AHRR)
          (wb-ice-cal-act-for-iter-per-time-step)
         (wb-ice-cal-act-for-particle-tracking)
         (wb-ice-solver-equations-control-events)
         (order-events-based-on-crank-angle)
         (wb-ice-report-events-table)
          (if injection_monitor_def
            (if (not (null? (rpgetvar 'dpm/injections-list)))
            (wb-ice-calc-acti-for-dpm-monitors))
        )
       )
      )
      ; (wb-trace #t)
      (if (string-ci=? userSettingFile? "no")
        (begin
          (if (rp-var-object 'ice/spark_parameter_list)
            (rpsetvar 'ice/spark_parameter_list spark_parameter_list))
          (if (rp-var-object 'ice/injection_parameter_list)
            (rpsetvar 'ice/injection_parameter_list injection_parameter_list))
          (if (rp-var-object 'ice/in_cylinder_parameter_list)
            (rpsetvar 'ice/in_cylinder_parameter_list in_cylinder_parameter_list))
          (if (rp-var-object 'ice/inlet_outlet_bc_list_parametric)
            (rpsetvar 'ice/inlet_outlet_bc_list_parametric inlet_outlet_bc_list))
          (if (rp-var-object 'ice/wall_bc_list_parametric)
            (rpsetvar 'ice/wall_bc_list_parametric wall_bc_list))
          (if (rp-var-object 'ice/injection_monitor_def)
            (rpsetvar 'ice/injection_monitor_def injection_monitor_def))
        )
      )


      )

    )
  )

;;------------utility methods---------------------------------------;;
(set! wb-ice-flushout-unused-events
  (lambda()

    (let
      (
       (valves-prop-list (read-var ICDyMeshSetFile 'setup_valve_list))
       (evo-angle (rpgetvar 'dynamesh/in-cyn/crank-period))
       (open-angle 0)
       (close-angle 0)
       (end-smoothing-angle 0)
       (begin-smoothing-angle 0)
       (valve-related-events-interval '())
       )
      (do ((i 0 (+ i 1))) ((= i (length valves-prop-list)))
	(if (member (list-ref (list-ref valves-prop-list i) 1) ports-to-deactivate)
	  (begin
	(set! open-angle (list-ref (list-ref valves-prop-list i) 3) )
	(set! close-angle (list-ref (list-ref valves-prop-list i) 4) )	  
	(set! valve-related-events-interval (list-add (list-add valve-related-events-interval (list (- open-angle 2) (+ open-angle 2)))  (list (- close-angle 2) (+ close-angle 2))))
	(set! valve-related-events-interval (list-add (list-add valve-related-events-interval (list (- (+ open-angle 5) 2) (+ (+ open-angle 5) 2)))  (list (- (- close-angle 5) 2) (+ (- close-angle 5) 2))))
	(set! end-smoothing-angle (cadr (assoc 'end-valve-open-smoothing (list-ref valves-prop-list i))))
	(set! begin-smoothing-angle (cadr (assoc 'begin-valve-close-smoothing (list-ref valves-prop-list i))))
	(set! valve-related-events-interval (list-add (list-add valve-related-events-interval (list (- end-smoothing-angle 2) (+ end-smoothing-angle 2)))  (list (- begin-smoothing-angle 2) (+ begin-smoothing-angle 2))))
	)
	  )
	)

      (if (= (length unrequired-events-interval) 0)
	(set! unrequired-events-interval valve-related-events-interval)
	)

      (do ((i 0 (+ i 1))) ((= i (length unrequired-events-interval)))

	(if (string-ci=? unrequired-events "delete")
	  (wb-ice-delete-unrequired-events-between-CA (car (list-ref unrequired-events-interval i)) (cadr (list-ref unrequired-events-interval i)) )

	  )
	(if (string-ci=? unrequired-events "disable")
	  (wb-ice-diasble-unrequired-events-between-CA (car (list-ref unrequired-events-interval i)) (cadr (list-ref unrequired-events-interval i)) )

	  )
	)
      )

    )
  )
(set! wb-ice-diasble-unrequired-events-between-CA
  (lambda(start-CA end-CA)
    (let
      (
       (new-event-list '())
       (event '())
       (current-event (rpgetvar 'dynamesh/in-cyn/event-list) )
       (temp-event '())
       )
      (do ((i 0 (+ i 1))) ((= i (length current-event)))
	(set! event (list-ref current-event i))
	(if (and (>= (cdr (assoc 'start event)) start-CA) (<= (cdr (assoc 'start event)) end-CA) )
	  (begin

	    (set! temp-event '((active . #f)))
	    (do ((j 1 (+ j 1))) ((= j (length event)))
	      (set! temp-event (list-add temp-event (list-ref event j)))
	      )

	    (set! event temp-event)
	    )
	  )
	(set! new-event-list (list-add new-event-list event))
	)
      (rpsetvar 'dynamesh/in-cyn/event-list new-event-list)


      )
    )
  )
(set! wb-ice-delete-unrequired-events-between-CA
  (lambda(start-CA end-CA)
    (let
      (
       (new-event-list '())
       (event '())
       (current-event (rpgetvar 'dynamesh/in-cyn/event-list) )
       (temp-event '())
       )
      (do ((i 0 (+ i 1))) ((= i (length current-event)))
	(set! event (list-ref current-event i))
	(if (not (and (>= (cdr (assoc 'start event)) start-CA) (<= (cdr (assoc 'start event)) end-CA) ))
	  (begin
	    (set! new-event-list (list-add new-event-list event))

	    )
	  )
	)
      (rpsetvar 'dynamesh/in-cyn/event-list new-event-list)
      )
    )
  )
(set! wb-ice-delete-valve-related-dynamic-zones
  (lambda()
    (let
      (
       (dyn-zone-list (rpgetvar 'dynamesh/dynamic-zones ))
       (zone-list-to-del '())
       (zone-name "")
       (valve-data-list (read-var ICDyMeshSetFile 'setup_valve_list))
       (layering-zones '())
       )


      (if (string-ci=? hybrid/layering "l")
	(begin

	  (do ((i 0 (+ i 1))) ((= i (length valve-data-list)))
	    (set! layering-zones (list-add layering-zones (string-append (list-ref (list-ref valve-data-list i) 1) "-ch")))	
	    )
	  (do ((i 0 (+ i 1))) ((= i (length dyn-zone-list)))
	    (set! zone-name  (thread-id->name (list-ref (list-ref dyn-zone-list i) 0)) )
	    (if (and (substring? "valve"  (symbol->string zone-name)) (not (member (symbol->string zone-name) layering-zones)) (not (substring? "fluid-ch-"  (symbol->string zone-name)))  )
	      (set! zone-list-to-del (list-add zone-list-to-del zone-name))
	      )
	    (if (member (symbol->string zone-name) layering-zones)
	      (ti-menu-load-string (format #f " /def d-m zones create ~s stationary , , ,"zone-name)) 
	      )
	    )
	  (do ((i 0 (+ i 1))) ((= i (length zone-list-to-del)))
	    (ti-menu-load-string (format #f "/def dyn-mesh zones delete ~s"  (list-ref zone-list-to-del i)) )
	    )	  
	  )
	(begin
	  (do ((i 0 (+ i 1))) ((= i (length dyn-zone-list)))
	    (set! zone-name  (thread-id->name (list-ref (list-ref dyn-zone-list i) 0)) )
	    (if (wb-ice-is-zone-under-deactivated-fluid-zone? (symbol->string zone-name))
	      (set! zone-list-to-del (list-add zone-list-to-del zone-name))
	      )
	    )
	  (do ((i 0 (+ i 1))) ((= i (length zone-list-to-del)))
	    (ti-menu-load-string (format #f "/def dyn-mesh zones delete ~s"  (list-ref zone-list-to-del i)) )
	    )
	  )
	)
      )
    )

  )
(set! wb-ice-deactivate-valve-related-cell-zones
  (lambda()
    (let
      (
       (cell-zone-list (map thread-name (get-threads-of-type 'fluid)))
       (zone-list-to-del "")
       (zone-name "")    
       (flag #f)
       (port-substring "")
       )
      (do ((i 0 (+ i 1))) ((= i (length cell-zone-list)))
	(set! zone-name (symbol->string (list-ref cell-zone-list i)))

	(if (wb-ice-is-zone-under-deactivated-fluid-zone? zone-name)
	  (set! zone-list-to-del (string-append zone-list-to-del " " zone-name)) 
	  )
	)
      (ti-menu-load-string (format #f "/mesh mod-zone deactivate y (~s)" (string->symbol zone-list-to-del)) )
      )
    (ic-all-dz-update-cg-position)
    ;(display-surfaces)
    )
  )


(set! wb-ice-copy-bc-from-cyl-head-to-valve-wall-faces
  (lambda()
    (let
      (
       (wall-zone-list (map thread-name (get-threads-of-type 'wall)))
       (zone-list-to-copy "")
       (zone-name "")
       (valve-data-list (read-var ICDyMeshSetFile 'setup_valve_list))
       (layering-zones '())
       )
      (if (string-ci=? hybrid/layering "l")
	(begin

	  (do ((i 0 (+ i 1))) ((= i (length valve-data-list)))
	    (set! layering-zones (list-add layering-zones (string-append (list-ref (list-ref valve-data-list i) 1) "-ch")))	
	    )
	  (do ((i 0 (+ i 1))) ((= i (length wall-zone-list)))
	    (set! zone-name  (symbol->string (list-ref wall-zone-list i)))
	    (if (member zone-name  layering-zones)
	      (set! zone-list-to-copy (string-append zone-list-to-copy " " zone-name))
	      )
	    )

	  )
	(begin

	  (do ((i 0 (+ i 1))) ((= i (length wall-zone-list)))
	    (set! zone-name  (symbol->string (list-ref wall-zone-list i)))
	    (if (wb-ice-is-zone-under-deactivated-fluid-zone? zone-name)
	      (set! zone-list-to-copy (string-append zone-list-to-copy " " zone-name))
	      )
	    )
	  )
	)
      (if (thread-name->id "cyl-head")
	(ti-menu-load-string (format #f "/def bc copy cyl-head (~s)" (string->symbol zone-list-to-copy)) )
	)

      )
    )
  ) 
(set! wb-ice-is-zone-under-deactivated-fluid-zone?
  (lambda(zone-name)
    (let
      (
      (port-substring "")
      (flag #f)
      )
    (do ((j 0 (+ j 1))) ((= j (length ports-to-deactivate)))
      (set! port-substring (string-append (substring (list-ref ports-to-deactivate j) 0 (- (string-length (list-ref ports-to-deactivate j)) 1)) "-" (substring (list-ref ports-to-deactivate j) (- (string-length (list-ref ports-to-deactivate j)) 1) (string-length (list-ref ports-to-deactivate j))) ))
      (if (or (substring? (list-ref ports-to-deactivate j)  zone-name) (substring? port-substring  zone-name))
	(begin	      
	  (set! j (- (length ports-to-deactivate) 1))
	  (set! flag #t)
	  )
	(set! flag #f)
	)
      ) 
    (if flag
      (= 1 1)
      (= 1 2)
      )

    )
  )
  )

(set! wb-ice-port-deactivation-related-events
  (lambda ()

    (ti-menu-load-string (format #f "/dis set colors color-by-type? no "))
    (ti-menu-load-string (format #f "/dis m-o "))
    

    (if deactivate-port
      (begin
	(wb-ice-deactivate-valve-related-cell-zones) ;this method will deactivate all cell zones with substring "valve" in it's name
	(ti-menu-load-string (format #f "/dis set colors color-by-type? no "))
	(ti-menu-load-string (format #f "/dis m-o "))
	)

      )

    ;__:Copying BC's from cyl-head faces to remaining valve faces
    ;
    (if deactivate-port
      (wb-ice-copy-bc-from-cyl-head-to-valve-wall-faces); this method will copy BC from cyl-head to all remaning valve wall faces, in case ports are deactivated
      )


    ;__:Disable unrequired events (if ports are deactivated) 
    ;
    (if deactivate-port
      (wb-ice-flushout-unused-events)
      )

    ;__:Delete all valve related dynamic zones (if ports are deactivated)
    ;
    (if deactivate-port
      (wb-ice-delete-valve-related-dynamic-zones) ;this method will delete all dynamic zones with substring "valve" in it's name
      )
    
    )
  )
  
;;-------------------- following function sets up inert-model for partially premixed and DUFL case in Fluent
(set! wb-ice-setup-inert-model
  (lambda ()
  (format  #t "\n\n\t\t ___________Setting Up Inert Model_____________\t\n\n")
    (let 
      ( 
        (model_string "")
        (model "")
        (inert_species '())
        (h_c_ratio 2.25)
        (inert_species_string "")
       
      )
      (if (not (null? ice-inert-model-param))
        (begin
          (if (assoc 'model ice-inert-model-param)
            (set! model (cadr (assoc 'model ice-inert-model-param)))
          )
          (if (string-ci=? model "h-c-ratio")
            (begin
              (set! h_c_ratio (number->string (cadr (assoc 'h-c-ratio ice-inert-model-param))))
              (set! model_string (string-append " yes " h_c_ratio ))
            )
            (begin
              (if (assoc 'inert-species ice-inert-model-param)
                (set! inert_species (cdr (assoc 'inert-species ice-inert-model-param)))
               )
               (for-each 
                (lambda (species) 
                  (set! inert_species_string (string-append inert_species_string " \"" (car species) "\" " " " (number->string (cadr species)) " "))) 
                  inert_species)
               (set! model_string (string-append " no " (number->string (length inert_species)) inert_species_string ))
          
            )
          )
            (ti-menu-load-string "/def model species inert-transport-model? yes")
            (ti-menu-load-string (format #f "/def model species inert-transport-controls yes yes ~s " (string->symbol model_string )))
            
      )
   
    )
    )
  )
)
;-------------------- following function define event at (invalve_open_angle - 1) deg when insert model is set
(set! wb-ice-inert-model-event-setup
  (lambda ()
    (let
      ( 
        
        (pre-event-list '())
        (cur-event-list '())
        (egr_event '())
        (valve_list '())
        (valve_type "")
        (valve_open_angle '())
        (min_invalve_open_angle #f)
      
      )
      (set! valve_list           (wb-ice-get-setup-valve-list))
      (if (not (null? valve_list))
        (begin
          (for-each (lambda (l)
                      (set! valve_type (list-ref l 1))
                      (if (string=? (substring valve_type 0 2) "in")
                      (set! valve_open_angle (append valve_open_angle (list (list-ref l 3))))
                      )
                    ) valve_list
          )
          (set! min_invalve_open_angle (wb-ice-find-min-element-from-list valve_open_angle))
          (if min_invalve_open_angle
            (begin
              (set! egr_event (list '(active . #t) (cons 'name "ice-inert-egr-reset") (cons 'start (- min_invalve_open_angle 1)) (list 'action 15 (format #f "(wb-ice-inert-egr-reset (wb-ice-get-all-chamber-zones) )")))) 
              (set! cur-event-list (list egr_event))
              (set! pre-event-list (rpgetvar 'dynamesh/in-cyn/event-list))
              (rpsetvar 'dynamesh/in-cyn/event-list (append pre-event-list cur-event-list))
            )
          )
        )
      )
    )
  )
)
;------------------ following is utility function to find minimum element from a list-----------------------------
(define (wb-ice-find-min-element-from-list ls)
  (let 
    ( (ele 0)
     )
    (if (null? ls)
    #f
    (begin
      (set! ele (car ls))
      (for-each (lambda (l)
                  (if (< l ele)
                    (set! ele l))
                  ) ls)
      ele)))
 )

;following function stores mim and max angles in rpvar-objects for AHRR calculation to be done in closed cycle only
(define wb-ice-get-min-max-angles-for-ahrr
  (lambda ()
    (let 
      (
       (open_angle_list '())
       (close_angle_list '())
       (valve_list (wb-ice-get-setup-valve-list))
       (min_open_angle 0)
       (max_close_angle 0)
       (current_ca (ice-remainder (rpgetvar 'dynamesh/in-cyn/crank-angle) 720))
       )
      (for-each 
        (lambda (event) 
          (if (string=? (substring (symbol->string (list-ref event 1) ) 0 7) "invalve")
            (begin
              (set! open_angle_list (append open_angle_list (list (list-ref event 3)))) 
              (set! close_angle_list (append close_angle_list (list (list-ref event 4)))) 
            )
          )
        ) valve_list
      )

      (set! min_open_angle (wb-ice-find-min-element-from-list open_angle_list))
      (set! max_close_angle (wb-ice-find-max-element-from-list close_angle_list))
      (if (rp-var-object 'ice/ahrr-min-open-angle)
        (rpsetvar 'ice/ahrr-min-open-angle min_open_angle)
      )
      (if (rp-var-object 'ice/ahrr-max-close-angle)
        (rpsetvar 'ice/ahrr-max-close-angle max_close_angle)
      )

	  )
	)
)

(define (wb-ice-find-max-element-from-list ls)
  (let 
    ( (ele 0)
     )
    (if (null? ls)
      0
      (begin
	(set! ele (car ls))
	(for-each (lambda (l)
		    (if (> l ele)
		      (set! ele l))
		    ) ls)
	ele)))
  )

(set! wb-setup-ic-define-parameters
  (lambda()
    ;(format  "\n\n\t\t ___________ Defining parameters for design point study_____________\t\n\n" )
    (if (or (string-ci=? (rpgetvar 'ice/solution-type) "combustion") (string-ci=? (rpgetvar 'ice/solution-type) "cold-flow") (string-ci=? (rpgetvar 'ice/solution-type) "port-flow"))
      (begin
        (if (rp-var-object 'ice/inlet_outlet_bc_list_parametric)
          (wb-ice-inlet-outlet-bc-parametric))
        (if (rp-var-object 'ice/wall_bc_list_parametric)
          (wb-ice-wall-bc-parametric))
        (if (rp-var-object 'ice/in_cylinder_parameter_list)
          (wb-ice-define-in-cylinder-as-parameters))
      )
    )
    (if (string-ci=? (rpgetvar 'ice/solution-type) "combustion") 
      (begin
        (if (rp-var-object 'ice/spark_parameter_list)
          (wb-ice-define-spark-parameters-combustion))
         (if (rp-var-object 'ice/injection_parameter_list)
          (wb-ice-define-injection-parameters-combustion))
      )
    )
  )
)

(set! wb-ice-define-spark-parameters-combustion
  (lambda()
    ;(define spark_parameter_list '(("Spark-0" (radius 0.22) (radius-final 0.022) (start-ca 22) )("Spark-1" (radius 0.33) (radius-final 0.033) (start-ca 33) )))
    (if (rpgetvar 'ice/spark_parameter_list)
      (begin
        (if (not (null? (rpgetvar 'ice/spark_parameter_list)))
          (format  "\n\n\t\t ___________ Defining spark parameters for design point study_____________\t\n\n" ))
        (for-each
          (lambda (param)
            (let
              ((spark_name (car param)))
              (for-each 
                (lambda (var)
                  (let
                    (
                      (spark_variable (car var))
                      (initial_value (cadr var))
                      (location_index 0)
                      (param_name "")
                      (current_list "")
                    )
                    (set! param_name (string-append spark_name "-" (symbol->string spark_variable)))
                    (do ((i 0 (+ i 1))) ((= i (length (rpgetvar 'spark/name))))
                      (if (string-ci=? spark_name (list-ref (rpgetvar 'spark/name) i))
                        (set! location_index i)))
                    
                    (set! current_list (string-append "(rpgetvar 'spark/" (symbol->string spark_variable) ")"))
                            
                    (ti-menu-load-string (format #f "/define/parameters/input-parameters/advance/use-in  scheme-proc  ~a ~a 
                        (lambda (value)
                          (rpsetvar 'spark/~a (wb-ice-set-element-in-list ~a ~a value ))) " param_name initial_value (symbol->string spark_variable) current_list location_index ))
                  )
                ) (cdr param)
              )
            )
          ) (rpgetvar 'ice/spark_parameter_list)
        )
      )
    )
  )
)

(set! wb-ice-define-injection-parameters-combustion
  (lambda ()
    (if (rpgetvar 'ice/injection_parameter_list)
      (begin
        (if (not (null? (rpgetvar 'ice/injection_parameter_list)))
          (format  "\n\n\t\t ___________ Defining injection parameters for design point study_____________\t\n\n" ))
        (for-each
          (lambda (param)
            (let
              ((inj_name (car param)))
              (for-each 
                (lambda (var)
                  (let
                    (
                      (inj_variable (car var))
                      (initial_value (cadr var))
                      (param_name "")
                    )
                    (set! param_name (string-append inj_name "-" (symbol->string inj_variable)))
                    (ti-menu-load-string (format #f "/define/parameters/input-parameters/advance/use-in  scheme-proc  ~a ~a 
                        (lambda (value)
                            (set-property-on-injections-list '~a value (list (assoc '~a (rpgetvar 'dpm/injections-list))))) " param_name initial_value inj_variable (string->symbol inj_name) ))
                  )
                )(cdr param)
              )
            )
          ) (rpgetvar 'ice/injection_parameter_list)
        )
        (add-missing-inj-props) ;;DE86001 injection panel car-cdr error work-around
      )
    )
  )
)

(set! wb-ice-phi-calculation
  (lambda ()
    (let
      (
        (zones (wb-ice-get-all-chamber-zones))
        (far_stoic  0.06643)
        (evap_species "")
        (phi 0)
      )
      (if (not (null? (rpgetvar 'dpm/injections-list)))
        (for-each
          (lambda (inj)
            (if (assoc 'evaporating-species (cadr inj))
              (set! evap_species (symbol->string (cdr (assoc 'evaporating-species (cadr inj ) ))))
            )
          ) (rpgetvar 'dpm/injections-list)
        )
        (set! evap_species (symbol->string (car (inquire-species-names))))
      )
      (if (string=? evap_species "c8h18<iso>")
        (set! far_stoic  0.06643)
      )
      (if (string=? evap_species "ch4")
        (set! far_stoic  0.05827)
      )
      (if (string=? evap_species "c7h16")
        (set! far_stoic  0.0662)
      )
      ;(set! evap_species (string-append "molef-" evap_species))

      (if (rpgetvar 'inert/off?)    
        (ti-menu-load-string 
          (string-append 
            "(custom-field-function/define
              '(((name far-actual) (display \"("evap_species " / (1 - "evap_species "))\") (syntax-tree (\"/\" \""evap_species "\" (\"-\" 1 \""evap_species "\"))) (code (field-/ (field-load \""evap_species "\") (field-- 1 (field-load \""evap_species "\"))))))
            )"
          )
        )
        (ti-menu-load-string 
        (string-append 
          "(custom-field-function/define
      '(((name far-actual) (display \""evap_species " / (1 - " evap_species " - mf-inert)\") (syntax-tree (\"/\" \""evap_species "\" (\"-\" (\"-\" 1 \"" evap_species "\") \"mf-inert\"))) (code (field-/ (field-load \""evap_species "\") (field-- (field-- 1 (field-load \""evap_species "\")) (field-load \"mf-inert\"))))))
      )"
        )
      )
    )
      
      
      (ti-menu-load-string 
        (string-append 
          "(custom-field-function/define
            '(((name far_stoic) (display \""(number->string far_stoic)"\") (syntax-tree "(number->string far_stoic)") (code "(number->string far_stoic)"))
            ))"
        )
      )
      (custom-field-function/define
        '(
          ((name phi) (display "far-actual / far_stoic") (syntax-tree ("/" "far-actual" "far_stoic")) (code (field-/ (cx-field-eval "far-actual") (cx-field-eval "far_stoic"))))
        )
      )
     ; (ti-menu-load-string (format #f "/sol/mon/volume s-m phi-on-chamber-zones \"Mass-Average\" phi ~s no yes yes ~s 1 yes f-t" zones (string-append "ice-phi-on-chamber-zones.out")))
    )
  )
)

(set! wb-ice-solver-equations-control-events
  (lambda ()
    (let
      (
        (equation_events_list (read-var solver-set-file 'equation_events))
        (pre_event_list (rpgetvar 'dynamesh/in-cyn/event-list))
        (cur_event_list '())
        (on_event '())
        (off_event '())
        (var "")
        (on_event_name "equation_on_event")
        (off_event_name "equation_off_event")
        (on_angle 0)
        (off_angle #f)
      )
      (if equation_events_list
        (if (not (null? equation_events_list))
          (begin
            (format  "\n\n\t\t_____________ setting solver equations control events___________\t\n\n" )
            (for-each
              (lambda (equation)
                (set! var (string-append "'" (symbol->string (car equation)) "/solve?"))
                (set! on_event_name (string-append (symbol->string (car equation)) "-equation-on-event"))
                (set! off_event_name (string-append (symbol->string (car equation)) "-equation-off-event"))
                (set! on_angle (cadr equation))
                (set! off_angle (caddr equation))
                (set! on_event (list '(active . #t) (cons 'name on_event_name) (cons 'start on_angle) (list 'action 15 (format #f "(if (rp-var-object ~a) (rpsetvar ~a #t)) (models-changed) " var var))))
                (set! cur_event_list (append cur_event_list  (list on_event)))
                (if off_angle
                  (begin
                    (set! off_event (list '(active . #t) (cons 'name off_event_name) (cons 'start off_angle) (list 'action 15 (format #f "(if (rp-var-object ~a) (rpsetvar ~a #f)) (models-changed)" var var))))
                    (set! cur_event_list (append cur_event_list  (list off_event)))
                  )
                )
                (if (> on_angle start-crank-angle)
                  (ti-menu-load-string (format #f "(if (rp-var-object ~a) (rpsetvar ~a #f)) (models-changed) " var var))
                )
              ) equation_events_list
            )
            (rpsetvar 'dynamesh/in-cyn/event-list (append pre_event_list cur_event_list))
          )
        )
      )
    )
  )
)

(set! wb-ice-define-nox-model
  (lambda (nox_model_params)
    (format  #t "\n\n\t\t ___________Setting Up NOX Model and its parameters_____________\t\n\n")
    (let
      (
        (thermal_nox? (if (assoc 'thermal_nox? nox_model_params) (cadr (assoc 'thermal_nox? nox_model_params))  #f))
        (prompt_nox? (if (assoc 'prompt_nox? nox_model_params) (cadr (assoc 'prompt_nox? nox_model_params))  #f))
        (n20_path? #t)
        (thermal_nox_string "")
        (prompt_nox_string "")
        (n20_path_string "")
        (fuel_species '("c8h18<iso>"))
        (fuel_carbon_no (if (assoc 'fuel_carbon_no nox_model_params) (cadr (assoc 'fuel_carbon_no nox_model_params))  15))
        (equi_ratio (if (assoc 'equi_ratio nox_model_params) (cadr (assoc 'equi_ratio nox_model_params)) 1))
        (fuel_species_string "")
        (fuel_species_list '())
        (reburn_string "")
        (reburn_fuel_species "")
        (reburn? #t)
        (turb_inter_string "")
        (max_post_iterations (if (assoc 'max_post_iterations nox_model_params) (cadr (assoc 'max_post_iterations nox_model_params))  20))

      )
      (if (assoc 'fuel_species nox_model_params)
        (begin
          (set! fuel_species (assoc 'fuel_species nox_model_params))
          (set! fuel_species_list (cdr fuel_species))
          (if (not (null? fuel_species))
            (begin
              (for-each 
                (lambda (e) 
                  (set! fuel_species_string (string-append fuel_species_string "\""e "\" " ))
                ) fuel_species_list
              )
              (set! fuel_species_string (string-append fuel_species_string "\"\""))
            )
          )
        )
      )
      ;(format "\nfuel_species_string = ~a\n" fuel_species_string)
        
      (if thermal_nox?
        (set! thermal_nox_string " yes 2 2 ")
        (set! thermal_nox_string " no ")
      )
      (if prompt_nox?
        (set! prompt_nox_string (format #f "yes no 1 ~a no ~a ~a" fuel_species_string fuel_carbon_no equi_ratio))
        (set! prompt_nox_string " no no ")
      )
      
      (if n20_path?
        (if thermal_nox?
        (set! n20_path_string " yes 0 ")
          (set! n20_path_string " yes 0 2 ")
        )
        (set! n20_path_string " no ")
      )
        
      (for-each
        (lambda (s)
          (if (member s (inquire-species-names))
            (set! reburn_fuel_species (string-append reburn_fuel_species "\""(symbol->string s) "\" " ))
          )
        ) '(ch20 hco ch3 ch3o)
      )
      (if (not (string-ci=? reburn_fuel_species ""))
        (set! reburn_fuel_species (string-append reburn_fuel_species "\"\"")))
      (if (and reburn? (or (string-ci=? ice-combustion-model "SI-Partially-Premixed") (not (string-ci=? ice-chemkin-file ""))))
        (set! reburn_string (format #f " yes 1 ~a no 0 " reburn_fuel_species ))
        (set! reburn_string " no ")
      )
      (if (string-ci=? ice-combustion-model "SI-Partially-Premixed") ;(string-ci=? ice-combustion-model "CI-DUFL"))
        (set! turb_inter_string " yes 4 , ")
      )
      (if (string-ci=? ice-combustion-model "CI-DUFL")
        (set! turb_inter_string " yes 1 , , , , ")
      )
      ;(format "\nreburn_fuel_species = ~a\n" reburn_fuel_species)
      (ti-menu-load-string (format #f "\n /def model nox? yes"  ) )
      (ti-menu-load-string (format #f "\n /def model nox-parameters nox-chemistry ~a ~a ~a ~a no" thermal_nox_string prompt_nox_string n20_path_string reburn_string) )
      (ti-menu-load-string (format #f "\n /def model nox-parameters nox-turbulence-interaction ~a " turb_inter_string))
      (rpsetvar 'post-process-equations? #t)
      (rpsetvar 'max-post-iterations-per-step max_post_iterations)
    )
  )
)
(set! wb-ice-define-soot-model
  (lambda (soot_model_params)
    (format  #t "\n\n\t\t ___________Setting Up SOOT Model and its parameters_____________\t\n\n")
    (let
      (
        (fuel_species "")
        (fuel_c_no 
          (if (assoc 'fuel_carbon_no soot_model_params) 
            (cadr (assoc 'fuel_carbon_no soot_model_params)) 11))
        (fuel_h_no 
          (if (assoc 'fuel_h_no soot_model_params) 
            (cadr (assoc 'fuel_h_no soot_model_params)) 22))
        (fuel_species_list 
          (if (assoc 'fuel_species soot_model_params) 
            (cdr (assoc 'fuel_species soot_model_params)) '("ch4")))
        (max_post_iterations (if (assoc 'max_post_iterations soot_model_params) (cadr (assoc 'max_post_iterations soot_model_params))  20))
      )
      (for-each
        (lambda (s)
          (set! fuel_species (string-append fuel_species "\""(symbol->string s) "\" " ))
        ) fuel_species_list
      )
      ;(format "\nfuel_species_string = ~a\n" fuel_species_string)
      (ti-menu-load-string (format #f "\n /def model soot? yes"  ) )
      (ti-menu-load-string (format #f "\n /def model soot-parameters soot-model-parameters no no yes , , , , , , , ,  1" ) )
      (ti-menu-load-string (format #f "\n /def model soot-parameters soot-process-parameter , , 0 , ~a ~a ~a , , , , , , ,  " fuel_species fuel_c_no fuel_h_no ))
      (if (or (string-ci=? ice-combustion-model "SI-Partially-Premixed") (string-ci=? ice-combustion-model "CI-DUFL")) 
      (ti-menu-load-string (format #f "\n /def model soot-parameters soot-turbulence-interaction yes 4 ," ) )
        (ti-menu-load-string (format #f "\n /def model soot-parameters soot-turbulence-interaction yes 1 20 , , , ," ) )
      )
      (rpsetvar 'post-process-equations? #t)
      (rpsetvar 'max-post-iterations-per-step max_post_iterations)
    )
  )
)

(set! wb-ice-calc-acti-for-dpm-monitors
  (lambda ()
    (let
      (
        (cal_act_string "") 
        (min_start_ca 0)
        (event '())
        (cur_event_list '())
        (calc_activity_name 'cal-act-for-writing-dpm-monitors)
      )
      (set! min_start_ca (wb-ice-get-injection-min-start-ca))
      (set! cal_act_string (format #f "(wb-ice-write-dpm-monitors-to-file)" ))
      (ti-menu-load-string (format #f "/solv exe-comm a-e ~s 1 ~s ~s"  calc_activity_name "time-step" cal_act_string))
      (if (or (< start-crank-angle min_start_ca) (null? (rpgetvar 'dpm/injections-list)))
        (ti-menu-load-string (format #f "/sol e-c disable ~s" calc_activity_name)))
      (set! event (list '(active . #t) (cons 'name (format #f "enable-writing-dpm-monitors-to-file")) (cons 'start min_start_ca) (list 'action 15 (format #f "/sol e-c enable ~s" calc_activity_name ))))
      (set! cur_event_list (list-add cur_event_list event))
      
      (rpsetvar 'dynamesh/in-cyn/event-list (append (rpgetvar 'dynamesh/in-cyn/event-list) cur_event_list))   
    )
  )
)
(set! wb-ice-get-injection-min-start-ca
  (lambda ()
    (let
      (
        (min_start_ca 0)
        (inj_start_ca 0)
        (inj_start_ca_list '())
      )
      (for-each
        (lambda (inj)
          (if (assoc 'unsteady-ca-start (cadr inj)) 
            (set! inj_start_ca (cdr (assoc 'unsteady-ca-start (cadr inj))))
          )
          (set! inj_start_ca_list (append inj_start_ca_list (list inj_start_ca)))
        ) (rpgetvar 'dpm/injections-list)
      )
     ; (format "\n inj_start_ca_list ~a: \n " inj_start_ca_list)
      (set! min_start_ca (wb-ice-find-min-element-from-list inj_start_ca_list))
      min_start_ca
    ) 
  )
)
