module ArDCA

using Random: randperm
using Distributed: @distributed
using Printf: @printf
using LinearAlgebra: rmul!, norm
using ExtractMacro: @extract
using NLopt: Opt,ftol_abs!,xtol_rel!,xtol_abs!,ftol_rel!,maxeval!,min_objective!,optimize
using Distributions: wsample
using LoopVectorization: @avx
using DCAUtils: read_fasta_alignment,remove_duplicate_sequences,compute_weights

export ardca,ArVar,ArAlg,ArNet,sample,sample_with_weights,epistatic_score,dms_single_site

include("types.jl")
include("ar.jl")
include("utils.jl")
include("dca.jl")

end # end module


module TestExamples2DEuler

using Test
using Trixi

include("test_trixi.jl")

# pathof(Trixi) returns /path/to/Trixi/src/Trixi.jl, dirname gives the parent directory
EXAMPLES_DIR = joinpath(pathof(Trixi) |> dirname |> dirname, "examples", "tree_2d_dgsem")

@testset "Compressible Euler" begin
  @trixi_testset "elixir_euler_source_terms.jl" begin
    @test_trixi_include(joinpath(EXAMPLES_DIR, "elixir_euler_source_terms.jl"),
      l2   = [8.517808508019351e-7, 1.2350203856098537e-6, 1.2350203856728076e-6, 4.277886946638239e-6],
      linf = [8.357848139128876e-6, 1.0326302096741458e-5, 1.0326302101404394e-5, 4.496194024383726e-5])
  end

  @trixi_testset "elixir_euler_convergence_pure_fv.jl" begin
    @test_trixi_include(joinpath(EXAMPLES_DIR, "elixir_euler_convergence_pure_fv.jl"),
      l2   = [0.026440292358506527, 0.013245905852168414, 0.013245905852168479, 0.03912520302609374],
      linf = [0.042130817806361964, 0.022685499230187034, 0.022685499230187922, 0.06999771202145322])
  end

  @trixi_testset "elixir_euler_density_wave.jl" begin
    @test_trixi_include(joinpath(EXAMPLES_DIR, "elixir_euler_density_wave.jl"),
      l2   = [0.0010600778457964775, 0.00010600778457634275, 0.00021201556915872665, 2.650194614399671e-5],
      linf = [0.006614198043413566, 0.0006614198043973507, 0.001322839608837334, 0.000165354951256802],
      tspan = (0.0, 0.5))
  end

  @trixi_testset "elixir_euler_source_terms_nonperiodic.jl" begin
    @test_trixi_include(joinpath(EXAMPLES_DIR, "elixir_euler_source_terms_nonperiodic.jl"),
      l2   = [2.3653424742011065e-6, 2.1388875092652046e-6, 2.1388875093792834e-6, 6.010896863407163e-6],
      linf = [1.4080465934984687e-5, 1.7579850582816192e-5, 1.757985059525069e-5, 5.95689353266593e-5])
  end

  @trixi_testset "elixir_euler_ec.jl" begin
    @test_trixi_include(joinpath(EXAMPLES_DIR, "elixir_euler_ec.jl"),
      l2   = [0.061751715597716854, 0.05018223615408711, 0.05018989446443463, 0.225871559730513],
      linf = [0.29347582879608825, 0.31081249232844693, 0.3107380389947736, 1.0540358049885143])
  end

  @trixi_testset "elixir_euler_ec.jl with flux_kennedy_gruber" begin
    @test_trixi_include(joinpath(EXAMPLES_DIR, "elixir_euler_ec.jl"),
      l2   = [0.03481471610306124, 0.027694280613944234, 0.027697905866996532, 0.12932052501462554],
      linf = [0.31052098400669004, 0.3481295959664616, 0.34807152194137336, 1.1044947556170719],
      maxiters = 10,
      surface_flux = flux_kennedy_gruber,
      volume_flux = flux_kennedy_gruber)
  end

  @trixi_testset "elixir_euler_ec.jl with flux_chandrashekar" begin
    @test_trixi_include(joinpath(EXAMPLES_DIR, "elixir_euler_ec.jl"),
      l2   = [0.03481122603050542, 0.027662840593087695, 0.027665658732350273, 0.12927455860656786],
      linf = [0.3110089578739834, 0.34888111987218107, 0.3488278669826813, 1.1056349046774305],
      maxiters = 10,
      surface_flux = flux_chandrashekar,
      volume_flux = flux_chandrashekar)
  end

  @trixi_testset "elixir_euler_shockcapturing.jl" begin
    @test_trixi_include(joinpath(EXAMPLES_DIR, "elixir_euler_shockcapturing.jl"),
      l2   = [0.05380378209319121, 0.04696482040740498, 0.046967440141927635, 0.19686385916646665],
      linf = [0.1852693811520424, 0.24028641582658528, 0.2326441454434102, 0.6874069967414047])
  end

  @trixi_testset "elixir_euler_blast_wave.jl" begin
    @test_trixi_include(joinpath(EXAMPLES_DIR, "elixir_euler_blast_wave.jl"),
      l2   = [0.1399704878290245, 0.11580885255188444, 0.115808885313645, 0.3391969791404581],
      linf = [1.4473441276982646, 1.3355435317505784, 1.335543531751034, 1.8203831482774346],
      maxiters = 30)
  end

  @trixi_testset "elixir_euler_blast_wave_pure_fv.jl" begin
    @test_trixi_include(joinpath(EXAMPLES_DIR, "elixir_euler_blast_wave_pure_fv.jl"),
      l2   = [0.39957047631960346, 0.21006912294983154, 0.21006903549932, 0.6280328163981136],
      linf = [2.20417889887697, 1.5487238480003327, 1.5486788679247812, 2.4656795949035857],
      tspan = (0.0, 0.5))
  end

  @trixi_testset "elixir_euler_blast_wave_amr.jl" begin
    @test_trixi_include(joinpath(EXAMPLES_DIR, "elixir_euler_blast_wave_amr.jl"),
      l2   = [0.6777351803934385, 0.28143110338521693, 0.28143035507881886, 0.7211949078634373],
      linf = [2.881942488461436, 1.8037294505391677, 1.803677581960154, 3.037915614619938],
      tspan = (0.0, 1.0))
  end

  @trixi_testset "elixir_euler_sedov_blast_wave.jl" begin
    @test_trixi_include(joinpath(EXAMPLES_DIR, "elixir_euler_sedov_blast_wave.jl"),
      l2   = [0.4819231474652106, 0.1655453843075888, 0.16554538430758944, 0.6182451347074112],
      linf = [2.4849541392059202, 1.2816207838889486, 1.2816207838888944, 6.4743208586529875],
      tspan = (0.0, 1.0))
  end

  @trixi_testset "elixir_euler_positivity.jl" begin
    @test_trixi_include(joinpath(EXAMPLES_DIR, "elixir_euler_positivity.jl"),
      l2   = [0.48401054859424775, 0.16613328471131006, 0.16613328471131006, 0.6181793382171535],
      linf = [2.4903327485761544, 1.2898210694161085, 1.2898210694161072, 6.4723873993158385],
      tspan = (0.0, 1.0))
  end

  @trixi_testset "elixir_euler_blob_mortar.jl" begin
    @test_trixi_include(joinpath(EXAMPLES_DIR, "elixir_euler_blob_mortar.jl"),
      l2   = [0.22206706482833133, 0.6296849068200803, 0.24351238064525166, 2.9118777552679345],
      linf = [9.584083314003589, 27.72635365994101, 9.343044146443756, 101.53747277352629],
      tspan = (0.0, 0.5))
  end

  @trixi_testset "elixir_euler_blob_amr.jl" begin
    @test_trixi_include(joinpath(EXAMPLES_DIR, "elixir_euler_blob_amr.jl"),
      l2   = [0.20150296718390992, 1.1816675092370863, 0.10129652123574924, 5.230357225596295],
      linf = [14.174958287930844, 71.16876942972455, 7.2799739019809415, 291.67608863630244],
      tspan = (0.0, 0.12))
  end

  @trixi_testset "elixir_euler_kelvin_helmholtz_instability.jl" begin
    @test_trixi_include(joinpath(EXAMPLES_DIR, "elixir_euler_kelvin_helmholtz_instability.jl"),
      l2   = [0.055689867638859906, 0.032985369421826734, 0.052243738479375024, 0.08009259073134713],
      linf = [0.24051443859674326, 0.16611572070980668, 0.123559477474734, 0.2694484247345663],
      tspan = (0.0, 0.2))
  end

  @trixi_testset "elixir_euler_kelvin_helmholtz_instability_amr.jl" begin
    @test_trixi_include(joinpath(EXAMPLES_DIR, "elixir_euler_kelvin_helmholtz_instability_amr.jl"),
      l2   = [0.05569140599245201, 0.033108757924402134, 0.05223526059785845, 0.08007239985228143],
      linf = [0.2540392117514094, 0.17432468822204936, 0.12323401271048683, 0.26897998287356195],
      tspan = (0.0, 0.2))
  end

  @trixi_testset "elixir_euler_colliding_flow.jl" begin
    @test_trixi_include(joinpath(EXAMPLES_DIR, "elixir_euler_colliding_flow.jl"),
      l2   = [7.23705116e-03,   4.48861301e-02,   8.47273157e-07,   6.62667920e-01],
      linf = [1.93754293e-01,   5.52253475e-01,   4.98055004e-05,   1.50879674e+01],
      tspan = (0.0, 0.1))
  end

  @trixi_testset "elixir_euler_colliding_flow_amr.jl" begin
    @test_trixi_include(joinpath(EXAMPLES_DIR, "elixir_euler_colliding_flow_amr.jl"),
      l2   = [6.76960244e-03,   3.21735698e-02,   2.63316434e-07,   6.78416591e-01],
      linf = [2.50119529e-01,   4.07493507e-01,   9.96993324e-05,   2.23204482e+01],
      tspan = (0.0, 0.1))
  end

  @trixi_testset "elixir_euler_astro_jet_amr.jl" begin
    @test_trixi_include(joinpath(EXAMPLES_DIR, "elixir_euler_astro_jet_amr.jl"),
      l2   = [0.011338493575859507, 10.097552800226566, 0.0038670992882799088, 4031.828021246965],
      linf = [3.316670548834158, 2992.6286682433883, 7.919515633718346, 1.1914747265545786e6],
      tspan = (0.0, 1.0e-7))
  end

  @trixi_testset "elixir_euler_vortex.jl" begin
    @test_trixi_include(joinpath(EXAMPLES_DIR, "elixir_euler_vortex.jl"),
      l2   = [3.6343141788303172e-6, 0.0032111379945554378, 0.0032111482803927763, 0.004545715899533244],
      linf = [7.901851921288117e-5, 0.030561510550305093, 0.03050266851613559, 0.042876690674344076])
  end

  @trixi_testset "elixir_euler_vortex_mortar.jl" begin
    @test_trixi_include(joinpath(EXAMPLES_DIR, "elixir_euler_vortex_mortar.jl"),
      l2   = [2.1203067597905396e-6, 2.792922844344066e-5, 3.7593422075434476e-5, 8.813644239472934e-5],
      linf = [5.932046017209647e-5, 0.0007491265252463908, 0.0008165690091972433, 0.0022122638482677814])
  end

  @trixi_testset "elixir_euler_vortex_mortar_split.jl" begin
    @test_trixi_include(joinpath(EXAMPLES_DIR, "elixir_euler_vortex_mortar_split.jl"),
      l2   = [2.1201025902895562e-6, 2.8056524989293713e-5, 3.759500393896144e-5, 8.84137216637438e-5],
      linf = [5.934103282212444e-5, 0.0007552316670187409, 0.0008152449093751235, 0.0022069874183294758])
  end

  @trixi_testset "elixir_euler_vortex_shockcapturing.jl" begin
    @test_trixi_include(joinpath(EXAMPLES_DIR, "elixir_euler_vortex_shockcapturing.jl"),
      l2   = [3.7998676433961623e-6, 5.563687203373343e-5, 5.561628017766063e-5, 0.00015707075214260475],
      linf = [8.522682141076654e-5, 0.0009610342345369727, 0.0009656468947373265, 0.0030861481615822584])
  end

  @trixi_testset "elixir_euler_vortex_mortar_shockcapturing.jl" begin
    @test_trixi_include(joinpath(EXAMPLES_DIR, "elixir_euler_vortex_mortar_shockcapturing.jl"),
      l2   = [2.1203212494737245e-6, 2.8056721454951553e-5, 3.759510818832351e-5, 8.842116438932004e-5],
      linf = [5.9340649220973596e-5, 0.0007552376287922602, 0.0008152432005811283, 0.0022069702233196153])
  end

  @trixi_testset "elixir_euler_vortex_amr.jl" begin
    @test_trixi_include(joinpath(EXAMPLES_DIR, "elixir_euler_vortex_amr.jl"),
      l2   = [2.1325938318497577e-6, 0.003281545066125044, 0.0032806321457482615, 0.00464605975938406],
      linf = [4.667437348149228e-5, 0.03175420871507906, 0.0318039789241531, 0.04561735256198318])
  end
