(*      _                   _ _
  _____| |__ ___ _ __  _ __(_| |___ _ _
 (_-/ _` / _/ _ | '  \| '_ | | / -_| '_|
 /__\__,_\__\___|_|_|_| .__|_|_\___|_|
                      |_|
 Copyright (c) 2013-2015 transentis management & consulting. All rights reserved.
*)

(*
Clear["SystemDynamics`{{{namespace}}}`*"];
BeginPackage["SystemDynamics`{{{namespace}}}`"];
*)
Needs["SystemDynamics`"];

{{prefix}}starttime := {{specs.start}};
{{prefix}}stoptime := {{specs.stop}};

(* stocks *){{#each stocks}}
{{{name}}}[t_,dt_] := {{{name}}}[t,dt] = {{{expression}}};{{/each}}

(* flows *){{#each flows}}
{{{name}}}[t_,dt_] := {{{name}}}[t,dt] = {{{expression}}};{{/each}}

(* converters *){{#each converters}}
{{{name}}}[t_,dt_] := {{{name}}}[t,dt] = {{{expression}}};{{/each}}

(* gf *){{#each gf}}
{{{name}}}[t_,dt_] := {{{name}}}[t,dt] = {{#if discrete}}Interpolation[Join[{{start}},{{points}},{{stop}}],InterpolationOrder->0][{{{expression}}}-(1-dt)]{{else}}Interpolation[graphicalFunction[{{points}},{{prefix}}sim],InterpolationOrder->1][{{{expression}}}]{{/if}};{{/each}}

(* constants *){{#each constants}}
{{{name}}}[t_,dt_] := {{{name}}}[t,dt] = {{{expression}}};{{/each}}


(* defaults & evaluator *)
{{prefix}}evaluator[OptionsPattern[]] :=  Module[{},{{#each constants}}
  {{{name}}}[T_,DT_] := {{{name}}}[T,DT] = OptionValue[{{{name}}}]/.{t->T,dt->DT};{{/each}}{{#each converters}}
  {{{name}}}[T_,DT_] := {{{name}}}[T,DT] = OptionValue[{{{name}}}]/.{t->T,dt->DT};{{/each}}{{#each gf}}
  {{{name}}}[t_,dt_] := {{{name}}}[t,dt] = {{#if discrete}}Interpolation[Join[{{start}},OptionValue[{{{name}}}],{{stop}}],InterpolationOrder->0][{{{expression}}}-(1-dt)]{{else}}Interpolation[OptionValue[{{{name}}}],InterpolationOrder->1][{{{expression}}}]{{/if}};{{/each}}
];
Options[{{prefix}}evaluator] = { {{#each defaults}}{{#if @index}},{{/if}}
  {{{name}}} -> {{{expression}}}{{/each}}
};

(* create simulation *)
{{prefix}}sim = Module[ {s},
  s = Unique["simulation"];
  s["name"] = "{{name}}";
  s["stocks"] = { {{#each stocks}}{{#if @index}}, {{/if}}{{{name}}}{{/each}} };
  s["flows"] = { {{#each flows}}{{#if @index}}, {{/if}}{{{name}}}{{/each}} };
  s["converters"] = { {{#each converters}}{{#if @index}}, {{/if}}{{{name}}}{{/each}} };
  s["gf"] = { {{#each gf}}{{#if @index}}, {{/if}}{{{name}}}{{/each}} };
  s["constants"] = { {{#each constants}}{{#if @index}}, {{/if}}{{{name}}}{{/each}} };
  s["spec"] = { {{specs.start}}, {{specs.stop}}, {{specs.dt}}, "{{specs.units}}" };
  s["evaluator"] = {{prefix}}evaluator;
  simulation[s]
];

(*
EndPackage[]
*)
