(* ::Package:: *)

(*Package written by Dmytro Popovych for Alexander Sakhnovych*)


replaceSymbols::usage="Replace the names used in Mathematica with corresponding LaTeX commands";
reverseNCP::usage="Replace non-commutative product of Mathematica expression(*todo*)";
replaceDiff::usage="Replace d[expr, var] with expr_{var}";
replaceBackslash::usage="Remove extra backslashes which could appear during other replacements";


(*removeSpaces[expr_]:=Module[
{},
StringReplace[expr, Whitespace:>""]]*)


replaceSymbols[expr_]:=Module[
{symbolPatterns={
	"tau":> "\\tau ",
	"tildetau":> "\\tilde\\tau ",
	"P1":> "P_{1}",
	"P2star":> "P_{2}^{*}",
	"A1":> "A_{1}",
	"A2":> "A_{2}",
	"jot":> "j",
	"inv[S]":> "S^{-1}",
	"**":>""}},
StringReplace[expr, symbolPatterns]
]


rNCPtoPower[expr_]:=StringReplace[expr,"reversedNCP["~~Shortest[var__~~","~~power__]~~"]":> var~~"^{"~~power~~"}"]


replaceDiff[expr_]:=Module[
{diffPatterns = {
  "d["~~Shortest[var__~~","~~a__] ~~ "]" :> var~~"_{" ~~ a ~~ "}"
  }
},
StringReplace[expr, diffPatterns]
]


replaceBackslash[expr_]:=StringReplace[expr, {x__?(#1 == "\\" &) :> "\\"}]


reverseNCP[expr_]:=Module[
	{reverseRules={
		HoldPattern[l___**a_**a_**r___]:>NonCommutativeMultiply[l,reversedNCP[a,2],r],
		HoldPattern[l___**reversedNCP[a_,n_]**a_**r___]:>NonCommutativeMultiply[l,reversedNCP[a,n+1],r],
		HoldPattern[l___**a_**reversedNCP[a_,n_]**r___]:>NonCommutativeMultiply[l,reversedNCP[a,n+1],r],
		reversedNCP[inv[a_],n_]:>reversedNCP[a,-n]}},
Substitute[expr,reverseRules]]


(* deprecated*)(*lineBreakOnPM[expr_]:=StringReplace[expr, {"+":>"+\n\\\\",x_~~"-"/;x=!="{"&&x=!="(":>x~~"-\n\\\\"}];*)
lineBreakOnPM[expr_,maxLength_:150]:=Module[{split,gather="",i,length=0},
split=StringSplit[expr,{"+":>"+",x_~~"-"/;x=!="{"&&x=!="(":>x~~"-"}];
gather=split[[1]]; 
length=StringLength[split[[1]]];
For[i=1,i<(Length[split]+1)/2,i++, 
If[StringLength[split[[2i+1]]]+length>maxLength,
{length=StringLength[split[[2i+1]]];gather=gather~~split[[2i]]~~"\n\\\\"~~split[[2i+1]];},
{length=length+StringLength[split[[2i+1]]];gather=gather~~split[[2i]]~~split[[2i+1]];}
]
];
gather
]


LaTeXify[expr_]:=replaceBackslash[replaceDiff[replaceSymbols[rNCPtoPower[StringReplace[ToString[reverseNCP[expr],InputForm],Whitespace :>""]]]]]


resultWindow[expr_,maxLength_:150] := Module[{modifiedExpr},
modifiedExpr=lineBreakOnPM[LaTeXify[expr],maxLength];
GUIRun[
   Widget["TextArea", {
     "text" -> modifiedExpr, 
     "lineWrap" -> True}] 
   ]
];