end

end # module


__precompile__(true)

module GGPlots

using Reexport
@reexport using StatPlots
@reexport using DataFrames
import Base: +

export
    ggplot,
    geom_point,
    geom_smooth

# -------------------------------------------------------------------------
# geoms

abstract Geom

const _point_keys = KW(:color => :marker_z)
immutable Point <: Geom
    kw::KW
end
function Point(; kw...)
    g = Point(KW(:seriestype => :scatter))
    for (k,v) in kw
        g.kw[get(_point_keys, k, k)] = v
    end
    g
end
const geom_point = Point

const _smooth_keys = KW(:method => :smooth)
const _smooth_vals = KW(:lm => true)
immutable Smooth <: Geom
    kw::KW
end
function Smooth(; kw...)
    g = Smooth(KW())
    for (k,v) in kw
        g.kw[get(_smooth_keys, k, k)] = get(_smooth_vals, v, v)
    end
    g
end
const geom_smooth = Smooth

# -------------------------------------------------------------------------
# ggplot

immutable GGPlot
    df::AbstractDataFrame
    args::Tuple
    kw::KW
end
function ggplot(df::AbstractDataFrame, args...; kw...)
    GGPlot(df, args, KW(kw))
end

function +(gg::GGPlot, geom::Geom)
    merge!(gg.kw, geom.kw)
    gg
end

StatPlots.plot(gg::GGPlot) = plot(gg.df, gg.args...; gg.kw...)
Base.display(gg::GGPlot) = display(plot(gg))

end # module


function reindex(trian::Triangulation,indices)
  TriangulationPortion(trian,collect(Int,indices))
end

function reindex(trian::Triangulation,indices::Vector{Int})
  TriangulationPortion(trian,indices)
end

function reindex(trian::Triangulation,indices::IdentityVector)
  trian
end

"""
"""
struct TriangulationPortion{Dc,Dp,G} <: Triangulation{Dc,Dp}
  oldtrian::G
  cell_to_oldcell::Vector{Int}
  @doc """
  """
  function TriangulationPortion(oldtrian::Triangulation{Dc,Dp},cell_to_oldcell::Vector{Int}) where {Dc,Dp}
    new{Dc,Dp,typeof(oldtrian)}(oldtrian,cell_to_oldcell)
  end
end

function get_reffes(trian::TriangulationPortion)
  get_reffes(trian.oldtrian)
end

function get_cell_type(trian::TriangulationPortion)
  reindex(get_cell_type(trian.oldtrian),trian.cell_to_oldcell)
end

function get_cell_coordinates(trian::TriangulationPortion)
  reindex(get_cell_coordinates(trian.oldtrian),trian.cell_to_oldcell)
end

function get_cell_map(trian::TriangulationPortion)
  cell_map = get_cell_map(trian.oldtrian)
  reindex(cell_map,trian.cell_to_oldcell)
end

function get_cell_id(trian::TriangulationPortion)
  reindex(get_cell_id(trian.oldtrian),trian.cell_to_oldcell)
end

function restrict(f::AbstractArray,trian::TriangulationPortion)
  reindex(restrict(f,trian.oldtrian),trian.cell_to_oldcell)
end

function get_normal_vector(trian::TriangulationPortion)
  reindex(get_normal_vector(trian.oldtrian),trian.cell_to_oldcell)
end


import Base: convert, promote_rule, strip
export MPointE, TVectorE
export getValue, getBasePoint, checkBasePoint
export addNoise, distance, dot, exp, getValue, log, norm
export manifoldDimension, parallelTransport
export randomMPoint, randomTVector
export tangentONB, typicalDistance, zeroTVector
export validateMPoint, validateTVector
export convert, promote_rule, strip
#
#
#
# The extended types for more information/security on base points of tangent vectors
# ---
@doc doc"""
    MPointE <: MPoint

A decorator pattern based extension of MPoint to identify when to switch
to the extended `TVectorE` for functions just working on points, e.g. `log`.
The constructor avoids multiple encapsualtions of extensions.

# Constructors
    MPointE(x [,v=true])

the point can constructed by extending an existing [`MPoint`](@ref).
optionally, the `validation` can be turned off (but is `true`by default).
If `x` is a [`MPointE`](@ref) the default of `v` is taken from `x`.
"""
struct MPointE{P <: MPoint} <: MPoint
  base::P
  validate::Bool
  MPointE{P}(b,v=true) where {P <: MPoint} = new(b,v)
end
MPointE(x::P,v::Bool=true) where {P <: MPoint} = MPointE{P}(x,v)
MPointE(x::MPointE{P},v::Bool=x.validate) where {P <: MPoint} = MPointE{P}(strip(x),v)

@doc doc"""
    TVectorE <: MPoint

A decorator pattern based extension of TVector to additionally store the base
point. The decorator is then used to verify, that exp and dot are only called
with correct base points.

# Constructors
    TVectorE(ξ,x [,v=true])

constructs an extended tangential vector based on the [`TVector`](@ref) `ξ`
with base [`MPoint`](@ref) `x` with optional `validation v`. If none of the
first two arguments is an extended element, `v` defaults to `true`, otherwise,
the one which is an extended is inherited or the `&&` of both validations.
"""
struct TVectorE{T <: TVector, P <: MPoint} <: TVector
  vector::T
  base::P
  validate::Bool
  TVectorE{T,P}(vec,base,val=true) where {T <: TVector, P <: MPoint} = new(vec,base,val)
end
TVectorE(ξ::T, x::P,v::Bool=true) where {T <: TVector, P <: MPoint} = TVectorE{T,P}(ξ,x,v)
TVectorE(ξ::T, x::P,v::Bool=x.validate) where {T <: TVector, P <: MPointE} = TVectorE(ξ,strip(x),v)
TVectorE(ξ::T, x::P,v::Bool=ξ.validate) where {T <: TVectorE, P <: MPoint} = checkBasePoint(ξ,x) ? TVectorE(strip(ξ),getBasePoint(ξ),v) : 0
TVectorE(ξ::T, x::P,v::Bool=x.validate && ξ.validate ) where {T <: TVectorE, P <: MPointE} = checkBasePoint(ξ,x) ? TVectorE(strip(ξ),getBasePoint(ξ),v) : 0
#
getValue(ξ::T) where {T <: TVectorE}= getValue(strip(ξ))
"""
    getBasePoint(ξ)

returns the base point of an extended tangent vector. To continue promotion of
the extended type, the result is always a [`MPointE`](@ref). To eliminate the
decorator, use [`strip`](@ref).
"""
getBasePoint(ξ::T) where {T <: TVectorE{Tl,Pl} where {Tl <: TVector, Pl <: MPoint }} = MPointE(strip(ξ.base))
"""
    strip(ξ)

returns the internal [`TVector`](@ref) of an extended tangent vector
[`TVectorE`](@ref).
"""
strip(ξ::T) where {T <: TVector} = ξ
strip(ξ::T) where {T <: TVectorE} = ξ.vector
#
# Add promotions and implicit conversions
promote_rule(::Type{MPointE{P}}, ::Type{P}) where {P <: MPoint} = MPointE{P}
convert(::Type{MPointE{P}}, x::P) where {P <: MPoint} = MPointE(x)
convert(::Type{MPointE{Q}}, x::P) where {P <: MPoint,  Q <: MPoint} = throw( ErrorException("Cannot `convert` an $(P) to MPointE{$(Q)} since the base type is not of type $(P)."))
convert(::Type{MPointE{P}}, x::MPointE{P}) where {P <: MPoint} = x
convert(::Type{P}, x::MPointE{P}) where {P <: MPoint} = strip(x)
convert(::Type{P}, x::MPointE{Q}) where {P <: MPoint, Q <: MPoint} = throw( ErrorException( "Cannot `convert` an MPointE{$(Q)} to $(P) since the base type is not of type $(P)."))
convert(::Type{P}, x::P) where {P <: MPoint} = x
#
convert(::Type{TVectorE{T,P}}, ξ::T) where {P <: MPoint, T <: TVector} =throw( ErrorException("Cannot `convert` an $(T) to TVectorE{$(T)}; no base MPoint known."))
convert(::Type{T}, ξ::TVectorE{T,P}) where {P <: MPoint, T <: TVector} = ξ.vector
convert(::Type{T}, ξ::TVectorE{S,P}) where {P <: MPoint, T <: TVector, S <: TVector} = throw( ErrorException("Cannot `convert` from TVectorE{$S,$P} to a $T since the TVector types don't match."))
convert(::Type{TVectorE{T,P}}, ξ::TVectorE{T,P}) where {P <: MPoint, T <: TVector} = ξ
convert(::Type{T}, ξ::T) where {T <: TVector} = ξ

getValue(x::P) where {P <: MPointE} = getValue( strip(x) );
show(io::IO, x::MPointE) = print(io, "$(strip(x))E")
"""
    strip(x)

returns the [`MPoint`](@ref) the [`MPointE`](@ref) `x` stores internally.
If applied to an already non-extended [`MPoint`](@ref), nothing happens.
"""
strip(x::P) where {P <: MPointE} = x.base
strip(x::P) where {P <: MPoint} = x

show(io::IO, ξ::TVectorE) = print(io, "$(ξ.vector)E_$(ξ.base)")
function +(ξ::T,ν::T) where {T <: TVectorE}
  checkBasePoint(ξ,ν)
  return T(strip(ξ)+ν.vector,getBasePoint(ξ))
end
function -(ξ::T,ν::T) where {T <: TVectorE}
  checkBasePoint(ξ,ν)
  return T(strip(ξ)-ν.vector,getBasePoint(ξ))
end
"""
    checkBasePoint(ξ,ν)

checks, whether the base of two tangent vectors is identical, if both tangent
vectors are of type `TVectorE`. If one of them is not an extended vector, the
function returns true, expecting the tangent vector implicitly to be correct.
"""
function checkBasePoint(ξ::T,ν::T) where {T <: TVectorE}
  if getValue( getBasePoint(ξ) ) != getValue( getBasePoint(ν) )
    throw(
    DomainError("The two tangent vectors $ξ and $ν do not have the same base.")
    )
  else
    return true
  end
end
checkBasePoint(ξ::T,ν::S) where {T <: TVectorE, S <: TVector} = true
checkBasePoint(ξ::S,ν::T) where {T <: TVectorE, S <: TVector} = true
"""
    checkBasePoint(ξ,x)

checks, whether the base of the tangent vector `ξ` is `x`. If `ξ` is not an
extended tangent vector `TVectorE` the function returns true, assuming the base
implicitly to be correct
"""
function checkBasePoint(ξ::T,x::P) where {T <: TVectorE, P <: MPoint}
  if getValue( getBasePoint(ξ) ) != getValue(x)
    throw(
    DomainError("The tangent vector $ξ is not from the tangent space of $x")
    )
  else
    return true
  end
