(*Revision history:
09-03-2002:replaced Inner[List,A.x,b,List]]] by Inner[List,-A.x,b,List] in GetInequFromHRep[hrep_List/;hrep[[Length[hrep]]]≠{"end"}] "GetInequFromMatrix[{A_,b_,part_,angles_}]:= \
A.MakeVariables[part,angles]>=b" changed to\
"GetInequFromMatrix[{A_,b_,part_,angles_}]:=
    			A.MakeVariables[part,angles]>=-b"
18-09-2002:: in GetViolInequalities replaced ApplyFunctions[hrep,angles,...] with ApplyFunctions[hrep,N/@angles,...]    
20-02-2003: in ContPlotInequalities  added wrapper to PlotLabel to adjust Label according to ImageSize	
18-03-2003: MakeVariables for TruthTable changed to MakeVariablesTT for subscripts
    			*)

\(BeginPackage["CddIF`", "DiscreteMath`Combinatorica`", "Graphics`MultipleListPlot`"]\)
CddIF::usage = "These package acts as an Interface to the \
cdd-programm\n(Copyright (C) 1996, Komei Fukuda, fukuda@ifor.math.ethz.ch) \
written by Stefan Filipp, e9725660@stud3.tuwien.ac.at, May 2001.\nAvailable \
Functions are:\n
CddFormat
ToCddExtFile
TruthTable
RunCdd
ShowVRep
ConvToHRep
ReadInHRep
GetInequFromHRep
InequToRead
GetViolInequalities
PlotInequalities
ContPlotInequalities
Cdd"
SetCddCmd::usage = "SetCddCmd[cmd_String] - sets commandname for \
cdd"
CddFormat::usage = "CddFormat[vertices_List,options_List] - ouputs \
vertices and Options in an V-presentation format for use in cdd"
\(ToCddExtFile::usage = "ToCddExtFile[file_String,vertices_List,options_List] or 
 ToCddExtFile[file_String,particles_Integer,measurements_Integer,options_List] - 
makes a file in V-presentation format for use in cdd with extension ".ext"."\)
\(TruthTable::usage = "TruthTable[particles_Integer,measurements_Integer] - 
creates a truthtable corresponding to the appropriate correlation polytope."\)
RunCdd::usage = "RunCdd[file_String] - \nruns cdd with (.ext)-file as \
parameter and returns H-representation to use in other functions"
ShowVRep::usage = "ShowVRep[particles_Integer, measurements_Integer] \
- \nreturns V-representation of given configuration"
\(ConvToHRep::usage = "ConvToHRep[particles_Integer,measurements_Integer,file___String,options___] or 
ConvToHRep[vertices_List,file___String,options___] - 
converts given configuration or vertices-List to H-Representation"\)
ReadInHRep::usage = "ReadInHRep[file_String] - \nreads \
H-Representation from (.ine)-file for use in other functions"
GetInequFromHRep::usage = "GetInequFromHRep[hrep_List] - \nyields a \
list of inequalities from a given H-Representation"
InequToRead::usage = "InequToRead[inequalities_List] - \nyields a \
list of inequalities in readable form obtained from a list format returned by \
GetInequFromHRep[...]"
\(GetViolInequalities::usage = 
\*""GetViolInequalities[hrep_List, angles_List, functions_,NrOfInequ_List,violation_Real] or \nGetViolInequalities[file_String,angles_List, functions_, NrOfInequ_List,violation_Real] - \ncalculates the QM-discrepancy by applying functions_ to the H-Representation with given angles of measurement. \nAngles is for example {{0,π/2},{π/2,π}}, where the first detector for the first particle is at 0degrees, the 2nd detector for the 1st particle at π/2, the 1st detector for the 2nd particle at π/2.... Functions must take lists as input (e.g. Prob[{x_,y_}]:=Sin[x-y]^2/2).\nNrOfInequ_List is either \"All\" or a range specification of the form {min,max}.\n Violation indicates, that only inequalities violated more than this value are taken into consideration.\n If there are many inequalities, a (.ine)-file should be handed over instead of a H-Representation, it utilizes less memory and with option PrintOut-> True you see the violated ones printed out immediately.""\)
\(PlotInequalities::usage = \*""PlotInequalities[hrep_List,range_List,angles_List,functions_,opts___ or \nPlotInequalities[file_String, range_List, angles_List, functions_,NrOfInequ_List,violation_Real,opts___] - \n plots inequalities p(x) <= b as functions f(x)= p(x) - b, positive values indicating violation of classical conditions of experience.\nAngles is for example {{0,x},{x,π}}, where the detector for the first particle can be set to 0 degrees and x, the detector for the 2nd particle to π and x respectively, where x is a variable iterated as specified in \"range\".\nThe parameter \"functions\" must take lists as input (e.g. Prob[{x_,y_}]:=Sin[x-y]^2/2).\nNrOfInequ_List is either \"All\" or a range specification of the form {min,max}.\n Violation indicates, that only inequalities violated more than this value are taken into consideration.\n""\)
\(ContPlotInequalities::usage = \*""ContPlotInequalities[hrep_List,range_List,range_List,angles_List,functions_,NrOfInequ_List,violation_Real,opts___] or \nContPlotInequalities[file_String,range_List,range_List,angles_List,functions_,NrOfInequ,violation_Real,opts___] - \n yields contourplots of inequalities p(x,y) <= b specified by NrOfInequ (either \"All\" or range of form {min,max}) as functions f(x,y) = p(x,y) - b that are violated more than given by parameter \"violation\".\nThe parameter \"functions\" must take lists as input (e.g. Prob[{x_,y_}]:=Sin[x-y]^2/2), \"angles\" has to be a list containing the possible detection angles for each particle.""\)
\(Cdd::usage = "Cdd[input_List,cmd_String] - General Interface to "Cdd"
input_List has to be a list of strings each element representing a line for cdd.
cmd can be an alternate command like cddr or cddf"
\)
Begin["`Private`"]
Off[General::spell1]
Off[Graphics`MultipleListPlot`Star::shdw]
Options[CddIF] := {CddCmd -> "cdd"}
Options[CddFormat] := {}
Options[TruthTable] := {IncludeVars -> True}
Options[PlotList] := {PlotPoints -> 25}
Options[PlotInequalities] := {PlotJoined -> True, 
        Graphics`MultipleListPlot`SymbolShape -> None, 
        PlotStyle -> {Dashing[{}]}}
Options[GetViolInequalities] := {PrintOut -> False}
Options[ContPlotList] := {PrintOut -> False, 
        PlotPoints -> 25}
\(Options[ContPlot] := {PlotRange -> {\(-0. \), 1}, 
        ColorFunction -> \((GrayLevel[1 - #] &)\), Contours -> 30, 
        ContourLines -> False}
\)
\(SetCddCmd[cmd_String] := \ SetOptions[CddIF, CddCmd -> cmd]
 (*\ 
      Looks, \ if\ there\ is\ any\ "1" - value\ in\ list, \ 
      then\ value\ is\ taken\ as\ true\ *) \)
\(LogAnd[prop_List] := Times @@ prop

 (*\ 
      Gives\ any\ possible\ combination\ of\ 1  ´s\ and\ 0  ´s\ of\ length\ 2^n\ *) \)
\(CreateTrueVal[
        elements_Integer] := 
Reverse\  /@ \((Map[
PadLeft[#, elements] &, 
IntegerDigits[
              Range[0, Power[2, elements] - 1], 
              2]
])\)

 (*\ 
      Gives\ a\ list, \ 
      where\ all\ joint\ events\ are\ taken\ into\ consideration\ *) \)
\(EventList[
        SingleEvents_List] := 
Flatten[
\(Flatten[
Apply[Outer, 
\(Insert[#, List, 
                      1] &\) /@ \ 
DiscreteMath`Combinatorica`KSubsets[
                    SingleEvents, #], 
{1}], 
#] &\) /@ \ 
          Range[Length[
              SingleEvents]], 
1]

 (*\ 
      yields\ the\ truthtable\ for\ the\ events\ "x-particles are measured in y-angles"\ *) \)
TruthT[part_Integer, 
        angles_Integer] := 
Module[
{events = 
            Table[Unique[], {part}, {angles}]}, 
Map[
          LogAnd, 
(EventList[
                    events] /. #) & /@ 
(
Inner[Rule, Flatten[events], #, 
                    List] & /@  
CreateTrueVal[
                  Length[Flatten[
                      events]]]
), 
{2}]]

TruthTable[part_Integer, angles_Integer, 
        opts___] := 
(Prepend[TruthT[part, angles], 
              MakeVariablesTT[part, angles]] // 
            MatrixForm)/;(IncludeVars   /. {opts} /. 
            Options[TruthTable])

TruthTable[part_Integer, angles_Integer, 
        opts___] := 
TruthT[part, 
          angles] /; ¬(IncludeVars  /. {opts} /. 
              Options[TruthTable])

 (* 
            takes a list of vertices (i . e .  v - 
                  representation) and yields the representation ready to use with cdd *) 
\(CddFormat[vertices_List, 
        opts___List] := 
Append[
Insert[
Insert[
Insert[
vertices, 1, Table[{i, 1}, {i, 1, 
                  Length[vertices]}]], 
Append[
              Plus[Dimensions[vertices], {0, 
                  1}], "integer"], {1}], 
"V-representation
begin", {1}], 
"end
" <> 
\((\(StringJoin[#, "
"] &\) /@ 
\(ToString\  /@ \ 
Union[
                  opts, Options[
                    CddFormat]]\))\)]

 (*\ excludes\ comments\ from\ cdd - files\ *) \)
\(TestImportTable[
        strings_List] := 
True\  /; 
\(\((strings[\([1]\)] ≠ "*")\)\(&&\)\(
\)\((\((StringTake[strings[\([1]\)], 
                    1] ≠ "*")\) || 
              NumericQ[
                strings[\([1]\)]])\)\(
\)\(
\)\( (*\ 
            writes\ vertices\ into\ file\ including\ options\ for\ cdd\ if\ a\ list\ of\ vertices\ is\ given \((more\ general\ form)\)*) \)\)\)
\(ToCddExtFile[file_String, vertices_List, 
        opts___List] := 
Export[
file <> ".ext", 
CddFormat[vertices, 
          opts], 
"Table"]

 (*\ 
      writes\ vertices\ into\ file\ including\ options\ for\ cdd\ if\ a\ configuration\ \((x - particles, \ 
          y - angles)\)\ is\ given\ \((special\ form\ for\ boole - bell - 
            type\ inequalities)\)\ *) \)
\(ToCddExtFile[file_String, part_Integer, angles_Integer, 
        opts___List] := 
Export[
file <> ".ext", 
CddFormat[
          TruthT[part, 
            angles]], 
"Table"]

 (*\ 
      runs\ cdd\ on\ given\ file\ and\ yields\ result\ as\ h - 
        representation\ \((for\ use\ in\ further\ functions)\)\ *) \)
\(RunCdd[file_String, part_Integer, 
        angles_Integer] := 
Select[
CompoundExpression[
Run[\((CddCmd /. Options[CddIF])\) <> " " <> 
              file <> ".ext"], 
PutAppend[
            OutputForm["Konfiguration "\  <> 
                ToString[part]\  <> \ " "\  <> ToString[angles]]\ , 
            StringJoin[file, ".ine"]], 
Import[
            file <> ".ine", "Table"]], 
TestImportTable]
\)
\(RunCdd[
        file_String] := 
Select[
CompoundExpression[
Run[\((CddCmd /. Options[CddIF])\) <> " " <> 
              file <> ".ext"], 
Import[
            file <> ".ine", "Table"]], 
TestImportTable]


 (*\ shows\ v - representation\ *) \)
ShowVRep[part_, angles_] := 
CddFormat[
        TruthT[part, angles]]

  
GetMatrixFromVRep[
        vrep_List] := 
Module[
{m = 
            vrep[[Range[3, 
                  Length[vrep] - 1]]]}, 
m[[All, 
            Range[2, 
              Length[m[[1]]]]]]]

 (* converts particles - angles - configuration to h - 
        representation using cdd *) 
\(ConvToHRep[part_, angles_, file_String: "tmp", 
        opts___] := 
CompoundExpression[
ToCddExtFile[
          file, TruthT[part, angles], opts], 
RunCdd[file, 
          part, angles]]
\)
\(ConvToHRep[vertices_List, file_String: "tmp", 
        opts___] := 
CompoundExpression[
ToCddExtFile[
          file, vertices, opts], 
RunCdd[
          file]]

 (*\ 
      reads\ h - representation\ from\ file . ine\ *) \)
\(ReadInHRep[
        file_String] := 
Select[
Import[
          file <> ".ine", "Table"], 
TestImportTable]

\)
Concatenate[arg__] := Symbol[StringJoin[ToString /@  {arg}]]
Concatenate[arg_List] := 
      Symbol[StringJoin[ToString /@  arg]]
ClearAttributes[Concatenate, 
      Listable]

  
MakeVariables[part_, 
        angles_] := 
Concatenate /@
EventList[
Outer[
Concatenate, 
FromCharacterCode[
              List  /@ Range[97, 97 + part - 1]], 
Range[
              angles]]]

MakeVariablesTT[part_, 
        angles_] := 
DisplayForm /@ (
RowBox[#] & /@ 
EventList[
Outer[
Subscript[
                    Symbol[#1], #2] &, 
FromCharacterCode[
                  List  /@ 
                    Range[97, 97 + part - 1]], 
Range[
                  angles]]])

 (*only relevant data (A . x ≤ b) from H - 
        Representation is taken*) 
GetMatrixFromHRep[
        hrep_List] :=    
Module[
{m = 
            hrep[[Range[4, Length[hrep] - 2]]], 
part = 
            hrep[[-1, 2]], 
angles = 
            hrep[[-1, 
                3]] }, 
List[
m[[Range[Length[m]], 
              Range[2, Length[m[[1]]]]]], 
m[[All, 
              1]], 
part, 
angles]]

GetMatrixFromHRepMod[
        hrep_List] := 
Module[
{m = 
            hrep[[Range[4, 
                  Length[hrep] - 
                    2]]]}, 
List[
m[[Range[Length[m]], 
              Range[2, Length[m[[1]]]]]], 
m[[All, 
              1]]]]


 (* inequalities from h - 
        representation are equipped with variables *) 
\(GetInequFromHRep[
        hrep_List\  /; \ 
          hrep[\([Length[
                  hrep]]\)] != {"end"}] := \ \ 
Module[
{rawmatrix = 
            GetMatrixFromHRep[
              hrep]}, 
Module[
{A = 
              rawmatrix[\([1]\)], 
b = 
              rawmatrix[\([2]\)], 
x = 
              MakeVariables[rawmatrix[\([3]\)], 
                rawmatrix[\([4]\)]]}, 
Inner[
            List, \(-A . x\), b, List]]]
\)
GetInequFromHRep[
        hrep_List] := 
Module[
{rawmatrix = hrep[[Range[4, 
                  Length[hrep] - 
                    1]]]}, 
Module[
{A = rawmatrix[[All, 
                  Range[2, 
                    Length[rawmatrix[[1]]]]]], 
b = 
              rawmatrix[[All, 1]], 
x = 
              Symbol /@ FromCharacterCode /@ 
                  Range[97, 
                    97 + Length[rawmatrix[[1]]] - 
                      2]}, 
Inner[List, -A . x, b, 
            List]]]


 (*Inequalities from' rawmatrix' - 
        data obtained by GetMatrixFromHRep are produced here *) 
GetInequFromMatrix[{A_, b_, part_, angles_}] := 
A . 
          MakeVariables[part, 
            angles] ≥ -b

 (* 
      more readable form of inequalities obtained by GetInequFromHRep *) 
InequToRead[
        ineq_List] := LessEqual[#[[1]], #[[2]]] & /@ ineq // 
        MatrixForm

PartSymbol[
        sym_Symbol] := Symbol[StringTake[SymbolName[sym], {#, # + 1}]] & /@ 
        Range[1, StringLength[SymbolName[sym]], 
          2]

NotNull[x_Integer] := 
      True  /; x ≠ 0

 (* 
      not really applicable  -  
        further improvement of this function in future versions *) 
ReduceInequ[
        hrep_List] := 
Module[
{rawmatrix = GetMatrixFromHRep[hrep]}, 
Module[
{A = 
              rawmatrix[[1]], 
b = 
              rawmatrix[[2]], 
x = 
              MakeVariables[rawmatrix[[3]], 
                rawmatrix[[4]]]}, 
(#1 . 
                    x ≥ #2) &
Sequence @@ 
(Delete[#, 
Position[A, 
                        x_ /; Length[
                              Cases[x, y_?(NotNull[#] &)]] ≤ 
                            1, {1}, Heads -> False]  (* 
                        triviale weg *) 
] & /@ 
{A, b})]]

 (* 
      functions are applied to h - representation,  
      angles of detectors must be given and functions must be predefined in buffer *) 
\(ApplyFunctions[
        hrep_List\  /; \((StringPosition[\(hrep[\([\(-1\)]\)]\)[\([1]\)], "Konfiguration"] ≠ {})\)\ , angles_List, 
        func_ /; ValueQ[
            func[{_}]]] := 
Module[
{rawmatrix = 
            GetMatrixFromHRep[
              hrep]}, 
Module[
{A = 
              rawmatrix[\([1]\)], 
b = 
              rawmatrix[\([2]\)], 
x = 
              func /@ EventList[angles], 
vars = 
              MakeVariables[rawmatrix[\([3]\)], 
                rawmatrix[\([4]\)]]}, 
{GetInequFromHRep[
              hrep], \(-A . 
                x\)}]]
\)
\(ApplyFunctions[hrep_List, angles_List, 
        func_ /; ValueQ[
            func[{_}]]] := 
Module[
{rawmatrix = 
            GetMatrixFromHRepMod[
              hrep]}, 
Module[
{A = 
              rawmatrix[\([1]\)], 
b = 
              rawmatrix[\([2]\)], 
x = 
              func /@ EventList[angles], 
vars = 
              Symbol /@ \(FromCharacterCode /@ 
                  Range[97, 
                    97 + Length[rawmatrix[\([1]\)]] - 
                      2]\)}, 
{GetInequFromHRep[
              hrep], \(-A . x\)}]]

 (*\ 
      plot\ inequalities\ *) 
\)
NotNullAppend[l_List, expr_ /; ¬ expr === Null] := 
      Flatten[{l, expr}, 1]
\(NotNullAppend[l_List, expr_ /; expr === Null] := 
      l

\)
PlotList[function_, r : {var_, varmin_, varmax_}, 
        violation_Real] := 
Module[
{points = 
            N[PlotPoints /. 
                Options[
                  PlotList]]}, 
Module[
{plist = 
Table[
{var, 
                  function}, 
Evaluate[
                  Append[r, (varmax - varmin)/
                      points]]]}, 
{plist} /; 
            Max[plist[[All, 2]]] > 
              violation]]

PlotList[function_, r : {var_, varmin_, varmax_}, violation_Real, 
        opts___] := Null

PlotInequalities[hrep_List, limit_List, angles_List, 
        func_ /; ValueQ[func[{_}]], 
        opts___] := 
Module[
{data = 
            ApplyFunctions[hrep, angles, 
              func]}, 
Plot[
Evaluate[
            data[[2]] - data[[1]][[All, 
                  2]]], 
limit, 
          opts]]


\(PlotInequalities[file_String, limit_List, angles_List, 
        func_ /; ValueQ[func[{_}]], 
        equnr_ /; \((VectorQ[equnr] || equnr == All)\), violation_Real:  0. , 
        opts___] := 
Module[
{strFile = 
            OpenRead[file], plotfunctions}, 
Off[
          Read::readn]; 
plotfunctions = 
Module[
{strInput = 
                Read[strFile, Record], 
i = 0, min, 
              max, 
cols, 
result = {}, 
readform = Record, 
vars = 
                MakeVariables[
                  Sequence @@ Dimensions[angles]], 
x = 
                func /@ EventList[angles]}, 
If[
              equnr === All, 
min = 0; 
              max = Infinity, 
min = First[equnr]; 
              max = Last[
                  equnr]]; 

While[\((¬ \((strInput === 
                        EndOfFile)\)\  && ¬ \((strInput === $Failed)\)\  && \((i <= max)\))\), 
result = 
                NotNullAppend[
                  result, 
If[
strInput == "begin", 
strInput = 
                      Read[strFile, {Number, Number, 
                          String}]; 
cols = 
                      strInput[\([2]\)]; 
readform = 
                      Table[Number, {cols}];, 
Null, \(i++\); 
If[\((i >= min)\) && \((i <= 
                            max)\), 
Module[
{inequ = 
                            Times[Drop[strInput, 
                                1], \(-1\)], 
bound = 
                            strInput[\([1]\)]}, 
PlotList[
                          inequ . x - bound, limit, 
                          violation]]]]]; 
strInput = 
                Read[strFile, readform];]; result]; 
On[
          Read::readn]; 
Close[file]; 
If[
          plotfunctions ≠ {}, 
Graphics`MultipleListPlot`MultipleListPlot[
            Sequence @@ plotfunctions, 
            Sequence @@ 
              Join[{opts}, 
                Options[
                  PlotInequalities]]], 
{}]]

 (*\ 
      violated\ inequalites\ are\ obtained\ *) \ \)
GetViolInequalities[hrep_List, angles_List, func_ /; ValueQ[func[{_}]], 
        equnr_ /; (VectorQ[equnr] || equnr == All), 
        violation_Real:  
          0. ] :=  
Module[
{data = 
            ApplyFunctions[hrep, N /@ angles, 
              func], 
datarange = 
            equnr /. (equnr :> 
                  Range[Sequence @@ 
                        equnr]  /;  ¬ (equnr === 
                          All))}, 
Module[
{iequ = data[[1]][[datarange, 
                  1]], 
limit = data[[1]][[datarange, 
                  2]], 
qmsolution = data[[2]][[datarange]]}, 
List[
                LessEqual[iequ[[#]], limit[[#]]], 
                qmsolution[[#]]] & /@ 
Flatten[
Position[
Inner[Plus, 
                  qmsolution, -limit, List], 
x_ /; 
                  Greater[x, 
                    violation]]]]]


\(GetViolInequalities[file_String, angles_List, 
        func_ /; ValueQ[func[{_}]], 
        equnr_ /; \((VectorQ[equnr] || equnr == All)\), 
        violation_Real:  0. , 
        opt___] := 
Module[
{strFile = 
            OpenRead[file], retval}, 
Off[
          Read::readn]; 
retval = 
          Module[
{strInput = 
                Read[strFile, Record], 
i = 0, min, 
              max, 
cols, 
result = {}, 
readform = Record, 
vars = 
                MakeVariables[
                  Sequence @@ Dimensions[angles]], 
x = 
                func /@ EventList[
                    angles]}, 

If[
              equnr === All, 
min = 0; \ 
              max = Infinity, 
min = First[equnr]; \ 
              max = Last[
                  equnr]]; 

While[\((¬ \((strInput === 
                        EndOfFile)\) && ¬ \((strInput === $Failed)\) && \((i ≤ max)\))\), 
result = 
                NotNullAppend[result, 
                  If[
strInput == "begin", 
strInput = 
                      Read[strFile, {Number, Number, 
                          String}]; 
cols = 
                      strInput[\([2]\)]; 
readform = 
                      Table[Number, {cols}], 
Null, \(i++\); 
If[\((i ≥ 
                            min)\) && \((i ≤ 
                            max)\), 
Module[
{inequ = 
                            Times[Drop[strInput, 
                                1], \(-1\)], 
limit = 
                            strInput[\([1]\)]}, 
If[\((inequ . x - limit)\) > 
                            violation, 
If[\(PrintOut /. {opt}\) /. Options[GetViolInequalities], 
Print[{inequ . 
                                    vars ≤ limit, 
                                inequ . x // 
                                  N}]]; 
{inequ . 
                                vars ≤ limit, 
                            inequ . x // 
                              N}]]]]]; 
strInput = 
                Read[strFile, readform];
]; 
            result]; 
On[
          Read::readn]; 
Close[
          file]; 
DeleteCases[retval, 
          x_ /; Length[x] ≠ 
              
              2]
]
\)
\(ContPlotList[function_, r1 : {var1_, var1min_, var1max_}, 
        r2 : {var2_, var2min_, var2max_}, 
        opts___] := 
Module[
{points = 
            N[\(PlotPoints\  /. {opts}\) /. \ 
                Options[
                  ContPlotList]]}, 
List[
Table[
function, 
Evaluate[
              Append[r1, \((var1max - var1min)\)/
                  points]], 
Evaluate[
              Append[r2, \((var2max - var2min)\)/
                  points]]], 
Flatten[
Prepend[
Options[ContourGraphics], 
{opts, Options[ContPlot], 
                MeshRange -> {{var1min, var1max}, {var2min, 
                      var2max}}}]]]]

 (*\ 
      contour\ plot\ from\ h - 
        representation\ of\ violated\ inequalities\ *) \)
ContPlotInequalities[hrep_List, range1_, range2_, angles_, 
        func_ /; ValueQ[func[{_}]], 
        equnr_ /;  VectorQ[equnr]  ||  equnr == All, 
        violation_Real:  0. , 
        opts___] := 
Module[
{data = 
            ApplyFunctions[hrep, angles, 
              func], 
isize = ImageSize /. {opts} /. 
              ImageSize -> 
                288, 
fsize = FontSize /. {opts} /. $TextStyle /. FontSize -> 12}, 
ContourGraphics[
              Sequence @@ #] & /@ 
Select[
(ContPlotList[#[[1]], range1, range2, opts, 
                    PlotLabel -> 
DisplayForm[
StyleBox[
GridBox[{{#[[2]]}}, 
                            ColumnWidths -> 
                              IntegerPart[
                                isize/
                                  fsize]], 
LineSpacing -> {N[fsize/12], 2}, 
                          LineIndent -> 
                            0]]
]
 & /@ 
Part[
(Inner[
List, 
data[[2]] - data[[1]][[All, 
                            2]], 
LessEqual @@@ 
                        data[[1]], 
List]), 
equnr /. (equnr :> 
                        Range[Sequence @@ 
                              equnr] /; ¬ (equnr === 
                                All))]), 
Max[#[[1]]] > violation &]]

\(ContPlotInequalities[file_String, range1_List, range2_List, 
        angles_List, func_ /; ValueQ[func[{_}]], 
        equnr_ /; \ VectorQ[equnr] || equnr == All, violation_Real:  0.001, 
        opts___] := 
Module[
{strFile = 
            OpenRead[file], 
          contplots}, 

If[
          strFile === $Failed, Abort[]]; 
Off[
          Read::readn]; 
contplots = 
          Module[
{strInput = 
                Read[strFile, 
                  Record], 
result = {}, 
i = 0, min, 
              max, 
symInput, 
cols, 
              rows, 
contopts = 
                DeleteCases[{opts}, 
                  x_ /; MemberQ[x, PrintOut]], 
readform = 
                Record, 
vars = 
                MakeVariables[
                  Sequence @@ Dimensions[angles]], 
x = 
                func /@ EventList[
                    angles], 
isize = \(ImageSize /. {opts}\) /. ImageSize -> 
                    288, 
fsize = \(\(FontSize /. {opts}\) /. $TextStyle\) /. FontSize -> 
                    12}, 



While[\((strInput ≠ "begin")\)\  && \ ¬ \((strInput === 
                      EndOfFile)\)\  && ¬ \((strInput === $Failed)\), \ 
strInput = 
                Read[strFile, 
                  readform]]; 

strInput = Read[strFile, {Number, Number, String}]; 
cols = 
              strInput[\([2]\)]; 
rows = 
              strInput[\([1]\)]; 
readform = 
              Table[Number, {cols}]; \ 
If[equnr === All, 
              min = 0; \ max = rows, min = First[equnr]; \ 
              max = Last[equnr]]; \ \ \ 
For[i = 0, 
              i < min - 1, \(i++\), 
              Read[strFile, 
                readform]]; 

For[
              i = min, 
              i <= max, \(i++\), 
strInput = 
                Read\ [strFile, readform]; 
result = 
                NotNullAppend[
                  result, 
Module[
{graph = ContPlotList[
Times[Drop[strInput, 1] . x, \(-1\)] - 
                            strInput[\([1]\)], 
range1, 
range2, 
Sequence @@ 
                            contopts]}, 
If[
                      Max[graph[\([1]\)]] > 
                        violation, 
If[\(PrintOut /. {opts}\) /. Options[ContPlotList], 
Show[
                          ContourGraphics[
                            graph[\([1]\)], 
PlotLabel -> ToString[Times[Drop[strInput, 1] . vars, \(-1\)] <= 
                                  strInput[\([1]\)], 
                                PageWidth -> 
                                  50], 
graph[\([2]\)]]]]; 
ContourGraphics[graph[\([1]\)], 
                        PlotLabel -> 
DisplayForm[
StyleBox[
GridBox[{{Times[
                                        Drop[strInput, 1] . vars, \(-1\)] <= 
                                      strInput[\([1]\)]}}, 
                                ColumnWidths -> 
                                  IntegerPart[
                                    isize/
                                      fsize]], 
LineSpacing -> {N[fsize/12], 2}, LineIndent -> 0]], 
                        graph[\([2]\)]]]
]]]; 
            result]; 

Close[
          strFile]; 
On[
          Read::readn]; 
contplots]


 (*\ 
      general\ interface\ to\ cdd\ *) \)
\(Cdd[input_List, 
        cmd_String: \((CddCmd /. 
              Options[CddIF])\)] := 
Module[
{calculation}, 
If[
          Position[input, 
              x_\  /; ToLowerCase[
                    ToString[
                      x]] == "v-representation"] ≠ {}, 
Export["tmp.ext", 
            input, "Table"]; 
Run[
            
            cmd <> " " <> \ "tmp.ext"]; 
calculation = 
            Import["tmp.ine", "Table"], 
file = 
            Export["tmp.ine", input, "Table"]; 
Run[
            cmd\  <> \ " tmp.ine"]; 
calculation = 
            Import["tmp.ext", "Table"]]; 
Return[
          calculation\ ];]
\)
SetDirectory["."]
SetCddCmd["cdd"]
End[]
EndPackage[]