(defrule MAIN::Print_Ordinary_Messages
  (declare (salience 800))
  (AllowRetroAction PrintMessages)
  (Current Stage ?Stage)
  ?f <- (Errmsg (Level ?L) (Routine ?Rout) (Msg $?MSG) (Stage ?Stage))
  ?g <- (ErrorInfo None ?f)
=>
  (printout t crlf " *** " (upcase ?L) " *** from [" ?Rout "]" crlf)
  (loop-for-count (?Count 1 (length$ $?MSG)) do
    (printout t "    " (nth$ ?Count $?MSG) crlf)
  )
  (printout t crlf)
  (Stop_Iter)
)


(defrule MAIN::Print_Internal_Error_Messages
  (declare (salience 800))
  (AllowRetroAction PrintMessages)
  (Current Stage ?Stage)
  ?f <- (Errmsg (Level ?L) (Routine ?Rout) (Msg $?MSG) (Stage ?Stage))
  ?g <- (ErrorInfo InternalError ?f)
=>
  (assert (Message (Stage ?Stage)
                   (String $?MSG)
                   (Level 5)
                   (Kind GeneralDiagnostic)
           )
   )
  (bind ?Message (str-cat "A serious internal error has occured (in " ?Rout ")s."))
  (assert (Message (Stage ?Stage)
                   (String ?Message (AddGeneralMessage ContactPolyflow)
                                    (AddGeneralMessage Apologize)
                    )
                   (Level 5)
                   (Kind Suggestion)
           )
   )

  (Stop_Iter)
)

;~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

(defrule MAIN::Init_Mail
  (declare (salience 810))
  (Current Stage ?Stage)
  ?f <- (Errmsg (Level Error) (Routine ?Rout) (Msg $?MSG) (Stage ?Stage))
  ?g <- (ErrorInfo InternalError ?f)
  (MailTo ?addr)
=>
  (bind ?Cmd (str-cat "rm -f errors." ?addr))
  (CShell ?Cmd)
)

(defrule MAIN::Send_Mail
  (declare (salience -2000))
  (Current Stage ?Stage)
  ?f <- (Errmsg (Level Error) (Routine ?Rout) (Msg $?MSG)(Stage ?Stage))
  ?g <- (ErrorInfo InternalError ?f)
  (MailTo ?addr)
=>
  (bind ?Cmd (str-cat "mail " ?addr " < errors." ?addr))
  (CShell ?Cmd)
  (printout t crlf  "A mail has been sent to " ?addr crlf)
)

(defrule MAIN::Mail_Internal_Error_Messages
  (MailTo ?addr)
  (Current Stage ?Stage)
  ?f <- (Errmsg (Level Error) (Routine ?Rout) (Msg $?MSG)(Stage ?Stage))
  ?g <- (ErrorInfo InternalError ?f)
=>
  (bind ?Cmd (str-cat "echo 'Dear Developer' >> errors." ?addr))
  (CShell ?Cmd)
  (bind ?Cmd (str-cat "echo '===============' >> errors." ?addr))
  (CShell ?Cmd)
  (bind ?Cmd (str-cat 
     "echo 'The following Error message has not been handled' >> errors." ?addr
              )
   )
  (CShell ?Cmd)
  (bind ?Cmd (str-cat "echo '  ' >> errors." ?addr))
  (CShell ?Cmd)

  (bind ?Cmd (str-cat "echo 'In routine ' " ?Rout " >> errors." ?addr))
  (CShell ?Cmd)

  (loop-for-count (?Count 1 (length$ $?MSG)) do
    (bind ?Cmd (str-cat "echo '" (nth$ ?Count $?MSG) "' >> errors." ?addr))
    (CShell ?Cmd)
  )
)

;~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


(defrule MAIN::Internal_Error
  (declare (salience 70))
  (Current Stage ?Stage)
  ?f <- (Errmsg (Level Error | Intern)  (Routine ?Rout) (Msg $?MSG)
                (Stage ?Stage)
         )
  (not (ErrorInfo MoreInfo ?f))
=>

  (assert (ErrorInfo InternalError ?f))
)