end
checkBasePoint(ξ::T,x::P) where {T<: TVector, P<: MPoint} = true
#
# Defaults for validation that do warnings if used but return true
#
# unary operators
*(ξ::T,s::Number) where {T <: TVectorE} = T(s*strip(ξ),getBasePoint(ξ))
*(s::Number, ξ::T) where {T <: TVectorE} = T(s*strip(ξ),getBasePoint(ξ))
/(ξ::T,s::Number) where {T <: TVectorE} = T(strip(ξ)/s,getBasePoint(ξ))
-(ξ::T) where {T <: TVectorE} = T(-strip(ξ),getBasePoint(ξ))
+(ξ::T) where {T <: TVectorE} = T(strip(ξ),getBasePoint(ξ))
# compare extended vectors
==(ξ::T,ν::T) where {T <: TVectorE} = ( checkBasePoint(ξ,ν) && all(strip(ξ)==ν.vector) )
#
# encapsulate default functions
#
distance(M::mT, x::P, y::P) where {mT <: Manifold, P <: MPointE} = _distance(M,strip(x),strip(y), x.validate&&y.validate)
distance(M::mT, x::P, y::Q) where {mT <: Manifold, P <: MPointE, Q <: MPoint} = _distance(M,strip(x),strip(y), x.validate)
distance(M::mT, x::P, y::Q) where {mT <: Manifold, P <: MPoint, Q <: MPointE} = _distance(M,strip(x),strip(y), y.validate)
function _distance(M,x,y,v)
  if v
    validateMPoint(M,x)
    validateMPoint(M,y)
  end
  return distance(M,x,y)
end

function dot(M::mT, x::P, ξ::T, ν::T)::Float64 where {mT<:Manifold, P <: MPointE, T<:TVectorE}
  checkBasePoint(ξ,x)
  checkBasePoint(ξ,ν)
  return _dot(M, strip(x), strip(ξ), strip(ν), x.validate && ξ.validate && ν.validate )
end
function dot(M::mT, x::P, ξ::T, ν::S) where {mT <: Manifold, P <: MPointE, T <: TVectorE, S <: TVector}
  checkBasePoint(ξ,x)
  return _dot(M, strip(x),strip(ξ),ν, x.validate && ξ.validate)
end
function dot(M::mT, x::P, ξ::S, ν::T) where {mT <: Manifold, P <: MPointE, T <: TVectorE, S <: TVector}
  checkBasePoint(ν,x)
  return _dot(M, strip(x), ξ, strip(ν), x.validate && ν.validate )
end
dot(M::mT, x::P, ξ::T, ν::T) where {mT <: Manifold, P <: MPointE, T <: TVector} = _dot(M,strip(x),ξ,ν, x.validate)

function dot(M::mT, x::P, ξ::T, ν::T) where {mT <: Manifold, P <: MPoint, T <: TVectorE}
  checkBasePoint(ξ,ν)
  return _dot(M,x,strip(ξ),strip(ν), ξ.validate && ν.validate )
end
function dot(M::mT, x::P, ξ::S, ν::T) where {mT <: Manifold, P <: MPoint, T <: TVectorE, S <: TVector}
  checkBasePoint(ν,x)
  return _dot(M,x,ξ,strip(ν), ν.validate )
end
function dot(M::mT, x::P, ξ::T, ν::S) where {mT <: Manifold, P <: MPoint, T <: TVectorE, S <: TVector}
  checkBasePoint(ξ,x)
  return _dot(M,x,strip(ξ),ν, ξ.validate )
end
function _dot(M,x,ξ,ν,v)
  if v
    validateMPoint(M,x)
    validateTVector(M,x,ξ)
    validateTVector(M,x,ν)
  end
  return dot(M,x,ξ,ν)
end

function exp(M::mT,x::P,ξ::T,t::Float64=1.0) where {mT<:Manifold, P<:MPointE, T<:TVectorE}
  checkBasePoint(ξ,x)
  return _exp(M, strip(x), t*strip(ξ), x.validate && ξ.validate )
end
exp(M::mT,x::P,ξ::T,t::Float64=1.0) where {mT<:Manifold, P<:MPointE, T<:TVector} = _exp(M,strip(x), t*ξ
, x.validate )
function exp(M::mT,x::P,ξ::T,t::Float64=1.0) where {mT<:Manifold, P<:MPoint, T<:TVectorE}
  checkBasePoint(ξ,x)
  return _exp(M, x, t*strip(ξ), ξ.validate )
end
function _exp(M,x,ξ,v)
  if v
    validateMPoint(M,x)
    validateTVector(M,x,ξ)
  end
  y = exp(M,x,ξ)
  if v
    validateMPoint(M,y)
  end
  return MPointE(y, v)
end

log(M::mT,x::Q,y::Q) where {mT<:Manifold, Q<:MPointE} = _log(M,strip(x),strip(y), x.validate && y.validate )
log(M::mT,x::P,y::Q) where {mT<:Manifold, P<:MPoint, Q<:MPointE} = _log(M, x, strip(y), y.validate )
log(M::mT,x::Q,y::P) where {mT<:Manifold, P<:MPoint, Q<:MPointE} = _log(M, strip(x), y, x.validate )
function _log(M,x,y,v)
  if v
    validateMPoint(M,x)
    validateMPoint(M,y)
  end
  ν = log(M,x,y)
  if v
    validateTVector(M,x,ν)
  end
  return TVectorE(ν,x, v)
end

manifoldDimension(x::P) where {P <: MPointE} = manifoldDimension(strip(x))

function norm(M::mT, x::P, ξ::T)::Float64 where {mT<:Manifold, P <: MPointE, T<:TVectorE}
  checkBasePoint(ξ,x)
  return _norm(M,strip(x),strip(ξ), x.validate && ξ.validate )
end
norm(M::mT,x::P,ξ::T) where {mT<:Manifold, P <: MPointE, T<:TVector} = _norm(M,strip(x),ξ, x.validate)
function norm(M::mT,x::P,ξ::T) where {mT<:Manifold, P <: MPoint, T<:TVectorE}
  checkBasePoint(ξ,x)
  return _norm(M,x,strip(ξ), ξ.validate)
end
function _norm(M,x,ξ,v)
  if v
    validateMPoint(M,x)
    validateTVector(M,x,ξ)
  end
  norm(M,x,ξ)
end

function parallelTransport(M::mT,x::P,y::Q,ξ::T) where {mT <: Manifold, P <: MPointE, Q <: MPoint, T<: TVectorE}
  checkBasePoint(ξ,x)
  return _parallelTransport(M,strip(x),y,strip(ξ), x.validate && ξ.validate)
end
function parallelTransport(M::mT,x::P,y::P,ξ::T) where {mT <: Manifold, P <: MPointE, T<: TVectorE}
  checkBasePoint(ξ,x)
  return _parallelTransport(M,strip(x),strip(y),strip(ξ), x.validate && y.validate && ξ.validate)
end
function parallelTransport(M::mT,x::P,y::Q,ξ::T) where {mT <: Manifold, P <: MPoint, Q <: MPointE, T<: TVectorE}
  checkBasePoint(ξ,x)
  _parallelTransport( M, x, strip(y), strip(ξ), y.validate && ξ.validate )
end
parallelTransport(M::mT,x::P,y::P,ξ::T) where {mT <: Manifold, P <: MPointE, T<: TVector} = _parallelTransport(M, strip(x), strip(y), ξ, x.validate && y.validate )
function parallelTransport(M::mT,x::P,y::Q,ξ::T) where {mT <: Manifold, P <: MPoint, Q <: MPointE, T<: TVector}
  checkBasePoint(ξ,x)
  return _parallelTransport(M,x,strip(y),ξ, y.validate )
end
parallelTransport(M::mT,x::P,y::Q,ξ::T) where {mT <: Manifold, P <: MPointE, Q <: MPoint, T<: TVector} = _parallelTransport(M,strip(x),y,ξ, x.validate )
function _parallelTransport(M,x,y,ξ,v)
  if v
    validateMPoint(M,x)
    validateMPoint(M,y)
    validateTVector(M,x,ξ)
  end
  ν = parallelTransport(M,x,y,ξ)
  if v
    validateTVector(M,y,ν)
  end
  return TVectorE(ν,y,v)
end

function randomTVector(M::mT, x::P,options...) where {mT <: Manifold, P <: MPointE}
  ξ = randomTVector(M,strip(x),options...)
  if x.validate
    validateTVector(M,strip(x),ξ)
  end
  return TVectorE(ξ,x,x.validate)
end

tangentONB(M::mT, x::P, y::Q) where {mT <: Manifold, P <: MPointE, Q <: MPoint} = _tangentONB(M, strip(x), y, x.validate )
tangentONB(M::mT, x::Q, y::P) where {mT <: Manifold, P <: MPointE, Q <: MPoint} = _tangentONB(M, x, strip(y), y.validate )
tangentONB(M::mT, x::P, y::P) where {mT <: Manifold, P <: MPointE} = _tangentONB(M, strip(x), strip(y), x.validate && y.validate )

function _tangentONB(M,x::MPoint,y::MPoint, v::Bool)
  if v
    validateMPoint(M,x)
    validateMPoint(M,y)
  end
  V,κ = tangentONB(M,x,log(M,x,y))
  if v
    validateTVector.(Ref(M), Ref(x), V)
  end
  return TVectorE.(V, Ref(x), Ref(v)), κ
end
tangentONB(M::mT, x::P, ξ::T) where {mT <: Manifold, P <: MPointE, T <: TVectorE} = _tangentONB(M, strip(x), strip(ξ), x.validate && ξ.validate )
tangentONB(M::mT, x::P, ξ::T) where {mT <: Manifold, P <: MPoint, T <: TVectorE} = _tangentONB(M, x, strip(ξ), ξ.validate )
tangentONB(M::mT, x::P, ξ::T) where {mT <: Manifold, P <: MPointE, T <: TVector} = _tangentONB(M, strip(x), ξ, x.validate )
function _tangentONB(M, x::MPoint, ξ::TVector, v::Bool)
  if v
    validateMPoint(M,x)
    validateTVector(M,x,ξ)
  end
  V,κ = tangentONB(M,x,ξ)
  if v
    validateTVector.(Ref(M), Ref(x), V)
  end
  return TVectorE.(V, Ref(x), Ref(v)), κ
end

validateMPoint(M::mT,x::P) where {mT <: Manifold, P <: MPointE} = validateMPoint(M,strip(x))
validateTVector(M::mT,x::P,ξ::T) where {mT <: Manifold, P <: MPointE, T <: TVectorE} = validateTVector(M, strip(x), strip(ξ))
validateTVector(M::mT,x::P,ξ::T) where {mT <: Manifold, P <: MPoint, T <: TVectorE} = validateTVector(M, x, strip(ξ))
validateTVector(M::mT,x::P,ξ::T) where {mT <: Manifold, P <: MPointE, T <: TVector} = validateTVector(M, strip(x), ξ)
function zeroTVector(M::mT,x::P) where {mT <: Manifold, P <: MPointE}
  if x.validate
    validateMPoint(M,x)
  end
  return TVectorE( zeroTVector(M,strip(x)), strip(x), x.validate )
end


function result_dataframe(variable::JuMP.Containers.DenseAxisArray)

    result = Array{Float64,length(variable.axes)}(undef, length(variable.axes[2]), length(variable.axes[1]))
    # TODO: Remove this line once PowerSystems moves to Symbols
    names = Array{Symbol,1}(undef,length(variable.axes[1]))

    for t in variable.axes[2], (ix,name) in enumerate(variable.axes[1])

        result[t,ix] = JuMP.value(variable[name,t])

        names[ix] = Symbol(name)

    end

    return DataFrames.DataFrame(result, names)

end

function get_model_result(ps_m::PSI.CanonicalModel; kwargs...)

    results_df = Dict{Symbol, DataFrames.DataFrame}()

    for (k,v) in ps_m.variables

        results_df[k] = result_dataframe(v)

    end

    return results_df

end

function optimizer_log(ps_m::PSI.CanonicalModel; kwargs...)

    optimizer_log = Dict{Symbol,Any}()

    # TODO: Not all solvers can access the SolveTime() property
    #optimizer_log[:solve_time] = MOI.get(ps_m.JuMPmodel, MOI.SolveTime())
    optimizer_log[:termination_status] = JuMP.termination_status(ps_m.JuMPmodel)
    optimizer_log[:primal_status] = JuMP.primal_status(ps_m.JuMPmodel)
    optimizer_log[:dual_status] = JuMP.dual_status(ps_m.JuMPmodel)

    return optimizer_log

