(*********************************************************************

	Copyright 1989 by Roman E. Maeder
	
	Adapted from
	Roman E. Maeder: Programming in Mathematica, Addison-Wesley, 1989.

	Permission is hereby granted to make copies of this file for
	any purpose other than direct profit, or as part of a
	commercial product, provided this copyright notice is left
	intact.  Sale, other than for the cost of media, is prohibited.
	
	Permission is hereby granted to reproduce part or all of
	this file, provided that the source is acknowledged.

 *********************************************************************)


BeginPackage["RMPackages`ReIm`"]

(*  to declare a variable x to be real, define    x/: Im[x] = 0  *)

(* no exports *)

Begin["`Private`"]

protected = Unprotect[Re,Im, Abs, Conjugate, Arg]

(* fundamental rules, Im[x]==0 serves as our test for 'reality' *)

Re[x_] := x  /; Im[x] == 0
Conjugate[x_] :=  x /; Im[x] == 0
Conjugate[x_] := -x /; Re[x] == 0

(* there must not be a rule for Im[x] in terms of Re[x] !! *)

(* things known to be real *)

Im[Re[ _ ]]  := 0
Im[Im[ _ ]]  := 0
Im[Abs[ _ ]] := 0
Im[Arg[ _ ]] := 0

(* arithmetic *)

Re[x_ + y_] := Re[x] + Re[y]
Im[x_ + y_] := Im[x] + Im[y]

Re[x_ y_] := Re[x] Re[y] - Im[x] Im[y]
Im[x_ y_] := Re[x] Im[y] + Im[x] Re[y]

Re[ 1/x_ ] :=  Re[x] / (Re[x]^2 + Im[x]^2)
Im[ 1/x_ ] := -Im[x] / (Re[x]^2 + Im[x]^2)

Re[E^x_] := Cos[Im[x]] Exp[Re[x]]
Im[E^x_] := Sin[Im[x]] Exp[Re[x]]

Im[x_^2] := 2 Re[x] Im[x]

Re[ x_^n_Integer ] :=
	Block[{a, b},
		a = Round[n/2]; b = n-a;
		Re[x^a] Re[x^b] - Im[x^a] Im[x^b]
	]

Im[ x_^n_Integer ] :=
	Block[{a, b},
		a = Round[n/2]; b = n-a;
		Re[x^a] Im[x^b] + Im[x^a] Re[x^b]
	]

Re[x_Integer^n_Rational] := 0                /; IntegerQ[2n] && x<0
Im[x_Integer^n_Rational] := 
	(-x)^n (-1)^((Numerator[n]-1)/2) /; IntegerQ[2n] && x<0

Re[x_Integer^n_Rational] := x^n /; OddQ[Denominator[n]] || x>0
Im[x_Integer^n_Rational] := 0   /; OddQ[Denominator[n]] || x>0

Re[(-1)^n_Rational] := Cos[n Pi]
Im[(-1)^n_Rational] := Sin[n Pi]

(* functions *)

Re[Sin[x_]] := Sin[Re[x]] Cosh[Im[x]]
Im[Sin[x_]] := Cos[Re[x]] Sinh[Im[x]]

Re[Cos[x_]] :=  Cos[Re[x]] Cosh[Im[x]]
Im[Cos[x_]] := -Sin[Re[x]] Sinh[Im[x]]

Re[Log[r_?Positive]] := Log[r]
Im[Log[r_?Positive]] := 0
Re[Log[r_?Negative]] := Log[-r]
Im[Log[r_?Negative]] := Pi

Re[Log[z_]] := (1/2) Log[Re[z]^2 + Im[z]^2]
Im[Log[z_]] := Arg[z]

Re[Log[a_ b_]] := Re[Log[a] + Log[b]]
Im[Log[a_ b_]] := Im[Log[a] + Log[b]]
Re[Log[a_^c_]] := Re[c Log[a]]
Im[Log[a_^c_]] := Im[c Log[a]]

Re[Tan[x_]] := Re[Sin[x]/Cos[x]]
Im[Tan[x_]] := Im[Sin[x]/Cos[x]]

(* conjugates *)

Re[Conjugate[z_]] :=  Re[z]
Im[Conjugate[z_]] := -Im[z]

Conjugate[x_+y_]:= Conjugate[x]+Conjugate[y]
Conjugate[x_ y_]:= Conjugate[x] Conjugate[y]
Conjugate[x_^n_Integer]:= Conjugate[x]^n
Conjugate[Conjugate[x_]]:= x

Protect[Release[protected]]

End[]
EndPackage[]
