;////////////////////////////////////////////////////////////////////////////
;//                                                                        //
;//                 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 comb-file-rel-path "")
;(define fluent-file-rel-path "")
(if (string?  (getenv "AWP_ROOT180"))
  (if (nt?)
    (begin
      (set! comb-file-rel-path (string-append (getenv "AWP_ROOT180") "\\Addins\\ICEngine\\CustomizationFiles\\WB-ICE-Combustion-Setup.scm"))
      ;(set! fluent-file-rel-path (string-append (getenv "AWP_ROOT180") "\\Addins\\ICEngine\\CustomizationFiles\\WB-ICE-Fluent.scm"))
      )
    (begin
      (set! comb-file-rel-path (string-append (getenv "AWP_ROOT180") "/Addins/ICEngine/CustomizationFiles/WB-ICE-Combustion-Setup.scm"))
      ;(set! fluent-file-rel-path (string-append (getenv "AWP_ROOT180") "/Addins/ICEngine/CustomizationFiles/WB-ICE-Fluent.scm"))
      )
    )
  (begin
    (set! comb-file-rel-path "WB-ICE-Combustion-Setup.scm")
    ;(set! fluent-file-rel-path "WB-ICE-Fluent.scm")
    )
  )
(if (file-exists? comb-file-rel-path)
  (begin
    ;(ti-menu-load-string (format #f "/file r-m ~s"fluent-file-rel-path))
    (ti-menu-load-string (format #f "/file r-m ~s"comb-file-rel-path))
    )
  )
(define read-var)
(define wb-setup-ic-global-solver-setting)
(define wb-setup-ic-user-solver-setting)
(define wb-setup-ic-case)
(define initial-fluids '())
(define final-fluids '())
(define new-interiors '())
(define initial-walls '())
(define final-walls '())
(define initial-interiors '())
(define wb-ice-report-dir-fluent)
(define wb-setup-ic-solver)
(define wb-ice-inlet-outlet-bc)
(define wb-ice-inlet-outlet-bc-parametric)
(define wb-ice-wall-bc)
(define wb-ice-wall-bc-parametric)
(define wb-ice-set-cell-zone-conditions)
(define wb-ice-coldflow-viscous-model-setup)
(define wb-ice-coldflow-initialization)
(define wb-ice-create-planes)
(define wb-ice-transientflow-create-default-images-on-planes)
(define wb-ice-post-plane-images-for-transient-flow)

(define wb-ice-cal-act-cold-flow)
(define wb-ice-portflow-create-default-images-on-planes)
(define wb-ice-post-plane-images-for-port-flow)

(define wb-ice-create-view-for-planes)
(define wb-ice-setup-view)
(define wb-ice-report-mesh)
(define wb-ice-report-urf)
(define wb-ice-plot-profile)
(define wb-ice-swirl-data)
(define wb-ice-postproc-monitors-default)
(define wb-ice-postproc-monitors-user)
(define wb-ice-list-monitors-to-file)
(define wb-ice-residual-monitor-history)
(define patching-values)
(define ice-initialization-values '())
(define ice-panel-read-data)
(define ice-read-data)
(define ice-apply-call-back)
(define wb-ice-dyn-mesh-setup)
(define wb-ice-solver-setup)
(define wb-ice-urf-setting)
(define set-smoothing-events)
(define define-deforming-zone-event)
(define delete-dynamic-zone-event)
(define define-stationary-zone-event)
(define define-rigidbody-zone-event)
(define read-valve-profile)
(define wb-ice-post-iter-post-plane-images-cold-flow)
(define wb-ice-post-iter-post-plane-images-port-flow)
(define wb-ice-cold-flow-capture-mesh-images)
(define order-events-based-on-crank-angle)

(define wb-ice-plot-residual-events)
(define wb-ice-post-iter-plot-residual)

(define wb-ice-keygrid-events)
(define wb-ice-read-keygrid-data)
(define wb-ice-keygrid-mesh-list '())
(define wb-ice-crevice-setup)
(define wb-ice-read-transient-table-data)
(define wb-ice-read-multiple-profiles-data)
(define wb-ice-activate-decactivate-ports)
(define wb-ice-find-zones-to-deactivate)
(define wb-ice-deactivate-ports-at-start)
(define wb-ice-set-display-after-port-deactivation)




;regeneration related
(define wb-ice-regen)
(define regen-piston-events)
(define regen-valve-events)
(define wb-regen-solver-events)

;port flow related
(define wb-ice-portflow-solver-setup)
(define wb-ice-portflow-viscous-model-setup)
(define wb-ice-portflow-initialization)
(define wb-ice-mesh-improve)

;;depricated methods

(define wb-ice-insert-layer)
(define wb-ice-delete-layer)
(define mesh-replace-initial)
(define mesh-replace-final)
(define capturingImagesOnSurfacesOfDifferentProperties)
(set! capturingImagesOnSurfacesOfDifferentProperties wb-ice-capture-images)


;; Engine Parameters
(define valves-check)
(define V-adk-old 1)
(define smoothing-on #f)
(define setup-valve-list '((1 "iname" "iprof" 340 580 0.015 (0 0 1) (0 0 0) #f #f 5)) )
(define inlet-outlet-bc-list)
(define wall-bc-list)
(define rpm 2160)
(define dCA 0.25)
(define crank_radius 105e-3)
(define piston_pin_offset 0)
(define Connecting_rod_length 145e-3)
(define Piston_stroke_cutoff 13e-3)
(define Min_valve_lift 0.35e-3)
(define increment 5)
(define auto_activate_deactivate #f)
(define auto_activate_deactivate_s "#f")
;
(define non_const_URFs #f)
(define non_const_dt #f)
(define non_const_URFs-s "#f")
(define non_const_dt-s "#f")
(define valveStore 1)

(define valve-value)
(define symmetryengine #f)
(define point_on_symmetry (list 0 0 0))
(define symm_normal (list 0 1 0))

;; Usability methods

(define changeZoneName)
(define createStationaryDynMeshZone)
(define createRigidBodyDynMeshZone)
(define changeStationaryDynMeshZoneLayerHeight)
(define deleteDynMeshZone)
(define createDeformingDynMeshZone)
(define createMeshInterface)
(define deleteMeshInterface)
(define changeBC)
(define insert-element-in-list)
(define get-unit-vector)
(define create-periodic-zones)
(define wb-ice-ca-based-case-data-save-frequency)


;cff for swirl
(define create-cff-am-swirl)
(define wb-ice-cff-on-swirl-planes)

;; Valve Parameters
(define no_of_valves 1)
(define V-adk 1)
(define valve_root_name)
(define valve_profile_name)
(define valve_axis)
(define open_valve)
(define close_valve)
(define valve_mar_rad 0.015)
(define valve_origin (list 0e-3 0e-3 0e-3))
(define valve_axis (list 0 0 1))

;;Piston Parameters
(define cylinder_axis_origin (list 0e-3 0e-3 0e-3))
(define cylinder_axis (list 0 0 1))
(define cylinder_radius 46.0e-3)
(define ice_mesh_topology #t)
(define piston_type 1)
(define start-crank-angle 0)
(define sector_angle 90)
(define insert_angle 30)
(define insert_angle_intake_stroke 40)
(define delete_angle 330)
(define withbowl #f)
(define hybrid/layering "h")
(define hybrid #t)
(define layering #f)
(define hybrid-s "#t")
(define layering-s "#f")
(define solution-type "cold-flow")
(define userSettingFile? "yes")
(define reference-mesh-size .001)
(define vlayer-mesh-size  .0005)
(define chamber-mesh-size .001)
(define deactivate-port? #f)
(define activation_angle_tolerence 2)

(define conf/nonconf "c")
(define conformal #t)
(define nonconformal #f)

(define matching_interface #t)

(define ICDyMeshSetFile "IC-parameters")
(define solver-set-file "ic-solver-set-file")
(define system-solver-set-file "ic-solver-set-file")
(define user-solver-set-file "ic-solver-set-file")
(define valve-profile-path "WBICValveProfFile.prof")
(define piston-full-prof  "**piston-full**")
(define piston-limit-prof "**piston-limit**")
(define wb-ic-register-post-journal)
(define wb-ice-post-iteration-method)
; create a temporary widget so the when u register post-iteration journal multiple times it will override the old one
(define ICPanel #f)
(define ICWidget #f) 
(if (and (cx-gui?) (not (and (in-wb?) (wb-in-batch-mode?))))
  (begin
    (set! ICPanel (cx-create-panel "IC Engine" #f #f))
    (set! ICWidget(cx-create-text-entry ICpanel "IC Widget"))
))


(define wb-ice-post-iteration-journal #f)
(define wb-ice-pre-iteration-journal #f)
(define wb-ice-user-bc-file #f)
(define wb-ic-write-custom-files)
(define wb-ic-update-time-steps)
(define wb-ic-write-solver-settings)


(define wb-ice-define-dynamic-settings-for-valves-hybrid)
(define combustion-simulation-type "")
(define wb-ice-get-setup-valve-list)

;;scheme refactoring methods for journal-l journal-h
(define wb-ice-define-initial-model-settings)
(define wb-ice-define-in-cylinder-settings)
(define wb-ice-define-non-conf-interface-rpvars)
(define wb-ice-dyn-mesh-zone-names-check-layering)
(define wb-ice-define-dyn-mesh-settings-layering)
(define wb-ice-define-dynamic-settings-for-valves-layering)
(define wb-ice-define-ib-ob-interfaces)
(define wb-ice-define-ib-ob-interfaces-controls-layering)
(define wb-ice-define-events-at-valve-opening-closing)
(define wb-ice-define-smoothing-events)
(define wb-ice-define-smoothing-controls)
(define wb-ice-define-piston-interfaces-layering)
(define wb-ice-define-dyn-mesh-settings-hybrid)
(define wb-ice-define-mesh-interface-for-piston-type1)
(define wb-ice-define-mesh-interface-for-piston-type2)
(define wb-ice-define-mesh-interface-for-piston-type3)

(define wb-ice-define-events-for-time-step-changes)
(define wb-ice-cal-act-for-remesh-cell-zones-during-smoothing)
(define wb-ice-set-time-step-change-events-new)
(define wb-ice-set-time-step-change-events-previous-support)
(define wb-ice-cal-act-for-plot-last-monitor-values)
(define wb-ice-define-events-for-case-data-solution-points)
(define wb-ice-define-in-cylinder-as-parameters)
(define wb-ice-bc-get-data-string)
(define wb-ice-bc-get-turb-string)
(define wb-ice-bc-get-temp-string)
(define wb-ice-bc-get-mixture-fraction-string)
(define wb-ice-bc-get-mixture-var-string)
(define wb-ice-bc-get-progress-var-string)
(define wb-ice-bc-get-inert-var-string)
(define wb-ice-bc-get-species-mf-string)
(define wb-ice-define-piston-type3-insert-delete-angle-events)
(define wb-ice-cal-act-for-adaptive-time-step)
;;ICE rpvars

(define wb-ice-rpvars-init)



(set! wb-ice-dyn-mesh-setup
  (lambda ()
    (format  "\n\n\t\t ___________Setting Up Dynamic Mesh _____________\t\n\n")  

    (if (string-ci=? combustion-simulation-type "sector")
      (begin
        (wb-ice-sector-case-setup)
      )
      (begin
        (wb-ice-define-initial-model-settings)
        (wb-ice-define-in-cylinder-settings)
        (wb-ice-define-non-conf-interface-rpvars)
        (if (string-ci=? hybrid/layering "l")
            (wb-ice-define-dyn-mesh-setup-layering) ;journal-l
            (wb-ice-define-dyn-mesh-setup-hybrid) ;journal-h
        )
        (wb-ice-plot-residual-events)
        (wb-ice-crevice-setup)
        (format  "\n\n\t\t ___________Dynamic Mesh Setup Done_____________\t\n\n") 
      )
    )
  )
)



;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; START OF READ_DATA
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(set! ice-panel-read-data
  (lambda ()

    (ice-read-data)
    (update-callback)
    ))
(set! ice-read-data

  (lambda ()
    (set! rpm                        (read-var ICDyMeshSetFile 'rpm))
    (set! dCA                        (read-var ICDyMeshSetFile 'crank_angle_step_size))
    (set! crank_radius               (read-var ICDyMeshSetFile 'crank_radius))
    (set! piston_pin_offset          (read-var ICDyMeshSetFile 'piston_pin_offset))
    (set! Connecting_rod_length      (read-var ICDyMeshSetFile 'connecting_rod_length))
    (set! Min_valve_lift             (read-var ICDyMeshSetFile 'min_valve_lift))
    (set! auto_activate_deactivate   (read-var ICDyMeshSetFile 'auto_activate_deactivate))
    (set! symmetryengine             (read-var ICDyMeshSetFile 'symmetry_engine))
    (set! point_on_symmetry          (read-var ICDyMeshSetFile 'point_on_symmetry))
    (set! symm_normal                (read-var ICDyMeshSetFile 'symm_normal))
    (set! hybrid/layering            (read-var ICDyMeshSetFile 'hybrid/layering))
    (set! hybrid                     (read-var ICDyMeshSetFile 'hybrid))
    (set! layering                   (read-var ICDyMeshSetFile 'layering))

    (set! conf/nonconf               (read-var ICDyMeshSetFile 'conf/nonconf))
    (set! conformal                  (read-var ICDyMeshSetFile 'conformal))
    (set! nonconformal               (read-var ICDyMeshSetFile 'nonconformal))

    (set! piston_type                (read-var ICDyMeshSetFile 'piston_type))
    (set! Piston_stroke_cutoff       (read-var ICDyMeshSetFile 'piston_stroke_cutoff))
    (set! cylinder_radius            (read-var ICDyMeshSetFile 'cylinder_radius))
    (set! ice_mesh_topology            (read-var ICDyMeshSetFile 'ice_mesh_topology))
    
    (set! withbowl                   (read-var ICDyMeshSetFile 'withbowl))
    (if  (read-var ICDyMeshSetFile 'start_crank_angle)
      (set! start-crank-angle          (read-var ICDyMeshSetFile 'start_crank_angle))
      )
    (if  (read-var ICDyMeshSetFile 'sector_angle)
      (set! sector_angle          (read-var ICDyMeshSetFile 'sector_angle))
      )
    (if (read-var ICDyMeshSetFile 'insert_angle)
      (set! insert_angle  (read-var ICDyMeshSetFile 'insert_angle))
      )
    (if (read-var ICDyMeshSetFile 'insert_angle_power_stroke)
      (set! insert_angle  (read-var ICDyMeshSetFile 'insert_angle_power_stroke))
      ) 

    (set! insert_angle_intake_stroke (read-var ICDyMeshSetFile 'insert_angle_intake_stroke))

    (if (read-var ICDyMeshSetFile 'delete_angle)
      (set! delete_angle (read-var ICDyMeshSetFile 'delete_angle))
      (if ( or (read-var ICDyMeshSetFile 'insert_angle_power_stroke) (read-var ICDyMeshSetFile 'insert_angle) ) 
	(set! delete_angle (- 360 insert_angle dCA))
	)
      )

    (set! cylinder_axis              (read-var ICDyMeshSetFile 'cylinder_axis))
    (set! cylinder_axis_origin       (read-var ICDyMeshSetFile 'cylinder_axis_origin))
    (set! no_of_valves               (read-var ICDyMeshSetFile 'no_of_valves))
    (set! V-adk no_of_valves)
    (set! setup-valve-list           (wb-ice-get-setup-valve-list))
    (if (rp-var-object 'ice/setup-valve-list) 
      (rpsetvar 'ice/setup-valve-list setup-valve-list))
    (set! inlet-outlet-bc-list           (read-var ICDyMeshSetFile 'inlet_outlet_bc_list))

    (set! patching-values           (read-var ICDyMeshSetFile 'patching_values))
    (set! valve-profile-path         (read-var ICDyMeshSetFile 'profile-path))
    (if (read-var ICDyMeshSetFile 'combustion_simulation_type) 	(set! combustion-simulation-type   (read-var ICDyMeshSetFile 'combustion_simulation_type)))

    (if (read-var ICDyMeshSetFile 'piston-full)
      (set! piston-full-prof (read-var ICDyMeshSetFile 'piston-full))
      )

    (if (read-var ICDyMeshSetFile 'piston-limit)
      (set! piston-limit-prof (read-var ICDyMeshSetFile 'piston-limit))
      )
    (if (not (rp-var-object 'ice/engine-piston-type))
      (rp-var-define 'ice/engine-piston-type 0 'number 1)
    )
    (rpsetvar 'ice/engine-piston-type piston_type)

    ;;this variable will control the layer size of dynamic zones
    (define wb-ice-mesh-settings-file (string-append (wb-get-dir) "/../ICE/ice-mesh-settings.txt"))
	   (if (read-var ICDyMeshSetFile 'reference_mesh_size)
      (begin
          (if (file-exists? wb-ice-mesh-settings-file)
              (set! reference-mesh-size   (read-var wb-ice-mesh-settings-file 'reference_mesh_size))
              (set! reference-mesh-size   (read-var ICDyMeshSetFile 'reference_mesh_size)))
          (set! vlayer-mesh-size      (* 0.4 reference-mesh-size))
          (set! chamber-mesh-size     (* 0.8 reference-mesh-size))
      )
    )



    ;;(set! monitor-def  (read-var solver-set-file 'monitor_def))
    (set! V-adk-old no_of_valves)
    (if (and valve-profile-path (file-exists? valve-profile-path))
      (begin
	(ti-menu-load-string (format #f "/file/read-profile  ~s " valve-profile-path))
	))
    )
  )
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; END OF READ_DATA
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; RELATED TO READ & WRITE FILE
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(set! read-var
  (lambda (par-file var-name)
    (let ((port (open-input-file par-file)))
      (let loop ((x (read port)) (y (read port)))
	(if (eof-object? x) (close-input-port port)
	  (if (equal? x var-name)
	    (begin (close-input-port port) y)
	    (loop (read port) (read port))))))
    )
  )

(define writedata
  (lambda ()
    (set! ICDyMeshSetFile (string-append "IC-motion-parameters" ".par"))
    (cx-file-dialog "data_files" "*.par" ICDyMeshSetFile applycallback_filedialog_wd #f)
    )
  )

(define readdata
  (lambda ()
    (set! ICDyMeshSetFile (string-append "IC-motion-parameters" ".par"))
    (cx-file-dialog "data_files" "*.par" ICDyMeshSetFile applycallback_filedialog_rd #f)
    )
  )

(define applycallback_filedialog_wd
  (lambda (widget name)
    (set! ICDyMeshSetFile name)

    (if (file-exists? ICDyMeshSetFile)

      (begin

	(let
	  (
	   (panel)
	   (t1)
	   (t2) 
	   )
	  (set! panel (cx-create-panel " Warning " 'modal #t    'ice-apply-call-back  write_data    ))


	  (let ((help (cx-get-panel-button-id panel "Help")))
	    (cx-hide-item help))


	  (set! t1 (cx-create-text panel (string-append "The file \"" ICDyMeshSetFile "\" already exists.")))
	  (set! t2 (cx-create-text panel "OK to overwrite? " 'below t1  ))

	  (cx-show-panel panel)
	  )
	)
      (write_data)
      )
    )
  )

(define applycallback_filedialog_rd
  (lambda (widget  name )
    (set! ICDyMeshSetFile name)
    (ice-panel-read-data)
    )
  )

;; JOURNAL FOR VALVE AND PISTON SETUP

(define wb-ice-define-dyn-mesh-setup-layering
  (lambda()
    (define final_list '())
    (set! final_list (wb-ice-dyn-mesh-zone-names-check-layering))

    (if (= 0 (length final_list))
      (begin
        (format  "\n\n\t\t ___________Zone Names Validation PASS _____________\t\n\n")  
        (format  "\n\n\t\t ___________Setting the Zone Types for layering _____________\t\n\n")  
        
        (wb-ice-define-dyn-mesh-settings-layering)
        
        (define valve_list setup-valve-list)
        (if (string-ci=? combustion-simulation-type "full_engine_ivc_to_evo")
          (set! valve_list (read-var ICDyMeshSetFile 'setup_valve_list))
        )
   
        (wb-ice-define-dynamic-settings-for-valves-layering valve_list)
    
        (ic-all-dz-update-cg-position) 
        ;this is to update all the values in the dynamic mesh zones column
        (wb-ice-define-ib-ob-interfaces)
        
        (wb-ice-define-ib-ob-interfaces-controls-layering)
        
        (wb-ice-define-events-at-valve-opening-closing)
        
        (wb-ice-define-smoothing-events)
       
        (wb-ice-define-smoothing-controls)
      
        (wb-ice-define-piston-interfaces-layering)
      )
      (begin
        (format "\n\n\t\t ___________  The following zones did not match, so Dynamic mesh setup is not successful. \n \t\t ___________ Check the zones and do the setup again _____________\t\n\n ~s\n" final_list )
      )
    )
  )
)

; Hybrid Setup Journal
(define wb-ice-define-dyn-mesh-setup-hybrid
  (lambda()
    (define final_list '())
    (if ice_mesh_topology
      (set! final_list (wb-ice-dyn-mesh-zone-names-check-hybrid)))

    (if (= 0 (length final_list))
      (begin
        (format  "\n\n\t\t ___________Zone Names Validation PASS _____________\t\n\n")  
        (wb-ice-define-dyn-mesh-settings-hybrid)
        ;;valve dynamic settings
        (wb-ice-define-dynamic-settings-for-valves-hybrid)
        (wb-ice-define-events-at-valve-opening-closing)
        (wb-ice-define-ib-ob-interfaces)
        (wb-ice-define-smoothing-events)
        ;activate spring smoothing on all shapes
        (wb-ice-define-smoothing-controls)
        (format  "\n\n\t\t ___________  Creating Grid Interfaces for Piston _____________\t\n\n")  
        (if (= piston_type 1)
          (wb-ice-define-mesh-interface-for-piston-type1))
        (if  (= piston_type 2)
          (wb-ice-define-mesh-interface-for-piston-type2))
        (if  (= piston_type 3)
          (wb-ice-define-mesh-interface-for-piston-type3))
      )
      (begin 
        (format "\n\n\t\t ___________  The following zones did not match, so Dynamic mesh setup is not successful.\n \t\t ___________ Check the zones and do the setup again_____________\t\n\n ~s\n" final_list )
      )
    )
  )
)

;;valve dynamic settings
(set! wb-ice-define-dynamic-settings-for-valves-hybrid
  (lambda ()
    (let
      (
        (ib_cell_height 1)
        (ob_cell_height 1)
        (smoothing-on #f)
        (min_scale 1)
        (max_scale 1)
        (ave_scale 1)
        (valve_name "")
        (profile_name "")
        (axis_x 0)
        (axis_y 0)
        (axis_z 0)
        (smoothing_string " no yes yes no no ")
        (zone_name "")
      )
      (for-each 
        (lambda (valve_list)
          (set! valve_name (list-ref valve_list 1))
          (format "\n\n\t\t ___________ Setting Dynamic Mesh Zones for ~s _____________\t\n\n" valve_name )
          (set! profile_name (list-ref valve_list 2))
          (set! axis_x (list-ref (list-ref valve_list 6) 0))
          (set! axis_y (list-ref (list-ref valve_list 6) 1))
          (set! axis_z (list-ref (list-ref valve_list 6) 2))
          
          (if (thread-name->id (string-append "fluid-" valve_name "-vlayer"))
            (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create fluid-" valve_name "-vlayer rigid-body " profile_name " " (number->string axis_x) " " (number->string axis_y) " " (number->string axis_z))))
          (if (thread-name->id (string-append "fluid-" valve_name "-ib"))
            (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create fluid-" valve_name "-ib rigid-body " profile_name " " (number->string axis_x) " " (number->string axis_y) " " (number->string axis_z))))
          (if (thread-name->id (string-append valve_name "-ib"))
            (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create " valve_name "-ib rigid-body " profile_name " no " (number->string axis_x) " " (number->string axis_y) " " (number->string axis_z) " ,, 0")))
          (if (thread-name->id (string-append valve_name "-ob"))
            (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create " valve_name "-ob rigid-body " profile_name " no " (number->string axis_x) " " (number->string axis_y) " " (number->string axis_z) " ,, 0")))
          (if (thread-name->id (string-append valve_name "-ch"))
            (begin
              (set! ave_scale (+ (* 0.5 (car (%get-min-max-length-scale-on-zone (thread-name->id  (string-append valve_name "-ch")) #f))) (* 0.5 (car (cdr (%get-min-max-length-scale-on-zone (thread-name->id  (string-append valve_name "-ch")) #f))))))
              (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create " valve_name "-ch rigid-body " profile_name " no " (number->string axis_x) " " (number->string axis_y) " " (number->string axis_z) " ,, " (number->string ave_scale) ))
            )
          )
          (if (thread-name->id (string-append "intf-int-" valve_name "-ib-fluid-ib"))
            (begin
              (set! ib_cell_height  (+ (* 0.5 (car (%get-min-max-length-scale-on-zone (thread-name->id  (string-append "intf-int-" valve_name "-ib-fluid-ib")) #f))) (* 0.5 (car (cdr (%get-min-max-length-scale-on-zone (thread-name->id  (string-append "intf-int-" valve_name "-ib-fluid-ib")) #f))))))
              (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create intf-int-" valve_name "-ib-fluid-ib stationary " (string-append "fluid-" valve_name  "-ib") " ," (number->string ib_cell_height)))
            )
          )
          (if (thread-name->id (string-append "intf-int-" valve_name "-ob-fluid-vlayer"))
            (begin
              (set! ob_cell_height  (+ (* 0.25 (car (%get-min-max-length-scale-on-zone (thread-name->id  (string-append "intf-int-" valve_name "-ob-fluid-vlayer")) #f))) (* 0.25 (car (cdr (%get-min-max-length-scale-on-zone (thread-name->id  (string-append "intf-int-" valve_name "-ob-fluid-vlayer")) #f))))))
              (if (assoc 'smoothing valve_list) 
                (set! smoothing-on (cadr (assoc 'smoothing valve_list))))
              (if smoothing-on
                (begin
                  (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create intf-int-" valve_name "-ob-fluid-vlayer stationary " (string-append "fluid-" valve_name  "-vlayer") " , 0 " ))
                  (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create " valve_name "-seat stationary ,, 0 " ))
                )
                (begin
                  (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create intf-int-" valve_name "-ob-fluid-vlayer stationary " (string-append "fluid-" valve_name  "-vlayer") " ," (number->string ob_cell_height)))
                  (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create " valve_name "-seat stationary ,, " (number->string ob_cell_height)))
                )
              )
            )
          )
          (if (thread-name->id (string-append "intf-" valve_name "-ob-fluid-ch"))
            (begin
              (set! ave_scale (caddr  (%get-min-max-length-scale-on-zone (thread-name->id  (string-append "intf-" valve_name "-ob-fluid-ch")) #f)))
              (set! min_scale (* 0.4 ave_scale))
              (set! max_scale (* 1.4 ave_scale))
              (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create intf-" valve_name "-ob-fluid-ch deforming cylinder " (number->string (list-ref valve_list 5)) " " (number->string (list-ref (list-ref valve_list 7) 0)) " " (number->string (list-ref (list-ref valve_list 7) 1)) " " (number->string (list-ref (list-ref valve_list 7) 2)) " " (number->string axis_x) " " (number->string axis_y) " " (number->string axis_z) " no no yes yes no " (number->string min_scale) " " (number->string max_scale) " 0.6"))
            )
          )

          (set! zone_name (string-append valve_name "-stem"))
          (if (thread-name->id zone_name)
            (if (not ice_mesh_topology)
              (begin
                (set! ave_scale (caddr  (%get-min-max-length-scale-on-zone (thread-name->id  zone_name) #f)))
                (set! min_scale (* 0.4 ave_scale))
                (set! max_scale (* 1.4 ave_scale))
                (set! smoothing_string " no no yes yes no ")
                (ti-menu-load-string (string-append  "/define/d-m zones c " zone_name " " " deforming faceted " smoothing_string " " (number->string min_scale) " "  (number->string max_scale) " 0.6"))
              )
            )
          )
   
          (ic-all-dz-update-cg-position) ;this is to update all the values in the dynamic mesh zones 
        )
        (rpgetvar 'ice/setup-valve-list)
      )
      (if (and symmetryengine (thread-name->id "symm-cyl-tri"))
        (begin
          (set! ave_scale (caddr  (%get-min-max-length-scale-on-zone (thread-name->id  (string-append "symm-cyl-tri")) #f)))
          (set! min_scale (* 0.4 ave_scale))
          (set! max_scale (* 1.4 ave_scale))
          (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create symm-cyl-tri deforming plane " (number->string (list-ref point_on_symmetry 0)) " " (number->string (list-ref point_on_symmetry 1)) " " (number->string (list-ref point_on_symmetry 2)) " " (number->string (list-ref symm_normal 0)) " "  (number->string (list-ref symm_normal 1)) " " (number->string (list-ref symm_normal 2)) " no no yes yes no " (number->string min_scale) " " (number->string max_scale) " 0.65"))
          (ti-menu-load-string "/def/bc/zt symm-cyl-tri symmetry")
        )
      )
    )
  )
)
;;Retrieve the zones from the valveId and set the smoothing events from the information in valveData
(set! set-smoothing-events
  (lambda (valveData)
    (let 
      (
        (valve_no (list-ref valveData 0))
        (valve_id (list-ref valveData 1))
        (smoothing-on #f)
        (valve_open (list-ref valveData 3))
        (smoothing_end 0)
        (smoothing_start 0)
        (event_list '())
        (event1 '())
        (event2 '())
        (event3 '())
        (pre_event_list (rpgetvar 'dynamesh/in-cyn/event-list))
      )
      (if (assoc 'smoothing valveData) 
        (set! smoothing-on (cadr (assoc 'smoothing valveData))))
      (if smoothing-on
        (begin
          (if (assoc 'end-valve-open-smoothing valveData) 
            (set! smoothing_end (cadr (assoc 'end-valve-open-smoothing valveData)))
            (set! smoothing-on #f))
          (if (assoc 'begin-valve-close-smoothing valveData) 
            (set! smoothing_start (cadr (assoc 'begin-valve-close-smoothing valveData)))
            (set! smoothing-on #f))
        )
      )
      (if smoothing-on
        (begin
          (set! event1 (list '(active . #t) (cons 'name (string-append "start-smoothing-at-" valve_id "-open")) (cons 'start valve_open) (list 'action 15 (format #f "(wb-ice-start-smoothing-at-valve-open ~s )" valve_no ))))
          (set! event2 (list '(active . #t) (cons 'name (string-append "stop-smoothing-after-" valve_id "-open")) (cons 'start smoothing_end) (list 'action 15 (format #f "(wb-ice-stop-smoothing-at-valve-open ~s ~s)" valve_no vlayer-mesh-size ))))
          (set! event3 (list '(active . #t) (cons 'name (string-append "start-smoothing-before-" valve_id "-close")) (cons 'start smoothing_start) (list 'action 15 (format #f "(wb-ice-start-smoothing-before-valve-close ~s )" valve_no))))
          (set! event_list (list-add event_list event1))
          (set! event_list (list-add event_list event2))
          (set! event_list (list-add event_list event3))
          (rpsetvar 'dynamesh/in-cyn/event-list (append pre_event_list event_list))
        )
      )
    )
  )
)



(set! define-deforming-zone-event
  (lambda (zone-id start-angle event-name)
    (let ((deform-event '()))

      ;(pp "in define deforming zone")
      (set! deform-event (list '(active . #t) (cons 'name event-name) (cons 'start start-angle) (list 'action 15 (format #f "define dynamic-mesh zones create ~s deforming , , , , no ~s ~s 0.6" zone-id  (* 0.4 (caddr (%get-min-max-length-scale-on-zone zone-id #f)))  (* 1.4 (caddr (%get-min-max-length-scale-on-zone zone-id #f))) ))))
      deform-event
      )

    )
  )

(set! delete-dynamic-zone-event
  (lambda (zone-id start-angle event-name)
    (let ((deform-event '()))
      ;(pp "in define deforming zone 2")

      (set! deform-event (list '(active . #t) (cons 'name event-name) (cons 'start start-angle) (list 'action 15 (format #f "define dynamic-mesh zones delete ~s" zone-id ))))
      deform-event
      )

    )
  )


(set! define-stationary-zone-event
  (lambda (zone-id start-angle event-name adjacent-zone cell-height)
    (let ((deform-event '()))
        (set! cell-height (string-append "(wb-ice-convert-units " (number->string cell-height) " " ")" ))
        

      ;(pp "in define deforming zone 3 3")
      (set! deform-event (list '(active . #t) (cons 'name event-name) (cons 'start start-angle) (list 'action 15 (format #f "define dynamic-mesh zones create ~s stationary ~s , ~s" zone-id  adjacent-zone (string->symbol cell-height) ))))
      deform-event
      )

    )
  )

(set! define-rigidbody-zone-event
  (lambda (zone-id start-angle event-name motion-profile motion-axis )
    (let ((deform-event '()))

      ;(pp "in define deforming zone 4")
      (set! deform-event (list '(active . #t) (cons 'name event-name) (cons 'start start-angle) (list 'action 15 (format #f "define dynamic-mesh zones create ~s rigid-body  ~s ~s ~s  ~s " zone-id  motion-profile (car motion-axis)  (cadr motion-axis)  (caddr motion-axis) ))))
      deform-event
      )

    )
  )

(set! read-valve-profile
  (lambda (valve-data)
    (let( (profile-name #f))
      (if (assoc 'profile-path valve-data) (set! profile-name (cadr (assoc 'profile-path valve-data))))
      (if  (and profile-name (file-exists? profile-name))

	(ti-menu-load-string (string-append  "/file/read-profile  " profile-name))
	)

      )))


(set! wb-ice-urf-setting

  (lambda ()
    (format  "\n\n\t\t ___________Setting Up URF_____________\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 14")
    (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")
    (ti-menu-load-string "/solve set discretization-scheme temp 1")

    (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 "/sol/set/limits 1000 5e7 150 2000 ,,,")
    (ti-menu-load-string "(rpsetvar 'max-iterations-per-step 50)")
    ;(ti-menu-load-string "/define d-m events e-e-f ice-event.event")
	
    )
  )
(set! wb-ice-create-planes

  (lambda ()
    (format  "\n\n\t\t ___________Defining User planes_____________\t\n\n")  
    (define post-plane)
    (set! post-plane  (read-var solver-set-file 'post_planes))
    (do ((i 0 (+ i 1))) ((= i (length post-plane)))

      (let 
	(
	 (point1_x (list-ref (list-ref (list-ref post-plane i) 1) 0))
	 (point1_y (list-ref (list-ref (list-ref post-plane i) 1) 1))
	 (point1_z (list-ref (list-ref (list-ref post-plane i) 1) 2))
	 (point2_x (list-ref (list-ref (list-ref post-plane i) 2) 0))
	 (point2_y (list-ref (list-ref (list-ref post-plane i) 2) 1))
	 (point2_z (list-ref (list-ref (list-ref post-plane i) 2) 2))
	 (point3_x (list-ref (list-ref (list-ref post-plane i) 3) 0))
	 (point3_y (list-ref (list-ref (list-ref post-plane i) 3) 1))
	 (point3_z (list-ref (list-ref (list-ref post-plane i) 3) 2))
	 (name (lowercase (list-ref (list-ref post-plane i) 0)))

	 ) 
	(ti-menu-load-string (format #f "/sur plane ~s ~s ~s ~s ~s ~s ~s ~s ~s ~s" (string->symbol name) point1_x point1_y point1_z point2_x point2_y point2_z point3_x point3_y point3_z))

	)
      )
    )
  )


(set! wb-ice-post-iter-post-plane-images-cold-flow
  (lambda()
    (do ((j 0 (+ j 1))) ((= j 2))
      (define setting-file)
      (if (= j 0) 
	(set! setting-file system-solver-set-file)
	)
      (if(= j 1)
	(set! setting-file user-solver-set-file)
	)
      (if (and (file-exists? setting-file) (read-var setting-file 'post_plane_images))
	(begin
	  (define post_plane_images)
	  (set! post_plane_images  (read-var setting-file 'post_plane_images))	
	  (do ((i 0 (+ i 1))) ((= i (length post_plane_images)))	
	    (let 
	      (
	       (name (cadr (assoc 'name (list-ref post_plane_images i))))
	       (surfaces (map lowercase (cadr (assoc 'surfaces (list-ref post_plane_images i)))))
	       (view (lowercase (cadr (assoc 'view (list-ref post_plane_images i)))))
	       (quantities (cadr(assoc 'quantities (list-ref post_plane_images i))))
	       (interval-tag (cadr (assoc 'interval-tag (list-ref post_plane_images i)))) 
	       (frequency (cadr (assoc 'frequency (assoc 'interval-tag (list-ref post_plane_images i)))))
	       (startCA (cadr (assoc 'start-CA (assoc 'interval-tag (list-ref post_plane_images i)))))
	       (endCA (cadr (assoc 'end-CA (assoc 'interval-tag (list-ref post_plane_images i)))))		       
	       )
	      (if  (or (not interval-tag) (and (not startCA) (not endCA) (not frequency))) 
		(wb-ice-capture-images name surfaces quantities view)
		)
	      )
	    )
	  )
	)
      )
    )
  )
(set! wb-ice-post-iter-post-plane-images-port-flow
  (lambda()
    (do ((j 0 (+ j 1))) ((= j 2))
      (define setting-file)
      (if (= j 0) 
	(set! setting-file system-solver-set-file)
	)
      (if(= j 1)
	(set! setting-file user-solver-set-file)
	)
      (if (and (file-exists? setting-file) (read-var setting-file 'post_plane_images))
	(begin
	  (define post_plane_images)
	  (set! post_plane_images  (read-var setting-file 'post_plane_images))	
	  (do ((i 0 (+ i 1))) ((= i (length post_plane_images)))	
	    (let 
	      (
	       (name (cadr (assoc 'name (list-ref post_plane_images i))))
	       (surfaces (map lowercase (cadr (assoc 'surfaces (list-ref post_plane_images i)))))
	       (view (lowercase (cadr (assoc 'view (list-ref post_plane_images i)))))
	       (quantities (cadr(assoc 'quantities (list-ref post_plane_images i))))
	       (interval-tag (cadr (assoc 'interval-tag (list-ref post_plane_images i)))) 
	       (frequency (cadr (assoc 'frequency (assoc 'interval-tag (list-ref post_plane_images i)))))
	       (start-iter (cadr (assoc 'start-iter (assoc 'interval-tag (list-ref post_plane_images i)))))
	       (end-iter (cadr (assoc 'end-iter (assoc 'interval-tag (list-ref post_plane_images i)))))	
	       )
		(if  (or (not interval-tag) (and (not start-iter) (not end-iter) (not frequency))) 
		(wb-ice-capture-images name surfaces quantities view)
		)
	      )
	    )
	  )
	)
      )
    )
  )

;if the user comes with case file prior to 15.0
(set! wb-ice-cold-flow-capture-mesh-images 
  (lambda(post-plane)
     (wb-ice-transient-flow-capture-mesh-images post-plane)
    )
  )

;for case file prior to version 15.0
(set! wb-ice-cal-act-cold-flow
  (lambda(images-name startCA endCA frequency surface-list quantity-list view)
    (wb-ice-cal-act-transient-flow images-name startCA endCA frequency surface-list quantity-list view)
    )
  )


(set! wb-ice-post-plane-images-for-transient-flow
  (lambda()
    (define post_plane_images)
    (set! post_plane_images  (read-var solver-set-file 'post_plane_images))	
    (do ((i 0 (+ i 1))) ((= i (length post_plane_images)))	
      (let 
	(
	 (name (cadr (assoc 'name (list-ref post_plane_images i))))
	 (surfaces (map lowercase (cadr (assoc 'surfaces (list-ref post_plane_images i)))))
	 (view (lowercase (cadr (assoc 'view (list-ref post_plane_images i)))))
	 (quantities (cadr(assoc 'quantities (list-ref post_plane_images i))))
	 (frequency (cadr (assoc 'frequency (assoc 'interval-tag (list-ref post_plane_images i)))))
	 (startCA (cadr (assoc 'start-CA  (assoc 'interval-tag (list-ref post_plane_images i)))))
	 (endCA (cadr (assoc 'end-CA (assoc 'interval-tag (list-ref post_plane_images i)))))	   
         (dpm #f)
	 (dpm-list '())
	 (injection '())
	(overlay '(overlay #f))
	(overlay-string "")
	 (s1 "time-step")
	 )
	 (if (assoc 'dpm (list-ref post_plane_images i))
	   (begin
	     (set! dpm #t)
	     (set! dpm-list (assoc 'dpm (list-ref post_plane_images i)))
	     (if (assoc 'injection dpm-list)
	       (set! injection (cadr (assoc 'injection dpm-list)))
	       )	   
	     )
	   )	
       (if (assoc 'overlay (list-ref post_plane_images i))
        (if (cadr (assoc 'overlay (list-ref post_plane_images i)))
          (set! overlay '(overlay #t))))

	 (if (and startCA endCA frequency)
	  (begin
	    (define surface-string "'(")
	    (do ((j 0 (+ j 1))) ((= j (length surfaces)))
	      (set! surface-string (string-append surface-string "\""(list-ref surfaces j)"\" ") )    
	      )
	    (set! surface-string (string-append surface-string ")") ) 

	    (define quantity-list "'( ")
	    (do ((j 0 (+ j 1))) ((= j (length quantities)))
	      (set! quantity-list (string-append quantity-list "\""(list-ref quantities j)"\" ") )    
	      )
	    (set! quantity-list (string-append quantity-list ")") )   


      (set! overlay-string 
        (if (cadr overlay)
          "'(overlay #t)"  "'(overlay #f)" ))
	    (define arg-list overlay-string)
	    (if dpm
	      (set! arg-list (string-append arg-list " '(dpm #t)") )  
	      )	    
	    (if (> (length injection) 0)
	      (begin
		(set! arg-list (string-append arg-list " '(injection ("))
		(do ((j 0 (+ j 1))) ((= j (length injection)))
		  (set! arg-list (string-append arg-list "\""(list-ref injection j)"\" ") )    
		  )
		(set! arg-list (string-append arg-list "))") )
		)
	      )



	    (define cal-act-string "")
	    (set! cal-act-string (string-append "(wb-ice-cal-act-transient-flow \""name"\" "(number->string startCA)" "(number->string endCA)" "(number->string frequency)" "surface-string" "quantity-list " \""view"\" "arg-list")"))

	      (ti-menu-load-string (format #f "/solv exe-comm a-e cal-act-for-~s 1 ~s ~s" (string->symbol name) s1 cal-act-string))
	      )
	    )
	  )
	)
      (if (string-ci=? userSettingFile? "no")
	(begin
	  (define post-plane-name-list "'(")
	  (define post-plane)
	  (set! post-plane  (read-var solver-set-file 'post_planes))
	  (do ((i 0 (+ i 1))) ((= i (length post-plane)))
	    (set! post-plane-name-list (string-append post-plane-name-list "\""(list-ref (list-ref post-plane i) 0)"\" ") )    
	    )
	  (set! post-plane-name-list (string-append post-plane-name-list ")") )
	  (define cal-act-string "")
	  (set! cal-act-string (string-append "(wb-ice-transient-flow-capture-mesh-images "post-plane-name-list")"))
	  (ti-menu-load-string (format #f "/solv exe-comm a-e capture-mesh-images 15 \"time-step\" ~s" cal-act-string))
	)
	)
      )
    )

(set! wb-ice-transientflow-create-default-images-on-planes

  (lambda ()
    (format  "\n\n\t\t ___________Defining Images on User planes_____________\t\n\n")  
    (if (read-var solver-set-file 'post_plane_images)
      (begin
	(wb-ice-post-plane-images-for-transient-flow)
	)
      (begin
	(define post-plane)
	(set! post-plane  (read-var solver-set-file 'post_planes))
	(do ((i 0 (+ i 1))) ((= i (length post-plane)))

	  (let* 
	    (

	     (name (list-ref (list-ref post-plane i) 0))
	     (s1 "time-step")
	     (s2 (format #f "/dis set cont surf ( ~s )" (string->symbol name)))
	     (s3 "/dis cont v-m , ,")
	     (s4 (format #f "/dis view rv ~s-view" (string->symbol name)))
	     (s5 (format #f "dis hc ~aice-anim-vel-mag-on-~s-%t.jpg" wb-ice-report-dir-path (string->symbol name)))
	     (s6 (format #f "/dis set ms (~s)" (string->symbol name)))
	     (s7 "/dis s-m , ,")
	     (s8 (format #f "dis hc ~aice-anim-mesh-on-~s-%t.jpg" wb-ice-report-dir-path (string->symbol name)))
       (s9 (format #f "/display/set/mesh-display-configuration classic"))
	     ) 
	    (ti-menu-load-string "/dis set pic driver jpeg")
	    (ti-menu-load-string (format #f "/dis set cont surf ~s ,"(string->symbol name)))
	    (ti-menu-load-string "/dis set cont filled-cont yes")
	    ;;(ti-menu-load-string "view auto")

	    (ti-menu-load-string (format #f  "/solv exe-comm a-e , 15 ~s ~s" s1 s2))
	    (ti-menu-load-string (format #f  "/solv exe-comm a-e , 15 ~s ~s" s1 s3))
	    (ti-menu-load-string (format #f  "/solv exe-comm a-e , 15 ~s ~s" s1 s4))
	    (ti-menu-load-string (format #f  "/solv exe-comm a-e , 15 ~s ~s" s1 s5))
	    (ti-menu-load-string (format #f  "/solv exe-comm a-e , 15 ~s ~s" s1 s6))
	    (ti-menu-load-string (format #f  "/solv exe-comm a-e , 15 ~s ~s" s1 s7))
	    (ti-menu-load-string (format #f  "/solv exe-comm a-e , 15 ~s ~s" s1 s9))
	    (ti-menu-load-string (format #f  "/solv exe-comm a-e , 15 ~s ~s" s1 s8))


	    )
	  )  
	)
      )
    )
  )

(set! wb-ice-post-plane-images-for-port-flow
  (lambda()
    (define post_plane_images)
    (set! post_plane_images  (read-var solver-set-file 'post_plane_images))	
    (do ((i 0 (+ i 1))) ((= i (length post_plane_images)))	
      (let 
        (
          (name (cadr (assoc 'name (list-ref post_plane_images i))))
          (surfaces (map lowercase (cadr (assoc 'surfaces (list-ref post_plane_images i)))))
          (view (lowercase (cadr (assoc 'view (list-ref post_plane_images i)))))
          (quantities (cadr(assoc 'quantities (list-ref post_plane_images i))))
          (frequency (cadr (assoc 'frequency (assoc 'interval-tag (list-ref post_plane_images i)))))
          (start-iter (cadr (assoc 'start-iter (assoc 'interval-tag (list-ref post_plane_images i)))))
          (end-iter (cadr (assoc 'end-iter (assoc 'interval-tag (list-ref post_plane_images i)))))	   
          (s1 "iteration")
          (overlay '(overlay #f))
          (overlay-string "")
          (arg-list "")
          (cal-act-string "")
        )
        (if (or (and start-iter end-iter frequency) (and (not start-iter) (not end-iter) frequency))
          (begin
            (define surface-string "'(")
            (do ((j 0 (+ j 1))) ((= j (length surfaces)))
              (set! surface-string (string-append surface-string "\""(list-ref surfaces j)"\" ") )    
            )
            (set! surface-string (string-append surface-string ")") ) 

            (define quantity-list "'( ")
            (do ((j 0 (+ j 1))) ((= j (length quantities)))
              (set! quantity-list (string-append quantity-list "\""(list-ref quantities j)"\" ") )    
            )
            (set! quantity-list (string-append quantity-list ")") )
            (if (assoc 'overlay (list-ref post_plane_images i))
              (if (cadr (assoc 'overlay (list-ref post_plane_images i)))
                (set! overlay '(overlay #t))))
            (set! overlay-string 
                  (if (cadr overlay)
                    "'(overlay #t)"  "'(overlay #f)" ))
            (set! arg-list overlay-string)          
            
            (if (and start-iter end-iter frequency) 
              (begin
                (set! cal-act-string (string-append "(wb-ice-cal-act-port-flow \""name"\" " (number->string start-iter) " " (number->string end-iter) " " (number->string frequency) " " surface-string " " quantity-list "\""view"\"" arg-list ")" ) )

                (ti-menu-load-string (format #f "/solv exe-comm a-e cal-act-for-~s 1 ~s ~s" (string->symbol name) s1 cal-act-string))
              )
            )
            (if (and (not start-iter) (not end-iter) frequency)
              (begin
                (set! cal-act-string (string-append "(wb-ice-cal-act-port-flow \""name"\" #f #f "(number->string frequency)" "surface-string" "quantity-list" \""view"\" "arg-list")" ))		  
                (ti-menu-load-string (format #f "/solv exe-comm a-e cal-act-for-~s ~s ~s ~s" (string->symbol name) (string->symbol (number->string frequency)) s1 cal-act-string))
              )
            )
          )
        )
      )
    )    
  )
)
(set! wb-ice-portflow-create-default-images-on-planes

  (lambda ()
    (format  "\n\n\t\t ___________Defining Images on User planes_____________\t\n\n")  
    (if  (read-var solver-set-file 'post_plane_images)
      (begin
	(wb-ice-post-plane-images-for-port-flow)
	)
      (begin 
	(define post-plane)
	(set! post-plane  (read-var solver-set-file 'post_planes))
	(do ((i 0 (+ i 1))) ((= i (length post-plane)))
	  (let* 
	    (
	     (name (list-ref (list-ref post-plane i) 0))
	     (s1 "iteration")
	     (s2 (format #f "/dis set cont surf ( ~s )" (string->symbol name)))
	     (s3 "/dis cont v-m , ,")
	     (s4 (format #f "/dis view rv ~s-view" (string->symbol name)))
	     (s5 (format #f "dis hc ~aice-anim-vel-mag-on-~s-%i.jpg" wb-ice-report-dir-path (string->symbol name)))
	     ) 
	    (ti-menu-load-string "/dis set pic driver jpeg")
	    (ti-menu-load-string (format #f "/dis set cont surf ~s ,"(string->symbol name)))
	    (ti-menu-load-string "/dis set cont filled-cont yes")

	    (ti-menu-load-string (format #f  "/solv exe-comm a-e , 50 ~s ~s" s1 s2))
	    (ti-menu-load-string (format #f  "/solv exe-comm a-e , 50 ~s ~s" s1 s3))
	    (ti-menu-load-string (format #f  "/solv exe-comm a-e , 50 ~s ~s" s1 s4))
	    (ti-menu-load-string (format #f  "/solv exe-comm a-e , 50 ~s ~s" s1 s5))
	    )
	  )
	  )      
	)
      )
  )
(set! wb-ice-create-view-for-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  (read-var ICDyMeshSetFile 'cylinder_axis))
	(define up-vectorx (car cyl-axis))
	(define up-vectory (cadr cyl-axis))
	(define up-vectorz (caddr cyl-axis))
	(let
	  (
	   (mod-cyl-axis (sqrt ( + (* (car cyl-axis) (car cyl-axis))  (* (cadr cyl-axis) (cadr cyl-axis))  (* (caddr cyl-axis) (caddr cyl-axis)))))
	   )
	  (set! up-vectorx (/ (car cyl-axis) mod-cyl-axis))
	  (set! up-vectory (/(cadr cyl-axis) mod-cyl-axis))
	  (set! up-vectorz (/(caddr cyl-axis) mod-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-cut-off .010)
	(if (read-var ICDyMeshSetFile 'piston_stroke_cutoff)
	  (set! piston-cut-off (read-var ICDyMeshSetFile 'piston_stroke_cutoff))
	  )	

	(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 (or (string-ci=? solution-type "cold-flow")  (string-ci=? solution-type "combustion"))
	  (begin
	    (if (and (> (length (map thread-name (get-threads-of-type 'pressure-inlet))) 0) (surface-name->id (list-ref (map thread-name (get-threads-of-type 'pressure-inlet)) 0)) )
	      (set! top-pt (list-ref (list-ref (surface-coordinates  (surface-name->id (list-ref (map thread-name (get-threads-of-type 'pressure-inlet)) 0)) ) 0)0) )
	      (if  (and (> (length (map thread-name (get-threads-of-type 'pressure-outlet))) 0) (surface-name->id (list-ref (map thread-name (get-threads-of-type 'pressure-outlet)) 0)))
		(set! top-pt (list-ref (list-ref (surface-coordinates  (surface-name->id (list-ref (map thread-name (get-threads-of-type 'pressure-outlet)) 0)) ) 0)0) )
		)
	      )
	    (set! ox  (+ ox (* piston-cut-off up-vectorx))) 
	    (set! oy  (+ oy (* piston-cut-off up-vectory)))
	    (set! oz  (+ oz (* piston-cut-off up-vectorz)))

	    ;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 (lowercase (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)
	     )

	    (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))))

	    (set! unit-x (/ x-coeff mod))
	    (set! unit-y (/ y-coeff mod))
	    (set! unit-z (/ z-coeff mod))

	    ;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 "port-flow")
	      (begin
		(if (string-ci=? (substring  name 0 9) "ice_swirl")	
		  (begin
		    (ti-menu-load-string (format #f "/dis view camera target ~s ~s ~s" x0 y0 z0))
		    (if sym-engine 
		      (ti-menu-load-string (format #f "/dis view camera u-v ~s ~s ~s" (car sym-norm)  (cadr sym-norm)   (caddr sym-norm)))
		      )

		    )
		  (begin
		    (ti-menu-load-string (format #f "/dis view camera target ~s ~s ~s" ox oy oz ))
		    (ti-menu-load-string (format #f "/dis view camera u-v ~s ~s ~s" up-vectorx up-vectory up-vectorz))

		    )
		  )
		(ti-menu-load-string "view auto")
		(ti-menu-load-string (format #f "/dis view s-v ~s-view" (string->symbol name)))
		)
	      )
	    (if (or (string-ci=? solution-type "cold-flow")  (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-postproc-monitors-default

  (lambda ()
    (pp "inside wb-ice-postproc-monitors-default")
    (define engine-type)
    (set! engine-type  (read-var ICDyMeshSetFile 'layering))
    (let 
      ((s1 "Volume-Average")
       (s2 "Mass-Average"))
      (if engine-type 
	;(pp "engine type is straight valve engine")
	(begin
	  (ti-menu-load-string (format #f "/sol/mon vol s-m pressure-mon1 ~s pressure fluid-ch-upper fluid-ch-lower , no no yes  pressure-mon1.out 1 no f-t" s1))
	  (ti-menu-load-string (format #f "/sol/mon vol s-m temp-mon1 ~s temperature fluid-ch-upper fluid-ch-lower , no no yes  pressure-mon1.out 1 no f-t" s2))
	  (ti-menu-load-string (string-append "/sol/mon vol s-m mesh-quality , cell-equivolume-skew fluid-ch-upper fluid-ch-lower , no no yes  mesh-mon.out 1 no f-t"))
	  )
	;(pp "Engine is canted valve engine")
	(begin 
	  (ti-menu-load-string (string-append "/sol/mon vol s-m mesh-quality , cell-equivolume-skew fluid-ch , no no yes  mesh-mon.out 1 no f-t"))
	  (ti-menu-load-string (format #f "/sol/mon vol s-m temp-mon1 ~s temperature fluid-ch , no no yes  temp-mon.out 1 no f-t" s2))
	  (ti-menu-load-string (format #f "/sol/mon vol s-m pressure-mon1 ~s pressure fluid-ch , no no yes  pressure-mon.out 1 no f-t" s1))
	  )

	)
      )
    )
  )
(set! wb-ice-residual-monitor-history
  (lambda()
    (format "\n\n\t\t ___________Setting Residual Monitor's Storage and Display History_____________\t\n\n")
    (ti-menu-load-string "/sol mon residual n-display 5000")
    (if (string-ci=? solution-type "port-flow")
      (ti-menu-load-string "/sol mon residual n-save 5000")
      (ti-menu-load-string "/sol mon residual n-save 50000")
      )
    )
  )
(set! wb-ice-postproc-monitors-user
  (lambda ()
    (let 
      (
        (monitor-def  (read-var solver-set-file 'monitor_def))
      )
      (if monitor-def
        (begin
          (format  "\n\n\t\t ___________Setting Up Monitors_____________\t\n\n")  
          (for-each
            (lambda (monitor)
              (let 
                (
                 (mon_name (list-ref monitor 0))
                 (report_type (list-ref monitor 2))
                 (field_var (list-ref monitor 3))
                 (zones_temp '())
                 (zones '())
                 (x_pos 0)
                 (y_pos 0)
                 (z_pos 0)
                 (radius 0.001)
                 (all_surfaces (inquire-surface-names))
                 (point_name "")
                 )
                ;special conditons when following are the report type, as for the following report type there does not exist any field variable
                (if (or (string-ci=? (list-ref monitor 2) "Mass Flow Rate") (string-ci=? (list-ref monitor 2) "Volume Flow Rate") 
                  (string-ci=? (list-ref monitor 2) "Mass") (string-ci=? (list-ref monitor 2) "Volume") )
                  (begin
                    (if (and (string? field_var) (string-ci=? field_var "null"))
                      (begin
                        (set! field_var "")
                        (set! zones_temp (list-ref monitor 4))
                      )
                      (begin
                        (set! field_var "")
                        (set! zones_temp (list-ref monitor 3))
                      )
                    )
                  )
                  (begin
                    (set! zones_temp (list-ref monitor 4))
                  )
                )
            
                (for-each
                  (lambda (zone_name)
                    (if (or (zone-name->id zone_name) (member zone_name (inquire-surface-names)) )
                      (set! zones (list-add zones zone_name))
                    )
                  ) zones_temp
                )
                    
                (if (string=? (list-ref monitor 1) "surface")
                  (begin
                    (if (rp-unsteady?)
                      (ti-menu-load-string (format #f "/sol/mon/surface s-m ~s ~s ~s ~s no no yes ~s 1 yes f-t" (string->symbol mon_name) report_type (string->symbol field_var) zones (string-append "ice-" mon_name ".out")))
                      (ti-menu-load-string (format #f "/sol/mon/surface s-m ~s ~s ~s ~s no no yes ~s 1" (string->symbol mon_name) report_type (string->symbol field_var) zones (string-append "ice-" mon_name ".out")))
                    )
                  )
                )
                (if (string=? (list-ref monitor 1) "volume")
                  (begin
                    (if (rp-unsteady?)
                      (ti-menu-load-string (format #f "/sol/mon/volume s-m ~s ~s ~s ~s no no yes ~s 1 yes f-t" (string->symbol mon_name) report_type (string->symbol field_var) zones (string-append "ice-" mon_name ".out")))
                      (ti-menu-load-string (format #f "/sol/mon/volume s-m ~s ~s ~s ~s no no yes ~s 1" (string->symbol mon_name) report_type (string->symbol field_var) zones (string-append "ice-" mon_name ".out")))
                    )
                  )
                )
                (if (string=? (list-ref monitor 1) "probe")
                  (begin
                    (set! x_pos (cadr (assoc 'x zones_temp )))
                    (set! y_pos (cadr (assoc 'y zones_temp )))
                    (set! z_pos (cadr (assoc 'z zones_temp )))
                    (set! radius (cadr (assoc 'radius zones_temp )))
                    (set! point_name (string-append "point-" mon_name))
                    (if (not (member (string->symbol point_name) all_surfaces))
                      (if (= radius 0)
                        (ti-menu-load-string (format #f "/surface/point-surface ~a ~a ~a ~a \n" point_name x_pos y_pos z_pos))
                        (ti-menu-load-string (format #f "/surface/sphere-slice ~a ~a ~a ~a ~a \n" point_name x_pos y_pos z_pos radius))
                      )
                      (format " \n\n surface with name ~a already exist, so point surface is created \n\n" point_name)
                    )
                    (set! all_surfaces (inquire-surface-names)) 
                    (if (member (string->symbol point_name) all_surfaces) 
                      (begin
                        (if (rp-unsteady?)
                          (ti-menu-load-string (format #f "/sol/mon/surface s-m ~s ~s ~s ~s () no no yes ~s 1 yes f-t" (string->symbol mon_name) report_type (string->symbol field_var) (string->symbol point_name) (string-append "ice-" mon_name ".out")))
                          (ti-menu-load-string (format #f "/sol/mon/surface s-m ~s ~s ~s ~s  () no no yes ~s 1" (string->symbol mon_name) report_type (string->symbol field_var) (string->symbol point_name) (string-append "ice-" mon_name ".out")))
                        )
                      )
                      (format " \n\nPoint surface ~a does not exist, so no point-monitor is created. Check the x, y, z values \n\n" point_name)
                    )
                  )
                )
                (format "\n\n")
              )
            ) monitor-def
          )
          (wb-ice-list-monitors-to-file (string-append wb-ice-report-dir-path "ice-monitors"))
        )
      )
    )
  )
)

(set! wb-ice-coldflow-initialization

  (lambda ()
    (format  "\n\n\t\t ___________Initializing the Flow as Cold 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 

	(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)))
	     )
	    (ti-menu-load-string (format #f "/solve init set-defa ~s ~s \n" (string->symbol init-var) init-value) )
	    )
	  )
	)
      )
    (if (not (data-valid?))
      (ti-menu-load-string "/solve init init")
      )
    (begin
      (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  ~s " patch-parts1 (string->symbol patch-variable) patch-value))
	    ))
	))

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


    )
  )
(set! wb-ice-portflow-initialization
  (lambda ()
    (format  "\n\n\t\t ___________Initializing the FLow_____________\t\n\n")  
	
    (ti-menu-load-string "/solve/initialize/initialize-flow")
    (if (read-var solver-set-file 'initialize-fmg?)
      (begin
        (format  "\n\n\t\t ___________Doing FMG initiallization_____________\t\n\n")
        (ti-menu-load-string "/solve/initialize/set-fmg-initialization , , , , , , , , , , , , yes")
        (ti-menu-load-string "/solve/initialize/fmg-initialization yes")
      )
    )
  )
)  

(set! wb-ic-update-time-steps
  (lambda ()

    (rpsetvar 'number-of-time-steps 1)
    (ti-menu-load-string "/solve it 0")
    )
  )
(set! wb-ice-swirl-data

  (lambda ()
    (define swirl-data)
    (define tumbx1 0)
    (define tumbx2 0)
    (define tumbx3 0)	  
    (define tumby1 0)
    (define tumby2 0)
    (define tumby3 0)
    (define b1 (car cylinder_axis))
    (define b2 (cadr cylinder_axis))
    (define b3 (caddr cylinder_axis))


    (set! swirl-data (read-var solver-set-file 'swirl_data))
    (set! cylinder_axis_origin       (read-var ICDyMeshSetFile 'cylinder_axis_origin))
    (set! setup-valve-list           (wb-ice-get-setup-valve-list))
    ;(set! valve_origin (list-ref (list-ref setup-valve-list 0) 7) )
    (if (read-var icdymeshsetfile 'symmetry_engine)
      (begin
	(set! tumbx1 (car (read-var icdymeshsetfile 'symm_normal)))
	(set! tumbx2 (cadr (read-var icdymeshsetfile 'symm_normal)))
	(set! tumbx3 (caddr (read-var icdymeshsetfile 'symm_normal)))
	)
      (begin 
	(define invalve_origin (list 0 0 0))
	(define invalve_count 0)
	(define invalve_origin_x 0)
	(define invalve_origin_y 0)
	(define invalve_origin_z 0)
	(define exvalve_origin (list 0 0 0))
	(define exvalve_count 0)
	(define exvalve_origin_x 0)
	(define exvalve_origin_y 0)
	(define exvalve_origin_z 0)	
	(define valve_name)
	(set! valve-value 0)
	(do ((valve-value 0 (+ valve-value 1))) ((= valve-value (length setup-valve-list)))
	  (set! valve_name (list-ref (list-ref setup-valve-list valve-value) 2) )
	  (if (string=? (substring valve_name 0 2) "in")
	    (begin
	       (set! invalve_origin (list-ref (list-ref setup-valve-list valve-value) 7) )
	       (set! invalve_origin_x (+ invalve_origin_x (car invalve_origin)))
	       (set! invalve_origin_y (+ invalve_origin_y (cadr invalve_origin)))
	       (set! invalve_origin_z (+ invalve_origin_z (cadr invalve_origin)))		  
	       (set! invalve_count (+ invalve_count 1))
	       )
	      )
	    (if (string=? (substring valve_name 0 2) "ex")
	     (begin
		    (set! exvalve_origin (list-ref (list-ref setup-valve-list valve-value) 7) )
		    (set! exvalve_origin_x (+ exvalve_origin_x (car exvalve_origin)))
		    (set! exvalve_origin_y (+ exvalve_origin_y (cadr exvalve_origin)))
		    (set! exvalve_origin_z (+ exvalve_origin_z (cadr exvalve_origin)))		  
		    (set! exvalve_count (+ exvalve_count 1))
	     )
        )	  
	  )
	(if (> invalve_count 0)
	  (begin
	    (set! invalve_origin_x (/ invalve_origin_x invalve_count))
	    (set! invalve_origin_y (/ invalve_origin_y invalve_count))
	    (set! invalve_origin_z (/ invalve_origin_z invalve_count))
	    )
	  )	 
	(if (> exvalve_count 0)
	  (begin
	    (set! exvalve_origin_x (/ exvalve_origin_x exvalve_count))
	    (set! exvalve_origin_y (/ exvalve_origin_y exvalve_count))
	    (set! exvalve_origin_z (/ exvalve_origin_z exvalve_count))
	    )
	  )	
	(define unitx 0)
	(define unity 0)
	(define unitz 0)
	(define unitm 0)
	(if (and (> invalve_count 0) (> exvalve_count 0))
	  (begin
	    (set! unitx  (- invalve_origin_x exvalve_origin_x))
	    (set! unity  (- invalve_origin_y exvalve_origin_y))
	    (set! unitz  (- invalve_origin_z exvalve_origin_z))
	    (set! unitm (sqrt (+ (* unitx unitx) (* unity unity) (* unitz unitz))))		 
	    )
	  ) 	
	(if (and (> invalve_count 0) (= exvalve_count 0))
	  (begin
	    (set! unitx  (- invalve_origin_x (car cylinder_axis_origin)))
	    (set! unity  (- invalve_origin_y (cadr cylinder_axis_origin)))
	    (set! unitz  (- invalve_origin_z (caddr cylinder_axis_origin)))	
	    (set! unitm (sqrt (+ (* unitx unitx) (* unity unity) (* unitz unitz))))
	    )
	  ) 		  
	(if (and (= invalve_count 0) (> exvalve_count 0))
	  (begin
	    (set! unitx  (- exvalve_origin_x (car cylinder_axis_origin)))
	    (set! unity  (- exvalve_origin_y (cadr cylinder_axis_origin)))
	    (set! unitz  (- exvalve_origin_z (caddr cylinder_axis_origin)))	
	    (set! unitm (sqrt (+ (* unitx unitx) (* unity unity) (* unitz unitz))))
	    )
	  ) 		  
	(let* (
	       ;(unitx (- (car valve_origin) (car cylinder_axis_origin)))
	       ;(unity (- (cadr valve_origin) (cadr cylinder_axis_origin)))
	       ;(unitz (- (caddr valve_origin) (caddr cylinder_axis_origin)))

	       ( a1 (/ unitx unitm))
	       ( a2 (/ unity unitm))
	   ( a3 (/ unitz unitm))
	   ( c1 (- (* a2 b3) (* a3 b2)))
	   ( c2 (- (* a3 b1) (* a1 b3)))
	   ( c3 (- (* a1 b2) (* a2 b1)))
	   (unitm1 (sqrt (+ (* c1 c1) (* c2 c2) (* c3 c3))))
	   )
        (set! unitx (/ c1 unitm1))
        (set! unity (/ c2 unitm1))
        (set! unitz (/ c3 unitm1))
	   )
       (set! tumbx1 unitx)
       (set! tumbx2 unity)
       (set! tumbx3 unitz)	
     )
    )	  
	(set! tumby1 (- (* b2 tumbx3) (* b3 tumbx2)))
	(set! tumby2 (- (* b3 tumbx1) (* b1 tumbx3)))
	(set! tumby3 (- (* b1 tumbx2) (* b2 tumbx1)))
	(define unit1 0)
	(set! unit1 (sqrt (+ (* tumby1 tumby1) (* tumby2 tumby2) (* tumby3 tumby3))))
	(set! tumby1 (/ tumby1 unit1))
	(set! tumby2 (/ tumby2 unit1))
	(set! tumby3 (/ tumby3 unit1))
	(ti-menu-load-string (format #f "/def d-m c ico yes 1 ~s ice-incylinder-output.txt cg ~s ~s ~s ~s ~s ~s ~s ~s ~s" swirl-data (car cylinder_axis) (cadr cylinder_axis) (caddr cylinder_axis) tumbx1 tumbx2 tumbx3 tumby1 tumby2 tumby3))

    )
  )
(set! wb-ice-inlet-outlet-bc

  (lambda ()
    (set! inlet-outlet-bc-list           (read-var solver-set-file 'inlet_outlet_bc_list))
    (if inlet-outlet-bc-list
      (begin
	(format  "\n\n\t\t ___________Setting Up Inlet and Outlet BC_____________\t\n\n")  
	(do ((i 0 (+ i 1))) ((= i (length inlet-outlet-bc-list)))
	  (let
	    (
	     (value 0)
	     (temp 0)
	     (turb1 1)
	     (turb2 5)
	     (turbtype "int-hyd-dia")
	     (zonename #f)
	     (data-profile? "no")
	     (temp-profile? "no")
	     (data-profile-name "")
	     (data-profile-field "")
	     (temp-profile-name "")
	     (temp-profile-field "")
	     (temp-string #f)
	     (data-string #f)
	     (turb-string #f)

	     ;for DUFL model
	     (mean-mixture-fraction-profile? "no")
	     (mean-mixture-fraction-profile-name "")
	     (mean-mixture-fraction-profile-field "")
	     (mean-mixture-fraction-string " no 0 ")
	     (mean-mixture-fraction-value 0)

	     (mixture-fraction-var-profile? "no")
	     (mixture-fraction-var-profile-name "")
	     (mixture-fraction-var-profile-field "")
	     (mixture-fraction-var-string " no 0 ")
	     (mixture-fraction-var-value 0)
	     ;for partially-premixed model
	     (progress-variable-profile? "no")
	     (progress-variable-profile-name "")
	     (progress-variable-profile-field "")
	     (progress-variable-string " no 0")
	     (progress-variable-value 0)
       
         (inert-stream-profile? "no")
	     (inert-stream-profile-name "")
	     (inert-stream-profile-field "")
	     (inert-stream-string "")
	     (inert-stream-value 0)

	     ;for LFR model
	     (ice '())
	     (species-mf "")
	     (mf 0)
	     (l '())
	     (negative-mass-flow-string "")


	     )

	    (if (assoc 'zone (list-ref inlet-outlet-bc-list i))
	      (set! zonename  (cadr (assoc 'zone (list-ref inlet-outlet-bc-list i))))
	      )

	    (if (assoc 'data-profile (list-ref inlet-outlet-bc-list i))
	      (begin
		(set! data-profile? (cadr(assoc 'data-profile (list-ref inlet-outlet-bc-list i))))
		(if (string-ci=? data-profile? "yes")
		  (begin

		    (set! data-profile-name (caddr (assoc 'data-profile (list-ref inlet-outlet-bc-list i))))
		    (set! data-profile-field (cadddr (assoc 'data-profile (list-ref inlet-outlet-bc-list i))))
		    (set! data-string (string-append " yes no \"" data-profile-name "\" \"" data-profile-field "\" " ))
		    )
		  (begin 
		    (set! value (caddr (assoc 'data-profile (list-ref inlet-outlet-bc-list i))))
		    (set! data-string (string-append " no " (number->string value) " " ))
		    (if (string=? (cadr (assoc 'type (list-ref inlet-outlet-bc-list i))) "mass-flow-inlet")
		      (set! data-string (string-append " no "  (number->string (abs value)) " " ))
		      )
		    )

		  )
		)
	      )


	    (if  (assoc 'turbulance (list-ref inlet-outlet-bc-list i))
	      (begin
		(set! turbtype (cadr (assoc 'turbulance (list-ref inlet-outlet-bc-list i))))
		(set! turb1 (caddr (assoc 'turbulance (list-ref inlet-outlet-bc-list i))))
		(set! turb2 (cadddr (assoc 'turbulance (list-ref inlet-outlet-bc-list i))))
		(if (string-ci=? turbtype "int-vis-ratio")
		  (set! turb-string  (string-append " no no yes " (number->string turb1) " " (number->string turb2) " " ))
		  (set! turb-string  (string-append " no no no yes " (number->string turb1) " " (number->string turb2) " " ))
		  )
		)
	      )

	    (if (assoc 'temperature-profile (list-ref inlet-outlet-bc-list i))
	      (begin 
		(set! temp-profile? (cadr (assoc 'temperature-profile (list-ref inlet-outlet-bc-list i))))
		(if (string-ci=? temp-profile? "yes")
		  (begin
		    (set! temp-profile-name (caddr (assoc 'temperature-profile (list-ref inlet-outlet-bc-list i))))
		    (set! temp-profile-field (cadddr (assoc 'temperature-profile (list-ref inlet-outlet-bc-list i))))
		    (set! temp-string (string-append " yes no \"" temp-profile-name "\" \"" temp-profile-field "\" " ))

		    )
		  (begin 
		    (set! temp (caddr (assoc 'temperature-profile (list-ref inlet-outlet-bc-list i))))
		    (set! temp-string (string-append " no " (number->string temp) " " ))
		    ))

		)
	      )
	    (if (assoc 'mean-mixture-fraction (list-ref inlet-outlet-bc-list i))
	      (begin 
		(set! mean-mixture-fraction-profile? (cadr (assoc 'mean-mixture-fraction (list-ref inlet-outlet-bc-list i))))
		(if (string-ci=? mean-mixture-fraction-profile? "yes")
		  (begin
		    (set! mean-mixture-fraction-profile-name (caddr (assoc 'mean-mixture-fraction (list-ref inlet-outlet-bc-list i))))
		    (set! mean-mixture-fraction-profile-field (cadddr (assoc 'mean-mixture-fraction (list-ref inlet-outlet-bc-list i))))
		    (set! mean-mixture-fraction-string (string-append " yes no \"" mean-mixture-fraction-profile-name "\" \"" mean-mixture-fraction-profile-field "\" " ))

		    )
		  (begin 
		    (set! mean-mixture-fraction-value (caddr (assoc 'mean-mixture-fraction (list-ref inlet-outlet-bc-list i))))
		    (set! mean-mixture-fraction-string (string-append " no " (number->string mean-mixture-fraction-value) " " ))
		    ))

		)
	      )

	    (if (assoc 'mixture-fraction-var (list-ref inlet-outlet-bc-list i))
	      (begin 
		(set! mixture-fraction-var-profile? (cadr (assoc 'mixture-fraction-var (list-ref inlet-outlet-bc-list i))))
		(if (string-ci=? mixture-fraction-var-profile? "yes")
		  (begin
		    (set! mixture-fraction-var-profile-name (caddr (assoc 'mixture-fraction-var (list-ref inlet-outlet-bc-list i))))
		    (set! mixture-fraction-var-profile-field (cadddr (assoc 'mixture-fraction-var (list-ref inlet-outlet-bc-list i))))
		    (set! mixture-fraction-var-string (string-append " yes no \"" mixture-fraction-var-profile-name "\" \"" mixture-fraction-var-profile-field "\" " ))

		    )
		  (begin 
		    (set! mixture-fraction-var-value (caddr (assoc 'mixture-fraction-var (list-ref inlet-outlet-bc-list i))))
		    (set! mixture-fraction-var-string (string-append " no " (number->string mixture-fraction-var-value) " " ))
		    ))

		)
	      )

	    (if (assoc 'progress-variable (list-ref inlet-outlet-bc-list i))
	      (begin 
		(set! progress-variable-profile? (cadr (assoc 'progress-variable (list-ref inlet-outlet-bc-list i))))
		(if (string-ci=? progress-variable-profile? "yes")
		  (begin
		    (set! progress-variable-profile-name (caddr (assoc 'progress-variable (list-ref inlet-outlet-bc-list i))))
		    (set! progress-variable-profile-field (cadddr (assoc 'progress-variable (list-ref inlet-outlet-bc-list i))))
		    (set! progress-variable-string (string-append " yes no \"" progress-variable-profile-name "\" \"" progress-variable-profile-field "\" " ))

		    )
		  (begin 
		    (set! progress-variable-value (caddr (assoc 'progress-variable (list-ref inlet-outlet-bc-list i))))
		    (set! progress-variable-string (string-append " no " (number->string progress-variable-value) " " ))
		    ))

		)
	      )
        
    (if (assoc 'inert-stream (list-ref inlet-outlet-bc-list i))
	      (begin 
		(set! inert-stream-profile? (cadr (assoc 'inert-stream (list-ref inlet-outlet-bc-list i))))
		(if (string-ci=? inert-stream-profile? "yes")
		  (begin
		    (set! inert-stream-profile-name (caddr (assoc 'inert-stream (list-ref inlet-outlet-bc-list i))))
		    (set! inert-stream-profile-field (cadddr (assoc 'inert-stream (list-ref inlet-outlet-bc-list i))))
		    (set! inert-stream-string (string-append " yes no \"" inert-stream-profile-name "\" \"" inert-stream-profile-field "\" " ))

		    )
		  (begin 
		    (set! inert-stream-value (caddr (assoc 'inert-stream (list-ref inlet-outlet-bc-list i))))
		    (set! inert-stream-string (string-append " no " (number->string inert-stream-value) " " ))
		    ))

		)
	      )

	    (if (assoc 'species-mass-fraction (list-ref inlet-outlet-bc-list i))
	      (begin 
		(set! l (inquire-species-names) )
		(set! ice (cdr (assoc 'species-mass-fraction (list-ref inlet-outlet-bc-list i))))
		(do ((i 0 (+ i 1))) ((>= i (- (length l) 1)))
		  (if (assoc (list-ref l i) ice)
		    (set! mf (cadr (assoc (list-ref l i) ice)))
		    (set! mf 0)
		    )
		  (set! species-mf (string-append species-mf " no"  " " (number->string mf)))
		  )
		)
	      (begin
         (if (string-ci=? solution-type "combustion")
           (begin 
		           (set! l (inquire-species-names) )
		           (do ((i 0 (+ i 1))) ((>= i (- (length l) 1)))
		                 (set! species-mf (string-append species-mf " no 0" ))
		            )
            )
          )
	      	)
	      )


	    (format  "\n")
	    (if (and (zone-name->id zonename) data-string temp-string turb-string)
	      (begin
		(if (string=? (cadr (assoc 'type (list-ref inlet-outlet-bc-list i))) "pressure-inlet")
		  (begin 
		    (ti-menu-load-string (string-append "/def b-c m-z z-t " zonename " p-i"))
		    (format "\n")
		    (if (string-ci=? solution-type "combustion")
		      (begin
			(if (string-ci=? ice-combustion-model "CI-DUFL")
			  (ti-menu-load-string (string-append "/def b-c p-i " zonename  " yes " data-string " no 0 " temp-string " no yes " turb-string mean-mixture-fraction-string mixture-fraction-var-string inert-stream-string ))
			  )
			(if (string-ci=? ice-combustion-model "SI-Partially-Premixed")
			  (ti-menu-load-string (string-append "/def b-c p-i " zonename  " yes " data-string " no 0 " temp-string " no yes " turb-string mean-mixture-fraction-string mixture-fraction-var-string progress-variable-string inert-stream-string " no" ))
			  )
			(if (or (string-ci=? ice-combustion-model "CI-LFR") (string-ci=? ice-combustion-model "SI-LFR"))
			  (ti-menu-load-string (string-append "/def b-c p-i " zonename  " yes " data-string " no 0 " temp-string " no yes " turb-string " no" species-mf " no no"  ))

			  )
			)
		      )
		    (if (or (string-ci=? solution-type "cold-flow")  (string-ci=? solution-type "port-flow")) 
		      (ti-menu-load-string (string-append "/def b-c p-i " zonename  " yes " data-string " no 0 " temp-string " no yes " turb-string ))
		      )
		    (format "\n")
		    )
		  )

		(if (string=? (cadr (assoc 'type (list-ref inlet-outlet-bc-list i))) "pressure-outlet")
		  (begin 
		    (ti-menu-load-string (string-append "/def b-c m-z z-t " zonename " p-o"))
		    (if (or (string-ci=? solution-type "cold-flow")  (string-ci=? solution-type "port-flow")) 
		      (ti-menu-load-string (string-append "/def b-c p-o " zonename data-string  temp-string " no yes " turb-string " no no no " ))
		      )
		    (if (string-ci=? solution-type "combustion")
		      (begin
			(if (string-ci=? ice-combustion-model "CI-DUFL")
			  (ti-menu-load-string (string-append "/def b-c p-o " zonename data-string  temp-string " no yes " turb-string mean-mixture-fraction-string mixture-fraction-var-string inert-stream-string  " no no no " ))
			  )
			(if (or (string-ci=? ice-combustion-model "CI-LFR") (string-ci=? ice-combustion-model "SI-LFR"))
			  (ti-menu-load-string (string-append "/def b-c p-o " zonename data-string  temp-string " no yes " turb-string " no" species-mf " no no no no no " ))

			  )
			(if (string-ci=? ice-combustion-model "SI-Partially-Premixed")
			  (ti-menu-load-string (string-append "/def b-c p-o " zonename data-string  temp-string " no yes " turb-string mean-mixture-fraction-string mixture-fraction-var-string progress-variable-string inert-stream-string " no no no no " ))
			  )
			)
		      )
		    )
		  )

		(if (string=? (cadr (assoc 'type (list-ref inlet-outlet-bc-list i))) "mass-flow-inlet")
      
		  (begin
		    (if (< value 0)
		      (set! negative-mass-flow-string "no 0 no no yes")
		      (set! negative-mass-flow-string "no 0 no yes")
		      )
		    (ti-menu-load-string (string-append "/def b-c m-z z-t " zonename " mfi"))
		    (format  "\n")
		    (if (or (string-ci=? solution-type "cold-flow")  (string-ci=? solution-type "port-flow")) 
		      (ti-menu-load-string (string-append "/def b-c mfi " zonename " yes yes " data-string temp-string  negative-mass-flow-string  turb-string ))
		      )
		    (if (string-ci=? solution-type "combustion")
		      (begin
			(if (string-ci=? ice-combustion-model "CI-DUFL")
			  (ti-menu-load-string (string-append "/def b-c mfi " zonename " yes yes " data-string temp-string negative-mass-flow-string turb-string mean-mixture-fraction-string mixture-fraction-var-string ))
			  )
			(if (or (string-ci=? ice-combustion-model "CI-LFR") (string-ci=? ice-combustion-model "SI-LFR"))
			  (ti-menu-load-string (string-append "/def b-c mfi " zonename " yes yes " data-string temp-string negative-mass-flow-string turb-string " no" species-mf " no no" ))
			  )
			(if (string-ci=? ice-combustion-model "SI-Partially-Premixed")
			  (ti-menu-load-string (string-append "/def b-c mfi " zonename " yes yes " data-string temp-string negative-mass-flow-string turb-string progress-variable-string mean-mixture-fraction-string mixture-fraction-var-string " no" ))
			  )

			(format  "\n")
			)
		      )
		    )
		  )
		)
	      (format  "\n\n--Warning: Unable to setup BC for Zone ~s ---\n\n" zonename)
	      )

	    )
	  )
	)
      )

    ;;(ti-menu-load-string (format #f  "/file wbc ice-bc_rpm"))
    )
  )
(set! wb-ice-inlet-outlet-bc-parametric
  (lambda ()
    (if (rp-var-object 'ice/inlet_outlet_bc_list_parametric)
      (set! inlet-outlet-bc-list           (rpgetvar 'ice/inlet_outlet_bc_list_parametric)))
      (if inlet-outlet-bc-list
        (begin
          (do ((i 0 (+ i 1))) ((= i (length inlet-outlet-bc-list)))
            (let
              (
                (data_parametric #f)
                (temprature_parametric #f)
                (param_present "")
                (zonename "")
                (temp-string #f)
                (data-string #f)
                (turb-string #f)
                (mean-mixture-fraction-string " no 0 ")
                (mixture-fraction-var-string " no 0 ")
                (progress-variable-string " no 0")
                (inert-stream-string "")
                (species-mf "")
                (supersonic_pr_string " no 0 ")
                (dir_string " no yes")
                (abs_string " yes ")
                (avg_pr_string " no no no ")
                (parameter #f)
                (value 0)
                (bc_list (list-ref inlet-outlet-bc-list i))
              )
              (if (assoc 'parameter (list-ref inlet-outlet-bc-list i))
                (set! parameter #t))
              (if parameter
                (begin
                  (set! supersonic_pr_string " no no 0 ")
                  (if (assoc 'data-parameter (assoc 'parameter (list-ref inlet-outlet-bc-list i)))
                    (begin
                      (set! data_parametric #t)
                      ;(set! data_par_name (cadr (assoc 'data-parameter (assoc 'parameter (list-ref inlet-outlet-bc-list i)))))
                    )
                  )
                  (if (assoc 'temperature-parameter (assoc 'parameter (list-ref inlet-outlet-bc-list i)))
                    (begin
                      (set!  temprature_parametric #t)
                      ;(set!  temp_par_name (cadr (assoc 'temperature-parameter (assoc 'parameter (list-ref inlet-outlet-bc-list i)))))
                    )
                  )
                  (ti-menu-load-string (format #f  "/def parameters enable-in-TUI?  yes\n"))
                  ;(format "\ndata parameteric : ~a" data_parametric)
                  ;(format "\ntemprature_parametric  : ~a\n" temprature_parametric)
                  (if (pair? (get-input-parameter-list 'real 'units-quantity 'pressure))
                    (set! param_present "no "))
                  (if (assoc 'zone (list-ref inlet-outlet-bc-list i))
                  (set! zonename  (cadr (assoc 'zone (list-ref inlet-outlet-bc-list i)))))
                  (format  "\n\n\t\t ___________Setting parametric setup for zone ~a_____________\t\n\n" zonename )
                  (set! data-string (wb-ice-bc-get-data-string (list-ref inlet-outlet-bc-list i)))
                  (set! turb-string (wb-ice-bc-get-turb-string (list-ref inlet-outlet-bc-list i)))
                  (set! temp-string (wb-ice-bc-get-temp-string (list-ref inlet-outlet-bc-list i)))
                  (set! mean-mixture-fraction-string (wb-ice-bc-get-mixture-fraction-string (list-ref inlet-outlet-bc-list i)))
                  (set! mixture-fraction-var-string (wb-ice-bc-get-mixture-var-string (list-ref inlet-outlet-bc-list i)))
                  (set! progress-variable-string (wb-ice-bc-get-progress-var-string (list-ref inlet-outlet-bc-list i)))
                  (set! inert-stream-string (wb-ice-bc-get-inert-var-string (list-ref inlet-outlet-bc-list i)))
                  (set! species-mf (wb-ice-bc-get-species-mf-string (list-ref inlet-outlet-bc-list i)))
                  (format  "\n")
                  (if (and (zone-name->id zonename) data-string temp-string turb-string)
                    (begin
                      (if (string=? (cadr (assoc 'type (list-ref inlet-outlet-bc-list i))) "pressure-inlet")
                        (begin 
                          (ti-menu-load-string (string-append "/def b-c m-z z-t " zonename " p-i"))
                          (format "\n")
                          (if (string-ci=? solution-type "combustion")
                            (begin
                              (if (string-ci=? ice-combustion-model "CI-DUFL")
                                (ti-menu-load-string (string-append "/def b-c p-i " zonename  abs_string data-string supersonic_pr_string temp-string dir_string turb-string mean-mixture-fraction-string mixture-fraction-var-string inert-stream-string )))
                              (if (string-ci=? ice-combustion-model "SI-Partially-Premixed")
                                (ti-menu-load-string (string-append "/def b-c p-i " zonename  abs_string data-string supersonic_pr_string temp-string dir_string turb-string mean-mixture-fraction-string mixture-fraction-var-string progress-variable-string inert-stream-string " no" )))
                              (if (or (string-ci=? ice-combustion-model "CI-LFR") (string-ci=? ice-combustion-model "SI-LFR"))
                                (ti-menu-load-string (string-append "/def b-c p-i " zonename  abs_string data-string supersonic_pr_string temp-string dir_string turb-string " no" species-mf " yes "  )))
                            )
                          )
                          (if (or (string-ci=? solution-type "cold-flow")  (string-ci=? solution-type "port-flow")) 
                            (ti-menu-load-string (string-append "/def b-c p-i " zonename  abs_string data-string supersonic_pr_string temp-string dir_string turb-string ))
                          )
                          (format "\n")
                        )
                      )
                      (if (string=? (cadr (assoc 'type (list-ref inlet-outlet-bc-list i))) "pressure-outlet")
                        (begin 
                          (ti-menu-load-string (string-append "/def b-c m-z z-t " zonename " p-o"))
                          (if (or (string-ci=? solution-type "cold-flow")  (string-ci=? solution-type "port-flow")) 
                            (ti-menu-load-string (string-append "/def b-c p-o " zonename data-string  temp-string dir_string turb-string avg_pr_string )))
                          (if (string-ci=? solution-type "combustion")
                            (begin
                              (if (string-ci=? ice-combustion-model "CI-DUFL")
                                (ti-menu-load-string (string-append "/def b-c p-o " zonename data-string  temp-string dir_string turb-string mean-mixture-fraction-string mixture-fraction-var-string inert-stream-string  avg_pr_string )))
                              (if (or (string-ci=? ice-combustion-model "CI-LFR") (string-ci=? ice-combustion-model "SI-LFR"))
                                (ti-menu-load-string (string-append "/def b-c p-o " zonename data-string  temp-string dir_string turb-string " no" species-mf " no no no no no " )))
                              (if (string-ci=? ice-combustion-model "SI-Partially-Premixed")
                                (ti-menu-load-string (string-append "/def b-c p-o " zonename data-string  temp-string dir_string turb-string mean-mixture-fraction-string mixture-fraction-var-string progress-variable-string inert-stream-string " no no no no " )))
                            )
                          )
                        )
                      )
                      
                      (if (string=? (cadr (assoc 'type (list-ref inlet-outlet-bc-list i))) "mass-flow-inlet")
                        (begin
                          (if (assoc 'data-profile bc_list)
                            (if (string-ci=? (cadr (assoc 'data-profile bc_list)) "no")
                                (set! value (caddr (assoc 'data-profile bc_list))))
                          )
                          (if (< value 0)
                            (set! dir_string " no no yes")
                            (set! dir_string " no yes")
                          )
                          (set! abs_string " yes yes ")
                          (ti-menu-load-string (string-append "/def b-c m-z z-t " zonename " mfi"))
                          (format  "\n")
                          (if (or (string-ci=? solution-type "cold-flow")  (string-ci=? solution-type "port-flow")) 
                            (ti-menu-load-string (string-append "/def b-c mfi " zonename abs_string data-string temp-string  supersonic_pr_string dir_string  turb-string )))
                          (if (string-ci=? solution-type "combustion")
                            (begin
                              (if (string-ci=? ice-combustion-model "CI-DUFL")
                                (ti-menu-load-string (string-append "/def b-c mfi " zonename abs_string data-string temp-string supersonic_pr_string dir_string turb-string mean-mixture-fraction-string mixture-fraction-var-string )))
                              (if (or (string-ci=? ice-combustion-model "CI-LFR") (string-ci=? ice-combustion-model "SI-LFR"))
                                (ti-menu-load-string (string-append "/def b-c mfi " zonename abs_string data-string temp-string supersonic_pr_string dir_string turb-string " no" species-mf " yes" )))
                              (if (string-ci=? ice-combustion-model "SI-Partially-Premixed")
                                (ti-menu-load-string (string-append "/def b-c mfi " zonename abs_string data-string temp-string supersonic_pr_string dir_string turb-string progress-variable-string mean-mixture-fraction-string mixture-fraction-var-string " yes" )))
                            )
                            (format  "\n")
                          )
                        )
                      )
                    )
                    (format  "\n\n--Warning: Unable to setup BC for Zone ~s ---\n\n" zonename)
                  )
                )
              )
            )
          )
        )
      )
    )
  )
  
(set! wb-ice-bc-get-data-string
  (lambda (bc_list)
    (let
      (
        (inlet-outlet-bc-list (rpgetvar 'ice/inlet_outlet_bc_list_parametric))
        (data-profile? "no")
        (data_par_name "")
        (data-profile-name "")
        (data-profile-field "")
        (param_present "")
        
        (data-string #f)
        (value 0)
        (value_prev 0)
        (data_parametric #f)
        (temprature_parametric #f)
      
      )
      (if (assoc 'parameter bc_list)
        (begin
          (if (assoc 'data-parameter (assoc 'parameter bc_list))
            (begin
              (set! data_parametric #t)
              (set! data_par_name (cadr (assoc 'data-parameter (assoc 'parameter bc_list))))
            )
          )
          (if (assoc 'temperature-parameter (assoc 'parameter bc_list))
            (set! temprature_parametric #t))
        )
      )
      (if (pair? (get-input-parameter-list 'real 'units-quantity 'pressure))
        (set! param_present "no "))    
      (if (assoc 'data-profile bc_list)
        (begin
          (set! data-profile? (cadr (assoc 'data-profile bc_list)))
          (if (string-ci=? data-profile? "yes")
            (begin
              (set! data-profile-name (caddr (assoc 'data-profile bc_list)))
              (set! data-profile-field (cadddr (assoc 'data-profile bc_list)))
              (set! data-string (string-append " yes no \"" data-profile-name "\" \"" data-profile-field "\" " ))
            )
            (begin 
              (set! value (caddr (assoc 'data-profile bc_list)))
              (if (string=? (cadr (assoc 'type bc_list)) "mass-flow-inlet")
                (set! value (abs value)))
              (set! data-string (string-append " no " (number->string value) " " ))
              (if data_parametric
                (set! data-string (string-append " yes " param_present " " data_par_name " " (number->string value) " " ))
                (set! data-string (string-append " no no "  (number->string value) " " ))
              )
            )
          )
        )
      ) data-string
    )
  )
)

(set! wb-ice-bc-get-turb-string
  (lambda (bc_list)
    (let
      (
        (inlet-outlet-bc-list (rpgetvar 'ice/inlet_outlet_bc_list_parametric))
        (turb-string #f)
        (turb1 1)
        (turb2 5)
        (turbtype "int-hyd-dia")
        (data_parametric #f)
        (temprature_parametric #f)
      
      )
      (if (assoc 'parameter bc_list)
        (begin
          (if (assoc 'data-parameter (assoc 'parameter bc_list))
            (set! data_parametric #t))
          (if (assoc 'temperature-parameter (assoc 'parameter bc_list))
            (set! temprature_parametric #t))
        )
      )
      (if  (assoc 'turbulance bc_list)
        (begin
          (set! turbtype (cadr (assoc 'turbulance bc_list)))
          (set! turb1 (caddr (assoc 'turbulance bc_list)))
          (set! turb2 (cadddr (assoc 'turbulance bc_list)))
          (if (string-ci=? turbtype "int-vis-ratio")
            (begin
            (set! turb-string  (string-append " no no yes " (number->string turb1) " " (number->string turb2) " " ))
              (if (or data_parametric temprature_parametric)
                (set! turb-string  (string-append " no no yes no " (number->string turb1) " no " (number->string turb2) " " )))
            )
            (begin
              (set! turb-string  (string-append " no no no yes " (number->string turb1) " " (number->string turb2) " " ))
              (if (or data_parametric temprature_parametric)
                (set! turb-string  (string-append " no no no yes no " (number->string turb1) " no " (number->string turb2) " " )))
            )
          )
        )
      ) turb-string
    )
  )
)

(set! wb-ice-bc-get-temp-string
  (lambda (bc_list)
    (let
      (
        (inlet-outlet-bc-list (rpgetvar 'ice/inlet_outlet_bc_list_parametric))
        (temp-profile? "no")
        (temp 300)
        (temp-profile-name "")
        (temp-profile-field "")
        (temp-string #f)
        (data_parametric #f)
        (temprature_parametric #f)
        (param_present "")
        (temp_par_name "")
      
      )
      (if (assoc 'parameter bc_list)
        (begin
          (if (assoc 'data-parameter (assoc 'parameter bc_list))
            (set! data_parametric #t))
          (if (assoc 'temperature-parameter (assoc 'parameter bc_list))
            (begin
              (set! temprature_parametric #t)
              (set!  temp_par_name (cadr (assoc 'temperature-parameter (assoc 'parameter bc_list))))
            )
          )
        )
      )
      (if (pair? (get-input-parameter-list 'real 'units-quantity 'temperature))
        (set! param_present "no "))
      (if (assoc 'temperature-profile bc_list)
        (begin 
          (set! temp-profile? (cadr (assoc 'temperature-profile bc_list)))
          (if (string-ci=? temp-profile? "yes")
            (begin
              (set! temp-profile-name (caddr (assoc 'temperature-profile bc_list)))
              (set! temp-profile-field (cadddr (assoc 'temperature-profile bc_list)))
              (set! temp-string (string-append " yes no \"" temp-profile-name "\" \"" temp-profile-field "\" " ))

            )
            (begin 
              (set! temp (caddr (assoc 'temperature-profile bc_list)))
              (set! temp-string (string-append " no " (number->string temp) " " ))
              (if temprature_parametric
                (set! temp-string (string-append " yes " param_present temp_par_name " " (number->string temp) " " ))
                (set! temp-string (string-append " no no " (number->string temp) " " ))
              )
            )
          )
        )
      ) temp-string
    )
  )
)
(set! wb-ice-bc-get-mixture-fraction-string
  (lambda (bc_list)
    (let
      (
        (inlet-outlet-bc-list (rpgetvar 'ice/inlet_outlet_bc_list_parametric))
        (mean-mixture-fraction-profile? "no")
        (mean-mixture-fraction-profile-name "")
        (mean-mixture-fraction-profile-field "")
        (mean-mixture-fraction-string " no 0 ")
        (mean-mixture-fraction-value 0)
        (data_parametric #f)
        (temprature_parametric #f)
      
      )
      (if (assoc 'parameter bc_list)
        (begin
          (if (assoc 'data-parameter (assoc 'parameter bc_list))
            (set! data_parametric #t))
          (if (assoc 'temperature-parameter (assoc 'parameter bc_list))
            (set! temprature_parametric #t))
        )
      )
      (if (assoc 'mean-mixture-fraction bc_list)
        (begin 
          (set! mean-mixture-fraction-profile? (cadr (assoc 'mean-mixture-fraction bc_list)))
          (if (string-ci=? mean-mixture-fraction-profile? "yes")
            (begin
              (set! mean-mixture-fraction-profile-name (caddr (assoc 'mean-mixture-fraction bc_list)))
              (set! mean-mixture-fraction-profile-field (cadddr (assoc 'mean-mixture-fraction bc_list)))
              (set! mean-mixture-fraction-string (string-append " yes no \"" mean-mixture-fraction-profile-name "\" \"" mean-mixture-fraction-profile-field "\" " ))
            )
            (begin 
              (set! mean-mixture-fraction-value (caddr (assoc 'mean-mixture-fraction bc_list)))
              (set! mean-mixture-fraction-string (string-append " no " (number->string mean-mixture-fraction-value) " " ))
              (if (or data_parametric temprature_parametric)
                (set! mean-mixture-fraction-string (string-append " no no " (number->string mean-mixture-fraction-value) " " )))
            )
          )
        )
      ) mean-mixture-fraction-string
    )
  )
)
(set! wb-ice-bc-get-mixture-var-string
  (lambda (bc_list)
    (let
      (
        (inlet-outlet-bc-list (rpgetvar 'ice/inlet_outlet_bc_list_parametric))
        (mixture-fraction-var-profile? "no")
        (mixture-fraction-var-profile-name "")
        (mixture-fraction-var-profile-field "")
        (mixture-fraction-var-string " no 0 ")
        (mixture-fraction-var-value 0)
        (data_parametric #f)
        (temprature_parametric #f)
      
      )
      (if (assoc 'parameter bc_list)
        (begin
          (if (assoc 'data-parameter (assoc 'parameter bc_list))
            (set! data_parametric #t))
          (if (assoc 'temperature-parameter (assoc 'parameter bc_list))
            (set! temprature_parametric #t))
        )
      )
      (if (assoc 'mixture-fraction-var bc_list)
        (begin 
          (set! mixture-fraction-var-profile? (cadr (assoc 'mixture-fraction-var bc_list)))
          (if (string-ci=? mixture-fraction-var-profile? "yes")
            (begin
              (set! mixture-fraction-var-profile-name (caddr (assoc 'mixture-fraction-var bc_list)))
              (set! mixture-fraction-var-profile-field (cadddr (assoc 'mixture-fraction-var bc_list)))
              (set! mixture-fraction-var-string (string-append " yes no \"" mixture-fraction-var-profile-name "\" \"" mixture-fraction-var-profile-field "\" " ))

            )
            (begin 
              (set! mixture-fraction-var-value (caddr (assoc 'mixture-fraction-var bc_list)))
              (set! mixture-fraction-var-string (string-append " no " (number->string mixture-fraction-var-value) " " ))
              (if (or data_parametric temprature_parametric)
                (set! mixture-fraction-var-string (string-append " no no " (number->string mixture-fraction-var-value) " " )))
            )
          )
        )
      ) mixture-fraction-var-string
    )
  )
)
(set! wb-ice-bc-get-progress-var-string
  (lambda (bc_list)
    (let
      (
        (progress-variable-profile? "no")
        (progress-variable-profile-name "")
        (progress-variable-profile-field "")
        (progress-variable-string " no 0")
        (progress-variable-value 0)
        (data_parametric #f)
        (temprature_parametric #f)
      
      )
      (if (assoc 'parameter bc_list)
        (begin
          (if (assoc 'data-parameter (assoc 'parameter bc_list))
            (set! data_parametric #t))
          (if (assoc 'temperature-parameter (assoc 'parameter bc_list))
            (set! temprature_parametric #t))
        )
      )
      (if (assoc 'progress-variable bc_list)
        (begin 
          (set! progress-variable-profile? (cadr (assoc 'progress-variable bc_list)))
          (if (string-ci=? progress-variable-profile? "yes")
            (begin
              (set! progress-variable-profile-name (caddr (assoc 'progress-variable bc_list)))
              (set! progress-variable-profile-field (cadddr (assoc 'progress-variable bc_list)))
              (set! progress-variable-string (string-append " yes no \"" progress-variable-profile-name "\" \"" progress-variable-profile-field "\" " ))
            )
            (begin 
              (set! progress-variable-value (caddr (assoc 'progress-variable bc_list)))
              (set! progress-variable-string (string-append " no " (number->string progress-variable-value) " " ))
              (if (or data_parametric temprature_parametric)
                (set! progress-variable-string (string-append " no no " (number->string progress-variable-value) " " )))
            )
          )  
        )
      ) progress-variable-string
    )
  )
)
(set! wb-ice-bc-get-inert-var-string
  (lambda (bc_list)
    (let
      (
        (inert-stream-profile? "no")
        (inert-stream-profile-name "")
        (inert-stream-profile-field "")
        (inert-stream-string "")
        (inert-stream-value 0)
        (data_parametric #f)
        (temprature_parametric #f)
      
      )
      (if (assoc 'parameter bc_list)
        (begin
          (if (assoc 'data-parameter (assoc 'parameter bc_list))
            (set! data_parametric #t))
          (if (assoc 'temperature-parameter (assoc 'parameter bc_list))
           (set! temprature_parametric #t))
        )
      )
      (if (assoc 'inert-stream bc_list)
        (begin 
          (set! inert-stream-profile? (cadr (assoc 'inert-stream bc_list)))
          (if (string-ci=? inert-stream-profile? "yes")
            (begin
              (set! inert-stream-profile-name (caddr (assoc 'inert-stream bc_list)))
              (set! inert-stream-profile-field (cadddr (assoc 'inert-stream bc_list)))
              (set! inert-stream-string (string-append " yes no \"" inert-stream-profile-name "\" \"" inert-stream-profile-field "\" " ))
            )
            (begin 
              (set! inert-stream-value (caddr (assoc 'inert-stream bc_list)))
              (set! inert-stream-string (string-append " no " (number->string inert-stream-value) " " ))
              (if (or data_parametric temprature_parametric)
                (set! inert-stream-string (string-append " no no " (number->string inert-stream-value) " " )))
            )
          )
        )
      ) inert-stream-string
    )
  )
)
(set! wb-ice-bc-get-species-mf-string
  (lambda (bc_list)
    (let
      (
        (ice_speices_list '())
        (species-mf "")
        (mf 0)
        (available_species_list '())
        (dir_string "")
        (data_parametric #f)
        (temprature_parametric #f)
      
      )
      (if (assoc 'parameter bc_list)
        (begin
          (if (assoc 'data-parameter (assoc 'parameter bc_list))
            (set! data_parametric #t))
          (if (assoc 'temperature-parameter (assoc 'parameter bc_list))
            (set! temprature_parametric #t))
        )
      )
      (if (assoc 'species-mass-fraction bc_list)
        (begin 
          (set! available_species_list (inquire-species-names) )
          (set! ice_speices_list (cdr (assoc 'species-mass-fraction bc_list)))
          (do ((i 0 (+ i 1))) ((>= i (- (length available_species_list) 1)))
            (if (assoc (list-ref available_species_list i) ice_speices_list)
              (set! mf (cadr (assoc (list-ref available_species_list i) ice_speices_list)))
              (set! mf 0)
            )
            (if (or data_parametric temprature_parametric)
              (set! species-mf (string-append species-mf " no no"  " " (number->string mf)))
              (set! species-mf (string-append species-mf " no"  " " (number->string mf))))
          )
        )
        (begin
         (if (string-ci=? solution-type "combustion")
           (begin 
              (set! available_species_list (inquire-species-names) )
              (do ((i 0 (+ i 1))) ((>= i (- (length available_species_list) 1)))
                     (set! species-mf (string-append species-mf " no 0" ))
                )
            )
          )
        )
      ) species-mf
    )
  )
)


(set! wb-ice-set-cell-zone-conditions
  (lambda()
    ;changing cell zone axis of rotation 
    (let
      (
       (cyl-axis '(0 0 1))
       (cyl-orig '(0 0 0))
       (fluid-zones  (map thread-name (get-threads-of-type 'fluid)))
       )
      (if (read-var ICDyMeshSetFile 'cylinder_axis)
	(set! cyl-axis (get-unit-vector (read-var ICDyMeshSetFile 'cylinder_axis)) )
	)
      (if (read-var ICDyMeshSetFile 'cylinder_axis_origin)
	(set! cyl-orig  (read-var ICDyMeshSetFile 'cylinder_axis_origin) )
	)
      (if (> (length fluid-zones) 0)
	(begin
	  (do ((i 0 (+ i 1))) ((= i (length fluid-zones)))
	    (ti-menu-load-string (format #f "/def b-c fluid ~s ,,,,,~s,~s,~s,~s,~s,~s,,," (list-ref fluid-zones i) (car cyl-orig) (cadr cyl-orig) (caddr cyl-orig) (car cyl-axis) (cadr cyl-axis) (caddr cyl-axis) ) ) 
	    )
	  )
	)
      )

    )
  )
(set! wb-ice-wall-bc

  (lambda ()
    ;(format  "\n\n\t\t ___________Setting Up Wall BC_____________\t\n\n")  
    (define wall-bc-list)
    (set! wall-bc-list           (read-var solver-set-file 'wall_bc_list))
    (if wall-bc-list
      (begin
	(format  "\n\n\t\t ___________Setting Up User Wall BC_____________\t\n\n") 
	(do ((i 0 (+ i 1))) ((= i (length wall-bc-list)))
	  (let
	    (  
	       (zonename #f)
	       (value #f)
	       (data-profile? #f )
	       (data-profile-name #f)
	       (data-profile-field #f)
	       (data-string #f)
	       (slipwall-stirng #f)
	       )
	    (if (assoc 'zone (list-ref wall-bc-list i))
	      (set! zonename  (lowercase (cadr (assoc 'zone (list-ref wall-bc-list i)))))
	      )

	    (if (assoc 'data-profile (list-ref wall-bc-list i))
	      (begin
		(set! data-profile? (cadr(assoc 'data-profile (list-ref wall-bc-list i))))
		(if (string-ci=? data-profile? "yes")
		  (begin

		    (set! data-profile-name (caddr (assoc 'data-profile (list-ref wall-bc-list i))))
		    (set! data-profile-field (cadddr (assoc 'data-profile (list-ref wall-bc-list i))))
		    (set! data-string (string-append " yes no \"" data-profile-name "\" \"" data-profile-field "\" " ))
		    )
		  (begin 
		    (set! value (caddr (assoc 'data-profile (list-ref wall-bc-list i))))
		    (set! data-string (string-append " no " (number->string value) " " ))
		    )

		  )
		)
	      )
	    (if (and (assoc 'slipwall (list-ref wall-bc-list i)) (string-ci=? (cadr (assoc 'slipwall (list-ref wall-bc-list i))) "yes") )
	      (begin
		(set! slipwall-stirng " yes shear-bc-spec-shear , , , , , , , , , , " )
		)
		  (begin
		(set! slipwall-stirng " no no , no , " )
		)
	      )

	    (if (string-ci=? zonename "all")
	      (begin
		(define initial-walls (map thread-name (sort-threads-by-name (get-threads-of-type 'wall))))
		(do ((j 0 (+ j 1))) ((= j (length initial-walls)))
		  (ti-menu-load-string (format #f "/def bc wall ~s 0 no 0 no yes temperature ~s no no ~s " (list-ref initial-walls j) (string->symbol data-string)(string->symbol slipwall-stirng)))
		      )
		    )
		  (begin
        (if (equal? (thread-type (get-thread zonename)) 'wall)
          (if (and (zone-name->id zonename) data-string)
        (ti-menu-load-string (format #f "/def bc wall ~s 0 no 0 no yes temperature ~s no no ~s  " (string->symbol zonename) (string->symbol data-string)(string->symbol slipwall-stirng)))
        (if (zone-name->id zonename)
          (ti-menu-load-string (format #f "/def bc wall ~s 0 no 0 no yes temperature no 300 no no ~s  " (string->symbol zonename)(string->symbol slipwall-stirng)))
            (format  "\n\n--Warning: Unable to setup Wall BC for Zone ~s ---\n\n" zonename)

          )	      
        )
        (format " \n\n Warning : Zone \"~a\" is not of type wall so no wall boundary condition is defined on it \n\n" zonename)
       )
		)
		  )

		)
	)
	)
      (begin
	(format  "\n\n\t\t ___________Setting Up Default Wall BC_____________\t\n\n") 
	(define initial-walls (map thread-name (sort-threads-by-name (get-threads-of-type 'wall))))
	(do ((j 0 (+ j 1))) ((= j (length initial-walls)))
	  (ti-menu-load-string (format #f "/def bc wall ~s 0 no 0 no yes temperature no 300 no no no no , no , " (list-ref initial-walls j)))
	  )
	)
      )

    )
  )
(set! wb-ice-wall-bc-parametric
  (lambda ()
    (define wall-bc-list)
    (if (rp-var-object 'ice/wall_bc_list_parametric)
      (set! wall-bc-list           (rpgetvar 'ice/wall_bc_list_parametric)))
    (if wall-bc-list
      (begin
        (do ((i 0 (+ i 1))) ((= i (length wall-bc-list)))
          (let
            (  
              (zonename #f)
              (value #f)
              (data-profile? #f )
              (data-profile-name #f)
              (data-profile-field #f)
              (data-string #f)
              (slipwall_string " yes shear-bc-noslip ")
              (wall_thickness_string " 0 ")
              (heat_gen_string " no 0 ")
              (data_parametric #f)
              (data_par_name "")
              (roughness_height_str " no 0 ")
              (roughness_str " no 0 ")
              (conv_aug_str " no 1 ")
              (param_present "")
              (dpm_bc "")
              (spec_shear_compo "")
              (species_string "")
              (parameteric #f)
              (particle_wall_heat_exchange "")
            )
            (if (not (null? (rpgetvar 'dpm/injections-list)))
              (begin
                (set! dpm_bc " yes reflect polynomial 1 1 polynomial 1 1 ")
                (set! particle_wall_heat_exchange " no ")
              )
            )
            (if (assoc 'parameter (list-ref wall-bc-list i))
              (set! parameteric #t))
            (if parameteric
              (begin
                
                (if (assoc 'temperature-parameter (assoc 'parameter (list-ref wall-bc-list i)))
                  (begin
                    (set! data_parametric #t)
                    (set! data_par_name (cadr (assoc 'temperature-parameter (assoc 'parameter (list-ref wall-bc-list i)))))
                    ;(set! supersonic_pr_string " no no 0 ")
                    (set! wall_thickness_string " no 0 ")
                    (set! heat_gen_string " no no 0 ")
                    (set! roughness_height_str " no no 0 ")
                    (set! roughness_str " no no 0 ")
                    (set! conv_aug_str " no no 1 ")
                    (if (not (null? (rpgetvar 'dpm/injections-list)))
                      (set! dpm_bc " yes reflect no polynomial 1 1 no polynomial 1 1 "))
                  )
                )
                (ti-menu-load-string (format #f  "\n /def parameters enable-in-TUI?  yes\n"))
                ;(format "\ndata parameteric : ~a\n" data_parametric)
                (if (pair? (get-input-parameter-list 'real 'units-quantity 'temperature))
                    (set! param_present "no "))
                (if (assoc 'zone (list-ref wall-bc-list i))
                  (set! zonename  (lowercase (cadr (assoc 'zone (list-ref wall-bc-list i))))))
                (if (assoc 'data-profile (list-ref wall-bc-list i))
                  (begin
                    (set! data-profile? (cadr(assoc 'data-profile (list-ref wall-bc-list i))))
                    (if (string-ci=? data-profile? "yes")
                      (begin
                        (set! data-profile-name (caddr (assoc 'data-profile (list-ref wall-bc-list i))))
                        (set! data-profile-field (cadddr (assoc 'data-profile (list-ref wall-bc-list i))))
                        (set! data-string (string-append " yes no \"" data-profile-name "\" \"" data-profile-field "\" " ))
                      )
                      (begin 
                        (set! value (caddr (assoc 'data-profile (list-ref wall-bc-list i))))
                        (set! data-string (string-append " no " (number->string value) " " ))
                        (if data_parametric
                          (set! data-string (string-append " yes " param_present " " data_par_name " " (number->string value) " " )))
                      )
                    )
                  )
                )
                (if (and (assoc 'slipwall (list-ref wall-bc-list i)) (string-ci=? (cadr (assoc 'slipwall (list-ref wall-bc-list i))) "yes") )
                  (begin
                    (set! slipwall_string " yes shear-bc-spec-shear ")
                    (set! spec_shear_compo " no 1 no 1 no 1 ")
                    (if data_parametric
                      (set! spec_shear_compo " no no 1 no no 1 no no 1 "))
                  )
                  (set! slipwall_string " yes shear-bc-noslip ")
                )
               (if (string-ci=? solution-type "combustion")
                 (if (or (string-ci=? ice-combustion-model "CI-LFR") (string-ci=? ice-combustion-model "SI-LFR") )
                    (begin
                      (do ((i 1 (+ i 1))) ((= i (length (inquire-species-names))))
                        (set! species_string (string-append species_string " yes "))
                      )
                    )
                  )
                )
                (if (not (string-ci=? zonename "all"))
                  (begin
                    (if (equal? (thread-type (get-thread zonename)) 'wall)
                      (if (and (zone-name->id zonename) data-string)
                        (begin
                          (format  "\n\n\t\t ___________Setting parametric setup for zone ~a_____________\t\n\n" zonename) 
                        (ti-menu-load-string (string-append "\n/def bc wall " zonename " " wall_thickness_string heat_gen_string "no yes temperature " data-string " no no " slipwall_string roughness_height_str roughness_str dpm_bc particle_wall_heat_exchange species_string spec_shear_compo conv_aug_str))
                        )
                        (if (zone-name->id zonename)
                          (ti-menu-load-string (format #f "/def bc wall ~s 0 no 0 no yes temperature no 300 no no ~s  " (string->symbol zonename)(string->symbol slipwall_string)))
                          (format  "\n\n--Warning: Unable to setup Wall BC for Zone ~s. Check that the zone exists. ---\n\n" zonename))
                      )
                      (format " \n\n Warning : Zone \"~a\" is not of type wall so no wall boundary condition is defined on it \n\n" zonename)
                   )
                  )
                )
              )
            )
          )
        )
      )
    )
  )
)

(set! wb-ice-coldflow-viscous-model-setup
  (lambda ()
    (format  "\n\n\t\t ___________Setting Up Models_____________\t\n\n")
      (ti-menu-load-string "/def mode vis ke-standa yes")
      (ti-menu-load-string (format #f  "/def dm eve eef event"))
      (ti-menu-load-string "/dis set pic driver jpeg")
      (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-portflow-viscous-model-setup
  (lambda ()
    (format  "\n\n\t\t ___________Setting Up Models_____________\t\n\n")
     (ti-menu-load-string "/def mode vis kw-standa yes")
     (ti-menu-load-string "/dis set pic driver jpeg")
     
    )
  )  
(set! wb-ice-report-mesh

  (lambda ()
    (format  "\n\n\t\t ___________Setting Up Mesh Report_____________\t\n\n")  
    (define cur-event-list)
    (define pre-event-list)
    (let 
      (
       (my1 (list '(active . #t) (cons 'name "report-event-for-cell-count-at-0CA") (cons 'start 0) (list 'action 15 (format #f "(with-output-to-file (string-append wb-ice-report-dir-path \"ice-cell-count-0\") grid-show)")))) 
       (my2 (list '(active . #t) (cons 'name "report-event-for-cell-count-at-180CA") (cons 'start 180) (list 'action 15 (format #f "(with-output-to-file (string-append wb-ice-report-dir-path \"ice-cell-count-180\") grid-show)"))))
       (my3 (list '(active . #t) (cons 'name "report-event-for-cell-count-at-TDC") (cons 'start 720) (list 'action 15 (format #f "(with-output-to-file (string-append wb-ice-report-dir-path \"ice-cell-count-0\") grid-show)")))) 
       (my4 (list '(active . #t) (cons 'name "report-event-for-cell-count-at-BDC") (cons 'start 540) (list 'action 15 (format #f "(with-output-to-file (string-append wb-ice-report-dir-path \"ice-cell-count-180\") grid-show)")))) 
       )
      (if (string-ci=? solution-type "cold-flow")
      (set! cur-event-list (list my1 my2 ))
      )
      (if (string-ci=? solution-type "combustion")
      (set! cur-event-list (list my3 my4 ))
      )
      (set! pre-event-list (rpgetvar 'dynamesh/in-cyn/event-list))
      ;)
      (rpsetvar 'dynamesh/in-cyn/event-list (append pre-event-list cur-event-list))
      ;(pp "in here")

      )
    )
  )
(set! wb-ice-report-urf
  (lambda ()
    (define valve-list)
    (define cur-event-list)
    (define pre-event-list)
    (define list1)
    (set! list1 '())
    (format  "\n\n\t\t ___________Reporting URF _____________\t\n\n")  

    ;set report dir
    ;(wb-ice-report-dir)

    (set! valve-list           (wb-ice-get-setup-valve-list))
    (ti-menu-load-string "/dis set pic driver jpeg")
    (do ((i 0 (+ i 1))) ((= i (length valve-list)))
      (let ((my1 '())
            (my2 '())
            (my3 '()))
	
	 ;(list1 '())
	 (set! my1 (list '(active . #t) (cons 'name "report-event-for-solver-setting") (cons 'start 0) 
                   (list 'action 15 "(ti-menu-load-string (format #f \"/report summ yes ~aice-report-solver-settings-0\" wb-ice-report-dir-path))")))
	 (set! my2 (list '(active . #t) (cons 'name "report-event-for-solver-setting") (cons 'start (list-ref (list-ref setup-valve-list i) 3))
                   (list 'action 15 (string-append "(ti-menu-load-string (format #f \"/report summ yes ~aice-report-solver-settings-" (number->string (list-ref (list-ref setup-valve-list i) 3)) "\" wb-ice-report-dir-path))")))) 
	 (set! my3 (list '(active . #t) (cons 'name "report-event-for-solver-setting") (cons 'start (list-ref (list-ref setup-valve-list i) 4))
                   (list 'action 15 (string-append "(ti-menu-load-string (format #f \"/report summ yes ~aice-report-solver-settings-" (number->string (list-ref (list-ref setup-valve-list i) 4)) "\" wb-ice-report-dir-path))"))))
	(let
	  (	
		(p (list-ref (list-ref setup-valve-list i) 2))
		)
	  (set! list1 (append list1 (list (string->symbol p))))
	  )
  

	(set! cur-event-list (list my1 my2 my3))
	(set! pre-event-list (rpgetvar 'dynamesh/in-cyn/event-list))
	(rpsetvar 'dynamesh/in-cyn/event-list (append pre-event-list cur-event-list))
	))

    )
  ) 

(set! wb-ice-insert-layer
  (lambda()
    (if (and (not (thread-name->id "fluid-layer-cylinder")) (not (thread-name->id "fluid-piston")))
      (begin
	(if (and  (thread-name->id "piston") (thread-name->id "cyl-tri"))
	  (begin
	    (wb-ice-mesh-replace-initial)
	    (insert-internal-layer (thread-name->id "piston") (thread-name->id "cyl-tri") 'interior-fluid-layer-cylinder-fluid-piston 'int-piston) 
	    (wb-ice-mesh-replace-final)
	    )
	  )
	)
      )
    )
  )

(set! wb-ice-delete-layer
  (lambda()
    (pp "delete-layer")
    )
  )

(set! mesh-replace-initial
  (lambda()
    (wb-ice-mesh-replace-initial)
    )
  )

(set! mesh-replace-final
  (lambda()
    (wb-ice-mesh-replace-final)
    )
  )
  




(set! wb-ice-plot-profile
  (lambda ()
    (define valve-list)
    (define valve-profile-list)
    (define profile-list)
    (set! valve-profile-list '())
    (set! profile-list '())

    (format  "\n\n\t\t ___________Plotting the Profile_____________\t\n\n")  
    ;set report dir
    ;(wb-ice-report-dir)
    (set! valve-list           (wb-ice-get-setup-valve-list))
    (ti-menu-load-string "/dis set pic driver jpeg")
    (do ((i 0 (+ i 1))) ((= i (length valve-list)))
      (let
      (	
		(p (list-ref (list-ref setup-valve-list i) 2))
		)
        (set! valve-profile-list (append valve-profile-list (list (string->symbol p))))
	)
      )
    (set! profile-list (append valve-profile-list (list (string->symbol piston-full-prof))))
    (if (= piston_type 1)

      (set! profile-list (append profile-list (list (string->symbol piston-limit-prof))))
      )

    (ti-menu-load-string (format #f "/def dm c icp ppl ~s ~s 720 10 yes" profile-list start-crank-angle))
    (ti-menu-load-string (format #f "/dis hc ~aice-profile-plot1.jpg" wb-ice-report-dir-path))
    (ti-menu-load-string (format #f "/def dm c icp ppl ~s 0 720 10 yes" valve-profile-list))
    (ti-menu-load-string  (format #f  "/dis hc ~aice-profile-plot.jpg" wb-ice-report-dir-path))
    )
  )



(set! wb-ice-report-dir-fluent

  (lambda ()
    (define icedir "./")
    (if (wb-get-dir)
      (set! icedir (directory (wb-get-dir)))
      (if (client-default-basename "r") 
	(set! icedir (directory (directory (client-default-basename "r"))))
	)
      )
    (chdir icedir)

    )
  )



(set! wb-ice-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 ))
   (in_cylinder_parameter_list (read-var solver-set-file 'in_cylinder_parameter_list ))
   (inlet_outlet_bc_list (read-var solver-set-file 'inlet_outlet_bc_list ))
   (wall_bc_list (read-var solver-set-file 'wall_bc_list ))
	 )



      ;(if (OR report-mesh? report-urf?  swirl-data? user-monitor?)
	;(wb-ice-report-dir)
	;)

      ;improving the mesh
      (if (string-ci=? userSettingFile? "no")
	(if (string-ci=? solution-type "port-flow") 
	  (wb-ice-mesh-improve)
	  )
	)

      ;setting up viscous models
      (if set-default-models?
	(begin
	  (if (string-ci=? solution-type "cold-flow") 
	    (wb-ice-coldflow-viscous-model-setup)
	    )
	  (if (string-ci=? solution-type "port-flow") 
	    (wb-ice-portflow-viscous-model-setup)
	    )
	  )
	)

      ;setting up the solver case
      (if (string-ci=? userSettingFile? "no")
	(if (string-ci=? solution-type "port-flow") 
	  (wb-ice-portflow-solver-setup)
	  )
	)

      (if set-default-urf?
	(begin
	  (if (string-ci=? solution-type "cold-flow")
	    (wb-ice-urf-setting)
	    )
	  )
	)
      (if set-bc?
	(begin
	  (wb-ice-inlet-outlet-bc)
	  (if (or (string-ci=? solution-type "cold-flow") (string-ci=? solution-type "port-flow") )
	    (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 (string-ci=? userSettingFile? "no")
	(wb-ice-set-cell-zone-conditions)
	)

      (if (and report-urf? (not (string-ci=? solution-type "port-flow") ))
	(begin	
	  ;(wb-ice-report-dir)
	  (wb-ice-report-urf)
	  (wb-ice-plot-profile)
	  )
	)
      ;(if (string-ci=? userSettingFile? "no")
      ; (wb-ice-plot-residual)
      ;)

      (if (string-ci=? userSettingFile? "no")
	(if (string-ci=? solution-type "cold-flow")	
	  (if (> start-crank-angle 0)
	    (wb-regen-solver-events)
	    )
	  )
	)


      (if initialize-flow?
	(begin
	  (if (string-ci=? solution-type "cold-flow") 
	    (wb-ice-coldflow-initialization)
	    )
	  (if (string-ci=? solution-type "port-flow") 
	    (wb-ice-portflow-initialization)
	    )
	  )
	)

      (if (and report-mesh? (not (string-ci=? solution-type "port-flow") ))
	(wb-ice-report-mesh)
	)

      (if (and post-planes?)
	(begin
	  (wb-ice-create-planes)
	  (wb-ice-create-view-for-planes)
	  (if (string-ci=? solution-type "cold-flow")	 
	    (wb-ice-transientflow-create-default-images-on-planes)
	    )
	  (if (string-ci=? solution-type "port-flow") 
	    (wb-ice-portflow-create-default-images-on-planes)
	    )

	  )
	)
   (if (and (string-ci=? solution-type "cold-flow")(string-ci=? userSettingFile? "no") )
	    (wb-ice-cal-act-for-iter-per-time-step)
	    )

      (if swirl-data?
	(wb-ice-swirl-data)
	)

      (if swirl-def?
	(if (string-ci=? solution-type "port-flow")
	  (wb-ice-cff-on-swirl-planes)
	  )
	)

      ; stores number of residual storage and display history, 5000
      (if (string-ci=? userSettingFile? "no")
	(wb-ice-residual-monitor-history)
	)

    (if user-monitor?
        (wb-ice-postproc-monitors-user)
    )

  (if (string-ci=? userSettingFile? "no")
    (if (string-ci=? solution-type "cold-flow")	
      (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))))
      )
    )
  )
  (if (string-ci=? userSettingFile? "no")
    (begin
      (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))
    )
  )

      ;(wb-ice-report-dir)

      )
    )

  )

(set! wb-setup-ic-global-solver-setting
  (lambda(ic-solver-set-file)
    (if (and ic-solver-set-file (file-exists? ic-solver-set-file))
      (begin
	(set! solver-set-file ic-solver-set-file)
	(set! userSettingFile?   "no")
	(set! system-solver-set-file solver-set-file)
	(if (read-var solver-set-file 'solution-type) 	
    (begin
      (set! solution-type   (read-var solver-set-file 'solution-type))
      (if  (rp-var-object 'ice/solution-type)
        (rpsetvar 'ice/solution-type solution-type)
      )
    )
  )
	(if (read-var solver-set-file 'combustion_simulation_type) 	
    (begin
      (set! combustion-simulation-type   (read-var solver-set-file 'combustion_simulation_type))
      (rpsetvar 'ice/combustion-simulation-type combustion-simulation-type)
     )
  )
   
	(if (or (string-ci=? solution-type "cold-flow") (string-ci=? solution-type "port-flow"))
	  (wb-ice-solver-setup)
	  )
	(if (string-ci=? solution-type "combustion")
	  (wb-ice-combustion-solver-setup)
	  )
  (if (read-var solver-set-file 'deactivate-port?) 	
    (set! deactivate-port?   (read-var solver-set-file 'deactivate-port?))
  )
  (if (read-var solver-set-file 'activation_angle_tolerence) 	
    (set! activation_angle_tolerence   (read-var solver-set-file 'activation_angle_tolerence))
  )
   
    (if deactivate-port?
      (if (and 
            (or (string-ci=? solution-type "combustion") (string-ci=? solution-type "cold-flow"))
            (not (or (string-ci=? combustion-simulation-type "full_engine_ivc_to_evo") (string-ci=? combustion-simulation-type "sector")))
          )
      (wb-ice-activate-decactivate-ports))
    )
      
	(if (or (string-ci=? solution-type "cold-flow") (string-ci=? solution-type "combustion"))
	  (begin
	    ;define time change events based on list in bcsettings file
      (if (thread-name->id "cyl-tri")
        (if (or (>= (%prism-layer-count (thread-name->id 'cyl-tri) 1) 1 ) (>= (%prism-layer-count (thread-name->id 'cyl-tri) 0) 1 ))
        (wb-ice-define-inflation-settings #f)))
      (wb-ice-define-events-for-time-step-changes)
      (wb-ice-define-events-for-case-data-solution-points)
      ;ordering all events based on crank angle
	    (order-events-based-on-crank-angle)
      (wb-ice-cal-act-for-plot-last-monitor-values)
      (wb-ice-cal-act-for-adaptive-time-step)
	    )
	  )
  
  (if (and 
        (or (string-ci=? solution-type "combustion") (string-ci=? solution-type "cold-flow"))
        (not  (string-ci=? combustion-simulation-type "sector"))
      )
      (wb-ice-cal-act-for-remesh-cell-zones-during-smoothing)
  )
  
          
     
    (if (read-var solver-set-file 'num-of-CA)
      (define ca-to-run (read-var solver-set-file 'num-of-CA))
      (define ca-to-run 720)
      )
    (if (string-ci=? solution-type "port-flow")
      (rpsetvar 'number-of-iterations 2000)
      (begin
	    (format  "\n\n\t\t ___________setting no of time steps ______________\t\n\n")
	    (rpsetvar 'number-of-time-steps (wb-ice-get-no-of-time-steps ca-to-run ))
	    )
	  )
    ;(define spark_parameter_list '( ("Spark-0" (start-ca 20) (y-loc 0.003)) ("spark-1" (start-ca 30) (x-loc 0.002)) ))
    ;(wb-ice-define-parameters-combustion spark_parameter_list)
        
	(if (string-ci=? solution-type "cold-flow")
	  (format  "\n\n\t\t ___________WB IC Cold Flow Solver Setup Complete ______________\t\n\n")
	  )
	(if (string-ci=? solution-type "port-flow")
	  (format  "\n\n\t\t ___________WB IC Port Flow Solver Setup Complete ______________\t\n\n")
	  )
	(if (string-ci=? solution-type "combustion")
	  (format  "\n\n\t\t ___________WB ICE Combustion Solver Setup Complete ______________\t\n\n")
	  )
	)
      )
    )
  )
(set! wb-setup-ic-user-solver-setting
  (lambda(ic-solver-set-file)
    (if (and ic-solver-set-file (file-exists? ic-solver-set-file))
      (begin
	(set! solver-set-file ic-solver-set-file)
	(set! userSettingFile?   "yes")
	(set! user-solver-set-file solver-set-file)
	(if (or (string-ci=? solution-type "cold-flow") (string-ci=? solution-type "port-flow"))
	  (wb-ice-solver-setup)
	  )
	(if (string-ci=? solution-type "combustion")
	  (wb-ice-combustion-solver-setup)
	  )
	(if (string-ci=? solution-type "cold-flow")
	  (format  "\n\n\t\t ___________WB IC Cold Flow Solver Setup Complete ______________\t\n\n")
	  )
	(if (string-ci=? solution-type "port-flow")
	  (format  "\n\n\t\t ___________WB IC Port Flow Solver Setup Complete ______________\t\n\n")
	  )
	(if (string-ci=? solution-type "combustion")
	  (format  "\n\n\t\t ___________WB ICE Combustion Solver Setup Complete ______________\t\n\n")
	  )
	)
      )
    (if deactivate-port?
      (if (and 
            (or (string-ci=? solution-type "combustion") (string-ci=? solution-type "cold-flow"))
            (not (or (string-ci=? combustion-simulation-type "full_engine_ivc_to_evo") (string-ci=? combustion-simulation-type "sector")))
          )
        (wb-ice-deactivate-ports-at-start)
      )
    )
  (if (transcript-open?) (ti-menu-load-string "file stop-trans")  )    
    )
  )  
(set! wb-setup-ic-case
  (lambda (ic-prop-file)
    ;; Create Report directory
    (wb-ice-report-dir)
    (set! wb-ice-report-dir-path "../Report/")
    (if (not (transcript-open?))
      (ti-menu-load-string (format #f "/file start-tran \"wb-ice-transcript.trn\" ")))
    (if (read-var ic-prop-file 'solution-type) 	(set! solution-type   (read-var ic-prop-file 'solution-type)))
	(if (read-var ic-prop-file 'combustion_simulation_type) 	(set! combustion-simulation-type   (read-var ic-prop-file 'combustion_simulation_type)))    
    (set! ICDyMeshSetFile ic-prop-file)
    (wb-ice-rpvars-init)
     ;reading transient table data
    (wb-ice-read-transient-table-data)
    (wb-ice-read-multiple-profiles-data)
    (if (string-ci=? solution-type "cold-flow")
      (begin
	(format  "\n\n\t\t ___________Setting Up WB IC Cold Flow Case ..._____________\t\n\n")
	(ice-read-data)
	(wb-ice-dyn-mesh-setup)
	(if (> start-crank-angle 0)
	  (wb-ice-regen)
	  )
	)
      )
    (if (string-ci=? solution-type "port-flow")
      (begin
	(format  "\n\n\t\t ___________Setting Up WB IC Port Flow Case ..._____________\t\n\n")
	(ice-read-data)
	)
      )
    (if (string-ci=? solution-type "combustion")
      (begin
	(format  "\n\n\t\t ___________Setting Up WB IC Combustion Flow Case ..._____________\t\n\n")
	(ice-read-data)
	(wb-ice-dyn-mesh-setup)

	(if (not (string-ci=? combustion-simulation-type "sector"))
	  (if (> start-crank-angle 0)
	    (wb-ice-regen)
	    )
	  )
	)
      )              
    )
  )


(set! wb-ic-register-post-journal
  (lambda()
    (let()
      (cx-add-dependent 'calculation-complete ICWidget wb-ice-post-iteration-method);register the post-iteration journal file
      )

    )
  )

(set! wb-ic-write-solver-settings
  (lambda (file-name)
    ;(wb-ice-report-dir)
    (ti-menu-load-string (format #f "/report summ yes ~aice-report-solver-settings-0" wb-ice-report-dir-path))
    )
  )


(set! wb-ic-write-custom-files
  (lambda()
    (let((outputport #f))
      ;(wb-ice-report-dir)
      (set! outputport (open-output-file (string-append wb-ice-report-dir-path "ice-custom-file-list")))
      (if outputport
	(begin
	  (format outputport "solver-setting-file       ~s~%" ICDyMeshSetFile )
	  (format outputport "bc-file	         	~s~%" system-solver-set-file )
	  (format outputport "user-bc-file		~s~%" user-solver-set-file )
	  (format outputport "pre-iter-file		~s~%" wb-ice-pre-iteration-journal )
	  (format outputport "post-iter-file		~s~%" wb-ice-post-iteration-journal )

	  (close-output-port outputport)
	  )
	)

      )

    )
  )

(set! wb-setup-ic-solver
  (lambda (ic-solver-set-file)

    (if (and ic-solver-set-file (file-exists? ic-solver-set-file))
      (begin
	(set! solver-set-file ic-solver-set-file)
	(if (read-var solver-set-file 'userSettingFile?)
	  (set! userSettingFile?   (read-var solver-set-file 'userSettingFile?))
	  (set! userSettingFile?   "yes")
	    )
	(if (string-ci=? userSettingFile? "yes")
	 (set! user-solver-set-file solver-set-file)
	 (set! system-solver-set-file solver-set-file)
	 )
	(if (read-var solver-set-file 'solution-type) 	(set! solution-type   (read-var solver-set-file 'solution-type)))
   	(if (read-var solver-set-file 'combustion_simulation_type) 	(set! combustion-simulation-type   (read-var solver-set-file 'combustion_simulation_type))) 
	(wb-ice-solver-setup)
	(if (string-ci=? solution-type "cold-flow")
	  (begin
	    ;ordering all events based on crank angle
	    (order-events-based-on-crank-angle)
	    )
	  )
	(if (string-ci=? solution-type "cold-flow")
	  (format  "\n\n\t\t ___________WB IC Cold Flow Solver Setup Complete ______________\t\n\n")
	  (format  "\n\n\t\t ___________WB IC Port Flow Solver Setup Complete ______________\t\n\n")
	  )
	)
      )

    )
  )

(set! wb-ice-post-iteration-method
  (lambda ()

    (wb-ic-write-solver-settings)
    (if (string? wb-ice-post-iteration-journal)
      (if (and (file-exists? wb-ice-post-iteration-journal) (not (file-directory? wb-ice-post-iteration-journal)))
        (begin
          (format "\n\n\t\t _______________ Executing Post Iteration Journal  ~s  _______________\n\n" wb-ice-post-iteration-journal)
          (ti-menu-load-string (string-append "/file/read-journal \"" wb-ice-post-iteration-journal "\""))
          (format "\n\n\t\t _______________ Executed Post Iteration Journal  ~s  _______________\n\n" wb-ice-post-iteration-journal)
          ;(wb-ice-report-dir)
        )))

    (if (string-ci=? solution-type  "cold-flow")
      (wb-ice-post-iter-post-plane-images-cold-flow)
      )
    (if (string-ci=? solution-type "port-flow")
      (wb-ice-post-iter-post-plane-images-port-flow)
      (wb-ice-report-events-table)
      )
    (wb-ice-post-iter-plot-residual)




    )

  )
(set! wb-ice-mesh-improve
  (lambda()
    (if (or (mesh-has-polyhedra?) (mesh-is-adapted?))
      (begin
        (format  "\n\n\t\t ___________Improving Mesh Quality_____________\t\n\n")	
	(ti-menu-load-string "/mesh/repair-improve/improve-quality \n")	        
	)
      )
    )
  )
(set! wb-ice-portflow-solver-setup
  (lambda() 

    ; Change length units, otherwise the limit setup will not be correct because SI is assumed for limits
    ;
    (ti-menu-load-string "/def/units/length m\n")
    (ti-menu-load-string "/def/units/temperature k\n")
    (ti-menu-load-string "/def/units/pressure pascal\n")

    ;Solver set up	
    (ti-menu-load-string "/def/models/steady\n")	
    (ti-menu-load-string "/def/models/solver/pressure-based\n")	
    (ti-menu-load-string "/def/models/energy yes,,,no\n")
    (ti-menu-load-string "/def/materials/change-create/air air yes ideal-gas,,,,,,\n")

    (ti-menu-load-string "/solve/set/p-v-c 24\n")
    (ti-menu-load-string "/solve/set/gradient-scheme no yes\n")

    (if (or (mesh-has-polyhedra?) (mesh-is-adapted?))
      (begin
        (ti-menu-load-string "/solve/set/discretization-scheme/pressure 12\n")	
	(ti-menu-load-string "/solve/set/discretization-scheme/mom 1\n")	
	(ti-menu-load-string "/solve/set/discretization-scheme/k 1\n")	
        (ti-menu-load-string "/solve/set/discretization-scheme/temperature 1\n")
	(ti-menu-load-string "/solve/set/discretization-scheme/density 1\n")       	
	(ti-menu-load-string "/solve/set/discretization-scheme/omega 1\n")
        (ti-menu-load-string "/solve/set/hotr/enable y\n")
	)
	(begin
	(ti-menu-load-string "/solve/set/discretization-scheme/pressure 10\n")
	(ti-menu-load-string "/solve/set/discretization-scheme/mom 1\n")
	(ti-menu-load-string "/solve/set/discretization-scheme/k 0\n")
        (ti-menu-load-string "/solve/set/discretization-scheme/temperature 1\n")
	(ti-menu-load-string "/solve/set/discretization-scheme/density 1\n")
	(ti-menu-load-string "/solve/set/discretization-scheme/omega 0\n")	)
	)
			
	(ti-menu-load-string "/solve/set/pseudo-transient yes , 1 0.25 ,\n")	
 )
)

;----------------------Methods related to starting Fluent at any crank angle other than 0--------------------------------------------------- 


(set! changeBC
  (lambda (zone-name BC-type)
      (ti-menu-load-string (string-append  "/def/b-c/z-t " zone-name " " BC-type))
    
	)
)


(set! deleteMeshInterface
  (lambda(intf-name)
    (ti-menu-load-string (string-append  "/def/m-i/delete " intf-name ))
    )
  )


(set! createMeshInterface
  (lambda(intf-name intf-zone-1 intf-zone-2 . arg)

    ;for periodic interface
    (if (> (length arg) 0)
      (begin
	(if (assoc 'periodic arg )
    (if (cadr (assoc 'periodic arg )) 
      (begin
        (define angle-shift (compute-face-periodic-shift (thread-name->id intf-zone-1) (thread-name->id intf-zone-2) 1))
        (if (= 0 (car angle-shift))
          (ti-menu-load-string (format #f  "/def/m-i/make-periodic ~s ~s yes ~s yes no ~s"(string->symbol intf-zone-1) (string->symbol intf-zone-2)  sector_angle (string->symbol intf-name)))
          (ti-menu-load-string (format #f  "/def/m-i/make-periodic ~s ~s yes , yes no ~s"(string->symbol intf-zone-1) (string->symbol intf-zone-2)  (string->symbol intf-name)))
        )
      )
    )
  )
   
  (if (assoc 'matching arg ) 
    (if (cadr (assoc 'matching arg )) 
    (ti-menu-load-string (string-append  "/def/m-i/create " intf-name " " intf-zone-1 " () "intf-zone-2 " () no no no yes"))
    )
  )
	)
      (begin
	(ti-menu-load-string (string-append  "/def/m-i/create " intf-name " " intf-zone-1 " () "intf-zone-2 " () no"))
	)
      )
    )

  )


(set! createDeformingDynMeshZone
  (lambda(zone-name)
    (ti-menu-load-string (string-append  "/def/d-m/z/create " zone-name " deforming , , , , no " (number->string (* 0.4 (caddr (%get-min-max-length-scale-on-zone (thread-name->id  zone-name) #f)))) " " (number->string (* 1.4 (caddr (%get-min-max-length-scale-on-zone (thread-name->id  zone-name) #f)))) " 0.6"))      
    )
  )



(set! deleteDynMeshZone
  (lambda(zone-name)
    (ti-menu-load-string (string-append  "/def/d-m/z/delete " zone-name))
    )
  )


(set! changeStationaryDynMeshZoneLayerHeight
  (lambda(zone-name layer-ht)
    (ti-menu-load-string (string-append  "/def/d-m/z/create " zone-name " stationary , ,  " (number->string layer-ht)))  
    )
  )




;----------if insert layer possible this method returns 1
(define isInsertLayerPossible)
(set! isInsertLayerPossible
  (lambda()
    (if(thread-name->id "int-piston")
      (+ 1 0)     
      )
    )
  )



(define createSlidingInterface)
(set! createSlidingInterface
  (lambda (valve-name)
    (format (string-append "\n \n _________________creating sliding interface for " valve-name "_____________________\n"))
    ;-------------for layering approach
    (if (string-ci=? hybrid/layering "l")
      (begin          

	(changeBC (string-append  "intf-" valve-name "-ob-fluid-vlayer") "interface")
	(deleteMeshInterface valve-name)
	(createMeshInterface valve-name (string-append "intf-" valve-name "-ob-fluid-ch-valve intf-" valve-name "-ob-fluid-vlayer") (string-append "intf-" valve-name "-ob-fluid-ch-lower intf-" valve-name "-ob-fluid-ch-upper") )	
	)
      )

    ;-------------for hybrid approach
    (if (string-ci=? hybrid/layering "h")
      (begin          
	;------------for piston type-1 or piston type-3
	(if (and (or (= piston_type 3) (= piston_type 1)) (thread-name->id (string-append  "intf-" valve-name "-ob-fluid-ch")) (thread-name->id (string-append  "intf-" valve-name "-ob-fluid-vlayer")))
	  (begin 
	    (changeBC (string-append  "intf-" valve-name "-ob-fluid-ch") "interface")		
	    (changeBC (string-append  "intf-" valve-name "-ob-fluid-vlayer") "interface")
	    (createMeshInterface valve-name (string-append "intf-" valve-name "-ob-fluid-ch") (string-append "intf-" valve-name "-ob-fluid-vlayer") '(matching #t))
	    )
	  ) 
	)
      )

    )
  )

(define createDeformingZones)
(set! createDeformingZones
  (lambda (valve-name)
    (format (string-append "\n \n _______________creating deforming zones for " valve-name "____________________\n"))    
    ;------------for layering or hybrid approach 
    (if (and (or (string-ci=? hybrid/layering "l") (string-ci=? hybrid/layering "h") ) (thread-name->id (string-append "intf-" valve-name "-ob-fluid-vlayer")) (string-append "intf-" valve-name "-ib-fluid-ob-quad"))
      (begin          
	(createDeformingDynMeshZone (string-append "intf-" valve-name "-ob-fluid-vlayer"))
	(createDeformingDynMeshZone (string-append "intf-" valve-name "-ib-fluid-ob-quad")) 
	)
      )               
    )
  )

(define deleteRigidBodyZone)
(set! deleteRigidBodyZone
  (lambda (valve-name)
    (format (string-append "\n \n _________________deleting rigid body zone__________________ \n"))     
    (if (and (string-ci=? hybrid/layering "l") (thread-name->id (string-append "fluid-"valve-name "-vlayer")))
      (begin                    
	(deleteDynMeshZone (string-append "fluid-"valve-name "-vlayer")) 
	)
      )
    (if (and (string-ci=? hybrid/layering "h") (thread-name->id (string-append "fluid-"valve-name "-vlayer")))
      (begin           
	(deleteDynMeshZone (string-append "fluid-"valve-name "-vlayer"))
	)
      )       
    )
  )

(define reducingCellLayerHeight)
(set! reducingCellLayerHeight
  (lambda (valve-name)
    ;----------------for layering approach or hybrid 
    (if (and (or (string-ci=? hybrid/layering "l") (string-ci=? hybrid/layering "h")) (thread-name->id (string-append "intf-int-" valve-name "-ob-fluid-vlayer")) (thread-name->id (string-append valve-name "-seat")))
      (begin 
	(format (string-append "\n \n ________________reducing cell height______________________ \n")) 
	(changeStationaryDynMeshZoneLayerHeight (string-append "intf-int-" valve-name "-ob-fluid-vlayer") 0)
	(changeStationaryDynMeshZoneLayerHeight (string-append valve-name "-seat") 0)
	)
      )
    )
  )

(define increasingCellLayerHeight)
(set! increasingCellLayerHeight
  (lambda (valve-name)
    ;----------------for layering approach or hybrid 
    (if (and (or (string-ci=? hybrid/layering "l") (string-ci=? hybrid/layering "h"))  (thread-name->id (string-append "intf-int-" valve-name "-ob-fluid-vlayer")) (thread-name->id (string-append valve-name "-seat")))
      (begin  
	(format (string-append "\n \n ______________increasing cell height____________________ \n")) 
	(changeStationaryDynMeshZoneLayerHeight (string-append "intf-int-" valve-name "-ob-fluid-vlayer") vlayer-mesh-size)
	(changeStationaryDynMeshZoneLayerHeight (string-append valve-name "-seat") vlayer-mesh-size)
	)
      )    
    )
  )

;----------------------------events based on solver setting for regeneration----------------------------------------
(set! wb-regen-solver-events
  (lambda ()
    (format  "\n\n\t\t ___________ Executing events based on Crank Angle _____________\t\n\n") 

    (set! valve-value 0)
    (do ((valve-value 0 (+ valve-value 1))) ((= valve-value (length setup-valve-list)))

      (let
	(
	 (valve-name (list-ref (list-ref setup-valve-list valve-value) 1))
	 (valve-open-angle (list-ref (list-ref setup-valve-list valve-value) 3))
	 (valve-close-angle (list-ref (list-ref setup-valve-list valve-value) 4))
	 (end-valve-open-smoothing-angle (list-ref (list-ref (list-ref setup-valve-list valve-value) 9) 1) )
	 (begin-valve-close-smoothing-angle (list-ref (list-ref (list-ref setup-valve-list valve-value) 10) 1) )
	 )

	;---------Reducing URF during valve open and close
	(if (or (and (> start-crank-angle (- valve-open-angle 1)) (< start-crank-angle (+ valve-open-angle increment))) (and (> start-crank-angle (- valve-close-angle increment)) (< start-crank-angle (+ valve-close-angle 1))) )
	  (begin
	    (format (string-append "\n \n _____________reducing urf for " valve-name "_____________________\n"))      
	    (ti-menu-load-string "/solve/set/u-r epsilon 0.2 k 0.2 mom 0.4 pressure 0.2")       
	    )     
	  )

	)
      )
    )
  )
;----------------------------events based on valves for regeneration----------------------------------------
(set! regen-valve-events
  (lambda ()
    (format  "\n\n\t\t ___________ Executing events based on Crank Angle _____________\t\n\n") 

    (set! valve-value 0)
    (do ((valve-value 0 (+ valve-value 1))) ((= valve-value (length setup-valve-list)))

      (let
	(
	 (valve-name (list-ref (list-ref setup-valve-list valve-value) 1))
	 (valve-open-angle (list-ref (list-ref setup-valve-list valve-value) 3))
	 (valve-close-angle (list-ref (list-ref setup-valve-list valve-value) 4))
	 (end-valve-open-smoothing-angle (list-ref (list-ref (list-ref setup-valve-list valve-value) 9) 1) )
	 (begin-valve-close-smoothing-angle (list-ref (list-ref (list-ref setup-valve-list valve-value) 10) 1) )
	 (cnt (quotient start-crank-angle 720))
	 (angle-remained 0)
	 )
	(set! angle-remained (- start-crank-angle (* cnt 720)))
	(if (< valve-close-angle valve-open-angle)
	  (set! valve-close-angle (+ valve-close-angle (rpgetvar 'dynamesh/in-cyn/crank-period)))
	)
	(if (< begin-valve-close-smoothing-angle end-valve-open-smoothing-angle)
	  (set! begin-valve-close-smoothing-angle (+ begin-valve-close-smoothing-angle (rpgetvar 'dynamesh/in-cyn/crank-period)))
	  )

	;--------Creating Sliding Interface
	(if (and (> angle-remained valve-open-angle) (< angle-remained valve-close-angle)) 
	  (createSlidingInterface valve-name)
	  )


	;----------Reducing crank angle step size at valve open  and close
	(if (or (and (> angle-remained valve-open-angle) (< angle-remained (+ valve-open-angle increment))) (and (> angle-remained (- valve-close-angle increment)) (< angle-remained  valve-close-angle))) 
	  (begin 
	    (format (string-append "\n \n _____________reducing crank angle step size for " valve-name "_____________________\n"))            
	    (ti-menu-load-string "/def/d-m/controls/i-c-p/c-a-s (* 0.5 dCA)")    
	    )     
	  )

	;------- Creating deforming zone, Deleting rigid zone and, Reducing and Increasing cell height of stationary zone during valve opening and closing
	(if (and (> angle-remained valve-open-angle) (< angle-remained valve-close-angle))
	  (begin
	    (if (or (and (> angle-remained valve-open-angle) (< angle-remained end-valve-open-smoothing-angle)) (and (> angle-remained begin-valve-close-smoothing-angle) (< angle-remained valve-close-angle)))
	      (begin
		(createDeformingZones valve-name)
		(deleteRigidBodyZone valve-name)
		(reducingCellLayerHeight valve-name)
		)
	      )

	    (if (and (> angle-remained end-valve-open-smoothing-angle) (< angle-remained begin-valve-close-smoothing-angle))
	      (increasingCellLayerHeight valve-name)
	      )
	    )
	  )
	)


      )
    )
  )
;--------------executing piston related events during regeneration
(set! regen-piston-events
  (lambda()

    (define ave_scale)
    (if (thread-name->id "int-piston")
      (begin
	(set! ave_scale (+ (* 0.5 (car (%get-min-max-length-scale-on-zone (thread-name->id  "int-piston") #f))) (* 0.5 (car (cdr (%get-min-max-length-scale-on-zone (thread-name->id  "int-piston") #f))))))




	(format  "\n___Creating fluid-piston-layer as rigid body zone___\n")

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

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

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

	;;Changes in 14.5 to take care of corrections from thomas  DE40230 for exclude boundary conditions
	
	(if (thread-name->id "cyl-quad")
	  (ti-menu-load-string (format #f "\n/def d-m zones create cyl-quad rigid-body   ~s  yes  ~s  ~s  ~s"  (string->symbol piston-full-prof) (list-ref cylinder_axis 0) (list-ref cylinder_axis 1) (list-ref cylinder_axis 2)))
		
	  )
	(if (thread-name->id "cyl-piston")
	  (ti-menu-load-string (format #f "\n/def d-m zones create cyl-piston rigid-body   ~s  yes  ~s  ~s  ~s"  (string->symbol piston-full-prof) (list-ref cylinder_axis 0) (list-ref cylinder_axis 1) (list-ref cylinder_axis 2)))
		
	  )


	;;changes end
	
	(format  "\n___Creating int-piston as stationary zone___\n")
	(if (and (thread-name->id  "fluid-layer-cylinder") (thread-name->id  "fluid-ch"))
	(ti-menu-load-string (format #f "/define/dynamic-mesh/zones/create int-piston stationary ~s , 0 ~s , ~s " (thread-name->id  "fluid-ch") (thread-name->id  "fluid-layer-cylinder") ave_scale ))
	(pp "Can not set int-piston dynamic mesh definition as fluid-ch and-or fluid-layer-cylinder cell zones are absent")
	)


	)
      )
    )
  )


(set! createRigidBodyDynMeshZone
  (lambda(zone-name piston-profile direction . arg )
    (let
      (
       (exclude-from-bc "no")
       (cell-ht1 0)
       (cell-ht2 0)
       )
      (if arg
	(begin
	  (if (assv 'exclude-bc arg)
	    (set! exclude-from-bc (cadr (assv 'exclude-bc arg)))
	    )
	  (if (assv 'cell-ht1 arg)
	    (set! cell-ht1 (cadr (assv 'cell-ht1 arg)))
	    )
	  )
	)

      (if (thread-name->id zone-name)
	(begin

	  (if (member (string->symbol zone-name ) (map thread-name (get-threads-of-type 'fluid)))
	    (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create " zone-name " rigid-body " piston-profile "  "   (number->string (list-ref direction 0)) " " (number->string (list-ref direction 1)) " " (number->string (list-ref direction 2))))
	    )
	  (if (not (member (string->symbol zone-name ) (map thread-name (get-threads-of-type 'fluid))))
	    (ti-menu-load-string (format #f "/define/dynamic-mesh/zones/create ~s rigid-body ~s ~s ~s ~s ~s , , ~s ,  " (string->symbol zone-name) (string->symbol piston-profile) (string->symbol exclude-from-bc) (car direction) (cadr direction) (caddr direction) cell-ht1))
	    )
	  )
	)
      )
    )
  )



(set! createStationaryDynMeshZone
  (lambda(zone-name cellHtAdjZone-1 cellHtAdjZone-2)
    (if cellHtAdjZone-2
      (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create "zone-name " stationary , ,  "(number->string cellHtAdjZone-1)" , ,  " (number->string cellHtAdjZone-2)))
      (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create "zone-name " stationary , ,  "(number->string cellHtAdjZone-1) ))
      )
    )
  )


(set! changeZoneName
  (lambda(zone-name isFluid? new-name)
    (if (not isFluid?)
      (ti-menu-load-string (string-append "/def/b-c/zone-name " zone-name " " new-name))
      )
    )
  )
;-------------Interface method to execute regen------------------------------
(set! wb-ice-regen
  (lambda ()
    (wb-ice-mesh-replace-initial) ;this will update the fluid and interiorzone-list every time we read the scheme file
    (regen-valve-events)
    (if (and (= piston_type 3) (> start-crank-angle insert_angle))
      (if (isinsertlayerpossible)
	(regen-piston-events)
	)
      )
    )
  )



(set! create-cff-am-swirl
  (lambda(cff-name swirl-center)
    ;this method takes cff-name , swirl-center as input
    ;creates swirl formula, "(r x v)" , where r is radial vector, v is velocity
    ;creates three scalar with naming convention cff-name

    (if (= (length swirl-center) 3)
      (begin
	(let
	  (
	   (name  cff-name)
	   (s_c_x (number->string (car swirl-center)))
	   (s_c_y (number->string (cadr swirl-center)))
	   (s_c_z (number->string (caddr swirl-center)))

	   )
	  (ti-menu-load-string (string-append "
					      (custom-field-function/define
						'(((name am-x-"name") (display \"(Vz * (y - "s_c_y")) - (Vy * (z - "s_c_z"))\") (syntax-tree (\"-\" (\"*\" \"z-velocity\" (\"-\" \"y-coordinate\" "s_c_y")) (\"*\" \"y-velocity\" (\"-\" \"z-coordinate\" "s_c_z")))) (code (field-- (field-* (field-load \"z-velocity\") (field-- (field-load \"y-coordinate\") "s_c_y")) (field-* (field-load \"y-velocity\") (field-- (field-load \"z-coordinate\") "s_c_z")))))
						  ((name am-y-"name") (display \"(Vx * (z - "s_c_z")) - (Vz * (x - "s_c_x"))\") (syntax-tree (\"-\" (\"*\" \"x-velocity\" (\"-\" \"z-coordinate\" "s_c_z")) (\"*\" \"z-velocity\" (\"-\" \"x-coordinate\" "s_c_x")))) (code (field-- (field-* (field-load \"x-velocity\") (field-- (field-load \"z-coordinate\") "s_c_z")) (field-* (field-load \"z-velocity\") (field-- (field-load \"x-coordinate\") "s_c_x")))))
						  ((name am-z-"name") (display \"(Vy * (x - "s_c_x")) - (Vx * (y - "s_c_y"))\") (syntax-tree (\"-\" (\"*\" \"y-velocity\" (\"-\" \"x-coordinate\" "s_c_x")) (\"*\" \"x-velocity\" (\"-\" \"y-coordinate\" "s_c_y")))) (code (field-- (field-* (field-load \"y-velocity\") (field-- (field-load \"x-coordinate\") "s_c_x")) (field-* (field-load \"x-velocity\") (field-- (field-load \"y-coordinate\") "s_c_y")))))
						  ))			   
					      "))



	  )
	)
      )
    )
  )

(set! wb-ice-cff-on-swirl-planes
  (lambda()
    (format  "\n\n\t\t ___________ Creating swirl custom field functions _____________\t\n\n")
    (if (and (read-var ICDyMeshSetFile 'cylinder_axis) (read-var solver-set-file 'swirl_def))
      (begin
	(define swirl-def (read-var solver-set-file 'swirl_def))
	(do ((i 0 (+ i 1))) ((= i (length swirl-def)))
	  (let
	    (
	     (name  (cadr (assoc 'name (list-ref swirl-def i))))
	     (swirl-center (cadr (assoc 'swirl-center (list-ref swirl-def i))))
	     (swirl-axis (cadr (assoc 'swirl-axis (list-ref swirl-def i))))
	     (function (cadr (assoc 'function (list-ref swirl-def i))))
	     (list-cff (cx-inquire-user-def-cf-names))
	     )
	    (if (member (string->symbol name) list-cff)
	      (begin
		(format "\n\nNote: CFF with name \"~s\" already exist? \nOverwritng with the new CFF.\n\n " (string->symbol name)) 
		(ti-menu-load-string (format #f "/def cff delete (~s)" (string->symbol name)) )
		)		    
	      )
	    (create-cff-am-swirl (string-append name) swirl-center)
	    (format  "\n")
	    (ti-menu-load-string (string-append "/def cff def \""name"\" "function))
	    )

	  )
	)
      )
    )
  )





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

(set! get-unit-vector
  (lambda(axis)
    (let
      (
        (mod (sqrt (+ (* (car axis) (car axis)) (* (cadr axis) (cadr axis)) (* (caddr axis) (caddr axis))) ) )
	(temp-axis '())
       )
      (set! temp-axis (list-add temp-axis (/ (car axis) mod)) )
      (set! temp-axis (list-add temp-axis (/ (cadr axis) mod)) )
      (list-add temp-axis (/ (caddr axis) mod))
      )
    )
  )


(set! order-events-based-on-crank-angle
  (lambda()
    (let
      (
       (event-list (rpgetvar 'dynamesh/in-cyn/event-list))
       (CA-list '())
       (temp-event-list '())
       (event-list-ordered '())
       (start-CA 0)
       (start-CA-ordered 0)
       (insert-flag 0)
       )
      (set! event-list-ordered (insert-element-in-list (list-ref event-list 0) 0 event-list-ordered))
      (set! temp-event-list event-list-ordered)

      (do ((i 1 (+ i 1))) ((= i  (length  event-list)))

	(set! insert-flag 0)
	(set! start-CA (cdr (assoc 'start (list-ref event-list i))) )

	(do ((j 0 (+ j 1))) ((= j  (length  event-list-ordered)))
	  (set! start-CA-ordered (cdr (assoc 'start (list-ref event-list-ordered j))) )
	  (if (< start-CA start-CA-ordered)
	    (begin
	      (set! temp-event-list (insert-element-in-list (list-ref event-list i) j  temp-event-list))
	      (set! insert-flag 1)
	      (set! j (- (length  event-list-ordered) 1))		
	      )
	    )	   
	  )
	(if (= insert-flag 0)
	  (set! temp-event-list (insert-element-in-list (list-ref event-list i) (length  event-list-ordered) temp-event-list))
	  )		
	(set! event-list-ordered temp-event-list)
	)    
      (rpsetvar 'dynamesh/in-cyn/event-list event-list-ordered)
      )

    )
  )


(set! wb-ice-post-iter-plot-residual
  (lambda()
    (format  "\n\n\t\t ___________plot residual _____________\t\n\n")
    (if (string-ci=? solution-type "port-flow")
      (begin
	(ti-menu-load-string "/plot residual")
	(if (file-exists? "residual.jpg")
	  (ti-menu-load-string (format #f "/dis hc ~aice-residual.jpg y" wb-ice-report-dir-path))
	  (ti-menu-load-string (format #f "/dis hc ~aice-residual.jpg " wb-ice-report-dir-path))
	  )
	)
      )
    (if (or (string-ci=? solution-type "cold-flow") (string-ci=? solution-type "combustion"))
      (begin
	(let
	  (
	   (last-iter (rpgetvar 'ice/residual-iteration-history))
	   (curr-iter (client-inquire-iteration))
	   (n-display 1000)
	   (CA (time->absolute-crank-angle (rpgetvar 'flow-time)))
	   )
	  (if (> curr-iter 0)
	    (begin
	      (set! n-display (- curr-iter last-iter))
	      (if (< n-display 0)
                 (set! n-display curr-iter)
		)	      
	      (if (> n-display 0)
		(begin
		(ti-menu-load-string (format #f "/sol mon res n-display ~s" (string->symbol (number->string n-display))))
		(ti-menu-load-string "/plot residual")
		(if (file-exists? (string-append  wb-ice-report-dir-path "ice-residual-final.jpg"))
		  (ti-menu-load-string (format #f "/dis hc ~aice-residual-final.jpg  y" wb-ice-report-dir-path))
		  (ti-menu-load-string (format #f "/dis hc ~aice-residual-final.jpg" wb-ice-report-dir-path))
		  )
		)
		)
	      )
	    )

	  )
     (wb-ice-write-iterations-per-time-step)
     ;;DE81879: need to write relaxation URFs at the end of simulation
     (ti-menu-load-string (format #f  "/def dm eve eef ~aice-event_file" wb-ice-report-dir-path) )


	)
      )

    )
  )


(set! wb-ice-setup-view
  (lambda()
    (if (data-valid?)
      (begin
	(do ((i 0 (+ i 1))) ((= i (length (cx-get-views))))
	  (let 
	    (
	     (view-name (symbol->string (view->name (list-ref (cx-get-views) i))))	     
	     )
	    (if (> (string-length view-name) 12)
	      (begin
		(if (string-ci=? (substring view-name 0 12) "ice_cutplane")
		  (begin
		    (set! i (- (length (cx-get-views)) 1))
		    (ti-menu-load-string (format #f "/dis view r-v ~s" (string->symbol view-name)))
		    )

		  )
		)
	      )
	    )
	  )
	)
      )
    )
  )

(set! wb-ice-plot-residual-events
  (lambda()
    (let
      (
       (event01 '())
       (event02 '())
       (event03 '())
       (event04 '())
       (cur-event-list '())
       (pre-event-list '())
       )
      (set! event01 (list '(active . #t) (cons 'name "save-residual-plot-180") (cons 'start 180) (list 'action 15 (format #f "(wb-ice-plot-residual)")))) 
      (set! event02 (list '(active . #t) (cons 'name "save-residual-plot-360") (cons 'start 360) (list 'action 15 (format #f "(wb-ice-plot-residual)")))) 
      (set! event03 (list '(active . #t) (cons 'name "save-residual-plot-540") (cons 'start 540) (list 'action 15 (format #f "(wb-ice-plot-residual)")))) 
      (set! event04 (list '(active . #t) (cons 'name "save-residual-plot-720") (cons 'start 720) (list 'action 15 (format #f "(wb-ice-plot-residual)")))) 

      (set! cur-event-list (list event01 event02 event03 event04)) 

      ; Append current events to previously set up events if any

      (set! pre-event-list (rpgetvar 'dynamesh/in-cyn/event-list))

      (rpsetvar 'dynamesh/in-cyn/event-list (append pre-event-list cur-event-list))
      )
    )
  )

(set! wb-ice-crevice-setup
  (lambda()
    (let
      (
       (ave_scale 0)
       )
      (if (thread-name->id "fluid-crevice")
	(begin
	  (format  "\n\n\t\t ___________Interfaces and Dynamic Mesh Setup of Crevice_____________\t\n\n") 

	  (if (and  (thread-name->id "intf-crevice-on-piston") (thread-name->id "intf-piston-on-crevice"))
	    (begin
	      (changeBC "intf-crevice-on-piston" "interface")
	      (changeBC "intf-piston-on-crevice" "interface")
        (if matching_interface
          (createMeshInterface "intf-fluid-piston-crevice"  "intf-crevice-on-piston" "intf-piston-on-crevice" '(matching #t))
          (createMeshInterface "intf-fluid-piston-crevice"  "intf-crevice-on-piston" "intf-piston-on-crevice" )
        )
	      )
	    )
	  (if (thread-name->id "piston")
	    (set! ave_scale (+ (* 0.5 (car (%get-min-max-length-scale-on-zone (thread-name->id  "piston") #t))) (* 0.5 (car (cdr (%get-min-max-length-scale-on-zone (thread-name->id  "piston") #t))))))
	    )

	  (createRigidBodyDynMeshZone "fluid-crevice" piston-full-prof cylinder_axis )
	  (createRigidBodyDynMeshZone "intf-crevice-on-piston" piston-full-prof cylinder_axis (list 'cell-ht1 ave_scale))
	  (createRigidBodyDynMeshZone "cyl-crevice" piston-full-prof cylinder_axis '(exclude-bc "yes"))

	  (if (thread-name->id "symm-crevice")
	    (changeBC "symm-crevice" "symmetry")
	    )

	  )
	)
      )
    )
  )
(set! wb-ice-read-keygrid-data
  (lambda()
    (let
      (
       (key-grid-file  "../ICE/KeyGrids/keygrid.txt")
       (input-file-port #f)
       (key-grid-data "")
       (line-string-list '())
       (key-grid-angle 0)
       (key-grid-mesh "")          
       (key-grid-zones '())
       (key-grid-zones-string '())
       )
      (if (file-exists? key-grid-file)
        (begin
          (set! wb-ice-keygrid-mesh-list '())
          (set! input-file-port (open-input-file key-grid-file))

          (set! key-grid-data (read-line input-file-port))
          (let loop ()
            (if (> (string-length key-grid-data) 0)
              (loop 
                (set! line-string-list (string-split key-grid-data))
                (set! key-grid-angle (string->number (cadr line-string-list))) 
                (set! key-grid-mesh (caddr line-string-list))
                (set! key-grid-zones-string '())
                (if (> (length line-string-list) 3)
                  (begin
                    (set! key-grid-zones-string "'")
                    (set! key-grid-zones (cdddr line-string-list))
                    (for-each 
                      (lambda (s)
                        (set! key-grid-zones-string (string-append key-grid-zones-string s " "))
                      ) key-grid-zones
                    )
                    ;(format "\n\nkeygrid zonoes for angle ~a : ~a" key-grid-angle key-grid-zones-string)
                  )
                )
                (set! wb-ice-keygrid-mesh-list (list-add wb-ice-keygrid-mesh-list (list key-grid-angle key-grid-mesh key-grid-zones-string)))
                (set! key-grid-data (read-line input-file-port))
              )
            )
          )     
        )
      )
    )
  )
)
(set! wb-ice-keygrid-events
  (lambda (ket-grid-list)
    (let
      (
       (event '())
       (CA 0)
       (mesh-file "")
       (cur-event-list '())
       (pre-event-list '())
       (zone_list '())
       )
      (do ((i 1 (+ i 1))) ((= i (length ket-grid-list)))
	(set! CA (car (list-ref ket-grid-list i)))
	(set! mesh-file (cadr (list-ref ket-grid-list i)))
	;(if (file-exists? (string-append "../ICE/KeyGrids/" mesh-file))
	  ;(begin
	    (set! mesh-file (string-append "../ICE/KeyGrids/" mesh-file))
      (set! zone_list (caddr (list-ref ket-grid-list i)))
      ;(format "zone list is = ~a " zone_list)
	    (set! event (list '(active . #t) (cons 'name (format #f "key-grid-~s"CA)) (cons 'start CA) (list 'action 15 (format #f "(wb-ice-mesh-replace ~s ~s ~a '(wb_ice_only_smoothing? #f))"mesh-file "program-controlled" zone_list)))) 
	    (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))      
      )
    )
  )




(define wb-ice-self-exec-method)
(set! wb-ice-self-exec-method
  (lambda()    
    (let
      (
       (dir-path (string-append (wb-get-dir) "/"))
       (custom-file "")
       (set-file "")
       (bc-file "")
       (user-bc-file "")
       (pre-journal "")
       (post-journal "")
       )
      ;set defaults
      (if (file-exists? (string-append dir-path "../Report"))
          (set! wb-ice-report-dir-path "../Report/"))
      (set! custom-file (string-append wb-ice-report-dir-path "ice-custom-file-list"))
      (if(file-exists? (string-append dir-path custom-file))
	(begin
	  (if (read-var custom-file 'solver-setting-file)
	    (if (string? (read-var custom-file 'solver-setting-file))
	      (set! set-file (read-var custom-file 'solver-setting-file))
	      (set! set-file (symbol->string (read-var custom-file 'solver-setting-file)))
	      )
	    (if (< (rpgetvar 'fluent-case-version) 145 ) ;this condition is for files for 14.0
	      (set! set-file "icDyMSettings.txt")
	      (set! set-file "icSolverSettings.txt")
	      )
	    )
	  (if (read-var custom-file 'bc-file)
	    (if (string? (read-var custom-file 'bc-file))
	    (set! bc-file (read-var custom-file 'bc-file) )
	      (set! bc-file (symbol->string (read-var custom-file 'bc-file) ) )
	      )
	    (set! set-file "icBcSettings.txt")
	    )
	  (if (read-var custom-file 'user-bc-file)
	    (if (string? (read-var custom-file 'user-bc-file))
	    (set! user-bc-file (read-var custom-file 'user-bc-file))
	      (set! user-bc-file (symbol->string (read-var custom-file 'user-bc-file)))
	      )
	    (set! user-bc-file "icUserSettings.txt")
	    )
	  (if (read-var custom-file 'pre-iter-file )
	    (set! pre-journal (read-var custom-file 'pre-iter-file ))
	    )
	  (if  (read-var custom-file 'post-iter-file )
	    (set! post-journal (read-var custom-file 'post-iter-file ))
	    )

	  (if(file-exists? (string-append dir-path "../ICE/" (strip-directory  set-file)))
	    (set! ICDyMeshSetFile (string-append "../ICE/" (strip-directory  set-file)))
	    )

	  (if(file-exists? (string-append dir-path "../ICE/" (strip-directory  bc-file)))
	    (begin
	      (set! system-solver-set-file (string-append dir-path "../ICE/" (strip-directory  bc-file)))
	      (set! solver-set-file (string-append dir-path "../ICE/" (strip-directory  bc-file)))
	      (set! solution-type   (read-var system-solver-set-file 'solution-type))  
          (if (read-var system-solver-set-file 'combustion_simulation_type) 	(set! combustion-simulation-type   (read-var system-solver-set-file 'combustion_simulation_type)))          
	      )
	    )
	  (if(file-exists? (string-append dir-path "../ICE/" (strip-directory  user-bc-file)))
	    (set! user-solver-set-file (string-append dir-path "../ICE/" (strip-directory  user-bc-file)))
	    )
	  (if (file-exists? (string-append dir-path "../ICE/" (strip-directory  pre-journal)))
	    (set! wb-ice-pre-iteration-journal (string-append dir-path "../ICE/" (strip-directory  pre-journal)))
	    )
	  (if (file-exists? (string-append dir-path "../ICE/" (strip-directory  post-journal)))
	    (set! wb-ice-post-iteration-journal (string-append dir-path "../ICE/" (strip-directory  post-journal)))
	    )

	  (wb-ic-write-custom-files)
	  (if (wb-get-dir) 
	    (wb-changedir (wb-get-dir) )
	    )
	  )

	)
      (if (and (in-wb?) (wb-in-batch-mode?))
	(wb-ic-register-post-journal)
	)
	       

      )
    )
  )


(define wb-check-dir)
(set! wb-check-dir
  (lambda()
    (let
      (
       (icedir "./")
       (custom-file (string-append wb-ice-report-dir-path "ice-custom-file-list"))
       (wb-dir "")
       )

      (if (wb-get-dir) 
	(set! wb-dir (wb-get-dir) )
	)


      (if (> (string-length wb-dir) 0)
	(set! icedir (wb-get-dir))
	(begin
	  (set! icedir case-dir-name)
	  (wb-changedir icedir)
	  )
	)
      (if (> (string-length icedir) 2)
	(begin
	;(wb-ice-report-dir)
        (set! custom-file (string-append icedir "/" custom-file))
	)
	)
      (if(and (not (file-exists? custom-file)) (not (> (string-length wb-dir) 0)) ) ;seconnd condition is when the scheme is read through WB at the very begining 
	(begin
	  (format  "\n\n\t\t ___________ICE directory error _____________\t\n\n")
	  (format  "\n  Could not locate \"ice-custom-file-list\".\n")
	  (format  "\n  Make sure ICE project directory structure is maintained.\n")
	  (format  "\n  Note:- Scheme file should be read after Fluent case file.\n")
	  )
	)	  

      )
    )
  )

(set!  wb-ice-rpvars-init
  (lambda()


    ;1)  ice/residual-iteration-history
    (if (not (rp-var-object 'ice/residual-iteration-history))
      (rp-var-define 'ice/residual-iteration-history 0 'integer #f))

    ;2) auto save case-data crank angle based
    (if (not (rp-var-object 'ice/auto-save/CA))
      (rp-var-define 'ice/auto-save/CA  #f 'bool 1)
      )
    (if (not (rp-var-object 'ice/auto-save/CA/frquency))
      (rp-var-define 'ice/auto-save/CA/frquency  30 'int 1)
      )
    (if (not (rp-var-object 'ice/solution-type))
      (rp-var-define 'ice/solution-type  "cold-flow" 'string 1)
      )
    (if (not (rp-var-object 'ice/combustion-simulation-type))
      (rp-var-define 'ice/combustion-simulation-type "" 'string 1)
      )
    (if (not (rp-var-object 'ice/ahrr-min-open-angle))
      (rp-var-define 'ice/ahrr-min-open-angle 0 'number 1)
      )
    (if (not (rp-var-object 'ice/ahrr-max-close-angle))
      (rp-var-define 'ice/ahrr-max-close-angle 0 'number 1)
    )
    (if (not (rp-var-object 'ice/setup-valve-list))
      (rp-var-define 'ice/setup-valve-list '() 'list 1)
    )
    (if (not (rp-var-object 'ice/engine-piston-type))
      (rp-var-define 'ice/engine-piston-type 0 'number 1)
    )
    (if (not (rp-var-object 'ice/in_cylinder_parameter_list))
      (rp-var-define 'ice/in_cylinder_parameter_list 0 'number 1)
    )
    (if (not (rp-var-object 'ice/inlet_outlet_bc_list_parametric))
      (rp-var-define 'ice/inlet_outlet_bc_list_parametric 0 'number 1)
    )
    (if (not (rp-var-object 'ice/wall_bc_list_parametric))
      (rp-var-define 'ice/wall_bc_list_parametric 0 'number 1)
    )
    

    )
  )


(wb-check-dir)
(wb-ice-self-exec-method)

(define (wb-ice-update-monitor-after-thread-split-or-merge list-1 list-2)
  (let ((loop-list '())
        (is-2d? #t))
    (if (= 1 (length list-1))
      (if (member (car list-1) (map thread-id (get-face-threads)))
        (begin
          (set! loop-list (append (rpgetvar 'monitor/drag)
                                  (rpgetvar 'monitor/lift)
                                  (rpgetvar 'monitor/moment)))
          (if (pair? surface-mon-list)
            (set! loop-list (append loop-list (return-rpvar-from-session-variable surface-mon-list))))
          (set! is-2d? #t))
        (begin
          (if (pair? vol-mon-list)
            (set! loop-list (return-rpvar-from-session-variable vol-mon-list))
            (set! loop-list '()))
          (set! is-2d? #f))
        )
      (if (member (car list-2) (map thread-id (get-face-threads)))
        (begin
          (set! loop-list (append (rpgetvar 'monitor/drag)
                                  (rpgetvar 'monitor/lift)
                                  (rpgetvar 'monitor/moment)))
          (if (pair? surface-mon-list)
            (set! loop-list (append loop-list (return-rpvar-from-session-variable surface-mon-list))))
          (set! is-2d? #t)
          )
        (begin
          (if (pair? vol-mon-list)
            (set! loop-list (return-rpvar-from-session-variable vol-mon-list))
            (set! loop-list '()))
          (set! is-2d? #f))
        )
      )
    (for-each (lambda (mon)
                (let ((zone/surface/thread-list '())
                      (temp-list '())
                      (all-surfs '())
                      (merged-zone-present? #f)
                      (thread-type 'zones)
                      )
                  (set! zone/surface/thread-list (or (assoc 'zones mon)
                                                     (assoc 'thread-list mon)
                                                     (assoc 'surfaces mon)))
                  (if zone/surface/thread-list
                    (set! thread-type (car zone/surface/thread-list)))
                  (set! all-surfs (convert-surface-ids-to-zone-ids (cdr zone/surface/thread-list)))
                  (if (= 1 (length list-1))
                    ;; This block takes care of thread split.
                    (if (member (car list-1)
                                (if (equal? thread-type 'surfaces)
                                  (car all-surfs)
                                  zone/surface/thread-list))
                      (set-cdr! zone/surface/thread-list (append (cdr zone/surface/thread-list)
                                                                 (if (equal? thread-type 'surfaces)
                                                                   (append (convert-zone-ids-to-surface-ids list-2) (cdr all-surfs))
                                                                   list-2))))
                    ;; This block takes care of threads merger.
                    (begin
                      (for-each (lambda (z)
                                  (if (not (member z (append list-1 list-2)))
                                    (set! temp-list
                                      (if (equal? thread-type 'surfaces)
                                        (append (convert-zone-ids-to-surface-ids (list z)) temp-list)
                                        (cons z temp-list)))
                                    (set! merged-zone-present? #t))
                                  )
                                (if (equal? thread-type 'surfaces)
                                  (car all-surfs)
                                  (cdr zone/surface/thread-list))
                                )
                      (if merged-zone-present?
                        (set! temp-list (append (if (equal? thread-type 'surfaces)
                                                  (append (convert-zone-ids-to-surface-ids list-2) (cdr all-surfs))
                                                  list-2) temp-list)))
                      (set-cdr! zone/surface/thread-list temp-list)
                      )))
                ) loop-list)
    ;; Updating the rpvar.
    (if is-2d?
      (begin
        (rpsetvar 'monitor/drag (rpgetvar 'monitor/drag))
        (rpsetvar 'monitor/lift (rpgetvar 'monitor/lift))
        (rpsetvar 'monitor/moment (rpgetvar 'monitor/moment))
        (if (pair? surface-mon-list)
          (rpsetvar 'monitor/surfaces (return-rpvar-from-session-variable surface-mon-list)))
        )
      (if (pair? vol-mon-list)
        (rpsetvar 'monitor/volume (return-rpvar-from-session-variable vol-mon-list))))
    ))
 (set! wb-ice-ca-based-case-data-save-frequency
   (lambda (save-frequency)
   
    (let 
     ( (auto-save-freq 1)
     )
    (ti-menu-load-string (format #f "/file/auto-save/data-frequency ~s " auto-save-freq))
    (rpsetvar 'ice/auto-save/CA #t)
    (rpsetvar 'ice/auto-save/CA/frquency save-frequency)
    )
   )
 )

(set! wb-ice-get-setup-valve-list
  (lambda ()
    (let ((valve_list '()))
      (if (not (or (string-ci=? combustion-simulation-type "full_engine_ivc_to_evo") (string-ci=? combustion-simulation-type "sector")))
        (set! valve_list (read-var ICDyMeshSetFile 'setup_valve_list)))
    valve_list)
))

(define (path-with-forward-slash str)
  (let ((char-lst (string->list str))
        (i 0))
    (for-each (lambda (c)
                (if (eqv? #\\ c) (string-set! str i #\/))
                (set! i (+ i 1)))
              char-lst))
  str)

(set! wb-ice-read-transient-table-data
  (lambda ()
    (format #t "reading transient table data files \n ")
    (if (read-var ICDyMeshSetFile 'transient-table-file )
      (begin
        (let
          (
            (file_path_list (read-var ICDyMeshSetFile 'transient-table-file))
            (dp0_dir "")
          
          )
         (for-each 
          (lambda (file_path)
            (if (wb-get-dir) 
              (set! dp0_dir (directory (directory (wb-get-dir)))) 
              (set! dp0_dir (directory (directory (directory (client-default-basename "r")))))
            )
            (set! file_path (string-append (path-with-forward-slash dp0_dir) "/" (path-with-forward-slash file_path)))
            (if (file-exists? file_path)
              (ti-menu-load-string (format #f "/file read-transient-table ~s" file_path ))
              (begin 
                (format #t "\n Failed to read following file. Please check the file path \n" )
                (format #t file_path )
              )
            )
          ) file_path_list
         )
        )
      )
    )
  )
)

(set! wb-ice-read-multiple-profiles-data
  (lambda ()
    (format #t "\n\n reading profiles files \n ")
    (if (read-var ICDyMeshSetFile 'profile-file )
      (begin
        (let
          (
            (file_path_list (read-var ICDyMeshSetFile 'profile-file))
            (dp0_dir "")
          
          )
         (for-each 
          (lambda (file_path)
            (if (wb-get-dir) 
              (set! dp0_dir (directory (directory (wb-get-dir)))) 
              (set! dp0_dir (directory (directory (directory (client-default-basename "r")))))
            )
            (set! file_path (string-append (path-with-forward-slash dp0_dir) "/" (path-with-forward-slash file_path)))
            (if (file-exists? file_path)
              (ti-menu-load-string (format #f "/file read-profile ~s" file_path ))
              (begin 
                (format #t "\n Failed to read following file. Please check the file path \n" )
                (format #t file_path )
              )
            )
          ) file_path_list
         )
        )
      )
    )
  )
)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(set! wb-ice-define-initial-model-settings
  (lambda ()
    ; Change length units, otherwise the limit setup will not be correct because SI is assumed for limits
    (format  "\n\n\t\t ___________Setting Up initial-model-settings _____________\t\n\n") 
    (ti-menu-load-string "/def/units/length m")
    (ti-menu-load-string "/def/units/temperature k")
    (ti-menu-load-string "/def/units/pressure pascal")
    ; Solver setup
    
    (ti-menu-load-string "/def/mod/unsteady-1st-order yes")
    (ti-menu-load-string "/def/material/cc air , y ideal-gas y piecewise-polynomial ,,,,,,,,,,,,,,,,,,,,,,, ,,,,,")
    (ti-menu-load-string "/dis/set/hardcopy/driver tiff /dis/set/hardcopy/color/color")
    (ti-menu-load-string "/def/mod/viscous/ke-standard y")
    (ti-menu-load-string "/sol/mon/residual/con-c 0.001 ,,,,, 2e-3")
    (ti-menu-load-string "/sol/set/dis-s/press 14")
    (ti-menu-load-string "/sol/set/p-v-coupling 22 /sol/set/p-v-controls 0 1 yes")
    (ti-menu-load-string "/sol/set/un-rel/press 0.5 /sol/set/un-rel/k 0.4 /sol/set/un-rel/epsilon 0.4")
    (ti-menu-load-string "/sol/set/limits 800 , 60 ,,,,")
    (rpsetvar 'partition/encapsulate-si? #f)
  )
)

(set! wb-ice-define-dynamic-settings-for-valves-layering
  (lambda (valve_list)
    (format  "\n\t\t ___________define valve interfaces for layering-approach _____________\t\n\n")
    (for-each
      (lambda (valve_value)
        (ti-menu-load-string (string-append  "/def/bc/zt intf-" (list-ref valve_value 1) "-ob-fluid-ch-upper interface"))
        (ti-menu-load-string (string-append  "/def/bc/zt intf-" (list-ref valve_value 1) "-ob-fluid-ch-lower interface"))
        (ti-menu-load-string (string-append  "/def/bc/zt intf-" (list-ref valve_value 1) "-ob-fluid-ch-valve interface"))
        (ti-menu-load-string (string-append  "/def/mi/create " (list-ref valve_value 1) " intf-" (list-ref valve_value 1) "-ob-fluid-ch-valve () intf-" (list-ref valve_value 1) "-ob-fluid-ch-upper intf-" (list-ref valve_value 1) "-ob-fluid-ch-lower () no"))
        ;setting invalve-ch new layer height as 2*vlayer height for smoothing-on as false otherwise set it to 1mm
        (set! smoothing-on (cadr (assoc 'smoothing valve_value)))
        (if (not (string-ci=? (list-ref valve_value 2) "(null)"))
            (if smoothing-on 
              (ti-menu-load-string (string-append  "/define/d-m/zones/create " (list-ref valve_value 1) "-ch rigid-body " (list-ref valve_value 2) " no " (number->string (list-ref (list-ref valve_value 6) 0)) " " (number->string (list-ref (list-ref valve_value 6) 1)) " " (number->string (list-ref (list-ref valve_value 6) 2)) " ,, "(number->string chamber-mesh-size) ))
              (ti-menu-load-string (string-append  "/define/d-m/zones/create " (list-ref valve_value 1) "-ch rigid-body " (list-ref valve_value 2) " no " (number->string (list-ref (list-ref valve_value 6) 0)) " " (number->string (list-ref (list-ref valve_value 6) 1)) " " (number->string (list-ref (list-ref valve_value 6) 2)) " ,, " (number->string (+ (* 0.6 (car (%get-min-max-length-scale-on-zone (thread-name->id  (string-append (list-ref valve_value 1) "-ch")) #f))) (* 0.6 (car (cdr (%get-min-max-length-scale-on-zone (thread-name->id  (string-append (list-ref valve_value 1) "-ch")) #f)))))) ))
            )
            (if smoothing-on 
              (ti-menu-load-string (string-append  "/define/d-m/zones/create " (list-ref valve_value 1) "-ch stationary ,, " (number->string chamber-mesh-size) ))
              (ti-menu-load-string (string-append  "/define/d-m/zones/create " (list-ref valve_value 1) "-ch stationary ,, " (number->string (+ (* 0.6 (car (%get-min-max-length-scale-on-zone (thread-name->id  (string-append (list-ref valve_value 1) "-ch")) #f))) (* 0.6 (car (cdr (%get-min-max-length-scale-on-zone (thread-name->id  (string-append (list-ref valve_value 1) "-ch")) #f)))))) ))
            )
        )
        
        (ti-menu-load-string (string-append  "/define/d-m/zones/create fluid-ch-" (list-ref valve_value 1) " rigid-body " piston-full-prof "  " (number->string (list-ref (list-ref valve_value 6) 0)) " " (number->string (list-ref (list-ref valve_value 6) 1)) " " (number->string (list-ref (list-ref valve_value 6) 2))))
  
      ) valve_list
    )
  )
)

(set! wb-ice-dyn-mesh-zone-names-check-layering
  (lambda ()
    (let 
      (
        (dyn_zone_check_list '())
        (dyn_zone_check_list_conformal '())
        (dyn_zone_check_list_nonconformal '())
        (dyn_zone_check_list_prev '())
        (all_surfaces (inquire-surface-names))
        (surface_counter 0)
        (final_list (list))
        (matched #f)
      )

      (format  "\n\n\t\t ___________Validating Zone Names _____________\t\n\n")  
    
      (set! dyn_zone_check_list (list "fluid-piston" "fluid-ch-lower" "piston" "intf-piston-ch" "intf-piston-bowl" ))
      (set! dyn_zone_check_list_nonconformal (list "intf-deck-fluid-ch-lower" "intf-deck-fluid-ch-upper") )
        
      (for-each
        (lambda (valve_value)

          (set! dyn_zone_check_list_prev (list
              (string-append "fluid-ch-" (list-ref valve_value 1) )
              (string-append "fluid-" (list-ref valve_value 1) "-ib")
              (string-append "fluid-" (list-ref valve_value 1) "-vlayer")
              (string-append "intf-" (list-ref valve_value 1) "-ib-fluid-ib")
              (string-append "intf-" (list-ref valve_value 1) "-ib-fluid-ob-quad")
              (string-append "intf-" (list-ref valve_value 1) "-ib-fluid-ob-tri")
              (string-append "intf-" (list-ref valve_value 1) "-ob-fluid-ch-lower")
              (string-append "intf-" (list-ref valve_value 1) "-ob-fluid-ch-upper")
              (string-append "intf-" (list-ref valve_value 1) "-ob-fluid-ch-valve")
              (string-append "intf-" (list-ref valve_value 1) "-ob-fluid-vlayer")
              (string-append "intf-piston-" (list-ref valve_value 1) )
              (string-append (list-ref valve_value 1) "-ch" )
              (string-append (list-ref valve_value 1) "-ib" )
              (string-append (list-ref valve_value 1) "-ob" )
              (string-append (list-ref valve_value 1) "-seat"))
          )
   
          (set! dyn_zone_check_list_conformal (append dyn_zone_check_list_conformal (list 
              (string-append "int-" (list-ref valve_value 1) "-ib" )
              (string-append "int-" (list-ref valve_value 1) "-ob" )
              ))
          )

          (set! dyn_zone_check_list_nonconformal (append dyn_zone_check_list_nonconformal (list 
                  (string-append "intf-int-" (list-ref valve_value 1) "-ib-fluid-ib")
                  (string-append "intf-int-" (list-ref valve_value 1) "-ib-fluid-port")
                  (string-append "intf-int-" (list-ref valve_value 1) "-ob-fluid-port")
                  (string-append "intf-int-" (list-ref valve_value 1) "-ob-fluid-vlayer")
                  ))
          )


          (set! dyn_zone_check_list (append dyn_zone_check_list dyn_zone_check_list_prev))

        )setup-valve-list
      )

      (if (string-ci=? conf/nonconf "c")
        (set! dyn_zone_check_list (append dyn_zone_check_list dyn_zone_check_list_conformal))
        (set! dyn_zone_check_list (append dyn_zone_check_list dyn_zone_check_list_nonconformal))
      )	

      (set!  all_surfaces (append all_surfaces (inquire-zone-names)))
    
      (for-each
        (lambda (dyn_zone)
          (if dyn_zone
            (begin      
              (set! matched #f)
              (for-each
                (lambda (surfacename)
                  (if (string-ci=? (symbol->string surfacename) dyn_zone)
                    (begin 
                      (set! surface_counter (+ surface_counter 1))
                      (set! matched #t)
                    )
                  ) 
                ) all_surfaces
              )
              (if (not matched)
                (set! final_list (append final_list (list dyn_zone )))
              )
            )
          )    
        ) dyn_zone_check_list
      )
      final_list
    )
  )
)

(set! wb-ice-define-dyn-mesh-settings-layering
  (lambda ()
    (format  "\n\n\t\t ___________Setting dyn-mesh-settings-layering _____________\t\n\n") 
    (ti-menu-load-string "/def/d-m/controls/layering y ")
    (ti-menu-load-string "/def/d-m/controls/smoothing y")
    (ti-menu-load-string "/def/d-m/controls/layering-parameter/constant-height no ")
    (ti-menu-load-string "/def/d-m/controls/layering-parameter/collapse-factor 0.2 ")
    (ti-menu-load-string "/def/d-m/controls/remeshing n ")
  )
)


(set! wb-ice-define-ib-ob-interfaces
  (lambda ()
     (format  "\n\n\t\t ___________ Changing zone types to Interface for ib, ob bodies _____________\t\n\n")
    (let
      (
        (valve_name "")
      )
      (for-each
        (lambda (valve_list)
          (set! valve_name (list-ref valve_list 1))
          (if (and (thread-name->id (string-append "fluid-" valve_name "-ib")) (thread-name->id (string-append "fluid-" valve_name "-vlayer")))
            (begin
              (ti-menu-load-string (string-append  "/def/bc/zt intf-" valve_name "-ib-fluid-ib interface"))
              (ti-menu-load-string (string-append  "/def/bc/zt intf-" valve_name "-ib-fluid-ob-quad interface"))
              (ti-menu-load-string (string-append  "/def/bc/zt intf-" valve_name "-ib-fluid-ob-tri interface"))
              (ti-menu-load-string (string-append  "/def/bc/zt intf-" valve_name "-ob-fluid-vlayer wall"))
              (if (string-ci=? hybrid/layering "l")
                (ti-menu-load-string (string-append  "/def/bc/zt intf-piston-" valve_name " interface"))
              )

              (if (string-ci=? conf/nonconf "n")
                (begin
                  (ti-menu-load-string (string-append  "/def/bc/zt intf-int-" valve_name "-ib-fluid-ib interface"))
                  (ti-menu-load-string (string-append  "/def/bc/zt intf-int-" valve_name "-ib-fluid-port interface"))
                  (ti-menu-load-string (string-append  "/def/bc/zt intf-int-" valve_name "-ob-fluid-port interface"))
                  (ti-menu-load-string (string-append  "/def/bc/zt intf-int-" valve_name "-ob-fluid-vlayer interface"))
                  )
              )
            )
          )
        ) (rpgetvar 'ice/setup-valve-list)
      )
      (format  "\n\n\t\t ___________ Creating Grid Interfaces for ib and ob bodies_____________\t\n\n") 
      (for-each
        (lambda (valve_list)
          (set! valve_name (list-ref valve_list 1))
          (if (and (thread-name->id (string-append "fluid-" valve_name "-ib")) (thread-name->id (string-append "fluid-" valve_name "-vlayer")))
            (begin
           ;DE30479 End
              (if matching_interface
                (define matching_string " no no yes")
                (define matching_string " no")
              )
              (if (string-ci=? hybrid/layering "l")
                (ti-menu-load-string (string-append  "/def/gi/create intf-" valve_name "-ib intf-" valve_name "-ib-fluid-ib () intf-" valve_name "-ib-fluid-ob-tri intf-" valve_name "-ib-fluid-ob-quad () " matching_string))
                (ti-menu-load-string (string-append  "/def/gi/create intf-" valve_name " intf-" valve_name "-ib-fluid-ib () intf-" valve_name "-ib-fluid-ob-quad intf-" valve_name "-ib-fluid-ob-tri () " matching_string ))          
              )
              (if matching_interface
                (define matching_string " no no no yes")
                (define matching_string " no")
              )
              (if (string-ci=? conf/nonconf "n")
                (begin
                  (ti-menu-load-string (string-append  "/def/gi/create intf-int-" valve_name "-ib intf-int-" valve_name "-ib-fluid-ib () intf-int-" valve_name "-ib-fluid-port () " matching_string))
                  (ti-menu-load-string (string-append  "/def/gi/create intf-int-" valve_name "-ob intf-int-" valve_name "-ob-fluid-port () intf-int-" valve_name "-ob-fluid-vlayer () " matching_string))
                  )
              )
            )
          )
        ) (rpgetvar 'ice/setup-valve-list)
      )
    )
  )
)
 
(set! wb-ice-define-ib-ob-interfaces-controls-layering
  (lambda ()
   (let
    (
      (ib_cell_height 0)
      (ob_cell_height 0)
      (smoothing_on #f)
    )
    (format  "\n\n\t\t ___________ Setting Dynamic Mesh Controls _____________\t\n\n")  
    (for-each
      (lambda (valve_list)
        ; Rigid body dynamic zone setup
        (format "\n\n\t\t ___________ Setting Dynamic Mesh Zones for ~s _____________\t\n\n" (list-ref valve_list 1) )  
        
        (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create fluid-" (list-ref valve_list 1) "-ib rigid-body " (list-ref valve_list 2) " " (number->string (list-ref (list-ref valve_list 6) 0)) " " (number->string (list-ref (list-ref valve_list 6) 1)) " " (number->string (list-ref (list-ref valve_list 6) 2))))
        (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create fluid-" (list-ref valve_list 1) "-vlayer rigid-body " (list-ref valve_list 2) " " (number->string (list-ref (list-ref valve_list 6) 0)) "  " (number->string (list-ref (list-ref valve_list 6) 1)) " " (number->string (list-ref (list-ref valve_list 6) 2))))
        (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create " (list-ref valve_list 1) "-ib rigid-body " (list-ref valve_list 2) " no " (number->string (list-ref (list-ref valve_list 6) 0)) " " (number->string (list-ref (list-ref valve_list 6) 1)) " " (number->string (list-ref (list-ref valve_list 6) 2)) " ,, 0"))
        (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create " (list-ref valve_list 1) "-ob rigid-body " (list-ref valve_list 2) " no " (number->string (list-ref (list-ref valve_list 6) 0)) " " (number->string (list-ref (list-ref valve_list 6) 1)) "  " (number->string (list-ref (list-ref valve_list 6) 2)) " ,, 0"))
       
        (if (string-ci=? conf/nonconf "c")
          (begin
            (set! ib_cell_height  (+ (* 0.5 (car (%get-min-max-length-scale-on-zone (thread-name->id  (string-append "int-" (list-ref valve_list 1) "-ib")) #f))) (* 0.5 (car (cdr (%get-min-max-length-scale-on-zone (thread-name->id  (string-append "int-" (list-ref valve_list 1) "-ib")) #f))))))
            (set! ob_cell_height  (+ (* 0.25 (car (%get-min-max-length-scale-on-zone (thread-name->id  (string-append "int-" (list-ref valve_list 1) "-ob")) #f))) (* 0.25 (car (cdr (%get-min-max-length-scale-on-zone (thread-name->id  (string-append "int-" (list-ref valve_list 1) "-ob")) #f))))))
            (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create int-" (list-ref valve_list 1) "-ib stationary " (string-append "fluid-" (list-ref valve_list 1)  "-ib") " ," (number->string ib_cell_height) " ,, 0"))
            (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create int-" (list-ref valve_list 1) "-ob stationary " (string-append "fluid-" (list-ref valve_list 1)  "-vlayer") " ," (number->string ob_cell_height) " ,, 0"))
            (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create " (list-ref valve_list 1) "-seat stationary ,, " (number->string ob_cell_height)))
          )
        )
        (if (string-ci=? conf/nonconf "n")
          (begin
            (set! ib_cell_height  (+ (* 0.5 (car (%get-min-max-length-scale-on-zone (thread-name->id  (string-append "intf-int-" (list-ref valve_list 1) "-ib-fluid-ib")) #f))) (* 0.5 (car (cdr (%get-min-max-length-scale-on-zone (thread-name->id  (string-append "intf-int-" (list-ref valve_list 1) "-ib-fluid-ib")) #f))))))
            (set! ob_cell_height  (+ (* 0.25 (car (%get-min-max-length-scale-on-zone (thread-name->id  (string-append "intf-int-" (list-ref valve_list 1) "-ob-fluid-vlayer")) #f))) (* 0.25 (car (cdr (%get-min-max-length-scale-on-zone (thread-name->id  (string-append "intf-int-" (list-ref valve_list 1) "-ob-fluid-vlayer")) #f))))))
            (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create intf-int-" (list-ref valve_list 1) "-ib-fluid-ib stationary " (string-append "fluid-" (list-ref valve_list 1)  "-ib") " ," (number->string ib_cell_height)))
            (set! smoothing_on #f)

            (if (assoc 'smoothing valve_list) 
              (set! smoothing_on (cadr (assoc 'smoothing valve_list)))
            )

            (if smoothing_on 
              (begin
                (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create intf-int-" (list-ref valve_list 1) "-ob-fluid-vlayer stationary " (string-append "fluid-" (list-ref valve_list 1)  "-vlayer") " , 0 " ))
                (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create " (list-ref valve_list 1) "-seat stationary ,, 0 " ))
              )
              (begin
                (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create intf-int-" (list-ref valve_list 1) "-ob-fluid-vlayer stationary " (string-append "fluid-" (list-ref valve_list 1)  "-vlayer") " , " (number->string ob_cell_height) ))
                (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create " (list-ref valve_list 1) "-seat stationary ,, " (number->string ob_cell_height) ))
              )
            )
          )
        )
        (ic-all-dz-update-cg-position) ;this is to update all the values in the dynamic mesh zones column
      ) setup-valve-list
    )
  )
 )
)
 
(set! wb-ice-define-events-at-valve-opening-closing
  (lambda ()
    (format  "\n\n\t\t ___________ Setting Dynamic Mesh Events _____________\t\n\n")  
   (let 
    (
      (event01 '())
      (event02 '())
      (event03 '())
      (event04 '())
      (cur_event_list '())
      (pre_event_list '())
      (event_name "")
      (open_angle "")
      (intf_name "")
      (zone1_name "")
      (zone2_name "")
      (valve_name "")
      (open_ca 0)
      (close_ca 0)
    )
    (for-each
      (lambda (valve_list)
        (set! valve_name (list-ref valve_list 1))
        (set! open_ca (list-ref valve_list 3))
        (set! close_ca (list-ref valve_list 4))
               
       ; Open and close valve events
        (if (and (string-ci=? hybrid/layering "l") (thread-name->id (string-append "intf-" valve_name "-ob-fluid-vlayer")) (thread-name->id (string-append "intf-" valve_name "-ob-fluid-ch-lower")) (thread-name->id (string-append "intf-" valve_name "-ob-fluid-ch-upper")) (thread-name->id (string-append "intf-" valve_name "-ob-fluid-ch-valve")))
          (begin
            (set! event01 (list '(active . #t) (cons 'name (string-append "open-" valve_name)) (cons 'start  open_ca ) (list 'action 2 valve_name (list (thread-name->id (string-append "intf-" valve_name "-ob-fluid-ch-valve")) (thread-name->id (string-append "intf-" valve_name "-ob-fluid-vlayer"))) (list (thread-name->id (string-append "intf-" valve_name "-ob-fluid-ch-lower")) (thread-name->id (string-append "intf-" valve_name "-ob-fluid-ch-upper"))) 0 0)))

            (set! event02 (list '(active . #t) (cons 'name (string-append "close-" valve_name)) (cons 'start  close_ca ) (list 'action 2 valve_name (list (thread-name->id (string-append "intf-" valve_name "-ob-fluid-ch-valve"))) (list (thread-name->id (string-append "intf-" valve_name "-ob-fluid-ch-lower")) (thread-name->id (string-append "intf-" valve_name "-ob-fluid-ch-upper"))) 0 0)))
          )
          (begin
            (if matching_interface
                (define matching_string "#t")
                (define matching_string "#f")
            )
            (set! event_name (string-append "open-" valve_name))
            (set! open_angle open_ca)
            (set! intf_name valve_name)
            (set! zone1_name (string-append "intf-" valve_name "-ob-fluid-ch"))
            (set! zone2_name (string-append "intf-" valve_name "-ob-fluid-vlayer"))
            (set! event01 
              (list '(active . #t) (cons 'name event_name) (cons 'start  open_angle) 
              (list 'action 15 (string-append "(wb-ice-define-valve-open-event \"" intf_name "\" "  "\"" zone1_name "\"" " "  "\"" zone2_name "\""  " " (number->string open_angle) " " matching_string ")" ))))
            (set! event02 (list '(active . #t) (cons 'name (string-append "close-" valve_name)) (cons 'start close_ca) (list 'action 3 valve_name)))
          )
        )
        (set! cur_event_list (list event01 event02)) 
        (set! pre_event_list (rpgetvar 'dynamesh/in-cyn/event-list))
        (rpsetvar 'dynamesh/in-cyn/event-list (append pre_event_list cur_event_list))
       
        ; Events for non-constant URFs and dt 
        (if (list-ref valve_list 8)
          (begin
            (set! event01 (list '(active . #t) (cons 'name (string-append "reduce-urf-due-to-open-" valve_name)) (cons 'start  (- open_ca 1) ) (list 'action 12 (list '(1 epsilon 0.2) '(1 k 0.2) '(1 mom 0.4) '(1 pressure 0.2)))))
            (set! event02 (list '(active . #t) (cons 'name (string-append "increase-urf-due-to-open-" valve_name)) (cons 'start  (+ open_ca  increment)) (list 'action 12 (list '(1 epsilon 0.4) '(1 k 0.4) '(1 mom 0.5) '(1 pressure 0.3)))))
            (set! event03 (list '(active . #t) (cons 'name (string-append "reduce-urf-due-to-close-" valve_name)) (cons 'start  (- close_ca  increment)) (list 'action 12 (list '(1 epsilon 0.2) '(1 k 0.2) '(1 mom 0.4) '(1 pressure 0.2)))))
            (set! event04 (list '(active . #t) (cons 'name (string-append "increase-urf-due-to-close-" valve_name)) (cons 'start (+ close_ca 1) ) (list 'action 12 (list '(1 epsilon 0.4) '(1 k 0.4) '(1 mom 0.5) '(1 pressure 0.3)))))    
           
            (set! cur_event_list (append cur_event_list  (list event01 event02 event03 event04)))
          )
        )
      ;; code moved to function (wb-ice-set-time-step-change-events-previous-support)
        (rpsetvar 'dynamesh/in-cyn/event-list (append pre_event_list cur_event_list))
      )
      (rpgetvar 'ice/setup-valve-list)
    )
  )
 )
)
 
(set! wb-ice-define-smoothing-events
  (lambda ()
    (format  "\n\n\t\t ___________ Setting smoothing events_____________\t\n\n") 
    (for-each
      (lambda (valve_list)
        (set-smoothing-events valve_list)
      ) setup-valve-list
    )
  )
)

(set! wb-ice-define-piston-interfaces-layering
  (lambda ()
    (let
      (
        (min_scale 1)
        (max_scale 1)
        (ave_scale 1)
        (piston_layer_height 1)
        (intf_piston_valveid_string "")
        (cyl_axis_x (number->string (car cylinder_axis)))
        (cyl_axis_y (number->string (cadr cylinder_axis)))
        (cyl_axis_z (number->string (caddr cylinder_axis)))
      )

      (format  "\n\n\t\t ___________  Creating Grid Interfaces for Piston _____________\t\n\n")  
      ; Change length unit to meter
     
      (ti-menu-load-string "/def/units/length m")
      
      (ti-menu-load-string (string-append  "/def/bc/zt intf-piston-ch interface"))
      (ti-menu-load-string (string-append  "/def/bc/zt intf-piston-bowl interface"))

      (if (string-ci=? conf/nonconf "n")
        (begin
          (ti-menu-load-string (string-append  "/def/bc/zt intf-deck-fluid-ch-lower interface"))
          (ti-menu-load-string (string-append  "/def/bc/zt intf-deck-fluid-ch-upper interface"))
        )
      )

      (for-each 
        (lambda (valve_list)
          (set! intf_piston_valveid_string (string-append intf_piston_valveid_string (string-append "intf-piston-" (list-ref valve_list 1))))
        (set! intf_piston_valveid_string (string-append intf_piston_valveid_string " "))
        ) setup-valve-list
      )
      ;;changes for straight valve crevice case when intf-crevice-on-piston zones is absent like in simple engine with crevice straight-valve-engine
      
      (if (and  (thread-name->id "fluid-crevice") 
                (not (thread-name->id "intf-crevice-on-piston")) 
                (thread-name->id "intf-piston-on-crevice")
          )
          (begin
            (changeBC "intf-piston-on-crevice" "interface")
            (set! intf_piston_valveid_string (string-append "/def/gi/create intf-piston intf-piston-bowl intf-piston-on-crevice () intf-piston-ch " intf_piston_valveid_string "() no"))
          )
          (set! intf_piston_valveid_string (string-append "/def/gi/create intf-piston intf-piston-bowl () intf-piston-ch " intf_piston_valveid_string "() no"))
      )
      (ti-menu-load-string intf_piston_valveid_string)

      (if (string-ci=? conf/nonconf "n")
        (ti-menu-load-string (string-append  "/def/gi/create intf-deck intf-deck-fluid-ch-upper () intf-deck-fluid-ch-lower () no"))
      )
     
      (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create fluid-piston rigid-body  " piston-full-prof "  " cyl_axis_x " " cyl_axis_y " " cyl_axis_z))
      (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create piston rigid-body " piston-full-prof "  no " cyl_axis_x " " cyl_axis_y " " cyl_axis_z " ,, 0"))

      (set! ave_scale (+ (* 0.5 (car (%get-min-max-length-scale-on-zone (thread-name->id  "intf-piston-ch") #f))) (* 0.5 (car (cdr (%get-min-max-length-scale-on-zone (thread-name->id  "intf-piston-ch") #f))))))
     
      (if smoothing-on 
        (set! piston_layer_height  chamber-mesh-size) 
        (set! piston_layer_height (* 2 ob_cell_height))
      )
      (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create intf-piston-ch rigid-body  " piston-full-prof "  no " cyl_axis_x " " cyl_axis_y " " cyl_axis_z " ,, " (number->string piston_layer_height)))
      
      (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create fluid-ch-lower rigid-body  " piston-full-prof " "  cyl_axis_x " " cyl_axis_y " " cyl_axis_z))

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

      ;;Changes in 14.5 to take care of corrections from thomas  DE40230 for exclude boundary conditions
      
      (if (thread-name->id "cyl-quad")
        (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create cyl-quad rigid-body  " piston-full-prof " yes "  cyl_axis_x " " cyl_axis_y " " cyl_axis_z))
      )
      (if (thread-name->id "cyl-piston")
        (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create cyl-piston rigid-body  " piston-full-prof " yes "  cyl_axis_x " " cyl_axis_y " " cyl_axis_z))
      )
     
    )
  )
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; journal-h functions starts from here ;;;;;;;;;;;;;;;;;;;;;;;

(define wb-ice-dyn-mesh-zone-names-check-hybrid
  (lambda ()
    (let 
      (
        (dyn_zone_check_list '())
        (dyn_zone_check_list_prev '())
        (all_surfaces (inquire-surface-names))
        (surface_counter 0)
        (final_list (list))
        (matched #f)
      )

      (format  "\n\n\t\t ___________Validating Zone Names _____________\t\n\n")  
    
      (set! dyn_zone_check_list (list "fluid-ch" "cyl-tri" ))
      (if symmetryengine
        (set! dyn_zone_check_list (append dyn_zone_check_list (list "symm-cyl-tri")))
      )
      
      (if (= piston_type 1)
        (set! dyn_zone_check_list (append dyn_zone_check_list (list "int-piston" "piston")))
      )
      
      (if (= piston_type 2)
         (if withbowl
          (set! dyn_zone_check_list (append dyn_zone_check_list (list "piston" "bowl" "fluid-piston" "intf-bowl")))
          (set! dyn_zone_check_list (append dyn_zone_check_list (list "piston" )))
          )
      )
      
      (if (= piston_type 3)
        (set! dyn_zone_check_list (append dyn_zone_check_list (list "piston" )))
      )
        
      ;(set! dyn_zone_check_list_nonconformal (list "intf-deck-fluid-ch-lower" "intf-deck-fluid-ch-upper") )
        
      (for-each
        (lambda (valve_value)

          (set! dyn_zone_check_list_prev (list
             (string-append "fluid-" (list-ref valve_value 1) "-ib")
             (string-append "fluid-" (list-ref valve_value 1) "-vlayer")
             
             (string-append "intf-int-" (list-ref valve_value 1) "-ib" "-fluid" "-ib")
             (string-append "intf-int-" (list-ref valve_value 1) "-ib" "-fluid" "-port")
             (string-append "intf-int-" (list-ref valve_value 1) "-ob" "-fluid" "-port")
             (string-append "intf-int-" (list-ref valve_value 1) "-ob" "-fluid" "-vlayer")
             
             (string-append "intf-" (list-ref valve_value 1) "-ib" "-fluid" "-ib")
             (string-append "intf-" (list-ref valve_value 1) "-ib" "-fluid" "-ob" "-quad")
             (string-append "intf-" (list-ref valve_value 1) "-ib" "-fluid" "-ob" "-tri")
             (string-append "intf-" (list-ref valve_value 1) "-ob" "-fluid" "-ch")
             (string-append "intf-" (list-ref valve_value 1) "-ob" "-fluid" "-vlayer") ;vlayer
             (string-append (list-ref valve_value 1) "-seat")
             (string-append (list-ref valve_value 1) "-ch")
             (string-append (list-ref valve_value 1) "-ib")
             (string-append (list-ref valve_value 1) "-ob")
              )
          )
         (set! dyn_zone_check_list (append dyn_zone_check_list dyn_zone_check_list_prev))
        )setup-valve-list
      )
      
      (set!  all_surfaces (append all_surfaces (inquire-zone-names)))
      (for-each
        (lambda (dyn_zone)
          (if dyn_zone
            (begin      
              (set! matched #f)
              (for-each
                (lambda (surfacename)
                  (if (string-ci=? (symbol->string surfacename) dyn_zone)
                    (begin 
                      (set! surface_counter (+ surface_counter 1))
                      (set! matched #t)
                    )
                  ) 
                ) all_surfaces
              )
              (if (not matched)
                (set! final_list (append final_list (list dyn_zone )))
              )
            )
          )    
        ) dyn_zone_check_list
      )
      final_list
    )
  )
)

(set! wb-ice-define-in-cylinder-settings
  (lambda ()
    (format  "\n\n\t\t ___________Setting In-Cylinder settings _____________\t\n\n") 
    
    (ti-menu-load-string (string-append "/def/d-m/dynamic-mesh y y " (number->string rpm) " 0 720 no"))
    (ti-menu-load-string (string-append "/def/d-m/controls/in-cylinder-parameter/crank-angle-step " (number->string dCA )))

    (if start-crank-angle
    (rpsetvar 'dynamesh/in-cyn/crank-start-angle start-crank-angle)
    (rpsetvar 'dynamesh/in-cyn/crank-start-angle 0)
    )

    (ic-update-flow-time-from-angle ( rpgetvar 'dynamesh/in-cyn/crank-start-angle))
    (ti-menu-load-string (string-append "/def/d-m/controls/in-cylinder-parameter/piston-data " (number->string crank_radius) " " (number->string Connecting_rod_length)" " (number->string piston_pin_offset)))
    (ti-menu-load-string (string-append "/def/d-m/controls/in-cylinder-parameter/piston-stroke-cutoff \n" (number->string Piston_stroke_cutoff)))
    (ti-menu-load-string (string-append "/def/d-m/controls/in-cylinder-parameter/min-lift " (number->string Min_valve_lift)))
    ;
    
  )
)

(set! wb-ice-define-non-conf-interface-rpvars
  (lambda ()
    (rpsetvar 'nonconformal/virtual-polygons? #t)

    ; DE 30479 unnecessary walls being created
    (rpsetvar 'nonconformal/smallest-area-tolerance-factor 0.05)
    (rpsetvar 'nonconformal/normal-tolerance-factor 0.5)
  )
)

(set! wb-ice-define-dyn-mesh-settings-hybrid
  (lambda ()
    (format  "\n\n\t\t ___________Setting dyn-mesh-settings-hybrid _____________\t\n\n") 
    (ti-menu-load-string "/def/dynamic-mesh/controls/layering y")
    (ti-menu-load-string "/def/dynamic-mesh/controls/layering-parameter/constant-height no")
    (ti-menu-load-string "/def/dynamic-mesh/controls/layering-parameter/collapse-factor 0.2")
    (ti-menu-load-string "/def/dynamic-mesh/controls/remeshing y")
    (ti-menu-load-string (string-append "/def/dynamic-mesh/controls/remeshing-parameter/length-min " (number->string (* 0.95 (car (%get-min-max-length-scale-on-zone (thread-name->id  "fluid-ch") #f))))))
    
    (ti-menu-load-string (string-append "/def/dynamic-mesh/controls/remeshing-parameter/length-max "  (number->string (* 1.1 (car (cdr (%get-min-max-length-scale-on-zone (thread-name->id  "fluid-ch") #f)))))))
     
    (ti-menu-load-string (string-append "/def/dynamic-mesh/controls/remeshing-parameter/size-remesh-interval 1"))
    (rpsetvar 'dynamesh/remesh/methods '(#t #f #f #t #f #f))
  )
)

(set! wb-ice-define-mesh-interface-for-piston-type1
  (lambda ()
    (format  "\n\n\t\t ___________ Defining  mesh-interface-for-piston-type1 _____________\t\n\n")
    (let 
      (
        (min_scale 1)
        (max_scale 1)
        (ave_scale 1)
        (piston_layer_height 1)
        (cyl_axis_x (number->string (car cylinder_axis)))
        (cyl_axis_y (number->string (cadr cylinder_axis)))
        (cyl_axis_z (number->string (caddr cylinder_axis)))
        
        
      )
      (ti-menu-load-string "/def/units/length m")
      (ti-menu-load-string (string-append  "/def/bc/zt int-piston interior"))
      
      (if (thread-name->id  "fluid-piston")
        (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create fluid-piston rigid-body  " piston-full-prof " " cyl_axis_x " " cyl_axis_y " " cyl_axis_z))
        )
      
      (if (thread-name->id "piston")
        (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create piston rigid-body  " piston-full-prof " no " cyl_axis_x " " cyl_axis_y " " cyl_axis_z " ,, 0"))
      )
      (if (thread-name->id  "int-piston")
        (begin
          (set! ave_scale (+ (* 0.5 (car (%get-min-max-length-scale-on-zone (thread-name->id  "int-piston") #f))) (* 0.5 (car (cdr (%get-min-max-length-scale-on-zone (thread-name->id  "int-piston") #f))))))
          (set! piston_layer_height (* 1.2 ave_scale))
        )
      )
      (if (and (thread-name->id  "int-piston") (thread-name->id  "fluid-piston-layer"))
        (begin
          (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create int-piston rigid-body " piston-limit-prof "  "cyl_axis_x " " cyl_axis_y " " cyl_axis_z " fluid-ch " ", " (number->string ave_scale) " fluid-piston-layer " ", " (number->string piston_layer_height)))
          (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create fluid-piston-layer rigid-body  " piston-full-prof "  " cyl_axis_x " " cyl_axis_y " " cyl_axis_z))
        )
      )
      (if (thread-name->id  "fluid-layer-cylinder")
        (begin
          (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create fluid-layer-cylinder rigid-body  " piston-full-prof " " cyl_axis_x " " cyl_axis_y " " cyl_axis_z))
          (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create int-piston rigid-body " piston-limit-prof "  "cyl_axis_x " " cyl_axis_y " " cyl_axis_z " fluid-ch " ", " (number->string ave_scale) " fluid-layer-cylinder " ", " (number->string piston_layer_height)))
        )
      )

      ;;Changes in 14.5 to take care of corrections from Thomas  DE40230 for exclude boundary conditions

      (if (thread-name->id "cyl-quad")
        (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create cyl-quad rigid-body  " piston-full-prof " yes "  cyl_axis_x " " cyl_axis_y " " cyl_axis_z))
      )
      (if (thread-name->id "cyl-piston")
        (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create cyl-piston rigid-body  " piston-full-prof " yes "  cyl_axis_x " " cyl_axis_y " " cyl_axis_z))
      )
     
      (if (thread-name->id "cyl-tri")
        (begin
          (set! ave_scale (+ (* 0.5 (car (%get-min-max-length-scale-on-zone (thread-name->id  "cyl-tri") #f))) (* 0.5 (car (cdr (%get-min-max-length-scale-on-zone (thread-name->id  "cyl-tri") #f))))))
          (set! min_scale (* 0.5 ave_scale))
          (set! max_scale (* 1.5 ave_scale))
          (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create cyl-tri deforming cylinder " (number->string cylinder_radius) " " (number->string (list-ref cylinder_axis_origin 0)) " " (number->string (list-ref cylinder_axis_origin 1)) " " (number->string (list-ref cylinder_axis_origin 2)) " " cyl_axis_x " " cyl_axis_y " " cyl_axis_z " no no yes yes no " (number->string min_scale) " " (number->string max_scale) " 0.6"))
        )
      )
    )
  )
)

(set! wb-ice-define-mesh-interface-for-piston-type2
  (lambda ()
    (format  "\n\n\t\t ___________Defining  mesh-interface-for-piston-type_2 _____________\t\n\n")
    (let 
      (
        (min_scale 1)
        (max_scale 1)
        (ave_scale 1)
        (piston_layer_height 1)
        (cyl_axis_x (number->string (car cylinder_axis)))
        (cyl_axis_y (number->string (cadr cylinder_axis)))
        (cyl_axis_z (number->string (caddr cylinder_axis)))
        (event01 '())
        (event02 '())
        (event03 '())
        (event04 '())
        (pre-event-list '())
        (cur-event-list '())
      )	
      (ti-menu-load-string "/def/units/length m")
	   
      (if (thread-name->id "piston")
        (begin
          (set! ave_scale (+ (* 0.5 (car (%get-min-max-length-scale-on-zone (thread-name->id  "piston") #t))) (* 0.5 (car (cdr (%get-min-max-length-scale-on-zone (thread-name->id  "piston") #t))))))
          (ti-menu-load-string (string-append  "/define/dyn-mesh/zones/create piston rigid-body  " piston-full-prof " no " cyl_axis_x " " cyl_axis_y " " cyl_axis_z " ,, " (number->string ave_scale)))
        )
      )
	    ;
	    ; Deforming dynamic zone setup
	    ;
      (if (thread-name->id "cyl-tri")
        (begin
          (set! ave_scale (+ (* 0.5 (car (%get-min-max-length-scale-on-zone (thread-name->id  "cyl-tri") #t))) (* 0.5 (car (cdr (%get-min-max-length-scale-on-zone (thread-name->id  "cyl-tri") #t))))))
          (set! min_scale (* 0.5 ave_scale))
          (set! max_scale (* 1.5 ave_scale))
          
          (ti-menu-load-string (string-append  "/define/dyn-mesh/zones/create cyl-tri deforming cylinder " (number->string cylinder_radius) " " (number->string (list-ref cylinder_axis_origin 0)) " " (number->string (list-ref cylinder_axis_origin 1)) " " (number->string (list-ref cylinder_axis_origin 2)) " " cyl_axis_x " " cyl_axis_y " " cyl_axis_z " no no yes yes no " (number->string min_scale) " " (number->string max_scale) " 0.6"))
        )
      )


	    ;;Changes in 14.5 to take care of corrections from thomas  DE40230 for exclude boundary conditions

	    (if (thread-name->id "cyl-quad")
	      (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create cyl-quad rigid-body  " piston-full-prof " yes "  cyl_axis_x " " cyl_axis_y " " cyl_axis_z))
	      )
	    (if (thread-name->id "cyl-piston")
	      (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create cyl-piston rigid-body  " piston-full-prof " yes "  cyl_axis_x " " cyl_axis_y " " cyl_axis_z))
	      )
	    ;;Changes end

	    (if withbowl
	      (begin
          (ti-menu-load-string "/def/bc/zt intf-bowl interface")
          (ti-menu-load-string "/def/bc/zt piston interface")
          (rpsetvar 'nonconformal/virtual-polygons? #t)
          (ti-menu-load-string "/def/gi/create intf-bowl piston () intf-bowl () no no")
         
          (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create fluid-piston rigid-body  " piston-full-prof "  " cyl_axis_x " " cyl_axis_y " " cyl_axis_z)) 
          (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create bowl rigid-body " piston-full-prof " no  "  cyl_axis_x " " cyl_axis_y " " cyl_axis_z " ,, 0"))
        )
	    )
	    
	    (set! event01 (list '(active . #t) (cons 'name "insert-piston-boundary-layer-power-stroke") (cons 'start  (+ 0   insert_angle)) (list 'action 6 (thread-name->id "piston") (thread-name->id "cyl-tri"))))
	    (set! event02 (list '(active . #t) (cons 'name "delete-piston-boundary-layer-power-stroke") (cons 'start  (- 360 insert_angle)) (list 'action 7 (thread-name->id "piston"))))
	    (set! event03 (list '(active . #t) (cons 'name "insert-piston-boundary-layer-intake-stroke") (cons 'start  (+ 360 insert_angle_intake_stroke)) (list 'action 6 (thread-name->id "piston") (thread-name->id "cyl-tri"))))
	    (set! event04 (list '(active . #t) (cons 'name "delete-piston-boundary-layer-intake-stroke") (cons 'start  (- 720 insert_angle_intake_stroke)) (list 'action 7 (thread-name->id "piston"))))
	    ;
	    (set! cur-event-list (list event01 event02 event03 event04))
	    ;
	    (set! pre-event-list (rpgetvar 'dynamesh/in-cyn/event-list))
	    (rpsetvar 'dynamesh/in-cyn/event-list (append pre-event-list cur-event-list))
	    ;
	    ;
	  )
	)
)

(set! wb-ice-define-mesh-interface-for-piston-type3
  (lambda ()
    (format  "\n\n\t\t ___________Defining  mesh-interface-for-piston-type_3_____________\t\n\n")
    (let 
      (
        (min_scale 1)
        (max_scale 1)
        (ave_scale 1)
        (piston_layer_height 1)
        (cyl_axis_x (number->string (car cylinder_axis)))
        (cyl_axis_y (number->string (cadr cylinder_axis)))
        (cyl_axis_z (number->string (caddr cylinder_axis)))
        (cyl_origin_x (number->string (car cylinder_axis_origin)))
        (cyl_origin_y (number->string (cadr cylinder_axis_origin)))
        (cyl_origin_z (number->string (caddr cylinder_axis_origin)))
        (event01 '())
        (event02 '())
        (event03 '())
        (event04 '())
        (meshreplace_initial_event '())
        (meshreplace_final_event '())
        (meshreplace_initial_event2 '())
        (meshreplace_final_event2 '())
        (pre-event-list '())
        (cur-event-list '())
        (event05 '())
        (event06 '())
        (event07 '())
        (event08 '())
        (event09 '())
        (event10 '())
        (event11 '())
        (event12 '())
        (insert_layer_angle_increment 1)
      )	
	    (ti-menu-load-string "/def/units/length m")
      
      (if (thread-name->id "piston")
        (begin
          (set! ave_scale (+ (* 0.5 (car (%get-min-max-length-scale-on-zone (thread-name->id  "piston") #t))) (* 0.5 (car (cdr (%get-min-max-length-scale-on-zone (thread-name->id  "piston") #t))))))
          (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create piston rigid-body  " piston-full-prof " no "  cyl_axis_x " " cyl_axis_y " " cyl_axis_z " ,, " (number->string ave_scale)))
        )
      )
      (if (thread-name->id "cyl-tri")
        (begin
          (set! ave_scale (+ (* 0.5 (car (%get-min-max-length-scale-on-zone (thread-name->id  "cyl-tri") #t))) (* 0.5 (car (cdr (%get-min-max-length-scale-on-zone (thread-name->id  "cyl-tri") #t))))))
          (set! min_scale (* 0.5 ave_scale))
          (set! max_scale (* 1.5 ave_scale))
          (ti-menu-load-string (string-append  "/define/dynamic-mesh/zones/create cyl-tri deforming cylinder " (number->string cylinder_radius) " " cyl_origin_x " " cyl_origin_y " " cyl_origin_z " " cyl_axis_x " " cyl_axis_y " " cyl_axis_z " no no yes yes no " (number->string min_scale) " " (number->string max_scale) " 0.6"))
        )
      )
      

	  )
	)
)

(set! wb-ice-define-smoothing-controls
  (lambda ()
    (ti-menu-load-string (format #f "/define/dynamic-mesh/controls/smoothing-parameters/spring-on-all-shapes? y"))
    (ti-menu-load-string "/def/dynamic-mesh/controls/smoothing-parameters/constant-factor 0.05")
    (ti-menu-load-string "/def/dynamic-mesh/controls/smoothing-parameters/max-iter 25")
  )
)


;;
(define (ice-monitor->field mon field default)
  (let ((x (assq field (cdr mon))))
    (if x (cdr x) default)))
(define (ice-monitor->report mon)
  (let ((r (ice-monitor->field mon 'report "Integral")))
    (if (string=? r "Mass-Avg")
  "Mass-Weighted Average"
  r)))
(define (ice-monitor->function mon) (ice-monitor->field mon 'function "Pressure..."))
(define (ice-monitor->sub-function mon) (ice-monitor->field mon 'sub-function
                "Static Pressure"))
(define (ice-monitor->quantity mon)
  (let ((r (ice-monitor->report mon)))
    (if (string=? r "Mass Flow Rate")
  "Mass Flow Rate"
  (if (string=? r "Volume Flow Rate")
      "Volume Flow Rate"
      (let ((sf (ice-monitor->sub-function mon)))
         (if (and sf (not (string=? "" sf)))
        sf
       (ice-monitor->function mon)))))))
(set! wb-ice-list-monitors-to-file
  (lambda(file_name )
    (let
      ((file_port #f) )
      (if (not (file-exists? file_name)) 
        (begin
          (set! file_port (open-output-file file_name))
          (if file_port
            (begin
              (newline file_port)
              (close-output-port file_port)
              )
            )
        )
      )
      ;(wb-ice-report-dir)
      (if (file-exists? file_name)
        (begin
          (set! file_port (open-file file_name "a"))
          (format file_port "~% " )
          (format file_port " /sol mon surf li ~%")
          (format file_port " Monitor   Plot Print Write Every Report-of Quantity (on Surfaces)~%")
          (for-each 
            (lambda (mon) 
              (format file_port "~10a ~4a ~5a ~5a ~5a"
              (car mon)
              (cdr (assoc 'plot? mon))
              (cdr (assoc 'print? mon))
              (cdr (assoc 'write? mon))
              (if (cdr (assoc 'unsteady? mon) ) "TmStp" " Iter"))
              (let ((q (ice-monitor->quantity mon) ))
                (if (or (string=? q "Mass Flow Rate")
                        (string=? q "Volume Flow Rate"))
                  (format file_port " ~a ~19a~%"
                    q
                    (map surface-id->name 
                    (cdr (assoc 'surfaces mon) )))
                  
                  (format file_port " ~6a ~12a ~a~%"
                    (cdr (assoc 'report mon) )
                    (cdr (assoc 'sub-function mon) )
                    (map surface-id->name 
                    (cdr (assoc 'surfaces mon) )))  ))
            ) (rpgetvar 'monitor/surfaces)
          )
          (format file_port "~%~% " )
          (format file_port " /sol mon vol li ~%")
          (format file_port "   Monitor Plot Print Write Every Report-of Quantity (on Volume)~%")
          (for-each 
            (lambda (mon)
              (format file_port "~10a ~4a ~5a ~5a ~5a"
              (car mon)
              (cdr (assoc 'plot? mon))
               (cdr (assoc 'print? mon))
              (cdr (assoc 'write? mon))
              (if (cdr (assoc 'unsteady? mon) ) "TmStp" " Iter"))
              (let ((q (ice-monitor->quantity mon)))
                (if (or (string=? q "Mass Flow Rate")
                        (string=? q "Volume Flow Rate"))
                    (format file_port " ~a ~19a~%"
                      q
                      (map thread-name 
                     (map get-thread (cdr (assoc 'zones mon) ))))
                    
                    (format file_port " ~6a ~12a ~a~%"
                      (cdr (assoc 'report mon) )
                      (cdr (assoc 'sub-function mon) )
                      (map thread-name 
                     (map get-thread (cdr (assoc 'zones mon) ))))))
                   ) (rpgetvar 'monitor/volume)
          )
          (close-output-port file_port)
        )
      )
    )
  )
)

(set! wb-ice-activate-decactivate-ports
  (lambda ()
   (format  "\n\n\t\t ___________Defining activation deactivation events for ports_____________\t\n\n")
    (let* 
      ( 
        (zone_list '())
        (valve_list setup-valve-list)
        (deactivate_zones_event '())
        (activate_zones_event '())
        (pre_event_list '() )
        (angle_tolerance activation_angle_tolerence)
      )
      (for-each 
        (lambda (valve)
          (set! zone_list (wb-ice-find-zones-to-deactivate (list-ref valve 1)))
           
          (if (not (null? zone_list))
            (begin
              (set! deactivate_zones_event (list '(active . #t) (cons 'name (string-append "deactivate-cell-zones-" (list-ref valve 1))) (cons 'start (+ (list-ref valve 4) angle_tolerance)) (list 'action 15 (format #f "(wb-ice-deactivate-cell-zones '~s )" zone_list )))) 
              (set! activate_zones_event (list '(active . #t) (cons 'name (string-append "activate-cell-zones-" (list-ref valve 1))) (cons 'start (- (list-ref valve 3) angle_tolerance)) (list 'action 15 (format #f "(wb-ice-activate-cell-zones '~s )" zone_list ))))
              
              (set! pre_event_list (rpgetvar 'dynamesh/in-cyn/event-list))
              (rpsetvar 'dynamesh/in-cyn/event-list (append pre_event_list (list deactivate_zones_event) (list activate_zones_event)))
            )
          )
        ) valve_list
      )
    )
  )
)

(set! wb-ice-find-zones-to-deactivate
  (lambda (compare_string)
    (let*
      (
        (all_zones (map thread-name (get-threads-of-type 'fluid)))
        (zones_to_deactivate '())
        (s (substring compare_string 0 (- (string-length compare_string) 1)))
        (n (substring compare_string (- (string-length compare_string) 1) (string-length compare_string)))
        (port_string "")
      )
      (set! port_string (string-append s "-" n))
      (for-each
        (lambda (zone)
          (set! zone (symbol->string zone))
            (if (or (and (substring? compare_string zone) (not (substring? "fluid-ch" zone))) (substring? port_string zone))
              (set! zones_to_deactivate (append zones_to_deactivate(list zone)))
            )
        ) all_zones 
      )zones_to_deactivate
    )
  )
)

(set! wb-ice-deactivate-ports-at-start
  (lambda ()
   (format  "\n\n\t\t ___________Checking Activation/Deactivating ports at start _____________\t\n\n")
    (let
      ( 
        (zone_list '())
        (current_ca 0)
        (open_angle 0)
        (close_angle 0)
        (valve_list setup-valve-list)
        (angle_tolerance 2)
      )
      (set! current_ca (ice-remainder (rpgetvar 'dynamesh/in-cyn/crank-angle) 720))
      (for-each 
        (lambda (valve)
          ;(format  "\n\n\t\t ___________Deactivating ports for ~a _____________\t\n\n" (list-ref valve 1))
          (set! zone_list (wb-ice-find-zones-to-deactivate (list-ref valve 1)))
          (set! open_angle (list-ref valve 3))
          (set! close_angle (list-ref valve 4))
          (if (or (< current_ca (- open_angle angle_tolerance)) (> current_ca (+ close_angle angle_tolerance)))
            (begin
              (format  "\n\n\t\t ___________Deactivating ports for ~a _____________\t\n\n" (list-ref valve 1))
              (wb-ice-deactivate-cell-zones (map string->symbol zone_list))
            )
          )
        ) valve_list
      ) 
    )
    (wb-ice-set-display-after-port-deactivation)
  )
)

(set! wb-ice-set-display-after-port-deactivation
  (lambda ()
     (ti-menu-load-string  "/display/set/mesh-display-configuration/post-processing")
    (ti-menu-load-string  "/display/set/r-o surface-edge-visibility yes no no no ")
    (ti-menu-load-string  "/display/set/r-o surface-edge-visibility yes yes ")
    (ti-menu-load-string  "/display/s-m , , ")
  )
)
(set! wb-ice-define-events-for-time-step-changes
  (lambda ()
    (let
      ((dt_event_list (read-var solver-set-file 'time_step_list)))

      (if dt_event_list
        (begin
          ;Defining dynamic-mesh events for time step changes new solver UI changes
          (wb-ice-set-time-step-change-events-new)
        )
        (begin
          ;Defining dynamic-mesh events for time step changes... previous project support
          (wb-ice-set-time-step-change-events-previous-support)
        )
      )
    )
  )
)
(set! wb-ice-cal-act-for-remesh-cell-zones-during-smoothing
  (lambda()
    (let
      (
       (cal-act-string "(wb-ice-remesh-cell-zones (wb-ice-get-deforming-cell-thread-ids) 0.965)")
       )

      (ti-menu-load-string (format #f "/solv exe-comm a-e remesh-cell-zone 1 ~s ~s"  "time-step" cal-act-string))  
      (ti-menu-load-string (format #f "/solv exe-comm disable remesh-cell-zone"))      
    )
  )
)
(set! wb-ice-set-time-step-change-events-previous-support
  (lambda ()
    (let 
      (
        (event01 '())
        (event02 '())
        (event03 '())
        (event04 '())
        (event05 '())
        (event06 '())
        (event07 '())
        (event08 '())
        (cur_event_list '())
        (pre_event_list '())
        (insert_layer_angle_increment 1)
      )
      (format  "\n\n\t\t_____________ Defining dynamic-mesh events for time step changes... previous project support___________\t\n\n")
      (for-each
        (lambda (valve_list)
          (set! event01 (list '(active . #t) (cons 'name (string-append "reduce-dt-due-to-open-" (list-ref valve_list 1))) (cons 'start (list-ref valve_list 3) ) (list 'action 5 (* 0.5 dCA))))
          (set! event02 (list '(active . #t) (cons 'name (string-append "increase-dt-due-to-open-" (list-ref valve_list 1))) (cons 'start (+ (list-ref valve_list 3)  increment)) (list 'action 5 dCA)))    
          (set! event03 (list '(active . #t) (cons 'name (string-append "reduce-dt-due-to-close-" (list-ref valve_list 1))) (cons 'start (- (list-ref valve_list 4)  increment)) (list 'action 5 (* 0.5 dCA))))
          (set! event04 (list '(active . #t) (cons 'name (string-append "increase-dt-due-to-close-" (list-ref valve_list 1))) (cons 'start (list-ref valve_list 4) ) (list 'action 5 dCA)))
          
          (set! cur_event_list (append cur_event_list  (list event01 event02 event03 event04)))
        )(rpgetvar 'ice/setup-valve-list)
      )
      ;piston-type 3
      (if piston_type
      (if  (= piston_type 3)
        (begin
          (set! event01 (list '(active . #t) (cons 'name "reduce-dt-before-insert-layer-1") (cons 'start (- insert_angle insert_layer_angle_increment )) (list 'action 5 (* 0.5 dCA))))
          (set! event02 (list '(active . #t) (cons 'name "increase-dt-after-insert-layer-1") (cons 'start (+ insert_angle insert_layer_angle_increment )) (list 'action 5 dCA)))
          (set! event03 (list '(active . #t) (cons 'name "reduce-dt-before-insert-layer-2") (cons 'start (+ (- insert_angle insert_layer_angle_increment ) 360)) (list 'action 5 (* 0.5 dCA))))
          (set! event04 (list '(active . #t) (cons 'name "increase-dt-after-insert-layer-2") (cons 'start (+ (+ insert_angle insert_layer_angle_increment ) 360)) (list 'action 5 dCA)))      

          (set! event05 (list '(active . #t) (cons 'name "reduce-dt-before-delete-layer-1") (cons 'start (- delete_angle insert_layer_angle_increment )) (list 'action 5 (* 0.5 dCA))))
          (set! event06 (list '(active . #t) (cons 'name "increase-dt-after-delete-layer-1") (cons 'start (+ delete_angle insert_layer_angle_increment )) (list 'action 5 dCA)))
          (set! event07 (list '(active . #t) (cons 'name "reduce-dt-before-delete-layer-2") (cons 'start (+ (- delete_angle insert_layer_angle_increment ) 360)) (list 'action 5 (* 0.5 dCA))))
          (set! event08 (list '(active . #t) (cons 'name "increase-dt-after-delete-layer-2") (cons 'start (+ (+ delete_angle insert_layer_angle_increment ) 360)) (list 'action 5 dCA)))
          (set! cur_event_list (append cur_event_list  (list event01 event02 event03 event04 event05 event06 event07 event08)))
        )
      )
      )
      (if (string-ci=? solution-type "combustion") 
        (begin
          (if (not (null? ice-injection-list))
            (for-each
              (lambda (injection)
                (wb-ice-create-injection-time-step-size-event injection 0.05 0.25)
              ) ice-injection-list
            )
          )
        )
      )
      (set! pre_event_list (rpgetvar 'dynamesh/in-cyn/event-list))
      (rpsetvar 'dynamesh/in-cyn/event-list (append pre_event_list cur_event_list))
    )
  )
)

(set! wb-ice-set-time-step-change-events-new
  (lambda ()
    (let
      (
        (dt_event_list (read-var solver-set-file 'time_step_list))
        (pre_event_list (rpgetvar 'dynamesh/in-cyn/event-list))
        (cur_event_list '())
      )
      (format  "\n\n\t\t_____________ Defining dynamic-mesh events for time step changes___________\t\n\n")
      (if dt_event_list
        (if (not (null? dt_event_list))
          (begin
            (for-each
              (lambda (event)
                (let*
                  (
                    (event_angle (car event))
                    (event_name
                      (if (> (if (pair? (cadr event)) (length (cadr event)) 1)  1)
                        (if (string? (cadadr event)) 
                          (cadadr event) 
                          (string-append "dt-event-at-" (number->string event_angle)))
                        (string-append "dt-event-at-" (number->string event_angle))
                      )
                    )
                    (dt_value 
                      (if (> (if (pair? (cadr event)) (length (cadr event)) 1)  1) 
                        (caadr event)
                        (cadr event)
                      )
                    )
                    (event_active? #t)
                    (event_list '())
                  )
                  (set! event_list (list '(active . event_active?) (cons 'name event_name) (cons 'start event_angle ) (list 'action 5 dt_value)))
                  (set! cur_event_list (append cur_event_list  (list event_list)))
                )
              ) dt_event_list
            )
            (rpsetvar 'dynamesh/in-cyn/event-list (append pre_event_list cur_event_list))
          )
            (format  "\n\n\t\t_____________ dt_event_list not found or is null, so no dt-change events are set in dynamic-mesh events ___________\t\n\n")  
        )
      )
    )
  )
)
(set! wb-ice-cal-act-for-plot-last-monitor-values
  (lambda()
    (format  "\n\n\t\t_____________ setting calculation activities for last residual monitor values ___________\t\n\n")
    (let
      (
       (cal-act-string "(wb-ice-plot-last-monitor-values)")
       )

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

(set! wb-ice-define-events-for-case-data-solution-points
  (lambda ()
    (let
      ((save_data_angles (read-var solver-set-file 'save_data_angles)))

      (if save_data_angles
        (let
          (
            (file_name "")
            (event '())
            (cur_event_list '())
            (pre_event_list '())
          )
          (format  "\n\n\t\t_____________ Defining dynamic-mesh events for solution-points___________\t\n\n")
          (for-each
            (lambda (ca)
              (set! file_name (string-append  "ice-solution-point-ca-" (number->string ca)))
              (set! event (list '(active . #t) (cons 'name (format #f "write-solution-point-at-ca-~s" ca)) (cons 'start ca) (list 'action 15 (format #f "(wb-ice-write-case-data-solution-point ~s)"file_name)))) 
              (set! cur_event_list (list-add cur_event_list event))
            )save_data_angles
          )
          (set! pre_event_list (rpgetvar 'dynamesh/in-cyn/event-list))
          (rpsetvar 'dynamesh/in-cyn/event-list (append pre_event_list cur_event_list))
        )
      )
    )
  )
)
(set! wb-ice-define-in-cylinder-as-parameters
  (lambda ()
    (if (rpgetvar 'ice/in_cylinder_parameter_list)
      (begin
        (if (assoc 'rpm (rpgetvar 'ice/in_cylinder_parameter_list))
          (let*
            (
            (param (assoc 'rpm (rpgetvar 'ice/in_cylinder_parameter_list)))
              (param_name (symbol->string (car param)))
              (initial_value (cadr param))

            )
            (format  "\n\n\t\t ___________ Defining rpm as parameters for design point study_____________\t\n\n" )
            (ti-menu-load-string (format #f "/define/parameters/input-parameters/advance/use-in  scheme-proc  ~a ~a 
                (lambda (value)
                    (ti-menu-load-string (args->string '/def/d-m/dynamic-mesh 'yes 'yes value '_ '_  ))) " param_name initial_value ))
          )
        )
        (if (assoc 'min_lift (rpgetvar 'ice/in_cylinder_parameter_list))
          (let*
            (
              (param (assoc 'min_lift (rpgetvar 'ice/in_cylinder_parameter_list)))
              (param_name (symbol->string "MinLift"))
              (initial_value (cadr param))

            )
            (format  "\n\n\t\t ___________ Defining rpm as parameters for design point study_____________\t\n\n" )
            (ti-menu-load-string (format #f "/define/parameters/input-parameters/advance/use-in  scheme-proc  ~a ~a 
                (lambda (value)
                    (ti-menu-load-string (args->string '/def/d-m/controls 'icp 'minimum-lift value ))) " param_name initial_value ))
          )
        )
      )
    )
  )
)

(set! wb-ice-define-piston-type3-insert-delete-angle-events
  (lambda ()
    (format  "\n\n\t\t ___________Defining insert-delete events for piston-type_3_____________\t\n\n")
    (let 
      (
        (event01 '())
        (event02 '())
        (event03 '())
        (event04 '())
        (pre-event-list '())
        (cur-event-list '())
      )
      (set! event01 (list '(active . #t) (cons 'name (format #f "insert-interior-layer-1")) (cons 'start insert_angle) (list 'action 15 (format #f "(wb-ice-insert-interior-layer)" ))))
      (set! event02 (list '(active . #t) (cons 'name (format #f "delete-interior-layer-1")) (cons 'start delete_angle) (list 'action 15 (format #f "(wb-ice-delete-interior-layer)" ))))
      (set! event03 (list '(active . #t) (cons 'name (format #f "insert-interior-layer-2")) (cons 'start  (+ 360 insert_angle)) (list 'action 15 (format #f "(wb-ice-insert-interior-layer)" ))))
      (set! event04 (list '(active . #t) (cons 'name (format #f "delete-interior-layer-2"))  (cons 'start  (+ 360 delete_angle)) (list 'action 15 (format #f "(wb-ice-delete-interior-layer)" ))))
      
      (set! cur-event-list (list  event01  event02  event03  event04 ))
	    (set! pre-event-list (rpgetvar 'dynamesh/in-cyn/event-list))
	    (rpsetvar 'dynamesh/in-cyn/event-list (append pre-event-list cur-event-list))
    )
  )
)

(set! wb-ice-cal-act-for-adaptive-time-step
  (lambda()
    (format  "\n\n\t\t_____________ setting calculation activities for adaptive time step ___________\t\n\n")
    (let
      (
        (ice_adaptive_time_step (read-var solver-set-file 'ice-adaptive-time-step ))
        (cal_act_string "")
        (max_ca_step_size 0.5)
        (min_ca_step_size 0.0625)
        (increase_ts_stabilize_ca 2)
        (decrease_ts_stabilize_ca 1)
        (enabled? #f)
      )
      (if ice_adaptive_time_step
        (begin
          (if (assoc 'enabled? ice_adaptive_time_step)
            (set! enabled? (cadr (assoc 'enabled? ice_adaptive_time_step))))
          (if enabled?
            (begin
              (if (assoc 'max-ca-step-size ice_adaptive_time_step)
                (set! max_ca_step_size (cadr (assoc 'max-ca-step-size ice_adaptive_time_step))))
              (if (assoc 'min-ca-step-size ice_adaptive_time_step)
                (set! min_ca_step_size (cadr (assoc 'min-ca-step-size ice_adaptive_time_step))))
              (if (assoc 'increase-ts-stabilize-ca ice_adaptive_time_step)
                (set! increase_ts_stabilize_ca (cadr (assoc 'increase-ts-stabilize-ca ice_adaptive_time_step))))
              (if (assoc 'decrease-ts-stabilize-ca ice_adaptive_time_step)
                (set! decrease_ts_stabilize_ca (cadr (assoc 'decrease-ts-stabilize-ca ice_adaptive_time_step))))
              (set! cal_act_string (format #f "(wb-ice-adapt-time-step '(enabled? ~a) '(max-ca-step-size ~a) '(min-ca-step-size ~a) '(ts-increase-stab-ca ~a) '(ts-decrease-stab-ca ~a) )" enabled? max_ca_step_size min_ca_step_size increase_ts_stabilize_ca decrease_ts_stabilize_ca))

              (ti-menu-load-string (format #f "/solv exe-comm a-e adaptive-time-step-calc-activity 1 ~s ~s"  "time-step" cal_act_string))
            )
          )
        )
      )
    )))