end


module Pattern

# -----------------------------------------------------------------------------

abstract Pattern

type PVar <: Pattern
    name::Symbol
end

type TypeAssert <: Pattern
    T
end

type Product <: Pattern
    factors::Vector{Pattern}
end

type TuplePat <: Pattern
    ps::Vector{Pattern}
end

# -----------------------------------------------------------------------------

abstract Node

# asserts that all args are egal
type EgalNode <: Node
    args::Vector{Node}
end

# asserts that valueof(v) is of type valueof(T)
type IsaNode <: Node
    v::Node
    T::Node
end

# asserts that valueof(t) is a tuple(ps...)
type TupleNode <: Node
    t::Node
    ps::Vector{Node}
end

type Atom <: Node
    value
end

type Var <: Node
    name::Symbol
end

# -----------------------------------------------------------------------------

abstract Value

type Atom{T} <: Value
    value::T
end
type Var <: Value
    name::Symbol
end

abstract Guard

# asserts that all args are egal
type Egal <: Guard
    args::Vector{Value}
end

# asserts that valueof(v)::valueof(T)
type Isa <: Guard
    v::Value
    T::Value
end

# asserts that valueof(t) is a tuple(ps...)
type TupleGuard <: Guard
    t::Value
    ps::Vector{Value}
end

end # module


using Compat

"""
    RomanNumeral(::Integer)
    RomanNumeral(::AbstractString)

Roman number: it contains both the standard number and its roman representation.
It behaves like standard numbers.
"""
@compat struct RomanNumeral <: Integer
    val::Int
    str::String
    RomanNumeral(int::Integer) = new(int, toroman(int))
    function RomanNumeral(str::AbstractString)
        num = parse(RomanNumeral, str)
        new(num, toroman(num))
    end
end

"""rn"MMXV" syntactic sugar"""
macro rn_str(str)
    RomanNumeral(str)
end

const RN = RomanNumeral

# Standard functions
# Conversion + promotion
Base.convert(::Type{Bool}, ::RN) = true
Base.convert(::Type{T}, x::RN) where {T<:Real} = T(x.val)

Base.promote_rule(::Type{RN}, ::Type{T}) where {T <: Integer} = T

# IO
Base.show(io::IO, num::RN) = write(io, num.str)
Base.length(num::RN) = length(num.str)
Base.hash(num::RN) = @compat xor(hash(num.str), hash(num.val))


# License for this file: MIT (expat)
# Copyright 2017-2021, DLR Institute of System Dynamics and Control
# Author: Martin Otter, DLR-SR

