(* ::Package:: *)

(************************************************************************)
(* This file was generated automatically by the Mathematica front end.  *)
(* It contains Initialization cells from a Notebook file, which         *)
(* typically will have the same name as this file except ending in      *)
(* ".nb" instead of ".m".                                               *)
(*                                                                      *)
(* This file is intended to be loaded into the Mathematica kernel using *)
(* the package loading commands Get or Needs.  Doing so is equivalent   *)
(* to using the Evaluate Initialization Cells menu command in the front *)
(* end.                                                                 *)
(*                                                                      *)
(* DO NOT EDIT THIS FILE.  This entire file is regenerated              *)
(* automatically each time the parent Notebook file is saved in the     *)
(* Mathematica front end.  Any changes you make to this file will be    *)
(* overwritten.                                                         *)
(************************************************************************)



(* ::Input::Initialization:: *)
BeginPackage["DataAnalysis`Phreeqc`",{"DataAnalysis`"}];


(* ::Input::Initialization:: *)
Unprotect[Evaluate[$Context<>"*"]];


(* ::Input::Initialization:: *)
PhreeqcOpenLink;
PhreeqcCloseLink;
PhreeqcLoadDB;
PhreeqcRunString;
PhreeqcRunFile;


(* ::Input::Initialization:: *)
SelectedOutput;


(* ::Input::Initialization:: *)
Begin["`Private`"];


(* ::Input::Initialization:: *)
SetAttributes[ErrorMessage,HoldFirst];
ErrorMessage[Args___]:=Module[
{},
Message[Args];
Abort[];
];


(* ::Input::Initialization:: *)
SetAttributes[CatchError,HoldAll];
CatchError[Body_]:=(Catch[Body]===$ErrorFlag);


(* ::Input::Initialization:: *)
PackageFolder=DirectoryName[$InputFileName];


(* ::Input::Initialization:: *)
PhreeqcOpenLink::usage="PhreeqcOpenLink[] opens a new link to IPhreeqc and returns the link object.";
PhreeqcOpenLink[]:=Module[
{L},
(
SetDirectory[ToFileName[{PackageFolder,"bin",$SystemID}]];
L=If[$OperatingSystem=="Windows",
Install["PhreeqMathematica`"],
Install["PhreeqMathematica"]
];
ResetDirectory[];

L
)
];


(* ::Input::Initialization:: *)
PhreeqcCloseLink::usage="PhreeqcCloseLink[link] closes a link to certain IPhreeqc link object.";
PhreeqcCloseLink[l_LinkObject]:=Module[
{},
(
Uninstall[l]
)
];

PhreeqcCloseLink[]:=If[Head[$DefaultPhreeqcLink]===LinkObject,Uninstall[$DefaultPhreeqcLink]];


(* ::Input::Initialization:: *)
PhreeqcLoadDB::usage="PhreeqcLoadDB[link,file] sets a new database for a certain IPhreeqc link object.
PhreeqcLoadDB[file] sets a new database for the default IPhreeqc link object.";
PhreeqcLoadDB[l_LinkObject,file_]:=Module[
{},
(
ExternalCall[l,CallPacket[0,{file}]]
)
];
PhreeqcLoadDB[file_]:=(
CheckDefaultLink[];
PhreeqcLoadDB[$DefaultPhreeqcLink,file]
);


(* ::Input::Initialization:: *)
CheckDefaultLink[]:=(
If[!(Head[$DefaultPhreeqcLink]===LinkObject),
(
Unprotect[$DefaultPhreeqcLink];
$DefaultPhreeqcLink=PhreeqcOpenLink[];
Protect[$DefaultPhreeqcLink];
),
If[!MemberQ[Links[],$DefaultPhreeqcLink],
Unprotect[$DefaultPhreeqcLink];
Quiet[Uninstall[$DefaultPhreeqcLink]];
$DefaultPhreeqcLink=PhreeqcOpenLink[];
Protect[$DefaultPhreeqcLink];
]
]
)


(* ::Input::Initialization:: *)
Options[PhreeqcRunString]={SelectedOutput->False};
SelectedOutput::usage="SelectedOutput is an option to PhreeqcRunString[link,str] specifying whether a selected output table should be returned.";

PhreeqcRunString::noresult="PHREEQC did not return any selected output for the script '`1`'.";

PhreeqcRunString::usage="PhreeqcRunString[link,str] evaluates a PHREEQC script from a string using the specified link object.
PhreeqcRunString[str] uses the default link object.";
PhreeqcRunString[l_LinkObject,str_,opts:OptionsPattern[]]:=Module[
{Ret,ColRow},
(
Ret=ExternalCall[l,CallPacket[1,{StringReplace[str,"\n"->";"],If[TrueQ[OptionValue[SelectedOutput]],1,0]}]];

If[TrueQ[OptionValue[SelectedOutput]],
(*MapIndexed[(Prepend[#1,If[#2[[1]]\[Equal]1,"ID",#2[[1]]-1]])&,ImportString[Ret,"Table"]]*)
If[Ret==="",ErrorMessage[PhreeqcRunString::noresult,str]];
Ret=ImportString[Ret,"Table"];
ColRow=FirstPosition[Ret,{_String..}]//First;
If[ColRow>1,
PrependTo[Ret,Ret[[ColRow]]];
Ret=Delete[Ret,ColRow+1];
];

MapIndexed[(Prepend[#1,If[#2[[1]]==1,"ID","Result-"<>ToString[#2[[1]]-1]]])&,Ret]
,
Ret
]
)
];
PhreeqcRunString[str_,opts:OptionsPattern[]]:=(
CheckDefaultLink[];
PhreeqcRunString[$DefaultPhreeqcLink,str,opts]
);


(* ::Input::Initialization:: *)
Options[PhreeqcRunFile]={SelectedOutput->False};
PhreeqcRunFile::noresult="PHREEQC did not return any selected output for the PHREEQC script in '`1`'.";

PhreeqcRunFile::usage="PhreeqcRunFile[link,file] evaluates a PHREEQC script from a file using the specified link object.
PhreeqcRunFile[file] uses the default link object.";
PhreeqcRunFile[l_LinkObject,file_,opts:OptionsPattern[]]:=Module[
{Ret,ColRow},
(
Ret=ExternalCall[l,CallPacket[2,{file,If[TrueQ[OptionValue[SelectedOutput]],1,0]}]];

If[TrueQ[OptionValue[SelectedOutput]],
If[Ret==="",ErrorMessage[PhreeqcRunFile::noresult,file]];
(*MapIndexed[(Prepend[#1,If[#2[[1]]\[Equal]1,"ID",#2[[1]]-1]])&,ImportString[Ret,"Table"]]*)
Ret=ImportString[Ret,"Table"];
ColRow=FirstPosition[Ret,{_String..}]//First;
If[ColRow>1,
PrependTo[Ret,Ret[[ColRow]]];
Ret=Delete[Ret,ColRow+1];
];

MapIndexed[(Prepend[#1,If[#2[[1]]==1,"ID","Result-"<>ToString[#2[[1]]-1]]])&,Ret]
,
Ret
]
)
];
PhreeqcRunFile[file_,opts:OptionsPattern[]]:=(
CheckDefaultLink[];
PhreeqcRunFile[$DefaultPhreeqcLink,file,opts]
);


(* ::Input::Initialization:: *)
End[];


(* ::Input::Initialization:: *)
Protect[Evaluate[$Context<>"*"]];
EndPackage[];