(defrule MAIN::Analyse_Error_NoInfo
  (declare (salience 50))
  (Current Stage ?Stage)
  ?f <- (Errmsg (Level ?L) (Routine ?Rout) (Msg $?MSG)(Stage ?Stage))
  (not (ErrorInfo ?Any ?f))
=>
  (assert (ErrorInfo None ?f))
)

;=======================================================================
;      Messages d'erreur specifiques,  reconnus a partir de Polyflow
;      call asstring('ErrorInfo More MessageKey')
;      avant un p3errm EFATAL.
;=======================================================================
;
(defrule MAIN::Print_MoreInfo_Messages
  (declare (salience 800))
  (AllowRetroAction PrintMessages)
  (Current Stage ?Stage)
  ?f <- (Errmsg (Level ?L) (Routine ?Rout) (Msg $?MSG)(Stage ?Stage))
  ?g <- (ErrorInfo MoreInfo ?f)
=>
  (printout t crlf ?L " in " ?Rout crlf)
  (loop-for-count (?Count 1 (length$ $?MSG)) do
    (printout t "    " (nth$ ?Count $?MSG) crlf)
  )
  (Stop_Iter)
)



; ========================================================================
; =                                                                      =
; =  Error messages related to files management (open, close, read,      =
; =  write                                                               =
; =                                                                      = 
; ========================================================================

(defrule MAIN::Error_FileOpeningError
  (declare (salience 100))
  (Current Stage ?Stage)
  (ErrorInfo More FileOpeningError)
  ?f1 <- (Errmsg (Level Warning) (Routine ?Rout1) (Msg $?MSG1 ?FileNameError))
  ?f2 <- (Errmsg (Level Error | Intern) (Routine ?Rout2) (Msg $?MSG2))
=>

  (assert (ErrorInfo MoreInfo ?f2))
  (bind ?Message1  (str-cat "Files " ?FileNameError " could not be opened. "
                   )
   )
  (assert (Message (Stage ?Stage)
                   (String ?Message1 $?MSG2)
                   (Level 5)
                   (Kind GeneralDiagnostic)
           )
   )
  (bind ?Message1 "Please modify access rights or location of the files "
                  "and rerun Polyflow"
   )
  (assert (Message (Stage ?Stage)
                   (String ?Message1)
                   (Level 5)
                   (Kind Suggestion)
           )
   )
  (Stop_Iter)
)

;~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

(defrule MAIN::Error_DataFileReadingError
  (declare (salience 100))
  (Current Stage ?Stage)
  (ErrorInfo More DataFileReadingError)
  ?f <- (Errmsg (Level Error | Intern) (Routine ?Rout) (Msg $?MSG))
=>

  (bind ?Message (str-cat "The Data file can not be read."))
  (assert (Message (Stage ?Stage)
                   (String ?Message)
                   (Level 5)
                   (Kind GeneralDiagnostic)
           )
   )

  (bind ?Message (str-cat "If you have edited and modified the data file, "
                          "it shoud be corrupt at the line specified in the "
                          "above error message. If the data file comes directly "
                          "from POLYDATA, this is a serious internal error from "
                          "POLYDATA. "
                  )
   )
  (assert (Message (Stage ?Stage)
                   (String ?Message (AddGeneralMessage ProblemPersist)
                                     (AddGeneralMessage Apologize)
                    )
                   (Level 5)
                   (Kind Suggestion)
           )
   )

  (assert (ErrorInfo MoreInfo ?f))
)

;~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

(defrule MAIN::Error_OldResultFileReadingError
  (declare (salience 100))
  (Current Stage ?Stage)
  (ErrorInfo More OldResultFileReadingError)
  ?f <- (Errmsg (Level Error | Intern) (Routine ?Rout) (Msg $?MSG))
=>

  (bind ?Message (str-cat "The old result file can not be read."))
  (assert (Message (Stage ?Stage)
                   (String ?Message)
                   (Level 5)
                   (Kind GeneralDiagnostic)
           )
   )
  (bind ?Message1 (str-cat "This file has been opened but its contents is "
                           "incoherent with the data file and the mesh file "
                           "(mesh or field size)."
                   )
   )
  (bind ?Message2 (str-cat "Please be sure that"))
  (bind ?Message3 (str-cat "  - The old result file is the correct one "
                           "(access rights and location)."
                   )
   )
  (bind ?Message4 (str-cat "  - The contents of this file is not corrupted."))
  (assert (Message (Stage ?Stage)
                   (String ?Message1 ?Message2 ?Message3 ?Message4
                           (AddGeneralMessage ProblemPersist)
                           (AddGeneralMessage Apologize)                           
                    )
                   (Level 5)
                   (Kind Suggestion)
           )
   )

  (assert (ErrorInfo MoreInfo ?f))
)

;~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
(defrule MAIN::Error_ReadField
  (declare (salience 100))
  (Current Stage ?Stage)
  (ErrorInfo More ReadFieldError)
  ?f <- (Errmsg (Level Error | Intern) (Routine ?Rout) (Msg $?MSG))
=>

  (bind ?Message (str-cat "An error occurs during initialization of a field "
                          "using a read statement. "
                  )
   )
  (assert (Message (Stage ?Stage)
                   (String ?Message)
                   (Level 5)
                   (Kind GeneralDiagnostic)
           )
   )  
  (bind ?Message (str-cat "Please, check POLYFLOW reads the good file (mesh "
                          "file or old result file)."
                  )
   )
  (assert (Message (Stage ?Stage)
                   (String ?Message
                           (AddGeneralMessage ProblemPersist)
                           (AddGeneralMessage Apologize)                           
                    )
                   (Level 5)
                   (Kind Suggestion)
           )
   )

  (assert (ErrorInfo MoreInfo ?f))
 )

 
; ========================================================================
; =                                                                      =
; =  Error messages related to memory management.                        =
; =                                                                      = 
; ========================================================================

(defrule MAIN::Error_NonBufferMemory
  (declare (salience 100))
  (Current Stage ?Stage)
  (ErrorInfo More NonBufferMemory)
  ?f <- (Errmsg (Level Error | Intern) (Routine ?Rout) (Msg $?MSG))
=>

  (bind ?Message (str-cat "Because of the shortage of memory, Polyflow has "
                          "first tried to stored large temporary files on "
                          "disk.  Even with this out of core option, the "
                          "memory requirements are still too large so that "
                          "Polyflow must stop.  "
   )
  )
  (assert (Message (Stage ?Stage)
                   (String ?Message)
                   (Level 5)
                   (Kind GeneralDiagnostic)
           )
   )  
  (bind ?Message1 (str-cat "Please be sure that"))
  (bind ?Message2 (str-cat "  - someone else is not using the memory at the "
                           "moment."
                   )
   )
  (bind ?Message3 (str-cat "  - the mesh has been properly renumbered."))
  (bind ?Message4 (str-cat "  - if this is a large 3D case,  domain "
                           "decomposition has been used. "
                   )
   )
  (bind ?Message5 (str-cat "If the problem persists and the physical memory "
                           "is larger than the RAM reported by Polyflow, "
                           "consider extending the virtual memory of the "
                           "computer. "
                   )
   )
  (assert (Message (Stage ?Stage)
                   (String ?Message1 ?Message2 ?Message3 ?Message4 ?Message5)
                   (Level 5)
                   (Kind Suggestion)
           )
   )  
  (assert (ErrorInfo MoreInfo ?f))
)


; ========================================================================
; =                                                                      =
; =  Error messages related to topological operations.                   =
; =                                                                      = 
; ========================================================================

(defrule MAIN::Error_Topology
  (declare (salience 100))
  (Current Stage ?Stage)
  (ErrorInfo More TopoError)
  ?f <- (Errmsg (Level Error | Intern) (Routine ?Rout) (Msg $?MSG))
=>

  (bind ?Message (str-cat "An error has occured during topological operation."))
  (assert (Message (Stage ?Stage)
                   (String ?Message)
                   (Level 5)
                   (Kind GeneralDiagnostic)
           )
   )  

  (bind ?Message (str-cat "This topological error is probably an inconsistency "
                          "between the mesh and the data files. "
                          "Different indexes are used for sub-domains or "
                          "boundary sets in the both files.  If you have "
                          "modified or refined your mesh, please check the "
                          "sub-domains and boundary sets numbering. "
                  )
   )
  (assert (Message (Stage ?Stage)
                   (String ?Message 
                           (AddGeneralMessage ProblemPersist)
                           (AddGeneralMessage Apologize)
                    )
                   (Level 5)
                   (Kind Suggestion)
           )
   )  
  (assert (ErrorInfo MoreInfo ?f))
)

(defrule MAIN::Error_Slicing
  (declare (salience 100))
  (Current Stage ?Stage)
  (ErrorInfo More SlicingError)
  ?f <- (Errmsg (Level Error | Intern) (Routine ?Rout) (Msg $?MSG))
=>

  (bind ?Message (str-cat "An error has occured during slicing operation."))
  (assert (Message (Stage ?Stage)
                   (String ?Message)
                   (Level 5)
                   (Kind GeneralDiagnostic)
           )
   )  
  (bind ?Message (str-cat "This slicing error is probably due to one of the following reasons: "
                          "1. the domain to slice is not sliceable (each slice, from inlet to outlet sections should have same cells/faces distribution). "
                          "2. there is an inconsistency between the inlet and outlet sections of the remeshing domain.  Please, check the inlet and oulet "
                          "sections in the remeshing menu."
                  )
   )
  (assert (Message (Stage ?Stage)
                   (String ?Message 
                           (AddGeneralMessage ProblemPersist)
                           (AddGeneralMessage Apologize)
                    )
                   (Level 5)
                   (Kind Suggestion)
           )
   )  
  (assert (ErrorInfo MoreInfo ?f))
)

; ========================================================================

(defrule MAIN::Error_License
  (declare (salience 100))
  (Current Stage ?Stage)
  (ErrorInfo More LicenseError)
  ?f <- (Errmsg (Level Error | Intern) (Routine ?Rout) (Msg $?MSG))
=>

  (bind ?Message (str-cat "A valid license could not be checkedout.  "))
  (assert (Message (Stage ?Stage)
                   (String ?Message)
                   (Level 5)
                   (Kind GeneralDiagnostic)
           )
   )  

  (bind ?Message1 (str-cat "In case you are using a floating license (FlexLm) "
                           "mechanism, this caused be caused by a licensing "
                           "daemon that is not currently out of work."
                   )
   )
  (bind ?Message2 (str-cat "If this is a new installation, a valid license key "
                           "must first be generated."
                   )
   )
  (bind ?Message3 (str-cat "In case the problem persists,  please contact your "
                           "Ansys Polyflow representative."
                   )
   )
  (assert (Message (Stage ?Stage)
                   (String ?Message1 ?Message2 ?Message3  
                    )
                   (Level 5)
                   (Kind Suggestion)
           )
   )  
  (assert (ErrorInfo MoreInfo ?f))
)

(defrule MAIN::Error_License_Non_Commercial
  (declare (salience 100))
  (Current Stage ?Stage)
  (ErrorInfo More LimitedLicenseError)
  ?f <- (Errmsg (Level Error | Intern) (Routine ?Rout) (Msg $?MSG))
=>

  (bind ?Message1 (str-cat "You are currently using Polyflow under a "
                           "NON-COMMERICIAL license contract. "                  
                   )
   )  
  (bind ?Message2 (str-cat "Those licensing conditions are intended for "
                           "educational use only.  This implies a limitation "
                           "based on the number of 2D or 3D elements in use, "
                           "and this number has been exceeded.  "
                   )
   )  
  
  (bind ?Message3 (str-cat "Please contact your Ansys Polyflow representative."))
  (assert (Message (Stage ?Stage)
                   (String ?Message1 ?Message2 ?Message3)
                   (Level 5)
                   (Kind GeneralDiagnostic)
           )
   )  
  (assert (ErrorInfo MoreInfo ?f))
)


; ========================================================================
; =                                                                      =
; =  Error messages related to evolution.                                =
; =                                                                      = 
; ========================================================================

(defrule MAIN::EvolutionFirstStep
  (declare (salience 100))
  (Current Stage ?Stage)
  (ErrorInfo More FirstDidNotConverge)
  ?f <- (Errmsg (Level Error | Intern) (Routine ?Rout) (Msg $?MSG))
=>

  (bind ?Message1 (str-cat "You are currently run Polyflow with an evolution "
                           "but the first step of the evolution did not "
                           "converge."
                   )
   )
  (bind ?Message2 (str-cat "The expert system suggests to check the set up of "
                           "of the problem and more precisely the non-linear "
                           "parameters."
                   )
   )
  (bind ?Message3 (str-cat "See also if there are no other previous messages "
                           "related to divergence or evolution."
                   )
   )
  (assert (Message (Stage ?Stage)
                   (String ?Message1 ?Message2 ?Message3)
                   (Level 5)
                   (Kind GeneralDiagnostic)
           )
   )  
  (assert (ErrorInfo MoreInfo ?f))
)

; ========================================================================
; =                                                                      =
; =  Error messages related to sdual.                                =
; =                                                                      = 
; ========================================================================

(defrule MAIN::MatrixErrorInDual
  (declare (salience 100))
  (Current Stage ?Stage)
  (ErrorInfo More DualMatrixError)
  ?f <- (Errmsg (Level Error | Intern) (Routine ?Rout) (Msg $?MSG))
=>

  (bind ?Message1 (str-cat "There is a problem during local matrix computation "
                           "of a dual postprocessor."
                           "  If some troubles have occured during the "
                           "computation of the main task, do not pay attention "
                           "to this message."
                   )
   )
  (assert (Message (Stage ?Stage)
                   (String ?Message1)
                   (Level 5)
                   (Kind GeneralDiagnostic)
           )
   )  
  (assert (ErrorInfo MoreInfo ?f))
)

; ========================================================================
; =                                                                      =
; =  Error messages related to cricsv.                                =
; =                                                                      = 
; ========================================================================

(defrule MAIN::ErrorFieldNotInitializedInCricsv
  (declare (salience 100))
  (Current Stage ?Stage)
  (ErrorInfo More Field not initialized in cricsv)
  ?f <- (Errmsg (Level Error | Intern) (Routine ?Rout) (Msg $?MSG))
=>
  (bind ?Message1 (str-cat "There is a problem during the reading of the CSV "
                           "file in the mesh/mesh interpolation module.  "
                           "Please check the field name, the label name "
                           "or the file name.  (See above message from routine "
                           "CRICSV)"
                   )
   )
  (assert (Message (Stage ?Stage)
                   (String ?Message1)
                   (Level 5)
                   (Kind Suggestion)
           )
   )  
  (assert (ErrorInfo MoreInfo ?f))
)

; ========================================================================
; =                                                                      =
; =  Error With UDF.                                                     =
; =                                                                      = 
; ========================================================================

; UDF not found

(defrule MAIN::ErrorUdfNotFound
  (declare (salience 100))
  (Current Stage ?Stage)
  (ErrorInfo More UDF not found ?UDFName)
  ?f <- (Errmsg (Level Error | Intern) (Routine ?Rout) (Msg $?MSG))
=>
  (bind ?Message1 (str-cat "Your UDF : " ?UDFName " has not been found."))
  (bind ?Message2 (str-cat "Please be sure that"))
  (bind ?Message3 (str-cat "  - You run POLYFLOW with the option -f "
                           "following by the name of the file containing the "
                           "udf."
                   )
   )
  (bind ?Message4 (str-cat "      i.e. polyflow -f udf-file < data-file"
                   )
   )
  (bind ?Message5 (str-cat "  - The name of the UDF (in the udf-file) is "
                           "correct."
                   )
   )
  (bind ?Message6 (str-cat "  - There are no error messages from clips at the "
                           "beginning of the listing.  "
                           "You can check your UDF using the qa executable: "
                   )
   )
  (bind ?Message7 (str-cat "      i.e. $POLYFLOW/bin/qa    "))
  (bind ?Message8 (str-cat "    At the CLIPS prompt, enter   (batch udf-file)"))
  (bind ?Message9 (str-cat "    If no errors are found, qa will report TRUE "
                           "and print out the UDF.  See POLYFLOW User's "
                           "Guide manual : chapter 28.2.3  Testing Your UDF"
                   )
   )
  (assert (Message (Stage ?Stage)
                   (String ?Message1 ?Message2 ?Message3 ?Message4 ?Message5 
                           ?Message6 ?Message7 ?Message8 ?Message9
                    )
                   (Level 5)
                   (Kind Suggestion)
           )
   )  
  (assert (ErrorInfo MoreInfo ?f))
)


; Trouble in Udf

(defrule MAIN::TroubleInUDF
  (declare (salience 100))
  (Current Stage ?Stage)
  (ErrorInfo More Trouble in UDF ?Routine ?UDFName)
  ?f <- (Errmsg (Level Error | Intern) (Routine ?Rout) (Msg $?MSG))
=>
  (bind ?Message1 (str-cat "There is a trouble in your UDF : " ?UDFName 
                           ".  Clips has printed an error message.  See above." 
                   )
   )
  (bind ?Message2 (str-cat "Please be sure that your UDF is correct.  "
                           "Check arguments, use of mathematical functions ..."
                   )
   )
  (assert (Message (Stage ?Stage)
                   (String ?Message1 ?Message2)
                   (Level 5)
                   (Kind Suggestion)
           )
   )  
  (assert (ErrorInfo MoreInfo ?f))
)

(defrule MAIN::Variable_Not_Ref_Preloc
   (declare (salience 100))
   (Current Stage ?Stage)
   (ErrorInfo More VariableNotReferenced)
   ?f <- (Errmsg (Level Warning) (Routine ?Rout) (Msg $?MSG))
   (not (VariableNotReferenced Already Treated))
=>
   (bind ?Message1 (str-cat 
      "There are some warning messages produced by preloc routine.  "
      "The subject of the message is related to variables not "
      "referenced.  This could lead to ponctual zero values for "
      "some variables (e.g. pressure or velocity).")
    )
   (bind ?Message2 (str-cat 
      "An other number of domains for the domain decomposition could "
      "avoid this trouble.")
    )
   (bind ?Message3 (str-cat
      "PLEASE CONTACT ANSYS POLYFLOW SUPPORT AND SEND US, IF POSSIBLE THE MESH"
      ", DATA, LISTING AND INSTANCES FILES.")
    )
   (assert (Message (Stage ?Stage)
                    (String ?Message1 ?Message2 ?Message3
                       (AddGeneralMessage Apologize)
                     )
                    (Level 5)
                    (Kind Warning)
            )
    )
   (assert (ErrorInfo More ?f))
   (assert (VariableNotReferenced Already Treated))
 ) 

(defrule MAIN::WarningInXTestq
   (EndOfP3 (Termination ?termination))
   ?f <- (Errmsg (Level Warning) (Routine XTESTQ) (Msg $?msg) (Stage ?stage))
   ?f2 <- (Evolution (Step ?step) (S ?scur) (Stage ?stage) (Status BeginStep))
   (test (< (fact-index ?f2) (fact-index ?f)))
=>
   (printout t crlf "WARNING from XTESTQ, at step " ?step " (at time " ?scur ")" crlf )
   (progn$ (?I $?msg)
     (printout t ?I crlf )
    )
;  (retract ?f)
)