#=
This file contains functions to transform the ODAE generated by the Pantelides
algorithm to an ODE, if this is reasonably possible
(e.g. without solving nonlinear equation systems inside the model or introducing stabilizing terms.
The approach is based on the dummy derivative method from
[Mattsson and Söderlind (1992](https://ieeexplore.ieee.org/document/274429),
the transformation algorithm from
[Otter and Elmqvist (2017)](https://modelica.org/events/modelica2017/proceedings/html/submissions/ecp17132565_OtterElmqvist.pdf),
and on some new ideas that are not yet published.

# Functions exported by this module:

- [`getSortedAndSolvedAST`](@ref): Given the BLT
  (after Pantelides algorithm),
  this function returns the Abstract Syntax Tree (AST) of
  the sorted and solved equations and selects the ODE states.
=#

export getSortedAndSolvedAST
export StateSelectionFunctions
export showCodeWithoutComments

#using OrderedCollections
using  ModiaBase
using  ModiaBase.BLTandPantelides
import ModiaBase: revertAssociation
using  StaticArrays

const INFORMATION = 0
const WARNING     = 1
const ERROR       = 2

"""
    stateSelectionFunctions = StateSelection.StateSelectionFunctions(;
        var_name               = v          -> nothing,
        var_julia_name         = v          -> nothing,
        var_unit               = v          -> "",
        var_startInitFixed     = v          -> (nothing,false),   # (startOrInit, fixed)
        var_is_state           = v_original -> false,
        equation               = e          -> ""
        isSolvableEquation     = (e_original,v_original) -> false,
        isLinearEquation       = (e_original,v_original) -> (false, false),
        getSolvedEquationAST   = (e, v)                  -> nothing,
        getResidualEquationAST = (e, residualName)       -> nothing,
        showMessage            = (message; severity=0,from="???",details="",variables=Int[],equations=Int[]) -> println("...")
    )

Generate an instance of an immutable struct that holds the callback functions
as needed by [`getSortedAndSolvedAST`](@ref).

The functions need to have the following arguments:

- `var_name(v::Int)::String`:\\
   Return full (Modia) path name of `v` as String (e.g. `"a.b.c"` or `"a.b.der(c)"`).

- `var_julia_name(v::Int)::String`:\\
  Return full Julia path name of variable `v` as `Symbol`
  (e.g. Symbol("m.a.b.c") or Symbol("a_b_der_c")).

- `var_unit(v::Int)::String`:\\
  Return unit of variable `v` as `String` (for example "N*m") or `""`, if no unit is defined.

- `var_startInitFixed(v::Int)::Tuple(Any,Bool)`:\\
  Return `(startOrInit, fixed)`, where `startOrInit` is the `start` or `init` value or `nothing`
  (if neither `start` nor `init` defined) and `fixed` is `true`, if an `init` value is defined.

-  `var_is_state(v_original::Int)::Bool`:\\
   Return true, if variable `v_original` is defined to be a state.

- `equation(e::Int)`:\\
   Return equation as string or "", if equation is not provided.

- `isSolvableEquation(e_original::Int, v_original::Int)::Bool`:\\
   Return `true` if original, undifferentiated equation `e_original`
   can be uniquely solved for variable `v_original`.

- `(isLinear, hasConstantCoefficient) = isLinearEquation(e_original::Int, v_original::Int)`:\\
   Return the information whether the original, undifferentiated equation `e`
   is **linear** with respect to variable `v` (`isLinear=true`) and if this is the case whether
   the coefficient of this linear term is **constant** after initialization
   (`hasConstantCoefficient=true`). If `v` is an array, then the array equation `e` must
   be linear with respect to all elements of array `v` in order to return `isLinear=true`.

- `AST = getSolvedEquationAST(e:Int, v:Int)`:\\
  Return Abstract Syntax Tree `AST::Expr` of equation `e` solved for variable `v`
  as instance of `Expr`.

- `AST = getResidualEquationAST(e::Int, residualName::Symbol)`:\\
  Return Abstract Syntax Tree `AST::Expr` of eqation `e` as residual equation with ustrip(..) \\
  `residualName = ustrip( < residual form of equation e> )`

- `showMessage(message; severity=0,from="???",details="",variables=Int[],equations=Int[])`:\\
  Print information, warning or error message.
"""
struct StateSelectionFunctions
    var_name::Function
    var_julia_name::Function
    var_unit::Function
    var_startInitFixed::Function
    var_nominal::Function
    var_unbounded::Function
    var_is_state::Function
    equation::Function
    isSolvableEquation::Function
    isLinearEquation::Function
    getSolvedEquationAST::Function
    getResidualEquationAST::Function
    showMessage::Function

    StateSelectionFunctions(;
        var_name               = v          -> nothing,
        var_julia_name         = v          -> nothing,
        var_unit               = v          -> "",
        var_startInitFixed     = v          -> (nothing,false),   # (startOrInit, fixed)
        var_nominal            = v_original -> NaN,
        var_unbounded          = v_original -> false,
        var_is_state           = v_original -> false,
        equation               = e          -> "",
        isSolvableEquation     = (e_original,v_original) -> false,
        isLinearEquation       = (e_original,v_original) -> (false, false),
        getSolvedEquationAST   = (e, v)                  -> nothing,
        getResidualEquationAST = (e, residualName)       -> nothing,
        showMessage            = (message; severity=0,from="???",details="",variables=Int[],equations=Int[]) ->
                                       println("\n!!! Message from $from with severity=$severity:\n$message,\ndetails\nvariables=$variables,\nequations=$equations")
    ) = new(var_name,
            var_julia_name,
            var_unit,
            var_startInitFixed,
            var_nominal,
            var_unbounded,
            var_is_state,
            equation,
            isSolvableEquation,
            isLinearEquation,
            getSolvedEquationAST,
            getResidualEquationAST,
            showMessage)
end

function printVector(vec)
    for v in vec
        println("    ", v)
    end
end

"""
    showMessage(message, severity, from, details, variables, equations)

Print message.

# Arguments:

- `severity::Int`: Severity of message: 0=Information, 1=warning, 2=Error
- `from::String`: Name of function that throws error message
- `message::String`: One line description of issue
- `details::String`: Detailed description of issue
- `variables::Vector{String}`: List of involved variables
- `equations::Vector{String}`: List of involved equations
"""
function showMessage(message::String, severity::Int, from::String, details::String,
                     variables::AbstractVector, equations::AbstractVector)::Nothing
    if severity == 0
        println("\nInformation message from $(from):")
    elseif severity == 1
        println("\nWarning message from $(from):")
    else
        println("\nError message from $(from):")
    end
    println(message)
    if length(details) > 0
        println(details)
    end
    if length(variables) > 0
        println("Involved variables:")
        printVector(variables)
    end
    if length(equations) > 0
        println("Involved equations:"),
        printVector(equations)
    end
	println("")
    return nothing
end

showCodeWithoutComments(code) = println("code = ", replace(sprint(show,code), r"( *#= .*=#\n)|(#= .*=#)" => "") )

"""
    (eConstraints,vConstraints) = getConstraintSets(BLT_i, assignRev, Arev, Brev,
                                       var_is_state, showMessage)

Determines the set of equations/constraints and their unknowns that are associated with
the highest derivative level BLT block i (BLT_i), according to the dummy derivative
method of [Mattsson and Söderlind (1992](https://ieeexplore.ieee.org/document/274429),
(note, eConstraints[j] and vConstraints[j] are of type Vector{Int}):

- eConstraints[end] = BLT_i, so the equations of BLT block i (must be highest derivative equations)
- eConstraints[j]: Constraint equations that form the integral of eConstraints[j+1].
- eConstraints[1]: Lowest order constraint equations. All equations in eConstraints[1]
                   are original, non-differentiated equations.

vConstraints[j] are the unknowns of eConstraints[j].

# Arguments:

- `BLT_i::Vector{Int}`: Vector of equation indices of BLT block i.

- `assignRev::Vector{Int}`: Reverted assign vector: vi = assignRev[ei] is variable vi assigned to equation ei

- `Arev::Vector{Int}`: Reverted variable association: `Arev[i] = der(V[k]) == V[i] ? k : 0`.

- `Brev::Vector{Int}`: Reverted equation association: `Erev[i] = der(E[k]) == E[i] ? k : 0`.

- `var_is_state::Function`: var_is_state(`vi`) returns true, if `vi` is defined to be a definite state.

- showMessage: showMessage2 below to print error/warning message

"""
function getConstraintSets(BLT_i::Vector{Int},
                           assignRev::Vector{Int},
                           Arev::Vector{Int},
                           Brev::Vector{Int},
                           var_is_state::Function,
                           showMessage::Function)
    # Determine unknowns of BLT block i
    BLT_i_unknowns = fill(0, length(BLT_i))
    for j in eachindex(BLT_i)
        BLT_i_unknowns[j] = assignRev[BLT_i[j]]
    end

    # Initialize constraint sets
    eConstraints = [BLT_i]
    vConstraints = [BLT_i_unknowns]

    # Check that number of equations and number of unknowns agree
    if length(BLT_i) != length(BLT_i_unknowns)
        showMessage("Number of equations and number of unknowns do not agree for BLT block";
                    severity  = ERROR,
                    variables = BLT_i_unknowns,
                    equations = BLT_i)
        return (eConstraints, vConstraints, false)
    end

    while true
        # Determine constraints at one differentiation order less
        ceq = fill(0, 0)
        for eq in eConstraints[1]
            if Brev[eq] > 0
                push!(ceq, Brev[eq])
            end
        end
        if length(ceq) == 0; break; end

        pushfirst!(eConstraints, ceq)   # move ceq to the beginning of the constraints vector

        # Determine unknowns of ceq
        veq        = fill(0,0)
        veq_states = fill(0,0)
        for vc in vConstraints[1]
            if Arev[vc] > 0
                if var_is_state( Arev[vc] )
                    push!(veq_states, Arev[vc])
                else
                    push!(veq, Arev[vc])
                end
            end
        end
        if length(veq) < length(ceq)
            nRemoveStates = length(veq_states) - (length(ceq) - length(veq))
            showMessage("$nRemoveStates of the followig defined states cannot be states!";
                severity  = ERROR,
                variables = veq_states,
                equations = ceq)
            return (eConstraints, vConstraints, false)
        end
        pushfirst!(vConstraints, veq)   # move veq to the beginning of the constraints vector
    end

    @assert(length(eConstraints) == length(vConstraints))
    return (eConstraints, vConstraints, true)
end

"""
    names = getNames(var_name::Function, v::Vector{Int})
    names = getNames(eq::EquationGraph , v::Vector{Int})

Get names of variables `v` as a string.
"""
function getNames(var_name::Function, v)::String
    if length(v) > 0
        str = var_name(v[1])
        for i in 2:length(v)
            str = str * ", " * var_name(v[i])
        end
        return str
    else
        return ""
    end
end
getNames(eq, v) = getNames(eq.fc.var_name, v)

function printVariables(eq, v; indent=4)
    for vi in v
        println(lpad(vi,indent), ": ", eq.fc.var_name(vi))
    end
    return nothing
end

"""
    printEquations(equation::Function, e::Vector{Int}; indent=4)
    printEquations(eq::EquationGraph, e::Vector{Int}; indent=4)
    printEquations(eq::EquationGraph, expr; indent=4)

Print equations `e` as a string or as vector of equations.
"""
function printEquations(equation::Function, e::Vector{Int}; indent=4)::Nothing
    for ei in e
        println(lpad(ei,indent), ": ", equation(ei))
    end
    return nothing
end
printEquations(eq, e; indent=4) = printEquations(eq.fc.equation, e; indent=indent)

function printEquations(expr::Expr; indent=4)
    indentation = repeat(" ",indent)
    str = string(expr)
    str = replace(str, r".*#= .*\n" => "")
    println(indentation, str)
end

#=

"""
    Arev = revertAssociation(A::Vector{Int})

Revert the association Vector `A[i] = j`, such that
`Arev[j] = i` (`A[i]=0` is allowed and is ignored).
"""
function revertAssociation(A::Vector{Int})::Vector{Int}
    nArev = max(maximum(A), length(A))
    Arev  = fill(0, nArev)
    for i in eachindex(A)
        if A[i] != 0
            Arev[ A[i] ] = i
        end
    end
    return Arev
end
=#

"""
    tearedEquations = TearedEquations(..)

Return an immutable struct that contains the information about a teared system of equations.
"""
struct TearedEquations
    isLinear::Bool                 # = true if equation system is linear
    hasConstantCoefficients::Bool  # = true if linear equation system has a constant coefficient matrix A
    vSolved::Vector{Int}           # Variables that are explicitly solved by tearing
    vTear::Vector{Int}             # Iteration variables of tearing
    eSolved::Vector{Int}           # Equations that are explicitly solved by tearing
    eResiduals::Vector{Int}        # Residual equations of the teared equations
    AST::Expr                      # AST of equation system
end

"""
    eq = EquationGraph(G, BLT, assign, A, B, log, showMessage::Function)

Construct the representation of the equation graph as needed by state selection.

# Arguments

- `G`: G[i] is the Integer vector of variable indices of equation i.
   A variable i can be a scalar or an array.
   G is of type Vector{ Vector{Int} } or Vector{ Any }.

- `BLT::Vector{Vector{Int}}`: BLT[i] is the vector of equations belonging to BLT-block i.
  In principal, **BLT[i] must include only highest derivative equations**.
  In order to ease the generation of BLT[i], to not be forced to map indices forth and back
  when calling the function that computes the BLT, the following assumption is
  made: If BLT[j] contains only **one equation with B[j][1] > 0** then this BLT block is
  a lower-derivative (dummy) block and is ignored.

- `assign::Vector{Int}`: ei = assign[vi] is equation ei assigned to variable vi

- `A`: A-Vector of Pantelides algorithm:
       `A[i] = if der(v[i]) == v[k] then k else 0`
       where `v[i]` is variable `i`.

- `B`: B-Vector of Pantelides algorithm:
       `B[i] = if der(e[i]) == e[k] then k else 0`
       where `e[i]` is equation `i`.

- `log`: = true, if logging is on

- `showMessage`: Function used to print warning/error messages.
"""
mutable struct EquationGraph
    success::Bool                                  # = true, if operation was successful, otherwise false
    log::Bool                                      # = true, if logging is on
    logDetails::Bool                               # = true, if detailled logging is on
    showMessage::Function
    fc::StateSelectionFunctions                    # Callback functions
    G                                              # Structure of equations
    A::Vector{Int}
    B::Vector{Int}
    Gunknowns::Vector{Vector{Int}}
    vOriginal::Vector{Bool}                        # vOriginal[v] = true, if variable v appears in an original (non-differentiated) equation
    vActive::Vector{Bool}                          # vActive[v] = false, if v is a state
    vSolvedWithFixedTrue::Vector{Int}              # Explicitly solved variables with fixed=true

    # Reverted info vectors
    Arev::Vector{Int}                              # Reverted vector A
    Brev::Vector{Int}                              # Reverted vector B
    assignRev::Vector{Int}                         # Reverted vector assign; vi = assignRev[ei] if equation ei is assigned to variable vi

    # Equation/Constraint sets
    eConstraintsVec::Vector{Vector{Vector{Int}}}   # eConstraintsVec[i] is the constraint set of highest derivative BLT block i
    vConstraintsVec::Vector{Vector{Vector{Int}}}   # vConstraintsVec[i] are the assigned variables of eConstraintsVec[i]

    # Tearing
    td::TearingSetup                               # Data structure for equation tearing to traverse a set of equations
                                                   # that are represented as a DAG (Directed Acyclic Graph).
    vSolved::Vector{Int}                           # Variables that are explicitly solved by tearing
    vTear::Vector{Int}                             # Iteration variables of tearing
    eSolved::Vector{Int}                           # Equations that are explicitly solved by tearing
    eResiduals::Vector{Int}                        # Residual equations of the teared equations
    vTearWithoutStart::Vector{Int}                 # Summary of all vTear variables that have no start value (to print warning message at the end)

    der_vSolvedLower::Vector{Int}                  # Initialize tearing with variables that are already explicitly solved
                                                   # (this is known from the constraints one differentiation level less)
    der_vTearLower::Vector{Int}                    # Highest priority variables to solve for
                                                   # (= differentiated tearing variables from one differentiation level less)
                                                   # (this is known from the constraints one differentiation level less)
    der_eSolvedLower::Vector{Int}                  # Initialize tearing with equations that are already explicitly solved
                                                   # (this is known from the constraints one differentiation level less)
    vc::Vector{Int}                                # Variables of the current component that are unknowns of the tearing
    ec::Vector{Int}                                # Equations of the current component that shall be teared
    vcCandidates::Vector{Vector{Int}}              # Try to solve equations ec in the following order for vc:
                                                   # vcCandidates[1], ..., [6]
    vLinActive::Vector{Bool}                       # Utility vector (vLinActive[i]=true, if variable is inspected)
    equationInfo::Modia.EquationInfo               # Info about the structure of the equations
                                                   # (equationInfo.x_names, equationInfo.linearEquations)

    # Sorted equations
    fullAssignRev::Vector{Int}                     # fullAssignRev[e] = v: If e is a scalar equation system, it is solved for v.
                                                   # If v = -1, the scalar equation system is not solved directly, but
                                                   #            as linear equation system (with tearing).
    tearedEquations::Vector{TearedEquations}       # Info about teared equation system
    tearedEquations_indices::Vector{Int}           # teq = tearedEquations_indices[e] is tearedEquations[teq]
    eAST::Vector{Expr}                             # eAST[e] is the AST of equation e
    AST_aux::Vector{Expr}                          # Abstract Syntax Tree of some code (auxiliary vector)
    AST::Vector{Expr}                              # Abstract Syntax Tree of the sorted and solved equations as vector of Expr
                                                   # Statements are evaluted in the order: AST[1], AST[2], ....

    function EquationGraph(G, BLT, assign, A, B, stateSelectionFunctions, log, logDetails, showMessage::Function)

        # Check input arguments
        @assert(length(B) == length(G))

        # Revert association vectors
        Arev      = revertAssociation(A)
        Brev      = revertAssociation(B)
        assignRev = revertAssociation(assign)

        # Initialize vector of variables of the non-differentiated, original equations
        vOriginal = fill(false, length(A))

        # Initialize the active variables
        vActive = fill(true, length(A))
        for v = 1:length(vActive)
            if Arev[v] > 0
                vActive[ Arev[v] ] = false    # Arev[v] is a potential state
            end
        end

        # Define empty constraint sets
        eConstraintsVec = Vector{Vector{Int}}[]
        vConstraintsVec = Vector{Vector{Int}}[]

        # Gunknowns has the same dimension as G.
        # Gunknowns[i] is not empty, if it is an original, non-differentiated
        # equation. In this case it is a subset of G[i] containing only the
        # unknown variables of the corresponding constraint set as needed by tearing.
        # Note, tearing is only applied on non-differentiated equations
        # Tearing information of differentiated equations is
        # deduced from the tearing of the non-differentiated equations.
        Gunknowns = fill(Int[], length(G))

        # Construct constraint sets of the dummy derivative method from the BLT
        success = true
        for (i,BLT_i) in enumerate(BLT)
            # Check that BLT block contains only higher derivative equations
            # (with one exception due to an agreed convention with Modia:
            # If BLT[j] has only one equation and B( BLT[j][1] ) > 0, so it is
            # a lower derivative equation, then this BLT block is ignored).
            highest = true
            for eqj in BLT_i
                if B[eqj] != 0 # One equation of block BLT_i appears also differentiated
                    highest = false
                    if length(BLT_i) > 1
                        success = false
                        showMessage("Equation $eqj in BLT[$i]=$BLT_i is not a highest derivative equation.";
                        details   = "This means that there is an error in argument BLT.",
                        severity  = ERROR,
                        equations = [eqj])
                    end
                    break
                end
            end
            if !success
                break
            end

            if highest
                # Get all equation sets eConstraints and their corresponding unknowns vConstraints
                # from lowest to highest differentiation order (eConstraints[end] is c)
                (eConstraints, vConstraints, success2) = getConstraintSets(BLT_i, assignRev, Arev, Brev,
                                                         stateSelectionFunctions.var_is_state, showMessage)
                if !success2
                    success=false
                    break
                end

                # Initialize vActive
                #for vc in vConstraints
                #    for v in vc
                #        if Arev[v] > 0
                #            vActive[ Arev[v] ] = false    # Arev[v] is a potential state
                #        end
                #    end
                #end

                push!(eConstraintsVec, eConstraints)
                push!(vConstraintsVec, vConstraints)

                # Determine unknown variables of G as used by tearing
                for i in eachindex(eConstraints)
                    for eq in eConstraints[i]
                        # Gunknowns[eq] contains the variables of G[eq] that are unknowns of vConstraints[i]
                        Gunknowns[eq] = intersect(G[eq], vConstraints[i])

                        if Brev[eq] == 0
                            # Original, non-differentiated equation
                            for v in Gunknowns[eq]
                                # v is a variable from the original, non-differentiated equations
                                vOriginal[v] = true
                            end
                        end
                    end
                end
            end
        end

        new(success, log, logDetails, showMessage, stateSelectionFunctions, G, A, B, Gunknowns, vOriginal, vActive,
            Int[], Arev, Brev, assignRev,
            eConstraintsVec, vConstraintsVec,
            TearingSetup(Gunknowns,length(Arev)),
            Int[], Int[], Int[], Int[], Int[], Int[], Int[], Int[], Int[], Int[],
            Vector{Int}[Int[], Int[], Int[], Int[], Int[], Int[]], fill(false, length(Arev)),
            Modia.EquationInfo(status=Modia.CODE_GENERATION),
            fill(0, length(B)), TearedEquations[], fill(0, length(B)),
            Vector{Expr}(undef, length(B)), Expr[], Expr[])
    end
end

function undifferentiated(eq::EquationGraph, v::Int)::Int
    while eq.Arev[v] > 0
        v = eq.Arev[v]
    end
    return v
end

"""
    isLinearOriginalOrDifferentiatedEquation(eq, e, v)
"""
function isLinearOriginalOrDifferentiatedEquation(eq::EquationGraph, e::Int, v::Int)
    # Determine original, undifferentiated equation
    while eq.Brev[e] > 0
        e = eq.Brev[e]
        v = eq.Arev[v]
    end

    # Check whether original, undifferentiated equation is linear
    return eq.fc.isLinearEquation(e, v)
end

"""
    (isLinear, hasConstantCoefficients) = isLinearEquationSystem!(eq, es, vs)

Returns `isLinear = true`, if equations `es::Vector{Int}` are linear with respect to
variables `vs::Vector{Int}`. If **all** coefficients of the linear factors are additionally constant,
`hasConstantCoefficients=true` is returned, otherwise false.
`eq::EquationGraph` is the data structure holding all information about the graph.
"""
function isLinearEquationSystem!(eq::EquationGraph, es::Vector{Int}, vs::Vector{Int})::Tuple{Bool,Bool}
    # It is assumed, that on input, eq.vLinActive[i] = false
    # On return, eq.vLinActive[i] = false again

    # Mark that vs are active variables
    eq.vLinActive[vs] .= true

    # Check whether es is linear with respect to vs
    isLinear::Bool = true
    hasConstantCoefficients::Bool = true
    for e in es
        for v in eq.G[e]
            if eq.vLinActive[v]  # Only check variables vs in G[e]
                (e_isLinear, e_hasConstantCoefficient) = isLinearOriginalOrDifferentiatedEquation(eq, e, v)
                if !e_isLinear
                    isLinear = false
                    hasConstantCoefficients = false
                    break
                else
                    hasConstantCoefficients = hasConstantCoefficients && e_hasConstantCoefficient
                end
            end
        end
        if !isLinear
            break
        end
    end

    # Unmark that vs are active variables
    eq.vLinActive[vs] .= false

    return (isLinear, hasConstantCoefficients)
end

"""
    tearEquationsWithCandidates!(eq::EquationGraph)

Tear equations (eq.der_eSolvedLower, eq.ec) with respect to variables
(eq.der_vSolvedLower, eq.vc) and initialize tearing with the
Directed-Acylic-Graph (eq.der_eSolvedLower, eq.der_vSolvedLower).

It is tried to solve the equations eq.ec with respect to variables `eq.vc`
in the following order:

1. eq.der_vTearLower\\
   (These are differentiated variables from the previous differentiation level that
    have been used as tearing variables at the previous differentation level.
    In general, it is adviceable to use non-differentiated
    variables as states and by trying to eliminate der_vTearLower first, it is tried to solve
    for all differentiated variables first; note these variables have no start values).

2. Variable has start=nothing and the variable does not appear differentiated
   in the set of original equations.
   (Variables without a start value should be explicitly computed during initialization and
   therefore these variables should be solved for;
   however, if a variable appears also differentiated in the original equations,
   then it should be tried to use it as a state and therefore, it should be first tried
   to not solve for this variable).

3. Variable has start=nothing and the variable appears differentiated
   in the set of original equations.
   (Variables without a start value should be explicitly computed during initialization and
   therefore these variables should be solved for).

4. Variable has fixed=false\\
   (The start value is a guess value, so it is safe to solve for the variable and
   hereyby ignore the start value)

5. Variable has fixed=nothing\\
   (The intention is to respect the start value if possible, that is, it should be avoided
   to solve for such a variable)

6. Variable has fixed=true\\
   (The start value must be respected, that is, if any possible no equation should be solved
   for this variable; if it is solved for, an error is triggered during initialization if the
   start value and the computed value do not agree)

# Example

Assume the constraint `phi1 = phi2` and differentiated constraints
`der(phi1) = der(phi2), w1 = der(phi1), w2 = der(phi2)` and start values are defined
for `phi1` and `w1`.

- Since no start value is defined for `phi2` (but a start value is defined for `phi1`),
  equation `phi1 = phi2` is solved for `phi2`, so `phi2 := phi1` and `phi1` is the tearing variable.
  This means that `der_vSolvedLower = der(phi1); der_vTearLower = der(phi2)`.

- On the next differentiation level, the differentiated equation `der(phi1) = der(phi2)`
  is solved in the same way as on the previous level due to `der_eSolvedLower, der_vSolvedLower`, that is
  `der(phi2) := der(phi1)`.

- Since `der_vTearLower = der(phi1)`, it is first tried to solve for `der(phi1)`. There is only
  one equation left  with `der(phi1)` and therefore this equation is solved for it:
  `der(phi1) := w1`.

- Since a start value is defined for `w1` and no start value for `w2`, it is tried to solve
  for `w2`, that is: `w2 := der(phi2)` and the result is that `w1` is used as tearing variable.

Resulting equation set with states = `phi1, w1`:

```julia
phi2      := phi1
der(phi1) := w1
der(phi2) := der(phi1)
w2        := der(phi2)
```
"""
function tearEquationsWithCandidates!(eq::EquationGraph)::Nothing
    # Empty all candidate vectors
    for c in eq.vcCandidates
        empty!(c)
    end

    # Determine priorities to solve for variables eq.vc
    #   Assume equations:
    #     (1)   s = ...
    #     (1')  w = der(s)
    #     (1'') a = der(w)
    #   Then it is most natural to use "w" and "a" as tearing variables if "s" is a tearing variable
    #   and solve for "der(phi)" and "der(w)".
    #   This means, that eq.der_vTearLower should be tried first to be solved
    eq.vcCandidates[1] = eq.der_vTearLower

    for v in setdiff(eq.vc, eq.der_vTearLower)
        # Variable has no start value because:
        #   (a) is not from the original, non-differentiated equations
        #   (b) is a differentiated variable
        #   (c) no start or init value is defined
        (startOrInit, fixed) = eq.fc.var_startInitFixed(v)
        hasNoStart = !eq.vOriginal[v] || eq.Arev[v] > 0 || startOrInit isa Nothing
        if hasNoStart
            # Has no start value
            if eq.vOriginal[v] && (eq.A[v]>0 && eq.vOriginal[eq.A[v]])
                # Is from the original, non-differentiated equations and its derivative
                # is also in the original equations (so try to use it as state).
                push!(eq.vcCandidates[3], v)
            else
                # All other variables without a start value are tried
                push!(eq.vcCandidates[2], v)
            end

        else
            if startOrInit isa Nothing
                push!(eq.vcCandidates[5], v)
            elseif fixed
                push!(eq.vcCandidates[6], v)
            else
                push!(eq.vcCandidates[4], v)
            end
        end
    end

    if eq.log && eq.logDetails
        println("    eSolvedFixed = ", eq.der_eSolvedLower)
        println("    vSolvedFixed = ", eq.der_vSolvedLower)
        println("    vcCandidates = ", eq.vcCandidates)
    end

    # Tear equations (ec are non-differentiated, original equations)
    (eq.eSolved, eq.vSolved, eq.eResiduals, eq.vTear) =
        tearEquations!(eq.td, eq.fc.isSolvableEquation, eq.ec, eq.vcCandidates;
                       eSolvedFixed = eq.der_eSolvedLower,
                       vSolvedFixed = eq.der_vSolvedLower,
                       log = eq.log && eq.logDetails)
    return nothing
end

"""
    v = derivativeOfVlower(vLower::Vector{Int}, A::Vector{Int})

Given a set of variables vLower and the A-Vector of Pantelides,
return the derivative of vLower (so the differentiated variables of vLower).
"""
function derivativeOfVlower(vLower::Vector{Int}, A::Vector{Int})::Vector{Int}
    v = fill(0, length(vLower))
    for i in eachindex(vLower)
        derv = A[ vLower[i] ]
        @assert(derv > 0)
        v[i] = derv
    end
    return v
end

"""
    addFixedVariable!(eq::EquationGraph, v::Int)

If variable v is not differentiated AND has fixed=true store it in eq.equationInfo
(this is used to check during initialization, that the start value is respected)
"""
function addFixedVariable!(eq::EquationGraph, v::Int)::Nothing
    (v_startOrInit,v_fixed) = eq.fc.var_startInitFixed(v)
    if eq.Arev[v] == 0 && v_fixed
        push!(eq.vSolvedWithFixedTrue, v)
        push!(eq.equationInfo.vSolvedWithFixedTrue, eq.fc.var_name(v))
    end
    return nothing
end

"""
    addSolvedEquations!(eq::EquationGraph, eSolved::Vector{Int}, vSolved::Vector{Int})

Solve equation eSolved[i] for variable vSolved[i] and push this information to
eq.SortedEquations. Furthermore, generate the AST.
"""
function addSolvedEquations!(eq::EquationGraph, eSolved::Vector{Int}, vSolved::Vector{Int})::Nothing
    if eq.log
        println("Julia code:")
    end

    for i in eachindex(eSolved)
        # Push solved equation to eAST
        v = vSolved[i]
        e = eSolved[i]
        eq.eAST[e] = eq.fc.getSolvedEquationAST(e, v)   # filter_lineno( )
        if eq.log
            printEquations(eq.eAST[e])
        end
        eq.fullAssignRev[e] = v
        addFixedVariable!(eq,v)
    end

    return nothing
end

"""
    addLinearEquations!(eq::EquationGraph, hasConstantCoefficients::Bool, unitless::Bool)

A linear equation system is solved. Push this information to
eq.SortedEquations. Furthermore, generate the AST for a for-loop that builds
and solves a linear equation system A*x = b
from the solved equations and the residual equations,
and push this information to eq.SortedEquations.AST.
"""
function addLinearEquations!(eq::EquationGraph, hasConstantCoefficients::Bool, unitless::Bool)::Nothing
    # Construct body of for-loop
    empty!(eq.AST_aux)
    while_body = eq.AST_aux
    vTear_names   = String[]
    vTear_lengths = Int[]

    # Assign iteration variables
    #   unitless = false:
    #     v_i = leq.x[i]
    #
    #   unitless = true:
    #     v_i = leq.x[i]*@u_str($v_unit)
    #
    #   assign vector-valued variables vec_j at the end (storage is allocated inside LinearEquations)
    #     vec_j = leq.x_vec[j]
    #
    vAssigned_names   = Any[]
    v_vec_julia_names = Any[]
    v_vec             = Int[]
    v_vec_startOrInit = Any[]
    i1 = 0
    i2 = 0
    for (i,v) in enumerate(eq.vTear)
        (v_startOrInit, v_fixed) = eq.fc.var_startInitFixed(undifferentiated(eq,v))
        v_name = eq.fc.var_name(v)

        if isFixedLengthStartOrInit(v_startOrInit, v_name)
            # length(v_startOrInit) is fixed after compilation
            v_julia_name = eq.fc.var_julia_name(v)
            v_unit       = unitless ? "" : eq.fc.var_unit(v)
            v_length     = isnothing(v_startOrInit) ? 1 : length(v_startOrInit)
            i1 = i2 + 1
            i2 = i1 + v_length - 1
            if v_startOrInit isa AbstractVector
                # v is a vector
                x_elements = Expr[]
                for i in i1:i2
                    push!(x_elements, :( _leq_mode.x[$i] ))
                end
                if v_unit == ""
                    push!(while_body, :( $v_julia_name = Modia.SVector{$v_length,_FloatType}($(x_elements...))) )
                else
                    push!(while_body, :( $v_julia_name = Modia.SVector{$v_length,_FloatType}($(x_elements...))*@u_str($v_unit)) )
                end
            elseif v_startOrInit isa Number || v_startOrInit isa Nothing
                # v is a scalar or nothing (= assumed to be a scalar)
                if v_unit == ""
                    push!(while_body, :( $v_julia_name = _leq_mode.x[$i1] ) )
                else
                    push!(while_body, :( $v_julia_name = _leq_mode.x[$i1]*@u_str($v_unit) ) )
                end
            else
                error("Should not occur: v_name = $v_name, v_startOrInit = $v_startOrInit")
            end
            push!(vAssigned_names, v_julia_name)
            push!(vTear_lengths  , v_length)

            # Store iteration variables in linearEquations to be used in error messages
            push!(vTear_names, v_name)
        else
            # length(v_startOrInit) may change after compilation
            push!(v_vec, v)
            push!(v_vec_startOrInit, v_startOrInit)
        end
    end

    # Assignment code for vector-valued variables
    nx_fixedLength = length(vAssigned_names)
    for (i,v) in enumerate(v_vec)
        v_startOrInit = v_vec_startOrInit[i]
        v_julia_name  = eq.fc.var_julia_name(v)
        v_unit        = unitless ? "" : eq.fc.var_unit(v)
        if v_unit == ""
            push!(while_body, :( $v_julia_name = _leq_mode.x_vec[$i] ) )
        else
            push!(while_body, :( $v_julia_name = _leq_mode.x_vec[$i]*@u_str($v_unit) ))
        end
        push!(vAssigned_names  , v_julia_name)
        push!(vTear_lengths    , length(v_startOrInit))
        push!(v_vec_julia_names, v_julia_name)

        # Store iteration variables in linearEquations to be used in error messages
        push!(vTear_names, eq.fc.var_name(v))
    end

    # Add solved equations
    for (i,e) in enumerate(eq.eSolved)
        push!(while_body, eq.fc.getSolvedEquationAST(e, eq.vSolved[i]))
        push!(vAssigned_names, eq.fc.var_julia_name(eq.vSolved[i]))
    end

    # Add residual equations
    #   appendResidual!(leq.residuals, < equation in residual form >)
    for (i,e) in enumerate(eq.eResiduals)
        e_AST = eq.fc.getResidualEquationAST(e, :(_leq_mode.residuals[$i]) )
        if !isnothing(e_AST)
            push!(while_body, e_AST)
        end
    end

    # Generate LinearEquations data structure
    push!(eq.equationInfo.linearEquations, (vTear_names, v_vec_julia_names, vTear_lengths, nx_fixedLength, hasConstantCoefficients))

    # Construct for-loop
    leq_index = length(eq.equationInfo.linearEquations)
    while_loop = quote
        local $(vAssigned_names...)
        _leq_mode = initLinearEquationsIteration!(_m, $leq_index)
        Modia.TimerOutputs.@timeit _m.timer "Modia LinearEquationsIteration!" while Modia.LinearEquationsIteration!(_leq_mode, _m.isInitial, _m.solve_leq, _m.storeResult, _m.time, _m.timer)
            $(while_body...)
        end
        _leq_mode = nothing
    end

    if eq.log
        showCodeWithoutComments(while_loop)
    end

    # Store information about linear equation system
    teq = TearedEquations(true, hasConstantCoefficients,
                          copy(eq.vSolved), copy(eq.vTear),
                          copy(eq.eSolved), copy(eq.eResiduals),
                          while_loop)
    push!(eq.tearedEquations, teq)
    teq_index = length(eq.tearedEquations)

    # Reference teq_index for all equations
    for eSolved in eq.eSolved
        eq.tearedEquations_indices[eSolved] = teq_index
    end
    for eResiduals in eq.eResiduals
        eq.tearedEquations_indices[eResiduals] = teq_index
    end

    # Store fixed=true variables
    for vTear in eq.vTear
        addFixedVariable!(eq,vTear)
    end
    for vSolved in eq.vSolved
        addFixedVariable!(eq,vSolved)
    end

    # Store vTear without a start value
    for vTear in eq.vTear
        (vTear_startOrInit, vTear_fixed) = eq.fc.var_startInitFixed(vTear)
        if vTear_startOrInit isa Nothing
            push!(eq.vTearWithoutStart, vTear)
        end
    end

    return nothing
end

"""
    sortEquations!(eq:EquationGraph)

Generate the sorted equations
"""
function sortEquations!(eq::EquationGraph, Goriginal)::Nothing
    if eq.log
         println("Sort equations (BLT on all equations under the assumption that the ODE states are known).")
    #    println("\nSorted equations (BLT on all equations under\nthe assumption that the ODE states are known):")
    #
    #    code = quote
    #        $(eq.AST...)
    #    end
    #    showCodeWithoutComments(code)
    end

    # Matching of all equations
    assign    = matching(Goriginal, length(eq.A), eq.vActive)
    assignRev = revertAssociation(assign)

    # Sort equations and find strong components
    blt = BLT(Goriginal,assign)

    # Generate AST of sorted equations
    for blt_i in blt
        @assert(length(blt_i) >= 1)

        solveLinearEquation = true
        if length(blt_i) == 1 # One equation in one unknown
            e = blt_i[1]

            # Check
            v = eq.fullAssignRev[e]
            if v != -1
                @assert(e == assign[v])

                # Push AST
                push!(eq.AST, eq.eAST[e])
                solveLinearEquation = false
            end
        end

        if solveLinearEquation # Equation system
            # Check that all equations reference the same equation system
            e1 = blt_i[1]
            teq_index = eq.tearedEquations_indices[e1]
            @assert(teq_index != 0)
            for j=2:length(blt_i)
                e = blt_i[j]
                if eq.tearedEquations_indices[e] != teq_index
                    error("... should not occur: teq_index=$teq_index, e1=$e1, e_teq_index=", eq.tearedEquations_indices[e])
                end
            end

            # Check that the assigned variables of the BLT block are the variables computed from the equation system
            teq = eq.tearedEquations[teq_index]
            vTearComputed = union(teq.vTear, teq.vSolved)
            vBltComputed = Int[]
            for e in blt_i
                push!(vBltComputed, assignRev[e])
            end
            vdiff = setdiff(vBltComputed, vTearComputed)
            @assert(length(vdiff) == 0)

            # Push AST
            push!(eq.AST, teq.AST)
        end
    end

    return nothing
end

"""
    (success, AST, equationInfo) = getSortedAndSolvedAST(
                                        G, BLT, assign, A, B, stateSelectionFunctions;
                                        log = false, logDetails=false, modelName = "???",
                                        defaultParameterAndStartValues = nothing,
                                        unitless=false)

From the BLT on highest derivative level `(G, BLT, assign, A, B)`,
a set of callback functions `stateSelectionFunctions`, this function returns the
AST (Abstract Syntax Tree) of the sorted and solved equations as
a vector of `Expr` and information about the ODE equations
(especially names of the ODE states).

# Input arguments

- `G`: G[i] is the Integer vector of variable indices of equation i.
   A variable i can be a scalar or an array.
   is of type Vector{ Vector{Int} } or Vector{ Any }.

- `BLT::Vector{Vector{Int}}`: BLT[i] is the vector of equations belonging to BLT-block i.
  In principal, **BLT[i] must include only highest derivative equations**.
  In order to ease the generation of BLT[i], to not be forced to map indices forth and back
  when calling the function that computes the BLT, the following assumption is
  made: If BLT[j] contains only **one equation with B[j][1] > 0** then this BLT block is
  a lower-derivative (dummy) block and is ignored.

- `assign::Vector{Int}`: ei = assign[vi] is equation ei assigned to variable vi

- `A`: A-Vector of Pantelides algorithm:
       `A[i] = if der(v[i]) == v[k] then k else 0`
       where `v[i]` is variable `i`.

- `B`: B-Vector of Pantelides algorithm:
       `B[i] = if der(e[i]) == e[k] then k else 0`
       where `e[i]` is equation `i`.

- `stateSelectionFunctions`:
  An instance of immutable struct [`StateSelectionFunctions`](@ref)
  that holds the information about the callback functions needed by
  `getSortedAndSolvedAST`.

- `log`: = true: Print debug information (to find bugs in the code).

- `logDetails`: = true: Print detailed debug information, if `log = true`.

- `modelName`: Name of model used in messages (otherwise not used).

# Output arguments

A tuple with the following values:

- `success::Bool`: = true, if generation was successful. = false, if
  an error occured. Arguments `AST, equationInfo` hold the information that
  have been collected until the error was detected.

- `AST::Vector{Expr}`: The AST (Abstract Syntax Tree) of the sorted and solved equations
  as Vector of `Expr`.

- `equationInfo::`[`Modia.EquationInfo`](@ref): Object that defines
  the states of the ODE.

When variable `v` has neither a `start` nor `init` attribute defined,
it is assumed to have `start=0.0`.

| defined   | Description                                                |
|:----------|:-----------------------------------------------------------|
| `start`   | `start` is allowed to be changed during initialization     |
| `init`    | `init` is not allowed to be changed during initialization  |

Note, `start, init` influence the state selection.

If an ODE state has neither a `start` nor an `init` value defined, a warning message is printed
(start/init value missing).

If a solved variable has an `init` value, an information message is printed in case `log=true`
(init value has no effect).

# Sketch of the Algorithm

Note, a statement *error xxx* means that an error occurs,
because it is not possible to transform the equations to an ODE.

## Generate equation sets

From BLT blocks that are not further differentiated (= highest order BLT blocks),
generate the equation sets as described by the dummy derivative method of
[Mattsson and Söderlind (1992)](https://ieeexplore.ieee.org/document/274429).
See also sections 4.5 and 4.6 of the paper
[Otter and Elmqvist (2017)](https://modelica.org/events/modelica2017/proceedings/html/submissions/ecp17132565_OtterElmqvist.pdf).

## Define initial ODE states

Initially, all differentiated variables are defined to be ODE states.
Whenever an initial ODE state is explicitly solved for in the course of the
algorithm, the variable is no longer an ODE state.

## Analyse equation sets

For every equation set on every differentiation level perform the following actions:

- If the equation set consists of *one* equation in *one* unknown, the equation
  is solved for this unknown (*error, if this is not possible*).

- If the equation set consists of *N linear* equations in *N* unknowns solve this
  equation system (*error, if no linear system*):\\
  The equations are first teared to reduce the number of iteration variables and
  afterwards the teared equation system is solved with a special iterator loop that
  solves a linear equation system with an LU decomposition with column pivoting
  (for details see [`Modia.LinearEquationsIteration!`](@ref)).\\

- If the equation set consists of *N linear* equations in *M* unknowns (*M > N*) perform
  the following actions (*error, if no linear system*).\\
  Note, due to the structure of BLT, this equation set cannot be
  on highest derivative level; due to the Pantelides algorithm,
  M < N is not possible).

  1. Solve the equation system explicitly via tearing for N unknowns
     (*error, if this is not possible*). Use start/init attributes of the M unknowns
     to influence tearing (e.g. it is tried to eliminate first variables that have neither start not init values).

  2. The N solved variables have been initially ODE states and are now defined to be
     no ODE states (so called dummy states, that is algebraic variables).

A BLT transformation of **all equations** is made under the assumption that
the selected ODE states are known. This phase is needed, because the dummy-derivative
ordering at the beginning does not necessarily provide already the right ordering.
In this phase the information from the previous phase is used (that is the already determined
tearing variables for systems of equations are utilized).
"""
function getSortedAndSolvedAST(Goriginal,     # Typically ::Vector{Vector{Int}}
                               G,
                               BLT,   # Typically ::Vector{Vector{Int}}
                               assign::Vector{Int},
                               A::Vector{Int},
                               B::Vector{Int},
                               stateSelectionFunctions::StateSelectionFunctions;
                               log::Bool        = false,
                               logDetails::Bool = false,
                               logStates::Bool  = false,
                               modelName        = "???",
                               unitless::Bool   = false,
                               defaultParameterAndStartValues = nothing)

    if log
        println("\n=== getSortedAndSolvedAST(...) started for $modelName.")
    end

    # Define error/warning function
    showMessage2(message; severity=0, details="",variables=Int[],equations=Int[]) =
    stateSelectionFunctions.showMessage(message; from="getSortedAndSolvedAST for model $modelName",
                                            severity=severity, details=details, variables=variables, equations=equations)

    # Construct data structure eq that holds all needed information for the state selection
    # (this includes constructing the equation/constraint sets and initialization of tearing)
    eq = EquationGraph(G, BLT, assign, A, B, stateSelectionFunctions, log, logDetails, showMessage2)
    if !eq.success
        @goto ERROR_RETURN
    end
    eq.equationInfo.defaultParameterAndStartValues = defaultParameterAndStartValues

    # Inspect every equation/constraint set in sequence from lowest-order to highest-order derivative
    for j in eachindex(eq.eConstraintsVec)
        # Equation/Constraint set and its unknowns that are inspected
        eConstraints = eq.eConstraintsVec[j]
        vConstraints = eq.vConstraintsVec[j]

        # Analyze all equation sets eConstraints[i] from lowest-order to highest-order derivatives
        for i in eachindex(eConstraints)
            if log
                println("\n... Equation set $j.$i ..............................")
                println("Equations: ")
                printEquations(eq, eConstraints[i])
                println("Unknown variables: ")
                printVariables(eq, vConstraints[i])
            end

            solveLinearEquation = true
            if length(eConstraints[i]) == 1 && length(vConstraints[i]) == 1
                # One equation in one unknown
                if i < length(eConstraints)
                    # Not on highest derivative level. Unknown is a dummy state.
                    v = vConstraints[i][1]
                    @assert(!eq.vActive[v])
                    eq.vActive[v] = true
                    if log
                        println("One equation in one unknown variable: Unknown is a dummy state.")
                    end
                else
                    if log
                        println("One equation in one unknown variable. Solve the equation:")
                    end
                end

                # Solve equation for unknown v and add solved equation to AST
                try
                    addSolvedEquations!(eq, eConstraints[i], vConstraints[i])
                    solveLinearEquation = false
                catch
                    if log
                        println("Not possible to solve the equation directly. Try so solve it as linear equation:")
                    end
                    solveLinearEquation = true
                    eq.fullAssignRev[eConstraints[i][1]] = -1
                end
            end

            if solveLinearEquation
                # N equations in M unknowns (M >= N)
                @assert(length(vConstraints[i]) >= length(eConstraints[i]))
                if log
                    N = length(eConstraints[i])
                    M = length(vConstraints[i])
                    println("$N equation(s) in $M unknown variable(s). Tear the system of equations:")
                end

                # Tear systems of equations
                if i == 1
                    # On the lowest derivative level, initialize tearing with empty vectors
                    empty!(eq.der_eSolvedLower)
                    empty!(eq.der_vSolvedLower)
                    empty!(eq.der_vTearLower)

                    # Variables/equations to be inspected by tearing
                    eq.vc = vConstraints[i]
                    eq.ec = eConstraints[i]

                else
                    # On derivative level i > 1, initialize tearing with the differentiated eSolved, vSolved, vTear
                    # from the previous level i-1.
                    # (eConstraints[i] is the derivative of eConstraints[i-1] + potentially additional equations)
                    eq.der_eSolvedLower = derivativeOfVlower(eq.eSolved, B)
                    eq.der_vSolvedLower = derivativeOfVlower(eq.vSolved, A)
                    eq.der_vTearLower   = derivativeOfVlower(eq.vTear  , A)

                    # Variables/equations to be inspected by tearing (remove the parts that are known from level i-1)
                    eq.vc = setdiff(vConstraints[i], eq.der_vSolvedLower)
                    eq.ec = setdiff(eConstraints[i], eq.der_eSolvedLower)
                end

                if log && i < length(eConstraints)
                    vWithStart = Int[]
                    for v in vConstraints[i]
                        (v_startOrInit,v_fixed) = eq.fc.var_startInitFixed(v)
                        if !(v_startOrInit isa Nothing)
                            push!(vWithStart, v)
                        end
                    end
                    println("    Unknowns with start or init values: ", getNames(eq, vWithStart))
                end

                tearEquationsWithCandidates!(eq)
                if log
                    println("    Tearing  variables: ", getNames(eq, eq.vTear))
                    if length(eq.eResiduals) > 0
                        println("    Residual equations: ");
                        printEquations(eq, eq.eResiduals; indent=8)
                    end
                end

                # Select dummy states
                if i < length(eConstraints)
                    # Not on highest derivative level. Solved variables are dummy states
                    for v in eq.vSolved
                        @assert(!eq.vActive[v])
                        eq.vActive[v] = true
                    end

                    if length(eConstraints[i]) == length(vConstraints[i])
                        # N equations in N unknowns - tearing variables are dummy states
                        for v in eq.vTear
                            @assert(!eq.vActive[v])
                            eq.vActive[v] = true
                        end
                        if log
                            println("    All unknowns are dummy states.")
                        end

                    else
                        if log
                            println("    All solved unknowns are dummy states.")
                        end
                    end
                elseif log
                    println("    All unknowns are solved.")
                end

                # Further actions depending on type of equations
                if length(eq.eResiduals) == 0
                    # There are no residual equations, add solved equations to AST
                    addSolvedEquations!(eq, eq.eSolved, eq.vSolved)

                elseif length(eConstraints[i]) == length(vConstraints[i])
                    # N equations in N unknowns with residual equations

                    # Check that equation system is linear in the unknowns
                    (isLinear, hasConstantCoefficients) = isLinearEquationSystem!(eq, eConstraints[i], vConstraints[i])
                    if !isLinear
                        if i == length(eConstraints)
                            # On highest derivative level:
                            # Assume that the equation system is linear, if at least one of the unknowns is a derivative
                            linearAssumption = true  # temporarily

                            #linearAssumption = false
                            #for v in vConstraints[i]
                            #    if eq.Arev[v] > 0
                            #        linearAssumption = true
                            #    end
                            #end

                            if linearAssumption
                                isLinear = true
                                hasConstantCoefficients = false
                                #showMessage2("It is heuristically assumed that equation system is linear (although isLinearEquation returned isLinear=false).";
                                #             severity  = WARNING,
                                #             variables = vConstraints[i],
                                #             equations = eConstraints[i])
                            end
                        end

                        if !isLinear
                            showMessage2("Cannot transform to ODE, because equation system is not linear.";
                                        severity  = ERROR,
                                        variables = vConstraints[i],
                                        equations = eConstraints[i])
                            @goto ERROR_RETURN
                        end
                    end

                    if log
                        println("Teared equation system is linear. Solve system with hasConstantCoefficients = $hasConstantCoefficients.")
                    end

                    # Generate AST to build-up and solve linear equation system of the teared equations
                    addLinearEquations!(eq, hasConstantCoefficients, unitless)

                else
                    # N equations in M unknowns with M > N and residual equations
                    @assert(length(vConstraints[i]) > length(eConstraints[i]))

                    # Assertion, that this case is not possible on highest derivative level
                    @assert(i < length(eConstraints))

                    showMessage2("Cannot transform to ODE because constraint equations cannot be explicitly solved by tearing",
                                 severity  = ERROR,
                                 variables = vConstraints[i],
                                 equations = eConstraints[i])
                    @goto ERROR_RETURN
                end
            end # if
        end  # for
    end # for

    # Determine ODE states
    ODE_states = Int[]
    for (ve,veActive) in enumerate(eq.vActive)
        if !veActive
            push!(ODE_states, ve)
        end
    end

    # Store state information in equationInfo
    x_info            = eq.equationInfo.x_info
    x_without_start   = Int[]
    x_vec             = Int[]
    x_vec_startOrInit = Any[]
    x_vec_fixed       = Bool[]
    for v in ODE_states
        (v_startOrInit, v_fixed) = eq.fc.var_startInitFixed(v)
        if isnothing(v_startOrInit)
            push!(x_without_start, v)
        end
        v_name = eq.fc.var_name(v)

        if isFixedLengthStartOrInit(v_startOrInit, v_name)
            v_der_x            = eq.A[v]
            v_unit             = unitless ? "" : eq.fc.var_unit(v)
            v_julia_name       = eq.fc.var_julia_name(v)
            v_der_x_name       = eq.fc.var_name(v_der_x)
            v_der_x_julia_name = eq.fc.var_julia_name(v_der_x)
            v_nominal          = eq.fc.var_nominal(v)
            v_unbounded        = eq.fc.var_unbounded(v)
            v_stateCategory    = Modia.XD

            push!(x_info, Modia.StateElementInfo(
                            v_name, v_julia_name,
                            v_der_x_name, v_der_x_julia_name,
                            v_stateCategory, v_unit, v_startOrInit, v_fixed,
                            v_nominal, v_unbounded))
        else
            # length(v_startOrInit) may change after compilation
            push!(x_vec            , v)
            push!(x_vec_startOrInit, v_startOrInit)
            push!(x_vec_fixed      , v_fixed)
        end
    end
    eq.equationInfo.nxFixedLength = length(x_info)
    for (i,v) in enumerate(x_vec)
        v_startOrInit      = x_vec_startOrInit[i]
        v_fixed            = x_vec_fixed[i]
        v_name             = eq.fc.var_name(v)
        v_der_x            = eq.A[v]
        v_unit             = unitless ? "" : eq.fc.var_unit(v)
        v_julia_name       = eq.fc.var_julia_name(v)
        v_der_x_name       = eq.fc.var_name(v_der_x)
        v_der_x_julia_name = eq.fc.var_julia_name(v_der_x)
        v_nominal          = eq.fc.var_nominal(v)
        v_unbounded        = eq.fc.var_unbounded(v)
        v_stateCategory    = Modia.XD

        push!(x_info, Modia.StateElementInfo(
                        v_name, v_julia_name,
                        v_der_x_name, v_der_x_julia_name,
                        v_stateCategory, v_unit, v_startOrInit, v_fixed,
                        v_nominal, v_unbounded))
    end

    # Handle systems with only algebraic variables, by introducing a dummy
    # differential equation der_x[1] = -x[1].
    if length(ODE_states) == 0
        if log
            println("Model has only algebraic variables.\n",
                    "Added a dummy differential equation der(_dummy_x) = -_dummy_x, _dummy_x(t0) = 0")
        end
        push!(eq.equationInfo.x_info, Modia.StateElementInfo(
              "_dummy_x", :(), "der(_dummy_x)", :(), XD, "", 0.0, true, NaN, false))
    end

    # Finalize equationInfo
    initEquationInfo!(eq.equationInfo)

    # Print ODE states
    if logStates
        println("\nSelected ODE states: ")
        x_table = Modia.get_x_table(x_info)
        show(stdout, x_table; allrows=true, allcols=true, summary=false, eltypes=false)
        print("\n\n")
    end

    # Sort equations and generate sorted AST (eq.AST)
    sortEquations!(eq, Goriginal)

    # Check that all ODE states have a start value
    if length(x_without_start) > 0
        showMessage2("Init/start values missing in the model for some ODE states.";
                     severity  = WARNING,
                     variables = x_without_start)
    end

    # Print info, if there are iteration variables without a start value
    if length(eq.vTearWithoutStart) > 0 && !unitless
        showMessage2("The following variables are iteration variables but have no start/init values defined.",
                     details = "If units are used in the model, start/init values with correct units should be defined\n" *
                               "to avoid unit errors during compilation.",
                     severity  = INFORMATION,
                     variables = eq.vTearWithoutStart)
    end

    # Print warning, if there are variables with fixed=true that are
    # explicitly solved for and log=true
    if log && length(eq.equationInfo.vSolvedWithFixedTrue) > 0
        showMessage2("The following variables have an 'init' initialization and are explicitly solved for.",
                     details = "Therefore, the 'init' values have no effect, but must exactly match the values,\n"*
                               "computed during initialization. Otherwise this gives a run-time error.\n"*
                               "It is adviced to use 'start' initialization or remove initialization for these variables." ,
                     severity  = WARNING,
                     variables = eq.vSolvedWithFixedTrue)
    end

    if log
        println("\n=== getSortedAndSolvedAST(...) terminated for $modelName.\n")
    end
    return (true, eq.AST, eq.equationInfo)

    @label ERROR_RETURN
    return (false, eq.AST, eq.equationInfo)
end