/* set output line length */
linel : slength(concat(maxima_tempdir,"/",%codigo_usuario%,".mac")) + 10;

/* texput */
texput(matrix,lambda([expr], printf(false,"\\begin{bmatrix}~%~{~{~a~^&~}~^\\\\~}~%\\end{bmatrix}",map(lambda([row],map(tex1,row)),args(expr)))));
texput(?rat,lambda([expr],printf(false,"\\dfrac{~a}{~a}",tex1(num(expr)),tex1(denom(expr)))));
texput("/",lambda([expr],printf(false,"\\dfrac{~a}{~a}",tex1(num(expr)),tex1(denom(expr)))));
texput(nounify(diff), lambda([expr],block([Y,X,n], [Y,X,n] : args(expr), if n=1 then printf(false,"\\dfrac{d\\,}{d{~a}}{~a}",tex1(X),tex1(Y)) else printf(false,"\\dfrac{d^{~a}\\,}{d{~a}^{~a}}{~a}",n,tex1(X),n,tex1(Y))))) ;
texput('diff, lambda([expr],block([Y,X,n], [Y,X,n] : args(expr), if n=1 then printf(false,"\\dfrac{d\\,}{d{~a}}{~a}",tex1(X),tex1(Y)) else printf(false,"\\dfrac{d^{~a}\\,}{d{~a}^{~a}}{~a}",n,tex1(X),n,tex1(Y))))) ;
tex_exp(expr) := block([b,e],
  [b,e] : args(expr),
  if e=-1 then printf(false,"\\dfrac{1}{~a} ",tex1(b))
  else if atom(b) then printf(false,"{~a}^{~a}",tex1(b),tex1(e))
  else printf(false,"\\left(~a\\right)^{~a}",tex1(b),tex1(e))) ,
texput("^",tex_exp) ,

/* add paths to package folder */

file_search_maxima:
   append (file_search_maxima,
           [concat(%dir_sources%, "/###.mac")])$

file_search_lisp:
   append (file_search_lisp,
           [concat(%dir_sources%, "/###.lisp")])$

/* Global variables */

%num_sentence%: 0$
%num_grafico%: 0$

/* Code for draw */

mwdrawxd(func, descgraf):=
  block([haiterm: false, formato],
    if not get('draw,'version) then load("draw"),
    descgraf: append([dimensions=[400,300],
                      gnuplot_file_name = concat(%codigo_usuario%,".gnuplot"),
                      data_file_name = concat(%codigo_usuario%,".data"),
                      file_name  = concat(maxima_tempdir,
                                          "/",
                                          %codigo_usuario%,
                                          ".g.",
                                          %num_proceso%,
                                          ".",
                                          %num_sentence%,
                                          ".",
                                          %num_grafico%) ],
                     descgraf),
    /* If terminal is not specified, force svg */
    for elem in descgraf do
       if part(elem,1) = 'terminal and 
          member(part(elem,2), ['png, 'gif, 'animated_gif, 'jpg, 'svg])
         then (haiterm: true,
               if part(elem,2) = 'png
                 then formato: "png"
               elseif part(elem,2) = 'jpg
                 then formato: "jpg"
               elseif member(part(elem,2), ['gif, 'animated_gif])
                 then formato: "gif"
               elseif part(elem,2) = 'svg
                 then formato: "svg",
               return()),
    if not haiterm
       then (formato: "svg",
             descgraf: endcons(terminal = 'svg,
               descgraf)),
    with_stdout(
      concat(maxima_tempdir,
             "/",
             %codigo_usuario%,
             ".gr.",
             %num_proceso%,
             ".",
             %num_sentence%,
             ".txt"), 
      print(concat("tmp/",
                   %codigo_usuario%,
                   ".g.",
                   %num_proceso%,
                   ".",
                   %num_sentence%,
                   ".",
                   %num_grafico%,
                   ".",
                   formato))),
    %num_grafico%: %num_grafico% + 1,
    apply(func,descgraf))$

Draw2d([descgraf]):= mwdrawxd('draw2d, descgraf) $
Draw3d([descgraf]):= mwdrawxd('draw3d, descgraf) $
Draw([descgraf])  := mwdrawxd('draw, descgraf) $

/* Code for plot */
/* 
   Example controlling graphic dimensions:
   plot2d (sin(x), [x, -%pi, %pi], [gnuplot_png_term_command, "set term pngcairo size 800,800"])$
*/

mwplotxd(func, descgraf):=
  block([gptc: false, formato:"svg", cleandescgraf:[]],
    for k in descgraf do
      if not listp(k) or 
         not member(first(k), ['png_file, 'svg_file, 'pdf_file, 'ps_file, 'gnuplot_term, 'gnuplot_out_file,
                               'run_viewer ])
        then (if not atom(k) and first(k)='gnuplot_png_term_command
                then gptc:true,
              cleandescgraf: endcons(k, cleandescgraf)),
    cleandescgraf: append(cleandescgraf,
                          [[gnuplot_out_file,  concat(%codigo_usuario%,".gnuplot")],
                           [svg_file, concat(maxima_tempdir,
                                             "/",
                                             %codigo_usuario%,
                                             ".g.",
                                             %num_proceso%,
                                             ".",
                                             %num_sentence%,
                                             ".",
                                             %num_grafico%,
                                             ".svg")] ] ),
    if not gptc
      then cleandescgraf: endcons([gnuplot_svg_term_command, "set term svg size 500,400"],
                                  cleandescgraf),
    with_stdout(
      concat(maxima_tempdir,
             "/",
             %codigo_usuario%,
             ".gr.",
             %num_proceso%,
             ".",
             %num_sentence%,
             ".txt"), 
      print(concat("tmp/",
                   %codigo_usuario%,
                   ".g.",
                   %num_proceso%,
                   ".",
                   %num_sentence%,
                   ".",
                   %num_grafico%,
                   ".",
                   formato))),
    %num_grafico%: %num_grafico% + 1,
    apply(func,cleandescgraf)  ) $

Plot2d([descgraf]):= (mwplotxd('plot2d, descgraf), 'plot2d) $
Plot3d([descgraf]):= (mwplotxd('plot3d, descgraf), 'plot3d) $

/* statistical graphics */

Scatterplot([desc]) := Draw(apply('scatterplot_description, desc)) $
Histogram([desc]) := Draw2d(apply(histogram_description, desc)) $
Barsplot([desc]) := Draw2d(apply(barsplot_description, desc)) $
Piechart([desc]) := Draw2d(apply(piechart_description, desc)) $
Boxplot([desc]) := Draw2d(apply(boxplot_description, desc)) $
Starplot([desc]) := Draw2d(apply(starplot_description, desc)) $

/* direction fields package */

Drawdf([params]) := Draw(apply('df_graphics, params))$

/* output formats */

translate_into_tex(sentencias) :=
  block(
    print("start_maxima_output_tex_code:"),
    map(lambda([%%lambda_argument%%],
               %num_sentence%: %num_sentence% + 1,
               %num_grafico%: 1,
               tex(eval_string(%%lambda_argument%%))),
        sentencias)) $

translate_into_print(sentencias) :=
  block([res],
    print("start_maxima_output_print_code:"),
    map(lambda([%%lambda_argument%%],
               %num_sentence%: %num_sentence% + 1,
               %num_grafico%: 1,
               res: eval_string(%%lambda_argument%%),
               print("%%%"),
               print(res),
               print("%%%")),
        sentencias)) $
