BeginPackage["CSM`Modular`"]

mod::usage = "mod[n, p] is a representation of the number (n mod p)."

Begin["`Private`"]

(* Constructor and Normal Form *)

mod[n_, p_]/; n < 0 || n >= p := mod[ Mod[n, p], p ]

(* Arithmetic *)

mod/: mod[a_,p_] + mod[b_,p_] := mod[ a + b, p ]
mod/: mod[a_,p_] * mod[b_,p_] := mod[ a * b, p ]
mod/: mod[a_,p_] ^ q_Integer  := mod[ PowerMod[a, q, p], p ]

(* Output Formatting *)

Format[m_mod] := Infix[m," mod "]

(* Type Conversion of Integers *)

mod/: mod[a_,p_] + b_Integer := mod[ a + b, p ]
mod/: mod[a_,p_] * b_Integer := mod[ a * b, p ]

End[]

EndPackage[]
