diff --git a/Crypto/Lol.hs b/Crypto/Lol.hs
--- a/Crypto/Lol.hs
+++ b/Crypto/Lol.hs
@@ -3,8 +3,8 @@
 Description : Primary interface to the Lol library.
 Copyright   : (c) Eric Crockett, 2011-2017
                   Chris Peikert, 2011-2017
-License     : GPL-2
-Maintainer  : ecrockett0@email.com
+License     : GPL-3
+Maintainer  : ecrockett0@gmail.com
 Stability   : experimental
 Portability : POSIX
 
@@ -28,7 +28,7 @@
     numbers.
 
   * \( \Z_q = \Z/(q\Z) \) is the integers mod \( q \). \( \Z_q \) is
-    implemented in "Crypto.Lol.Types.ZqBasic".
+    implemented in "Crypto.Lol.Types.Unsafe.ZqBasic".
 
   * The finite field of order \( p \) is denoted \( \F_{p} \), and is
     implemented in "Crypto.Lol.Types.FiniteField".
@@ -48,12 +48,17 @@
     This is the dimension of a cyclotomic ring over the base ring.
 -}
 
+-- EAC: See https://github.com/haskell/haddock/issues/563
 module Crypto.Lol
-( module X
+( module Crypto.Lol.Cyclotomic.Cyc
+, module Crypto.Lol.Cyclotomic.Linear
+, module Crypto.Lol.Cyclotomic.Language
+, module Crypto.Lol.Gadget
+, module Crypto.Lol.Prelude
 ) where
 
-import Crypto.Lol.Cyclotomic.Cyc        as X
-import Crypto.Lol.Cyclotomic.Linear     as X
-import Crypto.Lol.Cyclotomic.RescaleCyc as X
-import Crypto.Lol.Gadget                as X
-import Crypto.Lol.Prelude               as X
+import Crypto.Lol.Cyclotomic.Cyc
+import Crypto.Lol.Cyclotomic.Language
+import Crypto.Lol.Cyclotomic.Linear
+import Crypto.Lol.Gadget
+import Crypto.Lol.Prelude
diff --git a/Crypto/Lol/Benchmarks.hs b/Crypto/Lol/Benchmarks.hs
new file mode 100644
--- /dev/null
+++ b/Crypto/Lol/Benchmarks.hs
@@ -0,0 +1,45 @@
+{-|
+Module      : Crypto.Lol.Benchmarks
+Description : Infrastructure for benchmarking lol.
+Copyright   : (c) Eric Crockett, 2011-2017
+                  Chris Peikert, 2011-2017
+License     : GPL-3
+Maintainer  : ecrockett0@email.com
+Stability   : experimental
+Portability : POSIX
+
+  \( \def\C{\mathbb{C}} \)
+
+Benchmarks for individual layers of the Lol stack (Tensor, CycRep, Cyc), plus
+default parameters and helper functions for diplaying results.
+-}
+
+-- EAC: See https://github.com/haskell/haddock/issues/563, which claims that
+-- Haddock doesn't support "re-exporting modules". However, the following
+-- method duplicates the docs of all the re-exported modules here, which is
+-- what I want. It doesn't like it if I rename the modules though.
+module Crypto.Lol.Benchmarks
+(
+-- * Default parameters for benchmarks
+ module Crypto.Lol.Benchmarks.Default
+-- * Benchmarks for different layers of Lol
+,module Crypto.Lol.Benchmarks.TensorBenches
+,module Crypto.Lol.Benchmarks.CycRepBenches
+,module Crypto.Lol.Benchmarks.CycBenches
+-- * Utilities for creating benchmarks
+,module Crypto.Lol.Utils.Benchmarks
+-- * Utilities for showing benchmark results
+,module Crypto.Lol.Utils.ShowType
+,Verb(..)
+,module Crypto.Lol.Utils.PrettyPrint.Table
+,module Crypto.Lol.Utils.PrettyPrint.Diagnostic) where
+
+import Crypto.Lol.Benchmarks.CycBenches
+import Crypto.Lol.Benchmarks.CycRepBenches
+import Crypto.Lol.Benchmarks.Default
+import Crypto.Lol.Benchmarks.TensorBenches
+import Crypto.Lol.Utils.Benchmarks
+import Crypto.Lol.Utils.PrettyPrint            (Verb (..))
+import Crypto.Lol.Utils.PrettyPrint.Diagnostic
+import Crypto.Lol.Utils.PrettyPrint.Table
+import Crypto.Lol.Utils.ShowType
diff --git a/Crypto/Lol/Benchmarks/CycBenches.hs b/Crypto/Lol/Benchmarks/CycBenches.hs
new file mode 100644
--- /dev/null
+++ b/Crypto/Lol/Benchmarks/CycBenches.hs
@@ -0,0 +1,172 @@
+{-|
+Module      : Crypto.Lol.Benchmarks.CycBenches
+Description : Benchmarks for the 'Cyc' interface.
+Copyright   : (c) Eric Crockett, 2011-2017
+                  Chris Peikert, 2011-2017
+License     : GPL-3
+Maintainer  : ecrockett0@email.com
+Stability   : experimental
+Portability : POSIX
+
+Benchmarks for the 'Cyc' interface.
+-}
+
+{-# LANGUAGE DataKinds             #-}
+{-# LANGUAGE FlexibleContexts      #-}
+{-# LANGUAGE NoImplicitPrelude     #-}
+{-# LANGUAGE PartialTypeSignatures #-}
+{-# LANGUAGE ScopedTypeVariables   #-}
+{-# LANGUAGE TypeFamilies          #-}
+{-# LANGUAGE TypeOperators         #-}
+
+{-# OPTIONS_GHC -fno-warn-partial-type-signatures #-}
+
+module Crypto.Lol.Benchmarks.CycBenches (cycBenches1, cycBenches2) where
+
+import Control.Applicative
+import Control.Monad.Random hiding (lift)
+
+import Crypto.Lol
+import Crypto.Lol.Types
+import Crypto.Lol.Utils.Benchmarks (Benchmark, bgroup, mkBench, mkBenchIO)
+import Crypto.Random
+
+-- must come after imports
+{-# ANN module "HLint: ignore Use camelCase" #-}
+
+-- | Benchmarks for single-index 'Cyc' operations.
+-- There must be a CRT basis for \(O_m\) over @r@.
+{-# INLINABLE cycBenches1 #-}
+cycBenches1 :: forall t m r gen . _ => Proxy '(t,m,r) -> Proxy gen -> Benchmark
+cycBenches1 ptmr pgen =
+  let z = zero :: Cyc t m r
+      errorBench = mkBenchIO "error" (bench_errRounded ptmr pgen 0.1)
+      benches = ($ z) <$> [
+        mkBench "zipWith (*)" (bench_mul z),
+        mkBench "crt" bench_crt,
+        mkBench "crtInv" bench_crtInv,
+        mkBench "l" bench_l,
+        mkBench "lInv" bench_lInv,
+        mkBench "*g Pow" bench_mulgPow,
+        mkBench "*g Dec" bench_mulgDec,
+        mkBench "*g CRT" bench_mulgCRT,
+        mkBench "divG Pow" bench_divGPow,
+        mkBench "divG Dec" bench_divGDec,
+        mkBench "divG CRT" bench_divGCRT,
+        mkBench "lift" bench_liftPow] in
+  bgroup "Cyc" (benches ++ [errorBench])
+
+-- | Benchmarks for inter-ring 'Cyc' operations.
+-- There must be a CRT basis for \(O_{m'}\) over @r@.
+{-# INLINABLE cycBenches2 #-}
+cycBenches2 :: forall t m m' r . _ => Proxy '(t,m,m',r) -> Benchmark
+cycBenches2 ptmmr =
+  let z' = zero :: Cyc t m' r
+      z = zero :: Cyc t m r
+      benches = [
+        mkBench "twacePow" (bench_twacePow ptmmr) z',
+        mkBench "twaceDec" (bench_twaceDec ptmmr) z',
+        mkBench "twaceCRT" (bench_twaceCRT ptmmr) z',
+        mkBench "embedPow" (bench_embedPow ptmmr) z,
+        mkBench "embedDec" (bench_embedDec ptmmr) z,
+        mkBench "embedCRT" (bench_embedCRT ptmmr) z] in
+  bgroup "Cyc" benches
+
+{-# INLINABLE bench_mul #-}
+-- no CRT conversion, just coefficient-wise multiplication
+bench_mul :: _ => Cyc t m r -> Cyc t m r -> Cyc t m r
+bench_mul a b = adviseCRT a * adviseCRT b
+
+{-# INLINABLE bench_crt #-}
+-- convert input from Pow basis to CRT basis
+bench_crt :: _ => Cyc t m r -> Cyc t m r
+bench_crt = adviseCRT . advisePow
+
+{-# INLINABLE bench_crtInv #-}
+-- convert input from CRT basis to Pow basis
+bench_crtInv :: _ => Cyc t m r -> Cyc t m r
+bench_crtInv = advisePow . adviseCRT
+
+{-# INLINABLE bench_l #-}
+-- convert input from Dec basis to Pow basis
+bench_l :: _ => Cyc t m r -> Cyc t m r
+bench_l = advisePow . adviseDec
+
+{-# INLINABLE bench_lInv #-}
+-- convert input from Pow basis to Dec basis
+bench_lInv :: _ => Cyc t m r -> Cyc t m r
+bench_lInv = adviseDec  . advisePow
+
+{-# INLINE bench_liftPow #-}
+-- lift an element in the Pow basis
+bench_liftPow :: _ => Cyc t m r -> Cyc t m r'
+bench_liftPow = liftPow . advisePow
+
+{-# INLINABLE bench_mulgPow #-}
+-- multiply by g when input is in Pow basis
+bench_mulgPow :: _ => Cyc t m r -> Cyc t m r
+bench_mulgPow = mulG . advisePow
+
+{-# INLINABLE bench_mulgDec #-}
+-- multiply by g when input is in Dec basis
+bench_mulgDec :: _ => Cyc t m r -> Cyc t m r
+bench_mulgDec = mulG . adviseDec
+
+{-# INLINABLE bench_mulgCRT #-}
+-- multiply by g when input is in CRT basis
+bench_mulgCRT :: _ => Cyc t m r -> Cyc t m r
+bench_mulgCRT = mulG . adviseCRT
+
+{-# INLINABLE bench_divGPow #-}
+-- divide by g when input is in Pow basis
+bench_divGPow :: _ => Cyc t m r -> Maybe (Cyc t m r)
+bench_divGPow = divG . advisePow . mulG
+
+{-# INLINABLE bench_divGDec #-}
+-- divide by g when input is in Dec basis
+bench_divGDec :: _ => Cyc t m r -> Maybe (Cyc t m r)
+bench_divGDec = divG . adviseDec . mulG
+
+{-# INLINABLE bench_divGCRT #-}
+-- divide by g when input is in CRT basis
+bench_divGCRT :: _ => Cyc t m r -> Maybe (Cyc t m r)
+bench_divGCRT = divG . adviseCRT
+
+{-# INLINABLE bench_errRounded #-}
+-- generate a rounded error term
+bench_errRounded :: forall t m r gen . _
+                 => Proxy '(t,m,r) -> Proxy gen -> Double -> IO (Cyc t m (LiftOf r))
+bench_errRounded _ _ v = do
+  gen <- newGenIO
+  let e = roundedGaussian v :: Rand (CryptoRand gen) (Cyc t m (LiftOf r))
+  return $ evalRand e gen
+
+{-# INLINE bench_twacePow #-}
+bench_twacePow :: forall t m m' r . _
+  => Proxy '(t,m,m',r) -> Cyc t m' r -> Cyc t m r
+bench_twacePow _ = (twace :: Cyc t m' r -> Cyc t m r) . advisePow
+
+{-# INLINE bench_twaceDec #-}
+bench_twaceDec :: forall t m m' r . _
+  => Proxy '(t,m,m',r) -> Cyc t m' r -> Cyc t m r
+bench_twaceDec _ = (twace :: Cyc t m' r -> Cyc t m r) . adviseDec
+
+{-# INLINE bench_twaceCRT #-}
+bench_twaceCRT :: forall t m m' r . _
+  => Proxy '(t,m,m',r) -> Cyc t m' r -> Cyc t m r
+bench_twaceCRT _ = (twace :: Cyc t m' r -> Cyc t m r) . adviseCRT
+
+{-# INLINE bench_embedPow #-}
+bench_embedPow :: forall t m m' r . _
+  => Proxy '(t,m,m',r) -> Cyc t m r -> Cyc t m' r
+bench_embedPow _ = (advisePow . embed :: Cyc t m r -> Cyc t m' r) . advisePow
+
+{-# INLINE bench_embedDec #-}
+bench_embedDec :: forall t m m' r . _
+  => Proxy '(t,m,m',r) -> Cyc t m r -> Cyc t m' r
+bench_embedDec _ = (adviseDec . embed :: Cyc t m r -> Cyc t m' r) . adviseDec
+
+{-# INLINE bench_embedCRT #-}
+bench_embedCRT :: forall t m m' r . _
+  => Proxy '(t,m,m',r) -> Cyc t m r -> Cyc t m' r
+bench_embedCRT _ = (adviseCRT . embed :: Cyc t m r -> Cyc t m' r) . adviseCRT
diff --git a/Crypto/Lol/Benchmarks/CycRepBenches.hs b/Crypto/Lol/Benchmarks/CycRepBenches.hs
new file mode 100644
--- /dev/null
+++ b/Crypto/Lol/Benchmarks/CycRepBenches.hs
@@ -0,0 +1,196 @@
+{-|
+Module      : Crypto.Lol.Benchmarks.CycRepBenches
+Description : Benchmarks for 'CycRep'.
+Copyright   : (c) Eric Crockett, 2011-2017
+                  Chris Peikert, 2011-2017
+License     : GPL-3
+Maintainer  : ecrockett0@email.com
+Stability   : experimental
+Portability : POSIX
+
+Benchmarks for 'CycRep'. In a perfect world, these benchmarks would
+have the same performance as the 'Cyc' benchmarks. In practice, GHC
+gets in the way at higher levels of the library, resulting in worse
+performance for 'Cyc' in some cases.
+-}
+
+{-# LANGUAGE DataKinds             #-}
+{-# LANGUAGE FlexibleContexts      #-}
+{-# LANGUAGE NoImplicitPrelude     #-}
+{-# LANGUAGE PartialTypeSignatures #-}
+{-# LANGUAGE ScopedTypeVariables   #-}
+{-# LANGUAGE TypeFamilies          #-}
+{-# LANGUAGE TypeOperators         #-}
+
+{-# OPTIONS_GHC -fno-warn-partial-type-signatures #-}
+
+module Crypto.Lol.Benchmarks.CycRepBenches (cycRepBenches1, cycRepBenches2) where
+
+import Control.Monad.Random hiding (lift)
+
+import Crypto.Lol.Cyclotomic.CycRep
+import Crypto.Lol.Prelude
+import Crypto.Lol.Types
+import Crypto.Lol.Utils.Benchmarks  (Benchmark, bgroup, mkBench, mkBenchIO)
+import Crypto.Random
+
+-- must come after imports
+{-# ANN module "HLint: ignore Use camelCase" #-}
+
+-- | Benchmarks for single-index 'CycRep' operations.
+-- There must be a CRT basis for \(O_m\) over @r@.
+-- These cover the same functions as @cycBenches1@, but may have different
+-- performance due to how GHC interacts with Lol.
+{-# INLINABLE cycRepBenches1 #-}
+cycRepBenches1 :: forall t m r gen . _ => Proxy '(t,m,r) -> Proxy gen -> Benchmark
+cycRepBenches1 ptmr pgen =
+  let zDec = zero :: CycRep t D m r
+      zPow = zero :: CycRep t P m r
+      zEC = zero :: CycRepEC t m r
+      zPC = ecToPC zEC
+      errorBench = mkBenchIO "error" (bench_errRounded ptmr pgen 0.1)
+      benches = [
+        mkBench "zipWith (*)" (bench_mul zPC) zPC,
+        mkBench "crt"         bench_crt       zPow,
+        mkBench "crtInv"      bench_crtInv    zPC,
+        mkBench "l"           bench_l         zDec,
+        mkBench "lInv"        bench_lInv      zPow,
+        mkBench "*g Pow"      bench_mulgPow   zPow,
+        mkBench "*g Dec"      bench_mulgDec   zDec,
+        mkBench "*g CRT"      bench_mulgCRT   zPC,
+        mkBench "divG Pow"    bench_divGPow   zPow,
+        mkBench "divG Dec"    bench_divGDec   zDec,
+        mkBench "divG CRT"    bench_divGCRT   zPC,
+        mkBench "lift"        bench_liftPow   zPow] in
+      -- This is different because it lives in IO
+  bgroup "CycRep" (benches ++ [errorBench])
+
+-- | Benchmarks for inter-ring 'CycRep' operations.
+-- There must be a CRT basis for \(O_{m'}\) over @r@.
+-- These cover the same functions as @cycBenches2@, but may have different
+-- performance due to how GHC interacts with Lol.
+{-# INLINE cycRepBenches2 #-}
+cycRepBenches2 :: forall t m m' r . _ => Proxy '(t,m,m',r) -> Benchmark
+cycRepBenches2 ptmmr =
+  let zPow' = zero :: CycRep t P m' r
+      zDec' = zero :: CycRep t D m' r
+      zEC' = zero :: CycRepEC t m' r
+      zPC' = ecToPC zEC'
+      zPow = zero :: CycRep t P m r
+      zEC = zero :: CycRepEC t m r
+      zPC = ecToPC zEC
+      benches = [
+        mkBench "twacePow" (bench_twacePow ptmmr) zPow',
+        mkBench "twaceDec" (bench_twaceDec ptmmr) zDec',
+        mkBench "twaceCRT" (bench_twaceCRT ptmmr) zPC',
+        mkBench "embedPow" (bench_embedPow ptmmr) zPow,
+--        mkBench "embedDec" (bench_embedDec ptmmr) zDec,
+        mkBench "embedCRT" (bench_embedCRT ptmmr) zPC] in
+  bgroup "CycRep" benches
+
+pcToEC :: CycRepPC t m r -> CycRepEC t m r
+pcToEC (Right x) = Right x
+
+ecToPC :: CycRepEC t m r -> CycRepPC t m r
+ecToPC (Right x) = Right x
+
+{-# INLINE bench_mul #-}
+bench_mul :: _ => CycRepPC t m r -> CycRepPC t m r -> CycRepEC t m r
+bench_mul a b = pcToEC a * pcToEC b
+
+{-# INLINE bench_crt #-}
+-- convert input from Pow basis to CRT basis
+bench_crt :: _ => CycRep t P m r -> CycRepEC t m r
+bench_crt = toCRT
+
+{-# INLINABLE bench_crtInv #-}
+-- convert input from CRT basis to Pow basis
+-- EAC: This is slow without explicitly mentioning CRTElt. Possibly related to constraint synonym issues?
+bench_crtInv :: _ => CycRepPC t m r -> CycRep t P m r
+bench_crtInv (Right a) = toPow a
+
+{-# INLINE bench_l #-}
+-- convert input from Dec basis to Pow basis
+bench_l :: _ => CycRep t D m r -> CycRep t P m r
+bench_l = toPow
+
+{-# INLINE bench_lInv #-}
+-- convert input from Pow basis to Dec basis
+bench_lInv :: _ => CycRep t P m r -> CycRep t D m r
+bench_lInv = toDec
+
+{-# INLINABLE bench_liftPow #-}
+-- lift an element in the Pow basis
+bench_liftPow :: _ => CycRep t P m r -> CycRep t P m r'
+bench_liftPow = lift
+
+{-# INLINABLE bench_mulgPow #-}
+-- multiply by g when input is in Pow basis
+bench_mulgPow :: _ => CycRep t P m r -> CycRep t P m r
+bench_mulgPow = mulGPow
+
+{-# INLINABLE bench_mulgDec #-}
+-- multiply by g when input is in Dec basis
+bench_mulgDec :: _ => CycRep t D m r -> CycRep t D m r
+bench_mulgDec = mulGDec
+
+{-# INLINABLE bench_mulgCRT #-}
+-- multiply by g when input is in CRT basis
+bench_mulgCRT :: _ => CycRepPC t m r -> CycRep t C m r
+bench_mulgCRT (Right a) = mulGCRTC a
+
+{-# INLINABLE bench_divGPow #-}
+-- divide by g when input is in Pow basis
+bench_divGPow :: _ => CycRep t P m r -> Maybe (CycRep t P m r)
+bench_divGPow = divGPow . mulGPow
+
+{-# INLINABLE bench_divGDec #-}
+-- divide by g when input is in Dec basis
+bench_divGDec :: _ => CycRep t D m r -> Maybe (CycRep t D m r)
+bench_divGDec = divGDec . mulGDec
+
+{-# INLINABLE bench_divGCRT #-}
+-- divide by g when input is in CRT basis
+bench_divGCRT :: _ => CycRepPC t m r -> CycRep t C m r
+bench_divGCRT = either (error "bench_divGCRT expected a CRTC") divGCRTC
+
+{-# INLINABLE bench_errRounded #-}
+-- generate a rounded error term
+bench_errRounded :: forall t m r gen . _
+                 => Proxy '(t,m,r) -> Proxy gen -> Double -> IO (CycRep t D m (LiftOf r))
+bench_errRounded _ _ v = do
+  gen <- newGenIO
+  let e = roundedGaussian v :: Rand (CryptoRand gen) (CycRep t D m (LiftOf r))
+  return $ evalRand e gen
+
+{-# INLINE bench_twacePow #-}
+bench_twacePow :: forall t m m' r . _
+  => Proxy '(t,m,m',r) -> CycRep t P m' r -> CycRep t P m r
+bench_twacePow _ = twacePow
+
+{-# INLINE bench_twaceDec #-}
+bench_twaceDec :: forall t m m' r . _
+  => Proxy '(t,m,m',r) -> CycRep t D m' r -> CycRep t D m r
+bench_twaceDec _ = twaceDec
+
+{-# INLINE bench_twaceCRT #-}
+bench_twaceCRT :: forall t m m' r . _
+  => Proxy '(t,m,m',r) -> CycRepPC t m' r -> CycRepPC t m r
+bench_twaceCRT _ (Right a) = twaceCRTC a
+
+{-# INLINE bench_embedPow #-}
+bench_embedPow :: forall t m m' r . _
+  => Proxy '(t,m,m',r) -> CycRep t P m r -> CycRep t P m' r
+bench_embedPow _ = embedPow
+
+{-
+{-# INLINE bench_embedDec #-}
+bench_embedDec :: forall t m m' r . (Fact m', _)
+  => Proxy '(t,m,m',r) -> CycRep t D m r -> CycRep t D m' r
+bench_embedDec _ = embedDec
+-}
+
+{-# INLINE bench_embedCRT #-}
+bench_embedCRT :: forall t m m' r . _
+  => Proxy '(t,m,m',r) -> CycRepPC t m r -> CycRepPC t m' r
+bench_embedCRT _ (Right a) = embedCRTC a
diff --git a/Crypto/Lol/Benchmarks/Default.hs b/Crypto/Lol/Benchmarks/Default.hs
new file mode 100644
--- /dev/null
+++ b/Crypto/Lol/Benchmarks/Default.hs
@@ -0,0 +1,70 @@
+{-|
+Module      : Crypto.Lol.Benchmarks.Default
+Description : Default high-level benchmarks for 'Crypto.Lol.Cyclotomic.Tensor' implementations.
+Copyright   : (c) Eric Crockett, 2011-2017
+                  Chris Peikert, 2011-2017
+License     : GPL-3
+Maintainer  : ecrockett0@email.com
+Stability   : experimental
+Portability : POSIX
+
+Default high-level benchmarks for 'Crypto.Lol.Cyclotomic.Tensor' implementations.
+-}
+
+{-# LANGUAGE DataKinds             #-}
+{-# LANGUAGE FlexibleContexts      #-}
+{-# LANGUAGE NoStarIsType          #-}
+{-# LANGUAGE PartialTypeSignatures #-}
+{-# LANGUAGE PolyKinds             #-}
+{-# LANGUAGE QuantifiedConstraints #-}
+{-# LANGUAGE ScopedTypeVariables   #-}
+{-# LANGUAGE TypeFamilies          #-}
+{-# LANGUAGE TypeOperators         #-}
+
+{-# OPTIONS_GHC -fno-warn-partial-type-signatures #-}
+
+module Crypto.Lol.Benchmarks.Default
+( defaultLolBenches, oneIdxBenches, twoIdxBenches
+) where
+
+import Crypto.Lol
+import Crypto.Lol.Benchmarks.CycBenches
+import Crypto.Lol.Benchmarks.CycRepBenches
+import Crypto.Lol.Benchmarks.TensorBenches
+import Crypto.Lol.Utils.Benchmarks         (Benchmark, bgroup)
+import Crypto.Lol.Utils.ShowType
+
+import Control.DeepSeq (NFData)
+
+-- | Benchmark parameters reported in the paper. We suggest running these benchmarks
+-- to quickly compare performance on your system or with your
+-- 'Crypto.Lol.Cyclotomic.Tensor' backend.
+{-# INLINABLE defaultLolBenches #-}
+defaultLolBenches ::
+  (forall m r . (Fact m, NFData r) => NFData (t m r), _)
+  => Proxy t -> Proxy h -> [Benchmark]
+defaultLolBenches pt phash = [
+  bgroup "Single Index" $ ($ phash) . ($ pt) <$> [
+    oneIdxBenches (Proxy::Proxy '(F1024,        Zq 12289)),
+    oneIdxBenches (Proxy::Proxy '(F2048,        Zq 12289)),
+    oneIdxBenches (Proxy::Proxy '(F64*F27,      Zq 3457)),
+    oneIdxBenches (Proxy::Proxy '(F64*F81,      Zq 10369)),
+    oneIdxBenches (Proxy::Proxy '(F64*F9*F25,   Zq 14401))],
+  bgroup "Twace-Embed" $ ($ pt) <$> [
+    twoIdxBenches (Proxy::Proxy '(F8*F7*F13,  F32*F7*F13,   Zq 8737)),
+    twoIdxBenches (Proxy::Proxy '(F8*F7*F13,  F8*F5*F7*F13, Zq 14561)),
+    twoIdxBenches (Proxy::Proxy '(F128,       F128*F7*F13,  Zq 23297))]]
+
+-- | Collection of all single-index operations at all levels of the library.
+{-# INLINABLE oneIdxBenches #-}
+oneIdxBenches :: forall t m r gen . _ => Proxy '(m,r) -> Proxy t -> Proxy gen -> Benchmark
+oneIdxBenches _ _ pgen =
+  let ptmr = Proxy :: Proxy '(t,m,r)
+  in bgroup (showType ptmr) $ ($ pgen) . ($ ptmr) <$> [tensorBenches1, cycRepBenches1, cycBenches1]
+
+-- | Collection of all inter-ring operations at all levels of the library.
+{-# INLINABLE twoIdxBenches #-}
+twoIdxBenches :: forall t m m' r . _ => Proxy '(m,m',r) -> Proxy t -> Benchmark
+twoIdxBenches _ _ =
+  let ptmr = Proxy :: Proxy '(t,m,m',r)
+  in bgroup (showType ptmr) $ ($ ptmr) <$> [tensorBenches2, cycRepBenches2, cycBenches2]
diff --git a/Crypto/Lol/Benchmarks/TensorBenches.hs b/Crypto/Lol/Benchmarks/TensorBenches.hs
new file mode 100644
--- /dev/null
+++ b/Crypto/Lol/Benchmarks/TensorBenches.hs
@@ -0,0 +1,167 @@
+{-|
+Module      : Crypto.Lol.Benchmarks.TensorBenches
+Description : Benchmarks for the 'Tensor' interface.
+Copyright   : (c) Eric Crockett, 2011-2017
+                  Chris Peikert, 2011-2017
+License     : GPL-3
+Maintainer  : ecrockett0@email.com
+Stability   : experimental
+Portability : POSIX
+
+Benchmarks for the 'Tensor' interface. In a perfect world, these benchmarks would
+have the same performance as the 'Cyc' benchmarks. In practice, GHC gets in the
+way at higher levels of the library, resulting in worse performance for 'Cyc'
+in some cases.
+-}
+
+{-# LANGUAGE DataKinds             #-}
+{-# LANGUAGE FlexibleContexts      #-}
+{-# LANGUAGE NoImplicitPrelude     #-}
+{-# LANGUAGE PartialTypeSignatures #-}
+{-# LANGUAGE ScopedTypeVariables   #-}
+{-# LANGUAGE TypeFamilies          #-}
+
+{-# OPTIONS_GHC -fno-warn-partial-type-signatures #-}
+
+module Crypto.Lol.Benchmarks.TensorBenches (tensorBenches1, tensorBenches2) where
+
+import Control.Applicative
+import Control.Monad.Random hiding (lift)
+
+import Crypto.Lol.Cyclotomic.Tensor
+import Crypto.Lol.Prelude
+import Crypto.Lol.Types
+import Crypto.Lol.Types.IFunctor
+import Crypto.Lol.Utils.Benchmarks  (Benchmark, bgroup, mkBench, mkBenchIO)
+import Crypto.Random
+
+-- must come after imports
+{-# ANN module "HLint: ignore Use camelCase" #-}
+
+-- | Benchmarks for single-index 'Tensor' operations.
+-- There must be a CRT basis for \(O_m\) over @r@.
+-- These cover the same functions as @cycBenches1@, but may have different
+-- performance due to how GHC interacts with Lol.
+{-# INLINABLE tensorBenches1 #-}
+tensorBenches1 :: forall (t :: Factored -> * -> *) (m :: Factored) (r :: *) gen . (Fact m, _)
+               => Proxy '(t,m,r) -> Proxy gen -> Benchmark
+tensorBenches1 ptmr pgen =
+    let z = zero :: t m r
+        errorBench = mkBenchIO "error" (bench_errRounded ptmr pgen 0.1)
+        benches = ($ z) <$> [
+          mkBench "zipWith (*)" (bench_mul z),
+          mkBench "crt" bench_crt,
+          mkBench "crtInv" bench_crtInv,
+          mkBench "decToPow" bench_decToPow,
+          mkBench "powToDec" bench_powToDec,
+          mkBench "*g Pow" bench_mulGPow,
+          mkBench "*g Dec" bench_mulGDec,
+          mkBench "*g CRT" bench_mulGCRT,
+          mkBench "divG Pow" bench_divGPow,
+          mkBench "divG Dec" bench_divGDec,
+          mkBench "divG CRT" bench_divGCRT,
+          mkBench "lift" bench_lift] in
+    bgroup "Tensor" (benches ++ [errorBench])
+
+-- | Benchmarks for inter-ring 'Tensor' operations.
+-- There must be a CRT basis for \(O_{m'}\) over @r@.
+-- These cover the same functions as @cycBenches1@, but may have different
+-- performance due to how GHC interacts with Lol.
+{-# INLINABLE tensorBenches2 #-}
+tensorBenches2 :: forall (t :: Factored -> * -> *) (m :: Factored) (m' :: Factored) (r :: *) . _
+  => Proxy '(t,m,m',r) -> Benchmark
+tensorBenches2 ptmmr =
+  let z = zero :: t m r
+      z' = zero :: t m' r
+      benches = [
+        mkBench "twacePow" (bench_twacePow ptmmr) z',
+        mkBench "twaceDec" (bench_twacePow ptmmr) z', -- yes, twacePow is correct here. It's the same function!
+        mkBench "twaceCRT" (bench_twaceCRT ptmmr) z',
+        mkBench "embedPow" (bench_embedPow ptmmr) z,
+        mkBench "embedCRT" (bench_embedCRT ptmmr) z] in
+  bgroup "Tensor" benches
+
+{-# INLINABLE bench_mul #-}
+-- no CRT conversion, just coefficient-wise multiplication
+bench_mul :: _ => t m r -> t m r -> t m r
+bench_mul = zipWithI (*)
+
+{-# INLINABLE bench_crt #-}
+-- convert input from Pow basis to CRT basis
+bench_crt :: _ => t m r -> t m r
+bench_crt = fromJust' "TensorBenches.bench_crt" crt
+
+{-# INLINABLE bench_crtInv #-}
+-- convert input from CRT basis to Pow basis
+bench_crtInv :: _ => t m r -> t m r
+bench_crtInv = fromJust' "TensorBenches.bench_crtInv" crtInv
+
+{-# INLINABLE bench_decToPow #-}
+-- convert input from Dec basis to Pow basis
+bench_decToPow :: _ => t m r -> t m r
+bench_decToPow = decToPow
+
+{-# INLINABLE bench_powToDec #-}
+-- convert input from Dec basis to Pow basis
+bench_powToDec :: _ => t m r -> t m r
+bench_powToDec = powToDec
+
+{-# INLINABLE bench_lift #-}
+bench_lift :: _ => t m r -> t m r'
+bench_lift = fmapI lift
+
+{-# INLINABLE bench_mulGPow #-}
+-- multiply by g when input is in Pow basis
+bench_mulGPow :: _ => t m r -> t m r
+bench_mulGPow = mulGPow
+
+{-# INLINABLE bench_mulGDec #-}
+-- multiply by g when input is in Dec basis
+bench_mulGDec :: _ => t m r -> t m r
+bench_mulGDec = mulGDec
+
+{-# INLINABLE bench_mulGCRT #-}
+-- multiply by g when input is in CRT basis
+bench_mulGCRT :: _ => t m r -> t m r
+bench_mulGCRT = fromJust' "TensorBenches.bench_mulGCRT" mulGCRT
+
+{-# INLINABLE bench_divGPow #-}
+-- divide by g when input is in Pow basis
+bench_divGPow :: _ => t m r -> Maybe (t m r)
+bench_divGPow = divGPow . mulGPow
+
+{-# INLINABLE bench_divGDec #-}
+-- divide by g when input is in Dec basis
+bench_divGDec :: _ => t m r -> Maybe (t m r)
+bench_divGDec = divGDec . mulGDec
+
+{-# INLINABLE bench_divGCRT #-}
+-- divide by g when input is in CRT basis
+bench_divGCRT :: _ => t m r -> t m r
+bench_divGCRT = fromJust' "TensorBenches.bench_divGCRT" divGCRT
+
+{-# INLINABLE bench_errRounded #-}
+-- generate a rounded error term
+bench_errRounded :: forall t m r gen . (Fact m, CryptoRandomGen gen, TensorPowDec t r, _)
+  => Proxy '(t,m,r) -> Proxy gen -> Double -> IO (t m (LiftOf r))
+bench_errRounded _ _ v =
+  evalRand
+  (fmapI (roundMult one) <$>
+    (tweakedGaussianDec v :: Rand (CryptoRand gen) (t m Double)) :: Rand (CryptoRand gen)
+                                                                         (t m (LiftOf r))) <$> newGenIO
+
+{-# INLINABLE bench_twacePow #-}
+bench_twacePow :: forall t m m' r . _ => Proxy '(t,m,m',r) -> t m' r -> t m r
+bench_twacePow _ = twacePowDec
+
+{-# INLINABLE bench_twaceCRT #-}
+bench_twaceCRT :: forall t m m' r . _ => Proxy '(t,m,m',r) -> t m' r -> t m r
+bench_twaceCRT _ = fromJust' "TensorBenches.bench_twaceCRT" twaceCRT
+
+{-# INLINABLE bench_embedPow #-}
+bench_embedPow :: forall t m m' r . _ => Proxy '(t,m,m',r) -> t m r -> t m' r
+bench_embedPow _ = embedPow
+
+{-# INLINABLE bench_embedCRT #-}
+bench_embedCRT :: forall t m m' r . _ => Proxy '(t,m,m',r) -> t m r -> t m' r
+bench_embedCRT _ = fromJust' "TensorBenches.bench_embedCRT" embedCRT
diff --git a/Crypto/Lol/CRTrans.hs b/Crypto/Lol/CRTrans.hs
--- a/Crypto/Lol/CRTrans.hs
+++ b/Crypto/Lol/CRTrans.hs
@@ -3,7 +3,7 @@
 Description : Functions related to the Chinese Remainder Transform.
 Copyright   : (c) Eric Crockett, 2011-2017
                   Chris Peikert, 2011-2017
-License     : GPL-2
+License     : GPL-3
 Maintainer  : ecrockett0@email.com
 Stability   : experimental
 Portability : POSIX
@@ -14,12 +14,14 @@
 and ring extensions.
 -}
 
+{-# LANGUAGE ConstraintKinds       #-}
 {-# LANGUAGE FlexibleContexts      #-}
 {-# LANGUAGE FlexibleInstances     #-}
 {-# LANGUAGE MultiParamTypeClasses #-}
 {-# LANGUAGE PolyKinds             #-}
 {-# LANGUAGE RebindableSyntax      #-}
 {-# LANGUAGE ScopedTypeVariables   #-}
+{-# LANGUAGE TypeApplications      #-}
 {-# LANGUAGE TypeFamilies          #-}
 
 module Crypto.Lol.CRTrans
@@ -31,6 +33,7 @@
 import Crypto.Lol.Reflects
 
 import Control.Arrow
+import Control.Monad.Identity
 
 -- | Information that characterizes the (invertible) Chinese remainder
 -- transformation over a ring \(R\) (represented by the type @r@), namely:
@@ -52,7 +55,6 @@
 -- it should be the case that \(\omega_{m'}^{m'/m}=\omega_m\).
 
 class (Monad mon, Ring r) => CRTrans mon r where
-
   -- | 'CRTInfo' for a given index \(m\). The method itself may be
   -- slow, but the function it returns should be fast, e.g., via
   -- internal memoization.
@@ -82,12 +84,17 @@
   fromExt = fromExt *** fromExt
 
 -- | Complex numbers have 'CRTrans' for any index \(m\)
-instance (Monad mon, Transcendental a) => CRTrans mon (Complex a) where
+instance (Transcendental a) => CRTrans Identity (Complex a) where
   crtInfo = crtInfoC
 
+-- | For testing ergonomics, we also have a 'Maybe' instance of 'CRTrans'
+-- for complex numbers.
+instance (Transcendental a) => CRTrans Maybe (Complex a) where
+  crtInfo = crtInfoC
+
 crtInfoC :: forall mon m a . (Monad mon, Reflects m Int, Transcendental a)
             => TaggedT m mon (CRTInfo (Complex a))
-crtInfoC = let mval = proxy value (Proxy::Proxy m)
+crtInfoC = let mval = value @m
                mhat = valueHat mval
            in return (omegaPowC mval, recip $ fromIntegral mhat)
 
@@ -101,13 +108,21 @@
   fromExt = id
 
 -- | Returns 'Nothing'
-instance CRTrans Maybe Double where crtInfo = tagT Nothing
+instance CRTrans Maybe Double where
+  crtInfo = tagT Nothing
+
 -- | Returns 'Nothing'
-instance CRTrans Maybe Int where crtInfo = tagT Nothing
+instance CRTrans Maybe Int where
+  crtInfo = tagT Nothing
+
 -- | Returns 'Nothing'
-instance CRTrans Maybe Int64 where crtInfo = tagT Nothing
+instance CRTrans Maybe Int64 where
+  crtInfo = tagT Nothing
+
 -- | Returns 'Nothing'
-instance CRTrans Maybe Integer where crtInfo = tagT Nothing
+instance CRTrans Maybe Integer where
+  crtInfo = tagT Nothing
+
 -- can also do for Int8, Int16, Int32 etc.
 
 -- | Embeds into the complex numbers \(\C\).
diff --git a/Crypto/Lol/Cyclotomic/CRTSentinel.hs b/Crypto/Lol/Cyclotomic/CRTSentinel.hs
--- a/Crypto/Lol/Cyclotomic/CRTSentinel.hs
+++ b/Crypto/Lol/Cyclotomic/CRTSentinel.hs
@@ -4,8 +4,8 @@
               over a base ring, or over its extension ring.
 Copyright   : (c) Eric Crockett, 2011-2017
                   Chris Peikert, 2011-2017
-License     : GPL-2
-Maintainer  : ecrockett0@email.com
+License     : GPL-3
+Maintainer  : ecrockett0@gmail.com
 Stability   : experimental
 Portability : POSIX
 
@@ -19,6 +19,7 @@
 {-# LANGUAGE MultiParamTypeClasses #-}
 {-# LANGUAGE PolyKinds             #-}
 {-# LANGUAGE ScopedTypeVariables   #-}
+{-# LANGUAGE TypeApplications      #-}
 {-# LANGUAGE TypeFamilies          #-}
 {-# LANGUAGE TypeOperators         #-}
 
@@ -29,43 +30,40 @@
 , embedCRTCS, twaceCRTCS
 ) where
 
-import Data.Functor.Trans.Tagged
+import Data.Functor
 import Data.Maybe
-import Data.Proxy
 
-import Crypto.Lol.CRTrans
 import Crypto.Lol.Cyclotomic.Tensor
 import Crypto.Lol.Factored
 
-data CSentinel t m r = CSentinel
-data ESentinel t m r = ESentinel
+data CSentinel t m r = CSentinel deriving (Eq, Show)
+data ESentinel t m r = ESentinel deriving (Eq, Show)
 
-crtSentinel :: (Tensor t, Fact m, CRTrans Maybe r, TElt t r)
+crtSentinel :: (TensorCRT t Maybe r, Fact m)
                => Either (ESentinel t m r) (CSentinel t m r)
-crtSentinel = fromMaybe (Left ESentinel) (Right <$> crtCSentinel)
+crtSentinel = maybe (Left ESentinel) Right crtCSentinel
 {-# INLINABLE crtSentinel #-}
 
 crtCSentinel :: forall t m r .
-                (Tensor t, Fact m, CRTrans Maybe r, TElt t r)
+                (TensorCRT t Maybe r, Fact m)
                 => Maybe (CSentinel t m r)
-crtCSentinel = proxyT hasCRTFuncs (Proxy::Proxy (t m r)) *>
-               pure CSentinel
+crtCSentinel = hasCRTFuncs @t @m @r $> CSentinel
 {-# INLINABLE crtCSentinel #-}
 
-crtESentinel :: (Tensor t, Fact m, CRTrans Maybe r, TElt t r)
+crtESentinel :: (TensorCRT t Maybe r, Fact m)
                 => Maybe (ESentinel t m r)
 crtESentinel = case crtSentinel of
   Left  s -> Just s
   Right _ -> Nothing
 {-# INLINABLE crtESentinel #-}
 
-scalarCRTCS :: (Tensor t, Fact m, CRTrans Maybe r, TElt t r)
+scalarCRTCS :: (TensorCRT t Maybe r, Fact m)
               => CSentinel t m r -> r -> t m r
 scalarCRTCS _ = fromJust scalarCRT
 {-# INLINABLE scalarCRTCS #-}
 
 crtCS, crtInvCS, mulGCRTCS, divGCRTCS ::
-  (Tensor t, Fact m, CRTrans Maybe r, TElt t r)
+  (TensorCRT t Maybe r, Fact m)
   => CSentinel t m r -> t m r -> t m r
 
 crtCS     _ = fromJust crt
@@ -78,12 +76,12 @@
 {-# INLINABLE mulGCRTCS #-}
 {-# INLINABLE divGCRTCS #-}
 
-embedCRTCS :: (Tensor t, m `Divides` m', CRTrans Maybe r, TElt t r)
+embedCRTCS :: (TensorCRT t Maybe r, m `Divides` m')
               => CSentinel t m r -> CSentinel t m' r -> t m r -> t m' r
 embedCRTCS _ _ = fromJust embedCRT
 {-# INLINABLE embedCRTCS #-}
 
-twaceCRTCS :: (Tensor t, m `Divides` m', CRTrans Maybe r, TElt t r)
+twaceCRTCS :: (TensorCRT t Maybe r, m `Divides` m')
               => CSentinel t m' r -> CSentinel t m r -> t m' r -> t m r
 twaceCRTCS _ _ = fromJust twaceCRT
 {-# INLINE twaceCRTCS #-}
diff --git a/Crypto/Lol/Cyclotomic/Cyc.hs b/Crypto/Lol/Cyclotomic/Cyc.hs
--- a/Crypto/Lol/Cyclotomic/Cyc.hs
+++ b/Crypto/Lol/Cyclotomic/Cyc.hs
@@ -1,640 +1,1113 @@
 {-|
 Module      : Crypto.Lol.Cyclotomic.Cyc
-Description : An implementation of cyclotomic rings that hides the
-              internal representations of ring elements.
-Copyright   : (c) Eric Crockett, 2011-2017
-                  Chris Peikert, 2011-2017
-License     : GPL-2
-Maintainer  : ecrockett0@email.com
-Stability   : experimental
-Portability : POSIX
-
-  \( \def\Z{\mathbb{Z}} \)
-  \( \def\F{\mathbb{F}} \)
-  \( \def\Q{\mathbb{Q}} \)
-  \( \def\Tw{\text{Tw}} \)
-  \( \def\Tr{\text{Tr}} \)
-  \( \def\O{\mathcal{O}} \)
-
-An implementation of cyclotomic rings that hides the
-internal representations of ring elements (e.g., the choice of
-basis), and also offers more efficient storage and operations on
-subring elements (including elements from the base ring itself).
-
-For an implementation that allows (and requires) the programmer to
-control the underlying representation, see
-"Crypto.Lol.Cyclotomic.UCyc".
-
-__WARNING:__ as with all fixed-point arithmetic, the functions
-associated with 'Cyc' may result in overflow (and thereby
-incorrect answers and potential security flaws) if the input
-arguments are too close to the bounds imposed by the base type.
-The acceptable range of inputs for each function is determined by
-the internal linear transforms and other operations it performs.
--}
-
-{-# LANGUAGE ConstraintKinds       #-}
-{-# LANGUAGE DataKinds             #-}
-{-# LANGUAGE FlexibleContexts      #-}
-{-# LANGUAGE FlexibleInstances     #-}
-{-# LANGUAGE GADTs                 #-}
-{-# LANGUAGE MultiParamTypeClasses #-}
-{-# LANGUAGE NoImplicitPrelude     #-}
-{-# LANGUAGE PolyKinds             #-}
-{-# LANGUAGE RankNTypes            #-}
-{-# LANGUAGE ScopedTypeVariables   #-}
-{-# LANGUAGE TypeFamilies          #-}
-{-# LANGUAGE TypeOperators         #-}
-{-# LANGUAGE UndecidableInstances  #-}
-
-
-
-module Crypto.Lol.Cyclotomic.Cyc
-(
--- * Data type and constraints
-  Cyc, CElt, U.NFElt
--- * Constructors/deconstructors
-, scalarCyc
-, cycPow, cycDec, cycCRT, cycCRTC, cycCRTE, cycPC, cycPE
-, uncycPow, uncycDec, uncycCRT, unzipCyc
--- * Core cyclotomic operations
-, mulG, divG, gSqNorm, liftCyc, liftPow, liftDec
--- * Representation advice
-, advisePow, adviseDec, adviseCRT
--- * Error sampling
-, tGaussian, errorRounded, errorCoset
--- * Sub/extension rings
-, embed, twace, coeffsCyc, coeffsPow, coeffsDec, powBasis, crtSet
-) where
-
-import qualified Algebra.Additive     as Additive (C)
-import qualified Algebra.Module       as Module (C)
-import qualified Algebra.Ring         as Ring (C)
-import qualified Algebra.ZeroTestable as ZeroTestable (C)
-
-import Crypto.Lol.Cyclotomic.UCyc hiding (coeffsDec, coeffsPow, crtSet,
-                                   errorCoset, errorRounded, gSqNorm, mulG,
-                                   powBasis, tGaussian)
-
-import           Crypto.Lol.CRTrans
-import qualified Crypto.Lol.Cyclotomic.RescaleCyc as R
-import           Crypto.Lol.Cyclotomic.Tensor     (TElt, Tensor)
-import qualified Crypto.Lol.Cyclotomic.UCyc       as U
-import           Crypto.Lol.Gadget
-import           Crypto.Lol.Prelude               as LP
-import           Crypto.Lol.Types.FiniteField
-import           Crypto.Lol.Types.Proto
-import           Crypto.Lol.Types.ZPP
-
-import Control.Applicative hiding ((*>))
-import Control.Arrow
-import Control.DeepSeq
--- GHC warning is wrong: https://ghc.haskell.org/trac/ghc/ticket/12067
-import Control.Monad.Identity
-import Control.Monad.Random hiding (lift)
-import Data.Coerce
-import Data.Traversable
-
--- | Represents a cyclotomic ring such as \(\Z[\zeta_m]\),
--- \(\Z_q[\zeta_m]\), and \(\Q[\zeta_m]\) in an explicit
--- representation: @t@ is the
--- 'Tensor' type for storing coefficient tensors; @m@ is the
--- cyclotomic index; @r@ is the base ring of the coefficients (e.g.,
--- \(\Z\), \(\Z_q\)).
-data Cyc t m r where
-  Pow :: !(UCyc t m P r) -> Cyc t m r
-  Dec :: !(UCyc t m D r) -> Cyc t m r
-  CRT :: !(UCycEC t m r) -> Cyc t m r
-  -- super-optimized storage of scalars
-  Scalar :: !r -> Cyc t m r
-  -- optimized storage of subring elements
-  Sub :: (l `Divides` m) => !(Cyc t l r) -> Cyc t m r
-  -- CJP: someday try to merge the above two
-
--- | Constraints needed for most operations involving 'Cyc' data.
-type CElt t r = (UCRTElt t r, ZeroTestable r)
-
----------- Constructors / deconstructors ----------
-
--- | Wrap a 'UCyc' as a 'Cyc'.
-cycPow :: UCyc t m P r -> Cyc t m r
-cycPow = Pow
-{-# INLINABLE cycPow #-}
-
--- | Wrap a 'UCyc' as a 'Cyc'.
-cycDec :: UCyc t m D r -> Cyc t m r
-cycDec = Dec
-{-# INLINABLE cycDec #-}
-
--- | Wrap a 'UCycEC' as a 'Cyc'.
-cycCRT :: UCycEC t m r -> Cyc t m r
-cycCRT = CRT
-{-# INLINABLE cycCRT #-}
-
--- | Wrap a 'UCyc' as a 'Cyc'.
-cycCRTC :: UCyc t m C r -> Cyc t m r
-cycCRTC = CRT . Right
-{-# INLINABLE cycCRTC #-}
-
--- | Wrap a 'UCyc' as a 'Cyc'.
-cycCRTE :: UCyc t m E r -> Cyc t m r
-cycCRTE = CRT . Left
-{-# INLINABLE cycCRTE #-}
-
--- | Convenience wrapper.
-cycPC :: Either (UCyc t m P r) (UCyc t m C r) -> Cyc t m r
-cycPC = either Pow (CRT . Right)
-{-# INLINABLE cycPC #-}
-
--- | Convenience wrapper.
-cycPE :: Either (UCyc t m P r) (UCyc t m E r) -> Cyc t m r
-cycPE = either Pow (CRT . Left)
-{-# INLINABLE cycPE #-}
-
--- | Embed a scalar from the base ring as a cyclotomic element.
-scalarCyc :: r -> Cyc t m r
-scalarCyc = Scalar
-{-# INLINABLE scalarCyc #-}
-
--- | Unwrap a 'Cyc' as a 'UCyc' in powerful-basis representation.
-uncycPow :: (Fact m, CElt t r) => Cyc t m r -> UCyc t m P r
-{-# INLINABLE uncycPow #-}
-uncycPow c = let (Pow u) = toPow' c in u
-
--- | Unwrap a 'Cyc' as a 'UCyc' in decoding-basis representation.
-uncycDec :: (Fact m, CElt t r) => Cyc t m r -> UCyc t m D r
-{-# INLINABLE uncycDec #-}
-uncycDec c = let (Dec u) = toDec' c in u
-
--- | Unwrap a 'Cyc' as a 'UCyc' in a CRT-basis representation.
-uncycCRT :: (Fact m, CElt t r) => Cyc t m r -> UCycEC t m r
-{-# INLINABLE uncycCRT #-}
-uncycCRT c = let (CRT u) = toCRT' c in u
-
----------- Algebraic instances ----------
-
-instance (Fact m, CElt t r) => ZeroTestable.C (Cyc t m r) where
-  isZero (Pow u) = isZero u
-  isZero (Dec u) = isZero u
-  isZero (CRT (Right u)) = isZero u
-  isZero c@(CRT _) = isZero $ toPow' c
-  isZero (Scalar c) = isZero c
-  isZero (Sub c) = isZero c
-  {-# INLINABLE isZero #-}
-
-instance (Eq r, Fact m, CElt t r) => Eq (Cyc t m r) where
-  -- same representations
-  (Scalar c1) == (Scalar c2) = c1 == c2
-  (Pow u1) == (Pow u2) = u1 == u2
-  (Dec u1) == (Dec u2) = u1 == u2
-  (CRT (Right u1)) == (CRT (Right u2)) = u1 == u2
-  -- compare Subs in compositum
-  -- EAC: would like to convert c2 to basis of c1 before embedding
-  (Sub (c1 :: Cyc t l1 r)) == (Sub (c2 :: Cyc t l2 r)) =
-    (embed' c1 :: Cyc t (FLCM l1 l2) r) == embed' c2
-    \\ lcmDivides (Proxy::Proxy l1) (Proxy::Proxy l2)
-
-  -- some other relatively efficient comparisons
-  (Scalar c1) == (Pow u2) = scalarPow c1 == u2
-  (Pow u1) == (Scalar c2) = u1 == scalarPow c2
-
-  -- otherwise: compare in powerful basis
-  c1 == c2 = toPow' c1 == toPow' c2
-
-  {-# INLINABLE (==) #-}
-
-instance (Fact m, CElt t r) => Additive.C (Cyc t m r) where
-  {-# INLINABLE zero #-}
-  zero = Scalar zero
-
-  {-# INLINABLE (+) #-}
-  -- optimized addition of zero
-  (Scalar c1) + c2 | isZero c1 = c2
-  c1 + (Scalar c2) | isZero c2 = c1
-
-  -- SAME CONSTRUCTORS
-  (Scalar c1) + (Scalar c2) = Scalar (c1+c2)
-  (Pow u1) + (Pow u2) = Pow $ u1 + u2
-  (Dec u1) + (Dec u2) = Dec $ u1 + u2
-  (CRT u1) + (CRT u2) = CRT $ u1 + u2
-  -- Sub plus Sub: work in compositum
-  -- EAC: would like to convert c2 to basis of c1 before embedding
-  (Sub (c1 :: Cyc t m1 r)) + (Sub (c2 :: Cyc t m2 r)) =
-    (Sub $ (embed' c1 :: Cyc t (FLCM m1 m2) r) + embed' c2)
-    \\ lcm2Divides (Proxy::Proxy m1) (Proxy::Proxy m2) (Proxy::Proxy m)
-
-  -- SCALAR PLUS SOMETHING ELSE
-
-  (Scalar c) + (Pow u) = Pow $ scalarPow c + u
-  (Scalar c) + (Dec u) = Pow $ scalarPow c + toPow u -- workaround scalarDec
-  (Scalar c) + (CRT u) = CRT $ scalarCRT c + u
-  (Scalar c1) + (Sub c2) = Sub $ Scalar c1 + c2 -- must re-wrap Scalar!
-
-  (Pow u) + (Scalar c) = Pow $ u + scalarPow c
-  (Dec u) + (Scalar c) = Pow $ toPow u + scalarPow c -- workaround scalarDec
-  (CRT u) + (Scalar c) = CRT $ u + scalarCRT c
-  (Sub c1) + (Scalar c2) = Sub $ c1 + Scalar c2
-
-  -- SUB PLUS NON-SUB, NON-SCALAR: work in full ring
-  -- EAC: would like to convert sub to basis of other before embedding
-  (Sub c1) + c2 = embed' c1 + c2
-  c1 + (Sub c2) = c1 + embed' c2
-
-  -- mixed Dec and Pow: use linear-time conversions
-  (Dec u1) + (Pow u2) = Pow $ toPow u1 + u2
-  (Pow u1) + (Dec u2) = Pow $ u1 + toPow u2
-
-  -- one CRT: convert other to CRT
-  (CRT u1) + (Pow u2) = CRT $ u1 + toCRT u2
-  (CRT u1) + (Dec u2) = CRT $ u1 + toCRT u2
-  (Pow u1) + (CRT u2) = CRT $ toCRT u1 + u2
-  (Dec u1) + (CRT u2) = CRT $ toCRT u1 + u2
-
-  {-# INLINABLE negate #-}
-  negate (Pow u) = Pow $ negate u
-  negate (Dec u) = Dec $ negate u
-  negate (CRT u) = CRT $ negate u
-  negate (Scalar c) = Scalar (negate c)
-  negate (Sub c) = Sub $ negate c
-
-instance (Fact m, CElt t r) => Ring.C (Cyc t m r) where
-  {-# INLINABLE one #-}
-  one = Scalar one
-
-  {-# INLINABLE fromInteger #-}
-  fromInteger = Scalar . fromInteger
-
-  {-# INLINABLE (*) #-}
-
-  -- optimized mul-by-zero
-  v1@(Scalar c1) * _ | isZero c1 = v1
-  _ * v2@(Scalar c2) | isZero c2 = v2
-
-  -- both CRT: if over C, then convert result to pow for precision reasons
-  (CRT u1) * (CRT u2) = either (Pow . toPow) (CRT . Right) $ u1*u2
-
-  -- at least one Scalar
-  (Scalar c1) * (Scalar c2) = Scalar $ c1*c2
-  (Scalar c) * (Pow u) = Pow $ c *> u
-  (Scalar c) * (Dec u) = Dec $ c *> u
-  (Scalar c) * (CRT u) = CRT $ c *> u
-  (Scalar c1) * (Sub c2) = Sub $ Scalar c1 * c2
-
-  (Pow u) * (Scalar c) = Pow $ c *> u
-  (Dec u) * (Scalar c) = Dec $ c *> u
-  (CRT u) * (Scalar c) = CRT $ c *> u
-  (Sub c1) * (Scalar c2) = Sub $ c1 * Scalar c2
-
-  -- TWO SUBS: work in a CRT rep for compositum
-  (Sub (c1 :: Cyc t m1 r)) * (Sub (c2 :: Cyc t m2 r)) =
-    -- re-wrap c1, c2 as Subs of the composition, and force them to CRT
-    (Sub $ (toCRT' $ Sub c1 :: Cyc t (FLCM m1 m2) r) * toCRT' (Sub c2))
-    \\ lcm2Divides (Proxy::Proxy m1) (Proxy::Proxy m2) (Proxy::Proxy m)
-
-  -- ELSE: work in appropriate CRT rep
-  c1 * c2 = toCRT' c1 * toCRT' c2
-
--- | \(R_p\) is an \(\F_{p^d}\)-module when \(d\) divides \(\varphi(m)\), by
--- applying \(d\)-dimensional \(\F_p\)-linear transform on \(d\)-dim chunks of
--- powerful basis coeffs.
-instance (GFCtx fp d, Fact m, CElt t fp) => Module.C (GF fp d) (Cyc t m fp) where
-  -- CJP: optimize for Scalar if we can: r *> (Scalar c) is the tensor
-  -- that has the coeffs of (r*c), followed by zeros.  (This assumes
-  -- that the powerful basis has 1 as its first element, and that
-  -- we're using pow to define the module mult.)
-
-  -- can use any r-basis to define module mult, but must be
-  -- consistent.
-  r *> (Pow v) = Pow $ r LP.*> v
-  r *> x = r *> toPow' x
-
----------- Core cyclotomic operations ----------
-
-advisePow, adviseDec, adviseCRT :: (Fact m, CElt t r) => Cyc t m r -> Cyc t m r
-{-# INLINABLE advisePow #-}
-{-# INLINABLE adviseDec #-}
-{-# INLINABLE adviseCRT #-}
-
--- | Same as 'adviseCRT', but for the powerful-basis representation.
-advisePow = toPow'
-
--- | Same as 'adviseCRT', but for the powerful-basis representation.
-adviseDec = toDec'
-
--- | Yield an equivalent element that /may/ be in a CRT
--- representation.  This can serve as an optimization hint. E.g.,
--- call 'adviseCRT' prior to multiplying the same value by many
--- other values.
-adviseCRT = toCRT'
-
--- | Multiply by the special element \(g\) of the \(m\)th
--- cyclotomic.
-mulG :: (Fact m, CElt t r) => Cyc t m r -> Cyc t m r
-{-# INLINABLE mulG #-}
-mulG (Pow u) = Pow $ U.mulG u
-mulG (Dec u) = Dec $ U.mulG u
-mulG (CRT u) = CRT $ either (Left . U.mulG) (Right . U.mulG) u
-mulG c@(Scalar _) = mulG $ toCRT' c
-mulG (Sub c) = mulG $ embed' c   -- must go to full ring
-
--- | Divide by \(g\), returning 'Nothing' if not evenly divisible.
--- WARNING: this implementation is not a constant-time algorithm, so
--- information about the argument may be leaked through a timing
--- channel.
-divG :: (Fact m, CElt t r, IntegralDomain r)
-        => Cyc t m r -> Maybe (Cyc t m r)
-{-# INLINABLE divG #-}
-divG (Pow u) = Pow <$> U.divGPow u
-divG (Dec u) = Dec <$> U.divGDec u
-divG (CRT (Left u)) = Pow <$> U.divGPow (U.toPow u)
-divG (CRT (Right u)) = Just $ (CRT . Right) $ U.divGCRTC u
-divG c@(Scalar _) = divG $ toCRT' c
-divG (Sub c) = divG $ embed' c  -- must go to full ring
-
--- | Sample from the "tweaked" Gaussian error distribution \(t\cdot D\) in
--- the decoding basis, where \(D\) has scaled variance \(v\).
-tGaussian :: (Fact m, OrdFloat q, Random q, Tensor t, TElt t q,
-              ToRational v, MonadRandom rnd)
-             => v -> rnd (Cyc t m q)
-tGaussian = (Dec <$>) . U.tGaussian
-{-# INLINABLE tGaussian #-}
-
--- | Yield the scaled squared norm of \(g_m \cdot e\) under
--- the canonical embedding, namely,
--- \(\hat{m}^{-1} \cdot \| \sigma(g_m \cdot e) \|^2\).
-gSqNorm :: forall t m r . (Fact m, CElt t r) => Cyc t m r -> r
-{-# INLINABLE gSqNorm #-}
-gSqNorm (Dec u) = U.gSqNorm u
-gSqNorm c = gSqNorm $ toDec' c
-
--- | Generate an LWE error term with given scaled variance,
--- deterministically rounded with respect to the decoding basis.
--- (Note: This
--- implementation uses 'Double' precision to generate the Gaussian
--- sample, which may not be sufficient for rigorous proof-based
--- security.)
-errorRounded :: (ToInteger z, Tensor t, Fact m, TElt t z,
-                 ToRational v, MonadRandom rnd) => v -> rnd (Cyc t m z)
-{-# INLINABLE errorRounded #-}
-errorRounded = (Dec <$>) . U.errorRounded
-
--- | Generate an LWE error term with given scaled variance \(v \cdot p^2\) over
--- the given coset, deterministically rounded with respect to the
--- decoding basis. (Note: This
--- implementation uses 'Double' precision to generate the Gaussian
--- sample, which may not be sufficient for rigorous proof-based
--- security.)
-errorCoset ::
-  (Mod zp, z ~ ModRep zp, Lift zp z, Fact m,
-   CElt t zp, ToRational v, MonadRandom rnd)
-  => v -> Cyc t m zp -> rnd (Cyc t m z)
-errorCoset v = (Dec <$>) . U.errorCoset v . uncycDec
-{-# INLINABLE errorCoset #-}
-
----------- Inter-ring operations ----------
-
--- | Embed (lazily) into an extension ring.
-embed :: forall t m m' r . (m `Divides` m') => Cyc t m r -> Cyc t m' r
-{-# INLINABLE embed #-}
-embed (Scalar c) = Scalar c           -- keep as scalar
-embed (Sub (c :: Cyc t l r)) = Sub c  -- keep as subring element
-  \\ transDivides (Proxy::Proxy l) (Proxy::Proxy m) (Proxy::Proxy m')
-embed c = Sub c
-
--- | Force to a non-'Sub' constructor (for internal use only).
-embed' :: forall t r l m . (l `Divides` m, CElt t r) => Cyc t l r -> Cyc t m r
-{-# INLINE embed' #-}
-embed' (Pow u) = Pow $ embedPow u
-embed' (Dec u) = Dec $ embedDec u
-embed' (CRT u) = either (cycPE . embedCRTE) (cycPC . embedCRTC) u
-embed' (Scalar c) = Scalar c
-embed' (Sub (c :: Cyc t k r)) = embed' c
-  \\ transDivides (Proxy::Proxy k) (Proxy::Proxy l) (Proxy::Proxy m)
-
--- | The "tweaked trace" (twace) function
--- \(\Tw(x) = (\hat{m} / \hat{m}') \cdot \Tr((g' / g) \cdot x)\),
--- which fixes \(R\) pointwise (i.e., @twace . embed == id@).
-twace :: forall t m m' r . (m `Divides` m', UCRTElt t r, ZeroTestable r)
-         => Cyc t m' r -> Cyc t m r
-{-# INLINABLE twace #-}
-twace (Pow u) = Pow $ U.twacePow u
-twace (Dec u) = Dec $ U.twaceDec u
-twace (CRT u) = either (cycPE . twaceCRTE) (cycPC . twaceCRTC) u
-twace (Scalar u) = Scalar u
-twace (Sub (c :: Cyc t l r)) = Sub (twace c :: Cyc t (FGCD l m) r)
-                               \\ gcdDivides (Proxy::Proxy l) (Proxy::Proxy m)
-
--- | Return the given element's coefficient vector with respect to
--- the (relative) powerful/decoding basis of the cyclotomic
--- extension \(\O_{m'} / \O_m\).
--- See also 'coeffsPow', 'coeffsDec'.
-coeffsCyc :: (m `Divides` m', CElt t r) => R.Basis -> Cyc t m' r -> [Cyc t m r]
-{-# INLINABLE coeffsCyc #-}
-coeffsCyc R.Pow c' = Pow <$> U.coeffsPow (uncycPow c')
-coeffsCyc R.Dec c' = Dec <$> U.coeffsDec (uncycDec c')
-
-coeffsPow, coeffsDec :: (m `Divides` m', CElt t r) => Cyc t m' r -> [Cyc t m r]
-{-# INLINABLE coeffsPow #-}
-{-# INLINABLE coeffsDec #-}
--- | Specialized version of 'coeffsCyc' for powerful basis.
-coeffsPow = coeffsCyc R.Pow
--- | Specialized version of 'coeffsCyc' for decoding basis.
-coeffsDec = coeffsCyc R.Dec
-
--- | The relative powerful basis of \(\O_{m'} / \O_m\).
-powBasis :: (m `Divides` m', CElt t r) => Tagged m [Cyc t m' r]
-powBasis = (Pow <$>) <$> U.powBasis
-{-# INLINABLE powBasis #-}
-
--- | The relative mod-@r@ CRT set of the extension.
-crtSet :: (m `Divides` m', ZPP r, CElt t r, TElt t (ZpOf r))
-          => Tagged m [Cyc t m' r]
-crtSet = (Pow <$>) <$> U.crtSet
-{-# INLINABLE crtSet #-}
-
-
----------- Lattice operations and instances ----------
-
-instance (Reduce a b, Fact m, CElt t a, CElt t b)
-  -- CJP: need these specific constraints to get Reduce instance for Sub case
-         => Reduce (Cyc t m a) (Cyc t m b) where
-  {-# INLINABLE reduce #-}
-  reduce (Pow u) = Pow $ reduce u
-  reduce (Dec u) = Dec $ reduce u
-  reduce (CRT u) = Pow $ reduce $ either toPow toPow u
-  reduce (Scalar c) = Scalar $ reduce c
-  reduce (Sub (c :: Cyc t l a)) = Sub (reduce c :: Cyc t l b)
-
-type instance LiftOf (Cyc t m r) = Cyc t m (LiftOf r)
-
--- | Lift using the specified basis.
-liftCyc :: (Lift b a, Fact m, TElt t a, CElt t b)
-           => R.Basis -> Cyc t m b -> Cyc t m a
-{-# INLINABLE liftCyc #-}
-
-liftCyc R.Pow = liftPow
-liftCyc R.Dec = liftDec
-
-liftPow, liftDec :: (Lift b a, Fact m, TElt t a, CElt t b)
-                    => Cyc t m b -> Cyc t m a
-{-# INLINABLE liftPow #-}
-{-# INLINABLE liftDec #-}
-
--- | Lift using the powerful basis.
-liftPow (Pow u) = Pow $ lift u
-liftPow (Dec u) = Pow $ lift $ toPow u
-liftPow (CRT u) = Pow $ lift $ either toPow toPow u
--- optimized for subrings; these are correct for powerful basis but
--- not for decoding
-liftPow (Scalar c) = Scalar $ lift c
-liftPow (Sub c) = Sub $ liftPow c
-
--- | Lift using the decoding basis.
-liftDec c = Dec $ lift $ uncycDec c
-
--- | Unzip for a pair base ring.
-unzipCyc :: (Fact m, CElt t (a,b), CElt t a, CElt t b)
-            => Cyc t m (a,b) -> (Cyc t m a, Cyc t m b)
-{-# INLINABLE unzipCyc #-}
-unzipCyc (Pow u) = Pow *** Pow $ U.unzipPow u
-unzipCyc (Dec u) = Dec *** Dec $ U.unzipDec u
-unzipCyc (CRT u) = either ((cycPE *** cycPE) . unzipCRTE)
-                   ((cycPC *** cycPC) . unzipCRTC) u
-unzipCyc (Scalar c) = Scalar *** Scalar $ c
-unzipCyc (Sub c) = Sub *** Sub $ unzipCyc c
-
-instance {-# OVERLAPS #-} (Rescale a b, CElt t a, TElt t b)
-    => R.RescaleCyc (Cyc t) a b where
-
-  -- Optimized for subring constructors, for powerful basis.
-  -- Analogs for decoding basis are not quite correct, because (* -1)
-  -- doesn't commute with 'rescale' due to tiebreakers!
-  rescaleCyc R.Pow (Scalar c) = Scalar $ rescale c
-  rescaleCyc R.Pow (Sub c) = Sub $ R.rescalePow c
-
-  rescaleCyc R.Pow c = Pow $ fmapPow rescale $ uncycPow c
-  rescaleCyc R.Dec c = Dec $ fmapDec rescale $ uncycDec c
-  {-# INLINABLE rescaleCyc #-}
-
--- | specialized instance for product rings of \(\Z_q\)s: ~2x faster
--- algorithm
-instance (Mod a, Field b, Lift a (ModRep a), Reduce (LiftOf a) b,
-         CElt t (a,b), CElt t a, CElt t b, CElt t (LiftOf a))
-         => R.RescaleCyc (Cyc t) (a,b) b where
-
-  -- optimized for subrings and powerful basis (see comments in other
-  -- instance for why this doesn't work for decoding basis)
-  rescaleCyc R.Pow (Scalar c) = Scalar $ rescale c
-  rescaleCyc R.Pow (Sub c) = Sub $ R.rescalePow c
-
-  rescaleCyc bas c = let aval = proxy modulus (Proxy::Proxy a)
-                         (a,b) = unzipCyc c
-                         z = liftCyc bas a
-                     in Scalar (recip (reduce aval)) * (b - reduce z)
-  {-# INLINABLE rescaleCyc #-}
-
--- | promoted from base ring
-instance (Gadget gad zq, Fact m, CElt t zq) => Gadget gad (Cyc t m zq) where
-  gadget = (scalarCyc <$>) <$> gadget
-  {-# INLINABLE gadget #-}
-
-  -- CJP: default 'encode' works because mul-by-Scalar is fast
-
--- | promoted from base ring, using the powerful basis for best geometry
-instance (Decompose gad zq, Fact m, CElt t zq, CElt t (DecompOf zq))
-         => Decompose gad (Cyc t m zq) where
-
-  type DecompOf (Cyc t m zq) = Cyc t m (DecompOf zq)
-
-  -- faster implementations: decompose directly in subring, which is
-  -- correct because we decompose in powerful basis
-  decompose (Scalar c) = pasteT $ Scalar <$> peelT (decompose c)
-  decompose (Sub c) = pasteT $ Sub <$> peelT (decompose c)
-
-  -- traverse: Traversable (UCyc t m P) and Applicative (Tagged gad ZL)
-  decompose (Pow u) = fromZL $ Pow <$> traverse (toZL . decompose) u
-  decompose c = decompose $ toPow' c
-
-  {-# INLINABLE decompose #-}
-
-toZL :: Tagged s [a] -> TaggedT s ZipList a
-toZL = coerce
-
-fromZL :: TaggedT s ZipList a -> Tagged s [a]
-fromZL = coerce
-
--- | promoted from base ring, using the decoding basis for best geometry
-instance (Correct gad zq, Fact m, CElt t zq) => Correct gad (Cyc t m zq) where
-  -- sequence: Monad [] and Traversable (UCyc t m D)
-  -- sequenceA: Applicative (UCyc t m D) and Traversable (TaggedT gad [])
-  correct bs = Dec *** (Dec <$>) $
-               second sequence $ fmap fst &&& fmap snd $ (correct . pasteT) <$>
-               sequenceA (uncycDec <$> peelT bs)
-  {-# INLINABLE correct #-}
-
----------- Change of representation (internal use only) ----------
-
-toPow', toDec', toCRT' :: (Fact m, UCRTElt t r, ZeroTestable r) => Cyc t m r -> Cyc t m r
-{-# INLINABLE toPow' #-}
-{-# INLINABLE toDec' #-}
-{-# INLINABLE toCRT' #-}
-
--- | Force to powerful-basis representation (for internal use only).
-toPow' c@(Pow _) = c
-toPow' (Dec u) = Pow $ toPow u
-toPow' (CRT u) = Pow $ either toPow toPow u
-toPow' (Scalar c) = Pow $ scalarPow c
-toPow' (Sub c) = toPow' $ embed' c
-
--- | Force to decoding-basis representation (for internal use only).
-toDec' (Pow u) = Dec $ toDec u
-toDec' c@(Dec _) = c
-toDec' (CRT u) = Dec $ either toDec toDec u
-toDec' (Scalar c) = Dec $ toDec $ scalarPow c
-toDec' (Sub c) = toDec' $ embed' c
-
--- | Force to a CRT representation (for internal use only).
-toCRT' (Pow u) = CRT $ toCRT u
-toCRT' (Dec u) = CRT $ toCRT u
-toCRT' c@(CRT _) = c
-toCRT' (Scalar c) = CRT $ scalarCRT c
--- CJP: the following is the fastest algorithm for when both source
--- and target have the same CRTr/CRTe choice.  It is not the fastest
--- when the choices are different (it will do an unnecessary CRT if
--- input is non-CRT), but this is an unusual case.  Note: both calls
--- to toCRT' are necessary in general, because embed' may not preserve
--- CRT representation!
-toCRT' (Sub c) = toCRT' $ embed' $ toCRT' c
-
----------- Utility instances ----------
-
-instance (Tensor t, Fact m, NFData r, TElt t r,
-          NFData (CRTExt r), TElt t (CRTExt r)) => NFData (Cyc t m r) where
-  rnf (Pow u) = rnf u
-  rnf (Dec u) = rnf u
-  rnf (CRT u) = rnf u
-  rnf (Scalar u) = rnf u
-  rnf (Sub c) = rnf c
-
-instance (Random r, Tensor t, Fact m, UCRTElt t r) => Random (Cyc t m r) where
-  random g = let (u,g') = random g
-             in (either Pow (CRT . Right) u, g')
-  {-# INLINABLE random #-}
-
-  randomR _ = error "randomR non-sensical for Cyc"
-
-instance (Fact m, CElt t r, Protoable (UCyc t m D r))
-         => Protoable (Cyc t m r) where
-  type ProtoType (Cyc t m r) = ProtoType (UCyc t m D r)
-  toProto (Dec uc) = toProto uc
-  toProto x = toProto $ toDec' x
-  fromProto x = Dec <$> fromProto x
-
-instance (Show r, Show (CRTExt r), Fact m, TElt t r, TElt t (CRTExt r), Tensor t)
-  => Show (Cyc t m r) where
-  show (Pow x) = "Pow " ++ show x
-  show (Dec x) = "Dec " ++ show x
-  show (CRT (Left x)) = "CRT " ++ show x
-  show (CRT (Right x)) = "CRT " ++ show x
-  show (Scalar x) = "Scalar " ++ show x
-  show (Sub x) = "Sub " ++ show x
+Description : An implementation of cyclotomic rings that hides and
+              automatically manages the internal representations of
+              ring elements.
+Copyright   : (c) Eric Crockett, 2011-2018
+                  Chris Peikert, 2011-2018
+License     : GPL-3
+Maintainer  : ecrockett0@gmail.com
+Stability   : experimental
+Portability : POSIX
+
+  \( \def\Z{\mathbb{Z}} \)
+  \( \def\F{\mathbb{F}} \)
+  \( \def\Q{\mathbb{Q}} \)
+  \( \def\Tw{\text{Tw}} \)
+  \( \def\Tr{\text{Tr}} \)
+  \( \def\O{\mathcal{O}} \)
+
+An implementation of cyclotomic rings that hides the
+internal representations of ring elements (e.g., the choice of
+basis), and also offers more efficient storage and operations on
+subring elements (including elements from the base ring itself).
+
+For an implementation that allows (and requires) the programmer to
+control the underlying representation, see
+"Crypto.Lol.Cyclotomic.CycRep".
+
+__WARNING:__ as with all fixed-point arithmetic, the functions
+associated with 'Cyc' may result in overflow (and thereby
+incorrect answers and potential security flaws) if the input
+arguments are too close to the bounds imposed by the base type.
+The acceptable range of inputs for each function is determined by
+the internal linear transforms and other operations it performs.
+-}
+
+{-# LANGUAGE AllowAmbiguousTypes        #-}
+{-# LANGUAGE ConstraintKinds            #-}
+{-# LANGUAGE DataKinds                  #-}
+{-# LANGUAGE FlexibleContexts           #-}
+{-# LANGUAGE FlexibleInstances          #-}
+{-# LANGUAGE GADTs                      #-}
+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
+{-# LANGUAGE InstanceSigs               #-}
+{-# LANGUAGE MultiParamTypeClasses      #-}
+{-# LANGUAGE NoImplicitPrelude          #-}
+{-# LANGUAGE PartialTypeSignatures      #-}
+{-# LANGUAGE PolyKinds                  #-}
+{-# LANGUAGE QuantifiedConstraints      #-}
+{-# LANGUAGE RankNTypes                 #-}
+{-# LANGUAGE ScopedTypeVariables        #-}
+{-# LANGUAGE StandaloneDeriving         #-}
+{-# LANGUAGE TemplateHaskell            #-}
+{-# LANGUAGE TypeApplications           #-}
+{-# LANGUAGE TypeFamilies               #-}
+{-# LANGUAGE TypeOperators              #-}
+{-# LANGUAGE UndecidableInstances       #-}
+
+module Crypto.Lol.Cyclotomic.Cyc
+(
+-- * Data type
+  Cyc
+-- * Constructors/deconstructors
+, UnCyc(..)
+) where
+
+import qualified Algebra.Additive     as Additive (C)
+import qualified Algebra.Module       as Module (C)
+import qualified Algebra.Ring         as Ring (C)
+import qualified Algebra.ZeroTestable as ZeroTestable (C)
+
+import           Crypto.Lol.CRTrans
+import           Crypto.Lol.Cyclotomic.CycRep   hiding (coeffsDec,
+                                                 coeffsPow, crtSet,
+                                                 powBasis)
+import qualified Crypto.Lol.Cyclotomic.CycRep   as R
+import           Crypto.Lol.Cyclotomic.Language hiding (Dec, Pow)
+import qualified Crypto.Lol.Cyclotomic.Language as L
+import           Crypto.Lol.Cyclotomic.Tensor   (TensorCRT, TensorCRTSet,
+                                                 TensorGSqNorm,
+                                                 TensorGaussian,
+                                                 TensorPowDec)
+import           Crypto.Lol.Gadget
+import           Crypto.Lol.Prelude             as LP
+import           Crypto.Lol.Reflects
+import           Crypto.Lol.Types               (RRq, ZqBasic)
+import           Crypto.Lol.Types.FiniteField
+import           Crypto.Lol.Types.IFunctor
+import           Crypto.Lol.Types.Proto
+
+import Control.Applicative  hiding ((*>))
+import Control.Arrow
+import Control.DeepSeq
+import Control.Monad.Random hiding (lift)
+import Data.Constraint      ((\\))
+import Data.Foldable        (Foldable)
+import Data.Traversable
+import Language.Haskell.TH
+
+-- | Underlying GADT for a cyclotomic ring in one of several
+-- representations.
+data CycG t m r where
+  Pow :: !(CycRep t P m r) -> CycG t m r
+  Dec :: !(CycRep t D m r) -> CycG t m r
+  CRT :: !(CycRepEC t m r) -> CycG t m r
+  -- super-optimized storage of scalars
+  Scalar :: !r -> CycG t m r
+  -- optimized storage of subring elements
+  Sub :: (l `Divides` m) => !(CycG t l r) -> CycG t m r
+  -- CJP: someday try to merge the above two?
+
+-- | A cyclotomic ring such as \( \Z[\zeta_m] \), \( \Z_q[\zeta_m] \),
+-- or \( \Q[\zeta_m] \): @t@ is the 'Tensor' type for storing
+-- coefficient tensors; @m@ is the cyclotomic index; @r@ is the base
+-- ring of the coefficients (e.g., \(\ \Q \), \( \Z \), \( \Z_q \)).
+data family Cyc (t :: Factored -> * -> *) (m :: Factored) r
+
+type instance LiftOf (CycG t m r) = CycG t m (LiftOf r)
+type instance LiftOf (Cyc  t m r) = Cyc  t m (LiftOf r)
+
+-- could also do an Int instance
+newtype instance Cyc t m Double        = CycDbl { unCycDbl :: CycG t m Double }
+newtype instance Cyc t m Int64         = CycI64 { unCycI64 :: CycG t m Int64 }
+newtype instance Cyc t m (ZqBasic q z) = CycZqB { unCycZqB :: CycG t m (ZqBasic q z) }
+
+-- | cyclotomic over a product base ring, represented as a product of
+-- cyclotomics over the individual rings
+data    instance Cyc t m (a,b)         = CycPair !(Cyc t m a) !(Cyc t m b)
+
+-- | cyclotomic ring of integers with unbounded precision, limited to
+-- powerful- or decoding-basis representation.
+data instance Cyc t m Integer
+  = PowIgr !(CycRep t P m Integer)
+  | DecIgr !(CycRep t D m Integer)
+
+-- | additive group \( K/qR \), limited to powerful- or decoding-basis
+-- representation
+data instance Cyc t m (RRq q r)
+  = PowRRq !(CycRep t P m (RRq q r))
+  | DecRRq !(CycRep t D m (RRq q r))
+
+---------- Constructors / destructors ----------
+
+-- | Convenience wrapper.
+cycPC :: Either (CycRep t P m r) (CycRep t C m r) -> CycG t m r
+cycPC = either Pow (CRT . Right)
+{-# INLINABLE cycPC #-}
+
+-- | Convenience wrapper.
+cycPE :: Either (CycRep t P m r) (CycRep t E m r) -> CycG t m r
+cycPE = either Pow (CRT . Left)
+{-# INLINABLE cycPE #-}
+
+-- | Unwrap a 'CycG' as a 'CycRep' in powerful-basis representation.
+unCycGPow :: (Fact m, CRTElt t r) => CycG t m r -> CycRep t P m r
+{-# INLINABLE unCycGPow #-}
+unCycGPow c = let (Pow u) = toPow' c in u
+
+-- | Unwrap a 'CycG' as a 'CycRep' in decoding-basis representation.
+unCycGDec :: (Fact m, CRTElt t r) => CycG t m r -> CycRep t D m r
+{-# INLINABLE unCycGDec #-}
+unCycGDec c = let (Dec u) = toDec' c in u
+
+{-
+-- | Unwrap a 'CycG' as a 'CycRep' in a CRT-basis representation.
+uncycCRT :: (Fact m, CRTElt t r) => CycG t m r -> CycRepEC t m r
+{-# INLINABLE uncycCRT #-}
+uncycCRT c = let (CRT u) = toCRT' c in u
+-}
+
+-- | Go between 'Cyc' and 'CycRep', in a desired representation.
+class UnCyc t r where
+  cycPow   :: (Fact m) => CycRep t P m r -> Cyc t m r
+  cycDec   :: (Fact m) => CycRep t D m r -> Cyc t m r
+  unCycPow :: (Fact m) => Cyc t m r -> CycRep t P m r
+  unCycDec :: (Fact m) => Cyc t m r -> CycRep t D m r
+
+instance CRTElt t Double => UnCyc t Double where
+  cycPow   = CycDbl . Pow
+  cycDec   = CycDbl . Dec
+  unCycPow = unCycGPow . unCycDbl
+  unCycDec = unCycGDec . unCycDbl
+
+instance CRTElt t Int64 => UnCyc t Int64 where
+  cycPow   = CycI64 . Pow
+  cycDec   = CycI64 . Dec
+  unCycPow = unCycGPow . unCycI64
+  unCycDec = unCycGDec . unCycI64
+
+instance CRTElt t (ZqBasic q z) => UnCyc t (ZqBasic q z) where
+  cycPow   = CycZqB . Pow
+  cycDec   = CycZqB . Dec
+  unCycPow = unCycGPow . unCycZqB
+  unCycDec = unCycGDec . unCycZqB
+
+-- CJP TODO: one for Integer?; would require converting between Pow and
+-- Dec reps in pure Haskell
+
+instance TensorPowDec t (RRq q r) => UnCyc t (RRq q r) where
+  cycPow = PowRRq
+  cycDec = DecRRq
+  unCycPow (PowRRq v) = v
+  unCycPow (DecRRq v) = toPow v
+  unCycDec (DecRRq v) = v
+  unCycDec (PowRRq v) = toDec v
+
+instance (UnCyc t a, UnCyc t b, IFunctor t, IFElt t a, IFElt t b, IFElt t (a,b))
+  => UnCyc t (a,b) where
+  cycPow = uncurry CycPair . ((cycPow . fmapI fst) &&& (cycPow . fmapI snd))
+  cycDec = uncurry CycPair . ((cycDec . fmapI fst) &&& (cycDec . fmapI snd))
+
+  unCycPow (CycPair a b) = zipWithI (,) (unCycPow a) (unCycPow b)
+  unCycDec (CycPair a b) = zipWithI (,) (unCycDec a) (unCycDec b)
+
+---------- Category-theoretic instances ----------
+
+instance (Fact m, CRTElt t r, Foldable (t m))
+    => FoldableCyc (CycG t m) r where
+  foldrCyc (Just L.Pow)   f acc (Pow u) = foldr f acc u
+  foldrCyc (Just L.Dec)   f acc (Dec u) = foldr f acc u
+  foldrCyc Nothing        f acc (Pow u) = foldr f acc u
+  foldrCyc Nothing        f acc (Dec u) = foldr f acc u
+
+  foldrCyc b@(Just L.Pow) f acc c       = foldrCyc b f acc $ toPow' c
+  foldrCyc b@(Just L.Dec) f acc c       = foldrCyc b f acc $ toDec' c
+  foldrCyc Nothing        f acc c       = foldrCyc Nothing f acc $ toPow' c
+
+instance (FoldableCyc (CycG t m) Double) => FoldableCyc (Cyc t m) Double where
+  foldrCyc bas f acc = foldrCyc bas f acc . unCycDbl
+
+instance (FoldableCyc (CycG t m) Int64) => FoldableCyc (Cyc t m) Int64 where
+  foldrCyc bas f acc = foldrCyc bas f acc . unCycI64
+
+instance (FoldableCyc (CycG t m) (ZqBasic q z))
+  => FoldableCyc (Cyc t m) (ZqBasic q z) where
+  foldrCyc bas f acc = foldrCyc bas f acc . unCycZqB
+
+-- No instance for CycPair -- is one possible?
+
+instance (Foldable (t m)) => FoldableCyc (Cyc t m) Integer where
+  foldrCyc (Just L.Pow) f acc (PowIgr u) = foldr f acc u
+  foldrCyc (Just L.Dec) f acc (DecIgr u) = foldr f acc u
+  foldrCyc Nothing      f acc (PowIgr u) = foldr f acc u
+  foldrCyc Nothing      f acc (DecIgr u) = foldr f acc u
+  foldrCyc _            _ _   _          =
+    error "Cyc.foldrCyc over Integer: mismatched bases, implementation TODO."
+
+instance (Fact m, TensorPowDec t (RRq q r), Foldable (t m))
+    => FoldableCyc (Cyc t m) (RRq q r) where
+  foldrCyc (Just L.Pow) f acc = foldr f acc . unCycPow
+  foldrCyc (Just L.Dec) f acc = foldr f acc . unCycDec
+  foldrCyc Nothing      f acc = foldrCyc (Just L.Pow) f acc
+
+--- FunctorCyc
+
+instance (Fact m, CRTElt t a, IFunctor t, IFElt t a, IFElt t b)
+  => FunctorCyc (CycG t m) a b where
+  fmapCyc (Just L.Pow) f = Pow . fmapI f . unCycGPow
+  fmapCyc (Just L.Dec) f = Dec . fmapI f . unCycGDec
+  fmapCyc Nothing      f = fmapCyc (Just L.Pow) f
+
+instance (Functor (t m)) => FunctorCyc (Cyc t m) Integer Integer where
+  fmapCyc (Just L.Pow) f (PowIgr u) = PowIgr $ fmap f u
+  fmapCyc (Just L.Dec) f (DecIgr u) = DecIgr $ fmap f u
+  fmapCyc Nothing      f (PowIgr u) = PowIgr $ fmap f u
+  fmapCyc Nothing      f (DecIgr u) = DecIgr $ fmap f u
+  fmapCyc _            _ _          =
+    error "Cyc.fmapCyc Integer->Integer: mismatched bases, implementation TODO"
+
+-- CJP: the rest of the FunctorCyc instances are autogen'd at end of
+-- file, to avoid scoping problems
+
+---------- Algebraic instances ----------
+
+instance (Fact m, ZeroTestable r, CRTElt t r,
+          forall m' . Fact m' => ZeroTestable.C (t m' r))
+  => ZeroTestable.C (CycG t m r) where
+  isZero x = case x of
+    (Pow u)         -> isZero u
+    (Dec u)         -> isZero u
+    (CRT (Right u)) -> isZero u
+    c@(CRT _)       -> isZero $ toPow' c
+    (Scalar c)      -> isZero c
+    (Sub c)         -> isZero c
+
+deriving instance ZeroTestable (CycG t m Double) => ZeroTestable.C (Cyc t m Double)
+deriving instance ZeroTestable (CycG t m Int64) => ZeroTestable.C (Cyc t m Int64)
+deriving instance ZeroTestable (CycG t m (ZqBasic q z)) => ZeroTestable.C (Cyc t m (ZqBasic q z))
+
+instance (ZeroTestable (Cyc t m a), ZeroTestable (Cyc t m b))
+  => ZeroTestable.C (Cyc t m (a,b)) where
+  isZero (CycPair a b) = isZero a && isZero b
+
+instance ZeroTestable (t m Integer) => ZeroTestable.C (Cyc t m Integer) where
+  isZero (PowIgr v) = isZero v
+  isZero (DecIgr v) = isZero v
+
+instance ZeroTestable (t m (RRq q r)) => ZeroTestable.C (Cyc t m (RRq q r)) where
+  isZero (PowRRq c) = isZero c
+  isZero (DecRRq c) = isZero c
+
+-----
+
+instance (Eq r, Fact m, CRTElt t r,
+          forall m' . Fact m' => Eq (t m' r)) => Eq (CycG t m r) where
+  {-# INLINABLE (==) #-}
+  -- same representations
+  (Scalar c1) == (Scalar c2) = c1 == c2
+  (Pow u1) == (Pow u2) = u1 == u2
+  (Dec u1) == (Dec u2) = u1 == u2
+  (CRT (Right u1)) == (CRT (Right u2)) = u1 == u2
+
+  -- compare Subs in compositum
+  -- EAC: would like to convert c2 to basis of c1 *before* embedding
+  (Sub (c1 :: CycG t l1 r)) == (Sub (c2 :: CycG t l2 r)) =
+    (embed' c1 :: CycG t (FLCM l1 l2) r) == embed' c2
+    \\ lcmDivides @l1 @l2
+
+  -- some other relatively efficient comparisons
+  (Scalar c1) == (Pow u2) = scalarPow c1 == u2
+  (Pow u1) == (Scalar c2) = u1 == scalarPow c2
+
+  -- otherwise: compare in powerful basis
+  c1 == c2 = toPow' c1 == toPow' c2
+
+deriving instance Eq (CycG t m Int64)         => Eq (Cyc t m Int64)
+deriving instance Eq (CycG t m (ZqBasic q z)) => Eq (Cyc t m (ZqBasic q z))
+
+instance (Eq (Cyc t m a), Eq (Cyc t m b)) => Eq (Cyc t m (a,b)) where
+  (CycPair a b) == (CycPair a' b') = a == a' && b == b'
+
+-- no Eq for Double or RRq due to precision, nor for Integer because
+-- we can't change representations
+
+-----
+
+instance (Fact m, CRTElt t r, ZeroTestable r) => Additive.C (CycG t m r) where
+  {-# INLINABLE zero #-}
+  zero = Scalar zero
+
+  {-# INLINABLE (+) #-}
+  -- optimized addition of zero
+  (Scalar c1) + c2 | isZero c1 = c2
+  c1 + (Scalar c2) | isZero c2 = c1
+
+  -- SAME CONSTRUCTORS
+  (Scalar c1) + (Scalar c2) = Scalar (c1+c2)
+  (Pow u1) + (Pow u2) = Pow $ u1 + u2
+  (Dec u1) + (Dec u2) = Dec $ u1 + u2
+  (CRT u1) + (CRT u2) = CRT $ u1 + u2
+  -- Sub plus Sub: work in compositum
+  -- EAC: would like to convert c2 to basis of c1 before embedding
+  (Sub (c1 :: CycG t m1 r)) + (Sub (c2 :: CycG t m2 r)) =
+    Sub ((embed' c1 :: CycG t (FLCM m1 m2) r) + embed' c2)
+    \\ lcm2Divides @m1 @m2 @m
+
+  -- SCALAR PLUS SOMETHING ELSE
+
+  (Scalar c)  + (Pow u)  = Pow $ scalarPow c + u
+  (Scalar c)  + (Dec u)  = Pow $ scalarPow c + toPow u -- workaround scalarDec
+  (Scalar c)  + (CRT u)  = CRT $ scalarCRT c + u
+  (Scalar c1) + (Sub c2) = Sub $ Scalar c1 + c2 -- must re-wrap Scalar!
+
+  (Pow u)  + (Scalar c)  = Pow $ u + scalarPow c
+  (Dec u)  + (Scalar c)  = Pow $ toPow u + scalarPow c -- workaround scalarDec
+  (CRT u)  + (Scalar c)  = CRT $ u + scalarCRT c
+  (Sub c1) + (Scalar c2) = Sub $ c1 + Scalar c2
+
+  -- SUB PLUS NON-SUB, NON-SCALAR: work in full ring
+  -- EAC: would like to convert sub to basis of other before embedding
+  (Sub c1) + c2 = embed' c1 + c2
+  c1 + (Sub c2) = c1 + embed' c2
+
+  -- mixed Dec and Pow: use linear-time conversions
+  (Dec u1) + (Pow u2) = Pow $ toPow u1 + u2
+  (Pow u1) + (Dec u2) = Pow $ u1 + toPow u2
+
+  -- one CRT: convert other to CRT
+  (CRT u1) + (Pow u2) = CRT $ u1 + toCRT u2
+  (CRT u1) + (Dec u2) = CRT $ u1 + toCRT u2
+  (Pow u1) + (CRT u2) = CRT $ toCRT u1 + u2
+  (Dec u1) + (CRT u2) = CRT $ toCRT u1 + u2
+
+  {-# INLINABLE negate #-}
+  negate (Pow u)    = Pow $ negate u
+  negate (Dec u)    = Dec $ negate u
+  negate (CRT u)    = CRT $ negate u
+  negate (Scalar c) = Scalar (negate c)
+  negate (Sub c)    = Sub $ negate c
+
+deriving instance Additive (CycG t m Double) => Additive.C (Cyc t m Double)
+deriving instance Additive (CycG t m Int64) => Additive.C (Cyc t m Int64)
+deriving instance Additive (CycG t m (ZqBasic q z)) => Additive.C (Cyc t m (ZqBasic q z))
+
+instance (Additive (Cyc t m a), Additive (Cyc t m b))
+  => Additive.C (Cyc t m (a,b)) where
+  zero = CycPair zero zero
+  (CycPair a b) + (CycPair a' b') = CycPair (a+a') (b+b')
+  negate (CycPair a b) = CycPair (negate a) (negate b)
+
+instance (Additive (RRq q r), TensorPowDec t (RRq q r), IFunctor t, Fact m)
+  => Additive.C (Cyc t m (RRq q r)) where
+  zero = PowRRq zero
+
+  (PowRRq u1) + (PowRRq u2) = PowRRq $ u1 + u2
+  (DecRRq u1) + (DecRRq u2) = DecRRq $ u1 + u2
+  (PowRRq u1) + (DecRRq u2) = PowRRq $ u1 + toPow u2
+  (DecRRq u1) + (PowRRq u2) = PowRRq $ toPow u1 + u2
+
+  negate (PowRRq u) = PowRRq $ negate u
+  negate (DecRRq u) = DecRRq $ negate u
+
+-----
+
+instance (Fact m, CRTElt t r, ZeroTestable r) => Ring.C (CycG t m r) where
+  {-# INLINABLE one #-}
+  one = Scalar one
+
+  {-# INLINABLE fromInteger #-}
+  fromInteger = Scalar . fromInteger
+
+  {-# INLINABLE (*) #-}
+
+  -- optimized mul-by-zero
+  v1@(Scalar c1) * _ | isZero c1 = v1
+  _ * v2@(Scalar c2) | isZero c2 = v2
+
+  -- both CRT: if over C, then convert result to pow for precision reasons
+  (CRT u1) * (CRT u2) = either (Pow . toPow) (CRT . Right) $ u1*u2
+
+  -- at least one Scalar
+  (Scalar c1) * (Scalar c2) = Scalar $ c1*c2
+  (Scalar c) * (Pow u) = Pow $ c *> u
+  (Scalar c) * (Dec u) = Dec $ c *> u
+  (Scalar c) * (CRT u) = CRT $ c *> u
+  (Scalar c1) * (Sub c2) = Sub $ Scalar c1 * c2
+
+  (Pow u) * (Scalar c) = Pow $ c *> u
+  (Dec u) * (Scalar c) = Dec $ c *> u
+  (CRT u) * (Scalar c) = CRT $ c *> u
+  (Sub c1) * (Scalar c2) = Sub $ c1 * Scalar c2
+
+  -- TWO SUBS: work in a CRT rep for compositum
+  (Sub (c1 :: CycG t m1 r)) * (Sub (c2 :: CycG t m2 r)) =
+    -- re-wrap c1, c2 as Subs of the composition, and force them to CRT
+    Sub ((toCRT' $ Sub c1 :: CycG t (FLCM m1 m2) r) * toCRT' (Sub c2))
+    \\ lcm2Divides @m1 @m2 @m
+
+  -- ELSE: work in appropriate CRT rep
+  c1 * c2 = toCRT' c1 * toCRT' c2
+
+deriving instance Ring (CycG t m Double)        => Ring.C (Cyc t m Double)
+deriving instance Ring (CycG t m Int64)         => Ring.C (Cyc t m Int64)
+deriving instance Ring (CycG t m (ZqBasic q z)) => Ring.C (Cyc t m (ZqBasic q z))
+
+instance (Ring (Cyc t m a), Ring (Cyc t m b)) => Ring.C (Cyc t m (a,b)) where
+  one = CycPair one one
+  fromInteger z = CycPair (fromInteger z) (fromInteger z)
+  (CycPair a b) * (CycPair a' b') = CycPair (a*a') (b*b')
+
+-- no instance for RRq because it's not a ring
+
+-----
+
+instance (Fact m, CRTElt t r, ZeroTestable r) => Module.C r (CycG t m r) where
+  r *> (Scalar c) = Scalar $ r * c
+  r *> (Pow v)    = Pow $ r *> v
+  r *> (Dec v)    = Dec $ r *> v
+  r *> (Sub c)    = Sub $ r *> c
+  r *> x          = r *> toPow' x
+
+deriving instance Module Int64 (CycG t m Int64) => Module.C Int64 (Cyc t m Int64)
+deriving instance Module Double (CycG t m Double) => Module.C Double (Cyc t m Double)
+deriving instance (Module (ZqBasic q z) (CycG t m (ZqBasic q z)),
+                   Ring (ZqBasic q z)) -- satisfy superclass
+  => Module.C (ZqBasic q z) (Cyc t m (ZqBasic q z))
+
+instance (Module a (Cyc t m a), Module b (Cyc t m b))
+  => Module.C (a,b) (Cyc t m (a,b)) where
+  (a,b) *> (CycPair ca cb) = CycPair (a *> ca) (b *> cb)
+
+-- no instance for RRq because it's not, mathematically
+
+-- Module over finite field
+
+-- | \(R_p\) is an \(\F_{p^d}\)-module when \(d\) divides
+-- \(\varphi(m)\), by applying \(d\)-dimensional \(\F_p\)-linear
+-- transform on \(d\)-dim chunks of powerful basis coeffs.
+instance (GFCtx fp d, Fact m, CRTElt t fp, Module (GF fp d) (t m fp))
+  => Module.C (GF fp d) (CycG t m fp) where
+  -- CJP: optimize for Scalar if we can: r *> (Scalar c) is the tensor
+  -- that has the coeffs of (r*c), followed by zeros.  (This assumes
+  -- that the powerful basis has 1 as its first element, and that
+  -- we're using pow to define the module mult.)
+
+  -- Can use any r-basis to define module mult, but must be
+  -- consistent. We use powerful basis.
+  r *> (Pow v) = Pow $ r *> v
+  r *> x = r *> toPow' x
+
+deriving instance (Ring (GF (ZqBasic q z) d),
+                   Module (GF (ZqBasic q z) d) (CycG t m (ZqBasic q z)))
+  => Module.C (GF (ZqBasic q z) d) (Cyc t m (ZqBasic q z))
+
+---------- Cyclotomic classes ----------
+
+instance (Fact m, CRTElt t r, ZeroTestable r, IntegralDomain r)
+  => Cyclotomic (CycG t m r) where
+  {-# SPECIALIZE instance (Fact m, CRTElt t Int64) => Cyclotomic (CycG t m Int64) #-}
+  {-# SPECIALIZE instance (Fact m, CRTElt t Double) => Cyclotomic (CycG t m Double) #-}
+  {-# SPECIALIZE instance (Fact m, CRTElt t (ZqBasic q Int64), Reflects q Int64) => Cyclotomic (CycG t m (ZqBasic q Int64)) #-}
+
+  mulG (Pow u)         = Pow $ R.mulGPow u
+  mulG (Dec u)         = Dec $ R.mulGDec u
+  mulG (CRT (Left u))  = Pow $ R.mulGPow $ toPow u -- go to Pow for precision
+  mulG (CRT (Right u)) = CRT $ Right $ R.mulGCRTC u
+  mulG c@(Scalar _)    = mulG $ toCRT' c
+  mulG (Sub c)         = mulG $ embed' c   -- must go to full ring
+
+  divG (Pow u)         = Pow <$> R.divGPow u
+  divG (Dec u)         = Dec <$> R.divGDec u
+  divG (CRT (Left u))  = Pow <$> R.divGPow (toPow u) -- go to Pow for precision
+  divG (CRT (Right u)) = Just $ (CRT . Right) $ R.divGCRTC u
+  divG c@(Scalar _)    = divG $ toCRT' c
+  divG (Sub c)         = divG $ embed' c  -- must go to full ring
+
+  advisePow = toPow'
+  adviseDec = toDec'
+  adviseCRT = toCRT'
+
+deriving instance Cyclotomic (CycG t m Double) => Cyclotomic (Cyc t m Double)
+deriving instance Cyclotomic (CycG t m Int64)  => Cyclotomic (Cyc t m Int64)
+deriving instance Cyclotomic (CycG t m (ZqBasic q z)) => Cyclotomic (Cyc t m (ZqBasic q z))
+
+instance (Cyclotomic (Cyc t m a), Cyclotomic (Cyc t m b))
+  => Cyclotomic (Cyc t m (a,b)) where
+  {-# SPECIALIZE instance (Fact m, CRTElt t (ZqBasic q Int64), Reflects q Int64, Cyclotomic (Cyc t m b)) => Cyclotomic (Cyc t m (ZqBasic q Int64, b)) #-}
+
+  mulG (CycPair a b) = CycPair (mulG a) (mulG b)
+  divG (CycPair a b) = CycPair <$> divG a <*> divG b
+  advisePow (CycPair a b) = CycPair (advisePow a) (advisePow b)
+  adviseDec (CycPair a b) = CycPair (adviseDec a) (adviseDec b)
+  adviseCRT (CycPair a b) = CycPair (adviseCRT a) (adviseCRT b)
+
+-----
+
+instance (Fact m, TensorGSqNorm t r, CRTElt t r)
+  => GSqNormCyc (CycG t m) r where
+  gSqNorm (Dec c) = gSqNormDec c
+  gSqNorm c       = gSqNorm $ toDec' c
+
+instance (Fact m, TensorGSqNorm t Double, CRTElt t Double) -- copied
+  => GSqNormCyc (Cyc t m) Double where
+  gSqNorm = gSqNorm . unCycDbl
+
+instance (Fact m, TensorGSqNorm t Int64, CRTElt t Int64) -- copied
+  => GSqNormCyc (Cyc t m) Int64 where
+  gSqNorm = gSqNorm . unCycI64
+
+----
+
+-- | uses 'Double' for the intermediate Gaussian sample
+instance (Fact m, TensorGaussian t Double, FunctorCyc (Cyc t m) Double Int64)
+  => RoundedGaussianCyc (Cyc t m Int64) where
+  roundedGaussian :: forall v rnd . (ToRational v, MonadRandom rnd)
+                  => v -> rnd (Cyc t m Int64)
+  {-# INLINABLE roundedGaussian #-}
+  roundedGaussian svar =
+    fmapCyc (Just L.Dec) (roundMult one) <$>
+    (L.tweakedGaussian svar :: rnd (Cyc t m Double))
+
+-----
+
+instance (Lift' r, FunctorCyc (Cyc t m) r (LiftOf r)) => LiftCyc (Cyc t m r) where
+  {-# SPECIALIZE instance (Fact m, Reflects q Int64, UnCyc t (ZqBasic q Int64), UnCyc t Int64, IFunctor t, IFElt t (ZqBasic q Int64), IFElt t Int64) => LiftCyc (Cyc t m (ZqBasic q Int64)) #-}
+
+  {-# INLINABLE liftCyc #-}
+  liftCyc = flip fmapCyc lift
+
+-----
+
+instance (Fact m, TensorGaussian t q) => GaussianCyc (CycG t m q) where
+  tweakedGaussian = fmap Dec . R.tweakedGaussian
+
+instance (Fact m, TensorGaussian t Double) => GaussianCyc (Cyc t m Double) where
+  tweakedGaussian = fmap CycDbl . L.tweakedGaussian
+
+-- CJP: no GaussianCyc for Int64, Integer, ZqBasic, pairs, or RRq
+
+-- | uses 'Double' precision for the intermediate Gaussian samples
+instance (TensorGaussian t Double, IFElt t Double, IFunctor t, Fact m, Mod zp,
+          Lift zp (ModRep zp), CRTElt t zp, IFElt t (LiftOf zp))
+  => CosetGaussianCyc (CycG t m zp) where
+  {-# INLINABLE cosetGaussian #-}
+  cosetGaussian v = (Dec <$>) . R.cosetGaussian v . unCycGDec
+
+-- | uses 'Double' for the intermediate Gaussian samples
+instance (CosetGaussianCyc (CycG t m (ZqBasic q Int64)))
+  => CosetGaussianCyc (Cyc t m (ZqBasic q Int64)) where
+  cosetGaussian v = fmap CycI64 . L.cosetGaussian v . unCycZqB
+
+-- CJP: no CosetGaussianCyc for Double, Int64, Integer, or pairs
+
+-----
+
+instance (CRTElt t r, ZeroTestable r, IntegralDomain r) -- ZT, ID for superclass
+  => ExtensionCyc (CycG t) r where
+  {-# SPECIALIZE instance (CRTElt t Int64)  => ExtensionCyc (CycG t) Int64  #-}
+  {-# SPECIALIZE instance (CRTElt t Double) => ExtensionCyc (CycG t) Double #-}
+  {-# SPECIALIZE instance (CRTElt t (ZqBasic q Int64), Reflects q Int64) => ExtensionCyc (CycG t) (ZqBasic q Int64) #-}
+
+  -- lazily embed
+  embed :: forall m m' . (m `Divides` m') => CycG t m r -> CycG t m' r
+  embed (Scalar c) = Scalar c           -- keep as scalar
+  embed (Sub (c :: CycG t l r)) = Sub c -- keep as subring element
+    \\ transDivides @l @m @m'
+  embed c = Sub c
+
+  twace :: forall m m' . (m `Divides` m') => CycG t m' r -> CycG t m r
+  twace (Pow u) = Pow $ twacePow u
+  twace (Dec u) = Dec $ twaceDec u
+  twace (CRT u) = either (cycPE . twaceCRTE) (cycPC . twaceCRTC) u
+  twace (Scalar u) = Scalar u
+  twace (Sub (c :: CycG t l r)) = Sub (twace c :: CycG t (FGCD l m) r)
+                                  \\ gcdDivides @l @m
+
+  powBasis :: forall m m' . (m `Divides` m') => Tagged m [CycG t m' r]
+  powBasis = tag $ Pow <$> R.powBasis @m
+
+  coeffsCyc L.Pow c' = Pow <$> R.coeffsPow (unCycGPow c')
+  coeffsCyc L.Dec c' = Dec <$> R.coeffsDec (unCycGDec c')
+
+instance CRTElt t Double => ExtensionCyc (Cyc t) Double where
+  embed = CycDbl . embed . unCycDbl
+  twace = CycDbl . twace . unCycDbl
+  powBasis = (CycDbl <$>) <$> powBasis
+  coeffsCyc b = fmap CycDbl . coeffsCyc b . unCycDbl
+
+instance CRTElt t Int64 => ExtensionCyc (Cyc t) Int64 where
+  embed = CycI64 . embed . unCycI64
+  twace = CycI64 . twace . unCycI64
+  powBasis = (CycI64 <$>) <$> powBasis
+  coeffsCyc b = fmap CycI64 . coeffsCyc b . unCycI64
+
+instance (ExtensionCyc (CycG t) (ZqBasic q z))
+  => ExtensionCyc (Cyc t) (ZqBasic q z) where
+  embed = CycZqB . embed . unCycZqB
+  twace = CycZqB . twace . unCycZqB
+  powBasis = (CycZqB <$>) <$> powBasis
+  coeffsCyc b = fmap CycZqB . coeffsCyc b . unCycZqB
+
+instance (ExtensionCyc (Cyc t) a, ExtensionCyc (Cyc t) b)
+  => ExtensionCyc (Cyc t) (a,b) where
+  {-# SPECIALIZE instance (ExtensionCyc (Cyc t) (ZqBasic q Int64), ExtensionCyc (Cyc t) b) => ExtensionCyc (Cyc t) (ZqBasic q Int64, b) #-}
+
+  embed (CycPair a b) = CycPair (embed a) (embed b)
+  twace (CycPair a b) = CycPair (twace a) (twace b)
+  powBasis = zipWith CycPair <$> powBasis <*> powBasis
+  coeffsCyc bas (CycPair a b) =
+    zipWith CycPair (coeffsCyc bas a) (coeffsCyc bas b)
+
+instance (TensorPowDec t (RRq q r)) => ExtensionCyc (Cyc t) (RRq q r) where
+  embed (PowRRq u) = PowRRq $ embedPow u
+  embed (DecRRq u) = PowRRq $ embedPow $ toPow u
+  twace (PowRRq u) = PowRRq $ twacePow u
+  twace (DecRRq u) = DecRRq $ twaceDec u
+  powBasis :: forall m m' . (m `Divides` m') => Tagged m [Cyc t m' (RRq q r)]
+  powBasis = tag $ PowRRq <$> R.powBasis @m
+  coeffsCyc L.Pow (PowRRq c) = PowRRq <$> R.coeffsPow c
+  coeffsCyc L.Dec (DecRRq c) = DecRRq <$> R.coeffsDec c
+  coeffsCyc L.Pow (DecRRq c) = PowRRq <$> R.coeffsPow (toPow c)
+  coeffsCyc L.Dec (PowRRq c) = DecRRq <$> R.coeffsDec (toDec c)
+
+-- | Force to a non-'Sub' constructor (for internal use only).
+embed' :: forall t r l m . (l `Divides` m, CRTElt t r)
+       => CycG t l r -> CycG t m r
+{-# INLINE embed' #-}
+embed' (Pow u) = Pow $ embedPow u
+embed' (Dec u) = Pow $ embedPow $ toPow u
+embed' (CRT u) = either (cycPE . embedCRTE) (cycPC . embedCRTC) u
+embed' (Scalar c) = Scalar c
+embed' (Sub (c :: CycG t k r)) = embed' c \\ transDivides @k @l @m
+
+-----
+
+instance (PPow pp, Prime (PrimePP pp), zpp ~ ZqBasic pp z, ToInteger z,
+          CRTElt t zpp, TensorCRTSet t (ZqBasic (PrimePP pp) z),
+          ExtensionCyc (CycG t) zpp)
+  => CRTSetCyc (CycG t) (ZqBasic pp z) where
+  crtSet :: forall m m' . (m `Divides` m') => Tagged m [CycG t m' zpp]
+  crtSet = tag $ Pow <$> R.crtSet @m
+  {-# INLINABLE crtSet #-}
+
+instance (CRTSetCyc (CycG t) (ZqBasic q z))
+  => CRTSetCyc (Cyc t) (ZqBasic q z) where
+  crtSet = (CycZqB <$>) <$> crtSet
+  {-# INLINABLE crtSet #-}
+
+-- CJP TODO?: instance CRTSetCyc (Cyc t) (a,b)
+
+---------- Promoted lattice operations ----------
+
+-- | Rescales relative to the powerful basis. This instance is
+-- provided for convenience, but usage of 'RescaleCyc' is preferred to
+-- explicitly specify which basis by which to rescale.
+instance (RescaleCyc (Cyc t m) a b, Fact m,
+          Additive (Cyc t m a), Additive (Cyc t m b)) -- superclasses
+ => Rescale (Cyc t m a) (Cyc t m b) where
+  rescale = rescaleCyc L.Pow
+  {-# INLINABLE rescale #-}
+
+-- CJP: can we avoid incoherent instances by changing instance heads
+-- and using overlapping instances with isomorphism constraints?
+
+instance (Fact m, Rescale a b, CRTElt t a, TensorPowDec t b)
+  => RescaleCyc (CycG t m) a b where
+  {-# SPECIALIZE instance (Fact m, Reflects q1 Int64, Reflects q2 Int64, CRTElt t (ZqBasic q1 Int64), TensorPowDec t (ZqBasic q2 Int64)) => RescaleCyc (CycG t m) (ZqBasic q1 Int64) (ZqBasic q2 Int64) #-}
+
+  -- Optimized for subring constructors, for powerful basis.
+  -- Analogs for decoding basis are not quite correct, because (* -1)
+  -- doesn't commute with 'rescale' due to tiebreakers!
+  rescaleCyc L.Pow (Scalar c) = Scalar $ rescale c
+  rescaleCyc L.Pow (Sub c)    = Sub $ rescalePow c
+
+  rescaleCyc L.Pow c          = Pow $ fmapI rescale $ unCycGPow c
+  rescaleCyc L.Dec c          = Dec $ fmapI rescale $ unCycGDec c
+  {-# INLINABLE rescaleCyc #-}
+
+-- | identity rescale (more specific)
+instance {-# OVERLAPPING #-} RescaleCyc (CycG t m) a a where
+  -- No-op rescale
+  rescaleCyc _ = id
+  {-# INLINABLE rescaleCyc #-}
+
+-- | rescale from one modulus to another
+instance (RescaleCyc (CycG t m) (ZqBasic q z) (ZqBasic p z))
+  => RescaleCyc (Cyc t m) (ZqBasic q z) (ZqBasic p z) where
+  rescaleCyc b = CycZqB . rescaleCyc b . unCycZqB
+  {-# INLINABLE rescaleCyc #-}
+
+-- | rescale from one modulus to another
+instance (Fact m, Rescale (RRq q r) (RRq p r),
+          TensorPowDec t (RRq q r), TensorPowDec t (RRq p r))
+  => RescaleCyc (Cyc t m) (RRq q r) (RRq p r) where
+  rescaleCyc L.Pow (PowRRq u) = PowRRq $ rescale u
+  rescaleCyc L.Pow (DecRRq u) = PowRRq $ rescale $ toPow u
+  rescaleCyc L.Dec (DecRRq u) = DecRRq $ rescale u
+  rescaleCyc L.Dec (PowRRq u) = DecRRq $ rescale $ toDec u
+  {-# INLINABLE rescaleCyc #-}
+
+-- | no-op rescale for Cyc over pairs
+instance RescaleCyc (Cyc t m) (a,b) (a,b) where
+  rescaleCyc = const id
+  {-# INLINABLE rescaleCyc #-}
+
+-- | rescale up by one additional modulus
+instance (Fact m, Reflects q z, Reduce z b, ZeroTestable z,
+          CRTElt t (ZqBasic q z), Module.C b (Cyc t m b))
+  => RescaleCyc (Cyc t m) b (ZqBasic q z, b) where
+
+  rescaleCyc = let q :: z = value @q
+               -- same method works for any basis
+               in \_ b -> CycPair zero $ (reduce q :: b) *> b
+  {-# INLINABLE rescaleCyc #-}
+
+-- | specialized (faster) rescale-down by a single \(\Z_q\)
+instance (ToInteger z, Reflects q z, Reduce z b, Field b,
+          FunctorCyc (Cyc t m) (ZqBasic q z) z,
+          FunctorCyc (Cyc t m) z b,
+          Additive (Cyc t m b), Module b (Cyc t m b))
+  => RescaleCyc (Cyc t m) (ZqBasic q z, b) b where
+
+  rescaleCyc bas (CycPair a b) =
+    let q :: z = value @q
+        x      = liftCyc (Just bas) a
+    in recip (reduce q :: b) *> (b - reduceCyc x)
+  {-# INLINABLE rescaleCyc #-}
+
+-- CJP: do we really need these? Just have client call rescaleCyc
+-- multiple times?
+
+-- | convenient rescale-down by multiple components at once
+instance (RescaleCyc (Cyc t m) (b,c) c, RescaleCyc (Cyc t m) (a,(b,c)) (b,c))
+         => RescaleCyc (Cyc t m) (a,(b,c)) c where
+
+  rescaleCyc bas a = rescaleCyc bas (rescaleCyc bas a :: Cyc t m (b,c))
+  {-# INLINABLE rescaleCyc #-}
+
+-- | convenient rescale-down by multiple components at once
+instance (RescaleCyc (Cyc t m) (b,(c,d)) d,
+          RescaleCyc (Cyc t m) (a,(b,(c,d))) (b,(c,d)))
+         => RescaleCyc (Cyc t m) (a,(b,(c,d))) d where
+
+  rescaleCyc bas a = rescaleCyc bas (rescaleCyc bas a :: Cyc t m (b,(c,d)))
+  {-# INLINABLE rescaleCyc #-}
+
+-- | convenient rescale-down by multiple components at once
+instance (RescaleCyc (Cyc t m) (b,(c,(d,e))) e,
+          RescaleCyc (Cyc t m) (a,(b,(c,(d,e)))) (b,(c,(d,e))))
+         => RescaleCyc (Cyc t m) (a,(b,(c,(d,e)))) e where
+
+  rescaleCyc bas a = rescaleCyc bas (rescaleCyc bas a :: Cyc t m (b,(c,(d,e))))
+  {-# INLINABLE rescaleCyc #-}
+
+-----
+
+-- | promoted from base ring
+instance (Gadget gad (ZqBasic q z),
+          -- satisfy Gadget's Ring superclass; remove if it goes away
+          Fact m, CRTElt t (ZqBasic q z),
+          ZeroTestable (ZqBasic q z), IntegralDomain (ZqBasic q z))
+  => Gadget gad (CycG t m (ZqBasic q z)) where
+  gadget = Scalar <$> gadget @gad
+  {-# INLINABLE gadget #-}
+  -- CJP: default 'encode' works because mul-by-Scalar is fast
+
+-- can't auto-derive because of ambiguity of gadget
+instance Gadget gad (CycG t m (ZqBasic q z))
+  => Gadget gad (Cyc t m (ZqBasic q z)) where
+  gadget = CycZqB <$> gadget @gad
+  {-# INLINABLE gadget #-}
+
+instance (Gadget gad (Cyc t m a), Gadget gad (Cyc t m b))
+  => Gadget gad (Cyc t m (a,b)) where
+  gadget = (++) (flip CycPair zero <$> gadget @gad)
+                (     CycPair zero <$> gadget @gad)
+  {-# INLINABLE gadget #-}
+
+-----
+
+instance (Fact m, Reduce a b, CRTElt t a, TensorPowDec t b)
+  => Reduce (CycG t m a) (CycG t m b) where
+  reduce (Pow u)                 = Pow    $ reduce u
+  reduce (Dec u)                 = Dec    $ reduce u
+  reduce (CRT u)                 = Pow    $ reduce $ either toPow toPow u
+  reduce (Scalar c)              = Scalar $ reduce c
+  reduce (Sub (c :: CycG t l a)) = Sub (reduce c :: CycG t l b)
+  {-# INLINABLE reduce #-}
+
+instance (Reduce (CycG t m Int64) (CycG t m (ZqBasic q Int64)))
+  => Reduce (Cyc t m Int64) (Cyc t m (ZqBasic q Int64)) where
+  reduce = CycZqB . reduce . unCycI64
+  {-# INLINABLE reduce #-}
+
+instance (Reflects q Int64, Functor (t m))
+  => Reduce (Cyc t m Integer) (Cyc t m (ZqBasic q Int64)) where
+  reduce (PowIgr u) = CycZqB $ Pow $ fmap reduce u
+  reduce (DecIgr u) = CycZqB $ Dec $ fmap reduce u
+  {-# INLINABLE reduce #-}
+
+instance (Reflects q Double, FunctorCyc (Cyc t m) Double (RRq q Double))
+  => Reduce (Cyc t m Double) (Cyc t m (RRq q Double)) where
+  reduce = fmapCyc Nothing reduce
+  {-# INLINABLE reduce #-}
+
+instance (Reduce (Cyc t m z) (Cyc t m a), Reduce (Cyc t m z) (Cyc t m b))
+  => Reduce (Cyc t m z) (Cyc t m (a,b)) where
+  reduce z = CycPair (reduce z) (reduce z)
+  {-# INLINABLE reduce #-}
+
+-- | promoted from base ring, using the powerful basis for best geometry
+instance (Decompose gad (ZqBasic q z), CRTElt t (ZqBasic q z), Fact m,
+          -- for satisfying Decompose's Gadget superclass
+          ZeroTestable (ZqBasic q z), IntegralDomain (ZqBasic q z),
+          -- for satisfying Decompose's Reduce superclass w/o using m
+          CRTElt t z, ZeroTestable z)
+         => Decompose gad (CycG t m (ZqBasic q z)) where
+
+  type DecompOf (CycG t m (ZqBasic q z)) = CycG t m z
+
+  -- faster implementations: decompose directly in subring, which is
+  -- correct because we decompose in powerful basis
+  decompose (Scalar c) = Scalar <$> decompose @gad c
+  decompose (Sub c) = Sub <$> decompose @gad c
+  -- traverse: Traversable (CycRep t P m) and Applicative ZipList
+  decompose (Pow u) = getZipList $ Pow <$> traverse (ZipList . decompose @gad) u
+  decompose c = decompose @gad $ toPow' c
+  {-# INLINABLE decompose #-}
+
+-- specific to Int64 because we need to know constructor for lift type
+instance (Decompose gad (CycG t m (ZqBasic q Int64)),
+          -- for satisfying Decompose's Reduce superclass
+          Reduce (Cyc t m Int64) (Cyc t m (ZqBasic q Int64)))
+  => Decompose gad (Cyc t m (ZqBasic q Int64)) where
+
+  type DecompOf (Cyc t m (ZqBasic q Int64)) = Cyc t m Int64
+  decompose (CycZqB c) = CycI64 <$> decompose @gad c
+  {-# INLINABLE decompose #-}
+
+instance (Decompose gad (Cyc t m a), Decompose gad (Cyc t m b),
+         DecompOf (Cyc t m a) ~ DecompOf (Cyc t m b),
+         -- for satisfying Decompose's Reduce superclass
+         Reduce (DecompOf (Cyc t m a)) (Cyc t m (a, b)))
+  => Decompose gad (Cyc t m (a,b)) where
+  type DecompOf (Cyc t m (a,b)) = DecompOf (Cyc t m a)
+  decompose (CycPair a b) = (++) (decompose @gad a) (decompose @gad b)
+  {-# INLINABLE decompose #-}
+
+-----
+
+-- | promoted from base ring, using the decoding basis for best geometry
+instance (Correct gad (ZqBasic q z), CRTElt t (ZqBasic q z), Fact m,
+          -- satisfy Gadget superclass
+          ZeroTestable (ZqBasic q z), IntegralDomain (ZqBasic q z),
+          Traversable (CycRep t D m))
+  => Correct gad (CycG t m (ZqBasic q z)) where
+  -- sequence: Monad [] and Traversable (CycRep t D m)
+  -- sequenceA: Applicative (CycRep t D m) and Traversable (TaggedT gad [])
+  correct bs = Dec *** (Dec <$>) $
+               second sequence $ fmap fst &&& fmap snd $ correct @gad <$>
+               sequenceA (unCycGDec <$> bs)
+  {-# INLINABLE correct #-}
+
+-- specific to Int64 due to LiftOf. Can't auto-derive because of
+-- ambiguity of 'correct'
+instance Correct gad (CycG t m (ZqBasic q Int64))
+  => Correct gad (Cyc t m (ZqBasic q Int64)) where
+
+  correct = (CycZqB *** fmap CycI64) . correct @gad . fmap unCycZqB
+  {-# INLINABLE correct #-}
+  -- correct = coerce $
+  --   (correct @gad :: [CycG t m (ZqBasic q Int64)]
+  --                 -> (CycG t m (ZqBasic q Int64), [CycG t m Int64]))
+
+-- TODO: instance Correct gad (Cyc t m (a,b)) where
+-- seems hard; see Correct instance for pairs in Gadget.hs
+
+---------- Change of representation (internal use only) ----------
+
+toPow', toDec', toCRT' :: (Fact m, CRTElt t r) => CycG t m r -> CycG t m r
+{-# INLINABLE toPow' #-}
+{-# INLINABLE toDec' #-}
+{-# INLINABLE toCRT' #-}
+
+-- | Force to powerful-basis representation (for internal use only).
+toPow' c@(Pow _)  = c
+toPow' (Dec u)    = Pow $ toPow u
+toPow' (CRT u)    = Pow $ either toPow toPow u
+toPow' (Scalar c) = Pow $ scalarPow c
+toPow' (Sub c)    = toPow' $ embed' c
+
+-- | Force to decoding-basis representation (for internal use only).
+toDec' (Pow u)    = Dec $ toDec u
+toDec' c@(Dec _)  = c
+toDec' (CRT u)    = Dec $ either toDec toDec u
+toDec' (Scalar c) = Dec $ toDec $ scalarPow c
+toDec' (Sub c)    = toDec' $ embed' c
+
+-- | Force to a CRT representation (for internal use only).
+toCRT' (Pow u)    = CRT $ toCRT u
+toCRT' (Dec u)    = CRT $ toCRT u
+toCRT' c@(CRT _)  = c
+toCRT' (Scalar c) = CRT $ scalarCRT c
+-- CJP: the following is the fastest algorithm for when both source
+-- and target have the same CRTr/CRTe choice.  It is not the fastest
+-- when the choices are different (it will do an unnecessary CRT if
+-- input is non-CRT), but this is an unusual case.  Note: both calls
+-- to toCRT' are necessary in general, because embed' may not preserve
+-- CRT representation!
+toCRT' (Sub c)    = toCRT' $ embed' $ toCRT' c
+
+---------- Utility instances ----------
+
+instance (Random (t m r), Fact m, TensorCRT t Maybe r)
+  => Random (CycG t m r) where
+  random g = let (u,g') = random g
+             in (either Pow (CRT . Right) u, g')
+  {-# INLINABLE random #-}
+
+  randomR _ = error "randomR non-sensical for CycG"
+
+deriving instance Random (CycG t m Double)        => Random (Cyc t m Double)
+deriving instance Random (CycG t m Int64)         => Random (Cyc t m Int64)
+deriving instance Random (CycG t m (ZqBasic q z)) => Random (Cyc t m (ZqBasic q z))
+
+instance (Random (Cyc t m a), Random (Cyc t m b)) => Random (Cyc t m (a,b)) where
+  {-# SPECIALIZE instance (Fact m, Random (t m (ZqBasic q Int64)), TensorCRT t Maybe (ZqBasic q Int64), Random (Cyc t m b)) => Random (Cyc t m (ZqBasic q Int64, b)) #-}
+  random g = let (a,g') = random g
+                 (b,g'') = random g'
+                 in (CycPair a b, g'')
+  randomR _ = error "randomR non-sensical for Cyc"
+  {-# INLINABLE random #-}
+
+instance (Random (t m Integer), Fact m) => Random (Cyc t m Integer) where
+  random g = let (u,g') = random g in (PowIgr u, g')
+  randomR = error "randomR nonsensical for Cyc over Integer"
+  {-# INLINABLE random #-}
+
+instance (Random (t m (RRq q r)))
+  => Random (Cyc t m (RRq q r)) where
+  random g = let (u,g') = random g in (PowRRq u, g')
+  randomR = error "randomR nonsensical for Cyc over (RRq q r)"
+  {-# INLINABLE random #-}
+
+-----
+
+instance (Show r, Fact m, r' ~ CRTExt r, -- workaround TF in q'd constraint
+          forall m' . Fact m' => (Show (t m' r), Show (t m' r')))
+  => Show (CycG t m r) where
+  show (Pow x)         = "Cyc.Pow "    ++ show x
+  show (Dec x)         = "Cyc.Dec "    ++ show x
+  show (CRT (Left x))  = "Cyc.CRT "    ++ show x
+  show (CRT (Right x)) = "Cyc.CRT "    ++ show x
+  show (Scalar x)      = "Cyc.Scalar " ++ show x
+  show (Sub x)         = "Cyc.Sub "    ++ show x
+
+deriving instance Show (CycG t m Double)        => Show (Cyc t m Double)
+deriving instance Show (CycG t m Int64)         => Show (Cyc t m Int64)
+deriving instance Show (CycG t m (ZqBasic q z)) => Show (Cyc t m (ZqBasic q z))
+deriving instance (Show (Cyc t m a), Show (Cyc t m b))
+                  => Show (Cyc t m (a,b))
+
+deriving instance (Show (t m Integer))   => Show (Cyc t m Integer)
+deriving instance (Show (t m (RRq q r))) => Show (Cyc t m (RRq q r))
+
+-----
+
+instance (NFData r, Fact m, r' ~ CRTExt r,
+          forall m' . Fact m' => (NFData (t m' r), NFData (t m' r')))
+  => NFData (CycG t m r) where
+  rnf (Pow u)    = rnf u
+  rnf (Dec u)    = rnf u
+  rnf (CRT u)    = rnf u
+  rnf (Scalar u) = rnf u
+  rnf (Sub c)    = rnf c
+
+deriving instance NFData (CycG t m Double)        => NFData (Cyc t m Double)
+deriving instance NFData (CycG t m Int64)         => NFData (Cyc t m Int64)
+deriving instance NFData (CycG t m (ZqBasic q z)) => NFData (Cyc t m (ZqBasic q z))
+
+instance (NFData (Cyc t m a), NFData (Cyc t m b)) => NFData (Cyc t m (a,b)) where
+  rnf (CycPair a b) = rnf a `seq` rnf b
+
+instance (Fact m, forall m' . Fact m' => NFData (t m' Integer))
+  => NFData (Cyc t m Integer) where
+  rnf (PowIgr u) = rnf u
+  rnf (DecIgr u) = rnf u
+
+instance (Fact m, forall m' . Fact m' => NFData (t m' (RRq q r)))
+  => NFData (Cyc t m (RRq q r)) where
+  rnf (PowRRq u) = rnf u
+  rnf (DecRRq u) = rnf u
+
+---------- Protoable instances of Cyc/CycG ----------
+
+instance (Fact m, CRTElt t r, Protoable (CycRep t D m r))
+    => Protoable (CycG t m r) where
+  type ProtoType (CycG t m r) = ProtoType (CycRep t D m r)
+  toProto (Dec uc) = toProto uc
+  toProto x        = toProto $ toDec' x
+  fromProto x = Dec <$> fromProto x
+
+instance (Fact m, CRTElt t Double, Protoable (CycG t m Double))
+    => Protoable (Cyc t m Double) where
+  type ProtoType (Cyc t m Double) = ProtoType (CycG t m Double)
+  toProto = toProto . unCycDbl
+  fromProto x = CycDbl <$> fromProto x
+
+instance (Fact m, CRTElt t Int64, Protoable (CycG t m Int64))
+    => Protoable (Cyc t m Int64) where
+  type ProtoType (Cyc t m Int64) = ProtoType (CycG t m Int64)
+  toProto = toProto . unCycI64
+  fromProto x = CycI64 <$> fromProto x
+
+instance (Fact m, CRTElt t Double, Protoable (CycG t m (ZqBasic q z)))
+    => Protoable (Cyc t m (ZqBasic q z)) where
+  type ProtoType (Cyc t m (ZqBasic q z)) = ProtoType (CycG t m (ZqBasic q z))
+  toProto = toProto . unCycZqB
+  fromProto x = CycZqB <$> fromProto x
+
+instance (Fact m, CRTElt t Double, TensorPowDec t (RRq q Double),
+          Protoable (CycRep t D m (RRq q Double)))
+    => Protoable (Cyc t m (RRq q Double)) where
+  type ProtoType (Cyc t m (RRq q Double)) = ProtoType (CycG t m (RRq q Double))
+  toProto (PowRRq x) = toProto $ toDec x
+  toProto (DecRRq x) = toProto x
+  fromProto x = DecRRq <$> fromProto x
+
+---------- TH instances of FunctorCyc ----------
+
+-- CJP: the TH needs to appear before/after everything in the module
+-- so as not to screw up scoping
+
+let types = [ [t| Int64 |]
+            , [t| Double |]
+            , [t| ZqBasic $(varT (mkName "q")) $(varT (mkName "z")) |]
+            , [t| RRq $(varT (mkName "q")) $(varT (mkName "r")) |]
+            , [t| ( $(varT (mkName "a")) , $(varT (mkName "b"))) |] -- pair
+            ]
+    -- Instances that rely on IFunctor (in practice, Storable base
+    -- types), and go between any two IFElt types.
+    mkIFunctorCyc y z =
+      [d|
+       instance (Fact m, UnCyc t $y, UnCyc t $z,
+                 IFunctor t, IFElt t $y, IFElt t $z)
+         => FunctorCyc (Cyc t m) $y $z where
+         fmapCyc (Just L.Pow) f = cycPow . fmapI f . unCycPow
+         fmapCyc (Just L.Dec) f = cycDec . fmapI f . unCycDec
+         fmapCyc Nothing      f = fmapCyc (Just L.Pow) f
+       |]
+    -- Instances that map to Integer, hence need to use fmap.
+    mkFunctorCyc y =
+      [d|
+       instance (Fact m, Functor (t m), UnCyc t $y)
+         => FunctorCyc (Cyc t m) $y Integer where
+         fmapCyc (Just L.Pow) f = PowIgr . fmap f . unCycPow
+         fmapCyc (Just L.Dec) f = DecIgr . fmap f . unCycDec
+         fmapCyc Nothing      f = fmapCyc (Just L.Pow) f
+       |]
+    -- CJP TODO: if/when we get a way to convert Integer between Pow
+    -- and Dec, we can also have instances that go *from* Integer
+  in fmap concat $ sequence $
+     (mkIFunctorCyc <$> types <*> types) ++ (mkFunctorCyc <$> types)
diff --git a/Crypto/Lol/Cyclotomic/CycRep.hs b/Crypto/Lol/Cyclotomic/CycRep.hs
new file mode 100644
--- /dev/null
+++ b/Crypto/Lol/Cyclotomic/CycRep.hs
@@ -0,0 +1,752 @@
+{-|
+Module      : Crypto.Lol.Cyclotomic.CycRep
+Description : A low-level implementation of cyclotomic rings.
+Copyright   : (c) Eric Crockett, 2011-2017
+                  Chris Peikert, 2011-2017
+License     : GPL-3
+Maintainer  : ecrockett0@gmail.com
+Stability   : experimental
+Portability : POSIX
+
+  \( \def\Z{\mathbb{Z}} \)
+  \( \def\F{\mathbb{F}} \)
+  \( \def\Q{\mathbb{Q}} \)
+  \( \def\O{\mathcal{O}} \)
+
+A low-level implementation of cyclotomic rings that allows (and
+requires) the programmer to control the underlying representation
+of ring elements, i.e., powerful, decoding, or CRT basis.
+
+__WARNING:__ as with all fixed-point arithmetic, the functions
+associated with 'CycRep' may result in overflow (and thereby
+incorrect answers and potential security flaws) if the input
+arguments are too close to the bounds imposed by the base type.
+The acceptable range of inputs for each function is determined by
+the internal linear transforms and other operations it performs.
+-}
+
+{-# LANGUAGE AllowAmbiguousTypes        #-}
+{-# LANGUAGE ConstraintKinds            #-}
+{-# LANGUAGE DataKinds                  #-}
+{-# LANGUAGE FlexibleContexts           #-}
+{-# LANGUAGE FlexibleInstances          #-}
+{-# LANGUAGE GADTs                      #-}
+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
+{-# LANGUAGE InstanceSigs               #-}
+{-# LANGUAGE MultiParamTypeClasses      #-}
+{-# LANGUAGE PolyKinds                  #-}
+{-# LANGUAGE RankNTypes                 #-}
+{-# LANGUAGE RebindableSyntax           #-}
+{-# LANGUAGE ScopedTypeVariables        #-}
+{-# LANGUAGE TypeApplications           #-}
+{-# LANGUAGE TypeFamilies               #-}
+{-# LANGUAGE TypeOperators              #-}
+{-# LANGUAGE UndecidableInstances       #-}
+
+module Crypto.Lol.Cyclotomic.CycRep
+(
+-- * Data types and constraints
+  CycRep, P, D, C, E, CycRepEC, CycRepPC, CRTElt
+-- * Changing representation
+, toPow, toDec, toCRT
+-- * Scalars
+, scalarPow, scalarCRT
+-- * Basic operations
+, mulGPow, mulGDec, mulGCRTC, divGPow, divGDec, divGCRTC, gSqNormDec
+-- * Error sampling
+, tweakedGaussian, roundedGaussian, cosetGaussian
+-- * Inter-ring operations and values
+, embedPow, embedCRTC, embedCRTE
+, twacePow, twaceDec, twaceCRTC, twaceCRTE
+, coeffsPow, coeffsDec, powBasis, crtSet
+) where
+
+import Crypto.Lol.CRTrans
+import Crypto.Lol.Cyclotomic.CRTSentinel
+import Crypto.Lol.Cyclotomic.Tensor      hiding (divGDec, divGPow,
+                                          embedCRT, embedPow, gSqNormDec,
+                                          mulGDec, mulGPow, scalarCRT,
+                                          scalarPow, twaceCRT)
+import Crypto.Lol.Prelude                as LP
+import Crypto.Lol.Reflects
+import Crypto.Lol.Types.FiniteField
+import Crypto.Lol.Types.IFunctor
+import Crypto.Lol.Types.Proto
+import Crypto.Lol.Types.Unsafe.ZqBasic
+
+import qualified Crypto.Lol.Cyclotomic.Tensor as T
+
+import qualified Algebra.Additive     as Additive (C)
+import qualified Algebra.Module       as Module (C)
+import qualified Algebra.Ring         as Ring (C)
+import qualified Algebra.ZeroTestable as ZeroTestable (C)
+
+import Control.Applicative    as A
+import Control.DeepSeq
+import Control.Monad.Identity (Identity (..))
+import Control.Monad.Random   hiding (ap, lift)
+import Data.Foldable          as F
+import Data.Traversable
+
+--import qualified Debug.Trace as DT
+
+-- | Represents a cyclotomic ring such as \(\Z[\zeta_m]\),
+-- \(\Z_q[\zeta_m]\), and \(\Q(\zeta_m)\) in an explicit
+-- representation: @t@ is the 'TensorPowDec' type for storing coefficient
+-- tensors; @m@ is the cyclotomic index; @rep@ is the representation
+-- (e.g., 'P', 'D', 'C', 'E'); @r@ is the base ring of the
+-- coefficients (e.g., \(\Z\), \(\Z_q\)).
+
+-- | Nullary index type representing the powerful basis.
+data P
+-- | Nullary index type representing the decoding basis.
+data D
+-- | Nullary index type representing the CRT basis over base ring.
+data C
+-- | Nullary index type representing the CRT basis over extension of
+-- base ring.
+data E
+
+data family CycRep (t :: Factored -> * -> *) rep (m :: Factored) r
+
+newtype instance CycRep t P m r = Pow  (t m r) deriving (Eq, ZeroTestable.C)
+newtype instance CycRep t D m r = Dec  (t m r) deriving (Eq, ZeroTestable.C)
+
+-- C/ESentinel enforces invariant that exactly one of the following
+-- two can be created for a given (t,m,r).
+data    instance CycRep t C m r = CRTC !(CSentinel t m r) !(t m r) deriving (Eq)
+-- can't derive ZT due to sentinel
+
+data    instance CycRep t E m r = CRTE !(ESentinel t m r) !(t m (CRTExt r))
+-- no Eq due to precision
+
+{- CJP: old GADT definition of CycRep, which seems less
+   runtime-efficient than the data family definition.
+
+data CycRep t rep (m :: Factored) r where
+  Pow  :: !(t m r) -> CycRep t P m r
+  Dec  :: !(t m r) -> CycRep t D m r
+  CRTC :: !(CSentinel t m r) -> !(t m r) -> CycRep t C m r
+  CRTE :: !(ESentinel t m r) -> !(t m (CRTExt r)) -> CycRep t E m r
+-}
+
+-- | Convenient synonym for either CRT representation.
+type CycRepEC t m r = Either (CycRep t E m r) (CycRep t C m r)
+
+-- | Convenient synonym for random sampling.
+type CycRepPC t m r = Either (CycRep t P m r) (CycRep t C m r)
+
+-- | Constraints needed for CRT-related operations on 'CycRep' data.
+type CRTElt t r = (TensorG t r, CRTEmbed r,
+                   TensorCRT t Maybe r, TensorCRT t Identity (CRTExt r))
+
+-- | Embed a scalar from the base ring.
+scalarPow :: (TensorPowDec t r, Fact m) => r -> CycRep t P m r
+scalarPow = Pow . T.scalarPow
+{-# INLINABLE scalarPow #-}
+
+-- | Embed a scalar from the base ring.
+scalarCRT :: (Fact m, CRTElt t r) => r -> CycRepEC t m r
+scalarCRT r = case crtSentinel of
+  Right s -> Right $ CRTC s $ scalarCRTCS s r
+  Left  s -> Left  $ CRTE s $ runIdentity T.scalarCRT $ toExt r
+{-# INLINABLE scalarCRT #-}
+
+
+---------- Numeric Prelude instances ----------
+
+-- ZeroTestable instances
+
+{- CJP: only need these instances for GADT version of CycRep; for data
+   family they are auto-derived.
+
+instance ZeroTestable (t m r) => ZeroTestable.C (CycRep t P m r) where
+  isZero (Pow v) = isZero v
+  {-# INLINABLE isZero #-}
+
+instance ZeroTestable (t m r) => ZeroTestable.C (CycRep t D m r) where
+  isZero (Dec v) = isZero v
+  {-# INLINABLE isZero #-}
+
+-}
+
+-- ZT for P,D auto-derived
+
+instance ZeroTestable (t m r) => ZeroTestable.C (CycRep t C m r) where
+  -- can't derive this because of sentinel
+  isZero (CRTC _ v) = isZero v
+  {-# INLINABLE isZero #-}
+
+-- no ZT instance for E due to precision
+
+-- Additive instances
+
+-- TODO: replace these implementations to use Additive instance of
+-- underlying tensor? Would this require (forall m . Fact m => Additive (t m))?
+
+instance (TensorPowDec t r, Fact m) => Additive.C (CycRep t P m r) where
+  {-# SPECIALIZE instance (TensorPowDec t Int64, Fact m) => Additive.C (CycRep t P m Int64) #-}
+  {-# SPECIALIZE instance (TensorPowDec t Double, Fact m) => Additive.C (CycRep t P m Double) #-}
+  {-# SPECIALIZE instance (TensorPowDec t (ZqBasic q Int64), Fact m) => Additive.C (CycRep t P m (ZqBasic q Int64)) #-}
+
+  zero = Pow $ T.scalarPow zero
+  (Pow v1) + (Pow v2) = Pow $ zipWithI (+) v1 v2
+  (Pow v1) - (Pow v2) = Pow $ zipWithI (-) v1 v2
+  negate (Pow v) = Pow $ fmapI negate v
+  {-# INLINABLE zero #-}
+  {-# INLINABLE (+) #-}
+  {-# INLINABLE (-) #-}
+  {-# INLINABLE negate #-}
+
+instance (TensorPowDec t r, Fact m) => Additive.C (CycRep t D m r) where
+  {-# SPECIALIZE instance (TensorPowDec t Int64, Fact m) => Additive.C (CycRep t D m Int64) #-}
+  {-# SPECIALIZE instance (TensorPowDec t Double, Fact m) => Additive.C (CycRep t D m Double) #-}
+  {-# SPECIALIZE instance (TensorPowDec t (ZqBasic q Int64), Fact m) => Additive.C (CycRep t D m (ZqBasic q Int64)) #-}
+
+  zero = Dec $ T.scalarPow zero -- scalarPow works because it's zero
+  (Dec v1) + (Dec v2) = Dec $ zipWithI (+) v1 v2
+  (Dec v1) - (Dec v2) = Dec $ zipWithI (-) v1 v2
+  negate (Dec v) = Dec $ fmapI negate v
+  {-# INLINABLE zero #-}
+  {-# INLINABLE (+) #-}
+  {-# INLINABLE (-) #-}
+  {-# INLINABLE negate #-}
+
+-- | only for appropriate CRT representation (otherwise 'zero' would
+-- violate internal invariant)
+instance (Fact m, CRTElt t r) => Additive.C (CycRepEC t m r) where
+  {-# SPECIALIZE instance (Fact m, CRTElt t Int64) => Additive.C (CycRepEC t m Int64) #-}
+  {-# SPECIALIZE instance (Fact m, CRTElt t Double) => Additive.C (CycRepEC t m Double) #-}
+  {-# SPECIALIZE instance (Fact m, CRTElt t (ZqBasic q Int64)) => Additive.C (CycRepEC t m (ZqBasic q Int64)) #-}
+
+  zero = scalarCRT zero
+
+  -- CJP: precision OK?  Alternatively, switch to pow and back after
+  -- adding/subtracting.  Expensive, but necessary given output type.
+  (Right (CRTC s v1)) + (Right (CRTC _ v2)) = Right $ CRTC s $ zipWithI (+) v1 v2
+  (Left (CRTE s v1)) + (Left (CRTE _ v2)) = Left $ CRTE s $ zipWithI (+) v1 v2
+  _ + _ = error "CycRep (+) internal error: mixed CRTC/CRTE"
+
+  (Right (CRTC s v1)) - (Right (CRTC _ v2)) = Right $ CRTC s $ zipWithI (-) v1 v2
+  (Left (CRTE s v1)) - (Left (CRTE _ v2)) = Left $ CRTE s $ zipWithI (-) v1 v2
+  _ - _ = error "CycRep (-) internal error: mixed CRTC/CRTE"
+
+  negate (Right (CRTC s v)) = Right $ CRTC s $ fmapI negate v
+  negate (Left (CRTE s v))  = Left $ CRTE s $ fmapI negate v
+
+  {-# INLINABLE zero #-}
+  {-# INLINABLE (+) #-}
+  {-# INLINABLE (-) #-}
+  {-# INLINABLE negate #-}
+
+-- | only for appropriate CRT representation
+instance (Fact m, CRTElt t r) => Ring.C (CycRepEC t m r) where
+  {-# SPECIALIZE instance (Fact m, CRTElt t Int64) => Ring.C (CycRepEC t m Int64) #-}
+  {-# SPECIALIZE instance (Fact m, CRTElt t Double) => Ring.C (CycRepEC t m Double) #-}
+  {-# SPECIALIZE instance (Fact m, CRTElt t (ZqBasic q Int64)) => Ring.C (CycRepEC t m (ZqBasic q Int64)) #-}
+
+  one = scalarCRT one
+  fromInteger c = scalarCRT $ fromInteger c
+
+  (Right (CRTC s v1)) * (Right (CRTC _ v2)) = Right $ CRTC s $ zipWithI (*) v1 v2
+  (Left (CRTE s v1)) * (Left (CRTE _ v2)) = Left $ CRTE s $ zipWithI (*) v1 v2
+  _ * _ = error "CycRep internal error: mixed CRTC/CRTE"
+
+  {-# INLINABLE one #-}
+  {-# INLINABLE fromInteger #-}
+  {-# INLINABLE (*) #-}
+
+
+instance (Ring r, TensorPowDec t r, Fact m) => Module.C r (CycRep t P m r) where
+  {-# SPECIALIZE instance (Fact m, TensorPowDec t Int64) => Module.C Int64 (CycRep t P m Int64) #-}
+  {-# SPECIALIZE instance (Fact m, TensorPowDec t Double) => Module.C Double (CycRep t P m Double) #-}
+  {-# SPECIALIZE instance (Fact m, TensorPowDec t (ZqBasic q Int64), Reflects q Int64) => Module.C (ZqBasic q Int64) (CycRep t P m (ZqBasic q Int64)) #-}
+
+  r *> (Pow v) = Pow $ fmapI (r *) v
+  {-# INLINABLE (*>) #-}
+
+instance (Ring r, TensorPowDec t r, Fact m) => Module.C r (CycRep t D m r) where
+  {-# SPECIALIZE instance (Fact m, TensorPowDec t Int64) => Module.C Int64 (CycRep t D m Int64) #-}
+  {-# SPECIALIZE instance (Fact m, TensorPowDec t Double) => Module.C Double (CycRep t D m Double) #-}
+  {-# SPECIALIZE instance (Fact m, TensorPowDec t (ZqBasic q Int64), Reflects q Int64) => Module.C (ZqBasic q Int64) (CycRep t D m (ZqBasic q Int64)) #-}
+
+  r *> (Dec v) = Dec $ fmapI (r *) v
+  {-# INLINABLE (*>) #-}
+
+instance (CRTElt t r, Fact m) => Module.C r (CycRepEC t m r) where
+  {-# SPECIALIZE instance (CRTElt t Int64, Fact m) => Module.C Int64 (CycRepEC t m Int64) #-}
+  {-# SPECIALIZE instance (CRTElt t Double, Fact m) => Module.C Double (CycRepEC t m Double) #-}
+  {-# SPECIALIZE instance (CRTElt t (ZqBasic q Int64), Fact m) => Module.C (ZqBasic q Int64) (CycRepEC t m (ZqBasic q Int64)) #-}
+
+  r *> (Right (CRTC s v)) = Right $ CRTC s $ fmapI (r *) v
+  r *> (Left (CRTE s v)) = Left $ CRTE s $ fmapI (toExt r *) v
+  {-# INLINABLE (*>) #-}
+
+-- | \(R_p\) is an \(\F_{p^d}\)-module when \(d\) divides \(\varphi(m)\), by
+-- applying \(d\)-dimensional \(\F_p\)-linear transform on \(d\)-dim chunks of
+-- powerful basis coeffs.
+instance (GFCtx fp d, Fact m, TensorPowDec t fp, Module (GF fp d) (t m fp))
+         => Module.C (GF fp d) (CycRep t P m fp) where
+  -- can use any r-basis to define module mult, but must be
+  -- consistent.
+  r *> (Pow v) = Pow $ r LP.*> v
+
+
+instance (Fact m, Reduce a b, IFunctor t, IFElt t a, IFElt t b)
+         => Reduce (CycRep t P m a) (CycRep t P m b) where
+  {-# SPECIALIZE instance (Fact m, Reflects q Int64, IFunctor t, IFElt t Int64, IFElt t (ZqBasic q Int64)) => Reduce (CycRep t P m Int64) (CycRep t P m (ZqBasic q Int64)) #-}
+
+  reduce (Pow v) = Pow $ fmapI reduce v
+  {-# INLINABLE reduce #-}
+
+instance (Fact m, Reduce a b, IFunctor t, IFElt t a, IFElt t b)
+    => Reduce (CycRep t D m a) (CycRep t D m b) where
+  {-# SPECIALIZE instance (Fact m, Reflects q Int64, IFunctor t, IFElt t Int64, IFElt t (ZqBasic q Int64)) => Reduce (CycRep t D m Int64) (CycRep t D m (ZqBasic q Int64)) #-}
+
+  reduce (Dec v) = Dec $ fmapI reduce v
+  {-# INLINABLE reduce #-}
+
+-- CJP: no Reduce for C because CRT basis may not exist for target
+-- type
+
+type instance LiftOf (CycRep t P m r) = CycRep t P m (LiftOf r)
+type instance LiftOf (CycRep t D m r) = CycRep t D m (LiftOf r)
+
+instance (Fact m, Lift' r, IFunctor t, IFElt t r, IFElt t (LiftOf r))
+         => Lift' (CycRep t P m r) where
+  {-# SPECIALIZE instance (Fact m, Reflects q Int64, IFunctor t, IFElt t Int64, IFElt t (ZqBasic q Int64)) => Lift' (CycRep t P m (ZqBasic q Int64)) #-}
+
+  lift (Pow v) = Pow $ fmapI lift v
+  {-# INLINABLE lift #-}
+
+instance (Lift' r, IFunctor t, IFElt t r, IFElt t (LiftOf r), Fact m)
+         => Lift' (CycRep t D m r) where
+  {-# SPECIALIZE instance (Fact m, Reflects q Int64, IFunctor t, IFElt t Int64, IFElt t (ZqBasic q Int64)) => Lift' (CycRep t D m (ZqBasic q Int64)) #-}
+
+  lift (Dec v) = Dec $ fmapI lift v
+  {-# INLINABLE lift #-}
+
+-- CJP: no Lift' for C because CRT basis may not exist for target type
+
+instance (Rescale a b, TensorPowDec t a, TensorPowDec t b, Fact m)
+         => Rescale (CycRep t P m a) (CycRep t P m b) where
+  rescale (Pow v) = Pow $ fmapI rescale v
+  {-# INLINABLE rescale #-}
+
+instance (Rescale a b, TensorPowDec t a, TensorPowDec t b, Fact m)
+         => Rescale (CycRep t D m a) (CycRep t D m b) where
+  rescale (Dec v) = Dec $ fmapI rescale v
+  {-# INLINABLE rescale #-}
+
+-- CJP: no Rescale for C because CRT basis may not exist for target
+-- type
+
+-- CJP: we don't instantiate RescaleCyc because it requires changing bases
+
+-- CJP: we don't instantiate Gadget etc., because (1) their methods
+-- wouldn't be efficient, and (2) their superclass constraints are not
+-- satisfied anyway (e.g., Ring for P rep).
+
+-- | multiply by the special element @g@
+mulGPow :: (Fact m, TensorG t r) => CycRep t P m r -> CycRep t P m r
+{-# INLINABLE mulGPow #-}
+mulGPow (Pow v) = Pow $ T.mulGPow v
+
+-- | multiply by the special element @g@
+mulGDec :: (Fact m, TensorG t r) => CycRep t D m r -> CycRep t D m r
+{-# INLINABLE mulGDec #-}
+mulGDec (Dec v) = Dec $ T.mulGDec v
+
+-- | multiply by the special element @g@
+mulGCRTC :: (Fact m, TensorCRT t Maybe r)
+         => CycRep t C m r -> CycRep t C m r
+{-# INLINABLE mulGCRTC #-}
+mulGCRTC (CRTC s v) = CRTC s $ mulGCRTCS s v
+
+-- Note: We do not implement divGCRTE because we can't tell whether
+-- the element is actually divisible by g when using the CRT extension
+-- basis.
+
+-- | Divide by the special element \(g_m\).
+-- WARNING: this implementation is not a constant-time algorithm, so
+-- information about the argument may be leaked through a timing
+-- channel.
+divGPow :: (Fact m, TensorG t r) => CycRep t P m r -> Maybe (CycRep t P m r)
+{-# INLINABLE divGPow #-}
+divGPow (Pow v) = Pow <$> T.divGPow v
+
+-- | Similar to 'divGPow'.
+divGDec :: (Fact m, TensorG t r) => CycRep t D m r -> Maybe (CycRep t D m r)
+{-# INLINABLE divGDec #-}
+divGDec (Dec v) = Dec <$> T.divGDec v
+
+-- | Similar to 'divGPow'.
+divGCRTC :: (Fact m, CRTElt t r) => CycRep t C m r -> CycRep t C m r
+{-# INLINE divGCRTC #-}
+divGCRTC (CRTC s v) = CRTC s $ divGCRTCS s v
+
+-- | Yield the scaled squared norm of \(g_m \cdot e\) under
+-- the canonical embedding, namely,
+-- \(\hat{m}^{-1} \cdot \| \sigma(g_m \cdot e) \|^2\) .
+gSqNormDec :: (TensorGSqNorm t r, Fact m) => CycRep t D m r -> r
+{-# INLINABLE gSqNormDec #-}
+gSqNormDec (Dec v) = T.gSqNormDec v
+
+-- | Sample from the "tweaked" Gaussian error distribution \(t\cdot D\) in
+-- the decoding basis, where \(D\) has scaled variance \(v\).
+tweakedGaussian :: (TensorGaussian t q, MonadRandom rnd, Fact m, ToRational v)
+                   => v -> rnd (CycRep t D m q)
+{-# INLINABLE tweakedGaussian #-}
+tweakedGaussian = fmap Dec . tweakedGaussianDec
+
+-- | Sample from the tweaked Gaussian with given scaled variance,
+-- deterministically rounded using the decoding basis. (This
+-- implementation uses 'Double' precision to generate the Gaussian
+-- sample, which might not be sufficient for rigorous proof-based
+-- security.)
+roundedGaussian :: forall v rnd t m z .
+  (TensorGaussian t Double, IFElt t Double, IFunctor t, ToInteger z,
+   IFElt t z, Fact m, ToRational v, MonadRandom rnd)
+  => v -> rnd (CycRep t D m z)
+{-# INLINABLE roundedGaussian #-}
+roundedGaussian svar =
+  Dec . fmapI (roundMult one) <$> (tweakedGaussianDec svar :: rnd (t m Double))
+
+-- | Sample from the tweaked Gaussian with scaled variance \(v \cdot
+-- p^2\), deterministically rounded to the given coset of \(R_p\)
+-- using the decoding basis. (This implementation uses 'Double'
+-- precision to generate the Gaussian sample, which may not be
+-- sufficient for rigorous proof-based security.)
+cosetGaussian :: forall t m zp z v rnd .
+  (TensorGaussian t Double, IFElt t Double, IFunctor t, Lift zp z, Mod zp,
+   z ~ ModRep zp, IFElt t zp, IFElt t z, Fact m, ToRational v, MonadRandom rnd)
+  => v -> CycRep t D m zp -> rnd (CycRep t D m z)
+{-# INLINABLE cosetGaussian #-}
+cosetGaussian =
+  let pval = fromIntegral $ modulus @zp
+  in \ svar (Dec c) ->
+    Dec . zipWithI roundCoset c <$>
+    (tweakedGaussianDec (svar*pval*pval) :: rnd (t m Double))
+
+
+----- inter-ring operations
+
+-- | Embed into an extension ring, for the powerful basis.
+embedPow :: (TensorPowDec t r, m `Divides` m') => CycRep t P m r -> CycRep t P m' r
+embedPow (Pow v) = Pow $ T.embedPow v
+{-# INLINABLE embedPow #-}
+
+-- | Embed into an extension ring, for the CRT basis.  (The output is
+-- an 'Either' because the extension ring might not support 'C'.)
+embedCRTC :: (m `Divides` m', CRTElt t r)
+             => CycRep t C m r -> Either (CycRep t P m' r) (CycRep t C m' r)
+{-# INLINABLE embedCRTC #-}
+embedCRTC x@(CRTC s v) =
+  case crtSentinel of
+    -- go to CRTC if valid, else go to Pow
+    Left  _  -> Left $ embedPow $ toPow x
+    Right s' -> Right $ CRTC s' $ embedCRTCS s s' v
+
+-- | Similar to 'embedCRTC'.  (The output is an 'Either' because the
+-- extension ring might support 'C', in which case we never use 'E'.)
+embedCRTE :: forall m m' t r . (m `Divides` m', CRTElt t r)
+             => CycRep t E m r -> Either (CycRep t P m' r) (CycRep t E m' r)
+{-# INLINABLE embedCRTE #-}
+embedCRTE x@(CRTE _ v) =
+  case crtSentinel of
+    -- go to CRTE if valid, else go to Pow
+    Left  s -> Right $ CRTE s $ runIdentity T.embedCRT v
+    Right _ -> Left $ embedPow $ toPow x
+
+-- | Twace into a subring, for the powerful basis.
+twacePow :: (TensorPowDec t r, m `Divides` m')
+         => CycRep t P m' r -> CycRep t P m r
+{-# INLINABLE twacePow #-}
+twacePow (Pow v) = Pow $ twacePowDec v
+
+-- | Twace into a subring, for the decoding basis.
+twaceDec :: (TensorPowDec t r, m `Divides` m') => CycRep t D m' r -> CycRep t D m r
+{-# INLINABLE twaceDec #-}
+twaceDec (Dec v) = Dec $ twacePowDec v
+
+-- | Twace into a subring, for the CRT basis.  (The output is an
+-- 'Either' because the subring might not support 'C'.)
+twaceCRTC :: (m `Divides` m', CRTElt t r) => CycRep t C m' r -> CycRepPC t m r
+{-# INLINE twaceCRTC #-}
+twaceCRTC x@(CRTC s' v) =
+  case crtSentinel of
+    -- go to CRTC if valid for target, else go to Pow
+    Left  _ -> Left $ twacePow $ toPow x
+    Right s -> Right $ CRTC s $ twaceCRTCS s' s v
+
+-- | Similar to 'twaceCRTC'.  (The output is an 'Either' because the
+-- subring might support 'C', in which case we never use 'E'.)
+twaceCRTE :: forall t m m' r . (m `Divides` m', CRTElt t r)
+             => CycRep t E m' r -> Either (CycRep t P m r) (CycRep t E m r)
+{-# INLINABLE twaceCRTE #-}
+twaceCRTE x@(CRTE _ v) =
+  case crtSentinel of
+    -- go to CRTE if valid for target, else go to Pow
+    Left  s -> Right $ CRTE s $ runIdentity T.twaceCRT v
+    Right _ -> Left $ twacePow $ toPow x
+
+-- | Yield the \(\O_m\)-coefficients of an \(\O_{m'}\)-element,
+-- with respect to the relative powerful \(\O_m\)-basis.
+coeffsPow :: (TensorPowDec t r, m `Divides` m') => CycRep t P m' r -> [CycRep t P m r]
+{-# INLINABLE coeffsPow #-}
+coeffsPow (Pow v) = Pow <$> coeffs v
+
+-- | Yield the \(\O_m\)-coefficients of an \(\O_{m'}\) element,
+-- with respect to the relative decoding \(\O_m\)-basis.
+coeffsDec :: (TensorPowDec t r, m `Divides` m') => CycRep t D m' r -> [CycRep t D m r]
+{-# INLINABLE coeffsDec #-}
+coeffsDec (Dec v) = Dec <$> coeffs v
+
+-- | The relative powerful basis of \(\O_{m'} / \O_m\).
+powBasis :: forall m m' t r .
+  (TensorPowDec t r, m `Divides` m') => [CycRep t P m' r]
+{-# INLINABLE powBasis #-}
+powBasis = fmap Pow $ untag $ powBasisPow @t @r @m
+
+-- | The relative mod-\(r\) CRT set of \(\O_{m'} / \O_m\),
+-- represented with respect to the powerful basis (which seems to be
+-- the best choice for typical use cases).
+crtSet :: forall m m' pp p mbar m'bar t z zpp .
+          (m `Divides` m', p ~ PrimePP pp, mbar ~ PFree p m, m'bar ~ PFree p m',
+           PPow pp, Prime p, zpp ~ ZqBasic pp z,
+           ToInteger z, CRTElt t zpp, TensorCRTSet t (ZqBasic p z))
+       => [CycRep t P m' (ZqBasic pp z)]
+{-# INLINABLE crtSet #-}
+crtSet =
+  -- CJP: consider using traceEvent or traceMarker
+  --DT.trace ("CycRep.crtSet: m = " ++
+  --          show (proxy valueFact (Proxy::Proxy m)) ++ ", m'= " ++
+  --          show (proxy valueFact (Proxy::Proxy m'))) $
+  let (p,e) = ppPPow @pp
+      -- raise to the p^(e-1) power iteratively (one factor of p at a
+      -- time), switching back to pow basis each time so that we don't
+      -- lose precision!  (This fixes a bug witnessed for moderate
+      -- values of e.)
+      expon :: (Fact m'bar, ToPowDec t rep (ZqBasic pp z))
+        => Int -> CycRep t rep m'bar zpp -> CycRep t P m'bar zpp
+      expon 1  = toPow
+      expon e' = toPowCE . (^p) . toCRT . expon (e'-1)
+  in embedPow . expon e . Dec . fmapI (ZqB . unZqB) <$> -- safe!
+     (untag $ crtSetDec @t @_ @mbar :: [t m'bar (ZqBasic p z)])
+     \\ pFreeDivides @p @m @m' \\ pSplitTheorems @p @m \\ pSplitTheorems @p @m'
+
+
+--------- Changing representation ------------------
+
+class ToPowDec t rep r where
+  -- | Convert to powerful-basis representation.
+  toPow :: (Fact m) => CycRep t rep m r -> CycRep t P m r
+  -- | Convert to decoding-basis representation.
+  toDec :: (Fact m) => CycRep t rep m r -> CycRep t D m r
+
+-- | separate class because some base rings don't have a CRT basis
+class ToCRT t rep r where
+  -- | Convert to an appropriate CRT-basis representation.
+  toCRT :: (Fact m) => CycRep t rep m r -> Either (CycRep t E m r) (CycRep t C m r)
+
+instance TensorPowDec t r => ToPowDec t P r where
+  toPow = id
+  toDec (Pow v) = Dec $ powToDec v
+  {-# INLINABLE toPow #-}
+  {-# INLINABLE toDec #-}
+
+instance CRTElt t r => ToCRT t P r where
+  toCRT (Pow v) = case crtSentinel of
+                    Right s -> Right $ CRTC s $ crtCS s v
+                    Left  s -> Left  $ CRTE s $ runIdentity crt $ fmapI toExt v
+  {-# INLINABLE toCRT #-}
+
+instance TensorPowDec t r => ToPowDec t D r where
+  toPow (Dec v) = Pow $ decToPow v
+  toDec = id
+  {-# INLINABLE toPow #-}
+  {-# INLINABLE toDec #-}
+
+instance CRTElt t r => ToCRT t D r where
+  toCRT = toCRT . toPow
+  {-# INLINABLE toCRT #-}
+
+instance CRTElt t r => ToPowDec t C r where
+  toPow (CRTC s v) = Pow $ crtInvCS s v
+  toDec = toDec . toPow
+  {-# INLINABLE toPow #-}
+  {-# INLINABLE toDec #-}
+
+instance ToCRT t C r where
+  toCRT = Right
+  {-# INLINABLE toCRT #-}
+
+instance CRTElt t r => ToPowDec t E r where
+  toPow (CRTE _ v) = Pow $ fmapI fromExt $ runIdentity crtInv v
+  toDec = toDec . toPow
+  {-# INLINABLE toPow #-}
+  {-# INLINABLE toDec #-}
+
+instance ToCRT t E r where
+  toCRT = Left
+  {-# INLINABLE toCRT #-}
+
+{- CJP: non-class-based toPow etc., which can be defined for CycRep as a
+   GADT or data family. But it doesn't quite work for us because the
+   'CRTElt t r' constraint is too strong for 'r ~ RRq q Double', which
+   can't have a CRTrans instance.
+
+{-# INLINABLE toPow #-}
+toPow :: (Fact m, CRTElt t r) => CycRep t rep m r -> CycRep t P m r
+toPow = \case
+  c@(Pow _)  -> c
+  (Dec  v)   -> Pow $ decToPow v
+  (CRTC s v) -> Pow $ crtInvCS s v
+  (CRTE _ v) -> Pow $ fmapI fromExt $ runIdentity crtInv v
+
+{-# INLINABLE toDec #-}
+toDec :: (Fact m, CRTElt t r) => CycRep t rep m r -> CycRep t D m r
+toDec = \case
+  c@(Dec _)  -> c
+  (Pow  v)   -> Dec $ powToDec v
+  (CRTC s v) -> Dec $ powToDec $ crtInvCS s v
+  (CRTE _ v) -> Dec $ powToDec $ fmapI fromExt $ runIdentity crtInv v
+
+{-# INLINABLE toCRT #-}
+toCRT :: (Fact m, CRTElt t r) => CycRep t rep m r -> CycRepEC t m r
+toCRT = \case
+  c@(CRTC _ _) -> Right c
+  c@(CRTE _ _) -> Left c
+  (Pow v)      -> go v
+  (Dec v)      -> go $ decToPow v
+  where go v =
+          case crtSentinel of
+            Right s -> Right $ CRTC s $ crtCS s v
+            Left  s -> Left  $ CRTE s $ runIdentity crt $ fmapI toExt v
+-}
+
+-- | Convenient version of 'toPow' for 'Either' CRT basis type.
+toPowCE :: (Fact m, CRTElt t r) => CycRepEC t m r -> CycRep t P m r
+{-# INLINABLE toPowCE #-}
+toPowCE (Left u)  = toPow u
+toPowCE (Right u) = toPow u
+
+
+---------- Category-theoretic instances ----------
+
+----- No instances for E because types (and math) don't make sense.
+
+-- | apply coefficient-wise
+instance IFunctor t => IFunctor (CycRep t P) where
+  type IFElt (CycRep t P) a = IFElt t a
+  fmapI    f (Pow v)         = Pow $ fmapI f v
+  zipWithI f (Pow v) (Pow w) = Pow $ zipWithI f v w
+
+-- | apply coefficient-wise
+instance IFunctor t => IFunctor (CycRep t D) where
+  type IFElt (CycRep t D) a = IFElt t a
+  fmapI    f (Dec v)         = Dec $ fmapI f v
+  zipWithI f (Dec v) (Dec w) = Dec $ zipWithI f v w
+
+-- | apply coefficient-wise
+instance Functor (t m) => Functor (CycRep t P m) where
+  {-# INLINABLE fmap #-}
+  fmap f (Pow x) = Pow $ f <$> x
+
+-- | apply coefficient-wise
+instance Functor (t m) => Functor (CycRep t D m) where
+  {-# INLINABLE fmap #-}
+  fmap f (Dec x) = Dec $ f <$> x
+
+-- No Functor instance for C, because CRTrans a doesn't imply CRTrans b.
+
+instance Applicative (t m) => Applicative (CycRep t P m) where
+  pure = Pow . pure
+  (Pow f) <*> (Pow v) = Pow $ f <*> v
+  {-# INLINABLE pure #-}
+  {-# INLINABLE (<*>) #-}
+
+instance Applicative (t m) => Applicative (CycRep t D m) where
+  pure = Dec . pure
+  (Dec f) <*> (Dec v) = Dec $ f <*> v
+  {-# INLINABLE pure #-}
+  {-# INLINABLE (<*>) #-}
+
+-- CJP: no Applicative instance for C, because 'pure' would circumvent
+-- the invariant.  Moreover, `CRTrans (a -> b)` and `CRTrans a`
+-- doesn't imply `CRTrans b`.
+
+instance Foldable (t m) => Foldable (CycRep t P m) where
+  foldr f z (Pow x) = foldr f z x
+
+instance Foldable (t m) => Foldable (CycRep t D m) where
+  foldr f z (Dec x) = foldr f z x
+
+-- no Traversable for C, but it is Foldable
+instance Foldable (t m) => Foldable (CycRep t C m) where
+  foldr f b (CRTC _ v) = foldr f b v
+
+instance Traversable (t m) => Traversable (CycRep t P m) where
+  {-# INLINABLE traverse #-}
+  traverse f (Pow v) = Pow <$> traverse f v
+
+instance Traversable (t m) => Traversable (CycRep t D m) where
+  {-# INLINABLE traverse #-}
+  traverse f (Dec v) = Dec <$> traverse f v
+
+-- CJP: no Traversable instance for C, because no Functor instance
+-- (see above)
+
+
+---------- Utility instances ----------
+
+instance (Random (t m r)) => Random (CycRep t P m r) where
+  random g = let (v,g') = random g
+             in (Pow v, g')
+  randomR _ = error "randomR non-sensical for CycRep"
+
+instance (Random (t m r)) => Random (CycRep t D m r) where
+  random g = let (v,g') = random g
+             in (Dec v, g')
+  randomR _ = error "randomR non-sensical for CycRep"
+
+instance (Random (t m r), Fact m, TensorCRT t Maybe r)
+  => Random (CycRepPC t m r) where
+  -- create in CRTC basis if possible, otherwise in powerful
+  random = let cons = case crtSentinel of
+                 Left  _ -> Left  . Pow
+                 Right s -> Right . CRTC s
+           in \g -> let (v,g') = random g
+                    in (cons v, g')
+  randomR _ = error "randomR non-sensical for CycRep"
+
+instance (Show (t m r)) => Show (CycRep t P m r) where
+  show (Pow x) = "CycRep.Pow " ++ show x
+
+instance (Show (t m r)) => Show (CycRep t D m r) where
+  show (Dec x) = "CycRep.Dec " ++ show x
+
+instance (Show (t m r)) => Show (CycRep t C m r) where
+  show (CRTC _ x) = "CycRep.CRTC " ++ show x
+
+instance (Show (t m (CRTExt r))) => Show (CycRep t E m r) where
+  show (CRTE _ x) = "CycRep.CRTE " ++ show x
+
+
+instance (NFData (t m r)) => NFData (CycRep t P m r) where
+  rnf (Pow x) = rnf x
+
+instance (NFData (t m r)) => NFData (CycRep t D m r) where
+  rnf (Dec x) = rnf x
+
+instance (NFData (t m r)) => NFData (CycRep t C m r) where
+  rnf (CRTC _ x) = rnf x
+
+instance (NFData (t m (CRTExt r))) => NFData (CycRep t E m r) where
+  rnf (CRTE _ x) = rnf x
+
+
+instance (Protoable (t m r)) => Protoable (CycRep t D m r) where
+  type ProtoType (CycRep t D m r) = ProtoType (t m r)
+  toProto (Dec t) = toProto t
+  fromProto t = Dec <$> fromProto t
diff --git a/Crypto/Lol/Cyclotomic/Language.hs b/Crypto/Lol/Cyclotomic/Language.hs
new file mode 100644
--- /dev/null
+++ b/Crypto/Lol/Cyclotomic/Language.hs
@@ -0,0 +1,160 @@
+{-|
+Module      : Crypto.Lol.Cyclotomic.Language
+Description : Abstract interfaces for operations on cyclotomic rings.
+Copyright   : (c) Chris Peikert, 2018-
+License     : GPL-3
+Maintainer  : ecrockett0@gmail.com
+Stability   : experimental
+Portability : POSIX
+
+  \( \def\Z{\mathbb{Z}} \)
+  \( \def\F{\mathbb{F}} \)
+  \( \def\Q{\mathbb{Q}} \)
+  \( \def\Tw{\text{Tw}} \)
+  \( \def\Tr{\text{Tr}} \)
+  \( \def\O{\mathcal{O}} \)
+-}
+
+{-# LANGUAGE ConstraintKinds       #-}
+{-# LANGUAGE FlexibleContexts      #-}
+{-# LANGUAGE MultiParamTypeClasses #-}
+{-# LANGUAGE RankNTypes            #-}
+{-# LANGUAGE ScopedTypeVariables   #-}
+{-# LANGUAGE TypeFamilies          #-}
+{-# LANGUAGE TypeOperators         #-}
+
+module Crypto.Lol.Cyclotomic.Language
+where
+
+import Crypto.Lol.Prelude
+
+import Control.Monad.Random (MonadRandom)
+
+-- | Used to specify a basis for cyclotomic operations
+data Basis = Pow | Dec
+
+-- | Operations on cyclotomics.
+class Cyclotomic cmr where
+  -- | Multiply by the special element \( g \).
+  mulG :: cmr -> cmr
+
+  -- | Divide by the special element \( g \), returning 'Nothing' if
+  -- the input is not evenly divisible.
+  divG :: cmr -> Maybe cmr
+
+  -- | Yield an equivalent element that /may/ be in
+  -- powerful\/decoding\/CRT representation.  This can serve as an
+  -- optimization hint. E.g., call 'adviseCRT' prior to multiplying a
+  -- value by many other values.
+  advisePow, adviseDec, adviseCRT :: cmr -> cmr
+
+class GSqNormCyc cm r where
+  -- | Yield the scaled squared norm of \( g_m \cdot e \) under the
+  -- canonical embedding, namely, \( \hat{m}^{-1} \cdot \| \sigma(g_m
+  -- \cdot e) \|^2 \).
+  gSqNorm :: cm r -> r
+
+-- | Sampling from tweaked Gaussian distributions over cyclotomic
+-- number fields.
+class GaussianCyc cmq where
+  -- | Sample from the "tweaked" Gaussian distribution \( t \cdot D
+  -- \), where \( D \) has scaled variance \( v \).
+  tweakedGaussian :: (ToRational v, MonadRandom rnd) => v -> rnd cmq
+
+-- | Sampling from /discretized/ tweaked Gaussian distributions over
+-- cyclotomic number rings.
+class RoundedGaussianCyc cmz where
+  -- | Sample from the tweaked Gaussian with given scaled variance,
+  -- deterministically rounded using the decoding basis.
+  roundedGaussian :: (ToRational v, MonadRandom rnd) => v -> rnd cmz
+
+-- | Sampling from tweaked Gaussian distributions, discretized to
+-- mod-p cosets of cyclotomic number rings.
+class CosetGaussianCyc rp where
+  -- | Sample from the tweaked Gaussian with scaled variance \( v
+  -- \cdot p^2 \), deterministically rounded to the given coset of
+  -- \( R_p \) using the decoding basis.
+  cosetGaussian :: (ToRational v, MonadRandom rnd)
+                => v -> rp -> rnd (LiftOf rp)
+
+-- | Cyclotomic extensions \( \O_{m'}/\O_m \).
+class ExtensionCyc c r where
+  -- | Embed into a cyclotomic extension.
+  embed :: (m `Divides` m') => c m r -> c m' r
+
+  -- | The "tweaked trace" (twace) \( \Tw(x) = (\hat{m} / \hat{m}')
+  -- \cdot \Tr((g' / g) \cdot x) \), which is the left-inverse of
+  -- 'embed' (i.e., @twace . embed == id@).
+  twace :: (m `Divides` m') => c m' r -> c m r
+
+  -- | The relative powerful/decoding bases of the extension.
+  powBasis :: (m `Divides` m') => Tagged m [c m' r]
+
+  -- | Yield the coefficient vector with respect to the given
+  -- (relative) basis of the extension.
+  coeffsCyc :: (m `Divides` m') => Basis -> c m' r -> [c m r]
+
+coeffsPow, coeffsDec :: (ExtensionCyc c r, m `Divides` m') => c m' r -> [c m r]
+-- | 'coeffsCyc' specialized to the powerful basis.
+coeffsPow = coeffsCyc Pow
+-- | 'coeffsCyc' specialized to the decoding basis.
+coeffsDec = coeffsCyc Dec
+
+-- | Relative CRT sets of cyclotomic extensions.
+class ExtensionCyc c r => CRTSetCyc c r where
+  -- | The relative mod-@r@ CRT set of the extension.
+  crtSet :: (m `Divides` m') => Tagged m [c m' r]
+
+-- | Map over coefficients in a specified basis.
+class FunctorCyc cm a b where
+  -- | Map in the specified basis (where 'Nothing' indicates that
+  -- any 'Basis' may be used).
+  fmapCyc :: Maybe Basis -> (a -> b) -> cm a -> cm b
+
+-- | Convenient specializations of 'fmapCyc'.
+fmapAny, fmapPow, fmapDec :: FunctorCyc cm a b => (a -> b) -> cm a -> cm b
+fmapAny = fmapCyc   Nothing
+fmapPow = fmapCyc $ Just Pow
+fmapDec = fmapCyc $ Just Dec
+
+-- | Fold over coefficients in a specified basis.
+class FoldableCyc cm a where
+  -- | Fold in the specified basis (where 'Nothing' indicates that
+  -- any 'Basis' may be used).
+  foldrCyc :: Maybe Basis -> (a -> b -> b) -> b -> cm a -> b
+
+-- | Convenient specializations of 'foldrCyc'.
+foldrAny, foldrPow, foldrDec :: FoldableCyc cm a => (a -> b -> b) -> b -> cm a -> b
+foldrAny = foldrCyc   Nothing
+foldrPow = foldrCyc $ Just Pow
+foldrDec = foldrCyc $ Just Dec
+
+-- | Reduce on a cyclotomic (in an arbitrary basis).
+reduceCyc :: (FunctorCyc cm a b, Reduce a b) => cm a -> cm b
+reduceCyc = fmapAny reduce
+
+-- | Lift a cyclotomic in a specified basis.
+class LiftCyc cmr where
+  -- | Lift in the specified basis (where 'Nothing' indicates that any
+  -- 'Basis' may be used).
+  liftCyc :: Maybe Basis -> cmr -> LiftOf cmr
+
+-- | Convenient specializations of 'liftCyc'.
+liftAny, liftPow, liftDec :: LiftCyc cmr => cmr -> LiftOf cmr
+liftAny = liftCyc   Nothing
+liftPow = liftCyc $ Just Pow
+liftDec = liftCyc $ Just Dec
+
+-- | Rescaling on cyclotomics from one base ring to another. (This is
+-- a separate class because there are optimized rescaling algorithms
+-- that can't be implemented using 'FunctorCyc'.)
+class RescaleCyc cm a b where
+  -- | Rescale in the given basis.
+  rescaleCyc :: Basis -> cm a -> cm b
+
+rescalePow, rescaleDec :: (RescaleCyc cm a b) => cm a -> cm b
+-- | 'rescaleCyc' specialized to the powerful basis.
+rescalePow = rescaleCyc Pow
+-- | 'rescaleCyc' specialized to the decoding basis.
+rescaleDec = rescaleCyc Dec
+
diff --git a/Crypto/Lol/Cyclotomic/Linear.hs b/Crypto/Lol/Cyclotomic/Linear.hs
--- a/Crypto/Lol/Cyclotomic/Linear.hs
+++ b/Crypto/Lol/Cyclotomic/Linear.hs
@@ -2,10 +2,10 @@
 Module      : Crypto.Lol.Cyclotomic.Linear
 Description : Functions from one cyclotomic ring to another that are linear
               over a common subring.
-Copyright   : (c) Eric Crockett, 2011-2017
-                  Chris Peikert, 2011-2017
-License     : GPL-2
-Maintainer  : ecrockett0@email.com
+Copyright   : (c) Eric Crockett, 2011-2018
+                  Chris Peikert, 2011-2018
+License     : GPL-3
+Maintainer  : ecrockett0@gmail.com
 Stability   : experimental
 Portability : POSIX
 
@@ -18,53 +18,58 @@
 {-# LANGUAGE ConstraintKinds            #-}
 {-# LANGUAGE DataKinds                  #-}
 {-# LANGUAGE FlexibleContexts           #-}
+{-# LANGUAGE FlexibleInstances          #-}
 {-# LANGUAGE GeneralizedNewtypeDeriving #-}
-{-# LANGUAGE KindSignatures             #-}
 {-# LANGUAGE MultiParamTypeClasses      #-}
 {-# LANGUAGE NoImplicitPrelude          #-}
 {-# LANGUAGE RoleAnnotations            #-}
 {-# LANGUAGE ScopedTypeVariables        #-}
 {-# LANGUAGE StandaloneDeriving         #-}
+{-# LANGUAGE TypeApplications           #-}
 {-# LANGUAGE TypeFamilies               #-}
 {-# LANGUAGE TypeOperators              #-}
 {-# LANGUAGE UndecidableInstances       #-}
 
 module Crypto.Lol.Cyclotomic.Linear
-( Linear, ExtendLinIdx
-, linearDec, evalLin, extendLin
+( Linear, ExtendLinCtx
+, linearDec, evalLin, liftLin, fmapLin, extendLin
 ) where
 
-import Crypto.Lol.Cyclotomic.Cyc
+import Crypto.Lol.Cyclotomic.Language
+import Crypto.Lol.Cyclotomic.Tensor
 import Crypto.Lol.Prelude
 import Crypto.Lol.Reflects
 import Crypto.Lol.Types.Proto
-import Crypto.Proto.Lol.RqProduct (RqProduct)
-import Crypto.Proto.Lol.LinearRq (LinearRq(LinearRq))
+import Crypto.Proto.Lol.LinearRq      (LinearRq (LinearRq))
+import Crypto.Proto.Lol.RqProduct     (RqProduct)
 
 import Algebra.Additive as Additive (C)
 
 import Control.Applicative
 import Control.DeepSeq
 
-import Data.Word
+import qualified Data.Vector         as V
+import qualified Data.Vector.Unboxed as U
+import           Data.Word
 
 -- | An \(E\)-linear function from \(R\) to \(S\).
 
 -- CJP: also have constructor for relative Pow basis of R/E?  So far
 -- not needed.
-newtype Linear t z (e::Factored) (r::Factored) (s::Factored) = RD [Cyc t s z]
-
-deriving instance (NFData (Cyc t s z)) => NFData (Linear t z e r s)
+newtype Linear c (e::Factored) (r::Factored) (s::Factored) z = RD [c s z]
+  deriving Show
 
 -- some params are phantom but matter for safety
-type role Linear representational nominal representational representational nominal
+type role Linear representational representational representational nominal nominal
 
+deriving instance NFData (c s z) => NFData (Linear c e r s z)
+
 -- | Construct an \(E\)-linear function given a list of its output values
 -- (in \(S\)) on the relative decoding basis of \(R/E\).  The number of
 -- elements in the list must not exceed the size of the basis.
-linearDec :: forall t z e r s .
-             (e `Divides` r, e `Divides` s, CElt t z)
-             => [Cyc t s z] -> Linear t z e r s
+linearDec :: forall c e r s z .
+             (e `Divides` r, e `Divides` s, Cyclotomic (c s z), ExtensionCyc c z)
+          => [c s z] -> Linear c e r s z
 linearDec ys = let ps = proxy powBasis (Proxy::Proxy e) `asTypeOf` ys
                in if length ys <= length ps then RD (adviseCRT <$> ys)
                else error $ "linearDec: too many entries: "
@@ -72,60 +77,75 @@
                         ++ show (length ps)
 
 -- | Evaluates the given linear function on the input.
-evalLin :: forall t z e r s .
-           (e `Divides` r, e `Divides` s, CElt t z)
-           => Linear t z e r s -> Cyc t r z -> Cyc t s z
-evalLin (RD ys) r = sum (zipWith (*) ys $
-                         embed <$> (coeffsDec r :: [Cyc t e z]))
+evalLin :: forall c e r s z .
+           (e `Divides` r, e `Divides` s, Ring (c s z), ExtensionCyc c z)
+        => Linear c e r s z -> c r z -> c s z
+evalLin (RD ys) r = sum (zipWith (*) ys $ embed <$> (coeffsDec r :: [c e z]))
 
-instance Additive (Cyc t s z) => Additive.C (Linear t z e r s) where
+instance Additive (c s z) => Additive.C (Linear c e r s z) where
   zero = RD []
 
   (RD as) + (RD bs) = RD $ sumall as bs
-    where sumall [] ys = ys
-          sumall xs [] = xs
+    where sumall [] ys         = ys
+          sumall xs []         = xs
           sumall (x:xs) (y:ys) = x+y : sumall xs ys
 
   negate (RD as) = RD $ negate <$> as
 
-instance (Reduce z zq, Fact s, CElt t z, CElt t zq)
-         => Reduce (Linear t z e r s) (Linear t zq e r s) where
+instance (Reduce (c s z) (c s zp))
+  => Reduce (Linear c e r s z) (Linear c e r s zp) where
   reduce (RD ys) = RD $ reduce <$> ys
 
-type instance LiftOf (Linear t zp e r s) = Linear t (LiftOf zp) e r s
+type instance LiftOf (Linear c e r s zp) = Linear c e r s (LiftOf zp)
 
--- | lifts with respect to powerful basis, for best geometry
-instance (CElt t zp, CElt t z, z ~ LiftOf zp, Lift zp z, Fact s)
-         => Lift' (Linear t zp e r s) where
-  lift (RD ys) = RD $ liftPow <$> ys
+-- | Lift the linear function in the specified basis (or any, if
+-- 'Nothing' is given).  The powerful basis is generally best,
+-- geometrically.
+liftLin :: (LiftCyc (c s zp), LiftOf (c s zp) ~ c s (LiftOf zp))
+  => Maybe Basis -> Linear c e r s zp -> Linear c e r s (LiftOf zp)
+liftLin b (RD ys) = RD $ liftCyc b <$> ys
 
+-- | Change the underlying cyclotomic representation.
+fmapLin :: (c s z -> c' s z) -> Linear c e r s z -> Linear c' e r s z
+fmapLin f (RD cs) = RD (f <$> cs)
+
 -- | A convenient constraint synonym for extending a linear function
 -- to larger rings.
-type ExtendLinIdx e r s e' r' s' =
-  (Fact r, e ~ FGCD r e', r' ~ FLCM r e', -- these imply R'=R\otimes_E E'
-   e' `Divides` s', s `Divides` s') -- lcm(s,e')|s' <=> (S+E') \subseteq S'
+type ExtendLinCtx c e r s e' r' s' z =
+  (e ~ FGCD r e',                   -- E = R \cap E'
+   FLCM r e' `Divides` r',          -- (R+E') \subseteq R'
+   e' `Divides` s', s `Divides` s', -- (S+E') \subseteq S'
+   ExtensionCyc c z, Additive (c s' z))
 
 -- | Extend an \(E\)-linear function \(R\to S\) to an \(E'\)-linear
--- function \(R'\to S'\). (Mathematically, such extension only requires
--- \(\lcm(r,e') | r'\) (not equality), but this generality would
--- significantly complicate the implementation, and for our purposes
--- there's no reason to use any larger \(r'\).)
-extendLin :: (ExtendLinIdx e r s e' r' s')
-           => Linear t z e r s -> Linear t z e' r' s'
--- CJP: this simple implementation works because R/E and R'/E' have
--- identical decoding bases, because R' \cong R \otimes_E E'.  If we
--- relax the constraint on E then we'd have to change the
--- implementation to something more difficult.
-extendLin (RD ys) = RD (embed <$> ys)
+-- function \(R'\to S'\).
+extendLin :: forall c e r s e' r' s' z .
+             (ExtendLinCtx c e r s e' r' s' z)
+          => Linear c e r s z -> Linear c e' r' s' z
+-- need the indexing:
+-- dec_{R'/E'} <-> dec_{R'/(R+E')} \otimes dec_{(R+E')/E'}
+--               = dec_{R'/(R+E')} \otimes dec_{R/E}.
+extendLin (RD ys) =
+  let yvec  = V.fromList ys
+      ylen  = V.length yvec
+      idxs  = baseIndicesPow @(FLCM r e') @r'
+      y'vec = V.generate (U.length idxs) $ \idx ->
+        let (j0,j1) = idxs U.! idx
+        in if j0 == 0 && j1 < ylen then embed (yvec V.! j1) else zero
+  in RD $ V.toList y'vec
 
 instance (Reflects e Word32, Reflects r Word32,
-          Protoable (Cyc t s zq), ProtoType (t s zq) ~ RqProduct)
-  => Protoable (Linear t zq e r s) where
-  type ProtoType (Linear t zq e r s) = LinearRq
-  toProto (RD cs) = LinearRq (proxy value (Proxy::Proxy e)) (proxy value (Proxy::Proxy r)) $ toProto cs
+          Protoable (c s zq), ProtoType (c s zq) ~ RqProduct)
+  => Protoable (Linear c e r s zq) where
+
+  type ProtoType (Linear c e r s zq) = LinearRq
+
+  toProto (RD cs) =
+    LinearRq (value @e) (value @r) $ toProto cs
+
   fromProto (LinearRq e r cs) =
-    let e' = proxy value (Proxy::Proxy e)
-        r' = proxy value (Proxy::Proxy r)
+    let e' = value @e
+        r' = value @r
     in if e == e' && r == r'
        then RD <$> fromProto cs
        else error $ "Could not deserialize Linear: types imply e=" ++
diff --git a/Crypto/Lol/Cyclotomic/RescaleCyc.hs b/Crypto/Lol/Cyclotomic/RescaleCyc.hs
deleted file mode 100644
--- a/Crypto/Lol/Cyclotomic/RescaleCyc.hs
+++ /dev/null
@@ -1,38 +0,0 @@
-{-|
-Module      : Crypto.Lol.Cyclotomic.RescaleCyc
-Description : A class and helper functions for rescaling cycltomic ring elements.
-Copyright   : (c) Eric Crockett, 2011-2017
-                  Chris Peikert, 2011-2017
-License     : GPL-2
-Maintainer  : ecrockett0@email.com
-Stability   : experimental
-Portability : POSIX
-
-  \( \def\Z{\mathbb{Z}} \)
-
-A class and helper functions for rescaling cycltomic ring elements.
--}
-
-{-# LANGUAGE MultiParamTypeClasses #-}
-
-module Crypto.Lol.Cyclotomic.RescaleCyc where
-
-import Crypto.Lol.Factored
-
--- | Represents the basis used to rescale a cyclotomic ring element.
-data Basis = Pow | Dec
-
--- | Represents cyclotomic rings that are rescalable over their base
--- rings.  (This is a class because it allows for more efficient
--- specialized implementations.)
-class RescaleCyc c a b where
-  -- | Rescale in the given basis.
-  rescaleCyc :: Fact m => Basis -> c m a -> c m b
-
--- | Specialized convenience functions.
-rescalePow, rescaleDec :: (RescaleCyc c a b, Fact m) => c m a -> c m b
-{-# INLINE rescalePow #-}
-{-# INLINE rescaleDec #-}
-rescalePow = rescaleCyc Pow
-rescaleDec = rescaleCyc Dec
-
diff --git a/Crypto/Lol/Cyclotomic/Tensor.hs b/Crypto/Lol/Cyclotomic/Tensor.hs
--- a/Crypto/Lol/Cyclotomic/Tensor.hs
+++ b/Crypto/Lol/Cyclotomic/Tensor.hs
@@ -4,8 +4,8 @@
               helper functions for tensor indexing.
 Copyright   : (c) Eric Crockett, 2011-2017
                   Chris Peikert, 2011-2017
-License     : GPL-2
-Maintainer  : ecrockett0@email.com
+License     : GPL-3
+Maintainer  : ecrockett0@gmail.com
 Stability   : experimental
 Portability : POSIX
 
@@ -19,22 +19,30 @@
 indexing.
 -}
 
+{-# LANGUAGE AllowAmbiguousTypes     #-}
 {-# LANGUAGE ConstraintKinds         #-}
 {-# LANGUAGE DataKinds               #-}
 {-# LANGUAGE FlexibleContexts        #-}
 {-# LANGUAGE MultiParamTypeClasses   #-}
 {-# LANGUAGE NoImplicitPrelude       #-}
 {-# LANGUAGE PolyKinds               #-}
+{-# LANGUAGE QuantifiedConstraints   #-}
 {-# LANGUAGE RankNTypes              #-}
 {-# LANGUAGE ScopedTypeVariables     #-}
 {-# LANGUAGE TupleSections           #-}
+{-# LANGUAGE TypeApplications        #-}
 {-# LANGUAGE TypeFamilies            #-}
 {-# LANGUAGE TypeOperators           #-}
 {-# LANGUAGE UndecidableInstances    #-}
 {-# LANGUAGE UndecidableSuperClasses #-}
 
 module Crypto.Lol.Cyclotomic.Tensor
-( Tensor(..)
+( TensorPowDec(..)
+, TensorG(..)
+, TensorCRT(..)
+, TensorGaussian(..)
+, TensorGSqNorm(..)
+, TensorCRTSet(..)
 -- * Top-level CRT functions
 , hasCRTFuncs
 , scalarCRT, mulGCRT, divGCRT, crt, crtInv, twaceCRT, embedCRT
@@ -50,21 +58,20 @@
 where
 
 import Crypto.Lol.CRTrans
-import Crypto.Lol.Prelude           as LP hiding (lift, (*>))
-import Crypto.Lol.Types.FiniteField
+import Crypto.Lol.Prelude        as LP hiding (lift, (*>))
+import Crypto.Lol.Types.IFunctor
 
+import           Algebra.Module          as Module (C)
 import           Control.Applicative
-import           Control.DeepSeq
 import           Control.Monad.Random
-import           Data.Constraint
-import           Data.Singletons.Prelude hiding ((:-))
+import           Data.Singletons.Prelude
 import           Data.Traversable
 import           Data.Tuple              (swap)
 import qualified Data.Vector             as V
 import qualified Data.Vector.Unboxed     as U
 
--- | 'Tensor' encapsulates all the core linear transformations needed
--- for cyclotomic ring arithmetic.
+-- | Encapsulates linear transformations needed for cyclotomic ring
+-- arithmetic.
 
 -- | The type @t m r@ represents a cyclotomic coefficient tensor of
 -- index \(m\) over base ring \(r\).  Most of the methods represent linear
@@ -73,141 +80,124 @@
 -- well-defined only when a CRT basis exists over the ring \(r\) for
 -- index \(m\).
 
--- | The superclass constraints are for convenience, to ensure that we
--- can sample error tensors of 'Double's.
-
 -- | __WARNING:__ as with all fixed-point arithmetic, the methods
--- in 'Tensor' may result in overflow (and thereby incorrect answers
+-- in 'TensorPowDec' may result in overflow (and thereby incorrect answers
 -- and potential security flaws) if the input arguments are too close
 -- to the bounds imposed by the base type.  The acceptable range of
 -- inputs for each method is determined by the linear transform it
 -- implements.
 
-class (TElt t Double, TElt t (Complex Double)) => Tensor t where
+class (forall m . Fact m => (Applicative (t m), Traversable (t m)),
+       IFunctor t, IFElt t r, Additive r)
+  => TensorPowDec t r where
 
-  -- | Constraints needed by @t@ to hold type @r@.
-  type TElt t r :: Constraint
+  -- | Convert a scalar to a tensor in the powerful basis.
+  scalarPow :: Fact m => r -> t m r
 
-  -- | Properties that hold for any index. Use with '\\'.
-  entailIndexT :: Tagged (t m r)
-                  (Fact m :- (Applicative (t m), Traversable (t m)))
-  -- | Holds for any (legal) fully-applied tensor. Use with '\\'.
-  entailEqT :: Tagged (t m r)
-               ((Eq r, Fact m, TElt t r) :- Eq (t m r))
-  -- | Holds for any (legal) fully-applied tensor. Use with '\\'.
-  entailZTT :: Tagged (t m r)
-               ((ZeroTestable r, Fact m, TElt t r) :- ZeroTestable (t m r))
-  -- | Holds for any (legal) fully-applied tensor. Use with '\\'.
-  entailNFDataT :: Tagged (t m r)
-                   ((NFData r, Fact m, TElt t r) :- NFData (t m r))
-  -- | Holds for any (legal) fully-applied tensor. Use with '\\'.
-  entailRandomT :: Tagged (t m r)
-                   ((Random r, Fact m, TElt t r) :- Random (t m r))
-  -- | Holds for any (legal) fully-applied tensor. Use with '\\'.
-  entailShowT :: Tagged (t m r)
-                 ((Show r, Fact m, TElt t r) :- Show (t m r))
-  -- | Holds for any (legal) fully-applied tensor. Use with '\\'.
-  entailModuleT :: Tagged (GF fp d, t m fp)
-                   ((GFCtx fp d, Fact m, TElt t fp) :- Module (GF fp d) (t m fp))
+  -- | Convert between the decoding-basis and powerful-basis
+  -- representations.
+  powToDec, decToPow :: Fact m => t m r -> t m r
 
-  -- | Convert a scalar to a tensor in the powerful basis.
-  scalarPow :: (Additive r, Fact m, TElt t r) => r -> t m r
+  -- | The @twace@ linear transformation, which is the same in both the
+  -- powerful and decoding bases.
+  twacePowDec :: (m `Divides` m') => t m' r -> t m r
 
-  -- | 'l' converts from decoding-basis representation to
-  -- powerful-basis representation; 'lInv' is its inverse.
-  l, lInv :: (Additive r, Fact m, TElt t r) => t m r -> t m r
+  -- | The @embed@ linear transformations, for the powerful and
+  -- decoding bases.
+  embedPow, embedDec :: (m `Divides` m') => t m r -> t m' r
 
+  -- | Map a tensor in the powerful/decoding/CRT basis, representing
+  -- an \(\O_{m'}\) element, to a vector of tensors representing
+  -- \(\O_m\) elements in the same kind of basis.
+  coeffs :: (m `Divides` m') => t m' r -> [t m r]
+
+  -- CJP: we have to use tags due to this bug:
+  -- https://ghc.haskell.org/trac/ghc/ticket/14266 "It was a surprise
+  -- to me that I can see no way to allow to write an instance when
+  -- the method has a a locally-polymorphic but ambiguous method
+  -- types."
+
+  -- | The relative powerful basis of \( \O_{m'}/\O_{m} \),
+  -- w.r.t. the powerful basis of \( \O_{m'} \).
+  powBasisPow :: (m `Divides` m') => Tagged m [t m' r]
+
+-- | Encapsulates multiplication and division by \(g_m\)
+class TensorPowDec t r => TensorG t r where
   -- | Multiply by \(g_m\) in the powerful/decoding basis
-  mulGPow, mulGDec :: (Ring r, Fact m, TElt t r) => t m r -> t m r
+  mulGPow, mulGDec :: Fact m => t m r -> t m r
 
   -- | Divide by \(g_m\) in the powerful/decoding basis.  The 'Maybe'
   -- output indicates that the operation may fail, which happens
   -- exactly when the input is not divisible by \(g_m\).
-  divGPow, divGDec :: (ZeroTestable r, IntegralDomain r, Fact m, TElt t r)
-                      => t m r -> Maybe (t m r)
+  divGPow, divGDec :: Fact m => t m r -> Maybe (t m r)
 
+-- | Encapsulates functions related to the Chinese-remainder
+-- representation/transform.
+class (TensorPowDec t r, CRTrans mon r,
+       forall m . Fact m => (Module.C r) (t m r))
+  => TensorCRT t mon r where
   -- | A tuple of all the operations relating to the CRT basis, in a
   -- single 'Maybe' value for safety.  Clients should typically not
   -- use this method directly, but instead call the corresponding
   -- top-level functions: the elements of the tuple correpond to the
   -- functions 'scalarCRT', 'mulGCRT', 'divGCRT', 'crt', 'crtInv'.
-  crtFuncs :: (CRTrans mon r, Fact m, TElt t r) =>
+  crtFuncs :: Fact m =>
               mon (    r -> t m r, -- scalarCRT
                    t m r -> t m r, -- mulGCRT
                    t m r -> t m r, -- divGCRT
                    t m r -> t m r, -- crt
                    t m r -> t m r) -- crtInv
 
-  -- | Sample from the "tweaked" Gaussian error distribution \(t\cdot D\)
-  -- in the decoding basis, where \(D\) has scaled variance \(v\).
-  tGaussianDec :: (OrdFloat q, Random q, TElt t q,
-                   ToRational v, Fact m, MonadRandom rnd)
-                  => v -> rnd (t m q)
-
-  -- | Given the coefficient tensor of \(e\) with respect to the
-  -- decoding basis of \(R\), yield the (scaled) squared norm of
-  -- \(g_m \cdot e\) under the canonical embedding, namely,
-  -- \(\hat{m}^{-1} \cdot \| \sigma(g_m \cdot e) \|^2\).
-  gSqNormDec :: (Ring r, Fact m, TElt t r) => t m r -> r
-
-  -- | The @twace@ linear transformation, which is the same in both the
-  -- powerful and decoding bases.
-  twacePowDec :: (Ring r, m `Divides` m', TElt t r) => t m' r -> t m r
-
-  -- | The @embed@ linear transformations, for the powerful and
-  -- decoding bases.
-  embedPow, embedDec :: (Additive r, m `Divides` m', TElt t r)
-                        => t m r -> t m' r
-
   -- | A tuple of all the extension-related operations involving the
   -- CRT bases, for safety.  Clients should typically not use this
   -- method directly, but instead call the corresponding top-level
   -- functions: the elements of the tuple correpond to the functions
   -- 'twaceCRT', 'embedCRT'.
-  crtExtFuncs :: (CRTrans mon r, m `Divides` m', TElt t r) =>
+  crtExtFuncs :: (m `Divides` m') =>
                  mon (t m' r -> t m  r, -- twaceCRT
                       t m  r -> t m' r) -- embedCRT
 
-  -- | Map a tensor in the powerful\/decoding\/CRT basis, representing
-  -- an \(\O_{m'}\) element, to a vector of tensors representing
-  -- \(\O_m\) elements in the same kind of basis.
-  coeffs :: (Ring r, m `Divides` m', TElt t r) => t m' r -> [t m r]
-
-  -- | The powerful extension basis w.r.t. the powerful basis.
-  powBasisPow :: (Ring r, TElt t r, m `Divides` m') => Tagged m [t m' r]
-
-  -- | A list of tensors representing the mod-@p@ CRT set of the extension.
-  crtSetDec :: (m `Divides` m', PrimeField fp, Coprime (PToF (CharOf fp)) m',
-                TElt t fp)
-               => Tagged m [t m' fp]
+-- | A coefficient tensor that supports Gaussian sampling.
+class TensorGaussian t q where
+  -- | Sample from the "tweaked" Gaussian error distribution \(t\cdot D\)
+  -- in the decoding basis, where \(D\) has scaled variance \(v\).
+  tweakedGaussianDec :: (ToRational v, Fact m, MonadRandom rnd)
+                        => v -> rnd (t m q)
 
-  -- | Potentially optimized version of 'fmap' for types that satisfy 'TElt'.
-  fmapT :: (Fact m, TElt t a, TElt t b) => (a -> b) -> t m a -> t m b
+-- | A coefficient tensor that supports taking norms under the
+-- canonical embedding.
+class TensorGSqNorm t r where
+  -- | Given the coefficient tensor of \(e\) with respect to the
+  -- decoding basis of \(R\), yield the (scaled) squared norm of
+  -- \(g_m \cdot e\) under the canonical embedding, namely,
+  -- \(\hat{m}^{-1} \cdot \| \sigma(g_m \cdot e) \|^2\).
+  gSqNormDec :: Fact m => t m r -> r
 
-  -- | Potentially optimized zipWith for types that satisfy 'TElt'.
-  zipWithT :: (Fact m, TElt t a, TElt t b, TElt t c)
-              => (a -> b -> c) -> t m a -> t m b -> t m c
+-- | A 'TensorPowDec' that supports relative CRT sets for the element type
+-- 'fp' representing a prime-order finite field.
+class (TensorPowDec t fp) => TensorCRTSet t fp where
+  -- CJP: see above for why we use a Tagged type here
 
-  -- | Potentially optimized unzip for types that satisfy 'TElt'.
-  unzipT :: (Fact m, TElt t (a,b), TElt t a, TElt t b)
-            => t m (a,b) -> (t m a, t m b)
+  -- | Relative mod-@p@ CRT set of \( \O_{m'}/\O_{m} \) in the
+  -- decoding basis.
+  crtSetDec :: (m `Divides` m', Coprime (PToF (CharOf fp)) m')
+    => Tagged m [t m' fp]
 
 -- | Convenience value indicating whether 'crtFuncs' exists.
-hasCRTFuncs :: forall t m mon r . (CRTrans mon r, Tensor t, Fact m, TElt t r)
-               => TaggedT (t m r) mon ()
+hasCRTFuncs :: forall t m r mon . (TensorCRT t mon r, Fact m) => mon ()
 {-# INLINABLE hasCRTFuncs #-}
-hasCRTFuncs = tagT $ do
-  (_ :: r -> t m r,_,_,_,_) <- crtFuncs
+hasCRTFuncs = do
+  (_,_,_,_,_) <- crtFuncs @t @mon @r @m
   return ()
 
 -- | Yield a tensor for a scalar in the CRT basis.  (This function is
 -- simply an appropriate entry from 'crtFuncs'.)
-scalarCRT :: (CRTrans mon r, Tensor t, Fact m, TElt t r) => mon (r -> t m r)
+scalarCRT :: (TensorCRT t mon r, Fact m) => mon (r -> t m r)
 {-# INLINABLE scalarCRT #-}
 scalarCRT = (\(f,_,_,_,_) -> f) <$> crtFuncs
 
 mulGCRT, divGCRT, crt, crtInv ::
-  (CRTrans mon r, Tensor t, Fact m, TElt t r) => mon (t m r -> t m r)
+  (TensorCRT t mon r, Fact m) => mon (t m r -> t m r)
 {-# INLINABLE mulGCRT #-}
 {-# INLINABLE divGCRT #-}
 {-# INLINABLE crt #-}
@@ -230,26 +220,29 @@
 -- For cyclotomic indices \(m \mid m'\),
 -- \(\Tw(x) = (\hat{m}/\hat{m}') \cdot \Tr((g'/g) \cdot x)\).
 -- (This function is simply an appropriate entry from 'crtExtFuncs'.)
-twaceCRT :: forall t m m' mon r . (CRTrans mon r, Tensor t, m `Divides` m', TElt t r)
+twaceCRT :: forall t m m' mon r . (TensorCRT t mon r, m `Divides` m')
             => mon (t m' r -> t m r)
 {-# INLINABLE twaceCRT #-}
-twaceCRT = proxyT hasCRTFuncs (Proxy::Proxy (t m' r)) *>
-           proxyT hasCRTFuncs (Proxy::Proxy (t m  r)) *>
+twaceCRT = hasCRTFuncs @t @m' @r *>
+           hasCRTFuncs @t @m  @r *>
            (fst <$> crtExtFuncs)
 
 -- | Embed a tensor with index \(m\) in the CRT basis to a tensor with
 -- index \(m'\) in the CRT basis.
 -- (This function is simply an appropriate entry from 'crtExtFuncs'.)
-embedCRT :: forall t m m' mon r . (CRTrans mon r, Tensor t, m `Divides` m', TElt t r)
+embedCRT :: forall t m m' mon r . (TensorCRT t mon r, m `Divides` m')
             => mon (t m r -> t m' r)
-embedCRT = proxyT hasCRTFuncs (Proxy::Proxy (t m' r)) *>
-           proxyT hasCRTFuncs (Proxy::Proxy (t m  r)) *>
+embedCRT = hasCRTFuncs @t @m' @r *>
+           hasCRTFuncs @t @m  @r *>
            (snd <$> crtExtFuncs)
 
 fKron :: forall m r mon . (Fact m, Monad mon)
+          -- higher-rank argument needs to be tagged (pp can't be
+          -- ambiguous) because otherwise we can't invoke fKron on an
+          -- ambiguous forall'd value
          => (forall pp . (PPow pp) => TaggedT pp mon (KronC r))
-         -> TaggedT m mon (Kron r)
-fKron mat = tagT $ go $ sUnF (sing :: SFactored m)
+         -> mon (Kron r)
+fKron mat = go $ sUnF (sing :: SFactored m)
   where go :: Sing (pplist :: [PrimePower]) -> mon (Kron r)
         go spps = case spps of
           SNil -> return MNil
@@ -259,15 +252,18 @@
             return $ MKron rest' mat'
 
 -- | For a prime power \(p^e\), converts any matrix \(M\) for
--- prime \(p\) to \(\vece{1}_(p^{e-1}) \otimes M\), where \(\vece{1}\)
+-- prime \(p\) to \(\vec{1}_(p^{e-1}) \otimes M\), where \(\vec{1}\)
 -- denotes the all-1s vector.
 ppKron :: forall pp r mon . (PPow pp, Monad mon)
+          -- higher-rank argument needs to be tagged (pp can't be
+          -- ambiguous) because otherwise we can't invoke ppKron on an
+          -- ambiguous forall'd value
           => (forall p . (Prime p) => TaggedT p mon (KronC r))
           -> TaggedT pp mon (KronC r)
 ppKron mat = tagT $ case (sing :: SPrimePower pp) of
-  pp@(SPP (STuple2 sp _)) -> do
+  pp@(SPP (STuple2 (sp :: Sing p) _)) -> do
     (MC h w f) <- withWitnessT mat sp
-    let d = withWitness valuePPow pp `div` withWitness valuePrime sp
+    let d = withSingI pp (valuePPow @pp) `div` withSingI sp (valuePrime @p)
     return $ MC (h*d) w (f . (`mod` h))
 
 -- deeply embedded DSL for Kronecker products of matrices
@@ -282,46 +278,48 @@
 -- | Extract the @(i,j)@ element of a 'Kron'.
 indexK :: Ring r => Kron r -> Int -> Int -> r
 indexK MNil 0 0 = LP.one
+indexK MNil i j = error $ "indexK MNil out of bounds: i = " ++ show i ++ ", j = " ++ show j
 indexK (MKron m (MC r c mc)) i j =
   let (iq,ir) = i `divMod` r
       (jq,jr) = j `divMod` c
       in indexK m iq jq * mc ir jr
 
-gCRTK, gInvCRTK :: (Fact m, CRTrans mon r) => TaggedT m mon (Kron r)
+gCRTK, gInvCRTK :: forall m mon r . (Fact m, CRTrans mon r) => mon (Kron r)
 -- | A \(\varphi(m)\)-by-1 matrix of the CRT coefficients of \(g_m\), for
 -- \(m\)th cyclotomic.
-gCRTK = fKron gCRTPPow
+gCRTK = fKron @m gCRTPPow
 -- | A \(\varphi(m)\)-by-1 matrix of the inverse CRT coefficients of \(g_m\),
 -- for \(m\)th cyclotomic.
-gInvCRTK = fKron gInvCRTPPow
+gInvCRTK = fKron @m gInvCRTPPow
 
 -- | The "tweaked" \(\CRT^*\) matrix:
 -- \(\CRT^* \cdot \text{diag}(\sigma(g_m))\).
-twCRTs :: (Fact m, CRTrans mon r) => TaggedT m mon (Kron r)
-twCRTs = fKron twCRTsPPow
+twCRTs :: forall m mon r . (Fact m, CRTrans mon r) => mon (Kron r)
+twCRTs = fKron @m twCRTsPPow
 
 -- | The "tweaked" \(\CRT^*\) matrix (for prime powers):
 -- \(\CRT^* \cdot \text{diag}(\sigma(g_p))\).
-twCRTsPPow :: (PPow pp, CRTrans mon r) => TaggedT pp mon (KronC r)
+twCRTsPPow :: forall pp mon r .
+  (PPow pp, CRTrans mon r) => TaggedT pp mon (KronC r)
 twCRTsPPow = do
-  phi    <- pureT totientPPow
-  iToZms <- pureT indexToZmsPPow
-  jToPow <- pureT indexToPowPPow
+  let phi    = totientPPow @pp
+      iToZms = indexToZmsPPow @pp
+      jToPow = indexToPowPPow @pp
   (wPow, _) <- crtInfo
   (MC _ _ gCRT) <- gCRTPPow
-
   return $ MC phi phi (\j i -> wPow (jToPow j * negate (iToZms i)) * gCRT i 0)
 
 gCRTPPow, gInvCRTPPow :: (PPow pp, CRTrans mon r) => TaggedT pp mon (KronC r)
 gCRTPPow = ppKron gCRTPrime
 gInvCRTPPow = ppKron gInvCRTPrime
 
-gCRTPrime, gInvCRTPrime :: (Prime p, CRTrans mon r) => TaggedT p mon (KronC r)
+gCRTPrime, gInvCRTPrime :: forall p mon r .
+  (Prime p, CRTrans mon r) => TaggedT p mon (KronC r)
 
 -- | A \((p-1)\)-by-1 matrix of the CRT coefficients of \(g_p\), for
 -- \(p\)th cyclotomic.
 gCRTPrime = do
-  p <- pureT valuePrime
+  let p = valuePrime @p
   (wPow, _) <- crtInfo
   return $ MC (p-1) 1 $ if p == 2 then const $ const one
                         else (\i _ -> one - wPow (i+1))
@@ -329,7 +327,7 @@
 -- | A \((p-1)\)-by-1 matrix of the inverse CRT coefficients of \(g_p\),
 -- for the \(p\)th cyclotomic.
 gInvCRTPrime = do
-  p <- pureT valuePrime
+  let p = valuePrime @p
   (wPow, phatinv) <- crtInfo
   return $ MC (p-1) 1 $
     if p == 2 then const $ const one
@@ -346,13 +344,13 @@
   | e >= 1 = let (q,r) = j `divMod` p
              in r * (p^(e-1)) + digitRev (p,e-1) q
 
-indexToPowPPow, indexToZmsPPow :: PPow pp => Tagged pp (Int -> Int)
-indexToPowPPow = indexToPow <$> ppPPow
-indexToZmsPPow = indexToZms <$> ppPPow
+indexToPowPPow, indexToZmsPPow :: forall pp . PPow pp => Int -> Int
+indexToPowPPow = indexToPow (ppPPow @pp)
+indexToZmsPPow = indexToZms (ppPPow @pp)
 
 -- | Convert a \(\Z_m^*\) index to a linear tensor index in \([m]\).
-zmsToIndexFact :: Fact m => Tagged m (Int -> Int)
-zmsToIndexFact = zmsToIndex <$> ppsFact
+zmsToIndexFact :: forall m . Fact m => (Int -> Int)
+zmsToIndexFact = zmsToIndex (ppsFact @m)
 
 -- | For a prime power \(p^e\), map a tensor index to the corresponding
 -- power \(j \in [\varphi(p^e)]\), as in the powerful basis.
@@ -387,6 +385,8 @@
 -- they all have such a factorization. The first argument is the list
 -- of \((\varphi(m),\varphi(m'))\) pairs for the (merged) prime powers
 -- of \(m\),\(m'\).
+{-# INLINE toIndexPair #-}
+{-# INLINE fromIndexPair #-}
 toIndexPair :: [(Int,Int)] -> Int -> (Int,Int)
 fromIndexPair :: [(Int,Int)] -> (Int,Int) -> Int
 
@@ -411,70 +411,66 @@
 -- final component is a pair \( ( \varphi(p^e), \varphi(p^{e'}))\) for each
 -- triple in the first component.
 indexInfo :: forall m m' . (m `Divides` m')
-             => Tagged '(m, m') ([(Int,Int,Int)], Int, Int, [(Int,Int)])
-indexInfo = let pps = proxy ppsFact (Proxy::Proxy m)
-                pps' = proxy ppsFact (Proxy::Proxy m')
+             => ([(Int,Int,Int)], Int, Int, [(Int,Int)])
+indexInfo = let pps  = ppsFact @m
+                pps' = ppsFact @m'
                 mpps = mergePPs pps pps'
-                phi = proxy totientFact (Proxy::Proxy m)
-                phi' = proxy totientFact (Proxy::Proxy m')
+                phi  = totientFact @m
+                phi' = totientFact @m'
                 tots = totients mpps
-            in tag (mpps, phi, phi', tots)
+            in (mpps, phi, phi', tots)
 
 -- | A vector of \(\varphi(m)\) entries, where the \(i\)th entry is
--- the index into the powerful\/decoding basis of \(\O_{m'}\) of the
+-- the index into the powerful/decoding basis of \(\O_{m'}\) of the
 -- \(i\)th entry of the powerful/decoding basis of \(\O_m\).
-extIndicesPowDec :: (m `Divides` m') => Tagged '(m, m') (U.Vector Int)
+extIndicesPowDec :: forall m m' . (m `Divides` m') => U.Vector Int
 {-# INLINABLE extIndicesPowDec #-}
-extIndicesPowDec = do
-  (_, phi, _, tots) <- indexInfo
-  return $ U.generate phi (fromIndexPair tots . (0,))
+extIndicesPowDec =
+  let (_, phi, _, tots) = indexInfo @m @m'
+  in U.generate phi (fromIndexPair tots . (0,))
 
 -- | A vector of \(\varphi(m)\) blocks of \(\varphi(m')/\varphi(m)\) consecutive
 -- entries. Each block contains all those indices into the CRT basis
 -- of \(\O_{m'}\) that "lie above" the corresponding index into the CRT
 -- basis of \(\O_m\).
-extIndicesCRT :: forall m m' . (m `Divides` m')
-                 => Tagged '(m, m') (U.Vector Int)
-extIndicesCRT = do
-  (_, phi, phi', tots) <- indexInfo
-  return $ U.generate phi'
-           (fromIndexPair tots . swap . (`divMod` (phi' `div` phi)))
+extIndicesCRT :: forall m m' . (m `Divides` m') => U.Vector Int
+extIndicesCRT =
+  let (_, phi, phi', tots) = indexInfo @m @m'
+  in U.generate phi'
+     (fromIndexPair tots . swap . (`divMod` (phi' `div` phi)))
 
 baseWrapper :: forall m m' a . (m `Divides` m', U.Unbox a)
                => ([(Int,Int,Int)] -> Int -> a)
-               -> Tagged '(m, m') (U.Vector a)
-baseWrapper f = do
-  (mpps, _, phi', _) <- indexInfo
-  return $ U.generate phi' (f mpps)
+               -> U.Vector a
+baseWrapper f =
+  let (mpps, _, phi', _) = indexInfo @m @m'
+  in U.generate phi' (f mpps)
 
 -- | A lookup table for 'toIndexPair' applied to indices \([\varphi(m')]\).
-baseIndicesPow :: forall m m' . (m `Divides` m')
-                  => Tagged '(m, m') (U.Vector (Int,Int))
-baseIndicesPow = baseWrapper (toIndexPair . totients)
+baseIndicesPow :: forall m m' . (m `Divides` m') => U.Vector (Int,Int)
+baseIndicesPow = baseWrapper @m @m' (toIndexPair . totients)
 {-# INLINABLE baseIndicesPow #-}
 
 -- | A lookup table for 'baseIndexDec' applied to indices \([\varphi(m')]\).
-baseIndicesDec :: forall m m' . (m `Divides` m')
-                  => Tagged '(m, m') (U.Vector (Maybe (Int,Bool)))
+baseIndicesDec :: forall m m' . (m `Divides` m') => U.Vector (Maybe (Int,Bool))
 -- this one is more complicated; requires the prime powers
-baseIndicesDec = baseWrapper baseIndexDec
+baseIndicesDec = baseWrapper @m @m' baseIndexDec
 {-# INLINABLE baseIndicesDec #-}
 
 -- | Same as 'baseIndicesPow', but only includes the second component
 -- of each pair.
-baseIndicesCRT :: forall m m' . (m `Divides` m')
-                  => Tagged '(m, m') (U.Vector Int)
+baseIndicesCRT :: forall m m' . (m `Divides` m') => U.Vector Int
 baseIndicesCRT =
-  baseWrapper (\pps -> snd . toIndexPair (totients pps))
+  baseWrapper @m @m' (\pps -> snd . toIndexPair (totients pps))
 
 -- | The \(i_0\)th entry of the \(i_1\)th vector is
 -- 'fromIndexPair' \((i_1,i_0)\).
 extIndicesCoeffs :: forall m m' . (m `Divides` m')
-                    => Tagged '(m, m') (V.Vector (U.Vector Int))
-extIndicesCoeffs = do
-  (_, phi, phi', tots) <- indexInfo
-  return $ V.generate (phi' `div` phi)
-           (\i1 -> U.generate phi (\i0 -> fromIndexPair tots (i1,i0)))
+                    => V.Vector (U.Vector Int)
+extIndicesCoeffs =
+  let (_, phi, phi', tots) = indexInfo @m @m'
+  in V.generate (phi' `div` phi)
+     (\i1 -> U.generate phi (\i0 -> fromIndexPair tots (i1,i0)))
 
 -- | Convenient reindexing functions
 
diff --git a/Crypto/Lol/Cyclotomic/UCyc.hs b/Crypto/Lol/Cyclotomic/UCyc.hs
deleted file mode 100644
--- a/Crypto/Lol/Cyclotomic/UCyc.hs
+++ /dev/null
@@ -1,714 +0,0 @@
-{-|
-Module      : Crypto.Lol.Cyclotomic.UCyc
-Description : A low-level implementation of cyclotomic rings.
-Copyright   : (c) Eric Crockett, 2011-2017
-                  Chris Peikert, 2011-2017
-License     : GPL-2
-Maintainer  : ecrockett0@email.com
-Stability   : experimental
-Portability : POSIX
-
-  \( \def\Z{\mathbb{Z}} \)
-  \( \def\F{\mathbb{F}} \)
-  \( \def\Q{\mathbb{Q}} \)
-  \( \def\O{\mathcal{O}} \)
-
-A low-level implementation of cyclotomic rings that allows (and
-requires) the programmer to control the underlying representation
-of ring elements, i.e., powerful, decoding, or CRT basis.
-
-__WARNING:__ as with all fixed-point arithmetic, the functions
-associated with 'UCyc' may result in overflow (and thereby
-incorrect answers and potential security flaws) if the input
-arguments are too close to the bounds imposed by the base type.
-The acceptable range of inputs for each function is determined by
-the internal linear transforms and other operations it performs.
--}
-
-{-# LANGUAGE ConstraintKinds       #-}
-{-# LANGUAGE DataKinds             #-}
-{-# LANGUAGE FlexibleContexts      #-}
-{-# LANGUAGE FlexibleInstances     #-}
-{-# LANGUAGE GADTs                 #-}
-{-# LANGUAGE InstanceSigs          #-}
-{-# LANGUAGE MultiParamTypeClasses #-}
-{-# LANGUAGE PolyKinds             #-}
-{-# LANGUAGE RankNTypes            #-}
-{-# LANGUAGE RebindableSyntax      #-}
-{-# LANGUAGE ScopedTypeVariables   #-}
-{-# LANGUAGE TypeFamilies          #-}
-{-# LANGUAGE TypeOperators         #-}
-{-# LANGUAGE UndecidableInstances  #-}
-
-module Crypto.Lol.Cyclotomic.UCyc
-(
--- * Data types and constraints
-  UCyc, P, D, C, E, UCycEC, UCycPC, UCRTElt, NFElt
--- * Changing representation
-, toPow, toDec, toCRT, fmapPow, fmapDec
-, unzipPow, unzipDec, unzipCRTC, unzipCRTE
--- * Scalars
-, scalarPow, scalarCRT
--- * Basic operations
-, mulG, divGPow, divGDec, divGCRTC, gSqNorm
--- * Error sampling
-, tGaussian, errorRounded, errorCoset
--- * Inter-ring operations and values
-, embedPow, embedDec, embedCRTC, embedCRTE
-, twacePow, twaceDec, twaceCRTC, twaceCRTE
-, coeffsPow, coeffsDec, powBasis, crtSet
-) where
-
-import Crypto.Lol.Cyclotomic.Tensor hiding (divGDec, divGPow, embedCRT,
-                                     embedDec, embedPow, scalarCRT,
-                                     scalarPow, twaceCRT)
-
-import           Crypto.Lol.CRTrans
-import           Crypto.Lol.Cyclotomic.CRTSentinel
-import qualified Crypto.Lol.Cyclotomic.Tensor      as T
-import           Crypto.Lol.Prelude                as LP
-import           Crypto.Lol.Types.FiniteField
-import           Crypto.Lol.Types.ZPP
-
-import qualified Algebra.Additive     as Additive (C)
-import qualified Algebra.Module       as Module (C)
-import qualified Algebra.Ring         as Ring (C)
-import qualified Algebra.ZeroTestable as ZeroTestable (C)
-
-import Control.Applicative    as A
-import Control.Arrow
-import Control.DeepSeq
-import Control.Monad.Identity (Identity(..))
-import Control.Monad.Random hiding (lift)
-import Data.Foldable          as F
-import Data.Maybe
-import Data.Traversable
-
-import Crypto.Lol.Types.Proto
-
---import qualified Debug.Trace as DT
-
--- | Nullary index type representing the powerful basis.
-data P
--- | Nullary index type representing the decoding basis.
-data D
--- | Nullary index type representing the CRT basis over base ring.
-data C
--- | Nullary index type representing the CRT basis over extension of
--- base ring.
-data E
-
--- | Convenient synonym for either CRT representation.
-type UCycEC t m r = Either (UCyc t m E r) (UCyc t m C r)
-
--- | Convenient synonym for random sampling.
-type UCycPC t m r = Either (UCyc t m P r) (UCyc t m C r)
-
--- | Represents a cyclotomic ring such as \(\Z[\zeta_m]\),
--- \(\Z_q[\zeta_m]\), and \(\Q(\zeta_m)\) in an explicit
--- representation: @t@ is the 'Tensor' type for storing coefficient tensors;
--- @m@ is the cyclotomic index; @rep@ is the representation ('P', 'D', or 'C');
--- @r@ is the base ring of the coefficients (e.g., \(\Z\), \(\Z_q\)).
---
--- The 'Functor', 'Applicative', 'Foldable' and 'Traversable'
--- instances all work coefficient-wise (in the specified basis).
-data UCyc t (m :: Factored) rep r where
-  Pow  :: !(t m r) -> UCyc t m P r
-  Dec  :: !(t m r) -> UCyc t m D r
-  -- Use CRTSentinel to enforce invariant that exactly one of these
-  -- can be created for a given (t,m,r).
-  CRTC :: !(CSentinel t m r) -> !(t m r) -> UCyc t m C r
-  CRTE :: !(ESentinel t m r) -> !(t m (CRTExt r)) -> UCyc t m E r
-
--- | Constraints needed for CRT-related operations on 'UCyc' data.
-type UCRTElt t r = (Tensor t, CRTEmbed r,
-                    CRTrans Maybe r, TElt t r,
-                    CRTrans Identity (CRTExt r), TElt t (CRTExt r))
-
--- | Convenient synonym for 'deepseq'-able element type.
-type NFElt r = (NFData r, NFData (CRTExt r))
-
--- | Embed a scalar from the base ring.
-scalarPow :: (Tensor t, Fact m, Ring r, TElt t r) => r -> UCyc t m P r
-scalarPow = Pow . T.scalarPow
-{-# INLINABLE scalarPow #-}
-
--- | Embed a scalar from the base ring.
-scalarCRT :: (Fact m, UCRTElt t r) => r -> UCycEC t m r
-scalarCRT r = case crtSentinel of
-  Right s -> Right $ CRTC s $ scalarCRTCS s r
-  Left  s -> Left  $ CRTE s $ runIdentity T.scalarCRT $ toExt r
-{-# INLINABLE scalarCRT #-}
-
--- Eq instances
-
-instance (Eq r, Tensor t, Fact m, TElt t r) => Eq (UCyc t m P r) where
-  (Pow v1) == (Pow v2) = v1 == v2 \\ witness entailEqT v1
-  {-# INLINABLE (==) #-}
-
-instance (Eq r, Tensor t, Fact m, TElt t r) => Eq (UCyc t m D r) where
-  (Dec v1) == (Dec v2) = v1 == v2 \\ witness entailEqT v1
-  {-# INLINABLE (==) #-}
-
-instance (Eq r, Tensor t, Fact m, TElt t r) => Eq (UCyc t m C r) where
-  (CRTC _ v1) == (CRTC _ v2) = v1 == v2 \\ witness entailEqT v1
-  {-# INLINABLE (==) #-}
-
--- no Eq instance for E due to precision
-
----------- Numeric Prelude instances ----------
-
--- ZeroTestable instances
-
-instance (ZeroTestable r, Tensor t, Fact m, TElt t r)
-    => ZeroTestable.C (UCyc t m P r) where
-  isZero (Pow v) = isZero v \\ witness entailZTT v
-  {-# INLINABLE isZero #-}
-
-instance (ZeroTestable r, Tensor t, Fact m, TElt t r)
-    => ZeroTestable.C (UCyc t m D r) where
-  isZero (Dec v) = isZero v \\ witness entailZTT v
-  {-# INLINABLE isZero #-}
-
-instance (ZeroTestable r, Tensor t, Fact m, TElt t r)
-    => ZeroTestable.C (UCyc t m C r) where
-  isZero (CRTC _ v) = isZero v \\ witness entailZTT v
-  {-# INLINABLE isZero #-}
-
--- no ZT instance for E due to precision
-
--- Additive instances
-
-instance (Additive r, Tensor t, Fact m, TElt t r) => Additive.C (UCyc t m P r) where
-  zero = Pow $ T.scalarPow zero
-  (Pow v1) + (Pow v2) = Pow $ zipWithT (+) v1 v2
-  (Pow v1) - (Pow v2) = Pow $ zipWithT (-) v1 v2
-  negate (Pow v) = Pow $ fmapT negate v
-  {-# INLINABLE zero #-}
-  {-# INLINABLE (+) #-}
-  {-# INLINABLE (-) #-}
-  {-# INLINABLE negate #-}
-
-instance (Additive r, Tensor t, Fact m, TElt t r) => Additive.C (UCyc t m D r) where
-  zero = Dec $ T.scalarPow zero -- scalarPow works because it's zero
-  (Dec v1) + (Dec v2) = Dec $ zipWithT (+) v1 v2
-  (Dec v1) - (Dec v2) = Dec $ zipWithT (-) v1 v2
-  negate (Dec v) = Dec $ fmapT negate v
-  {-# INLINABLE zero #-}
-  {-# INLINABLE (+) #-}
-  {-# INLINABLE (-) #-}
-  {-# INLINABLE negate #-}
-
--- | only for appropriate CRT representation (otherwise 'zero' would
--- violate internal invariant)
-instance (Fact m, UCRTElt t r) => Additive.C (UCycEC t m r) where
-
-  zero = scalarCRT zero
-
-  -- CJP: precision OK?  Alternatively, switch to pow and back after
-  -- adding/subtracting.  Expensive, but necessary given output type.
-  (Right (CRTC s v1)) + (Right (CRTC _ v2)) = Right $ CRTC s $ zipWithT (+) v1 v2
-  (Left (CRTE s v1)) + (Left (CRTE _ v2)) = Left $ CRTE s $ zipWithT (+) v1 v2
-  _ + _ = error "UCyc (+) internal error: mixed CRTC/CRTE"
-
-  (Right (CRTC s v1)) - (Right (CRTC _ v2)) = Right $ CRTC s $ zipWithT (-) v1 v2
-  (Left (CRTE s v1)) - (Left (CRTE _ v2)) = Left $ CRTE s $ zipWithT (-) v1 v2
-  _ - _ = error "UCyc (-) internal error: mixed CRTC/CRTE"
-
-  negate (Right (CRTC s v)) = Right $ CRTC s $ fmapT negate v
-  negate (Left (CRTE s v)) = Left $ CRTE s $ fmapT negate v
-
-  {-# INLINABLE zero #-}
-  {-# INLINABLE (+) #-}
-  {-# INLINABLE (-) #-}
-  {-# INLINABLE negate #-}
-
--- | only for appropriate CRT representation
-instance (Fact m, UCRTElt t r) => Ring.C (UCycEC t m r) where
-
-  one = scalarCRT one
-  fromInteger c = scalarCRT $ fromInteger c
-
-  (Right (CRTC s v1)) * (Right (CRTC _ v2)) = Right $ CRTC s $ zipWithT (*) v1 v2
-  (Left (CRTE s v1)) * (Left (CRTE _ v2)) = Left $ CRTE s $ zipWithT (*) v1 v2
-  _ * _ = error "UCyc internal error: mixed CRTC/CRTE"
-
-  {-# INLINABLE one #-}
-  {-# INLINABLE fromInteger #-}
-  {-# INLINABLE (*) #-}
-
-
-instance (Ring r, Tensor t, Fact m, TElt t r) => Module.C r (UCyc t m P r) where
-  r *> (Pow v) = Pow $ fmapT (r *) v
-  {-# INLINABLE (*>) #-}
-
-instance (Ring r, Tensor t, Fact m, TElt t r) => Module.C r (UCyc t m D r) where
-  r *> (Dec v) = Dec $ fmapT (r *) v
-  {-# INLINABLE (*>) #-}
-
-instance (Ring r, Fact m, UCRTElt t r) => Module.C r (UCycEC t m r) where
-
-  r *> (Right (CRTC s v)) = Right $ CRTC s $ fmapT (r *) v
-  r *> (Left (CRTE s v)) = Left $ CRTE s $ fmapT (toExt r *) v
-  {-# INLINABLE (*>) #-}
-
--- | \(R_p\) is an \(\F_{p^d}\)-module when \(d\) divides \(\varphi(m)\), by
--- applying \(d\)-dimensional \(\F_p\)-linear transform on \(d\)-dim chunks of
--- powerful basis coeffs.
-instance (GFCtx fp d, Fact m, Tensor t, TElt t fp)
-         => Module.C (GF fp d) (UCyc t m P fp) where
-  -- can use any r-basis to define module mult, but must be
-  -- consistent.
-  r *> (Pow v) = Pow $ r LP.*> v \\ witness entailModuleT (r,v)
-
-
-instance (Reduce a b, Tensor t, Fact m, TElt t a, TElt t b)
-    => Reduce (UCyc t m P a) (UCyc t m P b) where
-  reduce (Pow v) = Pow $ fmapT reduce v
-  {-# INLINABLE reduce #-}
-
-instance (Reduce a b, Tensor t, Fact m, TElt t a, TElt t b)
-    => Reduce (UCyc t m D a) (UCyc t m D b) where
-  reduce (Dec v) = Dec $ fmapT reduce v
-  {-# INLINABLE reduce #-}
-
--- CJP: no Reduce for C because CRT basis may not exist for target
--- type
-
-type instance LiftOf (UCyc t m P r) = UCyc t m P (LiftOf r)
-type instance LiftOf (UCyc t m D r) = UCyc t m D (LiftOf r)
-
-instance (Lift' r, Tensor t, Fact m, TElt t r, TElt t (LiftOf r))
-         => Lift' (UCyc t m P r) where
-  lift (Pow v) = Pow $ fmapT lift v
-  {-# INLINABLE lift #-}
-
-instance (Lift' r, Tensor t, Fact m, TElt t r, TElt t (LiftOf r))
-         => Lift' (UCyc t m D r) where
-  lift (Dec v) = Dec $ fmapT lift v
-  {-# INLINABLE lift #-}
-
--- CJP: no Lift' for C because CRT basis may not exist for target type
-
-instance (Rescale a b, Tensor t, Fact m, TElt t a, TElt t b)
-         => Rescale (UCyc t m P a) (UCyc t m P b) where
-  rescale (Pow v) = Pow $ fmapT rescale v
-  {-# INLINABLE rescale #-}
-
-instance (Rescale a b, Tensor t, Fact m, TElt t a, TElt t b)
-         => Rescale (UCyc t m D a) (UCyc t m D b) where
-  rescale (Dec v) = Dec $ fmapT rescale v
-  {-# INLINABLE rescale #-}
-
--- CJP: no Rescale for C because CRT basis may not exist for target
--- type
-
--- CJP: we don't instantiate RescaleCyc because it requires changing bases
-
--- CJP: we don't instantiate Gadget etc., because (1) their methods
--- wouldn't be efficient, and (2) their superclass constraints are not
--- satisfied anyway (e.g., Ring for P rep).
-
-
--- | Type-restricted (and potentially more efficient) 'fmap' for
--- powerful-basis representation.
-fmapPow :: (Tensor t, Fact m, TElt t a, TElt t b)
-           => (a -> b) -> UCyc t m P a -> UCyc t m P b
-fmapPow f (Pow v) = Pow $ fmapT f v
-{-# INLINABLE fmapPow #-}
-
--- | Type-restricted (and potentially more efficient) 'fmap' for
--- decoding-basis representation.
-fmapDec :: (Tensor t, Fact m, TElt t a, TElt t b)
-           => (a -> b) -> UCyc t m D a -> UCyc t m D b
-fmapDec f (Dec v) = Dec $ fmapT f v
-{-# INLINABLE fmapDec #-}
-
--- | Unzip in the powerful basis.
-unzipPow :: (Tensor t, Fact m, TElt t (a,b), TElt t a, TElt t b)
-            => UCyc t m P (a,b) -> (UCyc t m P a, UCyc t m P b)
-{-# INLINABLE unzipPow #-}
-unzipPow (Pow v) = Pow *** Pow $ unzipT v
-
--- | Unzip in the decoding basis.
-unzipDec :: (Tensor t, Fact m, TElt t (a,b), TElt t a, TElt t b)
-            => UCyc t m D (a,b) -> (UCyc t m D a, UCyc t m D b)
-{-# INLINABLE unzipDec #-}
-unzipDec (Dec v) = Dec *** Dec $ unzipT v
-
--- | Unzip in the CRT basis over the base ring.  The output components
--- are 'Either' because each target base ring may not support 'C'.
-unzipCRTC :: (Fact m, UCRTElt t (a,b), UCRTElt t a, UCRTElt t b)
-             => UCyc t m C (a,b)
-             -> (Either (UCyc t m P a) (UCyc t m C a),
-                 Either (UCyc t m P b) (UCyc t m C b))
-{-# INLINABLE unzipCRTC #-}
-unzipCRTC (CRTC s v)
-  = let (ac,bc) = unzipT v
-        (ap,bp) = Pow *** Pow $ unzipT $ crtInvCS s v
-    in (fromMaybe (Left ap) (Right <$> (CRTC <$> crtCSentinel <*> pure ac)),
-        fromMaybe (Left bp) (Right <$> (CRTC <$> crtCSentinel <*> pure bc)))
-
--- | Unzip in the CRT basis over the extension of the base ring.  The
--- output components are 'Either' because each target base might
--- instead support 'C'.
-unzipCRTE :: (Fact m, UCRTElt t (a,b), UCRTElt t a, UCRTElt t b)
-             => UCyc t m E (a,b)
-             -> (Either (UCyc t m P a) (UCyc t m E a),
-                 Either (UCyc t m P b) (UCyc t m E b))
-{-# INLINABLE unzipCRTE #-}
-unzipCRTE (CRTE _ v)
-  = let (ae,be) = unzipT v
-        (a',b') = unzipT $ fmapT fromExt $ runIdentity crtInv v
-        (ap,bp) = Pow *** Pow $ (a',b')
-    in (fromMaybe (Left ap) (Right <$> (CRTE <$> crtESentinel <*> pure ae)),
-        fromMaybe (Left bp) (Right <$> (CRTE <$> crtESentinel <*> pure be)))
-
-
--- | Multiply by the special element \(g_m\).
-mulG :: (Fact m, UCRTElt t r) => UCyc t m rep r -> UCyc t m rep r
-{-# INLINE mulG #-}
-mulG (Pow v) = Pow $ mulGPow v
-mulG (Dec v) = Dec $ mulGDec v
-mulG (CRTC s v) = CRTC s $ mulGCRTCS s v
-mulG (CRTE s v) = CRTE s $ runIdentity mulGCRT v
-
--- Note: We do not implement divGCRTE because we can't tell whether
--- the element is actually divisible by g when using the CRT extension
--- basis.
-
--- | Divide by the special element \(g_m\).
--- WARNING: this implementation is not a constant-time algorithm, so
--- information about the argument may be leaked through a timing
--- channel.
-divGPow :: (Fact m, UCRTElt t r, ZeroTestable r, IntegralDomain r)
-        => UCyc t m P r -> Maybe (UCyc t m P r)
-{-# INLINABLE divGPow #-}
-divGPow (Pow v) = Pow <$> T.divGPow v
-
--- | Similar to 'divGPow'.
-divGDec :: (Fact m, UCRTElt t r, ZeroTestable r, IntegralDomain r)
-        => UCyc t m D r -> Maybe (UCyc t m D r)
-{-# INLINABLE divGDec #-}
-divGDec (Dec v) = Dec <$> T.divGDec v
-
--- | Similar to 'divGPow'.
-divGCRTC :: (Fact m, UCRTElt t r)
-        => UCyc t m C r -> UCyc t m C r
-{-# INLINE divGCRTC #-}
-divGCRTC (CRTC s v) = CRTC s $ divGCRTCS s v
-
--- | Yield the scaled squared norm of \(g_m \cdot e\) under
--- the canonical embedding, namely,
--- \(\hat{m}^{-1} \cdot \| \sigma(g_m \cdot e) \|^2\) .
-gSqNorm :: (Ring r, Tensor t, Fact m, TElt t r) => UCyc t m D r -> r
-gSqNorm (Dec v) = gSqNormDec v
-{-# INLINABLE gSqNorm #-}
-
--- | Sample from the "tweaked" Gaussian error distribution \(t\cdot D\) in
--- the decoding basis, where \(D\) has scaled variance \(v\).
-tGaussian :: (Tensor t, Fact m, OrdFloat q, Random q, TElt t q,
-              ToRational v, MonadRandom rnd)
-             => v -> rnd (UCyc t m D q)
-tGaussian = fmap Dec . tGaussianDec
-{-# INLINABLE tGaussian #-}
-
--- | Generate an LWE error term from the "tweaked" Gaussian with given
--- scaled variance, deterministically rounded using the decoding
--- basis. (Note: This
--- implementation uses 'Double' precision to generate the Gaussian
--- sample, which may not be sufficient for rigorous proof-based
--- security.)
-errorRounded :: forall v rnd t m z .
-                (ToInteger z, Tensor t, Fact m, TElt t z,
-                 ToRational v, MonadRandom rnd)
-                => v -> rnd (UCyc t m D z)
-{-# INLINABLE errorRounded #-}
-errorRounded svar =
-  Dec . fmapT (roundMult one) <$> (tGaussianDec svar :: rnd (t m Double))
-
--- | Generate an LWE error term from the "tweaked" Gaussian with
--- scaled variance \(v \cdot p^2\), deterministically rounded to the given
--- coset of \(R_p\) using the decoding basis. (Note: This
--- implementation uses 'Double' precision to generate the Gaussian
--- sample, which may not be sufficient for rigorous proof-based
--- security.)
-errorCoset :: forall t m zp z v rnd .
-  (Mod zp, z ~ ModRep zp, Lift zp z, Tensor t, Fact m,
-   ToRational v, MonadRandom rnd)
-  => v -> UCyc t m D zp -> rnd (UCyc t m D z)
-{-# INLINABLE errorCoset #-}
-errorCoset =
-  let pval = fromIntegral $ proxy modulus (Proxy::Proxy zp)
-  in \ svar c -> do err :: UCyc t m D Double <- tGaussian (svar*pval*pval)
-                    return $! roundCoset <$> c <*> err
-
-
------ inter-ring operations
-
--- | Embed into an extension ring, for the powerful basis.
-embedPow :: (Additive r, Tensor t, m `Divides` m', TElt t r)
-            => UCyc t m P r -> UCyc t m' P r
-embedPow (Pow v) = Pow $ T.embedPow v
-{-# INLINABLE embedPow #-}
-
--- | Embed into an extension ring, for the decoding basis.
-embedDec :: (Additive r, Tensor t, m `Divides` m', TElt t r)
-            => UCyc t m D r -> UCyc t m' D r
-embedDec (Dec v) = Dec $ T.embedDec v
-{-# INLINABLE embedDec #-}
-
--- | Embed into an extension ring, for the CRT basis.  (The output is
--- an 'Either' because the extension ring might not support 'C'.)
-embedCRTC :: (m `Divides` m', UCRTElt t r)
-             => UCyc t m C r -> Either (UCyc t m' P r) (UCyc t m' C r)
-{-# INLINABLE embedCRTC #-}
-embedCRTC x@(CRTC s v) =
-  case crtSentinel of
-    -- go to CRTC if valid, else go to Pow
-    Left  _ -> Left $ embedPow $ toPow x
-    Right s' -> Right $ CRTC s' $ embedCRTCS s s' v
-
--- | Similar to 'embedCRTC'.  (The output is an 'Either' because the
--- extension ring might support 'C', in which case we never use 'E'.)
-embedCRTE :: forall m m' t r . (m `Divides` m', UCRTElt t r)
-             => UCyc t m E r -> Either (UCyc t m' P r) (UCyc t m' E r)
-{-# INLINABLE embedCRTE #-}
-embedCRTE x@(CRTE _ v) =
-  case crtSentinel of
-    -- go to CRTE if valid, else go to Pow
-    Left  s -> Right $ CRTE s $ runIdentity T.embedCRT v
-    Right _ -> Left $ embedPow $ toPow x
-
--- | Twace into a subring, for the powerful basis.
-twacePow :: (Ring r, Tensor t, m `Divides` m', TElt t r)
-            => UCyc t m' P r -> UCyc t m P r
-twacePow (Pow v) = Pow $ twacePowDec v
-{-# INLINABLE twacePow #-}
-
--- | Twace into a subring, for the decoding basis.
-twaceDec :: (Ring r, Tensor t, m `Divides` m', TElt t r)
-            => UCyc t m' D r -> UCyc t m D r
-twaceDec (Dec v) = Dec $ twacePowDec v
-{-# INLINABLE twaceDec #-}
-
--- | Twace into a subring, for the CRT basis.  (The output is an
--- 'Either' because the subring might not support 'C'.)
-twaceCRTC :: (m `Divides` m', UCRTElt t r)
-             => UCyc t m' C r -> UCycPC t m r
-{-# INLINE twaceCRTC #-}
-twaceCRTC x@(CRTC s' v) =
-  case crtSentinel of
-    -- go to CRTC if valid for target, else go to Pow
-    Left  _ -> Left $ twacePow $ toPow x
-    Right s -> Right $ CRTC s $ twaceCRTCS s' s v
-
--- | Similar to 'twaceCRTC'.  (The output is an 'Either' because the
--- subring might support 'C', in which case we never use 'E'.)
-twaceCRTE :: forall t m m' r . (m `Divides` m', UCRTElt t r)
-             => UCyc t m' E r -> Either (UCyc t m P r) (UCyc t m E r)
-{-# INLINABLE twaceCRTE #-}
-twaceCRTE x@(CRTE _ v) =
-  case crtSentinel of
-    -- go to CRTE if valid for target, else go to Pow
-    Left  s -> Right $ CRTE s $ runIdentity T.twaceCRT v
-    Right _ -> Left $ twacePow $ toPow x
-
--- | Yield the \(\O_m\)-coefficients of an \(\O_{m'}\)-element,
--- with respect to the relative powerful \(\O_m\)-basis.
-coeffsPow :: (Ring r, Tensor t, m `Divides` m', TElt t r)
-             => UCyc t m' P r -> [UCyc t m P r]
-{-# INLINABLE coeffsPow #-}
-coeffsPow (Pow v) = LP.map Pow $ coeffs v
-
--- | Yield the \(\O_m\)-coefficients of an \(\O_{m'}\) element,
--- with respect to the relative decoding \(\O_m\)-basis.
-coeffsDec :: (Ring r, Tensor t, m `Divides` m', TElt t r)
-             => UCyc t m' D r -> [UCyc t m D r]
-{-# INLINABLE coeffsDec #-}
-coeffsDec (Dec v) = LP.map Dec $ coeffs v
-
--- | The relative powerful basis of \(\O_{m'} / \O_m\).
-powBasis :: (Ring r, Tensor t, m `Divides` m', TElt t r)
-            => Tagged m [UCyc t m' P r]
-{-# INLINABLE powBasis #-}
-powBasis = (Pow <$>) <$> powBasisPow
-
--- | The relative mod-\(r\) CRT set of \(\O_{m'} / \O_m\),
--- represented with respect to the powerful basis (which seems to be
--- the best choice for typical use cases).
-crtSet :: forall t m m' r p mbar m'bar .
-           (m `Divides` m', ZPP r, p ~ CharOf (ZpOf r),
-            mbar ~ PFree p m, m'bar ~ PFree p m',
-            UCRTElt t r, TElt t (ZpOf r))
-           => Tagged m [UCyc t m' P r]
-{-# INLINABLE crtSet #-}
-crtSet =
-  -- CJP: consider using traceEvent or traceMarker
-  --DT.trace ("UCyc.crtSet: m = " ++
-  --          show (proxy valueFact (Proxy::Proxy m)) ++ ", m'= " ++
-  --          show (proxy valueFact (Proxy::Proxy m'))) $
-  let (p,e) = proxy modulusZPP (Proxy::Proxy r)
-      pp = Proxy::Proxy p
-      pm = Proxy::Proxy m
-      pm' = Proxy::Proxy m'
-  in retag (fmap (embedPow .
-                  (if e > 1 then toPowCE . (^(p^(e-1))) . toCRT else toPow) .
-                  Dec . fmapT liftZp) <$>
-            (crtSetDec :: Tagged mbar [t m'bar (ZpOf r)]))
-     \\ pFreeDivides pp pm pm' \\ pSplitTheorems pp pm \\ pSplitTheorems pp pm'
-
-
---------- Conversion methods ------------------
-
--- | Convert to powerful-basis representation.
-toPow :: (Fact m, UCRTElt t r) => UCyc t m rep r -> UCyc t m P r
-{-# INLINABLE toPow #-}
-toPow x@(Pow _) = x
-toPow (Dec v) = Pow $ l v
-toPow (CRTC s v) = Pow $ crtInvCS s v
-toPow (CRTE _ v) = Pow $ fmapT fromExt $ runIdentity crtInv v
-
--- | Convenient version of 'toPow' for 'Either' CRT basis type.
-toPowCE :: (Fact m, UCRTElt t r) => UCycEC t m r -> UCyc t m P r
-{-# INLINABLE toPowCE #-}
-toPowCE (Left u) = toPow u
-toPowCE (Right u) = toPow u
-
--- | Convert to decoding-basis representation.
-toDec :: (Fact m, UCRTElt t r) => UCyc t m rep r -> UCyc t m D r
-{-# INLINABLE toDec #-}
-toDec (Pow v) = Dec $ lInv v
-toDec x@(Dec _) = x
-toDec x@(CRTC _ _) = toDec $ toPow x
-toDec x@(CRTE _ _) = toDec $ toPow x
-
--- | Convert to a CRT-basis representation.
-toCRT :: forall t m rep r . (Fact m, UCRTElt t r)
-         => UCyc t m rep r -> UCycEC t m r
-{-# INLINABLE toCRT #-}
-toCRT = let fromPow :: t m r -> UCycEC t m r
-            fromPow = case crtSentinel of
-              Right s -> Right . CRTC s . crtCS s
-              Left  s -> Left  . CRTE s . runIdentity crt . fmapT toExt
-        in \x -> case x of
-                   (CRTC _ _) -> Right x
-                   (CRTE _ _) -> Left x
-                   (Pow v) -> fromPow v
-                   (Dec v) -> fromPow $ l v
-
-
----------- Category-theoretic instances ----------
-
--- CJP: no instances for E because types (and math) don't make sense.
-
--- | apply coefficient-wise (with respect to powerful basis)
-instance (Tensor t, Fact m) => Functor (UCyc t m P) where
-  -- Functor instance is implied by Applicative laws
-  {-# INLINABLE fmap #-}
-  fmap f x = pure f <*> x
-
--- | apply coefficient-wise (with respect to decoding basis)
-instance (Tensor t, Fact m) => Functor (UCyc t m D) where
-  -- Functor instance is implied by Applicative laws
-  {-# INLINABLE fmap #-}
-  fmap f x = pure f <*> x
-
--- CJP: no Functor instance for C, because CRTrans for a doesn't imply
--- it for b.
-
-instance (Tensor t, Fact m) => Applicative (UCyc t m P) where
-  pure = Pow . pure \\ proxy entailIndexT (Proxy::Proxy (t m r))
-  (Pow f) <*> (Pow v) = Pow $ f <*> v \\ witness entailIndexT v
-
-  {-# INLINABLE pure #-}
-  {-# INLINABLE (<*>) #-}
-
-instance (Tensor t, Fact m) => Applicative (UCyc t m D) where
-  pure = Dec . pure \\ proxy entailIndexT (Proxy::Proxy (t m r))
-  (Dec f) <*> (Dec v) = Dec $ f <*> v \\ witness entailIndexT v
-
-  {-# INLINABLE pure #-}
-  {-# INLINABLE (<*>) #-}
-
--- CJP: no Applicative instance for C, because 'pure' would circumvent
--- the invariant.  Moreover, having CRTrans for (a -> b) and for a
--- doesn't imply it for b.
-
-instance (Tensor t, Fact m) => Foldable (UCyc t m P) where
-  {-# INLINABLE foldr #-}
-  foldr f b (Pow v) = F.foldr f b v \\ witness entailIndexT v
-
-instance (Tensor t, Fact m) => Foldable (UCyc t m D) where
-  {-# INLINABLE foldr #-}
-  foldr f b (Dec v) = F.foldr f b v \\ witness entailIndexT v
-
-instance (Tensor t, Fact m) => Foldable (UCyc t m C) where
-  {-# INLINABLE foldr #-}
-  foldr f b (CRTC _ v) = F.foldr f b v \\ witness entailIndexT v
-
-
-instance (Tensor t, Fact m) => Traversable (UCyc t m P) where
-  {-# INLINABLE traverse #-}
-  traverse f (Pow v) = Pow <$> traverse f v \\ witness entailIndexT v
-
-instance (Tensor t, Fact m) => Traversable (UCyc t m D) where
-  {-# INLINABLE traverse #-}
-  traverse f (Dec v) = Dec <$> traverse f v \\ witness entailIndexT v
-
--- CJP: no Traversable instance for C, because CRTrans for a doesn't
--- imply it for b.
-
-
----------- Utility instances ----------
-
-instance (Random r, UCRTElt t r, Fact m) => Random (UCyc t m P r) where
-
-  random g = let (v,g') = random g \\ witness entailRandomT v
-             in (Pow v, g')
-
-  randomR _ = error "randomR non-sensical for UCyc"
-
-instance (Random r, UCRTElt t r, Fact m) => Random (UCyc t m D r) where
-
-  random g = let (v,g') = random g \\ witness entailRandomT v
-             in (Dec v, g')
-
-  randomR _ = error "randomR non-sensical for UCyc"
-
-instance (Random r, UCRTElt t r, Fact m)
-         => Random (UCycPC t m r) where
-
-  -- create in CRTC basis if possible, otherwise in powerful
-  random = let cons = case crtSentinel of
-                 Left  _ -> Left  . Pow
-                 Right s -> Right . CRTC s
-           in \g -> let (v,g') = random g \\ witness entailRandomT v
-                    in (cons v, g')
-
-  randomR _ = error "randomR non-sensical for UCyc"
-
-instance (Tensor t, Fact m, NFElt r, TElt t r, TElt t (CRTExt r))
-         => NFData (UCyc t m rep r) where
-  rnf (Pow x)      = rnf x \\ witness entailNFDataT x
-  rnf (Dec x)      = rnf x \\ witness entailNFDataT x
-  rnf (CRTC _ x)   = rnf x \\ witness entailNFDataT x
-  rnf (CRTE _ x)   = rnf x \\ witness entailNFDataT x
-
-instance (Protoable (t m r)) => Protoable (UCyc t m D r) where
-  type ProtoType (UCyc t m D r) = ProtoType (t m r)
-  toProto (Dec t) = toProto t
-  fromProto t = Dec <$> fromProto t
-
-instance (Show r, Fact m, TElt t r, Tensor t) => Show (UCyc t m P r) where
-  show (Pow x) = "UPow " ++ show x \\ witness entailShowT x
-
-instance (Show r, Fact m, TElt t r, Tensor t) => Show (UCyc t m D r) where
-  show (Dec x) = "UDec " ++ show x \\ witness entailShowT x
-
-instance (Show r, Fact m, TElt t r, Tensor t) => Show (UCyc t m C r) where
-  show (CRTC _ x) = "UCRTC " ++ show x \\ witness entailShowT x
-
-instance (Show (CRTExt r), Fact m, TElt t (CRTExt r), Tensor t)
-  => Show (UCyc t m E r) where
-  show (CRTE _ x) = "UCRTE " ++ show x \\ witness entailShowT x
diff --git a/Crypto/Lol/Factored.hs b/Crypto/Lol/Factored.hs
--- a/Crypto/Lol/Factored.hs
+++ b/Crypto/Lol/Factored.hs
@@ -3,8 +3,8 @@
 Description : Type-level factored naturals.
 Copyright   : (c) Eric Crockett, 2011-2017
                   Chris Peikert, 2011-2017
-License     : GPL-2
-Maintainer  : ecrockett0@email.com
+License     : GPL-3
+Maintainer  : ecrockett0@gmail.com
 Stability   : experimental
 Portability : POSIX
 
diff --git a/Crypto/Lol/FactoredDefs.hs b/Crypto/Lol/FactoredDefs.hs
--- a/Crypto/Lol/FactoredDefs.hs
+++ b/Crypto/Lol/FactoredDefs.hs
@@ -3,8 +3,8 @@
 Description : Internal module.
 Copyright   : (c) Eric Crockett, 2011-2017
                   Chris Peikert, 2011-2017
-License     : GPL-2
-Maintainer  : ecrockett0@email.com
+License     : GPL-3
+Maintainer  : ecrockett0@gmail.com
 Stability   : experimental
 Portability : POSIX
 
@@ -12,18 +12,23 @@
 template Haskell splices in the same module.
 -}
 
-{-# LANGUAGE ConstraintKinds      #-}
-{-# LANGUAGE DataKinds            #-}
-{-# LANGUAGE GADTs                #-}
-{-# LANGUAGE InstanceSigs         #-}
-{-# LANGUAGE KindSignatures       #-}
-{-# LANGUAGE PolyKinds            #-}
-{-# LANGUAGE ScopedTypeVariables  #-}
-{-# LANGUAGE RankNTypes           #-}
-{-# LANGUAGE TemplateHaskell      #-}
-{-# LANGUAGE TypeFamilies         #-}
-{-# LANGUAGE TypeOperators        #-}
-{-# LANGUAGE UndecidableInstances #-}
+{-# LANGUAGE AllowAmbiguousTypes   #-}
+{-# LANGUAGE ConstraintKinds       #-}
+{-# LANGUAGE DataKinds             #-}
+{-# LANGUAGE FlexibleInstances     #-}
+{-# LANGUAGE GADTs                 #-}
+{-# LANGUAGE InstanceSigs          #-}
+{-# LANGUAGE MultiParamTypeClasses #-}
+{-# LANGUAGE NoStarIsType          #-}
+{-# LANGUAGE PolyKinds             #-}
+{-# LANGUAGE RankNTypes            #-}
+{-# LANGUAGE ScopedTypeVariables   #-}
+{-# LANGUAGE StandaloneDeriving    #-}
+{-# LANGUAGE TemplateHaskell       #-}
+{-# LANGUAGE TypeApplications      #-}
+{-# LANGUAGE TypeFamilies          #-}
+{-# LANGUAGE TypeOperators         #-}
+{-# LANGUAGE UndecidableInstances  #-}
 
 {-# OPTIONS_GHC -fno-warn-unused-binds          #-}
 {-# OPTIONS_GHC -fno-warn-redundant-constraints #-}
@@ -34,7 +39,7 @@
   Factored, SFactored, Fact, fType, fDec
 , reifyFact, reifyFactI, intToFact
 -- * Prime powers
-, PrimePower, SPrimePower, Sing(SPP), PPow, ppType, ppDec
+, PrimePower(..), SPrimePower, Sing(SPP), PPow, ppType, ppDec
 , reifyPPow, reifyPPowI
 -- * Primes
 , PrimeBin, SPrimeBin, Prime, pType, pDec
@@ -49,12 +54,13 @@
 , fGCD, FGCD, fLCM, FLCM, Coprime
 , fOddRadical, FOddRadical
 , pFree, PFree
--- * Convenient reflections
+-- * Reflections
 , ppsFact, valueFact, totientFact, radicalFact, oddRadicalFact, valueHatFact
 , ppPPow, primePPow, exponentPPow, valuePPow, totientPPow, radicalPPow, oddRadicalPPow, valueHatPPow
 , valuePrime
--- * Data-level equivalents of reflections for 'Factored' data
+-- * Operations on 'Factored' values
 , valueF, totientF, radicalF, oddRadicalF, valueHatF
+-- CJP: are the above actually used anywhere? Don't see that they're needed
 -- * Number-theoretic laws
 , transDivides, gcdDivides, lcmDivides, lcm2Divides
 , pSplitTheorems, pFreeDivides
@@ -69,10 +75,9 @@
 import Crypto.Lol.PosBin
 
 import Control.Arrow
-import Data.Constraint           hiding ((***), (&&&))
-import Data.Functor.Trans.Tagged
-import Data.List                 hiding ((\\))
-import Data.Singletons.Prelude   hiding ((:-))
+import Data.Constraint         hiding ((&&&), (***))
+import Data.List               hiding ((\\))
+import Data.Singletons.Prelude hiding (type (*))
 import Data.Singletons.TH
 import Language.Haskell.TH
 
@@ -140,8 +145,7 @@
                 GT -> pp : ppMul pp' pps'
 
             ppsMul :: [PrimePower] -> [PrimePower] -> [PrimePower]
-            ppsMul [] ys = ys
-            ppsMul (pp:pps) ys = ppsMul pps (ppMul pp ys)
+            ppsMul pps ys = foldl (flip ppMul) ys pps
 
             |]
 
@@ -220,7 +224,7 @@
               where go [] = []
                     go (pp@(PP (p',_)) : ps) =
                       if p == p' then ps
-                      else pp : (go ps)
+                      else pp : go ps
             |]
 
 -- | Type (family) synonym for division of 'Factored' types.
@@ -257,7 +261,7 @@
 -- | Reify a 'PrimePower' for a 'PPow' constraint.
 reifyPPowI :: (Int,Int) -> (forall pp proxy. PPow pp => proxy pp -> a) -> a
 reifyPPowI pp k =
-  reifyPPow pp $ (\(p::SPrimePower p) -> withSingI p $ k (Proxy::Proxy p))
+  reifyPPow pp (\(p::SPrimePower p) -> withSingI p $ k (Proxy::Proxy p))
 
 -- | Reify a 'Factored' as a singleton.
 reifyFact :: Int -> (forall m . SFactored m -> a) -> a
@@ -266,12 +270,12 @@
                     -> (forall (pps :: [PrimePower]) . Sing pps -> a) -> a
         reifyPPs [] c = c SNil
         reifyPPs (pp:pps) c =
-          reifyPPow pp (\spp -> reifyPPs pps (\sm' -> c $ SCons spp sm'))
+          reifyPPow pp (\spp -> reifyPPs pps (c . SCons spp))
 
 -- | Reify a 'Factored' for a 'Fact' constraint.
 reifyFactI :: Int -> (forall m proxy. Fact m => proxy m -> a) -> a
 reifyFactI pps k =
-  reifyFact pps $ (\(m::SFactored m) -> withSingI m $ k (Proxy::Proxy m))
+  reifyFact pps (\(m::SFactored m) -> withSingI m $ k (Proxy::Proxy m))
 
 -- | Constraint synonym for divisibility of 'Factored' types.
 type Divides m m' = (Fact m, Fact m', FDivides m m' ~ 'True)
@@ -282,68 +286,68 @@
 -- coercions: using proxy arguments here due to compiler bugs in usage
 
 -- coerce any divisibility relationship we want
-coerceFDivs :: p m -> p' m' -> (() :- (FDivides m m' ~ 'True))
-coerceFDivs _ _ = Sub $ unsafeCoerce (Dict :: Dict ())
+coerceFDivs :: forall m m' . (() :- (FDivides m m' ~ 'True))
+coerceFDivs = Sub $ unsafeCoerce (Dict :: Dict ())
 
 -- coerce any GCD we want
-coerceGCD :: p a -> p' a' -> p'' a'' -> (() :- (FGCD a a' ~ a''))
-coerceGCD _ _ _ = Sub $ unsafeCoerce (Dict :: Dict ())
+coerceGCD :: (() :- (FGCD a a' ~ a''))
+coerceGCD = Sub $ unsafeCoerce (Dict :: Dict ())
 
 -- | Entails constraint for transitivity of division, i.e.
 -- if \( k \mid l \) and \( l \mid m \), then \( k \mid m \).
-transDivides :: forall k l m . Proxy k -> Proxy l -> Proxy m ->
+transDivides :: forall k l m .
                 ((k `Divides` l, l `Divides` m) :- (k `Divides` m))
-transDivides k _ m = Sub Dict \\ coerceFDivs k m
+transDivides = Sub Dict \\ coerceFDivs @k @m
 
 -- | Entailment for divisibility by GCD:
 -- if \( g=\gcd(m_1,m_2) \) then \( g \mid m_1 \) and \( g \mid m_2 \).
-gcdDivides :: forall m1 m2 g . Proxy m1 -> Proxy m2 ->
+gcdDivides :: forall m1 m2 g .
               ((Fact m1, Fact m2, g ~ FGCD m1 m2) :-
                (g `Divides` m1, g `Divides` m2))
-gcdDivides m1 m2 =
+gcdDivides =
   Sub $ withSingI (sFGCD (sing :: SFactored m1) (sing :: SFactored m2))
-  Dict \\ coerceFDivs (Proxy::Proxy g) m1
-       \\ coerceFDivs (Proxy::Proxy g) m2
+  Dict \\ coerceFDivs @g @m1
+       \\ coerceFDivs @g @m2
 
 -- | Entailment for LCM divisibility:
 -- if \( l=\lcm(m_1,m_2) \) then \( m_1 \mid l \) and \( m_2 \mid l \).
-lcmDivides :: forall m1 m2 l . Proxy m1 -> Proxy m2 ->
+lcmDivides :: forall m1 m2 l .
               ((Fact m1, Fact m2, l ~ FLCM m1 m2) :-
                (m1 `Divides` l, m2 `Divides` l))
-lcmDivides m1 m2 =
+lcmDivides =
   Sub $ withSingI (sFLCM (sing :: SFactored m1) (sing :: SFactored m2))
-  Dict \\ coerceFDivs m1 (Proxy::Proxy l)
-       \\ coerceFDivs m2 (Proxy::Proxy l)
+  Dict \\ coerceFDivs @m1 @l
+       \\ coerceFDivs @m2 @l
 
 -- | Entailment for LCM divisibility:
 -- the LCM of two divisors of \( m \) also divides \( m \).
-lcm2Divides :: forall m1 m2 l m . Proxy m1 -> Proxy m2 -> Proxy m ->
+lcm2Divides :: forall m1 m2 m l .
                ((m1 `Divides` m, m2 `Divides` m, l ~ FLCM m1 m2) :-
-                (m1 `Divides` l, m2 `Divides` l, (FLCM m1 m2) `Divides` m))
-lcm2Divides m1 m2 m =
+                (m1 `Divides` l, m2 `Divides` l, FLCM m1 m2 `Divides` m))
+lcm2Divides =
   Sub $ withSingI (sFLCM (sing :: SFactored m1) (sing :: SFactored m2))
-  Dict \\ coerceFDivs (Proxy::Proxy (FLCM m1 m2)) m \\ lcmDivides m1 m2
+  Dict \\ coerceFDivs @(FLCM m1 m2) @m \\ lcmDivides @m1 @m2
 
 -- | Entailment for \( p \)-free division:
 -- if \( f \) is \(m \) after removing all \( p \)-factors, then \( f \mid m \)
 -- and \( \gcd(f,p)=1 \).
-pSplitTheorems :: forall p m f . Proxy p -> Proxy m ->
+pSplitTheorems :: forall p m f .
                   ((Prime p, Fact m, f ~ PFree p m) :-
                    (f `Divides` m, Coprime (PToF p) f))
-pSplitTheorems _ m =
+pSplitTheorems =
   Sub $ withSingI (sPFree (sing :: SPrimeBin p) (sing :: SFactored m))
-  Dict \\ coerceFDivs (Proxy::Proxy f) m
-  \\ coerceGCD (Proxy::Proxy (PToF p)) (Proxy::Proxy f) (Proxy::Proxy F1)
+  Dict \\ coerceFDivs @f @m
+  \\ coerceGCD @(PToF p) @f @F1
 
 -- | Entailment for \( p \)-free division:
 -- if \( m \mid m' \), then \( \text{p-free}(m) \mid \text{p-free}(m') \).
-pFreeDivides :: forall p m m' . Proxy p -> Proxy m -> Proxy m' ->
+pFreeDivides :: forall p m m' .
                 ((Prime p, m `Divides` m') :-
-                 ((PFree p m) `Divides` (PFree p m')))
-pFreeDivides _ _ _ =
+                 (PFree p m `Divides` PFree p m'))
+pFreeDivides =
   Sub $ withSingI (sPFree (sing :: SPrimeBin p) (sing :: SFactored m)) $
         withSingI (sPFree (sing :: SPrimeBin p) (sing :: SFactored m')) $
-        Dict \\ coerceFDivs (Proxy::Proxy (PFree p m)) (Proxy::Proxy (PFree p m'))
+        Dict \\ coerceFDivs @(PFree p m) @(PFree p m')
 
 -- | Type synonym for @(prime, exponent)@ pair.
 type PP = (Int, Int)
@@ -353,31 +357,31 @@
 ppToPP = (binToInt . unP *** posToInt) . unPP
 
 -- | Reflect a 'PrimePower' type to a 'PP' value.
-ppPPow :: forall pp . PPow pp => Tagged pp PP
-ppPPow = tag $ ppToPP $ fromSing (sing :: SPrimePower pp)
+ppPPow :: forall pp . PPow pp => PP
+ppPPow = ppToPP $ fromSing (sing :: SPrimePower pp)
 
 -- | Value-level prime-power factorization tagged by a 'Factored' type.
-ppsFact :: forall m . Fact m => Tagged m [PP]
-ppsFact = tag $ map ppToPP $ unF $ fromSing (sing :: SFactored m)
+ppsFact :: forall m . Fact m => [PP]
+ppsFact = map ppToPP $ unF $ fromSing (sing :: SFactored m)
 
 -- | The value of a 'PrimeBin' type.
-valuePrime :: forall p . Prime p => Tagged p Int
-valuePrime = tag $ binToInt $ unP $ fromSing (sing :: SPrimeBin p)
+valuePrime :: forall p . Prime p => Int
+valuePrime = binToInt $ unP $ fromSing (sing :: SPrimeBin p)
 
 
 valueFact, totientFact, radicalFact, oddRadicalFact, valueHatFact ::
-  Fact m => Tagged m Int
+  forall m . Fact m => Int
 -- | The value of a 'Factored' type.
-valueFact = valuePPs <$> ppsFact
+valueFact = valuePPs $ ppsFact @m
 -- | The totient of a 'Factored' type's value.
-totientFact = totientPPs <$> ppsFact
+totientFact = totientPPs $ ppsFact @m
 -- | The "hat" of a 'Factored' type's value:
 -- \( \hat{m} = \begin{cases} m & \mbox{if } m \text{ is odd} \\ m/2 & \text{otherwise} \end{cases} \).
-valueHatFact = valueHat <$> valueFact
+valueHatFact = valueHat $ valueFact @m
 -- | The radical (product of prime divisors) of a 'Factored' type.
-radicalFact = radicalPPs <$> ppsFact
+radicalFact = radicalPPs $ ppsFact @m
 -- | The odd radical (product of odd prime divisors) of a 'Factored' type.
-oddRadicalFact = oddRadicalPPs <$> ppsFact
+oddRadicalFact = oddRadicalPPs $ ppsFact @m
 
 valueF, totientF, radicalF, oddRadicalF, valueHatF :: Factored -> Int
 -- | The value of a 'Factored'.
@@ -392,22 +396,22 @@
 oddRadicalF = oddRadicalPPs . map ppToPP . unF
 
 primePPow, exponentPPow, valuePPow, totientPPow, radicalPPow, oddRadicalPPow, valueHatPPow ::
-  PPow pp => Tagged pp Int
+  forall pp . PPow pp => Int
 -- | Reflect the prime component of a 'PrimePower' type.
-primePPow = fst <$> ppPPow
+primePPow = fst $ ppPPow @pp
 -- | Reflect the exponent component of a 'PrimePower' type.
-exponentPPow = snd <$> ppPPow
+exponentPPow = snd $ ppPPow @pp
 -- | The value of a 'PrimePower' type.
-valuePPow = valuePP <$> ppPPow
+valuePPow = valuePP $ ppPPow @pp
 -- | The totient of a 'PrimePower' type's value.
-totientPPow = totientPP <$> ppPPow
+totientPPow = totientPP $ ppPPow @pp
 -- | The "hat" of a 'PrimePower' type's value:
 -- \( p^e \) if \( p \) is odd, \( 2^{e-1} \) otherwise.
-valueHatPPow = valueHat <$> valuePPow
+valueHatPPow = valueHat $ valuePPow @pp
 -- | The radical of a 'PrimePower' type's value.
-radicalPPow = radicalPP <$> ppPPow
+radicalPPow = radicalPP $ ppPPow @pp
 -- | The odd radical of a 'PrimePower' type's value.
-oddRadicalPPow = oddRadicalPP <$> ppPPow
+oddRadicalPPow = oddRadicalPP $ ppPPow @pp
 
 -- functions on data-level [PP]
 valuePPs, totientPPs, radicalPPs, oddRadicalPPs :: [PP] -> Int
@@ -471,8 +475,8 @@
 -- small-to-moderate-sized arguments (any reasonable cyclotomic index
 -- should be OK).
 fType :: Int -> TypeQ
-fType n = conT 'F `appT` (foldr (\pp -> appT (promotedConsT `appT` ppType pp))
-                                promotedNilT $ factorize n)
+fType n = conT 'F `appT` foldr (\pp -> appT (promotedConsT `appT` ppType pp))
+          promotedNilT (factorize n)
 
 -- | Template Haskell splice that defines the 'PrimeBin' type synonym
 -- @Prime@\(p\) for a positive prime integer \( p \).
diff --git a/Crypto/Lol/Gadget.hs b/Crypto/Lol/Gadget.hs
--- a/Crypto/Lol/Gadget.hs
+++ b/Crypto/Lol/Gadget.hs
@@ -3,7 +3,7 @@
 Description : Interfaces for "gadgets," decomposition, and error correction.
 Copyright   : (c) Eric Crockett, 2011-2017
                   Chris Peikert, 2011-2017
-License     : GPL-2
+License     : GPL-3
 Maintainer  : ecrockett0@email.com
 Stability   : experimental
 Portability : POSIX
@@ -11,6 +11,7 @@
 Interfaces for "gadgets," decomposition, and error correction.
 -}
 
+{-# LANGUAGE AllowAmbiguousTypes   #-}
 {-# LANGUAGE ConstraintKinds       #-}
 {-# LANGUAGE DataKinds             #-}
 {-# LANGUAGE FlexibleContexts      #-}
@@ -20,12 +21,13 @@
 {-# LANGUAGE PolyKinds             #-}
 {-# LANGUAGE ScopedTypeVariables   #-}
 {-# LANGUAGE TupleSections         #-}
+{-# LANGUAGE TypeApplications      #-}
 {-# LANGUAGE TypeFamilies          #-}
 {-# LANGUAGE UndecidableInstances  #-}
 
 module Crypto.Lol.Gadget
 ( Gadget(..), Decompose(..), Correct(..)
-, decomposeT, decomposeList, decomposeMatrix
+, decomposeList, decomposeMatrix
 , TrivGad, BaseBGad
 ) where
 
@@ -35,7 +37,6 @@
 
 import Control.Applicative
 import Control.Arrow
-import Data.Traversable
 
 -- | Dummy type representing the gadget \( [1] \).
 data TrivGad
@@ -44,61 +45,59 @@
 
 -- | "Gadget" vectors, parameterized by an index type.
 
+-- CJP: is Ring superclass really necessary here?
 class Ring u => Gadget gad u where
   -- | The gadget vector over @u@.
-  gadget :: Tagged gad [u]
+  gadget :: [u]
 
   -- | Yield an error-tolerant encoding of an element with respect to
   -- the gadget.  (Mathematically, this should just be the product of
   -- the input with the gadget, but it is a class method to allow for
   -- optimized implementations.)
-  encode :: u -> Tagged gad [u]
-  encode s = ((* s) <$>) <$> gadget
+  encode :: u -> [u]
+  encode s = (* s) <$> gadget @gad
 
 -- | Decomposition relative to a gadget.
 
+-- CJP: include a `Module (DecompOf u) u` superclass constraint?
 class (Gadget gad u, Reduce (DecompOf u) u) => Decompose gad u where
   -- | The ring that @u@ decomposes over.
   type DecompOf u
 
   -- | Yield a short vector \( x \) such that \( \langle g, x\rangle = u \).
-  decompose :: u -> Tagged gad [DecompOf u]
-
--- | Alternative to 'decompose'.
-decomposeT :: Decompose gad u => u -> TaggedT gad [] (DecompOf u)
-decomposeT = peelT . decompose
+  decompose :: u -> [DecompOf u]
 
 -- | Decompose a list entry-wise.
-decomposeList :: Decompose gad u => [u] -> Tagged gad [DecompOf u]
-decomposeList = fmap concat . traverse decompose
+decomposeList :: forall gad u . Decompose gad u => [u] -> [DecompOf u]
+decomposeList = concatMap (decompose @gad)
 
 -- | Decompose a matrix entry-wise.
 decomposeMatrix :: forall gad u . (Decompose gad u)
-                   => Matrix u -> Tagged gad (Matrix (DecompOf u))
-decomposeMatrix m = do
-  l <- length <$> (gadget :: Tagged gad [u]) -- CJP: avoid scoped type vars?
-  fromColumns (l * numRows m) (numColumns m) <$>
-    traverse decomposeList (columns m)
+                   => Matrix u -> Matrix (DecompOf u)
+decomposeMatrix =
+  let l = length $ gadget @gad @u
+  in \m -> fromColumns (l * numRows m) (numColumns m) $
+           decomposeList @gad <$> columns m
 
 -- | Error correction relative to a gadget.
 class Gadget gad u => Correct gad u where
 
   -- | Error-correct a "noisy" encoding of an element (see 'encode'),
   -- returning the encoded element and the error vector.
-  correct :: Tagged gad [u] -> (u, [LiftOf u])
+  correct :: [u] -> (u, [LiftOf u])
 
 
 -- | Product ring: concatenate gadgets over component rings
 instance (Gadget gad a, Gadget gad b) => Gadget gad (a,b) where
 
-  gadget = (++) <$> (map (,zero) <$> gadget) <*> (map (zero,) <$> gadget)
+  gadget = (++) ((,zero) <$> gadget @gad @a) ((zero,) <$> gadget @gad @b)
 
 -- | Product ring: concatenate decompositions for component rings
 instance (Decompose gad a, Decompose gad b, DecompOf a ~ DecompOf b)
          => Decompose gad (a,b) where
 
   type DecompOf (a,b) = DecompOf a
-  decompose (a,b) = (++) <$> decompose a <*> decompose b
+  decompose (a,b) = (++) (decompose @gad a) (decompose @gad b)
 
 -- | Product ring
 instance (Correct gad a, Correct gad b,
@@ -107,18 +106,15 @@
     => Correct gad (a,b) where
 
   correct =
-    let gada = gadget :: Tagged gad [a]
-        gadb = gadget :: Tagged gad [b]
-        ka = length gada
-        qaval = toInteger $ proxy modulus (Proxy::Proxy a)
-        qbval = toInteger $ proxy modulus (Proxy::Proxy b)
+    let ka = length $ gadget @gad @a
+        qaval = toInteger $ modulus @a
+        qbval = toInteger $ modulus @b
         qamod = fromIntegral qaval
         qbmod = fromIntegral qbval
         qainv = recip qamod
         qbinv = recip qbmod
     in \tv ->
-        let v = untag tv
-            (wa,wb) = splitAt ka v
+        let (wa,wb) = splitAt ka tv
             (va,xb) = unzip $
                       (\(a,b) -> let x = toInteger $ lift b
                                  in (qbinv * (a - fromIntegral x), x)) <$> wa
@@ -127,10 +123,10 @@
                                  in (qainv * (b - fromIntegral x), x)) <$> wb
             (sa,ea) = (qbmod *) ***
                       zipWith (\x e -> x + qbval * toInteger e) xb $
-                      correct (tag va `asTypeOf` gada)
+                      correct @gad va
             (sb,eb) = (qamod *) ***
                       zipWith (\x e -> x + qaval * toInteger e) xa $
-                      correct (tag vb `asTypeOf` gadb)
+                      correct @gad vb
         in ((sa,sb), ea ++ eb)
 
 
diff --git a/Crypto/Lol/GaussRandom.hs b/Crypto/Lol/GaussRandom.hs
--- a/Crypto/Lol/GaussRandom.hs
+++ b/Crypto/Lol/GaussRandom.hs
@@ -3,7 +3,7 @@
 Description : Gaussian sampling.
 Copyright   : (c) Eric Crockett, 2011-2017
                   Chris Peikert, 2011-2017
-License     : GPL-2
+License     : GPL-3
 Maintainer  : ecrockett0@email.com
 Stability   : experimental
 Portability : POSIX
@@ -53,7 +53,7 @@
 {-# INLINABLE realGaussians #-}
 realGaussians var n
     | odd n = V.tail <$> realGaussians var (n+1) -- O(1) tail
-    | otherwise = (V.fromList . uncurry (++) . unzip) <$>
+    | otherwise = V.fromList . uncurry (++) . unzip <$>
                   replicateM (n `div` 2) (realGaussian var)
 
 -- | Execute an action repeatedly until its result fails to satisfy a predicate,
diff --git a/Crypto/Lol/PosBin.hs b/Crypto/Lol/PosBin.hs
--- a/Crypto/Lol/PosBin.hs
+++ b/Crypto/Lol/PosBin.hs
@@ -3,7 +3,7 @@
 Description : Type-level positive naturals in Peano and binary.
 Copyright   : (c) Eric Crockett, 2011-2017
                   Chris Peikert, 2011-2017
-License     : GPL-2
+License     : GPL-3
 Maintainer  : ecrockett0@email.com
 Stability   : experimental
 Portability : POSIX
@@ -27,6 +27,6 @@
 
 import Crypto.Lol.PosBinDefs
 
-$(mapM posDec [1..16])
+$(mapM posDec [1..64])
 
 $(mapM binDec [1..128])
diff --git a/Crypto/Lol/PosBinDefs.hs b/Crypto/Lol/PosBinDefs.hs
--- a/Crypto/Lol/PosBinDefs.hs
+++ b/Crypto/Lol/PosBinDefs.hs
@@ -3,7 +3,7 @@
 Description : Internal module.
 Copyright   : (c) Eric Crockett, 2011-2017
                   Chris Peikert, 2011-2017
-License     : GPL-2
+License     : GPL-3
 Maintainer  : ecrockett0@email.com
 Stability   : experimental
 Portability : POSIX
@@ -15,18 +15,21 @@
 template Haskell splices in the same module.
 -}
 
-{-# LANGUAGE ConstraintKinds      #-}
-{-# LANGUAGE DataKinds            #-}
-{-# LANGUAGE GADTs                #-}
-{-# LANGUAGE InstanceSigs         #-}
-{-# LANGUAGE KindSignatures       #-}
-{-# LANGUAGE PolyKinds            #-}
-{-# LANGUAGE RankNTypes           #-}
-{-# LANGUAGE RebindableSyntax     #-}
-{-# LANGUAGE ScopedTypeVariables  #-}
-{-# LANGUAGE TemplateHaskell      #-}
-{-# LANGUAGE TypeFamilies         #-}
-{-# LANGUAGE UndecidableInstances #-}
+{-# LANGUAGE ConstraintKinds       #-}
+{-# LANGUAGE DataKinds             #-}
+{-# LANGUAGE EmptyCase             #-}
+{-# LANGUAGE FlexibleInstances     #-}
+{-# LANGUAGE GADTs                 #-}
+{-# LANGUAGE InstanceSigs          #-}
+{-# LANGUAGE PolyKinds             #-}
+{-# LANGUAGE QuantifiedConstraints #-}
+{-# LANGUAGE RankNTypes            #-}
+{-# LANGUAGE RebindableSyntax      #-}
+{-# LANGUAGE ScopedTypeVariables   #-}
+{-# LANGUAGE StandaloneDeriving    #-}
+{-# LANGUAGE TemplateHaskell       #-}
+{-# LANGUAGE TypeFamilies          #-}
+{-# LANGUAGE UndecidableInstances  #-}
 
 {-# OPTIONS_GHC -fno-warn-duplicate-exports     #-}
 {-# OPTIONS_GHC -fno-warn-redundant-constraints #-}
@@ -60,20 +63,19 @@
                        deriving (Show, Eq)
 
             instance Ord Pos where
-              compare O O          = EQ
-              compare O (S _)      = LT
-              compare (S _) O      = GT
-              compare (S a) (S b)  = compare a b
+              compare O O         = EQ
+              compare O (S _)     = LT
+              compare (S _) O     = GT
+              compare (S a) (S b) = compare a b
 
             addPos :: Pos -> Pos -> Pos
-            addPos O b      = S b
-            addPos (S a) b  = S $ addPos a b
+            addPos O b     = S b
+            addPos (S a) b = S $ addPos a b
 
             subPos :: Pos -> Pos -> Pos
-            subPos (S a) O      = a
-            subPos (S a) (S b)  = subPos a b
-            subPos O _          = error "Invalid call to subPos: a <= b"
-
+            subPos (S a) O     = a
+            subPos (S a) (S b) = subPos a b
+            subPos O _         = error "Invalid call to subPos: a <= b"
            |]
 
 -- not promotable due to numeric output
@@ -81,7 +83,7 @@
 -- | Convert a 'Pos' to an integral type.
 {-# INLINABLE posToInt #-}
 posToInt :: ToInteger.C z => Pos -> z
-posToInt O = one
+posToInt O     = one
 posToInt (S a) = one + posToInt a
 
 singletons [d|
@@ -119,7 +121,7 @@
 -- | Convert a 'Bin' to an integral type.
 {-# INLINABLE binToInt #-}
 binToInt :: ToInteger.C z => Bin -> z
-binToInt B1 = one
+binToInt B1     = one
 binToInt (D0 a) = 2 * binToInt a
 binToInt (D1 a) = 1 + 2 * binToInt a
 
@@ -127,9 +129,9 @@
 intToBin :: ToInteger.C z => z -> Bin
 intToBin 1 = B1
 intToBin x | x > 0 =
-  case even x of
-    True -> D0 $ intToBin $ x `div` 2
-    False -> D1 $ intToBin $ x `div` 2
+             if even x
+             then D0 $ intToBin $ x `div` 2
+             else D1 $ intToBin $ x `div` 2
 
 -- | Kind-restricted synonym for 'SingI'.
 type PosC (p :: Pos) = SingI p
@@ -150,9 +152,9 @@
 -- | Reify a 'Bin' as a singleton.
 reifyBin :: Int -> (forall b . SBin b -> a) -> a
 reifyBin x _ | x < 1  = error $ "reifyBin: non-positive x = " ++ show x
-reifyBin 1 k          = k SB1
+reifyBin 1 k = k SB1
 reifyBin x k | even x = reifyBin (x `div` 2) (k . SD0)
-reifyBin x k          = reifyBin (x `div` 2) (k . SD1)
+reifyBin x k = reifyBin (x `div` 2) (k . SD1)
 
 -- | Reify a 'Bin' for a 'SingI' constraint.
 reifyBinI :: Int -> (forall b proxy . BinC b => proxy b -> a) -> a
@@ -175,7 +177,7 @@
                     (0,1) -> conT 'B1
                     (q,0) -> conT 'D0 `appT` binType q
                     (q,1) -> conT 'D1 `appT` binType q
-                    _ -> fail "internal error in PosBinTH.bin"
+                    _     -> fail "internal error in PosBinTH.bin"
 
 posDec, binDec :: Int -> DecQ
 -- | Template Haskell splice that defines the 'Pos' type synonym @P@\(n\).
diff --git a/Crypto/Lol/Prelude.hs b/Crypto/Lol/Prelude.hs
--- a/Crypto/Lol/Prelude.hs
+++ b/Crypto/Lol/Prelude.hs
@@ -3,7 +3,7 @@
 Description : Alternate Prelude.
 Copyright   : (c) Eric Crockett, 2011-2017
                   Chris Peikert, 2011-2017
-License     : GPL-2
+License     : GPL-3
 Maintainer  : ecrockett0@email.com
 Stability   : experimental
 Portability : POSIX
@@ -17,6 +17,7 @@
 assorted utility functions.
 -}
 
+{-# LANGUAGE AllowAmbiguousTypes        #-}
 {-# LANGUAGE ConstraintKinds            #-}
 {-# LANGUAGE DataKinds                  #-}
 {-# LANGUAGE FlexibleContexts           #-}
@@ -30,6 +31,7 @@
 {-# LANGUAGE ScopedTypeVariables        #-}
 {-# LANGUAGE StandaloneDeriving         #-}
 {-# LANGUAGE TemplateHaskell            #-}
+{-# LANGUAGE TypeApplications           #-}
 {-# LANGUAGE TypeFamilies               #-}
 {-# LANGUAGE TypeOperators              #-}
 {-# LANGUAGE UndecidableInstances       #-}
@@ -56,8 +58,9 @@
 ) where
 
 import Crypto.Lol.Factored
-import Crypto.Lol.Types.Unsafe.Complex (Complex(), roundComplex, cis, real, imag, fromReal)
 import Crypto.Lol.Types.Numeric
+import Crypto.Lol.Types.Unsafe.Complex (Complex, cis, fromReal, imag, real,
+                                        roundComplex)
 
 import Algebra.Field          as Field (C)
 import Algebra.IntegralDomain as IntegralDomain (C)
@@ -67,7 +70,7 @@
 import Control.Arrow
 import Control.DeepSeq
 import Control.Monad.Identity
-import Control.Monad.Random hiding (lift)
+import Control.Monad.Random      hiding (lift)
 import Data.Coerce
 import Data.Default
 import Data.Functor.Trans.Tagged
@@ -99,14 +102,14 @@
 -- | Represents a quotient group modulo some integer.
 class (ToInteger (ModRep a), Additive a) => Mod a where
   type ModRep a
-  modulus :: Tagged a (ModRep a)
+  modulus :: ModRep a
 
 -- | Represents that @a@ is a subgroup of @b@.
 class (Additive a, Additive b) => Subgroup a b where
   fromSubgroup :: a -> b
 
 -- | Represents that @b@ is a quotient group of @a@.
-class (Additive a, Additive b) => Reduce a b where
+class Reduce a b where
   reduce :: a -> b
 
 -- | Represents that @b@ can be lifted to a "short" @a@ congruent to @b@.
@@ -142,21 +145,21 @@
 
 -- | A default implementation of rescaling for 'Mod' types.
 rescaleMod :: forall a b .
-              (Mod a, Mod b, (ModRep a) ~ (ModRep b),
+              (Mod a, Mod b, ModRep a ~ ModRep b,
                Lift a (ModRep b), Ring b)
               => a -> b
 {-# INLINABLE rescaleMod #-}
 rescaleMod =
-    let qval = proxy modulus (Proxy :: Proxy a)
-        q'val = proxy modulus (Proxy :: Proxy b)
+    let qval  = modulus @a
+        q'val = modulus @b
     in \x -> let (quot',_) = divModCent (q'val * lift x) qval
              in fromIntegral quot'
 
--- | Deterministically round to a nearby value in the desired coset.
+-- | Deterministically round to the nearest value in the desired coset.
 roundCoset :: forall zp z r .
               (Mod zp, z ~ ModRep zp, Lift zp z, RealField r) => zp -> r -> z
 {-# INLINABLE roundCoset #-}
-roundCoset = let pval = proxy modulus (Proxy::Proxy zp)
+roundCoset = let pval = modulus @zp
              in \ zp x -> let rep = lift zp
                           in rep + roundMult pval (x - fromIntegral rep)
 
@@ -171,8 +174,8 @@
 
   {-# INLINABLE lift #-}
   lift (a,b) =
-    let moda = toInteger $ proxy modulus (Proxy::Proxy a)
-        modb = toInteger $ proxy modulus (Proxy::Proxy b)
+    let moda = toInteger $ modulus @a
+        modb = toInteger $ modulus @b
         q = moda * modb
         ainv = fromMaybe (error "Lift' (a,b): moduli not coprime") $ moda `modinv` modb
         lifta = toInteger $ lift a
@@ -211,8 +214,7 @@
 instance (Mod a, Mod b) => Mod (a,b) where
   type ModRep (a,b) = Integer
 
-  modulus = tag $ fromIntegral (proxy modulus (Proxy::Proxy a)) *
-            fromIntegral (proxy modulus (Proxy::Proxy b))
+  modulus = fromIntegral (modulus @a) * fromIntegral (modulus @b)
   {-# INLINABLE modulus #-}
 
 -- | Reduce into product ring.
@@ -220,30 +222,51 @@
   reduce x = (reduce x, reduce x)
   {-# INLINABLE reduce #-}
 
+
+
+
 -- | Rescale a product ring of \(\Z_q\)s
 instance (Mod a, Field b, Lift a (ModRep a), Reduce (LiftOf a) b)
          => Rescale (a,b) b where
-  rescale = let q1val = proxy modulus (Proxy::Proxy a)
+  rescale = let q1val = modulus @a
                 q1inv = recip $ reduce q1val
             in \(x1,x2) -> q1inv * (x2 - reduce (lift x1))
   {-# INLINABLE rescale #-}
 
+-- | Rescale down by a product ring of two \(\Z_q\)s
+instance (Rescale (a,(b,c)) (b,c), Rescale (b,c) c,
+          Additive a, Additive c)
+         => Rescale (a,(b,c)) c where
+  rescale = (rescale :: (b,c) -> c) . rescale
+  {-# INLINABLE rescale #-}
+
+-- | Rescale down by a product ring of three \(\Z_q\)s
+instance (Rescale (a,(b,(c,d))) (b,(c,d)), Rescale (b,(c,d)) d, Additive a)
+  => Rescale (a,(b,(c,d))) d where
+  rescale = (rescale :: (b,(c,d)) -> d) . rescale
+  {-# INLINABLE rescale #-}
+
+-- | Rescale down by a product ring of four \(\Z_q\)s
+instance (Rescale (a,(b,(c,(d,e)))) (b,(c,(d,e))), Rescale (b,(c,(d,e))) e, Additive a)
+  => Rescale (a,(b,(c,(d,e)))) e where
+  rescale = (rescale :: (b,(c,(d,e))) -> e) . rescale
+  {-# INLINABLE rescale #-}
+
+-- | Rescale down by a product ring of five \(\Z_q\)s
+instance (Rescale (a,(b,(c,(d,(e,f))))) (b,(c,(d,(e,f)))), Rescale (b,(c,(d,(e,f)))) f, Additive a)
+  => Rescale (a,(b,(c,(d,(e,f))))) f where
+  rescale = (rescale :: (b,(c,(d,(e,f)))) -> f) . rescale
+  {-# INLINABLE rescale #-}
+
 -- | Rescale a product ring of \(\Z_q\)s
 instance (Mod b, Field a, Lift b (ModRep b), Reduce (LiftOf b) a)
          => Rescale (a,b) a where
-  rescale = let q2val = proxy modulus (Proxy::Proxy b)
+  rescale = let q2val = modulus @b
                 q2inv = recip $ reduce q2val
             in \(x1,x2) -> q2inv * (x1 - reduce (lift x2))
   {-# INLINABLE rescale #-}
 
 -- | Rescale a (multi-)product ring of \(\Z_q\)s
-instance (Rescale (a,(b,c)) (b,c), Rescale (b,c) c,
-          Additive a, Additive c)
-         => Rescale (a,(b,c)) c where
-  rescale = (rescale :: (b,c) -> c) . rescale
-  {-# INLINABLE rescale #-}
-
--- | Rescale a (multi-)product ring of \(\Z_q\)s
 instance (Rescale ((a,b),c) (a,b), Rescale (a,b) a,
           Additive a, Additive c)
          => Rescale ((a,b),c) a where
@@ -253,15 +276,37 @@
 -- | Rescale /up/ to a product ring of \(\Z_q\)s
 instance (Ring a, Mod b, Reduce (ModRep b) a) => Rescale a (a,b) where
   -- multiply by q2
-  rescale = let q2val = reduce $ proxy modulus (Proxy::Proxy b)
+  rescale = let q2val = reduce $ modulus @b
             in \x -> (q2val * x, zero)
   {-# INLINABLE rescale #-}
 
 -- | Rescale /up/ to a product ring of \(\Z_q\)s
 instance (Ring b, Mod a, Reduce (ModRep a) b) => Rescale b (a,b) where
   -- multiply by q1
-  rescale = let q1val = reduce $ proxy modulus (Proxy::Proxy a)
+  rescale = let q1val = reduce $ modulus @a
             in \x -> (zero, q1val * x)
+  {-# INLINABLE rescale #-}
+
+-- | Rescale up by a product of two rings
+instance (Additive a, Rescale c (b,c), Rescale (b,c) (a,(b,c))) => Rescale c (a,(b,c)) where
+  rescale x = rescale (rescale x :: (b,c))
+  {-# INLINABLE rescale #-}
+
+-- | Rescale up by a product of three rings
+instance (Additive a, Rescale d (b,(c,d)), Rescale (b,(c,d)) (a,(b,(c,d)))) => Rescale d (a,(b,(c,d))) where
+  rescale x = rescale (rescale x :: (b,(c,d)))
+  {-# INLINABLE rescale #-}
+
+-- | Rescale up by a product of four rings
+instance (Additive a, Rescale e (b,(c,(d,e))), Rescale (b,(c,(d,e))) (a,(b,(c,(d,e)))))
+  => Rescale e (a,(b,(c,(d,e)))) where
+  rescale x = rescale (rescale x :: (b,(c,(d,e))))
+  {-# INLINABLE rescale #-}
+
+-- | Rescale up by a product of five rings
+instance (Additive a, Rescale f (b,(c,(d,(e,f)))), Rescale (b,(c,(d,(e,f)))) (a,(b,(c,(d,(e,f))))))
+  => Rescale f (a,(b,(c,(d,(e,f))))) where
+  rescale x = rescale (rescale x :: (b,(c,(d,(e,f)))))
   {-# INLINABLE rescale #-}
 
 -- | Encode for a product ring
diff --git a/Crypto/Lol/RLWE/Continuous.hs b/Crypto/Lol/RLWE/Continuous.hs
--- a/Crypto/Lol/RLWE/Continuous.hs
+++ b/Crypto/Lol/RLWE/Continuous.hs
@@ -2,9 +2,9 @@
 Module      : Crypto.Lol.RLWE.Continuous
 Description : Functions and types for working with continuous ring-LWE samples.
 Copyright   : (c) Eric Crockett, 2011-2017
-                  Chris Peikert, 2011-2017
-License     : GPL-2
-Maintainer  : ecrockett0@email.com
+                  Chris Peikert, 2011-2018
+License     : GPL-3
+Maintainer  : ecrockett0@gmail.com
 Stability   : experimental
 Portability : POSIX
 
@@ -14,71 +14,79 @@
 Functions and types for working with continuous ring-LWE samples.
 -}
 
-{-# LANGUAGE ConstraintKinds       #-}
-{-# LANGUAGE FlexibleContexts      #-}
-{-# LANGUAGE MultiParamTypeClasses #-}
-{-# LANGUAGE RebindableSyntax      #-}
-{-# LANGUAGE ScopedTypeVariables   #-}
+{-# LANGUAGE AllowAmbiguousTypes #-}
+{-# LANGUAGE ConstraintKinds     #-}
+{-# LANGUAGE FlexibleContexts    #-}
+{-# LANGUAGE RebindableSyntax    #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+{-# LANGUAGE TypeApplications    #-}
+{-# LANGUAGE TypeFamilies        #-}
 
 module Crypto.Lol.RLWE.Continuous where
 
-import Crypto.Lol.Cyclotomic.Cyc    as C
-import Crypto.Lol.Cyclotomic.Tensor (TElt)
-import Crypto.Lol.Cyclotomic.UCyc   as U
-import Crypto.Lol.Prelude
+import Crypto.Lol
 
-import Control.Applicative
-import Control.Monad.Random hiding (lift)
+import Control.Monad.Random
 
--- | A continuous RLWE sample \( (a,b) \in R_q \times K/(qR)\).  (The
--- second component is a 'UCyc' because the base type @rrq@
--- representing \(\R/(q\Z)\), is an additive group
--- but not a ring, so we can't usefully work with a 'Cyc' over it.)
-type Sample t m zq rrq = (Cyc t m zq, UCyc t m D rrq)
+-- | A continuous RLWE sample \( (a,b) \in R_q \times K/(qR) \).  The
+-- base type @rrq@ represents \( \R/q\Z \), the additive group of
+-- reals modulo \( q \).
+type Sample cm zq rrq = (cm zq, cm rrq)
 
 -- | Common constraints for working with continuous RLWE.
-type RLWECtx t m zq rrq =
-  (Fact m, Ring zq, CElt t zq, Subgroup zq rrq, Lift' rrq,
-   TElt t rrq, TElt t (LiftOf rrq))
+type RLWECtx cm zq rrq =
+  (Cyclotomic (cm zq), Ring (cm zq), Additive (cm rrq),
+   Subgroup zq rrq, FunctorCyc cm zq rrq)
 
 -- | A continuous RLWE sample with the given scaled variance and secret.
-sample :: forall rnd v t m zq rrq .
-  (RLWECtx t m zq rrq, Random zq, Random (LiftOf rrq), OrdFloat (LiftOf rrq),
-   MonadRandom rnd, ToRational v)
-  => v -> Cyc t m zq -> rnd (Sample t m zq rrq)
+sample :: forall rnd v cm zq rrq .
+  (RLWECtx cm zq rrq, Random (cm zq), GaussianCyc (cm (LiftOf rrq)),
+   Reduce (cm (LiftOf rrq)) (cm rrq), MonadRandom rnd, ToRational v)
+  => v -> cm zq -> rnd (Sample cm zq rrq)
 {-# INLINABLE sample #-}
 sample svar s = let s' = adviseCRT s in do
   a <- getRandom
-  e :: UCyc t m D (LiftOf rrq) <- U.tGaussian svar
-  let as = fmapDec fromSubgroup $ uncycDec $ a * s' :: UCyc t m D rrq
+  e :: cm (LiftOf rrq) <- tweakedGaussian svar
+  let as = fmapDec fromSubgroup (a * s')
   return (a, as + reduce e)
 
 -- | The error term of an RLWE sample, given the purported secret.
-errorTerm :: (RLWECtx t m zq rrq)
-             => Cyc t m zq -> Sample t m zq rrq -> UCyc t m D (LiftOf rrq)
+errorTerm :: (RLWECtx cm zq rrq, LiftCyc (cm rrq))
+          => cm zq -> Sample cm zq rrq -> LiftOf (cm rrq)
 {-# INLINABLE errorTerm #-}
 errorTerm s = let s' = adviseCRT s
-              in \(a,b) -> lift $ b - fmapDec fromSubgroup (uncycDec $ a * s')
+              in \(a,b) -> liftDec $ b - fmapDec fromSubgroup (a * s')
 
 -- | The 'gSqNorm' of the error term of an RLWE sample, given the
 -- purported secret.
-errorGSqNorm :: (RLWECtx t m zq rrq, Ring (LiftOf rrq))
-                => Cyc t m zq -> Sample t m zq rrq -> LiftOf rrq
+errorGSqNorm :: (RLWECtx cm zq rrq, GSqNormCyc cm (LiftOf rrq),
+                 LiftCyc (cm rrq), LiftOf (cm rrq) ~ cm (LiftOf rrq))
+             => cm zq -> Sample cm zq rrq -> LiftOf rrq
 {-# INLINABLE errorGSqNorm #-}
-errorGSqNorm s = U.gSqNorm . errorTerm s
+errorGSqNorm = fmap gSqNorm . errorTerm
 
--- | A bound such that the 'gSqNorm' of a continuous error generated
--- by 'tGaussian' with scaled variance \(v\) (over the \(m\)th cyclotomic
--- field) is less than the bound except with probability approximately
--- \(\epsilon\).
-errorBound :: (Ord v, Transcendental v, Fact m)
-              => v              -- ^ the scaled variance
-              -> v              -- ^ \(\epsilon\)
-              -> Tagged m v
-errorBound v eps = do
-  n <- fromIntegral <$> totientFact
-  mhat <- fromIntegral <$> valueHatFact
-  let stabilize x =
+-- | Gives \( c^2 \) such that the Gaussian mass outside a ball of
+-- radius \( c \) is approximately \( \epsilon \) (i.e., the Gaussian
+-- measure for \( \| x^2 \| > c^2 \cdot n \) is \( \approx \epsilon
+-- \).)
+tailGaussian :: forall m v . (Fact m, Ord v, Transcendental v) => v -> v
+tailGaussian eps =
+  let n = fromIntegral $ totientFact @m
+      stabilize x =
         let x' = (1/2 + log (2 * pi * x)/2 - log eps/n)/pi
         in if x'-x < 0.0001 then x' else stabilize x'
-  return $ mhat * n * v * stabilize (1/(2*pi))
+  in stabilize $ 1/(2*pi)
+
+-- | A bound such that the 'gSqNorm' of a continuous error generated
+-- by 'tweakedGaussian' with scaled variance \(v\) (over the \(m\)th
+-- cyclotomic field) is less than the bound except with probability
+-- approximately \( \varepsilon \).
+errorBound :: forall m v . (Fact m, Ord v, Transcendental v)
+           => v              -- ^ the scaled variance
+           -> v              -- ^ \( \varepsilon \)
+           -> v
+errorBound v eps =
+  let n    = fromIntegral $ totientFact @m
+      mhat = fromIntegral $ valueHatFact @m
+      csq  = tailGaussian @m eps
+  in mhat * n * v * csq
diff --git a/Crypto/Lol/RLWE/Discrete.hs b/Crypto/Lol/RLWE/Discrete.hs
--- a/Crypto/Lol/RLWE/Discrete.hs
+++ b/Crypto/Lol/RLWE/Discrete.hs
@@ -2,76 +2,76 @@
 Module      : Crypto.Lol.RLWE.Discrete
 Description : Functions and types for working with discretized ring-LWE samples.
 Copyright   : (c) Eric Crockett, 2011-2017
-                  Chris Peikert, 2011-2017
-License     : GPL-2
-Maintainer  : ecrockett0@email.com
+                  Chris Peikert, 2011-2018
+License     : GPL-3
+Maintainer  : ecrockett0@gmail.com
 Stability   : experimental
 Portability : POSIX
 
 Functions and types for working with discretized ring-LWE samples.
 -}
 
+{-# LANGUAGE AllowAmbiguousTypes   #-}
 {-# LANGUAGE ConstraintKinds       #-}
 {-# LANGUAGE FlexibleContexts      #-}
 {-# LANGUAGE MultiParamTypeClasses #-}
 {-# LANGUAGE RebindableSyntax      #-}
 {-# LANGUAGE ScopedTypeVariables   #-}
+{-# LANGUAGE TypeApplications      #-}
+{-# LANGUAGE TypeFamilies          #-}
 
 module Crypto.Lol.RLWE.Discrete where
 
-import Crypto.Lol.Cyclotomic.Cyc
-import Crypto.Lol.Prelude
-import Crypto.Lol.RLWE.Continuous as C (errorBound)
+import Crypto.Lol
+import Crypto.Lol.RLWE.Continuous as C (errorBound, tailGaussian)
 
-import Control.Applicative
 import Control.Monad.Random
 
--- | A discrete RLWE sample \( (a,b) \in R_q \times R_q\).
-type Sample t m zq = (Cyc t m zq, Cyc t m zq)
+-- | A discrete RLWE sample \( (a,b) \in R_q \times R_q \).
+type Sample cm zq = (cm zq, cm zq)
 
 -- | Common constraints for working with discrete RLWE.
-type RLWECtx t m zq =
-  (Fact m, Ring zq, Lift' zq, ToInteger (LiftOf zq),
-   CElt t zq, CElt t (LiftOf zq))
+type RLWECtx cm zq = (Cyclotomic (cm zq), Ring (cm zq), Reduce (cm (LiftOf zq)) (cm zq))
 
 -- | A discrete RLWE sample with the given scaled variance and secret.
-sample :: forall rnd v t m zq .
-  (RLWECtx t m zq, Random zq, MonadRandom rnd, ToRational v)
-  => v -> Cyc t m zq -> rnd (Sample t m zq)
+sample :: forall rnd v cm zq .
+  (RLWECtx cm zq, Random (cm zq), RoundedGaussianCyc (cm (LiftOf zq)),
+   MonadRandom rnd, ToRational v)
+  => v -> cm zq -> rnd (Sample cm zq)
 {-# INLINABLE sample #-}
 sample svar s = let s' = adviseCRT s in do
   a <- getRandom
-  e :: Cyc t m (LiftOf zq) <- errorRounded svar
+  e :: cm (LiftOf zq) <- roundedGaussian svar
   return (a, a * s' + reduce e)
 
 -- | The error term of an RLWE sample, given the purported secret.
-errorTerm :: (RLWECtx t m zq)
-             => Cyc t m zq -> Sample t m zq -> Cyc t m (LiftOf zq)
+errorTerm :: (RLWECtx cm zq, LiftCyc (cm zq))
+          => cm zq -> Sample cm zq -> LiftOf (cm zq)
 {-# INLINABLE errorTerm #-}
 errorTerm s = let s' = adviseCRT s
               in \(a,b) -> liftDec $ b - a * s'
 
 -- | The 'gSqNorm' of the error term of an RLWE sample, given the
 -- purported secret.
-errorGSqNorm :: (RLWECtx t m zq)
-                => Cyc t m zq -> Sample t m zq -> LiftOf zq
+errorGSqNorm :: (RLWECtx cm zq, GSqNormCyc cm (LiftOf zq),
+                 LiftCyc (cm zq), LiftOf (cm zq) ~ cm (LiftOf zq))
+             => cm zq -> Sample cm zq -> LiftOf zq
 {-# INLINABLE errorGSqNorm #-}
 errorGSqNorm s = gSqNorm . errorTerm s
 
 -- | A bound such that the 'gSqNorm' of a discretized error term
--- generated by 'errorRounded' with scaled variance \(v\)
+-- generated by 'roundedGaussian' with scaled variance \(v\)
 -- (over the \(m\)th cyclotomic field) is less than the
 -- bound except with probability approximately \(\epsilon\).
-errorBound :: (RealRing v, Transcendental v, Fact m)
+errorBound :: forall m v . (Fact m, RealRing v, Transcendental v)
               => v              -- ^ the scaled variance
               -> v              -- ^ \(\epsilon\)
-              -> Tagged m Int64
-errorBound v eps = do
-  n <- fromIntegral <$> totientFact
-  cont <- C.errorBound v eps -- continuous bound
-  ps <- filter (/= 2) . fmap fst <$> ppsFact -- odd primes dividing m
-  let stabilize x =
-        let x' = (1/2 + log(2 * pi * x)/2 - log eps)/pi
-        in if x'-x < 0.0001 then x' else stabilize x'
-  return $ ceiling $ (2 ^ length ps) * n * stabilize (1/(2*pi)) + cont
-
+              -> Int64
+errorBound =
+  let n = fromIntegral $ totientFact @m
+      ps = filter (/= 2) . fmap fst $ ppsFact @m -- odd primes dividing m
+  in \v eps -> let
+    bsq = C.errorBound @m v eps -- continuous bound
+    csq = C.tailGaussian @m eps
+    fsq = (2 ^ length ps) * n * csq
+  in ceiling $ fsq + bsq + 2 * sqrt bsq * sqrt fsq
diff --git a/Crypto/Lol/RLWE/RLWR.hs b/Crypto/Lol/RLWE/RLWR.hs
--- a/Crypto/Lol/RLWE/RLWR.hs
+++ b/Crypto/Lol/RLWE/RLWR.hs
@@ -2,9 +2,9 @@
 Module      : Crypto.Lol.RLWE.RLWR
 Description : Functions and types for working with ring-LWR samples.
 Copyright   : (c) Eric Crockett, 2011-2017
-                  Chris Peikert, 2011-2017
-License     : GPL-2
-Maintainer  : ecrockett0@email.com
+                  Chris Peikert, 2011-2018
+License     : GPL-3
+Maintainer  : ecrockett0@gmail.com
 Stability   : experimental
 Portability : POSIX
 
@@ -13,9 +13,7 @@
 
 {-# LANGUAGE ConstraintKinds       #-}
 {-# LANGUAGE FlexibleContexts      #-}
-{-# LANGUAGE MultiParamTypeClasses #-}
 {-# LANGUAGE NoImplicitPrelude     #-}
-{-# LANGUAGE ScopedTypeVariables   #-}
 
 module Crypto.Lol.RLWE.RLWR where
 
@@ -24,22 +22,22 @@
 import Control.Monad.Random
 
 -- | An RLWR sample \( (a,b) \in R_q \times R_p\).
-type Sample t m zq zp = (Cyc t m zq, Cyc t m zp)
+type Sample cm zq zp = (cm zq, cm zp)
 
 -- | Common constraints for working with RLWR.
-type RLWRCtx t m zq zp =
-  (Fact m, Ring zq, RescaleCyc (Cyc t) zq zp, CElt t zq, CElt t zp)
+type RLWRCtx cm zq zp =
+  (Cyclotomic (cm zq), Random (cm zq), Ring (cm zq), RescaleCyc cm zq zp)
 
 -- | An RLWR sample with the given secret.
-sample :: (RLWRCtx t m zq zp, Random zq, MonadRandom rnd)
-          => Cyc t m zq -> rnd (Sample t m zq zp)
+sample :: (RLWRCtx cm zq zp, MonadRandom rnd)
+          => cm zq -> rnd (Sample cm zq zp)
 sample s = let s' = adviseCRT s in do
   a <- getRandom
   return (a, roundedProd s' a)
 
 -- | The \(b\) component of an RLWR sample for secret \(s\) and given \(a\),
 -- produced by rounding \(a\cdot s\) in the decoding basis.
-roundedProd :: (RLWRCtx t m zq zp) => Cyc t m zq -> Cyc t m zq -> Cyc t m zp
+roundedProd :: (RLWRCtx cm zq zp) => cm zq -> cm zq -> cm zp
 {-# INLINABLE roundedProd #-}
 roundedProd s = let s' = adviseCRT s in \a -> rescaleCyc Dec $ a * s'
 
diff --git a/Crypto/Lol/Reflects.hs b/Crypto/Lol/Reflects.hs
--- a/Crypto/Lol/Reflects.hs
+++ b/Crypto/Lol/Reflects.hs
@@ -3,7 +3,7 @@
 Description : Generic interface for reflecting types to values.
 Copyright   : (c) Eric Crockett, 2011-2017
                   Chris Peikert, 2011-2017
-License     : GPL-2
+License     : GPL-3
 Maintainer  : ecrockett0@email.com
 Stability   : experimental
 Portability : POSIX
@@ -11,31 +11,31 @@
 Generic interface for reflecting types to values.
 -}
 
+{-# LANGUAGE AllowAmbiguousTypes   #-}
 {-# LANGUAGE DataKinds             #-}
 {-# LANGUAGE FlexibleContexts      #-}
 {-# LANGUAGE FlexibleInstances     #-}
-{-# LANGUAGE KindSignatures        #-}
 {-# LANGUAGE MultiParamTypeClasses #-}
 {-# LANGUAGE NoImplicitPrelude     #-}
 {-# LANGUAGE PolyKinds             #-}
 {-# LANGUAGE ScopedTypeVariables   #-}
+{-# LANGUAGE TypeApplications      #-}
 {-# LANGUAGE UndecidableInstances  #-}
 
 module Crypto.Lol.Reflects
-( Reflects(..),
+( Reflects(..)
 ) where
 
+import Algebra.Ring      as Ring
 import Algebra.ToInteger as ToInteger
-import Algebra.Ring as Ring
 import NumericPrelude
 
 import Crypto.Lol.Factored
 
-import Control.Applicative
-import Data.Functor.Trans.Tagged
 import Data.Proxy
 import Data.Reflection
-import GHC.TypeLits              as TL
+import Data.Singletons
+import GHC.TypeLits    as TL
 
 -- | Reflection without fundep, and with tagged value. Intended only
 -- for low-level code; build specialized wrappers around it for
@@ -43,30 +43,26 @@
 
 class Reflects a i where
   -- | Reflect the value assiated with the type @a@.
-  value :: Tagged a i
+  value :: i
 
 instance (KnownNat a, Ring.C i) => Reflects (a :: TL.Nat) i where
-  value = tag $ fromIntegral $ natVal (Proxy::Proxy a)
-
-{-
+  value = fromIntegral $ natVal (Proxy::Proxy a)
 
 instance (PosC a, ToInteger.C i) => Reflects a i where
-  value = tag $ posToInt $ fromSing (sing :: Sing a)
+  value = posToInt $ fromSing (sing :: Sing a)
 
 instance (BinC a, ToInteger.C i) => Reflects a i where
-  value = tag $ binToInt $ fromSing (sing :: Sing a)
-
--}
+  value = binToInt $ fromSing (sing :: Sing a)
 
 instance (Prime p, ToInteger.C i) => Reflects p i where
-  value = fromIntegral <$> valuePrime
+  value = fromIntegral $ valuePrime @p
 
 instance (PPow pp, ToInteger.C i) => Reflects pp i where
-  value = fromIntegral <$> valuePPow
+  value = fromIntegral $ valuePPow @pp
 
 instance (Fact m, ToInteger.C i) => Reflects m i where
-  value = fromIntegral <$> valueFact
+  value = fromIntegral $ valueFact @m
 
 instance (Reifies q i, ToInteger.C i, Ring.C r)
   => Reflects (q :: *) r where
-  value = tag $ fromIntegral $ reflect (Proxy::Proxy q)
+  value = fromIntegral $ reflect (Proxy::Proxy q)
diff --git a/Crypto/Lol/Tests.hs b/Crypto/Lol/Tests.hs
new file mode 100644
--- /dev/null
+++ b/Crypto/Lol/Tests.hs
@@ -0,0 +1,37 @@
+{-|
+Module      : Crypto.Lol.Tests
+Description : Infrastructure for benchmarking lol.
+Copyright   : (c) Eric Crockett, 2011-2017
+                  Chris Peikert, 2011-2017
+License     : GPL-3
+Maintainer  : ecrockett0@email.com
+Stability   : experimental
+Portability : POSIX
+
+  \( \def\C{\mathbb{C}} \)
+
+Tests for individual layers of the Lol stack ('Crypto.Lol.Cyclotomic.Tensor',
+'Crypto.Lol.Cyclotomic.UCyc', Crypto.Lol.Cyclotomic.Cyc'), plus
+default parameters and helper functions for displaying results.
+-}
+
+-- EAC: See https://github.com/haskell/haddock/issues/563
+module Crypto.Lol.Tests
+(
+-- * Default parameters for tests
+ module Crypto.Lol.Tests.Default
+-- * Tests for different layers of Lol
+,module Crypto.Lol.Tests.TensorTests
+,module Crypto.Lol.Tests.CycTests
+,module Crypto.Lol.Tests.ZqTests
+-- * Utilities for creating tests
+,module Crypto.Lol.Utils.Tests
+-- * Utilities for showing benchmark results
+,module Crypto.Lol.Utils.ShowType) where
+
+import Crypto.Lol.Tests.Default
+import Crypto.Lol.Tests.TensorTests
+import Crypto.Lol.Tests.CycTests
+import Crypto.Lol.Tests.ZqTests
+import Crypto.Lol.Utils.Tests
+import Crypto.Lol.Utils.ShowType
diff --git a/Crypto/Lol/Tests/CycTests.hs b/Crypto/Lol/Tests/CycTests.hs
new file mode 100644
--- /dev/null
+++ b/Crypto/Lol/Tests/CycTests.hs
@@ -0,0 +1,81 @@
+{-|
+Module      : Crypto.Lol.Tests.CycTests
+Description : Tests for the 'Cyc' interface.
+Copyright   : (c) Eric Crockett, 2011-2017
+                  Chris Peikert, 2011-2017
+License     : GPL-3
+Maintainer  : ecrockett0@email.com
+Stability   : experimental
+Portability : POSIX
+
+Tests for the 'Cyc' interface.
+-}
+
+{-# LANGUAGE DataKinds             #-}
+{-# LANGUAGE FlexibleContexts      #-}
+{-# LANGUAGE NoImplicitPrelude     #-}
+{-# LANGUAGE PartialTypeSignatures #-}
+{-# LANGUAGE PolyKinds             #-}
+{-# LANGUAGE ScopedTypeVariables   #-}
+{-# LANGUAGE TypeFamilies          #-}
+{-# LANGUAGE TypeOperators         #-}
+
+{-# OPTIONS_GHC -fno-warn-partial-type-signatures #-}
+
+module Crypto.Lol.Tests.CycTests (cycTests1, cycTests2) where
+
+import Control.Applicative
+import Control.Monad       (join, liftM2)
+
+import Crypto.Lol
+
+import Crypto.Lol.Utils.ShowType
+import Crypto.Lol.Utils.Tests    (Gen, Test, testGroup, testWithGen,
+                                  testWithoutGen)
+
+-- | Tests for single-index 'Cyc' operations. There must be a CRT basis for \(O_m\) over @r@.
+cycTests1 :: forall t m r . (Fact m, _) => Gen (Cyc t m r) -> Test
+cycTests1 cycGen =
+  let ptmr = Proxy :: Proxy '(t,m,r) in
+  testGroup (showType ptmr) $ ($ cycGen) <$> [
+   testWithGen "mulGPow" prop_mulgPow,
+   testWithGen "mulGDec" prop_mulgDec,
+   testWithGen "mulGCRT" prop_mulgCRT]
+
+-- | Tests for inter-ring 'Cyc' operations. There must be a CRT basis for \(O_{m'}\) over @r@.
+cycTests2 :: forall t m m' r . _ => Proxy '(t,m,m',r) -> Gen (Cyc t m' r) -> Test
+cycTests2 _ cycGen =
+  let ptmmr = Proxy::Proxy '(t,m,m',r)
+  in testGroup (showType ptmmr) [
+      testWithoutGen "crtSet" (prop_crtSet_pairs ptmmr),
+      testWithGen "coeffsPow" (prop_coeffsPow ptmmr) cycGen]
+
+prop_mulgPow :: _ => Cyc t m r -> Bool
+prop_mulgPow x =
+  let y = advisePow x
+  in y == fromJust' "prop_mulgPow failed divisibility!" (divG $ mulG y)
+
+prop_mulgDec :: _ => Cyc t m r -> Bool
+prop_mulgDec x =
+  let y = adviseDec x in
+  y == fromJust' "prop_mulgDec failed divisibility!" (divG $ mulG y)
+
+prop_mulgCRT :: _ => Cyc t m r -> Bool
+prop_mulgCRT x =
+  let y = adviseCRT x in
+  y == fromJust' "prop_mulgCRT failed divisibility!" (divG $ mulG y)
+
+prop_coeffsPow :: forall t m m' r . _ => Proxy '(t,m,m',r) -> Cyc t m' r -> Bool
+prop_coeffsPow _ x =
+  let xs = map embed (coeffsPow x :: [Cyc t m r])
+      bs = proxy powBasis (Proxy::Proxy m)
+  in sum (zipWith (*) xs bs) == x
+
+-- verifies that CRT set elements satisfy c_i * c_j = delta_ij * c_i
+-- necessary (but not sufficient) condition
+prop_crtSet_pairs :: forall (t :: Factored -> * -> *) m (m' :: Factored) (r :: *) . _
+                  => Proxy '(t,m,m',r) -> Bool
+prop_crtSet_pairs _ =
+  let crtset = proxy crtSet (Proxy::Proxy m) :: [Cyc t m' r]
+      pairs = join (liftM2 (,)) crtset
+  in all (\(a,b) -> if a == b then a*b == a else a*b == zero) pairs
diff --git a/Crypto/Lol/Tests/Default.hs b/Crypto/Lol/Tests/Default.hs
new file mode 100644
--- /dev/null
+++ b/Crypto/Lol/Tests/Default.hs
@@ -0,0 +1,347 @@
+{-|
+Module      : Crypto.Lol.Tests.Default
+Description : High-level tensor tests.
+Copyright   : (c) Eric Crockett, 2011-2017
+                  Chris Peikert, 2011-2017
+License     : GPL-3
+Maintainer  : ecrockett0@gmail.com
+Stability   : experimental
+Portability : POSIX
+
+High-level test groups and parameters, which can be used to verify a
+'Crypto.Lol.Cyclotomic.Tensor' implementation.
+-}
+
+{-# LANGUAGE DataKinds             #-}
+{-# LANGUAGE FlexibleContexts      #-}
+{-# LANGUAGE NoStarIsType          #-}
+{-# LANGUAGE PartialTypeSignatures #-}
+{-# LANGUAGE PolyKinds             #-}
+{-# LANGUAGE QuantifiedConstraints #-}
+{-# LANGUAGE ScopedTypeVariables   #-}
+{-# LANGUAGE TypeFamilies          #-}
+{-# LANGUAGE TypeOperators         #-}
+
+{-# OPTIONS_GHC -fno-warn-partial-type-signatures #-}
+
+module Crypto.Lol.Tests.Default (
+  defaultZqTests, cycTests,
+  cpxTensorTests, dblTensorTests, int64TensorTests, zqTensorTests
+  )
+where
+
+import Crypto.Lol                        (Cyc, Int64)
+import Crypto.Lol.Factored
+import Crypto.Lol.Tests.CycTests
+import Crypto.Lol.Tests.TensorTests
+import Crypto.Lol.Tests.ZqTests
+import Crypto.Lol.Types.IrreducibleChar2 ()
+import Crypto.Lol.Types.Unsafe.Complex   (Complex)
+import Crypto.Lol.Utils.ShowType
+import Crypto.Lol.Utils.Tests            (Gen, Test, choose, chooseAny,
+                                          testGroup)
+
+import qualified Algebra.Ring as Ring (fromInteger)
+
+import Data.Proxy
+
+type CpxDbl = Complex Double
+
+-- Gens a complex number in [0,1) + [0,i)
+cpxDblGen :: Gen CpxDbl
+cpxDblGen = chooseAny
+
+-- Gens an Int64 in [-100,100]
+boundedInt64Gen :: Gen Int64
+boundedInt64Gen = choose (-100, 100)
+
+-- Gens a Tensor over Int64s in the range [-100,100]
+int64TensorGen :: forall t m . _ => Gen (t m Int64)
+int64TensorGen = choose (Ring.fromInteger (-100), Ring.fromInteger 100)
+
+unifTensorTests1 :: forall t m r . _ => Proxy '(m,r) -> Proxy t -> Test
+unifTensorTests1 _ _ =
+  let tensorGen = chooseAny :: Gen (t m r) in
+  tensorTests1 tensorGen
+
+unifTensorTests2 :: forall t m m' r . _ => Proxy '(m,m',r) -> Proxy t -> Test
+unifTensorTests2 _ _ =
+  let tensorGen = chooseAny :: Gen (t m r) in
+  tensorTests2 (Proxy::Proxy '(t,m,m',r)) tensorGen
+
+unifTensorCrtTests2 :: forall t m m' r . _ => Proxy '(m,m',r) -> Proxy t -> Test
+unifTensorCrtTests2 _ _ =
+  let tensorGen = chooseAny :: Gen (t m r) in
+  tensorCrtTests2 (Proxy::Proxy '(t,m,m',r)) tensorGen
+
+unifTensorCrtTests1 :: forall t m r . _ => Proxy '(m,r) -> Proxy t -> Test
+unifTensorCrtTests1 _ _ =
+  let ringGen   = chooseAny :: Gen r
+      tensorGen = chooseAny :: Gen (t m r) in
+  tensorCrtTests1 ringGen tensorGen
+
+boundedInt64TensorTests1 :: forall t m . _ => Proxy m -> Proxy t -> Test
+boundedInt64TensorTests1 _ _ = tensorTests1 (int64TensorGen :: Gen (t m Int64))
+
+boundedInt64TensorTests2 :: forall t m m' . _ => Proxy '(m,m') -> Proxy t -> Test
+boundedInt64TensorTests2 _ _ = tensorTests2
+                                 (Proxy::Proxy '(t,m,m',Int64))
+                                 (int64TensorGen :: Gen (t m Int64))
+
+unifCycTests1 :: forall t m r . _ => Proxy '(m,r) -> Proxy t -> Test
+unifCycTests1 _ _ =
+  let cycGen = chooseAny :: Gen (Cyc t m r) in
+  cycTests1 cycGen
+
+unifCycTests2 :: forall t m m' r . _ => Proxy '(m,m',r) -> Proxy t -> Test
+unifCycTests2 _ _ =
+  let cycGen = chooseAny :: Gen (Cyc t m' r) in
+  cycTests2 (Proxy::Proxy '(t,m,m',r)) cycGen
+
+-- | Default parameters for 'Crypto.Lol.Types.Unsafe.ZqBasic' tests.
+defaultZqTests :: Test
+defaultZqTests = testGroup "Zq Tests" [
+  zqTests (Proxy::Proxy (Zq 3)),
+  zqTests (Proxy::Proxy (Zq 7)),
+  zqTests (Proxy::Proxy (Zq (3 ** 5))),
+  zqTests (Proxy::Proxy (Zq (3 ** 5 ** 7)))]
+
+zqTensorTests :: _ => Proxy t -> Test
+zqTensorTests pt =
+  let uniIndexWithoutCrt = testGroup "Single-Index Tensor Tests over ZqBasic" $ ($ pt) <$> [
+        unifTensorTests1 (Proxy::Proxy '(F7,  Zq 29)),
+        unifTensorTests1 (Proxy::Proxy '(F12, SmoothZQ1)),
+        unifTensorTests1 (Proxy::Proxy '(F1,  Zq 17)),
+        unifTensorTests1 (Proxy::Proxy '(F2,  Zq 17)),
+        unifTensorTests1 (Proxy::Proxy '(F4,  Zq 17)),
+        unifTensorTests1 (Proxy::Proxy '(F8,  Zq 17)),
+        unifTensorTests1 (Proxy::Proxy '(F21, Zq 8191)),
+        unifTensorTests1 (Proxy::Proxy '(F42, Zq 8191)),
+        unifTensorTests1 (Proxy::Proxy '(F42, ZQ1)),
+        unifTensorTests1 (Proxy::Proxy '(F89, Zq 179))]
+      uniIndexWithCrt = testGroup "Single-Index TensorCRT Tests over ZqBasic" $ ($ pt) <$> [
+        unifTensorCrtTests1 (Proxy::Proxy '(F7,  Zq 29)),
+        unifTensorCrtTests1 (Proxy::Proxy '(F12, SmoothZQ1)),
+        unifTensorCrtTests1 (Proxy::Proxy '(F1,  Zq 17)),
+        unifTensorCrtTests1 (Proxy::Proxy '(F2,  Zq 17)),
+        unifTensorCrtTests1 (Proxy::Proxy '(F4,  Zq 17)),
+        unifTensorCrtTests1 (Proxy::Proxy '(F8,  Zq 17)),
+        unifTensorCrtTests1 (Proxy::Proxy '(F21, Zq 8191)),
+        unifTensorCrtTests1 (Proxy::Proxy '(F42, Zq 8191)),
+        unifTensorCrtTests1 (Proxy::Proxy '(F42, ZQ1)),
+        unifTensorCrtTests1 (Proxy::Proxy '(F89, Zq 179))]
+      multiIndexWithoutCrt = testGroup "Multi-Index Tensor Tests over ZqBasic" $ ($ pt) <$> [
+        unifTensorTests2 (Proxy::Proxy '(F1, F7,  Zq 29)),
+        unifTensorTests2 (Proxy::Proxy '(F4, F12, Zq 536871001)),
+        unifTensorTests2 (Proxy::Proxy '(F4, F12, SmoothZQ1)),
+        unifTensorTests2 (Proxy::Proxy '(F2, F8,  Zq 17)),
+        unifTensorTests2 (Proxy::Proxy '(F8, F8,  Zq 17)),
+        unifTensorTests2 (Proxy::Proxy '(F2, F8,  SmoothZQ1)),
+        unifTensorTests2 (Proxy::Proxy '(F4, F8,  Zq 17)),
+        unifTensorTests2 (Proxy::Proxy '(F3, F21, Zq 8191)),
+        unifTensorTests2 (Proxy::Proxy '(F7, F21, Zq 8191)),
+        unifTensorTests2 (Proxy::Proxy '(F3, F42, Zq 8191))]
+      multiIndexWithCrt = testGroup "Multi-Index TensorCRT Tests over ZqBasic" $ ($ pt) <$> [
+        unifTensorCrtTests2 (Proxy::Proxy '(F1, F7,  Zq 29)),
+        unifTensorCrtTests2 (Proxy::Proxy '(F4, F12, Zq 536871001)),
+        unifTensorCrtTests2 (Proxy::Proxy '(F4, F12, SmoothZQ1)),
+        unifTensorCrtTests2 (Proxy::Proxy '(F2, F8,  Zq 17)),
+        unifTensorCrtTests2 (Proxy::Proxy '(F8, F8,  Zq 17)),
+        unifTensorCrtTests2 (Proxy::Proxy '(F2, F8,  SmoothZQ1)),
+        unifTensorCrtTests2 (Proxy::Proxy '(F4, F8,  Zq 17)),
+        unifTensorCrtTests2 (Proxy::Proxy '(F3, F21, Zq 8191)),
+        unifTensorCrtTests2 (Proxy::Proxy '(F7, F21, Zq 8191)),
+        unifTensorCrtTests2 (Proxy::Proxy '(F3, F42, Zq 8191))] in
+  testGroup "All Tensor-like Tests over ZqBasic" [
+    uniIndexWithoutCrt, uniIndexWithCrt, multiIndexWithoutCrt, multiIndexWithCrt]
+
+int64TensorTests :: _ => Proxy t -> Test
+int64TensorTests pt =
+  let uniIndexWithoutCrt = testGroup "Single-Index Tensor Tests over Int64" $ ($ pt) <$> [
+        boundedInt64TensorTests1 (Proxy::Proxy F7),
+        boundedInt64TensorTests1 (Proxy::Proxy F12),
+        boundedInt64TensorTests1 (Proxy::Proxy F1),
+        boundedInt64TensorTests1 (Proxy::Proxy F2),
+        boundedInt64TensorTests1 (Proxy::Proxy F4),
+        boundedInt64TensorTests1 (Proxy::Proxy F8),
+        boundedInt64TensorTests1 (Proxy::Proxy F21),
+        boundedInt64TensorTests1 (Proxy::Proxy F42),
+        boundedInt64TensorTests1 (Proxy::Proxy F42),
+        boundedInt64TensorTests1 (Proxy::Proxy F89)]
+      multiIndexWithoutCrt = testGroup "Multi-Index Tensor Tests over Int64" $ ($ pt) <$> [
+        boundedInt64TensorTests2 (Proxy::Proxy '(F1, F7)),
+        boundedInt64TensorTests2 (Proxy::Proxy '(F4, F12)),
+        boundedInt64TensorTests2 (Proxy::Proxy '(F4, F12)),
+        boundedInt64TensorTests2 (Proxy::Proxy '(F2, F8)),
+        boundedInt64TensorTests2 (Proxy::Proxy '(F8, F8)),
+        boundedInt64TensorTests2 (Proxy::Proxy '(F2, F8)),
+        boundedInt64TensorTests2 (Proxy::Proxy '(F4, F8)),
+        boundedInt64TensorTests2 (Proxy::Proxy '(F3, F21)),
+        boundedInt64TensorTests2 (Proxy::Proxy '(F7, F21)),
+        boundedInt64TensorTests2 (Proxy::Proxy '(F3, F42))] in
+  testGroup "All Tensor-like Tests over Int64" [uniIndexWithoutCrt, multiIndexWithoutCrt]
+
+dblTensorTests :: _ => Proxy t -> Test
+dblTensorTests pt =
+  let uniIndexWithoutCrt = testGroup "Single-Index Tensor Tests over Double" $ ($ pt) <$> [
+        unifTensorTests1 (Proxy::Proxy '(F7, Double)),
+        unifTensorTests1 (Proxy::Proxy '(F12, Double)),
+        unifTensorTests1 (Proxy::Proxy '(F1, Double)),
+        unifTensorTests1 (Proxy::Proxy '(F2, Double)),
+        unifTensorTests1 (Proxy::Proxy '(F4, Double)),
+        unifTensorTests1 (Proxy::Proxy '(F8, Double)),
+        unifTensorTests1 (Proxy::Proxy '(F21, Double)),
+        unifTensorTests1 (Proxy::Proxy '(F42, Double)),
+        unifTensorTests1 (Proxy::Proxy '(F42, Double)),
+        unifTensorTests1 (Proxy::Proxy '(F89, Double))]
+      uniIndexWithCrt = testGroup "Single-Index TensorCRT Tests over Double" $ ($ pt) <$> [
+        unifTensorCrtTests1 (Proxy::Proxy '(F7, Double)),
+        unifTensorCrtTests1 (Proxy::Proxy '(F12, Double)),
+        unifTensorCrtTests1 (Proxy::Proxy '(F1, Double)),
+        unifTensorCrtTests1 (Proxy::Proxy '(F2, Double)),
+        unifTensorCrtTests1 (Proxy::Proxy '(F4, Double)),
+        unifTensorCrtTests1 (Proxy::Proxy '(F8, Double)),
+        unifTensorCrtTests1 (Proxy::Proxy '(F21, Double)),
+        unifTensorCrtTests1 (Proxy::Proxy '(F42, Double)),
+        unifTensorCrtTests1 (Proxy::Proxy '(F42, Double)),
+        unifTensorCrtTests1 (Proxy::Proxy '(F89, Double))]
+      multiIndexWithoutCrt = testGroup "Multi-Index Tensor Tests over Double" $ ($ pt) <$> [
+        unifTensorTests2 (Proxy::Proxy '(F1, F7, Double)),
+        unifTensorTests2 (Proxy::Proxy '(F4, F12, Double)),
+        unifTensorTests2 (Proxy::Proxy '(F4, F12, Double)),
+        unifTensorTests2 (Proxy::Proxy '(F2, F8, Double)),
+        unifTensorTests2 (Proxy::Proxy '(F8, F8, Double)),
+        unifTensorTests2 (Proxy::Proxy '(F2, F8, Double)),
+        unifTensorTests2 (Proxy::Proxy '(F4, F8, Double)),
+        unifTensorTests2 (Proxy::Proxy '(F3, F21, Double)),
+        unifTensorTests2 (Proxy::Proxy '(F7, F21, Double)),
+        unifTensorTests2 (Proxy::Proxy '(F3, F42, Double))]
+      multiIndexWithCrt = testGroup "Multi-Index TensorCRT Tests over Double" $ ($ pt) <$> [
+        unifTensorCrtTests2 (Proxy::Proxy '(F1, F7, Double)),
+        unifTensorCrtTests2 (Proxy::Proxy '(F4, F12, Double)),
+        unifTensorCrtTests2 (Proxy::Proxy '(F4, F12, Double)),
+        unifTensorCrtTests2 (Proxy::Proxy '(F2, F8, Double)),
+        unifTensorCrtTests2 (Proxy::Proxy '(F8, F8, Double)),
+        unifTensorCrtTests2 (Proxy::Proxy '(F2, F8, Double)),
+        unifTensorCrtTests2 (Proxy::Proxy '(F4, F8, Double)),
+        unifTensorCrtTests2 (Proxy::Proxy '(F3, F21, Double)),
+        unifTensorCrtTests2 (Proxy::Proxy '(F7, F21, Double)),
+        unifTensorCrtTests2 (Proxy::Proxy '(F3, F42, Double))] in
+  testGroup "All Tensor-like Tests over Double" [uniIndexWithoutCrt, multiIndexWithoutCrt]
+
+cpxTensorTests :: _ => Proxy t -> Test
+cpxTensorTests pt =
+  let uniIndexWithoutCrt = testGroup "Single-Index Tensor Tests over Complex Double" $ ($ pt) <$> [
+        unifTensorTests1 (Proxy::Proxy '(F7, CpxDbl)),
+        unifTensorTests1 (Proxy::Proxy '(F12, CpxDbl)),
+        unifTensorTests1 (Proxy::Proxy '(F1, CpxDbl)),
+        unifTensorTests1 (Proxy::Proxy '(F2, CpxDbl)),
+        unifTensorTests1 (Proxy::Proxy '(F4, CpxDbl)),
+        unifTensorTests1 (Proxy::Proxy '(F8, CpxDbl)),
+        unifTensorTests1 (Proxy::Proxy '(F21, CpxDbl)),
+        unifTensorTests1 (Proxy::Proxy '(F42, CpxDbl)),
+        unifTensorTests1 (Proxy::Proxy '(F42, CpxDbl)),
+        unifTensorTests1 (Proxy::Proxy '(F89, CpxDbl))]
+      uniIndexWithCrt = testGroup "Single-Index TensorCRT Tests over Complex Double" $ ($ pt) <$> [
+        unifTensorCrtTests1 (Proxy::Proxy '(F7, CpxDbl)),
+        unifTensorCrtTests1 (Proxy::Proxy '(F12, CpxDbl)),
+        unifTensorCrtTests1 (Proxy::Proxy '(F1, CpxDbl)),
+        unifTensorCrtTests1 (Proxy::Proxy '(F2, CpxDbl)),
+        unifTensorCrtTests1 (Proxy::Proxy '(F4, CpxDbl)),
+        unifTensorCrtTests1 (Proxy::Proxy '(F8, CpxDbl)),
+        unifTensorCrtTests1 (Proxy::Proxy '(F21, CpxDbl)),
+        unifTensorCrtTests1 (Proxy::Proxy '(F42, CpxDbl)),
+        unifTensorCrtTests1 (Proxy::Proxy '(F42, CpxDbl)),
+        unifTensorCrtTests1 (Proxy::Proxy '(F89, CpxDbl))]
+      multiIndexWithoutCrt = testGroup "Multi-Index Tensor Tests over Complex Double" $ ($ pt) <$> [
+        unifTensorTests2 (Proxy::Proxy '(F1, F7, CpxDbl)),
+        unifTensorTests2 (Proxy::Proxy '(F4, F12, CpxDbl)),
+        unifTensorTests2 (Proxy::Proxy '(F4, F12, CpxDbl)),
+        unifTensorTests2 (Proxy::Proxy '(F2, F8, CpxDbl)),
+        unifTensorTests2 (Proxy::Proxy '(F8, F8, CpxDbl)),
+        unifTensorTests2 (Proxy::Proxy '(F2, F8, CpxDbl)),
+        unifTensorTests2 (Proxy::Proxy '(F4, F8, CpxDbl)),
+        unifTensorTests2 (Proxy::Proxy '(F3, F21, CpxDbl)),
+        unifTensorTests2 (Proxy::Proxy '(F7, F21, CpxDbl)),
+        unifTensorTests2 (Proxy::Proxy '(F3, F42, CpxDbl))]
+      multiIndexWithCrt = testGroup "Multi-Index TensorCRT Tests over Complex Double" $ ($ pt) <$> [
+        unifTensorCrtTests2 (Proxy::Proxy '(F1, F7, CpxDbl)),
+        unifTensorCrtTests2 (Proxy::Proxy '(F4, F12, CpxDbl)),
+        unifTensorCrtTests2 (Proxy::Proxy '(F4, F12, CpxDbl)),
+        unifTensorCrtTests2 (Proxy::Proxy '(F2, F8, CpxDbl)),
+        unifTensorCrtTests2 (Proxy::Proxy '(F8, F8, CpxDbl)),
+        unifTensorCrtTests2 (Proxy::Proxy '(F2, F8, CpxDbl)),
+        unifTensorCrtTests2 (Proxy::Proxy '(F4, F8, CpxDbl)),
+        unifTensorCrtTests2 (Proxy::Proxy '(F3, F21, CpxDbl)),
+        unifTensorCrtTests2 (Proxy::Proxy '(F7, F21, CpxDbl)),
+        unifTensorCrtTests2 (Proxy::Proxy '(F3, F42, CpxDbl))] in
+  testGroup "All Tensor-like Tests over Complex Double" [
+    uniIndexWithoutCrt, uniIndexWithCrt, multiIndexWithoutCrt, multiIndexWithCrt]
+
+cycTests :: (forall m r . (Fact m, Eq r)   => Eq   (t m r),
+             forall m r . (Fact m, Show r) => Show (t m r),
+             _)
+  => Proxy t -> Test
+cycTests pt =
+  let uniIndex = testGroup "Single-Index Cyc Tests over ZqBasic" $ ($ pt) <$> [
+        unifCycTests1 (Proxy::Proxy '(F7,  Zq 29)),
+        unifCycTests1 (Proxy::Proxy '(F7,  Zq 32)),
+        unifCycTests1 (Proxy::Proxy '(F12, SmoothZQ1)),
+        unifCycTests1 (Proxy::Proxy '(F1,  Zq 17)),
+        unifCycTests1 (Proxy::Proxy '(F2,  Zq 17)),
+        unifCycTests1 (Proxy::Proxy '(F4,  Zq 17)),
+        unifCycTests1 (Proxy::Proxy '(F8,  Zq 17)),
+        unifCycTests1 (Proxy::Proxy '(F21, Zq 8191)),
+        unifCycTests1 (Proxy::Proxy '(F42, Zq 8191)),
+        unifCycTests1 (Proxy::Proxy '(F42, ZQ1)),
+        unifCycTests1 (Proxy::Proxy '(F42, Zq 1024)),
+        unifCycTests1 (Proxy::Proxy '(F42, ZQ2)),
+        unifCycTests1 (Proxy::Proxy '(F89, Zq 179))
+        ]
+      multiIndex = testGroup "Multi-Index Cyc Tests over ZqBasic" $ ($ pt) <$> [
+        unifCycTests2 (Proxy::Proxy '(H01, H1, Zq PP2)),
+        unifCycTests2 (Proxy::Proxy '(H01, H1, Zq PP4)),
+        unifCycTests2 (Proxy::Proxy '(H01, H1, Zq PP8)),
+        unifCycTests2 (Proxy::Proxy '(H01, H1, Zq PP16)),
+        unifCycTests2 (Proxy::Proxy '(H12, H2, Zq PP2)),
+        unifCycTests2 (Proxy::Proxy '(H12, H2, Zq PP4)),
+        unifCycTests2 (Proxy::Proxy '(H12, H2, Zq PP8)),
+        unifCycTests2 (Proxy::Proxy '(H12, H2, Zq PP16)),
+        unifCycTests2 (Proxy::Proxy '(H23, H3, Zq PP2)),
+        unifCycTests2 (Proxy::Proxy '(H23, H3, Zq PP4)),
+        unifCycTests2 (Proxy::Proxy '(H23, H3, Zq PP8)),
+        unifCycTests2 (Proxy::Proxy '(H23, H3, Zq PP16)),
+        unifCycTests2 (Proxy::Proxy '(H34, H4, Zq PP2)),
+        unifCycTests2 (Proxy::Proxy '(H34, H4, Zq PP4)),
+        unifCycTests2 (Proxy::Proxy '(H34, H4, Zq PP8)),
+        unifCycTests2 (Proxy::Proxy '(H34, H4, Zq PP16)),
+        unifCycTests2 (Proxy::Proxy '(H45, H5, Zq PP2)),
+        unifCycTests2 (Proxy::Proxy '(H45, H5, Zq PP4)),
+        unifCycTests2 (Proxy::Proxy '(H45, H5, Zq PP8)),
+        unifCycTests2 (Proxy::Proxy '(H45, H5, Zq PP16)),
+        unifCycTests2 (Proxy::Proxy '(F4, F28, Zq PP2)),
+        unifCycTests2 (Proxy::Proxy '(F4, F28, Zq PP4)),
+        unifCycTests2 (Proxy::Proxy '(F4, F28, Zq PP8)),
+        unifCycTests2 (Proxy::Proxy '(F7, F7*F13, Zq PP2)),
+        unifCycTests2 (Proxy::Proxy '(F7, F7*F13, Zq PP4)),
+        unifCycTests2 (Proxy::Proxy '(F1, F7, Zq PP8)),
+        unifCycTests2 (Proxy::Proxy '(F1, F7, Zq PP2))
+        ]
+  in testGroup "All Cyc Tests over ZqBasic" [uniIndex, multiIndex]
+
+-- three 24-bit moduli, enough to handle rounding for p=32 (depth-4 circuit at ~17 bits per mul)
+type ZQ1 = Zq 18869761
+type ZQ2 = Zq (19393921 ** 18869761)
+
+type SmoothZQ1 = Zq 2148249601
+
+type H01 = F64
+type H1 = F64 * F7
+type H12 = F32 * F7
+type H2 = F32 * F7 * F13
+type H23 = F8 * F7 * F13
+type H3 = F8 * F5 * F7 * F13
+type H34 = F4 * F5 * F7 * F13
+type H4 = F4 * F3 * F5 * F7 * F13
+type H45 = F3 * F5 * F7 * F13
+type H5 = F9 * F5 * F7 * F13
diff --git a/Crypto/Lol/Tests/TensorTests.hs b/Crypto/Lol/Tests/TensorTests.hs
new file mode 100644
--- /dev/null
+++ b/Crypto/Lol/Tests/TensorTests.hs
@@ -0,0 +1,290 @@
+{-|
+Module      : Crypto.Lol.Tests.TensorTests
+Description : Tests for the 'Tensor' interface.
+Copyright   : (c) Eric Crockett, 2011-2017
+                  Chris Peikert, 2011-2017
+License     : GPL-3
+Maintainer  : ecrockett0@email.com
+Stability   : experimental
+Portability : POSIX
+
+Tests for the 'Tensor' interface.
+-}
+
+{-# LANGUAGE ConstraintKinds       #-}
+{-# LANGUAGE DataKinds             #-}
+{-# LANGUAGE FlexibleContexts      #-}
+{-# LANGUAGE MultiParamTypeClasses #-}
+{-# LANGUAGE PartialTypeSignatures #-}
+{-# LANGUAGE PolyKinds             #-}
+{-# LANGUAGE RebindableSyntax      #-}
+{-# LANGUAGE ScopedTypeVariables   #-}
+{-# LANGUAGE TypeApplications      #-}
+{-# LANGUAGE TypeFamilies          #-}
+{-# LANGUAGE TypeOperators         #-}
+{-# LANGUAGE UndecidableInstances  #-}
+
+{-# OPTIONS_GHC -fno-warn-partial-type-signatures #-}
+
+module Crypto.Lol.Tests.TensorTests
+(
+  tensorCrtTests1, tensorCrtTests2, tensorTests1, tensorTests2
+)
+where
+
+import Crypto.Lol
+import Crypto.Lol.Cyclotomic.Tensor
+import Crypto.Lol.Utils.ShowType
+import Crypto.Lol.Utils.Tests       (Gen, Test, nestGroup, testGroup,
+                                     testWithGen, testWithoutGen, (=~=))
+
+import Control.Applicative
+import Data.Maybe
+
+-- TODO: We don't test:
+--         * TensorPowDec::coeffs,
+--         * TensorPowDec::powBasisPow,
+--         * TensorGSqNorm::gSqNormDec
+
+-- Has to take two generators because prop_scalar_crt only takes ring elements as input
+tensorTests1 :: forall t m r . _ => Gen (t m r) -> Test
+tensorTests1 tensorGen =
+  let ptmr  = Proxy::Proxy '(t,m,r)
+      tests = ($ tensorGen) <$> [
+        testWithGen   "fmap comparison"                           prop_fmap,
+        nestGroup     "GInv.G == id" [
+          testWithGen "Pow basis"                                 prop_ginv_pow,
+          testWithGen "Dec basis"                                 prop_ginv_dec],
+        testWithGen   "DecToPowToDec == id"                       prop_decToPowToDec,
+        testWithGen   "G commutes with L on Dec basis"            prop_g_dec,
+        testWithGen   "Tw and Em ID on Pow/Dec for equal indices" prop_twEmID] in
+  testGroup (showType ptmr) tests
+
+tensorCrtTests1 :: forall t m r . _ => Gen r -> Gen (t m r) -> Test
+tensorCrtTests1 ringGen tensorGen =
+  let ptmr = Proxy::Proxy '(t,m,r)
+      tests = [
+          testWithGen "GInv.G == id on CRT basis"             prop_ginv_crt tensorGen,
+          testWithGen "CRTInv.CRT == id"                      prop_crt_inv tensorGen,
+          testWithGen "G commutes with L on CRT basis"        prop_g_crt tensorGen,
+          testWithGen "Tw and Em ID on CRT for equal indices" prop_twEmIDCRT tensorGen,
+          testWithGen "Scalar"                               (prop_scalar_crt ptmr) ringGen] in
+  testGroup (showType ptmr) tests
+
+tensorTests2 :: forall t m m' r . _
+             => Proxy '(t,m,m',r) -> Gen (t m r) -> Test
+tensorTests2 _ tensorGen =
+  let ptmmr  = Proxy::Proxy '(t,m,m',r)
+      randTests  = ($ tensorGen) <$> [
+        nestGroup  "Tw.Em == id" [
+          testWithGen "Pow basis"                       (prop_trem_pow ptmmr)
+        , testWithGen "Dec basis"                       (prop_trem_dec ptmmr)
+          ],
+        testWithGen   "Em commutes with L in Dec basis" (prop_embed_dec ptmmr),
+        testWithGen   "Tw commutes with L in Dec basis" (prop_twace_dec ptmmr)]
+      deterministicTests = [
+        testGroup  "Twace invariants" [
+          testWithoutGen "Invar1 Pow basis"             (prop_twace_invar1_pow ptmmr),
+          testWithoutGen "Invar1 Dec basis"             (prop_twace_invar1_dec ptmmr),
+          testWithoutGen "Invar2 Pow/Dec basis"         (prop_twace_invar2_powdec ptmmr)]] in
+      testGroup (showType ptmmr) (randTests ++ deterministicTests)
+
+tensorCrtTests2 :: forall t m m' r . _ => Proxy '(t,m,m',r) -> Gen (t m r) -> Test
+tensorCrtTests2 _ tensorGen =
+  let ptmmr  = Proxy::Proxy '(t,m,m',r)
+      randTests  = ($ tensorGen) <$> [
+        testWithGen "Tw.Em == id in CRT basis"        (prop_trem_crt ptmmr),
+        testWithGen "Em commutes with L in CRT basis" (prop_embed_crt ptmmr),
+        testWithGen "Tw commutes with L in CRT basis" (prop_twace_crt ptmmr)]
+      deterministicTests = [
+        testGroup "Twace invariants" [
+          testWithoutGen "Invar1 CRT basis"           (prop_twace_invar1_crt ptmmr),
+          testWithoutGen "Invar2 CRT basis"           (prop_twace_invar2_crt ptmmr)]] in
+      testGroup (showType ptmmr) (randTests ++ deterministicTests)
+
+prop_fmap :: _ => t m r -> Bool
+prop_fmap x = fmap id x =~= x
+
+-- divG . mulG == id in Pow basis
+prop_ginv_pow :: _ => t m r -> Bool
+prop_ginv_pow x = fromMaybe (error "could not divide by G in prop_ginv_pow") (
+  divGPow $ mulGPow x) =~= x
+
+-- divG . mulG == id in Dec basis
+prop_ginv_dec :: _ => t m r -> Bool
+prop_ginv_dec x = fromMaybe (error "could not divide by G in prop_ginv_dec") (
+  divGDec $ mulGDec x) =~= x
+
+-- divG . mulG == id in CRT basis
+prop_ginv_crt :: _ => t m r -> Bool
+prop_ginv_crt x = fromMaybe (error "no CRT in prop_ginv_crt") $ do
+  divGCRT' <- divGCRT
+  mulGCRT' <- mulGCRT
+  return $ divGCRT' (mulGCRT' x) =~= x
+
+-- mulGDec == powToDec . mulGPow . decToPow
+prop_g_dec :: _ => t m r -> Bool
+prop_g_dec x = mulGDec x =~= powToDec (mulGPow $ decToPow x)
+
+prop_g_crt :: _ => t m r -> Bool
+prop_g_crt x = fromMaybe (error "no CRT in prop_g_crt") $ do
+  mulGCRT' <- mulGCRT
+  crt' <- crt
+  crtInv' <- crtInv
+  return $ mulGCRT' x =~= crt' (mulGPow $ crtInv' x)
+
+-- crtInv . crt == id
+prop_crt_inv :: _ => t m r -> Bool
+prop_crt_inv x = fromMaybe (error "no CRT in prop_crt_inv") $ do
+  crt' <- crt
+  crtInv' <- crtInv
+  return $ crtInv' (crt' x) =~= x
+
+-- powToDec . decToPowToDec == id
+prop_decToPowToDec :: _ => t m r -> Bool
+prop_decToPowToDec x = powToDec (decToPow x) =~= x
+
+-- scalarCRT = crt . scalarPow
+-- This only requires Proxy '(t,m) to be fully determined, but this works too
+prop_scalar_crt :: forall t m r . (TensorPowDec t r, Fact m, _) => Proxy '(t,m,r) -> r -> Bool
+prop_scalar_crt _ x = fromMaybe (error "no CRT in prop_scalar_crt") $ do
+  scalarCRT' <- scalarCRT
+  crt' <- crt
+  return $ (scalarCRT' x :: t m r) =~= crt' (scalarPow x)
+
+-- tests that twace . embed == id in the Pow basis
+prop_trem_pow :: forall t m m' r . (m `Divides` m', _) => Proxy '(t,m,m',r) -> t m r -> Bool
+prop_trem_pow _ x = twacePowDec (embedPow x :: t m' r) =~= x
+
+-- tests that twace . embed == id in the Dec basis
+prop_trem_dec :: forall t m m' r . (m `Divides` m', _) => Proxy '(t,m,m',r) -> t m r -> Bool
+prop_trem_dec _ x = twacePowDec (embedDec x :: t m' r) =~= x
+
+-- tests that twace . embed == id in the CRT basis
+prop_trem_crt :: forall t m m' r . (m `Divides` m', _) => Proxy '(t,m,m',r) -> t m r -> Bool
+prop_trem_crt _ x = maybe (error "no CRT in prop_trem_crt") (x=~=) (twaceCRT <*> (embedCRT <*> pure x :: Maybe (t m' r)))
+
+-- embedDec == powToDec . embedPow . decToPow
+prop_embed_dec :: forall t m m' r . (m `Divides` m', _) => Proxy '(t,m,m',r) -> t m r -> Bool
+prop_embed_dec _ x = (embedDec x :: t m' r) =~=
+                     powToDec (embedPow $ decToPow x)
+
+-- embedCRT = crt . embedPow . crtInv
+prop_embed_crt :: forall t m m' r . (m `Divides` m', _) => Proxy '(t,m,m',r) -> t m r -> Bool
+prop_embed_crt _ x = fromMaybe (error "no CRT in prop_embed_crt") $ do
+  crt' <- crt
+  crtInv' <- crtInv
+  embedCRT' <- embedCRT
+  return $ (embedCRT' x :: t m' r) =~= crt' (embedPow $ crtInv' x)
+
+-- twacePowDec = powToDec . twacePowDec . decToPow
+prop_twace_dec :: forall t m m' r . _ => Proxy '(t,m,m',r) -> t m r -> Bool
+prop_twace_dec _ x = (twacePowDec x :: t m r) =~=
+                     powToDec (twacePowDec $ decToPow x)
+
+-- twaceCRT = crt . twacePowDec . crtInv
+prop_twace_crt :: forall t m m' r . _ => Proxy '(t,m,m',r) -> t m r -> Bool
+prop_twace_crt _ x = fromMaybe (error "no CRT in prop_trace_crt") $ do
+  twaceCRT' <- twaceCRT
+  crt' <- crt
+  crtInv' <- crtInv
+  return $ (twaceCRT' x :: t m r) =~= crt' (twacePowDec $ crtInv' x)
+
+prop_twEmIDCRT :: forall t m r . _ => t m r -> Bool
+prop_twEmIDCRT x = (fromMaybe (error "twemid_crt") twaceCRT x =~= x) &&
+                   (fromMaybe (error "twemid_crt") embedCRT x =~= x)
+
+prop_twEmID :: forall t m r . _ => t m r -> Bool
+prop_twEmID x = (twacePowDec x =~= x) &&
+                (embedPow x =~= x)
+
+-- twace mhat'/g' = mhat*totm'/totm/g (Pow basis)
+prop_twace_invar1_pow :: forall t m m' r . _ => Proxy '(t,m,m',r) -> Bool
+prop_twace_invar1_pow _ = fromMaybe (error "could not divide by G in prop_twace_invar1_pow") $ do
+  let mhat  = valueHatFact @m
+      mhat' = valueHatFact @m'
+      totm  = totientFact  @m
+      totm' = totientFact  @m'
+  output :: t m r <- divGPow $ scalarPow $ fromIntegral $ mhat * totm' `div` totm
+  input :: t m' r <- divGPow $ scalarPow $ fromIntegral mhat'
+  return $ twacePowDec input =~= output
+
+-- twace mhat'/g' = mhat*totm'/totm/g (Dec basis)
+prop_twace_invar1_dec :: forall t m m' r . _ => Proxy '(t,m,m',r) -> Bool
+prop_twace_invar1_dec _ = fromMaybe (error "could not divide by G in prop_twace_invar1_dec") $ do
+  let mhat  = valueHatFact @m
+      mhat' = valueHatFact @m'
+      totm  = totientFact  @m
+      totm' = totientFact  @m'
+  output :: t m r <- divGDec $ powToDec $ scalarPow $ fromIntegral $ mhat * totm' `div` totm
+  input :: t m' r <- divGDec $ powToDec $ scalarPow $ fromIntegral mhat'
+  return $ twacePowDec input =~= output
+
+-- twace mhat'/g' = mhat*totm'/totm/g (CRT basis)
+prop_twace_invar1_crt :: forall t m m' r . _ => Proxy '(t,m,m',r) -> Bool
+prop_twace_invar1_crt _ = fromMaybe (error "no CRT in prop_twace_invar1_crt") $ do
+  let mhat  = valueHatFact @m
+      mhat' = valueHatFact @m'
+      totm  = totientFact  @m
+      totm' = totientFact  @m'
+  scalarCRT1 <- scalarCRT
+  scalarCRT2 <- scalarCRT
+  divGCRT1 <- divGCRT
+  divGCRT2 <- divGCRT
+  twaceCRT' <- twaceCRT
+  let output :: t m r = divGCRT1 $ scalarCRT1 $ fromIntegral $ mhat * totm' `div` totm
+      input :: t m' r = divGCRT2 $ scalarCRT2 $ fromIntegral mhat'
+  return $ twaceCRT' input =~= output
+
+-- twace preserves scalars in Pow/Dec basis
+prop_twace_invar2_powdec :: forall t m m' r . (TensorPowDec t r, m `Divides` m', _)
+                         => Proxy '(t,m,m',r) -> Bool
+prop_twace_invar2_powdec _ =
+  let output = scalarPow one :: t m r
+      input = scalarPow one :: t m' r
+  in twacePowDec input =~= output
+
+-- twace preserves scalars in Pow/Dec basis
+prop_twace_invar2_crt :: forall t m m' r . (TensorPowDec t r, m `Divides` m', _)
+                      => Proxy '(t,m,m',r) -> Bool
+prop_twace_invar2_crt _ = fromMaybe (error "no CRT in prop_twace_invar2_crt") $ do
+  scalarCRT1 <- scalarCRT
+  scalarCRT2 <- scalarCRT
+  let input = scalarCRT1 one :: t m' r
+      output = scalarCRT2 one :: t m r
+  return $ twacePowDec input =~= output
+
+{-
+-- tests that gSqNormDec of two "random-looking" vectors agrees for RT and CT
+-- t is a dummy param
+prop_gsqnorm :: forall (t :: Factored -> * -> *) m r . _ => r -> Test '(t,m,r)
+prop_gsqnorm x = test $
+  let crtCT = fromJust crt
+      crtRT = fromJust crt
+      -- not mathematically meaningful, we just need some "random" coefficients
+      ct = fmapT lift (mulGDec $ lInv $ crtCT $ scalarPow x :: CT m r)
+      rt = fmapT lift (mulGDec $ lInv $ crtRT $ scalarPow x :: RT m r)
+  in gSqNormDec ct == gSqNormDec rt
+
+-- we can't include a large modulus here because there is not enough
+-- precision in Doubles to handle the error
+{-type MRExtCombos = '[
+  '(F7, Zq 29),
+  '(F1, Zq 17),
+  '(F2, Zq 17),
+  '(F4, Zq 17),
+  '(F8, Zq 17),
+  '(F21, Zq 8191),
+  '(F42, Zq 8191),
+  '(F42, ZQ1),
+  '(F42, ZQ2),
+  '(F89, Zq 179)
+  ]-}
+
+type MM'RCombos = '[
+
+--type ExtParams = ( '(,) <$> Tensors) <*> MRExtCombos
+
+type NormParams = ( '(,) <$> '[RT]) <*> (Filter Liftable MRCombos)
+
+-}
diff --git a/Crypto/Lol/Tests/ZqTests.hs b/Crypto/Lol/Tests/ZqTests.hs
new file mode 100644
--- /dev/null
+++ b/Crypto/Lol/Tests/ZqTests.hs
@@ -0,0 +1,104 @@
+{-|
+Module      : Crypto.Lol.Tests.ZqTests
+Description : Tests for modular arithmetic.
+Copyright   : (c) Eric Crockett, 2011-2017
+                  Chris Peikert, 2011-2017
+License     : GPL-3
+Maintainer  : ecrockett0@email.com
+Stability   : experimental
+Portability : POSIX
+
+Tests for modular arithmetic.
+-}
+
+{-# LANGUAGE DataKinds             #-}
+{-# LANGUAGE FlexibleContexts      #-}
+{-# LANGUAGE FlexibleInstances     #-}
+{-# LANGUAGE GADTs                 #-}
+{-# LANGUAGE MultiParamTypeClasses #-}
+{-# LANGUAGE NoImplicitPrelude     #-}
+{-# LANGUAGE PartialTypeSignatures #-}
+{-# LANGUAGE RebindableSyntax      #-}
+{-# LANGUAGE ScopedTypeVariables   #-}
+{-# LANGUAGE StandaloneDeriving    #-}
+{-# LANGUAGE TypeApplications      #-}
+{-# LANGUAGE TypeOperators         #-}
+{-# LANGUAGE UndecidableInstances  #-}
+
+{-# OPTIONS_GHC -fno-warn-partial-type-signatures #-}
+
+module Crypto.Lol.Tests.ZqTests (zqTests) where
+
+import Crypto.Lol
+import Crypto.Lol.CRTrans
+import Crypto.Lol.Utils.ShowType
+import Crypto.Lol.Utils.Tests    (Gen, Test, chooseAny, testGroup,
+                                  testWithGen)
+
+import Control.Monad.Random
+
+-- | Tests for modular arithmetic implementations.
+zqTests :: forall r . (Mod r, _) => Proxy r -> Test
+zqTests p =
+  let gen1 = chooseAny :: Gen (LiftedMod r, LiftedMod r)
+      gen2 = chooseAny :: Gen (LiftedInvertible r, LiftedInvertible r)
+      gen3 = chooseAny :: Gen (Invertible r)
+      gen4 = chooseAny :: Gen (Invertible r, Invertible r) in
+  testGroup (showType p) [
+    testWithGen "(+)" prop_add gen1,
+    testWithGen "(*)" prop_mul gen2,
+    testWithGen "^-1" prop_recip gen3,
+    testWithGen "extension ring (*)" prop_mul_ext gen4
+  ]
+
+prop_add :: forall r . (Ring r, Eq r) => (LiftedMod r, LiftedMod r) -> Bool
+prop_add (LMod x, LMod y) = fromIntegral (x + y) == (fromIntegral x + fromIntegral y :: r)
+
+prop_mul :: forall r . (Ring r, Eq r) => (LiftedInvertible r, LiftedInvertible r) -> Bool
+prop_mul (LInv x, LInv y) = fromIntegral (x * y) == (fromIntegral x * fromIntegral y :: r)
+
+prop_recip :: (Field r, Eq r) => Invertible r -> Bool
+prop_recip (Invertible x) = one == (x * recip x)
+
+-- tests that multiplication in the extension ring matches CRT multiplication
+prop_mul_ext :: (CRTEmbed r, Eq r) => (Invertible r, Invertible r) -> Bool
+prop_mul_ext (Invertible x, Invertible y) =
+  let z = x * y
+      z' = fromExt $ toExt x * toExt y
+  in z == z'
+
+data LiftedMod r where
+  LMod :: (ToInteger (ModRep r)) => ModRep r -> LiftedMod r
+
+deriving instance Show (ModRep r) => Show (LiftedMod r)
+
+instance (Mod r, Random (ModRep r), ToInteger (ModRep r))
+  => Random (LiftedMod r) where
+  random = let q = modulus @r
+           in \g -> let (x,g') = randomR (0,q-1) g in (LMod x, g')
+  randomR = error "randomR not defined for `LiftedMod`"
+
+
+data LiftedInvertible r where
+  LInv :: (ToInteger (ModRep r)) => ModRep r -> LiftedInvertible r
+
+deriving instance Show (ModRep r) => Show (LiftedInvertible r)
+
+instance (Mod r, Random (ModRep r), PID (ModRep r), ToInteger (ModRep r))
+  => Random (LiftedInvertible r) where
+  random =
+    let q = modulus @r
+    in \g -> let (x,g') = randomR (1,q-1) g
+             in if gcd x q == 1 then (LInv x, g') else random g'
+  randomR = error "randomR not defined for `LiftedInvertible`"
+
+newtype Invertible r = Invertible r
+
+deriving instance Show r => Show (Invertible r)
+
+instance (Random (LiftedInvertible r), Ring r, ToInteger (ModRep r))
+  => Random (Invertible r) where
+  random g =
+    let (LInv x :: LiftedInvertible r, g') = random g
+    in (Invertible $ fromIntegral x, g')
+  randomR = error "randomR not defined for `Invertible`"
diff --git a/Crypto/Lol/Types.hs b/Crypto/Lol/Types.hs
--- a/Crypto/Lol/Types.hs
+++ b/Crypto/Lol/Types.hs
@@ -3,11 +3,14 @@
 Description : Concrete types needed to instantiate cryptographic applications.
 Copyright   : (c) Eric Crockett, 2011-2017
                   Chris Peikert, 2011-2017
-License     : GPL-2
+License     : GPL-3
 Maintainer  : ecrockett0@email.com
 Stability   : experimental
 Portability : POSIX
 
+  \( \def\Z{\mathbb{Z}} \)
+  \( \def\R{\mathbb{R}} \)
+
 Exports concrete types needed to instantiate cryptographic applications.
 Specifically:
 
@@ -18,10 +21,15 @@
   * "Crypto.Lol.Types.ZqBasic"
 -}
 
-module Crypto.Lol.Types ( module X ) where
+-- EAC: See https://github.com/haskell/haddock/issues/563
+module Crypto.Lol.Types
+( module Crypto.Lol.Types.Random
+, Complex, roundComplex, cis, real, imag, fromReal -- see my comment in the bug report
+, RRq
+, ZqBasic, goodQs) where
 
-import Crypto.Lol.Types.Unsafe.Complex   as X hiding (Complex)
-import Crypto.Lol.Types.IrreducibleChar2 as X ()
-import Crypto.Lol.Types.Random           as X
-import Crypto.Lol.Types.Unsafe.RRq       as X hiding (RRq')
-import Crypto.Lol.Types.Unsafe.ZqBasic   as X hiding (ZqB)
+import Crypto.Lol.Types.IrreducibleChar2 ()
+import Crypto.Lol.Types.Random
+import Crypto.Lol.Types.Unsafe.Complex   hiding (Complex')
+import Crypto.Lol.Types.Unsafe.RRq
+import Crypto.Lol.Types.Unsafe.ZqBasic   hiding (ZqB)
diff --git a/Crypto/Lol/Types/FiniteField.hs b/Crypto/Lol/Types/FiniteField.hs
--- a/Crypto/Lol/Types/FiniteField.hs
+++ b/Crypto/Lol/Types/FiniteField.hs
@@ -3,7 +3,7 @@
 Description : Basic (unoptimized) finite field arithmetic.
 Copyright   : (c) Eric Crockett, 2011-2017
                   Chris Peikert, 2011-2017
-License     : GPL-2
+License     : GPL-3
 Maintainer  : ecrockett0@email.com
 Stability   : experimental
 Portability : POSIX
@@ -23,6 +23,7 @@
 {-# LANGUAGE RebindableSyntax           #-}
 {-# LANGUAGE RoleAnnotations            #-}
 {-# LANGUAGE ScopedTypeVariables        #-}
+{-# LANGUAGE TypeApplications           #-}
 {-# LANGUAGE TypeFamilies               #-}
 {-# LANGUAGE UndecidableInstances       #-}
 
@@ -40,6 +41,8 @@
 import Crypto.Lol.Factored
 import Crypto.Lol.Prelude
 import Crypto.Lol.Reflects
+-- for specialization
+import Crypto.Lol.Types.Unsafe.ZqBasic hiding (ZqB, unZqB)
 
 import Algebra.Additive     as Additive (C)
 import Algebra.Field        as Field (C)
@@ -48,7 +51,7 @@
 import Algebra.ZeroTestable as ZeroTestable (C)
 import MathObj.Polynomial
 
-import Math.NumberTheory.Primes.Factorisation
+import Math.NumberTheory.Primes (factorise, unPrime)
 
 import           Control.Applicative  hiding ((*>))
 import           Control.DeepSeq
@@ -57,7 +60,7 @@
 import qualified Data.Vector          as V
 import           System.Random
 
---import qualified Debug.Trace as DT
+-- import qualified Debug.Trace as DT
 
 -- | A finite field of given degree over \(\F_p\).
 newtype GF fp d = GF (Polynomial fp)
@@ -76,16 +79,17 @@
 instance (GFCtx fp d) => Enumerable (GF fp d) where
   values = GF . fromCoeffs <$>
            -- d-fold cartesian product of Fp values
-           replicateM (proxy value (Proxy::Proxy d)) values
+           replicateM (value @d) values
 
 instance (Random fp, Reflects d Int) => Random (GF fp d) where
-  random = let d = proxy value (Proxy::Proxy d)
-           in runRand $ (GF . fromCoeffs) <$> replicateM d (liftRand random)
+  random = let d = value @d
+           in runRand $ GF . fromCoeffs <$> replicateM d (liftRand random)
   {-# INLINABLE random #-}
 
   randomR _ = error "randomR non-sensical for GF"
 
 instance (GFCtx fp d) => Ring.C (GF fp d) where
+  --{-# SPECIALIZE instance Ring.C (GF (ZqBasic q Int64) d) #-}
 
   one = GF one
 
@@ -100,25 +104,25 @@
           in \(GF f) -> let (_,(a,_)) = extendedGCD f g
                            in GF a
 
-instance (GFCtx fp d) => CRTrans Maybe (GF fp d) where
-
-  crtInfo :: forall m . (Reflects m Int) => TaggedT m Maybe (CRTInfo (GF fp d))
+instance (GFCtx fp d, NFData fp) => CRTrans Maybe (GF fp d) where
+  -- https://ghc.haskell.org/trac/ghc/wiki/Migration/8.2#KindgeneralizationandMonoLocalBinds
+  crtInfo :: forall (m :: k) . (Reflects m Int) => TaggedT m Maybe (CRTInfo (GF fp d))
+  {-# INLINABLE crtInfo #-}
   crtInfo = tagT $ (,) <$> omegaPow <*> scalarInv
     where
       omegaPow :: Maybe (Int -> GF fp d)
       omegaPow =
         let size' = proxy size (Proxy :: Proxy (GF fp d))
-            mval = proxy value (Proxy :: Proxy m)
+            mval = value @m
             (q,r) = (size'-1) `quotRem` mval
             gen = head $ filter isPrimitive values
             omega = gen^q
-            omegaPows = V.iterateN mval (*omega) one
+            omegaPows = force $ V.iterateN mval (*omega) one
         in if r == 0
            then Just $ (omegaPows V.!) . (`mod` mval)
            else Nothing
       scalarInv :: Maybe (GF fp d)
-      scalarInv = Just $ recip $ fromIntegral $ valueHat
-                    (proxy value (Proxy::Proxy m) :: Int)
+      scalarInv = Just $ recip $ fromIntegral $ valueHat (value @m :: Int)
 
 -- | This wrapper for a list of coefficients is used to define a
 -- \(\F_{p^d}\)-module structure for tensors over \(\F_p\) of dimension
@@ -129,12 +133,12 @@
   => Module.C (GF fp d) (TensorCoeffs fp) where
 
   r *> (Coeffs fps) =
-    let dval = proxy value (Proxy::Proxy d)
+    let dval = value @d
         n = length fps
     in if n `mod` dval /= 0 then
                 error $ "FiniteField: d (= " ++ show dval ++
                           ") does not divide n (= " ++ show n ++ ")"
-       else Coeffs $ concat ((toList . (r *) . fromList) <$> chunksOf dval fps)
+       else Coeffs $ concat (toList . (r *) . fromList <$> chunksOf dval fps)
 
 chunksOf :: Int -> [a] -> [[a]]
 chunksOf _ [] = []
@@ -145,21 +149,20 @@
 -- | Yield a list of length exactly \(d\) (i.e., including trailing zeros)
 -- of the \(\F_p\)-coefficients with respect to the power basis.
 toList :: forall fp d . (Reflects d Int, Additive fp) => GF fp d -> [fp]
-toList = let dval = proxy value (Proxy::Proxy d)
+toList = let dval = value @d
          in \(GF p) -> let l = coeffs p
                        in l ++ replicate (dval - length l) zero
 
 -- | Yield a field element given up to \(d\) coefficients with respect
 -- to the power basis.
 fromList :: forall fp d . (Reflects d Int) => [fp] -> GF fp d
-fromList = let dval = proxy value (Proxy::Proxy d)
+fromList = let dval = value @d
            in \cs -> if length cs <= dval then GF $ fromCoeffs cs
                      else error $ "FiniteField.fromList: length " ++
                               show (length cs) ++ " > degree " ++ show dval
 
 sizePP :: forall fp d . (GFCtx fp d) => Tagged (GF fp d) PP
-sizePP = tag (proxy valuePrime (Proxy::Proxy (CharOf fp)),
-              proxy value (Proxy::Proxy d))
+sizePP = tag (valuePrime @(CharOf fp), value @d)
 
 -- | The order of the field: @size (GF fp d) = @\( p^d \)
 size :: (GFCtx fp d) => Tagged (GF fp d) Int
@@ -167,7 +170,7 @@
 
 isPrimitive :: forall fp d . (GFCtx fp d) => GF fp d -> Bool
 isPrimitive = let q = proxy size (Proxy :: Proxy (GF fp d))
-                  ps = map (fromIntegral . fst) $ factorise $
+                  ps = map (fromIntegral . unPrime . fst) $ factorise @Integer $
                        fromIntegral $ q-1
                   exps = map ((q-1) `div`) ps
               in \g -> not (isZero g) && all (\e -> g^e /= 1) exps
@@ -177,18 +180,17 @@
 
 -- | Trace into the prime subfield.
 trace :: forall fp d . (GFCtx fp d) => GF fp d -> fp
+{-# SPECIALIZE trace :: (Prime p, Reflects d Int, Reflects p Int64, IrreduciblePoly (ZqBasic p Int64)) => GF (ZqBasic p Int64) d -> ZqBasic p Int64 #-}
 trace = let ts = proxy powTraces (Proxy::Proxy (GF fp d))
         in \(GF f) -> dotp ts (coeffs f)
 
 -- | Traces of the power basis elements \(\{1, x, x^2, \ldots, x^{d-1}\}\).
 powTraces :: forall fp d . (GFCtx fp d) => Tagged (GF fp d) [fp]
 powTraces =
-  --DT.trace ("FiniteField.powTraces: p = " ++
-  --          show (proxy value (Proxy::Proxy (CharOf fp)) :: Int) ++
-  --          ", d = " ++ show (proxy value (Proxy::Proxy d) :: Int)) $
-  let d = proxy value (Proxy :: Proxy d)
-  in tag $ map trace' $ take d $
-     iterate (* GF (X ^^ 1)) (one :: GF fp d)
+  {-DT.trace ("FiniteField.powTraces: p = " ++-}
+            {-show (valuePrime @(CharOf fp) :: Int) ++-}
+            {-", d = " ++ show (value @d :: Int)) $-}
+  tag $ map trace' $ take (value @d) $ iterate (* GF (X ^^ 1)) (one :: GF fp d)
 
 -- helper that computes trace via brute force: sum frobenius
 -- automorphisms
diff --git a/Crypto/Lol/Types/IFunctor.hs b/Crypto/Lol/Types/IFunctor.hs
new file mode 100644
--- /dev/null
+++ b/Crypto/Lol/Types/IFunctor.hs
@@ -0,0 +1,17 @@
+{-# LANGUAGE TypeFamilies #-}
+
+module Crypto.Lol.Types.IFunctor
+where
+
+import Crypto.Lol.Factored
+
+import Data.Constraint
+
+class IFunctor f where
+  type IFElt f a :: Constraint
+
+  fmapI :: (IFElt f a, IFElt f b, Fact m) => (a -> b) -> f m a -> f m b
+
+  zipWithI :: (IFElt f a, IFElt f b, IFElt f c, Fact m)
+    => (a -> b -> c) -> f m a -> f m b -> f m c
+
diff --git a/Crypto/Lol/Types/IZipVector.hs b/Crypto/Lol/Types/IZipVector.hs
--- a/Crypto/Lol/Types/IZipVector.hs
+++ b/Crypto/Lol/Types/IZipVector.hs
@@ -3,8 +3,8 @@
 Description : Provides applicative-like functions for indexed vectors.
 Copyright   : (c) Eric Crockett, 2011-2017
                   Chris Peikert, 2011-2017
-License     : GPL-2
-Maintainer  : ecrockett0@email.com
+License     : GPL-3
+Maintainer  : ecrockett0@gmail.com
 Stability   : experimental
 Portability : POSIX
 
@@ -15,15 +15,16 @@
 {-# LANGUAGE DataKinds                  #-}
 {-# LANGUAGE DeriveTraversable          #-}
 {-# LANGUAGE FlexibleContexts           #-}
+{-# LANGUAGE FlexibleInstances          #-}
 {-# LANGUAGE GeneralizedNewtypeDeriving #-}
 {-# LANGUAGE KindSignatures             #-}
-{-# LANGUAGE FlexibleInstances          #-}
 {-# LANGUAGE MultiParamTypeClasses      #-}
 {-# LANGUAGE PolyKinds                  #-}
 {-# LANGUAGE RebindableSyntax           #-}
 {-# LANGUAGE RecordWildCards            #-}
 {-# LANGUAGE RoleAnnotations            #-}
 {-# LANGUAGE ScopedTypeVariables        #-}
+{-# LANGUAGE TypeApplications           #-}
 {-# LANGUAGE TypeFamilies               #-}
 {-# LANGUAGE UndecidableInstances       #-}
 
@@ -31,16 +32,17 @@
 ( IZipVector, iZipVector, unIZipVector, unzipIZV
 ) where
 
-import Crypto.Lol.Prelude as LP
+import Crypto.Lol.Prelude              as LP
 import Crypto.Lol.Reflects
 import Crypto.Lol.Types.Proto
 import Crypto.Lol.Types.Unsafe.RRq
 import Crypto.Lol.Types.Unsafe.ZqBasic
 
-import Crypto.Proto.Lol.Kq1
+import Crypto.Proto.Lol.K
+import Crypto.Proto.Lol.Kq
 import Crypto.Proto.Lol.KqProduct
 import Crypto.Proto.Lol.R
-import Crypto.Proto.Lol.Rq1
+import Crypto.Proto.Lol.Rq
 import Crypto.Proto.Lol.RqProduct
 
 import Algebra.ZeroTestable as ZeroTestable
@@ -50,11 +52,11 @@
 import Control.Monad
 import Control.Monad.Except
 
-import Data.Foldable as F
-import Data.Sequence as S
+import Data.Foldable    as F
+import Data.Sequence    as S
 import Data.Traversable
 
-import Data.Vector (Vector)
+import           Data.Vector (Vector)
 import qualified Data.Vector as V
 
 
@@ -76,7 +78,7 @@
 -- | Smart constructor that checks whether length of input is right
 -- (should be totient of @m@).
 iZipVector :: forall m a . (Fact m) => Vector a -> Maybe (IZipVector m a)
-iZipVector = let n = proxy totientFact (Proxy::Proxy m)
+iZipVector = let n = totientFact @m
             in \vec -> if n == V.length vec
                        then Just $ IZipVector vec
                        else Nothing
@@ -91,7 +93,7 @@
 
 -- don't export
 repl :: forall m a . (Fact m) => a -> IZipVector m a
-repl = let n = proxy totientFact (Proxy::Proxy m)
+repl = let n = totientFact @m
        in IZipVector . V.replicate n
 
 -- Zip-py 'Applicative' instance.
@@ -107,13 +109,13 @@
   type ProtoType (IZipVector m Int64) = R
 
   toProto (IZipVector xs') =
-    let m = fromIntegral $ proxy valueFact (Proxy::Proxy m)
+    let m = fromIntegral $ valueFact @m
         xs = S.fromList $ V.toList xs'
     in R{..}
 
   fromProto R{..} = do
-    let m' = proxy valueFact (Proxy::Proxy m) :: Int
-        n = proxy totientFact (Proxy::Proxy m)
+    let m' = valueFact @m :: Int
+        n  = totientFact @m
         ys' = V.fromList $ F.toList xs
         len = F.length xs
     unless (m' == fromIntegral m) $ throwError $
@@ -124,24 +126,45 @@
       \Expected n=" ++ show n  ++ ", got " ++ show len
     return $ IZipVector ys'
 
+instance (Fact m) => Protoable (IZipVector m Double) where
+  type ProtoType (IZipVector m Double) = K
+
+  toProto (IZipVector xs') =
+    let m = fromIntegral $ valueFact @m
+        xs = S.fromList $ V.toList xs'
+    in K{..}
+
+  fromProto K{..} = do
+    let m' = valueFact @m :: Int
+        n  = totientFact @m
+        ys' = V.fromList $ F.toList xs
+        len = F.length xs
+    unless (m' == fromIntegral m) $ throwError $
+      "An error occurred while reading the proto type for CT.\n\
+      \Expected m=" ++ show m' ++ ", got " ++ show m
+    unless (len == n) $ throwError $
+      "An error occurred while reading the proto type for CT.\n\
+      \Expected n=" ++ show n  ++ ", got " ++ show len
+    return $ IZipVector ys'
+
 instance (Fact m, Reflects q Int64) => Protoable (IZipVector m (ZqBasic q Int64)) where
   type ProtoType (IZipVector m (ZqBasic q Int64)) = RqProduct
 
   toProto (IZipVector xs') =
-    let m = fromIntegral $ proxy valueFact (Proxy::Proxy m)
-        q = fromIntegral (proxy value (Proxy::Proxy q) :: Int64)
+    let m = fromIntegral $ valueFact @m
+        q = fromIntegral (value @q :: Int64)
         xs = S.fromList $ V.toList $ V.map LP.lift xs'
-    in RqProduct $ S.singleton Rq1{..}
+    in RqProduct $ S.singleton Rq{..}
 
   fromProto (RqProduct xs') = do
-    let rqlist = F.toList xs'
-        m' = proxy valueFact (Proxy::Proxy m) :: Int
-        q' = proxy value (Proxy::Proxy q) :: Int64
-        n = proxy totientFact (Proxy::Proxy m)
-    unless (F.length rqlist == 1) $ throwError $
+    let rqs = F.toList xs'
+        m' = valueFact @m :: Int
+        q' = value @q :: Int64
+        n  = totientFact @m
+    unless (F.length rqs == 1) $ throwError $
       "An error occurred while reading the proto type for CT.\n\
-      \Expected a list of one Rq, but list has length " ++ show (F.length rqlist)
-    let [Rq1{..}] = rqlist
+      \Expected one Rq, but list has length " ++ show (F.length rqs)
+    let [Rq{..}] = rqs
         ys' = V.fromList $ F.toList xs
         len = F.length xs
     unless (m' == fromIntegral m) $ throwError $
@@ -159,20 +182,20 @@
   type ProtoType (IZipVector m (RRq q Double)) = KqProduct
 
   toProto (IZipVector xs') =
-    let m = fromIntegral $ proxy valueFact (Proxy::Proxy m)
-        q = round (proxy value (Proxy::Proxy q) :: Double)
+    let m = fromIntegral $ valueFact @m
+        q = round (value @q :: Double)
         xs = S.fromList $ V.toList $ V.map LP.lift xs'
-    in KqProduct $ S.singleton Kq1{..}
+    in KqProduct $ S.singleton Kq{..}
 
   fromProto (KqProduct xs') = do
-    let rqlist = F.toList xs'
-        m' = proxy valueFact (Proxy::Proxy m) :: Int
-        q' = round (proxy value (Proxy::Proxy q) :: Double)
-        n = proxy totientFact (Proxy::Proxy m)
-    unless (F.length rqlist == 1) $ throwError $
+    let rqs = F.toList xs'
+        m' = valueFact @m :: Int
+        q' = round (value @q :: Double)
+        n  = totientFact @m
+    unless (F.length rqs == 1) $ throwError $
       "An error occurred while reading the proto type for CT.\n\
-      \Expected a list of one Rq, but list has length " ++ show (F.length rqlist)
-    let [Kq1{..}] = rqlist
+      \Expected one Rq, but list has length " ++ show (F.length rqs)
+    let [Kq{..}] = rqs
         ys' = V.fromList $ F.toList xs
         len = F.length xs
     unless (m' == fromIntegral m) $ throwError $
@@ -192,8 +215,8 @@
   => Protoable (IZipVector m (ZqBasic q Int64,b)) where
   type ProtoType (IZipVector m (ZqBasic q Int64, b)) = RqProduct
 
-  toProto = toProtoProduct RqProduct rqlist
-  fromProto = fromProtoNestRight RqProduct rqlist
+  toProto = toProtoProduct RqProduct rqs
+  fromProto = fromProtoNestRight RqProduct rqs
 
 instance (Protoable (IZipVector m (RRq q Double)),
           ProtoType (IZipVector m (RRq q Double)) ~ KqProduct,
@@ -201,8 +224,8 @@
   => Protoable (IZipVector m (RRq q Double,b)) where
   type ProtoType (IZipVector m (RRq q Double, b)) = KqProduct
 
-  toProto = toProtoProduct KqProduct kqlist
-  fromProto = fromProtoNestRight KqProduct kqlist
+  toProto = toProtoProduct KqProduct kqs
+  fromProto = fromProtoNestRight KqProduct kqs
 
 toProtoProduct :: forall m a b c .
   (Protoable (IZipVector m a), Protoable (IZipVector m b),
diff --git a/Crypto/Lol/Types/IrreducibleChar2.hs b/Crypto/Lol/Types/IrreducibleChar2.hs
--- a/Crypto/Lol/Types/IrreducibleChar2.hs
+++ b/Crypto/Lol/Types/IrreducibleChar2.hs
@@ -3,7 +3,7 @@
 Description : Orphan instance of 'IrreduciblePoly' for characteristic-2 fields.
 Copyright   : (c) Eric Crockett, 2011-2017
                   Chris Peikert, 2011-2017
-License     : GPL-2
+License     : GPL-3
 Maintainer  : ecrockett0@email.com
 Stability   : experimental
 Portability : POSIX
@@ -11,25 +11,31 @@
 Orphan instance of 'IrreduciblePoly' for characteristic-2 fields.
 -}
 
-{-# LANGUAGE FlexibleInstances    #-}
-{-# LANGUAGE PolyKinds            #-}
-{-# LANGUAGE RebindableSyntax     #-}
-{-# LANGUAGE ScopedTypeVariables  #-}
-{-# LANGUAGE TypeFamilies         #-}
-{-# LANGUAGE UndecidableInstances #-}
+{-# LANGUAGE FlexibleContexts      #-}
+{-# LANGUAGE FlexibleInstances     #-}
+{-# LANGUAGE InstanceSigs          #-}
+{-# LANGUAGE MultiParamTypeClasses #-}
+{-# LANGUAGE PolyKinds             #-}
+{-# LANGUAGE RebindableSyntax      #-}
+{-# LANGUAGE ScopedTypeVariables   #-}
+{-# LANGUAGE TypeApplications      #-}
+{-# LANGUAGE TypeFamilies          #-}
+{-# LANGUAGE UndecidableInstances  #-}
 
 module Crypto.Lol.Types.IrreducibleChar2 () where
 
-import Crypto.Lol.Prelude hiding (lookup)
+import Crypto.Lol.Prelude           hiding (lookup)
 import Crypto.Lol.Reflects
 import Crypto.Lol.Types.FiniteField hiding (fromList)
 
-import Data.Map hiding (map)
+import Data.Map   hiding (map)
 import Data.Maybe (fromMaybe)
 
 instance (CharOf a ~ Prime2, Field a) => IrreduciblePoly a where
+  -- https://ghc.haskell.org/trac/ghc/wiki/Migration/8.2#KindgeneralizationandMonoLocalBinds
+  irreduciblePoly :: forall (d :: k) . (Reflects d Int) => Tagged d (Polynomial a)
   irreduciblePoly = do
-    n <- value
+    let n = value @d
     return $ flip fromMaybe (lookup n polyMap) $ error $
       "The IrreduciblePoly instance for N2 included with the library " ++
       "(and exported by Crypto.Lol) only contains irreducible polynomials " ++
@@ -41,7 +47,7 @@
 polyMap = fromList $ map (\xs -> (head xs, coeffsToPoly xs)) coeffs
 
 coeffsToPoly :: (Ring fp) => [Int] -> Polynomial fp
-coeffsToPoly xs = (sum $ map (X^^) xs) + 1
+coeffsToPoly xs = sum (map (X^^) xs) + 1
 
 -- The list below is small portion of the table
 -- "Table of Low-Weight binary Irreducible Polynomials" at
diff --git a/Crypto/Lol/Types/Numeric.hs b/Crypto/Lol/Types/Numeric.hs
--- a/Crypto/Lol/Types/Numeric.hs
+++ b/Crypto/Lol/Types/Numeric.hs
@@ -3,7 +3,7 @@
 Description : Modifications to NumericPrelude for Lol.
 Copyright   : (c) Eric Crockett, 2011-2017
                   Chris Peikert, 2011-2017
-License     : GPL-2
+License     : GPL-3
 Maintainer  : ecrockett0@email.com
 Stability   : experimental
 Portability : POSIX
diff --git a/Crypto/Lol/Types/Proto.hs b/Crypto/Lol/Types/Proto.hs
--- a/Crypto/Lol/Types/Proto.hs
+++ b/Crypto/Lol/Types/Proto.hs
@@ -3,7 +3,7 @@
 Description : Convenient interfaces for serialization with protocol buffers.
 Copyright   : (c) Eric Crockett, 2011-2017
                   Chris Peikert, 2011-2017
-License     : GPL-2
+License     : GPL-3
 Maintainer  : ecrockett0@email.com
 Stability   : experimental
 Portability : POSIX
diff --git a/Crypto/Lol/Types/Random.hs b/Crypto/Lol/Types/Random.hs
--- a/Crypto/Lol/Types/Random.hs
+++ b/Crypto/Lol/Types/Random.hs
@@ -3,7 +3,7 @@
 Description : Types for using crypto-api with MonadCryptoRandom.
 Copyright   : (c) Eric Crockett, 2011-2017
                   Chris Peikert, 2011-2017
-License     : GPL-2
+License     : GPL-3
 Maintainer  : ecrockett0@email.com
 Stability   : experimental
 Portability : POSIX
diff --git a/Crypto/Lol/Types/Unsafe/Complex.hs b/Crypto/Lol/Types/Unsafe/Complex.hs
--- a/Crypto/Lol/Types/Unsafe/Complex.hs
+++ b/Crypto/Lol/Types/Unsafe/Complex.hs
@@ -3,7 +3,7 @@
 Description : Data type, functions, and instances for complex numbers.
 Copyright   : (c) Eric Crockett, 2011-2017
                   Chris Peikert, 2011-2017
-License     : GPL-2
+License     : GPL-3
 Maintainer  : ecrockett0@email.com
 Stability   : experimental
 Portability : POSIX
@@ -21,11 +21,10 @@
 {-# LANGUAGE MultiParamTypeClasses      #-}
 {-# LANGUAGE RebindableSyntax           #-}
 {-# LANGUAGE ScopedTypeVariables        #-}
-{-# LANGUAGE StandaloneDeriving         #-}
 {-# LANGUAGE TypeFamilies               #-}
 
-module Crypto.Lol.Types.Unsafe.Complex (
-  Complex(..)
+module Crypto.Lol.Types.Unsafe.Complex
+( Complex(..)
 , roundComplex
 , cis, real, imag, fromReal
 ) where
@@ -45,7 +44,7 @@
 
 -- | Newtype wrapper (with slightly different instances) for
 -- @Number.Complex@.
-newtype Complex a = Complex (C.T a)
+newtype Complex a = Complex' (C.T a)
     deriving (Additive.C, Ring.C, ZeroTestable.C, Field.C, Eq, Show)
 
 -- | Custom instance replacing the one provided by numeric prelude: it
@@ -53,38 +52,38 @@
 -- sometimes has precision issues, because it yields nonzero
 -- remainders, which is a problem for 'divG' methods.)
 instance (Field a) => IntegralDomain.C (Complex a) where
-  (Complex a) `divMod` (Complex b) = (Complex $ a / b, LP.zero)
+  (Complex' a) `divMod` (Complex' b) = (Complex' $ a / b, LP.zero)
 
 -- we can't use Generics for NFData because NP doesn't export the
 -- (deep) constructor for Complex.T
 instance (NFData a) => NFData (Complex a) where
-  rnf (Complex x) = let r = C.real x
-                        i = C.imag x
-                    in rnf r `seq` rnf i `seq` ()
+  rnf (Complex' x) = let r = C.real x
+                         i = C.imag x
+                     in rnf r `seq` rnf i `seq` ()
 
 instance (Random a) => Random (Complex a) where
     random g = let (a,g') = random g
                    (b,g'') = random g'
-               in (Complex $ a C.+: b, g'')
+               in (Complex' $ a C.+: b, g'')
 
     randomR = error "randomR not defined for (Complex t)"
 
 -- | Rounds the real and imaginary components to the nearest integer.
 roundComplex :: (RealRing a, ToInteger b) => Complex a -> (b,b)
-roundComplex (Complex x) = (round $ C.real x, round $ C.imag x)
+roundComplex (Complex' x) = (round $ C.real x, round $ C.imag x)
 
 -- | 'cis' \(t\) is a complex value with magnitude 1 and phase \(t \bmod 2\cdot\pi\)).
 cis :: Transcendental a => a -> Complex a
-cis = Complex . C.cis
+cis = Complex' . C.cis
 
 -- | Real component of a complex number.
 real :: Complex a -> a
-real (Complex a) = C.real a
+real (Complex' a) = C.real a
 
 -- | Imaginary component of a complex number.
 imag :: Complex a -> a
-imag (Complex a) = C.imag a
+imag (Complex' a) = C.imag a
 
 -- | Embeds a scalar as the real component of a complex number.
 fromReal :: Additive a => a -> Complex a
-fromReal = Complex . C.fromReal
+fromReal = Complex' . C.fromReal
diff --git a/Crypto/Lol/Types/Unsafe/RRq.hs b/Crypto/Lol/Types/Unsafe/RRq.hs
--- a/Crypto/Lol/Types/Unsafe/RRq.hs
+++ b/Crypto/Lol/Types/Unsafe/RRq.hs
@@ -3,8 +3,8 @@
 Description : An implementation of modular arithmetic over the reals.
 Copyright   : (c) Eric Crockett, 2011-2017
                   Chris Peikert, 2011-2017
-License     : GPL-2
-Maintainer  : ecrockett0@email.com
+License     : GPL-3
+Maintainer  : ecrockett0@gmail.com
 Stability   : experimental
 Portability : POSIX
 
@@ -25,6 +25,7 @@
 {-# LANGUAGE PolyKinds                  #-}
 {-# LANGUAGE RebindableSyntax           #-}
 {-# LANGUAGE ScopedTypeVariables        #-}
+{-# LANGUAGE TypeApplications           #-}
 {-# LANGUAGE TypeFamilies               #-}
 {-# LANGUAGE UndecidableInstances       #-}
 
@@ -36,53 +37,48 @@
 import Algebra.ZeroTestable as ZeroTestable (C)
 
 import Control.DeepSeq
+import System.Random
 
 import Crypto.Lol.Prelude
 import Crypto.Lol.Reflects
 import Crypto.Lol.Types.Unsafe.ZqBasic hiding (ZqB)
 
--- invariant: 0 <= x < q
--- | The ring \(\R/(q\Z)\) of reals modulo 'q', using
--- underlying floating type 'r'.
-newtype RRq q r = RRq' r
-    deriving (Eq, Ord, ZeroTestable.C, Show, NFData)
+-- invariant: 0 <= x < 1, scaled
+-- | The additive group \( \R/(q\Z) \) of reals modulo 'q', using
+-- underlying floating-point type 'r'.
+newtype RRq q r = RRq r
+    deriving (Eq, ZeroTestable.C, Show, NFData)
 
-{-# INLINABLE reduce' #-}
-reduce' :: forall q r . (Reflects q r, RealField r) => r -> RRq q r
-reduce' = let q = proxy value (Proxy::Proxy q)
-          in \x -> RRq' $ x - q * floor (x / q)
+instance RealField r => Additive.C (RRq q r) where
+  {-# INLINABLE zero #-}
+  zero = RRq zero
 
--- puts value in range [-q/2, q/2)
-decode' :: forall q r . (Reflects q r, Ord r, Ring r)
-           => RRq q r -> r
-decode' = let qval = proxy value (Proxy::Proxy q)
-          in \(RRq' x) -> if x + x < qval then x else x - qval
+  {-# INLINABLE (+) #-}
+  (RRq x) + (RRq y) = RRq $ fraction $ x + y
 
-instance (Reflects q r, RealField r, Additive (RRq q r))
-  => Reduce r (RRq q r) where
+  {-# INLINABLE negate #-}
+  negate (RRq x) = RRq $ fraction $ negate x
+
+reduce' :: forall q r . (Reflects q r, RealField r) => r -> RRq q r
+reduce' r = RRq $ fraction $ r / value @q -- scale down
+
+instance (Reflects q r, RealField r) => Reduce r (RRq q r) where
   reduce = reduce'
 
 type instance LiftOf (RRq q r) = r
 
-instance (Reflects q r, Reduce r (RRq q r), Ord r, Ring r)
+instance (Reflects q r, Field r, Reduce r (RRq q r))
   => Lift' (RRq q r) where
-  lift = decode'
-
--- instance of Additive
-instance (Reflects q r, RealField r, Ord r) => Additive.C (RRq q r) where
-
-  {-# INLINABLE zero #-}
-  zero = RRq' zero
+  lift (RRq r) = (r-0.5) * value @q
 
-  {-# INLINABLE (+) #-}
-  (+) = let qval = proxy value (Proxy::Proxy q)
-        in \ (RRq' x) (RRq' y) ->
-        let z = x + y
-        in RRq' (if z >= qval then z - qval else z)
+instance (Additive (RRq q r), Additive (RRq p r))
+  => Rescale (RRq q r) (RRq p r) where
+  rescale (RRq r) = RRq r
 
-  {-# INLINABLE negate #-}
-  negate (RRq' x) = reduce' $ negate x
+instance Random (RRq q Double) where
+  random g = let (r,g') = random g in (RRq r, g')
+  randomR = error "randomR is nonsensical for RRq"
 
-instance (ToInteger i, RealField r, Reflects q i, Reflects q r)
-  => Subgroup (ZqBasic q i) (RRq q r) where
+instance (ToInteger z, RealField r, Reflects q z, Reflects q r)
+  => Subgroup (ZqBasic q z) (RRq q r) where
   fromSubgroup = reduce' . fromIntegral . lift
diff --git a/Crypto/Lol/Types/Unsafe/ZqBasic.hs b/Crypto/Lol/Types/Unsafe/ZqBasic.hs
--- a/Crypto/Lol/Types/Unsafe/ZqBasic.hs
+++ b/Crypto/Lol/Types/Unsafe/ZqBasic.hs
@@ -3,7 +3,7 @@
 Description : An implementation of modular arithmetic over the integers.
 Copyright   : (c) Eric Crockett, 2011-2017
                   Chris Peikert, 2011-2017
-License     : GPL-2
+License     : GPL-3
 Maintainer  : ecrockett0@email.com
 Stability   : experimental
 Portability : POSIX
@@ -11,17 +11,14 @@
   \( \def\Z{\mathbb{Z}} \)
   \( \def\C{\mathbb{C}} \)
 
-An implementation of the quotient ring \(\Z_q = \Z/(q\Z)\).
-This module is "unsafe" because it exports the 'ZqBasic' constructor.
-This module should only be used to make tensor-specific instances for 'ZqBasic'.
-The safe way to use this type is to import "Crypto.Lol.Types".
-
-EAC: It may help GHC do specialization at higher levels of the library
-if we "simplify" constraints in this module. For example, replace the
-(Additive (ZqBasic q z)) constraint on the Reduce instance with
-(Additive z)
+An implementation of the quotient ring \(\Z_q = \Z/(q\Z)\).  This
+module is "unsafe" because it exports the 'ZqBasic' constructor.  This
+module should only be used to make tensor-specific instances for
+'ZqBasic'.  The safe way to use this type is to import
+"Crypto.Lol.Types".
 -}
 
+{-# LANGUAGE AllowAmbiguousTypes        #-}
 {-# LANGUAGE ConstraintKinds            #-}
 {-# LANGUAGE DataKinds                  #-}
 {-# LANGUAGE FlexibleContexts           #-}
@@ -32,33 +29,31 @@
 {-# LANGUAGE RebindableSyntax           #-}
 {-# LANGUAGE RoleAnnotations            #-}
 {-# LANGUAGE ScopedTypeVariables        #-}
+{-# LANGUAGE TypeApplications           #-}
 {-# LANGUAGE TypeFamilies               #-}
+{-# LANGUAGE TypeOperators              #-}
 {-# LANGUAGE UndecidableInstances       #-}
 
 module Crypto.Lol.Types.Unsafe.ZqBasic
-( ZqBasic(..) -- export the type, but not the constructor (for safety)
+( ZqBasic(..) -- export constructor from this (unsafe) module
 , goodQs
 ) where
 
 import Crypto.Lol.CRTrans
 import Crypto.Lol.Gadget
-import Crypto.Lol.Prelude           as LP
+import Crypto.Lol.Prelude  as LP
 import Crypto.Lol.Reflects
-import Crypto.Lol.Types.FiniteField
-import Crypto.Lol.Types.ZPP
 
-import Math.NumberTheory.Primes.Factorisation
-import Math.NumberTheory.Primes.Testing
+import Math.NumberTheory.Primes
 
 import Control.Applicative
 import Control.Arrow
-import Control.DeepSeq        (NFData)
-import Data.Coerce
+import Control.DeepSeq        (NFData, force)
 import Data.Maybe
 import NumericPrelude.Numeric as NP (round)
 import System.Random
 
-import qualified Data.Vector                 as V
+import qualified Data.Vector as V
 
 import qualified Algebra.Additive       as Additive (C)
 import qualified Algebra.Field          as Field (C)
@@ -66,15 +61,16 @@
 import qualified Algebra.Ring           as Ring (C)
 import qualified Algebra.ZeroTestable   as ZeroTestable (C)
 
--- an infinite list of primes greater than the input and congruent to
--- 1 mod m
-goodQs :: (IntegralDomain a, ToInteger a) => a -> a -> [a]
-goodQs m lower = filter (isPrime . toInteger) $
+-- | An infinite list of primes greater than @lower@ and congruent to
+-- 1 mod @m@.
+goodQs :: (ToInteger a) => a -> a -> [a]
+goodQs m lower = filter (isJust . isPrime . toInteger) $
   iterate (+m) $ lower + ((m-lower) `mod` m) + 1
+{-# SPECIALIZE goodQs :: Int64 -> Int64 -> [Int64] #-}
 
 -- | The ring \(\Z_q\) of integers modulo 'q', using underlying integer
 -- type 'z'.
-newtype ZqBasic q z = ZqB z
+newtype ZqBasic q z = ZqB { unZqB :: z }
     deriving (Eq, Ord, ZeroTestable.C, Show, NFData)
 
 -- the q argument, though phantom, matters for safety
@@ -84,56 +80,56 @@
 --deriving instance (U.Unbox i) => M.MVector U.MVector (ZqBasic q i)
 --deriving instance (U.Unbox i) => U.Unbox (ZqBasic q i)
 
+reduce' :: forall q z . (Reflects q z, IntegralDomain z) => z -> ZqBasic q z
+reduce' = ZqB . (`mod` value @q)
 {-# INLINABLE reduce' #-}
-reduce' :: forall q z . (Reflects q z, ToInteger z) => z -> ZqBasic q z
-reduce' = ZqB . (`mod` proxy value (Proxy::Proxy q))
 
 -- puts value in range [-q/2, q/2)
-decode' :: forall q z . (Reflects q z, ToInteger z) => ZqBasic q z -> z
-decode' = let qval = proxy value (Proxy::Proxy q)
+decode' :: forall q z . (Reflects q z, Ring z, Ord z) => ZqBasic q z -> z
+decode' = let qval = value @q
           in \(ZqB x) -> if 2 * x < qval then x else x - qval
+{-# INLINABLE decode' #-}
 
-instance (Reflects q z, ToInteger z, Enum z) => Enumerable (ZqBasic q z) where
-  values = let qval :: z = proxy value (Proxy::Proxy q)
-           in coerce [0..(qval-1)]
+instance (Reflects q z, Ring z, Enum z) => Enumerable (ZqBasic q z) where
+  {-# SPECIALIZE instance (Reflects q Int64) => Enumerable (ZqBasic q Int64) #-}
+  values = ZqB <$> [0..(value @q - 1)]
 
 instance (Reflects q z, ToInteger z) => Mod (ZqBasic q z) where
+  {-# SPECIALIZE instance (Reflects q Int64) => Mod (ZqBasic q Int64) #-}
   type ModRep (ZqBasic q z) = z
 
-  modulus = retag (value :: Tagged q z)
+  modulus = value @q
 
 type instance CharOf (ZqBasic p z) = p
 
-instance (PPow pp, zq ~ ZqBasic pp z,
-          PrimeField (ZpOf zq), Ring zq)
-         => ZPP (ZqBasic (pp :: PrimePower) z) where
-
-  type ZpOf (ZqBasic pp z) = ZqBasic (PrimePP pp) z
-
-  modulusZPP = retag (ppPPow :: Tagged pp PP)
-  liftZp = coerce
-
-instance (Reflects q z, ToInteger z) => Reduce z (ZqBasic q z) where
+instance (Reflects q z, IntegralDomain z) => Reduce z (ZqBasic q z) where
+  {-# SPECIALIZE instance (Reflects q Int64) => Reduce Int64 (ZqBasic q Int64) #-}
   reduce = reduce'
 
-instance (Reflects q z, ToInteger z, Additive (ZqBasic q z)) => Reduce Integer (ZqBasic q z) where
+instance {-# OVERLAPPING #-} (Reflects q z, ToInteger z) => Reduce Integer (ZqBasic q z) where
+  {-# SPECIALIZE instance (Reflects q Int64) => Reduce Integer (ZqBasic q Int64) #-}
   reduce = fromInteger
 
 type instance LiftOf (ZqBasic q z) = z
 
-instance (Reflects q z, ToInteger z) => Lift' (ZqBasic q z) where
+instance (Reflects q z, Ring z, Ord z, IntegralDomain z)
+  => Lift' (ZqBasic q z) where
+  {-# SPECIALIZE instance (Reflects q Int64) => Lift' (ZqBasic q Int64) #-}
   lift = decode'
 
 instance (Reflects q z, ToInteger z, Reflects q' z, Ring z)
          => Rescale (ZqBasic q z) (ZqBasic q' z) where
+  {-# SPECIALIZE instance (Reflects q Int64, Reflects q' Int64) => Rescale (ZqBasic q Int64) (ZqBasic q' Int64) #-}
 
   rescale = rescaleMod
 
-instance (Reflects p z, Reflects q z, ToInteger z, Field (ZqBasic q z), Field (ZqBasic p z))
+instance (Reflects p z, Reflects q z, IntegralDomain z,
+          Field (ZqBasic q z), Field (ZqBasic p z))
          => Encode (ZqBasic p z) (ZqBasic q z) where
+  {-# SPECIALIZE instance (Reflects p Int64, Reflects q Int64) => Encode (ZqBasic p Int64) (ZqBasic q Int64) #-}
 
-  lsdToMSD = let pval :: z = proxy value (Proxy::Proxy p)
-                 negqval :: z = negate $ proxy value (Proxy::Proxy q)
+  lsdToMSD = let pval = value @p
+                 negqval = negate $ value @q
              in (reduce' negqval, recip $ reduce' pval)
 
 -- | Yield a /principal/ \(m\)th root of unity \(\omega_m \in \Z_q^*\).
@@ -141,100 +137,108 @@
 -- generator of \(\Z_q^*\) and raising it to the \( (q-1)/m\) power.
 -- Therefore, outputs for different values of \(m\) are consistent,
 -- i.e., \(\omega_{m'}^(m'/m) = \omega_m\).
-principalRootUnity ::
-    forall m q z . (Reflects m Int, Reflects q z, ToInteger z, Enumerable (ZqBasic q z))
-               => TaggedT m Maybe (Int -> ZqBasic q z)
+principalRootUnity :: forall m q z .
+  (Reflects m Int, Reflects q z, ToInteger z, Enum z, NFData z)
+  => TaggedT m Maybe (Int -> ZqBasic q z)
 principalRootUnity =        -- use Integers for all intermediate calcs
-  let qval = fromIntegral (proxy value (Proxy::Proxy q) :: z)
-      mval = proxy value (Proxy::Proxy m)
+  let qval = fromIntegral (value @q :: z)
+      mval = value @m
       -- order of Zq^* (assuming q prime)
       order = qval-1
       -- the primes dividing the order of Zq^*
-      pfactors = fst <$> factorise order
+      pfactors = unPrime . fst <$> (factorise @Integer) order
       -- the powers we need to check
       exps = div order <$> pfactors
       -- whether an element is a generator of Zq^*
       isGen x = (x^order == one) && all (\e -> x^e /= one) exps
-  in tagT $ if isPrime qval -- for simplicity, require q to be prime
+   in tagT $ if isJust (isPrime qval) -- for simplicity, require q to be prime
             then let (mq,mr) = order `divMod` fromIntegral mval
                  in if mr == 0
                     then let omega = head (filter isGen values) ^ mq
-                             omegaPows = V.iterateN mval (*omega) one
+                             omegaPows = force $ V.iterateN mval (*omega) one
                          in Just $ (omegaPows V.!) . (`mod` mval)
                     else Nothing
             else Nothing       -- fail if q composite
 
 mhatInv :: forall m q z . (Reflects m Int, Reflects q z, ToInteger z, PID z)
            => TaggedT m Maybe (ZqBasic q z)
-mhatInv = let qval = proxy value (Proxy::Proxy q)
-          in peelT $ (fmap reduce' . (`modinv` qval) . fromIntegral) <$>
-                 valueHat <$> (value :: Tagged m Int)
+mhatInv = tagT $ reduce' <$>
+          (`modinv` value @q) (fromIntegral $ valueHat (value @m :: Int))
 
--- instance of CRTrans
-instance (Reflects q z, ToInteger z, PID z, Enumerable (ZqBasic q z))
+instance (Reflects q z, ToInteger z, PID z, Enum z, NFData z)
          => CRTrans Maybe (ZqBasic q z) where
+  {-# SPECIALIZE instance (Reflects q Int64) => CRTrans Maybe (ZqBasic q Int64) #-}
 
+  {-# INLINABLE crtInfo #-}
   crtInfo = (,) <$> principalRootUnity <*> mhatInv
 
 -- | Embeds into the complex numbers \( \C \).
-instance (Reflects q z, ToInteger z, Ring (ZqBasic q z)) => CRTEmbed (ZqBasic q z) where
+instance (Reflects q z, ToInteger z, Ring (ZqBasic q z))
+  => CRTEmbed (ZqBasic q z) where
+  {-# SPECIALIZE instance (Reflects q Int64) => CRTEmbed (ZqBasic q Int64) #-}
+
   type CRTExt (ZqBasic q z) = Complex Double
 
   toExt (ZqB x) = fromReal $ fromIntegral x
-  fromExt x = reduce' $ NP.round $ real x
+  fromExt = reduce' . NP.round . real
 
 -- instance of Additive
-instance (Reflects q z, ToInteger z, Additive z) => Additive.C (ZqBasic q z) where
+instance (Reflects q z, IntegralDomain z) => Additive.C (ZqBasic q z) where
+  {-# SPECIALIZE instance (Reflects q Int64) => Additive.C (ZqBasic q Int64) #-}
 
   {-# INLINABLE zero #-}
   zero = ZqB zero
 
   {-# INLINABLE (+) #-}
-  (+) = let qval = proxy value (Proxy::Proxy q)
-        in \ (ZqB x) (ZqB y) ->
-        let z = x + y
-        in ZqB (if z >= qval then z - qval else z)
+  (ZqB x) + (ZqB y) = reduce' $ x + y
 
   {-# INLINABLE negate #-}
   negate (ZqB x) = reduce' $ negate x
 
 -- instance of Ring
-instance (Reflects q z, ToInteger z, Ring z) => Ring.C (ZqBasic q z) where
+instance (Reflects q z, ToInteger z) => Ring.C (ZqBasic q z) where
+  {-# SPECIALIZE instance (Reflects q Int64) => Ring.C (ZqBasic q Int64) #-}
+
   {-# INLINABLE (*) #-}
   (ZqB x) * (ZqB y) = reduce' $ x * y
 
   {-# INLINABLE fromInteger #-}
   fromInteger =
-    let qval = toInteger (proxy value (Proxy::Proxy q) :: z)
+    let qval = toInteger (value @q :: z)
     -- this is safe as long as type z can hold the value of q
     in \x -> ZqB $ fromInteger $ x `mod` qval
 
 -- instance of Field
 instance (Reflects q z, ToInteger z, PID z, Show z) => Field.C (ZqBasic q z) where
+  {-# SPECIALIZE instance (Reflects q Int64) => Field.C (ZqBasic q Int64) #-}
 
   {-# INLINABLE recip #-}
-  recip = let qval = proxy value (Proxy::Proxy q)
+  recip = let qval = value @q
               -- safe because modinv returns in range 0..qval-1
           in \(ZqB x) -> ZqB $
                fromMaybe (error $ "ZqB.recip fail: " ++
                          show x ++ "\t" ++ show qval) $ modinv x qval
 
 -- (canonical) instance of IntegralDomain, needed for Cyclotomics
-instance (Reflects q z, ToInteger z, Field (ZqBasic q z)) => IntegralDomain.C (ZqBasic q z) where
+instance (Reflects q z, ToInteger z, PID z, Show z)
+  => IntegralDomain.C (ZqBasic q z) where
+  {-# SPECIALIZE instance (Reflects q Int64) => IntegralDomain.C (ZqBasic q Int64) #-}
   divMod a b = (a/b, zero)
 
 -- Gadget-related instances
 instance (Reflects q z, ToInteger z) => Gadget TrivGad (ZqBasic q z) where
-  gadget = tag [one]
+  {-# SPECIALIZE instance (Reflects q Int64) => Gadget TrivGad (ZqBasic q Int64) #-}
+  gadget = [one]
 
 instance (Reflects q z, ToInteger z) => Decompose TrivGad (ZqBasic q z) where
+  {-# SPECIALIZE instance (Reflects q Int64) => Decompose TrivGad (ZqBasic q Int64) #-}
   type DecompOf (ZqBasic q z) = z
-  decompose x = tag [lift x]
+  decompose x = [lift x]
 
 instance (Reflects q z, ToInteger z, Ring z) => Correct TrivGad (ZqBasic q z) where
-  correct a = case untag a of
-    [b] -> (b, [zero])
-    _ -> error "Correct TrivGad: wrong length"
+  {-# SPECIALIZE instance (Reflects q Int64) => Correct TrivGad (ZqBasic q Int64) #-}
+  correct [b] = (b, [zero])
+  correct _   = error "Correct TrivGad: wrong length"
 
 -- BaseBGad instances
 
@@ -249,19 +253,22 @@
 
 instance (Reflects q z, ToInteger z, RealIntegral z, Reflects b z)
          => Gadget (BaseBGad b) (ZqBasic q z) where
+  {-# SPECIALIZE instance (Reflects q Int64, Reflects b Int64) => Gadget (BaseBGad b) (ZqBasic q Int64) #-}
 
-  gadget = let qval = proxy value (Proxy :: Proxy q)
-               bval = proxy value (Proxy :: Proxy b)
-           in tag $ reduce' <$> gadgetZ bval qval
+  gadget = let qval = value @q
+               bval = value @b
+           in reduce' <$> gadgetZ bval qval
 
 instance (Reflects q z, ToInteger z, Reflects b z)
     => Decompose (BaseBGad b) (ZqBasic q z) where
+  {-# SPECIALIZE instance (Reflects q Int64, Reflects b Int64) => Decompose (BaseBGad b) (ZqBasic q Int64) #-}
+
   type DecompOf (ZqBasic q z) = z
-  decompose = let qval = proxy value (Proxy :: Proxy q)
-                  bval = proxy value (Proxy :: Proxy b)
+  decompose = let qval = value @q
+                  bval = value @b
                   k = gadlen bval qval
                   radices = replicate (k-1) bval
-              in tag . decomp radices . lift
+              in decomp radices . lift
 
 -- | Yield the error vector for a noisy multiple of the gadget (all
 -- over the integers).
@@ -293,29 +300,30 @@
 
       -- | Yield @(q \bar{D}) \cdot w@, given precomputed first entry
       qbarD :: [z] -> z -> [z]
-      qbarD [] x = [x]
+      qbarD [] x      = [x]
       qbarD (w0:ws) x = x : qbarD ws (b*x - q*w0)
 
       -- | Yield the difference between the input vectors, along with
       -- their final entry.
       subLast :: [z] -> [z] -> ([z], z)
-      subLast [v0] [v'0] = let y = v0-v'0 in ([y], y)
+      subLast [v0] [v'0]        = let y = v0-v'0 in ([y], y)
       subLast (v0:vs) (v'0:v's) = first ((v0-v'0):) $ subLast vs v's
 
 instance (Reflects q z, ToInteger z, Reflects b z)
     => Correct (BaseBGad b) (ZqBasic q z) where
+  {-# SPECIALIZE instance (Reflects q Int64, Reflects b Int64) => Correct (BaseBGad b) (ZqBasic q Int64) #-}
 
   correct =
-    let qval = proxy value (Proxy :: Proxy q)
-        bval = proxy value (Proxy :: Proxy b)
+    let qval = value @q
+        bval = value @b
         correct' = correctZ qval bval
-    in \tv -> let v = untag tv
-                  es = correct' $ lift <$> v
-              in (head v - reduce (head es), es)
+    in \tv -> let es = correct' $ lift <$> tv
+              in (head tv - reduce (head es), es)
 
 -- instance of Random
-instance (Reflects q z, ToInteger z, Random z) => Random (ZqBasic q z) where
-  random = let high = proxy value (Proxy::Proxy q) - 1
+instance (Reflects q z, Ring z, Random z) => Random (ZqBasic q z) where
+  {-# SPECIALIZE instance (Reflects q Int64) => Random (ZqBasic q Int64) #-}
+  random = let high = value @q - 1
            in \g -> let (x,g') = randomR (0,high) g
                     in (ZqB x, g')
 
diff --git a/Crypto/Lol/Types/ZPP.hs b/Crypto/Lol/Types/ZPP.hs
deleted file mode 100644
--- a/Crypto/Lol/Types/ZPP.hs
+++ /dev/null
@@ -1,37 +0,0 @@
-{-|
-Module      : Crypto.Lol.Types.ZPP
-Description : A class for integers mod a prime power.
-Copyright   : (c) Eric Crockett, 2011-2017
-                  Chris Peikert, 2011-2017
-License     : GPL-2
-Maintainer  : ecrockett0@email.com
-Stability   : experimental
-Portability : POSIX
-
-  \( \def\Z{\mathbb{Z}} \)
-
-A class for integers mod a prime power.
--}
-
-{-# LANGUAGE FlexibleContexts #-}
-{-# LANGUAGE TypeFamilies     #-}
-
-module Crypto.Lol.Types.ZPP
-( ZPP(..)
-) where
-
-import Crypto.Lol.Prelude
-import Crypto.Lol.Types.FiniteField
-
--- | Represents integers modulo a prime power.
-class (PrimeField (ZpOf zq), Ring zq) => ZPP zq where
-
-  -- | An implementation of the integers modulo the prime base.
-  type ZpOf zq
-
-  -- | The prime and exponent of the modulus.
-  modulusZPP :: Tagged zq PP
-
-  -- | Lift from \(\Z_p\) to a representative.
-  liftZp :: ZpOf zq -> zq
-
diff --git a/Crypto/Lol/Types/ZmStar.hs b/Crypto/Lol/Types/ZmStar.hs
--- a/Crypto/Lol/Types/ZmStar.hs
+++ b/Crypto/Lol/Types/ZmStar.hs
@@ -3,7 +3,7 @@
 Description : Multiplicative groups mod q.
 Copyright   : (c) Eric Crockett, 2011-2017
                   Chris Peikert, 2011-2017
-License     : GPL-2
+License     : GPL-3
 Maintainer  : ecrockett0@email.com
 Stability   : experimental
 Portability : POSIX
@@ -13,6 +13,7 @@
 A collection of helper functions for working with \(\Z_m^*\).
 -}
 
+{-# LANGUAGE AllowAmbiguousTypes   #-}
 {-# LANGUAGE ConstraintKinds       #-}
 {-# LANGUAGE DataKinds             #-}
 {-# LANGUAGE FlexibleContexts      #-}
@@ -20,6 +21,7 @@
 {-# LANGUAGE PolyKinds             #-}
 {-# LANGUAGE RebindableSyntax      #-}
 {-# LANGUAGE ScopedTypeVariables   #-}
+{-# LANGUAGE TypeApplications      #-}
 {-# LANGUAGE TypeFamilies          #-}
 {-# LANGUAGE TypeOperators         #-}
 {-# LANGUAGE UndecidableInstances  #-}
@@ -29,20 +31,20 @@
 ) where
 
 import Crypto.Lol.Factored
-import Crypto.Lol.Prelude       as LP hiding (null)
+import Crypto.Lol.Prelude              as LP hiding (null)
 import Crypto.Lol.Reflects
 import Crypto.Lol.Types.Unsafe.ZqBasic hiding (ZqB)
 
 import Data.List as L (foldl', transpose)
-import Data.Map  (Map, elems, empty, insertWith')
+import Data.Map.Strict  (Map, elems, empty, insertWith)
 import Data.Set  as S (Set, difference, findMin, fromList, map, null)
 
 
 -- | The multiplicative order of \(p\) (the argument) modulo \(m\).
 -- Requires \(\gcd(p,m)=1\).
-order :: forall m . (Reflects m Int) => Int -> Tagged m Int
-order p = tag $
-  let mval = proxy value (Proxy::Proxy m)
+order :: forall m . (Reflects m Int) => Int -> Int
+order p =
+  let mval = value @m
   in if gcd p mval /= 1
      then error "p and m not coprime"
      else 1 + length (takeWhile (/= one) $
@@ -52,7 +54,7 @@
 cosets :: forall zm . (Mod zm, ModRep zm ~ Int, Ord zm, Ring zm)
   => Int -> [Set zm]
 cosets p =
-  let mval = proxy modulus (Proxy::Proxy zm)
+  let mval = modulus @zm
   in if gcd p mval /= 1
      then error "p and m not coprime"
      else let zmstar = fromList $ LP.map fromIntegral $ filter ((==) 1 . gcd mval) [1..mval]
@@ -71,18 +73,17 @@
 -- (specified by representatives), where the cosets in each component
 -- are in bijective correspondence with the cosets of \(\Z_m^* / <p>\) under
 -- the natural (\(\bmod m\)) homomorphism.
-partitionCosets :: forall m m' . (m `Divides` m')
-  => Int -> Tagged '(m, m') [[Int]]
+partitionCosets :: forall m m' . (m `Divides` m') => Int -> [[Int]]
 partitionCosets p =
   let m'cosets = cosets p
       -- a map from cosets of Z_m^* / <p> to their preimages under the
       -- natural homomorphism
       partition =
-        L.foldl' (\cmap x -> insertWith' (++) (S.map (reduce . lift) x) [x] cmap)
+        L.foldl' (\cmap x -> insertWith (++) (S.map (reduce . lift) x) [x] cmap)
           (empty :: Map (Set (ZqBasic m Int)) [Set (ZqBasic m' Int)])
           m'cosets
       -- transpose the map to get a list of list of sets, where for each
       -- inner list, there is exactly one m'-(co)set lying above each m-coset
       part' = transpose $ elems partition
      -- concat the inner sets to get a list of "CRT cosets" (indexed in Z_m'^*)
-  in return $ LP.map (LP.map (lift . findMin)) part'
+  in LP.map (LP.map (lift . findMin)) part'
diff --git a/Crypto/Lol/Utils/Benchmarks.hs b/Crypto/Lol/Utils/Benchmarks.hs
new file mode 100644
--- /dev/null
+++ b/Crypto/Lol/Utils/Benchmarks.hs
@@ -0,0 +1,39 @@
+{-|
+Module      : Crypto.Lol.Utils.Benchmarks
+Description : Infrastructure for benchmarking Lol.
+Copyright   : (c) Eric Crockett, 2011-2017
+                  Chris Peikert, 2011-2017
+License     : GPL-3
+Maintainer  : ecrockett0@email.com
+Stability   : experimental
+Portability : POSIX
+
+Infrastructure for benchmarking Lol.
+-}
+
+{-# LANGUAGE DataKinds             #-}
+{-# LANGUAGE FlexibleContexts      #-}
+{-# LANGUAGE FlexibleInstances     #-}
+{-# LANGUAGE GADTs                 #-}
+{-# LANGUAGE MultiParamTypeClasses #-}
+{-# LANGUAGE PolyKinds             #-}
+{-# LANGUAGE RankNTypes            #-}
+{-# LANGUAGE ScopedTypeVariables   #-}
+{-# LANGUAGE TypeFamilies          #-}
+
+module Crypto.Lol.Utils.Benchmarks
+(mkBench, mkBenchIO
+-- Re-exports
+,C.bgroup, C.Benchmark) where
+
+import Control.DeepSeq
+
+import qualified Criterion as C
+
+-- | Make a `Benchmark` from a function and its input
+mkBench :: NFData b => String -> (a -> b) -> a -> C.Benchmark
+mkBench name f input = C.bench name $ C.nf f input
+
+-- | Make a `Benchmark` from an IO function and its input
+mkBenchIO :: NFData b => String -> IO b -> C.Benchmark
+mkBenchIO name i = C.bench name $ C.nfIO i
diff --git a/Crypto/Lol/Utils/GenArgs.hs b/Crypto/Lol/Utils/GenArgs.hs
deleted file mode 100644
--- a/Crypto/Lol/Utils/GenArgs.hs
+++ /dev/null
@@ -1,37 +0,0 @@
-{-|
-Module      : Crypto.Lol.Utils.GenArgs
-Description : Generate arguments for tests and benchmarks.
-Copyright   : (c) Eric Crockett, 2011-2017
-                  Chris Peikert, 2011-2017
-License     : GPL-2
-Maintainer  : ecrockett0@email.com
-Stability   : experimental
-Portability : POSIX
-
-  \( \def\C{\mathbb{C}} \)
-
-Classes used to generate arguments for tests and benchmarks.
-This is analagous to 'Arbitrary' in quickcheck, except it can also be used
-with criterion.
--}
-
-{-# LANGUAGE FlexibleInstances     #-}
-{-# LANGUAGE MultiParamTypeClasses #-}
-{-# LANGUAGE TypeFamilies          #-}
-
-module Crypto.Lol.Utils.GenArgs where
-
-import Control.Monad.Random
-
--- | Type of the output of a fully-applied function.
-type family ResultOf a where
-  ResultOf (a -> b) = ResultOf b
-  ResultOf a = a
-
--- | Generalization of 'Testable' from QuickCheck: generates function inputs
-class GenArgs fun where
-  genArgs :: (MonadRandom rnd) => fun -> rnd (ResultOf fun)
-
--- | Generate arguments to a function.
-instance (Random a, GenArgs b) => GenArgs (a -> b) where
-  genArgs f = getRandom >>= (genArgs . f)
diff --git a/Crypto/Lol/Utils/PrettyPrint.hs b/Crypto/Lol/Utils/PrettyPrint.hs
new file mode 100644
--- /dev/null
+++ b/Crypto/Lol/Utils/PrettyPrint.hs
@@ -0,0 +1,132 @@
+{-|
+Module      : Crypto.Lol.Utils.PrettyPrint
+Description : Pretty-printing for benchmark results.
+Copyright   : (c) Eric Crockett, 2011-2017
+                  Chris Peikert, 2011-2017
+License     : GPL-3
+Maintainer  : ecrockett0@email.com
+Stability   : experimental
+Portability : POSIX
+
+Pretty-printing for benchmark results.
+-}
+
+{-# LANGUAGE RecordWildCards #-}
+{-# LANGUAGE TupleSections   #-}
+
+module Crypto.Lol.Utils.PrettyPrint
+( getTableName
+, getBenchParams
+, getBenchLvl
+, getBenchFunc
+, getReports
+, getRuntime
+, col
+, testName
+, OptsInternal(..)
+, Verb(..)
+) where
+
+import Control.Monad          (foldM, when)
+import Control.Monad.IO.Class (liftIO)
+
+import Criterion.Internal     (runAndAnalyseOne)
+import Criterion.Main.Options (defaultConfig)
+import Criterion.Measurement  (initializeTime, secs)
+import Criterion.Monad        (Criterion, withConfig)
+import Criterion.Types
+
+import qualified Data.Map as Map
+
+import Statistics.Types (Estimate (..))
+
+-- | Verbosity of benchmark output.
+data Verb = Progress  -- ^ prints a \'.\' when each benchmark completes
+          | Abridged  -- ^ prints a one-line summary for each benchmark
+          | Full      -- ^ prints full criterion output for each benchmark
+          deriving (Eq)
+
+-- | Options for printing benchmark summary.
+data OptsInternal = OptsInternal
+  {verb          :: Verb,     -- ^ Verbosity
+   levels        :: [String], -- ^ Which levels of Lol to benchmark
+   benches       :: [String], -- ^ Which operations to benchmark
+   params        :: [String], -- ^ Which parameters to benchmark
+   redThreshold  :: Double,   -- ^ How many times larger a benchmark
+                              --   must be (compared to the minimum
+                              --   benchmark for that parameter,
+                              --   across all levels), to be printed in red
+   colWidth      :: Int,      -- ^ Character width of data columns
+   testNameWidth :: Int}      -- ^ Character width of row labels
+
+col, testName :: OptsInternal -> String
+testName OptsInternal{..} = "%-" ++ show testNameWidth ++ "s "
+col OptsInternal{..} = "%-" ++ show colWidth ++ "s "
+
+-- get the ith 'word' where words are separated by '/'
+wordBy :: Int -> String -> String
+wordBy 0 = takeWhile (/= '/')
+wordBy i = wordBy (i-1) . tail . dropWhile (/= '/')
+
+getTableName :: String -> String
+getTableName   = wordBy 0
+
+getBenchParams :: String -> String
+getBenchParams = wordBy 1
+
+getBenchLvl :: String -> String
+getBenchLvl    = wordBy 2
+
+getBenchFunc :: String -> String
+getBenchFunc   = wordBy 3
+
+getReports :: OptsInternal -> Benchmark -> IO [Report]
+getReports o = withConfig (config o) . summarizeBenchReports o
+
+config :: OptsInternal -> Config
+config OptsInternal{..} = defaultConfig {verbosity = if verb == Full then Normal else Quiet}
+
+-- collect reports from all selected benchmarks, printing a summary along the way
+summarizeBenchReports :: OptsInternal -> Benchmark -> Criterion [Report]
+summarizeBenchReports OptsInternal{..} b = do
+  liftIO initializeTime -- Workaround for criterion issue #195
+  snd <$> go (0, []) ("", b)
+  where
+    select name =
+      let param = getBenchParams name
+          lvl   = getBenchLvl    name
+          func  = getBenchFunc   name
+      in (lvl `elem` levels) && (func `elem` benches) && (param `elem` params)
+    -- if we find a Benchmark that we want to run (as determined by `select`)
+    go r@(rptIdx, reports) (benchPrefix, Benchmark desc b') |
+      select benchName = do
+          -- get a single report
+          when (verb == Abridged || verb == Full) $ liftIO $ putStr $ "benchmark " ++ benchName
+          when (verb == Full) $ liftIO $ putStrLn ""
+          dr <- runAndAnalyseOne rptIdx benchName b'
+          case dr of
+            Measurement{} -> error "PrettyPrint Measurement" -- for Wmissing-monadfail-instances
+            (Analysed rpt) -> do
+              when (verb == Progress) $ liftIO $ putStr "."
+              when (verb == Abridged) $ liftIO $ putStrLn $ "..." ++ secs (getRuntime rpt)
+              -- return the report
+              return (rptIdx, rpt:reports)
+                                                            |
+      otherwise = do
+        -- if we don't want to run this benchmark, print the name anyway.
+        liftIO $ putStrLn benchName
+        -- and return the input
+        return r
+          where benchName = addPrefix benchPrefix desc
+    go r (benchPrefix, BenchGroup desc bs) =
+      let lvlName = addPrefix benchPrefix desc -- append the description to the prefix
+          bs' = map (lvlName,) bs
+      in foldM go r bs'
+
+-- | The report runtime, in seconds.
+getRuntime :: Report -> Double
+getRuntime Report{..} =
+  let SampleAnalysis{..} = reportAnalysis
+      Regression{..} = head anRegress
+      Estimate{..} = regCoeffs Map.! "iters"
+  in estPoint
diff --git a/Crypto/Lol/Utils/PrettyPrint/Diagnostic.hs b/Crypto/Lol/Utils/PrettyPrint/Diagnostic.hs
new file mode 100644
--- /dev/null
+++ b/Crypto/Lol/Utils/PrettyPrint/Diagnostic.hs
@@ -0,0 +1,102 @@
+{-|
+Module      : Crypto.Lol.Utils.PrettyPrint.Diagnostic
+Description : Pretty-printing for benchmark results across levels of the Lol stack.
+Copyright   : (c) Eric Crockett, 2011-2017
+                  Chris Peikert, 2011-2017
+License     : GPL-3
+Maintainer  : ecrockett0@email.com
+Stability   : experimental
+Portability : POSIX
+
+Pretty-printing for benchmark results across levels of the Lol stack.
+-}
+
+{-# LANGUAGE RecordWildCards       #-}
+-- EAC: https://ghc.haskell.org/trac/ghc/ticket/13352
+{-# LANGUAGE DuplicateRecordFields #-}
+
+module Crypto.Lol.Utils.PrettyPrint.Diagnostic
+(prettyBenchesDiagnostic
+,defaultDiagnosticOpts
+,DiagnosticOpts(..)) where
+
+import Control.Monad (forM_, when)
+
+import Criterion.Measurement (secs)
+import Criterion.Types
+
+import Crypto.Lol.Utils.PrettyPrint
+
+import Data.List           (groupBy, nub, transpose)
+import System.Console.ANSI
+import System.IO
+import Text.Printf
+
+-- | Options for the diagnostic benchmark printout.
+data DiagnosticOpts = DOpts
+  {verb          :: Verb,     -- ^ Verbosity
+   levels        :: [String], -- ^ Which levels of Lol to benchmark. The empty list means run all levels.
+   benches       :: [String], -- ^ Which operations to benchmark. The empty list means run all benchmarks.
+   redThreshold  :: Double,   -- ^ How many times larger a benchmark
+                              --   must be (compared to the minimum
+                              --   benchmark for that parameter,
+                              --   across all levels), to be printed in red
+   colWidth      :: Int,      -- ^ Character width of data columns
+   testNameWidth :: Int}      -- ^ Character width of row labels
+
+-- | Runs all benchmarks with verbosity 'Progress'.
+defaultDiagnosticOpts :: DiagnosticOpts
+defaultDiagnosticOpts =
+  DOpts {verb = Progress,
+         levels = [],
+         benches = [],
+         redThreshold = 1.2,
+         colWidth = 15,
+         testNameWidth=40}
+
+optsToInternal :: DiagnosticOpts -> Benchmark -> OptsInternal
+optsToInternal DOpts{..} bnch =
+  OptsInternal{params=[getBenchParams $ head $ benchNames bnch],
+               levels=if null levels
+                      then nub $ map getBenchLvl $ benchNames bnch
+                      else levels,
+               benches=if null benches
+                       then nub $ map getBenchFunc $ benchNames bnch
+                       else benches,
+               ..}
+
+-- | Takes benchmark options an a benchmark group nested as params\/level\/op,
+-- and prints a table comparing operations across all selected levels of Lol.
+prettyBenchesDiagnostic :: DiagnosticOpts -> Benchmark-> IO ()
+prettyBenchesDiagnostic o bnch = do
+  hSetBuffering stdout NoBuffering -- for better printing of progress
+  let o'@OptsInternal{..} = optsToInternal o bnch
+  rpts <- getReports o' bnch
+  when (verb == Progress) $ putStrLn ""
+  printTable o' $ reverse rpts
+
+printTable :: OptsInternal -> [Report] -> IO ()
+printTable _ [] = return ()
+printTable o rpts = do
+  let colLbls = nub $ map (getBenchLvl . reportName) rpts
+  printf (testName o) $ getBenchParams $ reportName $ head rpts
+  mapM_ (printf (col o)) colLbls
+  printf "\n"
+  let rpts' = transpose $ groupBy (\a b -> getBenchLvl (reportName a) == getBenchLvl (reportName b)) rpts
+  mapM_ (printRow o) rpts'
+  putStrLn ""
+
+printRow :: OptsInternal -> [Report] -> IO ()
+printRow o@OptsInternal{..} xs@(rpt : _) = do
+  printf (testName o) $ getBenchFunc $ reportName rpt
+  let times = map getRuntime xs
+      minTime = minimum times
+      printCol t =
+        if t > (redThreshold*minTime)
+        then do
+          setSGR [SetColor Foreground Vivid Red]
+          printf (col o) $ secs t
+          setSGR [Reset]
+        else printf (col o) $ secs t
+  forM_ times printCol
+  putStrLn ""
diff --git a/Crypto/Lol/Utils/PrettyPrint/Table.hs b/Crypto/Lol/Utils/PrettyPrint/Table.hs
new file mode 100644
--- /dev/null
+++ b/Crypto/Lol/Utils/PrettyPrint/Table.hs
@@ -0,0 +1,95 @@
+{-|
+Module      : Crypto.Lol.Utils.PrettyPrint.Table
+Description : Pretty-printing for benchmark results within a single level of the Lol stack.
+Copyright   : (c) Eric Crockett, 2011-2017
+                  Chris Peikert, 2011-2017
+License     : GPL-3
+Maintainer  : ecrockett0@email.com
+Stability   : experimental
+Portability : POSIX
+
+Pretty-printing for benchmark results within a single level of the Lol stack.
+-}
+
+{-# LANGUAGE RecordWildCards #-}
+
+module Crypto.Lol.Utils.PrettyPrint.Table
+(prettyBenchesTable
+,defaultTableOpts
+,TableOpts(..)) where
+
+import Control.Monad (forM_, when)
+
+import Criterion.Measurement (secs)
+import Criterion.Types
+
+import Crypto.Lol.Utils.PrettyPrint
+
+import Data.List   (groupBy, nub, transpose)
+import System.IO
+import Text.Printf
+
+-- | Options for the simple benchmark format.
+data TableOpts = TOpts
+  {verb          :: Verb,     -- ^ Verbosity
+   level         :: String,   -- ^ Which level of Lol to benchmark
+   benches       :: [String], -- ^ Which operations to benchmark. The empty list means run all benchmarks.
+   params        :: [String], -- ^ Which parameters to benchmark. The empty list means run all parameters.
+   colWidth      :: Int,      -- ^ Character width of data columns
+   testNameWidth :: Int}      -- ^ Character width of row labels
+
+optsToInternal :: TableOpts -> Benchmark -> OptsInternal
+optsToInternal TOpts{..} bnch =
+  OptsInternal{params=if null params
+                      then nub $ map getBenchParams $ benchNames bnch
+                      else params,
+               levels=if null level
+                      then nub $ map getBenchLvl $ benchNames bnch
+                      else [level],
+               benches=if null benches
+                       then nub $ map getBenchFunc $ benchNames bnch
+                       else benches,
+               redThreshold = 0,
+               ..}
+
+-- | Runs all benchmarks with verbosity 'Progress'.
+defaultTableOpts :: Maybe String -> TableOpts
+defaultTableOpts lvl =
+  case lvl of
+    Nothing  -> go ""
+    (Just l) -> go l
+  where go level =
+          TOpts {verb = Progress,
+                 benches = [],
+                 params = [],
+                 colWidth = 30,
+                 testNameWidth=20, ..}
+
+-- | Takes benchmark options an a benchmark group nested as params\/level\/op,
+-- and prints a table comparing operations across all selected levels of Lol.
+prettyBenchesTable :: TableOpts -> Benchmark-> IO ()
+prettyBenchesTable o bnch = do
+  hSetBuffering stdout NoBuffering -- for better printing of progress
+  let o'@OptsInternal{..} = optsToInternal o bnch
+  rpts <- getReports o' bnch
+  when (verb == Progress) $ putStrLn ""
+  printTable o' $ reverse rpts
+
+printTable :: OptsInternal -> [Report] -> IO ()
+printTable _ [] = return ()
+printTable o rpts = do
+  let colLbls = nub $ map (getBenchParams . reportName) rpts
+      exName = reportName $ head rpts
+  printf (testName o) $ getTableName exName ++ "/" ++ getBenchLvl exName
+  mapM_ (printf (col o)) colLbls
+  printf "\n"
+  let rpts' = transpose $ groupBy (\a b -> getBenchParams (reportName a) == getBenchParams (reportName b)) rpts
+  mapM_ (printRow o) rpts'
+  putStrLn ""
+
+printRow :: OptsInternal -> [Report] -> IO ()
+printRow o@OptsInternal{..} xs@(rpt : _) = do
+  printf (testName o) $ getBenchFunc $ reportName rpt
+  let times = map (secs . getRuntime) xs
+  forM_ times (printf (col o))
+  putStrLn ""
diff --git a/Crypto/Lol/Utils/ShowType.hs b/Crypto/Lol/Utils/ShowType.hs
--- a/Crypto/Lol/Utils/ShowType.hs
+++ b/Crypto/Lol/Utils/ShowType.hs
@@ -3,7 +3,7 @@
 Description : Pretty print type parameters.
 Copyright   : (c) Eric Crockett, 2011-2017
                   Chris Peikert, 2011-2017
-License     : GPL-2
+License     : GPL-3
 Maintainer  : ecrockett0@email.com
 Stability   : experimental
 Portability : POSIX
@@ -15,6 +15,7 @@
 
 {-# LANGUAGE ConstraintKinds       #-}
 {-# LANGUAGE DataKinds             #-}
+{-# LANGUAGE ExplicitNamespaces    #-}
 {-# LANGUAGE FlexibleContexts      #-}
 {-# LANGUAGE FlexibleInstances     #-}
 {-# LANGUAGE GADTs                 #-}
@@ -23,24 +24,32 @@
 {-# LANGUAGE PolyKinds             #-}
 {-# LANGUAGE RankNTypes            #-}
 {-# LANGUAGE ScopedTypeVariables   #-}
+{-# LANGUAGE TypeApplications      #-}
 {-# LANGUAGE TypeFamilies          #-}
 {-# LANGUAGE TypeOperators         #-}
 {-# LANGUAGE UndecidableInstances  #-}
 
 module Crypto.Lol.Utils.ShowType
-(ArgType
-,showType
-,ShowType) where
+( ArgType
+, showType
+, ShowType
+, Zq
+, type (**)
+) where
 
-import Crypto.Lol (Int64,Fact,valueFact,Mod(..), Proxy(..), proxy, TrivGad, BaseBGad)
+import Crypto.Lol                      (BaseBGad, Complex, Fact, Int64,
+                                        Mod (..), Proxy (..), TrivGad,
+                                        valueFact)
 import Crypto.Lol.Reflects
 import Crypto.Lol.Types.Unsafe.ZqBasic hiding (ZqB)
 
-import GHC.TypeLits
+import GHC.TypeLits hiding (Mod)
 
+-- | Convenient syntax for multiplication of moduli in a 'Zq'.
 infixr 9 **
 data a ** b
 
+-- | Converts '**' syntax into nested pair representation.
 type family Zq (a :: k) :: * where
   Zq (a ** b) = (Zq a, Zq b)
   Zq q = (ZqBasic q Int64)
@@ -48,7 +57,7 @@
 
 type family (f :: (k1 -> k2)) <$>  (xs :: [k1]) where
   f <$> '[] = '[]
-  f <$> (x ': xs) = (f x) ': (f <$> xs)
+  f <$> (x ': xs) = f x ': (f <$> xs)
 
 type family (fs :: [k1 -> k2]) <*> (xs :: [k1]) where
   fs <*> xs = Go fs xs xs
@@ -56,16 +65,16 @@
 type family Go (fs :: [k1 -> k2]) (xs :: [k1]) (ys :: [k1]) where
   Go '[] xs ys = '[]
   Go (f ': fs) '[] ys = Go fs ys ys
-  Go (f ': fs) (x ': xs) ys = (f x) ': (Go (f ': fs) xs ys)
+  Go (f ': fs) (x ': xs) ys = f x ': Go (f ': fs) xs ys
 
 
--- | Wrapper type for printing test/benchmark names
+-- | Wrapper type for printing test/benchmark names.
 data ArgType (a :: k) = AT
 
--- | Constraint synonym for printing test parameters
+-- | Constraint synonym for printing test parameters.
 type ShowType a = Show (ArgType a)
 
--- | Print a showable type argument
+-- | Print a showable type argument.
 showType :: forall a . (Show (ArgType a)) => Proxy a -> String
 showType _ = show (AT :: ArgType a)
 
@@ -73,7 +82,7 @@
   show _ = show $ natVal (Proxy::Proxy n)
 
 instance (Fact m) => Show (ArgType m) where
-  show _ = "F" ++ show (proxy valueFact (Proxy::Proxy m))
+  show _ = "F" ++ show (valueFact @m)
 
 instance (Show (ArgType a), Show (ArgType b)) => Show (ArgType '(a,b)) where
   show _ = "(" ++ show (AT :: ArgType a) ++ "," ++ show (AT :: ArgType b) ++ ")"
@@ -89,17 +98,23 @@
 instance Show (ArgType (InternalList '[])) where
   show _ = ""
 
-instance (Mod (ZqBasic q i), Show i) => Show (ArgType (ZqBasic q i)) where
-  show _ = "Q" ++ show (proxy modulus (Proxy::Proxy (ZqBasic q i)))
+instance (Mod (ZqBasic q z), Show z) => Show (ArgType (ZqBasic q z)) where
+  show _ = "Q" ++ show (modulus @(ZqBasic q z))
 
 instance Show (ArgType Int64) where
   show _ = "Int64"
 
+instance Show (ArgType Double) where
+  show _ = "Double"
+
+instance Show (ArgType (Complex Double)) where
+  show _ = "Complex Double"
+
 instance Show (ArgType TrivGad) where
   show _ = "TrivGad"
 
 instance (Reflects b Integer) => Show (ArgType (BaseBGad (b :: k))) where
-  show _ = "Base" ++ show (proxy value (Proxy::Proxy b) :: Integer) ++ "Gad"
+  show _ = "Base" ++ show (value @b :: Integer) ++ "Gad"
 
 -- for RNS-style moduli
 instance (Show (ArgType a), Show (ArgType b)) => Show (ArgType (a,b)) where
diff --git a/Crypto/Lol/Utils/Tests.hs b/Crypto/Lol/Utils/Tests.hs
new file mode 100644
--- /dev/null
+++ b/Crypto/Lol/Utils/Tests.hs
@@ -0,0 +1,91 @@
+{-|
+Module      : Crypto.Lol.Utils.Tests
+Description : Infrastructure for testing Lol.
+Copyright   : (c) Eric Crockett, 2011-2017
+                  Chris Peikert, 2011-2017
+License     : GPL-3
+Maintainer  : ecrockett0@email.com
+Stability   : experimental
+Portability : POSIX
+
+Infrastructure for testing Lol.
+-}
+
+{-# LANGUAGE FlexibleContexts      #-}
+{-# LANGUAGE FlexibleInstances     #-}
+{-# LANGUAGE GADTs                 #-}
+{-# LANGUAGE MultiParamTypeClasses #-}
+{-# LANGUAGE PolyKinds             #-}
+{-# LANGUAGE RankNTypes            #-}
+{-# LANGUAGE ScopedTypeVariables   #-}
+{-# LANGUAGE TypeFamilies          #-}
+
+module Crypto.Lol.Utils.Tests
+(nestGroup
+,testIOWithGen
+,testIOWithoutGen
+,testWithGen
+,testWithoutGen
+,ApproxEqual(..)
+-- Re-exports
+,QCG.choose
+,QCG.chooseAny
+,TF.testGroup
+,QC.Gen
+,TF.Test) where
+
+import Crypto.Lol.Prelude              (Complex, Int64, imag, real)
+import Crypto.Lol.Types.Unsafe.ZqBasic
+
+import qualified Test.Framework                       as TF
+import qualified Test.Framework.Providers.QuickCheck2 as QC2
+import qualified Test.QuickCheck                      as QC
+import qualified Test.QuickCheck.Gen                  as QCG
+import qualified Test.QuickCheck.Monadic              as QCM
+
+-- The allowable distance from 1 the ratio of two Doubles is allowed to be in order for the numbers
+-- to be considered "approximately equal". That is, x =~= y iff -1-ε < x/y < 1+ε
+-- In the case that x == 0, we just measure that abs y < ε, and vice-versa for y == 0
+approxEqualEpsilon :: Double
+approxEqualEpsilon = 1e-6
+
+class ApproxEqual a where
+  (=~=) :: a -> a -> Bool
+
+instance ApproxEqual Int64 where
+  x =~= y = x == y
+
+instance Eq r => ApproxEqual (ZqBasic q r) where
+  x =~= y = x == y
+
+instance ApproxEqual Double where
+  x =~= y
+    | x == 0             = abs y < approxEqualEpsilon
+    | y == 0             = abs x < approxEqualEpsilon
+    | isNaN x || isNaN y = False
+    -- Calculate the distance of x/y and y/x from 1 and take the minimum
+    | otherwise          = let minDist = minimum $ map (\r -> abs $ abs r - 1) [x/y, y/x] in
+                               minDist < approxEqualEpsilon
+
+instance ApproxEqual (Complex Double) where
+  x =~= y = (real x =~= real y) && (imag x =~= imag y)
+
+-- | Make a 'Test' given a name, a testing function, and a parameter generator
+testWithGen :: (Show a, QC.Testable prop) => String -> (a -> prop) -> QC.Gen a -> TF.Test
+testWithGen name f gen = QC2.testProperty name $ QC.forAll gen f
+
+-- | Make a 'Test' given a name, a monadic (IO only) testing function, and a parameter generator
+testIOWithGen :: (Show a, QC.Testable prop) => String -> (a -> IO prop) -> QC.Gen a -> TF.Test
+testIOWithGen name f gen = QC2.testProperty name $ QCM.monadicIO $ QCM.forAllM gen (QCM.run . f)
+
+-- | Make a 'Test' given a name and a 'QC.Testable' value
+testWithoutGen :: (QC.Testable prop) => String -> prop -> TF.Test
+testWithoutGen name p = QC2.testProperty name $ QC.property p
+
+-- | Make a 'Test' given a name and a monadic (IO only) 'QC.Testable' value
+testIOWithoutGen :: (QC.Testable prop) => String -> IO prop -> TF.Test
+testIOWithoutGen name p = QC2.testProperty name $ QCM.monadicIO $ QCM.run p
+
+-- | Apply parameters to a list of 'Test'.
+nestGroup :: String -> [QC.Gen a -> TF.Test] -> QC.Gen a -> TF.Test
+nestGroup name ts gen = TF.testGroup name $ map ($ gen) ts
diff --git a/Crypto/Proto/Lol.hs b/Crypto/Proto/Lol.hs
--- a/Crypto/Proto/Lol.hs
+++ b/Crypto/Proto/Lol.hs
@@ -14,10 +14,10 @@
 protoInfo :: ProtoInfo
 protoInfo
  = Prelude'.read
-    "ProtoInfo {protoMod = ProtoName {protobufName = FIName \".Lol\", haskellPrefix = [MName \"Crypto\",MName \"Proto\"], parentModule = [], baseName = MName \"Lol\"}, protoFilePath = [\"Crypto\",\"Proto\",\"Lol.hs\"], protoSource = \"Lol.proto\", extensionKeys = fromList [], messages = [DescriptorInfo {descName = ProtoName {protobufName = FIName \".Lol.LinearRq\", haskellPrefix = [MName \"Crypto\",MName \"Proto\"], parentModule = [MName \"Lol\"], baseName = MName \"LinearRq\"}, descFilePath = [\"Crypto\",\"Proto\",\"Lol\",\"LinearRq.hs\"], isGroup = False, fields = fromList [FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".Lol.LinearRq.e\", haskellPrefix' = [MName \"Crypto\",MName \"Proto\"], parentModule' = [MName \"Lol\",MName \"LinearRq\"], baseName' = FName \"e\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 1}, wireTag = WireTag {getWireTag = 8}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 13}, typeName = Nothing, hsRawDefault = Nothing, hsDefault = Nothing},FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".Lol.LinearRq.r\", haskellPrefix' = [MName \"Crypto\",MName \"Proto\"], parentModule' = [MName \"Lol\",MName \"LinearRq\"], baseName' = FName \"r\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 2}, wireTag = WireTag {getWireTag = 16}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 13}, typeName = Nothing, hsRawDefault = Nothing, hsDefault = Nothing},FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".Lol.LinearRq.coeffs\", haskellPrefix' = [MName \"Crypto\",MName \"Proto\"], parentModule' = [MName \"Lol\",MName \"LinearRq\"], baseName' = FName \"coeffs\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 3}, wireTag = WireTag {getWireTag = 26}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = False, canRepeat = True, mightPack = False, typeCode = FieldType {getFieldType = 11}, typeName = Just (ProtoName {protobufName = FIName \".Lol.RqProduct\", haskellPrefix = [MName \"Crypto\",MName \"Proto\"], parentModule = [MName \"Lol\"], baseName = MName \"RqProduct\"}), hsRawDefault = Nothing, hsDefault = Nothing}], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False},DescriptorInfo {descName = ProtoName {protobufName = FIName \".Lol.R\", haskellPrefix = [MName \"Crypto\",MName \"Proto\"], parentModule = [MName \"Lol\"], baseName = MName \"R\"}, descFilePath = [\"Crypto\",\"Proto\",\"Lol\",\"R.hs\"], isGroup = False, fields = fromList [FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".Lol.R.m\", haskellPrefix' = [MName \"Crypto\",MName \"Proto\"], parentModule' = [MName \"Lol\",MName \"R\"], baseName' = FName \"m\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 1}, wireTag = WireTag {getWireTag = 8}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 13}, typeName = Nothing, hsRawDefault = Nothing, hsDefault = Nothing},FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".Lol.R.xs\", haskellPrefix' = [MName \"Crypto\",MName \"Proto\"], parentModule' = [MName \"Lol\",MName \"R\"], baseName' = FName \"xs\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 2}, wireTag = WireTag {getWireTag = 16}, packedTag = Just (WireTag {getWireTag = 16},WireTag {getWireTag = 18}), wireTagLength = 1, isPacked = False, isRequired = False, canRepeat = True, mightPack = True, typeCode = FieldType {getFieldType = 18}, typeName = Nothing, hsRawDefault = Nothing, hsDefault = Nothing}], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False},DescriptorInfo {descName = ProtoName {protobufName = FIName \".Lol.Rq1\", haskellPrefix = [MName \"Crypto\",MName \"Proto\"], parentModule = [MName \"Lol\"], baseName = MName \"Rq1\"}, descFilePath = [\"Crypto\",\"Proto\",\"Lol\",\"Rq1.hs\"], isGroup = False, fields = fromList [FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".Lol.Rq1.m\", haskellPrefix' = [MName \"Crypto\",MName \"Proto\"], parentModule' = [MName \"Lol\",MName \"Rq1\"], baseName' = FName \"m\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 1}, wireTag = WireTag {getWireTag = 8}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 13}, typeName = Nothing, hsRawDefault = Nothing, hsDefault = Nothing},FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".Lol.Rq1.q\", haskellPrefix' = [MName \"Crypto\",MName \"Proto\"], parentModule' = [MName \"Lol\",MName \"Rq1\"], baseName' = FName \"q\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 2}, wireTag = WireTag {getWireTag = 16}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 4}, typeName = Nothing, hsRawDefault = Nothing, hsDefault = Nothing},FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".Lol.Rq1.xs\", haskellPrefix' = [MName \"Crypto\",MName \"Proto\"], parentModule' = [MName \"Lol\",MName \"Rq1\"], baseName' = FName \"xs\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 3}, wireTag = WireTag {getWireTag = 24}, packedTag = Just (WireTag {getWireTag = 24},WireTag {getWireTag = 26}), wireTagLength = 1, isPacked = False, isRequired = False, canRepeat = True, mightPack = True, typeCode = FieldType {getFieldType = 18}, typeName = Nothing, hsRawDefault = Nothing, hsDefault = Nothing}], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False},DescriptorInfo {descName = ProtoName {protobufName = FIName \".Lol.Kq1\", haskellPrefix = [MName \"Crypto\",MName \"Proto\"], parentModule = [MName \"Lol\"], baseName = MName \"Kq1\"}, descFilePath = [\"Crypto\",\"Proto\",\"Lol\",\"Kq1.hs\"], isGroup = False, fields = fromList [FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".Lol.Kq1.m\", haskellPrefix' = [MName \"Crypto\",MName \"Proto\"], parentModule' = [MName \"Lol\",MName \"Kq1\"], baseName' = FName \"m\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 1}, wireTag = WireTag {getWireTag = 8}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 13}, typeName = Nothing, hsRawDefault = Nothing, hsDefault = Nothing},FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".Lol.Kq1.q\", haskellPrefix' = [MName \"Crypto\",MName \"Proto\"], parentModule' = [MName \"Lol\",MName \"Kq1\"], baseName' = FName \"q\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 2}, wireTag = WireTag {getWireTag = 16}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 4}, typeName = Nothing, hsRawDefault = Nothing, hsDefault = Nothing},FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".Lol.Kq1.xs\", haskellPrefix' = [MName \"Crypto\",MName \"Proto\"], parentModule' = [MName \"Lol\",MName \"Kq1\"], baseName' = FName \"xs\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 3}, wireTag = WireTag {getWireTag = 25}, packedTag = Just (WireTag {getWireTag = 25},WireTag {getWireTag = 26}), wireTagLength = 1, isPacked = False, isRequired = False, canRepeat = True, mightPack = True, typeCode = FieldType {getFieldType = 1}, typeName = Nothing, hsRawDefault = Nothing, hsDefault = Nothing}], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False},DescriptorInfo {descName = ProtoName {protobufName = FIName \".Lol.RqProduct\", haskellPrefix = [MName \"Crypto\",MName \"Proto\"], parentModule = [MName \"Lol\"], baseName = MName \"RqProduct\"}, descFilePath = [\"Crypto\",\"Proto\",\"Lol\",\"RqProduct.hs\"], isGroup = False, fields = fromList [FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".Lol.RqProduct.rqlist\", haskellPrefix' = [MName \"Crypto\",MName \"Proto\"], parentModule' = [MName \"Lol\",MName \"RqProduct\"], baseName' = FName \"rqlist\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 1}, wireTag = WireTag {getWireTag = 10}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = False, canRepeat = True, mightPack = False, typeCode = FieldType {getFieldType = 11}, typeName = Just (ProtoName {protobufName = FIName \".Lol.Rq1\", haskellPrefix = [MName \"Crypto\",MName \"Proto\"], parentModule = [MName \"Lol\"], baseName = MName \"Rq1\"}), hsRawDefault = Nothing, hsDefault = Nothing}], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False},DescriptorInfo {descName = ProtoName {protobufName = FIName \".Lol.KqProduct\", haskellPrefix = [MName \"Crypto\",MName \"Proto\"], parentModule = [MName \"Lol\"], baseName = MName \"KqProduct\"}, descFilePath = [\"Crypto\",\"Proto\",\"Lol\",\"KqProduct.hs\"], isGroup = False, fields = fromList [FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".Lol.KqProduct.kqlist\", haskellPrefix' = [MName \"Crypto\",MName \"Proto\"], parentModule' = [MName \"Lol\",MName \"KqProduct\"], baseName' = FName \"kqlist\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 1}, wireTag = WireTag {getWireTag = 10}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = False, canRepeat = True, mightPack = False, typeCode = FieldType {getFieldType = 11}, typeName = Just (ProtoName {protobufName = FIName \".Lol.Kq1\", haskellPrefix = [MName \"Crypto\",MName \"Proto\"], parentModule = [MName \"Lol\"], baseName = MName \"Kq1\"}), hsRawDefault = Nothing, hsDefault = Nothing}], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False},DescriptorInfo {descName = ProtoName {protobufName = FIName \".Lol.TypeRep\", haskellPrefix = [MName \"Crypto\",MName \"Proto\"], parentModule = [MName \"Lol\"], baseName = MName \"TypeRep\"}, descFilePath = [\"Crypto\",\"Proto\",\"Lol\",\"TypeRep.hs\"], isGroup = False, fields = fromList [FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".Lol.TypeRep.a\", haskellPrefix' = [MName \"Crypto\",MName \"Proto\"], parentModule' = [MName \"Lol\",MName \"TypeRep\"], baseName' = FName \"a\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 1}, wireTag = WireTag {getWireTag = 8}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 4}, typeName = Nothing, hsRawDefault = Nothing, hsDefault = Nothing},FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".Lol.TypeRep.b\", haskellPrefix' = [MName \"Crypto\",MName \"Proto\"], parentModule' = [MName \"Lol\",MName \"TypeRep\"], baseName' = FName \"b\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 2}, wireTag = WireTag {getWireTag = 16}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 4}, typeName = Nothing, hsRawDefault = Nothing, hsDefault = Nothing}], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False}], enums = [], oneofs = [], knownKeyMap = fromList []}"
+    "ProtoInfo {protoMod = ProtoName {protobufName = FIName \".crypto.proto.lol\", haskellPrefix = [], parentModule = [MName \"Crypto\",MName \"Proto\"], baseName = MName \"Lol\"}, protoFilePath = [\"Crypto\",\"Proto\",\"Lol.hs\"], protoSource = \"Lol.proto\", extensionKeys = fromList [], messages = [DescriptorInfo {descName = ProtoName {protobufName = FIName \".crypto.proto.lol.LinearRq\", haskellPrefix = [], parentModule = [MName \"Crypto\",MName \"Proto\",MName \"Lol\"], baseName = MName \"LinearRq\"}, descFilePath = [\"Crypto\",\"Proto\",\"Lol\",\"LinearRq.hs\"], isGroup = False, fields = fromList [FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".crypto.proto.lol.LinearRq.e\", haskellPrefix' = [], parentModule' = [MName \"Crypto\",MName \"Proto\",MName \"Lol\",MName \"LinearRq\"], baseName' = FName \"e\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 1}, wireTag = WireTag {getWireTag = 8}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 13}, typeName = Nothing, hsRawDefault = Nothing, hsDefault = Nothing},FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".crypto.proto.lol.LinearRq.r\", haskellPrefix' = [], parentModule' = [MName \"Crypto\",MName \"Proto\",MName \"Lol\",MName \"LinearRq\"], baseName' = FName \"r\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 2}, wireTag = WireTag {getWireTag = 16}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 13}, typeName = Nothing, hsRawDefault = Nothing, hsDefault = Nothing},FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".crypto.proto.lol.LinearRq.coeffs\", haskellPrefix' = [], parentModule' = [MName \"Crypto\",MName \"Proto\",MName \"Lol\",MName \"LinearRq\"], baseName' = FName \"coeffs\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 3}, wireTag = WireTag {getWireTag = 26}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = False, canRepeat = True, mightPack = False, typeCode = FieldType {getFieldType = 11}, typeName = Just (ProtoName {protobufName = FIName \".crypto.proto.lol.RqProduct\", haskellPrefix = [], parentModule = [MName \"Crypto\",MName \"Proto\",MName \"Lol\"], baseName = MName \"RqProduct\"}), hsRawDefault = Nothing, hsDefault = Nothing}], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False},DescriptorInfo {descName = ProtoName {protobufName = FIName \".crypto.proto.lol.R\", haskellPrefix = [], parentModule = [MName \"Crypto\",MName \"Proto\",MName \"Lol\"], baseName = MName \"R\"}, descFilePath = [\"Crypto\",\"Proto\",\"Lol\",\"R.hs\"], isGroup = False, fields = fromList [FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".crypto.proto.lol.R.m\", haskellPrefix' = [], parentModule' = [MName \"Crypto\",MName \"Proto\",MName \"Lol\",MName \"R\"], baseName' = FName \"m\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 1}, wireTag = WireTag {getWireTag = 8}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 13}, typeName = Nothing, hsRawDefault = Nothing, hsDefault = Nothing},FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".crypto.proto.lol.R.xs\", haskellPrefix' = [], parentModule' = [MName \"Crypto\",MName \"Proto\",MName \"Lol\",MName \"R\"], baseName' = FName \"xs\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 2}, wireTag = WireTag {getWireTag = 16}, packedTag = Just (WireTag {getWireTag = 16},WireTag {getWireTag = 18}), wireTagLength = 1, isPacked = False, isRequired = False, canRepeat = True, mightPack = True, typeCode = FieldType {getFieldType = 18}, typeName = Nothing, hsRawDefault = Nothing, hsDefault = Nothing}], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False},DescriptorInfo {descName = ProtoName {protobufName = FIName \".crypto.proto.lol.Rq\", haskellPrefix = [], parentModule = [MName \"Crypto\",MName \"Proto\",MName \"Lol\"], baseName = MName \"Rq\"}, descFilePath = [\"Crypto\",\"Proto\",\"Lol\",\"Rq.hs\"], isGroup = False, fields = fromList [FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".crypto.proto.lol.Rq.m\", haskellPrefix' = [], parentModule' = [MName \"Crypto\",MName \"Proto\",MName \"Lol\",MName \"Rq\"], baseName' = FName \"m\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 1}, wireTag = WireTag {getWireTag = 8}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 13}, typeName = Nothing, hsRawDefault = Nothing, hsDefault = Nothing},FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".crypto.proto.lol.Rq.q\", haskellPrefix' = [], parentModule' = [MName \"Crypto\",MName \"Proto\",MName \"Lol\",MName \"Rq\"], baseName' = FName \"q\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 2}, wireTag = WireTag {getWireTag = 16}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 4}, typeName = Nothing, hsRawDefault = Nothing, hsDefault = Nothing},FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".crypto.proto.lol.Rq.xs\", haskellPrefix' = [], parentModule' = [MName \"Crypto\",MName \"Proto\",MName \"Lol\",MName \"Rq\"], baseName' = FName \"xs\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 3}, wireTag = WireTag {getWireTag = 24}, packedTag = Just (WireTag {getWireTag = 24},WireTag {getWireTag = 26}), wireTagLength = 1, isPacked = False, isRequired = False, canRepeat = True, mightPack = True, typeCode = FieldType {getFieldType = 18}, typeName = Nothing, hsRawDefault = Nothing, hsDefault = Nothing}], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False},DescriptorInfo {descName = ProtoName {protobufName = FIName \".crypto.proto.lol.Kq\", haskellPrefix = [], parentModule = [MName \"Crypto\",MName \"Proto\",MName \"Lol\"], baseName = MName \"Kq\"}, descFilePath = [\"Crypto\",\"Proto\",\"Lol\",\"Kq.hs\"], isGroup = False, fields = fromList [FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".crypto.proto.lol.Kq.m\", haskellPrefix' = [], parentModule' = [MName \"Crypto\",MName \"Proto\",MName \"Lol\",MName \"Kq\"], baseName' = FName \"m\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 1}, wireTag = WireTag {getWireTag = 8}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 13}, typeName = Nothing, hsRawDefault = Nothing, hsDefault = Nothing},FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".crypto.proto.lol.Kq.q\", haskellPrefix' = [], parentModule' = [MName \"Crypto\",MName \"Proto\",MName \"Lol\",MName \"Kq\"], baseName' = FName \"q\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 2}, wireTag = WireTag {getWireTag = 16}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 4}, typeName = Nothing, hsRawDefault = Nothing, hsDefault = Nothing},FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".crypto.proto.lol.Kq.xs\", haskellPrefix' = [], parentModule' = [MName \"Crypto\",MName \"Proto\",MName \"Lol\",MName \"Kq\"], baseName' = FName \"xs\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 3}, wireTag = WireTag {getWireTag = 25}, packedTag = Just (WireTag {getWireTag = 25},WireTag {getWireTag = 26}), wireTagLength = 1, isPacked = False, isRequired = False, canRepeat = True, mightPack = True, typeCode = FieldType {getFieldType = 1}, typeName = Nothing, hsRawDefault = Nothing, hsDefault = Nothing}], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False},DescriptorInfo {descName = ProtoName {protobufName = FIName \".crypto.proto.lol.RqProduct\", haskellPrefix = [], parentModule = [MName \"Crypto\",MName \"Proto\",MName \"Lol\"], baseName = MName \"RqProduct\"}, descFilePath = [\"Crypto\",\"Proto\",\"Lol\",\"RqProduct.hs\"], isGroup = False, fields = fromList [FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".crypto.proto.lol.RqProduct.rqs\", haskellPrefix' = [], parentModule' = [MName \"Crypto\",MName \"Proto\",MName \"Lol\",MName \"RqProduct\"], baseName' = FName \"rqs\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 1}, wireTag = WireTag {getWireTag = 10}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = False, canRepeat = True, mightPack = False, typeCode = FieldType {getFieldType = 11}, typeName = Just (ProtoName {protobufName = FIName \".crypto.proto.lol.Rq\", haskellPrefix = [], parentModule = [MName \"Crypto\",MName \"Proto\",MName \"Lol\"], baseName = MName \"Rq\"}), hsRawDefault = Nothing, hsDefault = Nothing}], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False},DescriptorInfo {descName = ProtoName {protobufName = FIName \".crypto.proto.lol.KqProduct\", haskellPrefix = [], parentModule = [MName \"Crypto\",MName \"Proto\",MName \"Lol\"], baseName = MName \"KqProduct\"}, descFilePath = [\"Crypto\",\"Proto\",\"Lol\",\"KqProduct.hs\"], isGroup = False, fields = fromList [FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".crypto.proto.lol.KqProduct.kqs\", haskellPrefix' = [], parentModule' = [MName \"Crypto\",MName \"Proto\",MName \"Lol\",MName \"KqProduct\"], baseName' = FName \"kqs\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 1}, wireTag = WireTag {getWireTag = 10}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = False, canRepeat = True, mightPack = False, typeCode = FieldType {getFieldType = 11}, typeName = Just (ProtoName {protobufName = FIName \".crypto.proto.lol.Kq\", haskellPrefix = [], parentModule = [MName \"Crypto\",MName \"Proto\",MName \"Lol\"], baseName = MName \"Kq\"}), hsRawDefault = Nothing, hsDefault = Nothing}], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False},DescriptorInfo {descName = ProtoName {protobufName = FIName \".crypto.proto.lol.TypeRep\", haskellPrefix = [], parentModule = [MName \"Crypto\",MName \"Proto\",MName \"Lol\"], baseName = MName \"TypeRep\"}, descFilePath = [\"Crypto\",\"Proto\",\"Lol\",\"TypeRep.hs\"], isGroup = False, fields = fromList [FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".crypto.proto.lol.TypeRep.a\", haskellPrefix' = [], parentModule' = [MName \"Crypto\",MName \"Proto\",MName \"Lol\",MName \"TypeRep\"], baseName' = FName \"a\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 1}, wireTag = WireTag {getWireTag = 8}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 4}, typeName = Nothing, hsRawDefault = Nothing, hsDefault = Nothing},FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".crypto.proto.lol.TypeRep.b\", haskellPrefix' = [], parentModule' = [MName \"Crypto\",MName \"Proto\",MName \"Lol\",MName \"TypeRep\"], baseName' = FName \"b\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 2}, wireTag = WireTag {getWireTag = 16}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 4}, typeName = Nothing, hsRawDefault = Nothing, hsDefault = Nothing}], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False}], enums = [], oneofs = [], knownKeyMap = fromList []}"
 
 fileDescriptorProto :: FileDescriptorProto
 fileDescriptorProto
  = P'.getFromBS (P'.wireGet 11)
     (P'.pack
-      "\170\STX\n\tLol.proto\"@\n\bLinearRq\DC2\t\n\SOHe\CAN\SOH \STX(\r\DC2\t\n\SOHr\CAN\STX \STX(\r\DC2\RS\n\ACKcoeffs\CAN\ETX \ETX(\v2\SO.Lol.RqProduct\"\SUB\n\SOHR\DC2\t\n\SOHm\CAN\SOH \STX(\r\DC2\n\n\STXxs\CAN\STX \ETX(\DC2\"'\n\ETXRq1\DC2\t\n\SOHm\CAN\SOH \STX(\r\DC2\t\n\SOHq\CAN\STX \STX(\EOT\DC2\n\n\STXxs\CAN\ETX \ETX(\DC2\"'\n\ETXKq1\DC2\t\n\SOHm\CAN\SOH \STX(\r\DC2\t\n\SOHq\CAN\STX \STX(\EOT\DC2\n\n\STXxs\CAN\ETX \ETX(\SOH\"%\n\tRqProduct\DC2\CAN\n\ACKrqlist\CAN\SOH \ETX(\v2\b.Lol.Rq1\"%\n\tKqProduct\DC2\CAN\n\ACKkqlist\CAN\SOH \ETX(\v2\b.Lol.Kq1\"\US\n\aTypeRep\DC2\t\n\SOHa\CAN\SOH \STX(\EOT\DC2\t\n\SOHb\CAN\STX \STX(\EOT")
+      "\217\STX\n\tLol.proto\DC2\DLEcrypto.proto.lol\"M\n\bLinearRq\DC2\t\n\SOHe\CAN\SOH \STX(\r\DC2\t\n\SOHr\CAN\STX \STX(\r\DC2+\n\ACKcoeffs\CAN\ETX \ETX(\v2\ESC.crypto.proto.lol.RqProduct\"\SUB\n\SOHR\DC2\t\n\SOHm\CAN\SOH \STX(\r\DC2\n\n\STXxs\CAN\STX \ETX(\DC2\"&\n\STXRq\DC2\t\n\SOHm\CAN\SOH \STX(\r\DC2\t\n\SOHq\CAN\STX \STX(\EOT\DC2\n\n\STXxs\CAN\ETX \ETX(\DC2\"&\n\STXKq\DC2\t\n\SOHm\CAN\SOH \STX(\r\DC2\t\n\SOHq\CAN\STX \STX(\EOT\DC2\n\n\STXxs\CAN\ETX \ETX(\SOH\".\n\tRqProduct\DC2!\n\ETXrqs\CAN\SOH \ETX(\v2\DC4.crypto.proto.lol.Rq\".\n\tKqProduct\DC2!\n\ETXkqs\CAN\SOH \ETX(\v2\DC4.crypto.proto.lol.Kq\"\US\n\aTypeRep\DC2\t\n\SOHa\CAN\SOH \STX(\EOT\DC2\t\n\SOHb\CAN\STX \STX(\EOT")
diff --git a/Crypto/Proto/Lol/K.hs b/Crypto/Proto/Lol/K.hs
new file mode 100644
--- /dev/null
+++ b/Crypto/Proto/Lol/K.hs
@@ -0,0 +1,87 @@
+{-# LANGUAGE BangPatterns, DeriveDataTypeable, DeriveGeneric, FlexibleInstances, MultiParamTypeClasses #-}
+{-# OPTIONS_GHC  -fno-warn-unused-imports #-}
+module Crypto.Proto.Lol.K (K(..)) where
+import Prelude ((+), (/))
+import qualified Prelude as Prelude'
+import qualified Data.Typeable as Prelude'
+import qualified GHC.Generics as Prelude'
+import qualified Data.Data as Prelude'
+import qualified Text.ProtocolBuffers.Header as P'
+
+data K = K{m :: !(P'.Word32), xs :: !(P'.Seq P'.Double)}
+         deriving (Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable, Prelude'.Data, Prelude'.Generic)
+
+instance P'.Mergeable K where
+  mergeAppend (K x'1 x'2) (K y'1 y'2) = K (P'.mergeAppend x'1 y'1) (P'.mergeAppend x'2 y'2)
+
+instance P'.Default K where
+  defaultValue = K P'.defaultValue P'.defaultValue
+
+instance P'.Wire K where
+  wireSize ft' self'@(K x'1 x'2)
+   = case ft' of
+       10 -> calc'Size
+       11 -> P'.prependMessageSize calc'Size
+       _ -> P'.wireSizeErr ft' self'
+    where
+        calc'Size = (P'.wireSizeReq 1 13 x'1 + P'.wireSizeRep 1 1 x'2)
+  wirePut ft' self'@(K x'1 x'2)
+   = case ft' of
+       10 -> put'Fields
+       11 -> do
+               P'.putSize (P'.wireSize 10 self')
+               put'Fields
+       _ -> P'.wirePutErr ft' self'
+    where
+        put'Fields
+         = do
+             P'.wirePutReq 8 13 x'1
+             P'.wirePutRep 17 1 x'2
+  wireGet ft'
+   = case ft' of
+       10 -> P'.getBareMessageWith update'Self
+       11 -> P'.getMessageWith update'Self
+       _ -> P'.wireGetErr ft'
+    where
+        update'Self wire'Tag old'Self
+         = case wire'Tag of
+             8 -> Prelude'.fmap (\ !new'Field -> old'Self{m = new'Field}) (P'.wireGet 13)
+             17 -> Prelude'.fmap (\ !new'Field -> old'Self{xs = P'.append (xs old'Self) new'Field}) (P'.wireGet 1)
+             18 -> Prelude'.fmap (\ !new'Field -> old'Self{xs = P'.mergeAppend (xs old'Self) new'Field}) (P'.wireGetPacked 1)
+             _ -> let (field'Number, wire'Type) = P'.splitWireTag wire'Tag in P'.unknown field'Number wire'Type old'Self
+
+instance P'.MessageAPI msg' (msg' -> K) K where
+  getVal m' f' = f' m'
+
+instance P'.GPB K
+
+instance P'.ReflectDescriptor K where
+  getMessageInfo _ = P'.GetMessageInfo (P'.fromDistinctAscList [8]) (P'.fromDistinctAscList [8, 17, 18])
+  reflectDescriptorInfo _
+   = Prelude'.read
+      "DescriptorInfo {descName = ProtoName {protobufName = FIName \".crypto.proto.lol.K\", haskellPrefix = [], parentModule = [MName \"Crypto\",MName \"Proto\",MName \"Lol\"], baseName = MName \"K\"}, descFilePath = [\"Crypto\",\"Proto\",\"Lol\",\"K.hs\"], isGroup = False, fields = fromList [FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".crypto.proto.lol.K.m\", haskellPrefix' = [], parentModule' = [MName \"Crypto\",MName \"Proto\",MName \"Lol\",MName \"K\"], baseName' = FName \"m\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 1}, wireTag = WireTag {getWireTag = 8}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 13}, typeName = Nothing, hsRawDefault = Nothing, hsDefault = Nothing},FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".crypto.proto.lol.K.xs\", haskellPrefix' = [], parentModule' = [MName \"Crypto\",MName \"Proto\",MName \"Lol\",MName \"K\"], baseName' = FName \"xs\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 2}, wireTag = WireTag {getWireTag = 17}, packedTag = Just (WireTag {getWireTag = 17},WireTag {getWireTag = 18}), wireTagLength = 1, isPacked = False, isRequired = False, canRepeat = True, mightPack = True, typeCode = FieldType {getFieldType = 1}, typeName = Nothing, hsRawDefault = Nothing, hsDefault = Nothing}], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False}"
+
+instance P'.TextType K where
+  tellT = P'.tellSubMessage
+  getT = P'.getSubMessage
+
+instance P'.TextMsg K where
+  textPut msg
+   = do
+       P'.tellT "m" (m msg)
+       P'.tellT "xs" (xs msg)
+  textGet
+   = do
+       mods <- P'.sepEndBy (P'.choice [parse'm, parse'xs]) P'.spaces
+       Prelude'.return (Prelude'.foldl (\ v f -> f v) P'.defaultValue mods)
+    where
+        parse'm
+         = P'.try
+            (do
+               v <- P'.getT "m"
+               Prelude'.return (\ o -> o{m = v}))
+        parse'xs
+         = P'.try
+            (do
+               v <- P'.getT "xs"
+               Prelude'.return (\ o -> o{xs = P'.append (xs o) v}))
diff --git a/Crypto/Proto/Lol/Kq.hs b/Crypto/Proto/Lol/Kq.hs
new file mode 100644
--- /dev/null
+++ b/Crypto/Proto/Lol/Kq.hs
@@ -0,0 +1,95 @@
+{-# LANGUAGE BangPatterns, DeriveDataTypeable, DeriveGeneric, FlexibleInstances, MultiParamTypeClasses #-}
+{-# OPTIONS_GHC  -fno-warn-unused-imports #-}
+module Crypto.Proto.Lol.Kq (Kq(..)) where
+import Prelude ((+), (/))
+import qualified Prelude as Prelude'
+import qualified Data.Typeable as Prelude'
+import qualified GHC.Generics as Prelude'
+import qualified Data.Data as Prelude'
+import qualified Text.ProtocolBuffers.Header as P'
+
+data Kq = Kq{m :: !(P'.Word32), q :: !(P'.Word64), xs :: !(P'.Seq P'.Double)}
+          deriving (Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable, Prelude'.Data, Prelude'.Generic)
+
+instance P'.Mergeable Kq where
+  mergeAppend (Kq x'1 x'2 x'3) (Kq y'1 y'2 y'3) = Kq (P'.mergeAppend x'1 y'1) (P'.mergeAppend x'2 y'2) (P'.mergeAppend x'3 y'3)
+
+instance P'.Default Kq where
+  defaultValue = Kq P'.defaultValue P'.defaultValue P'.defaultValue
+
+instance P'.Wire Kq where
+  wireSize ft' self'@(Kq x'1 x'2 x'3)
+   = case ft' of
+       10 -> calc'Size
+       11 -> P'.prependMessageSize calc'Size
+       _ -> P'.wireSizeErr ft' self'
+    where
+        calc'Size = (P'.wireSizeReq 1 13 x'1 + P'.wireSizeReq 1 4 x'2 + P'.wireSizeRep 1 1 x'3)
+  wirePut ft' self'@(Kq x'1 x'2 x'3)
+   = case ft' of
+       10 -> put'Fields
+       11 -> do
+               P'.putSize (P'.wireSize 10 self')
+               put'Fields
+       _ -> P'.wirePutErr ft' self'
+    where
+        put'Fields
+         = do
+             P'.wirePutReq 8 13 x'1
+             P'.wirePutReq 16 4 x'2
+             P'.wirePutRep 25 1 x'3
+  wireGet ft'
+   = case ft' of
+       10 -> P'.getBareMessageWith update'Self
+       11 -> P'.getMessageWith update'Self
+       _ -> P'.wireGetErr ft'
+    where
+        update'Self wire'Tag old'Self
+         = case wire'Tag of
+             8 -> Prelude'.fmap (\ !new'Field -> old'Self{m = new'Field}) (P'.wireGet 13)
+             16 -> Prelude'.fmap (\ !new'Field -> old'Self{q = new'Field}) (P'.wireGet 4)
+             25 -> Prelude'.fmap (\ !new'Field -> old'Self{xs = P'.append (xs old'Self) new'Field}) (P'.wireGet 1)
+             26 -> Prelude'.fmap (\ !new'Field -> old'Self{xs = P'.mergeAppend (xs old'Self) new'Field}) (P'.wireGetPacked 1)
+             _ -> let (field'Number, wire'Type) = P'.splitWireTag wire'Tag in P'.unknown field'Number wire'Type old'Self
+
+instance P'.MessageAPI msg' (msg' -> Kq) Kq where
+  getVal m' f' = f' m'
+
+instance P'.GPB Kq
+
+instance P'.ReflectDescriptor Kq where
+  getMessageInfo _ = P'.GetMessageInfo (P'.fromDistinctAscList [8, 16]) (P'.fromDistinctAscList [8, 16, 25, 26])
+  reflectDescriptorInfo _
+   = Prelude'.read
+      "DescriptorInfo {descName = ProtoName {protobufName = FIName \".crypto.proto.lol.Kq\", haskellPrefix = [], parentModule = [MName \"Crypto\",MName \"Proto\",MName \"Lol\"], baseName = MName \"Kq\"}, descFilePath = [\"Crypto\",\"Proto\",\"Lol\",\"Kq.hs\"], isGroup = False, fields = fromList [FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".crypto.proto.lol.Kq.m\", haskellPrefix' = [], parentModule' = [MName \"Crypto\",MName \"Proto\",MName \"Lol\",MName \"Kq\"], baseName' = FName \"m\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 1}, wireTag = WireTag {getWireTag = 8}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 13}, typeName = Nothing, hsRawDefault = Nothing, hsDefault = Nothing},FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".crypto.proto.lol.Kq.q\", haskellPrefix' = [], parentModule' = [MName \"Crypto\",MName \"Proto\",MName \"Lol\",MName \"Kq\"], baseName' = FName \"q\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 2}, wireTag = WireTag {getWireTag = 16}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 4}, typeName = Nothing, hsRawDefault = Nothing, hsDefault = Nothing},FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".crypto.proto.lol.Kq.xs\", haskellPrefix' = [], parentModule' = [MName \"Crypto\",MName \"Proto\",MName \"Lol\",MName \"Kq\"], baseName' = FName \"xs\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 3}, wireTag = WireTag {getWireTag = 25}, packedTag = Just (WireTag {getWireTag = 25},WireTag {getWireTag = 26}), wireTagLength = 1, isPacked = False, isRequired = False, canRepeat = True, mightPack = True, typeCode = FieldType {getFieldType = 1}, typeName = Nothing, hsRawDefault = Nothing, hsDefault = Nothing}], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False}"
+
+instance P'.TextType Kq where
+  tellT = P'.tellSubMessage
+  getT = P'.getSubMessage
+
+instance P'.TextMsg Kq where
+  textPut msg
+   = do
+       P'.tellT "m" (m msg)
+       P'.tellT "q" (q msg)
+       P'.tellT "xs" (xs msg)
+  textGet
+   = do
+       mods <- P'.sepEndBy (P'.choice [parse'm, parse'q, parse'xs]) P'.spaces
+       Prelude'.return (Prelude'.foldl (\ v f -> f v) P'.defaultValue mods)
+    where
+        parse'm
+         = P'.try
+            (do
+               v <- P'.getT "m"
+               Prelude'.return (\ o -> o{m = v}))
+        parse'q
+         = P'.try
+            (do
+               v <- P'.getT "q"
+               Prelude'.return (\ o -> o{q = v}))
+        parse'xs
+         = P'.try
+            (do
+               v <- P'.getT "xs"
+               Prelude'.return (\ o -> o{xs = P'.append (xs o) v}))
diff --git a/Crypto/Proto/Lol/Kq1.hs b/Crypto/Proto/Lol/Kq1.hs
deleted file mode 100644
--- a/Crypto/Proto/Lol/Kq1.hs
+++ /dev/null
@@ -1,95 +0,0 @@
-{-# LANGUAGE BangPatterns, DeriveDataTypeable, DeriveGeneric, FlexibleInstances, MultiParamTypeClasses #-}
-{-# OPTIONS_GHC  -fno-warn-unused-imports #-}
-module Crypto.Proto.Lol.Kq1 (Kq1(..)) where
-import Prelude ((+), (/))
-import qualified Prelude as Prelude'
-import qualified Data.Typeable as Prelude'
-import qualified GHC.Generics as Prelude'
-import qualified Data.Data as Prelude'
-import qualified Text.ProtocolBuffers.Header as P'
-
-data Kq1 = Kq1{m :: !(P'.Word32), q :: !(P'.Word64), xs :: !(P'.Seq P'.Double)}
-         deriving (Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable, Prelude'.Data, Prelude'.Generic)
-
-instance P'.Mergeable Kq1 where
-  mergeAppend (Kq1 x'1 x'2 x'3) (Kq1 y'1 y'2 y'3) = Kq1 (P'.mergeAppend x'1 y'1) (P'.mergeAppend x'2 y'2) (P'.mergeAppend x'3 y'3)
-
-instance P'.Default Kq1 where
-  defaultValue = Kq1 P'.defaultValue P'.defaultValue P'.defaultValue
-
-instance P'.Wire Kq1 where
-  wireSize ft' self'@(Kq1 x'1 x'2 x'3)
-   = case ft' of
-       10 -> calc'Size
-       11 -> P'.prependMessageSize calc'Size
-       _ -> P'.wireSizeErr ft' self'
-    where
-        calc'Size = (P'.wireSizeReq 1 13 x'1 + P'.wireSizeReq 1 4 x'2 + P'.wireSizeRep 1 1 x'3)
-  wirePut ft' self'@(Kq1 x'1 x'2 x'3)
-   = case ft' of
-       10 -> put'Fields
-       11 -> do
-               P'.putSize (P'.wireSize 10 self')
-               put'Fields
-       _ -> P'.wirePutErr ft' self'
-    where
-        put'Fields
-         = do
-             P'.wirePutReq 8 13 x'1
-             P'.wirePutReq 16 4 x'2
-             P'.wirePutRep 25 1 x'3
-  wireGet ft'
-   = case ft' of
-       10 -> P'.getBareMessageWith update'Self
-       11 -> P'.getMessageWith update'Self
-       _ -> P'.wireGetErr ft'
-    where
-        update'Self wire'Tag old'Self
-         = case wire'Tag of
-             8 -> Prelude'.fmap (\ !new'Field -> old'Self{m = new'Field}) (P'.wireGet 13)
-             16 -> Prelude'.fmap (\ !new'Field -> old'Self{q = new'Field}) (P'.wireGet 4)
-             25 -> Prelude'.fmap (\ !new'Field -> old'Self{xs = P'.append (xs old'Self) new'Field}) (P'.wireGet 1)
-             26 -> Prelude'.fmap (\ !new'Field -> old'Self{xs = P'.mergeAppend (xs old'Self) new'Field}) (P'.wireGetPacked 1)
-             _ -> let (field'Number, wire'Type) = P'.splitWireTag wire'Tag in P'.unknown field'Number wire'Type old'Self
-
-instance P'.MessageAPI msg' (msg' -> Kq1) Kq1 where
-  getVal m' f' = f' m'
-
-instance P'.GPB Kq1
-
-instance P'.ReflectDescriptor Kq1 where
-  getMessageInfo _ = P'.GetMessageInfo (P'.fromDistinctAscList [8, 16]) (P'.fromDistinctAscList [8, 16, 25, 26])
-  reflectDescriptorInfo _
-   = Prelude'.read
-      "DescriptorInfo {descName = ProtoName {protobufName = FIName \".Lol.Kq1\", haskellPrefix = [MName \"Crypto\",MName \"Proto\"], parentModule = [MName \"Lol\"], baseName = MName \"Kq1\"}, descFilePath = [\"Crypto\",\"Proto\",\"Lol\",\"Kq1.hs\"], isGroup = False, fields = fromList [FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".Lol.Kq1.m\", haskellPrefix' = [MName \"Crypto\",MName \"Proto\"], parentModule' = [MName \"Lol\",MName \"Kq1\"], baseName' = FName \"m\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 1}, wireTag = WireTag {getWireTag = 8}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 13}, typeName = Nothing, hsRawDefault = Nothing, hsDefault = Nothing},FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".Lol.Kq1.q\", haskellPrefix' = [MName \"Crypto\",MName \"Proto\"], parentModule' = [MName \"Lol\",MName \"Kq1\"], baseName' = FName \"q\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 2}, wireTag = WireTag {getWireTag = 16}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 4}, typeName = Nothing, hsRawDefault = Nothing, hsDefault = Nothing},FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".Lol.Kq1.xs\", haskellPrefix' = [MName \"Crypto\",MName \"Proto\"], parentModule' = [MName \"Lol\",MName \"Kq1\"], baseName' = FName \"xs\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 3}, wireTag = WireTag {getWireTag = 25}, packedTag = Just (WireTag {getWireTag = 25},WireTag {getWireTag = 26}), wireTagLength = 1, isPacked = False, isRequired = False, canRepeat = True, mightPack = True, typeCode = FieldType {getFieldType = 1}, typeName = Nothing, hsRawDefault = Nothing, hsDefault = Nothing}], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False}"
-
-instance P'.TextType Kq1 where
-  tellT = P'.tellSubMessage
-  getT = P'.getSubMessage
-
-instance P'.TextMsg Kq1 where
-  textPut msg
-   = do
-       P'.tellT "m" (m msg)
-       P'.tellT "q" (q msg)
-       P'.tellT "xs" (xs msg)
-  textGet
-   = do
-       mods <- P'.sepEndBy (P'.choice [parse'm, parse'q, parse'xs]) P'.spaces
-       Prelude'.return (Prelude'.foldl (\ v f -> f v) P'.defaultValue mods)
-    where
-        parse'm
-         = P'.try
-            (do
-               v <- P'.getT "m"
-               Prelude'.return (\ o -> o{m = v}))
-        parse'q
-         = P'.try
-            (do
-               v <- P'.getT "q"
-               Prelude'.return (\ o -> o{q = v}))
-        parse'xs
-         = P'.try
-            (do
-               v <- P'.getT "xs"
-               Prelude'.return (\ o -> o{xs = P'.append (xs o) v}))
diff --git a/Crypto/Proto/Lol/KqProduct.hs b/Crypto/Proto/Lol/KqProduct.hs
--- a/Crypto/Proto/Lol/KqProduct.hs
+++ b/Crypto/Proto/Lol/KqProduct.hs
@@ -7,10 +7,10 @@
 import qualified GHC.Generics as Prelude'
 import qualified Data.Data as Prelude'
 import qualified Text.ProtocolBuffers.Header as P'
-import qualified Crypto.Proto.Lol.Kq1 as Lol (Kq1)
+import qualified Crypto.Proto.Lol.Kq as Crypto.Proto.Lol (Kq)
 
-data KqProduct = KqProduct{kqlist :: !(P'.Seq Lol.Kq1)}
-               deriving (Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable, Prelude'.Data, Prelude'.Generic)
+data KqProduct = KqProduct{kqs :: !(P'.Seq Crypto.Proto.Lol.Kq)}
+                 deriving (Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable, Prelude'.Data, Prelude'.Generic)
 
 instance P'.Mergeable KqProduct where
   mergeAppend (KqProduct x'1) (KqProduct y'1) = KqProduct (P'.mergeAppend x'1 y'1)
@@ -45,7 +45,7 @@
     where
         update'Self wire'Tag old'Self
          = case wire'Tag of
-             10 -> Prelude'.fmap (\ !new'Field -> old'Self{kqlist = P'.append (kqlist old'Self) new'Field}) (P'.wireGet 11)
+             10 -> Prelude'.fmap (\ !new'Field -> old'Self{kqs = P'.append (kqs old'Self) new'Field}) (P'.wireGet 11)
              _ -> let (field'Number, wire'Type) = P'.splitWireTag wire'Tag in P'.unknown field'Number wire'Type old'Self
 
 instance P'.MessageAPI msg' (msg' -> KqProduct) KqProduct where
@@ -57,7 +57,7 @@
   getMessageInfo _ = P'.GetMessageInfo (P'.fromDistinctAscList []) (P'.fromDistinctAscList [10])
   reflectDescriptorInfo _
    = Prelude'.read
-      "DescriptorInfo {descName = ProtoName {protobufName = FIName \".Lol.KqProduct\", haskellPrefix = [MName \"Crypto\",MName \"Proto\"], parentModule = [MName \"Lol\"], baseName = MName \"KqProduct\"}, descFilePath = [\"Crypto\",\"Proto\",\"Lol\",\"KqProduct.hs\"], isGroup = False, fields = fromList [FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".Lol.KqProduct.kqlist\", haskellPrefix' = [MName \"Crypto\",MName \"Proto\"], parentModule' = [MName \"Lol\",MName \"KqProduct\"], baseName' = FName \"kqlist\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 1}, wireTag = WireTag {getWireTag = 10}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = False, canRepeat = True, mightPack = False, typeCode = FieldType {getFieldType = 11}, typeName = Just (ProtoName {protobufName = FIName \".Lol.Kq1\", haskellPrefix = [MName \"Crypto\",MName \"Proto\"], parentModule = [MName \"Lol\"], baseName = MName \"Kq1\"}), hsRawDefault = Nothing, hsDefault = Nothing}], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False}"
+      "DescriptorInfo {descName = ProtoName {protobufName = FIName \".crypto.proto.lol.KqProduct\", haskellPrefix = [], parentModule = [MName \"Crypto\",MName \"Proto\",MName \"Lol\"], baseName = MName \"KqProduct\"}, descFilePath = [\"Crypto\",\"Proto\",\"Lol\",\"KqProduct.hs\"], isGroup = False, fields = fromList [FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".crypto.proto.lol.KqProduct.kqs\", haskellPrefix' = [], parentModule' = [MName \"Crypto\",MName \"Proto\",MName \"Lol\",MName \"KqProduct\"], baseName' = FName \"kqs\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 1}, wireTag = WireTag {getWireTag = 10}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = False, canRepeat = True, mightPack = False, typeCode = FieldType {getFieldType = 11}, typeName = Just (ProtoName {protobufName = FIName \".crypto.proto.lol.Kq\", haskellPrefix = [], parentModule = [MName \"Crypto\",MName \"Proto\",MName \"Lol\"], baseName = MName \"Kq\"}), hsRawDefault = Nothing, hsDefault = Nothing}], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False}"
 
 instance P'.TextType KqProduct where
   tellT = P'.tellSubMessage
@@ -66,14 +66,14 @@
 instance P'.TextMsg KqProduct where
   textPut msg
    = do
-       P'.tellT "kqlist" (kqlist msg)
+       P'.tellT "kqs" (kqs msg)
   textGet
    = do
-       mods <- P'.sepEndBy (P'.choice [parse'kqlist]) P'.spaces
+       mods <- P'.sepEndBy (P'.choice [parse'kqs]) P'.spaces
        Prelude'.return (Prelude'.foldl (\ v f -> f v) P'.defaultValue mods)
     where
-        parse'kqlist
+        parse'kqs
          = P'.try
             (do
-               v <- P'.getT "kqlist"
-               Prelude'.return (\ o -> o{kqlist = P'.append (kqlist o) v}))
+               v <- P'.getT "kqs"
+               Prelude'.return (\ o -> o{kqs = P'.append (kqs o) v}))
diff --git a/Crypto/Proto/Lol/LinearRq.hs b/Crypto/Proto/Lol/LinearRq.hs
--- a/Crypto/Proto/Lol/LinearRq.hs
+++ b/Crypto/Proto/Lol/LinearRq.hs
@@ -7,10 +7,10 @@
 import qualified GHC.Generics as Prelude'
 import qualified Data.Data as Prelude'
 import qualified Text.ProtocolBuffers.Header as P'
-import qualified Crypto.Proto.Lol.RqProduct as Lol (RqProduct)
+import qualified Crypto.Proto.Lol.RqProduct as Crypto.Proto.Lol (RqProduct)
 
-data LinearRq = LinearRq{e :: !(P'.Word32), r :: !(P'.Word32), coeffs :: !(P'.Seq Lol.RqProduct)}
-              deriving (Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable, Prelude'.Data, Prelude'.Generic)
+data LinearRq = LinearRq{e :: !(P'.Word32), r :: !(P'.Word32), coeffs :: !(P'.Seq Crypto.Proto.Lol.RqProduct)}
+                deriving (Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable, Prelude'.Data, Prelude'.Generic)
 
 instance P'.Mergeable LinearRq where
   mergeAppend (LinearRq x'1 x'2 x'3) (LinearRq y'1 y'2 y'3)
@@ -62,7 +62,7 @@
   getMessageInfo _ = P'.GetMessageInfo (P'.fromDistinctAscList [8, 16]) (P'.fromDistinctAscList [8, 16, 26])
   reflectDescriptorInfo _
    = Prelude'.read
-      "DescriptorInfo {descName = ProtoName {protobufName = FIName \".Lol.LinearRq\", haskellPrefix = [MName \"Crypto\",MName \"Proto\"], parentModule = [MName \"Lol\"], baseName = MName \"LinearRq\"}, descFilePath = [\"Crypto\",\"Proto\",\"Lol\",\"LinearRq.hs\"], isGroup = False, fields = fromList [FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".Lol.LinearRq.e\", haskellPrefix' = [MName \"Crypto\",MName \"Proto\"], parentModule' = [MName \"Lol\",MName \"LinearRq\"], baseName' = FName \"e\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 1}, wireTag = WireTag {getWireTag = 8}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 13}, typeName = Nothing, hsRawDefault = Nothing, hsDefault = Nothing},FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".Lol.LinearRq.r\", haskellPrefix' = [MName \"Crypto\",MName \"Proto\"], parentModule' = [MName \"Lol\",MName \"LinearRq\"], baseName' = FName \"r\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 2}, wireTag = WireTag {getWireTag = 16}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 13}, typeName = Nothing, hsRawDefault = Nothing, hsDefault = Nothing},FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".Lol.LinearRq.coeffs\", haskellPrefix' = [MName \"Crypto\",MName \"Proto\"], parentModule' = [MName \"Lol\",MName \"LinearRq\"], baseName' = FName \"coeffs\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 3}, wireTag = WireTag {getWireTag = 26}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = False, canRepeat = True, mightPack = False, typeCode = FieldType {getFieldType = 11}, typeName = Just (ProtoName {protobufName = FIName \".Lol.RqProduct\", haskellPrefix = [MName \"Crypto\",MName \"Proto\"], parentModule = [MName \"Lol\"], baseName = MName \"RqProduct\"}), hsRawDefault = Nothing, hsDefault = Nothing}], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False}"
+      "DescriptorInfo {descName = ProtoName {protobufName = FIName \".crypto.proto.lol.LinearRq\", haskellPrefix = [], parentModule = [MName \"Crypto\",MName \"Proto\",MName \"Lol\"], baseName = MName \"LinearRq\"}, descFilePath = [\"Crypto\",\"Proto\",\"Lol\",\"LinearRq.hs\"], isGroup = False, fields = fromList [FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".crypto.proto.lol.LinearRq.e\", haskellPrefix' = [], parentModule' = [MName \"Crypto\",MName \"Proto\",MName \"Lol\",MName \"LinearRq\"], baseName' = FName \"e\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 1}, wireTag = WireTag {getWireTag = 8}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 13}, typeName = Nothing, hsRawDefault = Nothing, hsDefault = Nothing},FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".crypto.proto.lol.LinearRq.r\", haskellPrefix' = [], parentModule' = [MName \"Crypto\",MName \"Proto\",MName \"Lol\",MName \"LinearRq\"], baseName' = FName \"r\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 2}, wireTag = WireTag {getWireTag = 16}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 13}, typeName = Nothing, hsRawDefault = Nothing, hsDefault = Nothing},FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".crypto.proto.lol.LinearRq.coeffs\", haskellPrefix' = [], parentModule' = [MName \"Crypto\",MName \"Proto\",MName \"Lol\",MName \"LinearRq\"], baseName' = FName \"coeffs\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 3}, wireTag = WireTag {getWireTag = 26}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = False, canRepeat = True, mightPack = False, typeCode = FieldType {getFieldType = 11}, typeName = Just (ProtoName {protobufName = FIName \".crypto.proto.lol.RqProduct\", haskellPrefix = [], parentModule = [MName \"Crypto\",MName \"Proto\",MName \"Lol\"], baseName = MName \"RqProduct\"}), hsRawDefault = Nothing, hsDefault = Nothing}], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False}"
 
 instance P'.TextType LinearRq where
   tellT = P'.tellSubMessage
diff --git a/Crypto/Proto/Lol/R.hs b/Crypto/Proto/Lol/R.hs
--- a/Crypto/Proto/Lol/R.hs
+++ b/Crypto/Proto/Lol/R.hs
@@ -9,7 +9,7 @@
 import qualified Text.ProtocolBuffers.Header as P'
 
 data R = R{m :: !(P'.Word32), xs :: !(P'.Seq P'.Int64)}
-       deriving (Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable, Prelude'.Data, Prelude'.Generic)
+         deriving (Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable, Prelude'.Data, Prelude'.Generic)
 
 instance P'.Mergeable R where
   mergeAppend (R x'1 x'2) (R y'1 y'2) = R (P'.mergeAppend x'1 y'1) (P'.mergeAppend x'2 y'2)
@@ -59,7 +59,7 @@
   getMessageInfo _ = P'.GetMessageInfo (P'.fromDistinctAscList [8]) (P'.fromDistinctAscList [8, 16, 18])
   reflectDescriptorInfo _
    = Prelude'.read
-      "DescriptorInfo {descName = ProtoName {protobufName = FIName \".Lol.R\", haskellPrefix = [MName \"Crypto\",MName \"Proto\"], parentModule = [MName \"Lol\"], baseName = MName \"R\"}, descFilePath = [\"Crypto\",\"Proto\",\"Lol\",\"R.hs\"], isGroup = False, fields = fromList [FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".Lol.R.m\", haskellPrefix' = [MName \"Crypto\",MName \"Proto\"], parentModule' = [MName \"Lol\",MName \"R\"], baseName' = FName \"m\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 1}, wireTag = WireTag {getWireTag = 8}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 13}, typeName = Nothing, hsRawDefault = Nothing, hsDefault = Nothing},FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".Lol.R.xs\", haskellPrefix' = [MName \"Crypto\",MName \"Proto\"], parentModule' = [MName \"Lol\",MName \"R\"], baseName' = FName \"xs\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 2}, wireTag = WireTag {getWireTag = 16}, packedTag = Just (WireTag {getWireTag = 16},WireTag {getWireTag = 18}), wireTagLength = 1, isPacked = False, isRequired = False, canRepeat = True, mightPack = True, typeCode = FieldType {getFieldType = 18}, typeName = Nothing, hsRawDefault = Nothing, hsDefault = Nothing}], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False}"
+      "DescriptorInfo {descName = ProtoName {protobufName = FIName \".crypto.proto.lol.R\", haskellPrefix = [], parentModule = [MName \"Crypto\",MName \"Proto\",MName \"Lol\"], baseName = MName \"R\"}, descFilePath = [\"Crypto\",\"Proto\",\"Lol\",\"R.hs\"], isGroup = False, fields = fromList [FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".crypto.proto.lol.R.m\", haskellPrefix' = [], parentModule' = [MName \"Crypto\",MName \"Proto\",MName \"Lol\",MName \"R\"], baseName' = FName \"m\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 1}, wireTag = WireTag {getWireTag = 8}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 13}, typeName = Nothing, hsRawDefault = Nothing, hsDefault = Nothing},FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".crypto.proto.lol.R.xs\", haskellPrefix' = [], parentModule' = [MName \"Crypto\",MName \"Proto\",MName \"Lol\",MName \"R\"], baseName' = FName \"xs\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 2}, wireTag = WireTag {getWireTag = 16}, packedTag = Just (WireTag {getWireTag = 16},WireTag {getWireTag = 18}), wireTagLength = 1, isPacked = False, isRequired = False, canRepeat = True, mightPack = True, typeCode = FieldType {getFieldType = 18}, typeName = Nothing, hsRawDefault = Nothing, hsDefault = Nothing}], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False}"
 
 instance P'.TextType R where
   tellT = P'.tellSubMessage
diff --git a/Crypto/Proto/Lol/Rq.hs b/Crypto/Proto/Lol/Rq.hs
new file mode 100644
--- /dev/null
+++ b/Crypto/Proto/Lol/Rq.hs
@@ -0,0 +1,95 @@
+{-# LANGUAGE BangPatterns, DeriveDataTypeable, DeriveGeneric, FlexibleInstances, MultiParamTypeClasses #-}
+{-# OPTIONS_GHC  -fno-warn-unused-imports #-}
+module Crypto.Proto.Lol.Rq (Rq(..)) where
+import Prelude ((+), (/))
+import qualified Prelude as Prelude'
+import qualified Data.Typeable as Prelude'
+import qualified GHC.Generics as Prelude'
+import qualified Data.Data as Prelude'
+import qualified Text.ProtocolBuffers.Header as P'
+
+data Rq = Rq{m :: !(P'.Word32), q :: !(P'.Word64), xs :: !(P'.Seq P'.Int64)}
+          deriving (Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable, Prelude'.Data, Prelude'.Generic)
+
+instance P'.Mergeable Rq where
+  mergeAppend (Rq x'1 x'2 x'3) (Rq y'1 y'2 y'3) = Rq (P'.mergeAppend x'1 y'1) (P'.mergeAppend x'2 y'2) (P'.mergeAppend x'3 y'3)
+
+instance P'.Default Rq where
+  defaultValue = Rq P'.defaultValue P'.defaultValue P'.defaultValue
+
+instance P'.Wire Rq where
+  wireSize ft' self'@(Rq x'1 x'2 x'3)
+   = case ft' of
+       10 -> calc'Size
+       11 -> P'.prependMessageSize calc'Size
+       _ -> P'.wireSizeErr ft' self'
+    where
+        calc'Size = (P'.wireSizeReq 1 13 x'1 + P'.wireSizeReq 1 4 x'2 + P'.wireSizeRep 1 18 x'3)
+  wirePut ft' self'@(Rq x'1 x'2 x'3)
+   = case ft' of
+       10 -> put'Fields
+       11 -> do
+               P'.putSize (P'.wireSize 10 self')
+               put'Fields
+       _ -> P'.wirePutErr ft' self'
+    where
+        put'Fields
+         = do
+             P'.wirePutReq 8 13 x'1
+             P'.wirePutReq 16 4 x'2
+             P'.wirePutRep 24 18 x'3
+  wireGet ft'
+   = case ft' of
+       10 -> P'.getBareMessageWith update'Self
+       11 -> P'.getMessageWith update'Self
+       _ -> P'.wireGetErr ft'
+    where
+        update'Self wire'Tag old'Self
+         = case wire'Tag of
+             8 -> Prelude'.fmap (\ !new'Field -> old'Self{m = new'Field}) (P'.wireGet 13)
+             16 -> Prelude'.fmap (\ !new'Field -> old'Self{q = new'Field}) (P'.wireGet 4)
+             24 -> Prelude'.fmap (\ !new'Field -> old'Self{xs = P'.append (xs old'Self) new'Field}) (P'.wireGet 18)
+             26 -> Prelude'.fmap (\ !new'Field -> old'Self{xs = P'.mergeAppend (xs old'Self) new'Field}) (P'.wireGetPacked 18)
+             _ -> let (field'Number, wire'Type) = P'.splitWireTag wire'Tag in P'.unknown field'Number wire'Type old'Self
+
+instance P'.MessageAPI msg' (msg' -> Rq) Rq where
+  getVal m' f' = f' m'
+
+instance P'.GPB Rq
+
+instance P'.ReflectDescriptor Rq where
+  getMessageInfo _ = P'.GetMessageInfo (P'.fromDistinctAscList [8, 16]) (P'.fromDistinctAscList [8, 16, 24, 26])
+  reflectDescriptorInfo _
+   = Prelude'.read
+      "DescriptorInfo {descName = ProtoName {protobufName = FIName \".crypto.proto.lol.Rq\", haskellPrefix = [], parentModule = [MName \"Crypto\",MName \"Proto\",MName \"Lol\"], baseName = MName \"Rq\"}, descFilePath = [\"Crypto\",\"Proto\",\"Lol\",\"Rq.hs\"], isGroup = False, fields = fromList [FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".crypto.proto.lol.Rq.m\", haskellPrefix' = [], parentModule' = [MName \"Crypto\",MName \"Proto\",MName \"Lol\",MName \"Rq\"], baseName' = FName \"m\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 1}, wireTag = WireTag {getWireTag = 8}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 13}, typeName = Nothing, hsRawDefault = Nothing, hsDefault = Nothing},FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".crypto.proto.lol.Rq.q\", haskellPrefix' = [], parentModule' = [MName \"Crypto\",MName \"Proto\",MName \"Lol\",MName \"Rq\"], baseName' = FName \"q\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 2}, wireTag = WireTag {getWireTag = 16}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 4}, typeName = Nothing, hsRawDefault = Nothing, hsDefault = Nothing},FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".crypto.proto.lol.Rq.xs\", haskellPrefix' = [], parentModule' = [MName \"Crypto\",MName \"Proto\",MName \"Lol\",MName \"Rq\"], baseName' = FName \"xs\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 3}, wireTag = WireTag {getWireTag = 24}, packedTag = Just (WireTag {getWireTag = 24},WireTag {getWireTag = 26}), wireTagLength = 1, isPacked = False, isRequired = False, canRepeat = True, mightPack = True, typeCode = FieldType {getFieldType = 18}, typeName = Nothing, hsRawDefault = Nothing, hsDefault = Nothing}], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False}"
+
+instance P'.TextType Rq where
+  tellT = P'.tellSubMessage
+  getT = P'.getSubMessage
+
+instance P'.TextMsg Rq where
+  textPut msg
+   = do
+       P'.tellT "m" (m msg)
+       P'.tellT "q" (q msg)
+       P'.tellT "xs" (xs msg)
+  textGet
+   = do
+       mods <- P'.sepEndBy (P'.choice [parse'm, parse'q, parse'xs]) P'.spaces
+       Prelude'.return (Prelude'.foldl (\ v f -> f v) P'.defaultValue mods)
+    where
+        parse'm
+         = P'.try
+            (do
+               v <- P'.getT "m"
+               Prelude'.return (\ o -> o{m = v}))
+        parse'q
+         = P'.try
+            (do
+               v <- P'.getT "q"
+               Prelude'.return (\ o -> o{q = v}))
+        parse'xs
+         = P'.try
+            (do
+               v <- P'.getT "xs"
+               Prelude'.return (\ o -> o{xs = P'.append (xs o) v}))
diff --git a/Crypto/Proto/Lol/Rq1.hs b/Crypto/Proto/Lol/Rq1.hs
deleted file mode 100644
--- a/Crypto/Proto/Lol/Rq1.hs
+++ /dev/null
@@ -1,95 +0,0 @@
-{-# LANGUAGE BangPatterns, DeriveDataTypeable, DeriveGeneric, FlexibleInstances, MultiParamTypeClasses #-}
-{-# OPTIONS_GHC  -fno-warn-unused-imports #-}
-module Crypto.Proto.Lol.Rq1 (Rq1(..)) where
-import Prelude ((+), (/))
-import qualified Prelude as Prelude'
-import qualified Data.Typeable as Prelude'
-import qualified GHC.Generics as Prelude'
-import qualified Data.Data as Prelude'
-import qualified Text.ProtocolBuffers.Header as P'
-
-data Rq1 = Rq1{m :: !(P'.Word32), q :: !(P'.Word64), xs :: !(P'.Seq P'.Int64)}
-         deriving (Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable, Prelude'.Data, Prelude'.Generic)
-
-instance P'.Mergeable Rq1 where
-  mergeAppend (Rq1 x'1 x'2 x'3) (Rq1 y'1 y'2 y'3) = Rq1 (P'.mergeAppend x'1 y'1) (P'.mergeAppend x'2 y'2) (P'.mergeAppend x'3 y'3)
-
-instance P'.Default Rq1 where
-  defaultValue = Rq1 P'.defaultValue P'.defaultValue P'.defaultValue
-
-instance P'.Wire Rq1 where
-  wireSize ft' self'@(Rq1 x'1 x'2 x'3)
-   = case ft' of
-       10 -> calc'Size
-       11 -> P'.prependMessageSize calc'Size
-       _ -> P'.wireSizeErr ft' self'
-    where
-        calc'Size = (P'.wireSizeReq 1 13 x'1 + P'.wireSizeReq 1 4 x'2 + P'.wireSizeRep 1 18 x'3)
-  wirePut ft' self'@(Rq1 x'1 x'2 x'3)
-   = case ft' of
-       10 -> put'Fields
-       11 -> do
-               P'.putSize (P'.wireSize 10 self')
-               put'Fields
-       _ -> P'.wirePutErr ft' self'
-    where
-        put'Fields
-         = do
-             P'.wirePutReq 8 13 x'1
-             P'.wirePutReq 16 4 x'2
-             P'.wirePutRep 24 18 x'3
-  wireGet ft'
-   = case ft' of
-       10 -> P'.getBareMessageWith update'Self
-       11 -> P'.getMessageWith update'Self
-       _ -> P'.wireGetErr ft'
-    where
-        update'Self wire'Tag old'Self
-         = case wire'Tag of
-             8 -> Prelude'.fmap (\ !new'Field -> old'Self{m = new'Field}) (P'.wireGet 13)
-             16 -> Prelude'.fmap (\ !new'Field -> old'Self{q = new'Field}) (P'.wireGet 4)
-             24 -> Prelude'.fmap (\ !new'Field -> old'Self{xs = P'.append (xs old'Self) new'Field}) (P'.wireGet 18)
-             26 -> Prelude'.fmap (\ !new'Field -> old'Self{xs = P'.mergeAppend (xs old'Self) new'Field}) (P'.wireGetPacked 18)
-             _ -> let (field'Number, wire'Type) = P'.splitWireTag wire'Tag in P'.unknown field'Number wire'Type old'Self
-
-instance P'.MessageAPI msg' (msg' -> Rq1) Rq1 where
-  getVal m' f' = f' m'
-
-instance P'.GPB Rq1
-
-instance P'.ReflectDescriptor Rq1 where
-  getMessageInfo _ = P'.GetMessageInfo (P'.fromDistinctAscList [8, 16]) (P'.fromDistinctAscList [8, 16, 24, 26])
-  reflectDescriptorInfo _
-   = Prelude'.read
-      "DescriptorInfo {descName = ProtoName {protobufName = FIName \".Lol.Rq1\", haskellPrefix = [MName \"Crypto\",MName \"Proto\"], parentModule = [MName \"Lol\"], baseName = MName \"Rq1\"}, descFilePath = [\"Crypto\",\"Proto\",\"Lol\",\"Rq1.hs\"], isGroup = False, fields = fromList [FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".Lol.Rq1.m\", haskellPrefix' = [MName \"Crypto\",MName \"Proto\"], parentModule' = [MName \"Lol\",MName \"Rq1\"], baseName' = FName \"m\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 1}, wireTag = WireTag {getWireTag = 8}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 13}, typeName = Nothing, hsRawDefault = Nothing, hsDefault = Nothing},FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".Lol.Rq1.q\", haskellPrefix' = [MName \"Crypto\",MName \"Proto\"], parentModule' = [MName \"Lol\",MName \"Rq1\"], baseName' = FName \"q\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 2}, wireTag = WireTag {getWireTag = 16}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 4}, typeName = Nothing, hsRawDefault = Nothing, hsDefault = Nothing},FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".Lol.Rq1.xs\", haskellPrefix' = [MName \"Crypto\",MName \"Proto\"], parentModule' = [MName \"Lol\",MName \"Rq1\"], baseName' = FName \"xs\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 3}, wireTag = WireTag {getWireTag = 24}, packedTag = Just (WireTag {getWireTag = 24},WireTag {getWireTag = 26}), wireTagLength = 1, isPacked = False, isRequired = False, canRepeat = True, mightPack = True, typeCode = FieldType {getFieldType = 18}, typeName = Nothing, hsRawDefault = Nothing, hsDefault = Nothing}], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False}"
-
-instance P'.TextType Rq1 where
-  tellT = P'.tellSubMessage
-  getT = P'.getSubMessage
-
-instance P'.TextMsg Rq1 where
-  textPut msg
-   = do
-       P'.tellT "m" (m msg)
-       P'.tellT "q" (q msg)
-       P'.tellT "xs" (xs msg)
-  textGet
-   = do
-       mods <- P'.sepEndBy (P'.choice [parse'm, parse'q, parse'xs]) P'.spaces
-       Prelude'.return (Prelude'.foldl (\ v f -> f v) P'.defaultValue mods)
-    where
-        parse'm
-         = P'.try
-            (do
-               v <- P'.getT "m"
-               Prelude'.return (\ o -> o{m = v}))
-        parse'q
-         = P'.try
-            (do
-               v <- P'.getT "q"
-               Prelude'.return (\ o -> o{q = v}))
-        parse'xs
-         = P'.try
-            (do
-               v <- P'.getT "xs"
-               Prelude'.return (\ o -> o{xs = P'.append (xs o) v}))
diff --git a/Crypto/Proto/Lol/RqProduct.hs b/Crypto/Proto/Lol/RqProduct.hs
--- a/Crypto/Proto/Lol/RqProduct.hs
+++ b/Crypto/Proto/Lol/RqProduct.hs
@@ -7,10 +7,10 @@
 import qualified GHC.Generics as Prelude'
 import qualified Data.Data as Prelude'
 import qualified Text.ProtocolBuffers.Header as P'
-import qualified Crypto.Proto.Lol.Rq1 as Lol (Rq1)
+import qualified Crypto.Proto.Lol.Rq as Crypto.Proto.Lol (Rq)
 
-data RqProduct = RqProduct{rqlist :: !(P'.Seq Lol.Rq1)}
-               deriving (Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable, Prelude'.Data, Prelude'.Generic)
+data RqProduct = RqProduct{rqs :: !(P'.Seq Crypto.Proto.Lol.Rq)}
+                 deriving (Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable, Prelude'.Data, Prelude'.Generic)
 
 instance P'.Mergeable RqProduct where
   mergeAppend (RqProduct x'1) (RqProduct y'1) = RqProduct (P'.mergeAppend x'1 y'1)
@@ -45,7 +45,7 @@
     where
         update'Self wire'Tag old'Self
          = case wire'Tag of
-             10 -> Prelude'.fmap (\ !new'Field -> old'Self{rqlist = P'.append (rqlist old'Self) new'Field}) (P'.wireGet 11)
+             10 -> Prelude'.fmap (\ !new'Field -> old'Self{rqs = P'.append (rqs old'Self) new'Field}) (P'.wireGet 11)
              _ -> let (field'Number, wire'Type) = P'.splitWireTag wire'Tag in P'.unknown field'Number wire'Type old'Self
 
 instance P'.MessageAPI msg' (msg' -> RqProduct) RqProduct where
@@ -57,7 +57,7 @@
   getMessageInfo _ = P'.GetMessageInfo (P'.fromDistinctAscList []) (P'.fromDistinctAscList [10])
   reflectDescriptorInfo _
    = Prelude'.read
-      "DescriptorInfo {descName = ProtoName {protobufName = FIName \".Lol.RqProduct\", haskellPrefix = [MName \"Crypto\",MName \"Proto\"], parentModule = [MName \"Lol\"], baseName = MName \"RqProduct\"}, descFilePath = [\"Crypto\",\"Proto\",\"Lol\",\"RqProduct.hs\"], isGroup = False, fields = fromList [FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".Lol.RqProduct.rqlist\", haskellPrefix' = [MName \"Crypto\",MName \"Proto\"], parentModule' = [MName \"Lol\",MName \"RqProduct\"], baseName' = FName \"rqlist\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 1}, wireTag = WireTag {getWireTag = 10}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = False, canRepeat = True, mightPack = False, typeCode = FieldType {getFieldType = 11}, typeName = Just (ProtoName {protobufName = FIName \".Lol.Rq1\", haskellPrefix = [MName \"Crypto\",MName \"Proto\"], parentModule = [MName \"Lol\"], baseName = MName \"Rq1\"}), hsRawDefault = Nothing, hsDefault = Nothing}], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False}"
+      "DescriptorInfo {descName = ProtoName {protobufName = FIName \".crypto.proto.lol.RqProduct\", haskellPrefix = [], parentModule = [MName \"Crypto\",MName \"Proto\",MName \"Lol\"], baseName = MName \"RqProduct\"}, descFilePath = [\"Crypto\",\"Proto\",\"Lol\",\"RqProduct.hs\"], isGroup = False, fields = fromList [FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".crypto.proto.lol.RqProduct.rqs\", haskellPrefix' = [], parentModule' = [MName \"Crypto\",MName \"Proto\",MName \"Lol\",MName \"RqProduct\"], baseName' = FName \"rqs\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 1}, wireTag = WireTag {getWireTag = 10}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = False, canRepeat = True, mightPack = False, typeCode = FieldType {getFieldType = 11}, typeName = Just (ProtoName {protobufName = FIName \".crypto.proto.lol.Rq\", haskellPrefix = [], parentModule = [MName \"Crypto\",MName \"Proto\",MName \"Lol\"], baseName = MName \"Rq\"}), hsRawDefault = Nothing, hsDefault = Nothing}], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False}"
 
 instance P'.TextType RqProduct where
   tellT = P'.tellSubMessage
@@ -66,14 +66,14 @@
 instance P'.TextMsg RqProduct where
   textPut msg
    = do
-       P'.tellT "rqlist" (rqlist msg)
+       P'.tellT "rqs" (rqs msg)
   textGet
    = do
-       mods <- P'.sepEndBy (P'.choice [parse'rqlist]) P'.spaces
+       mods <- P'.sepEndBy (P'.choice [parse'rqs]) P'.spaces
        Prelude'.return (Prelude'.foldl (\ v f -> f v) P'.defaultValue mods)
     where
-        parse'rqlist
+        parse'rqs
          = P'.try
             (do
-               v <- P'.getT "rqlist"
-               Prelude'.return (\ o -> o{rqlist = P'.append (rqlist o) v}))
+               v <- P'.getT "rqs"
+               Prelude'.return (\ o -> o{rqs = P'.append (rqs o) v}))
diff --git a/Crypto/Proto/Lol/TypeRep.hs b/Crypto/Proto/Lol/TypeRep.hs
--- a/Crypto/Proto/Lol/TypeRep.hs
+++ b/Crypto/Proto/Lol/TypeRep.hs
@@ -9,7 +9,7 @@
 import qualified Text.ProtocolBuffers.Header as P'
 
 data TypeRep = TypeRep{a :: !(P'.Word64), b :: !(P'.Word64)}
-             deriving (Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable, Prelude'.Data, Prelude'.Generic)
+               deriving (Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable, Prelude'.Data, Prelude'.Generic)
 
 instance P'.Mergeable TypeRep where
   mergeAppend (TypeRep x'1 x'2) (TypeRep y'1 y'2) = TypeRep (P'.mergeAppend x'1 y'1) (P'.mergeAppend x'2 y'2)
@@ -58,7 +58,7 @@
   getMessageInfo _ = P'.GetMessageInfo (P'.fromDistinctAscList [8, 16]) (P'.fromDistinctAscList [8, 16])
   reflectDescriptorInfo _
    = Prelude'.read
-      "DescriptorInfo {descName = ProtoName {protobufName = FIName \".Lol.TypeRep\", haskellPrefix = [MName \"Crypto\",MName \"Proto\"], parentModule = [MName \"Lol\"], baseName = MName \"TypeRep\"}, descFilePath = [\"Crypto\",\"Proto\",\"Lol\",\"TypeRep.hs\"], isGroup = False, fields = fromList [FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".Lol.TypeRep.a\", haskellPrefix' = [MName \"Crypto\",MName \"Proto\"], parentModule' = [MName \"Lol\",MName \"TypeRep\"], baseName' = FName \"a\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 1}, wireTag = WireTag {getWireTag = 8}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 4}, typeName = Nothing, hsRawDefault = Nothing, hsDefault = Nothing},FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".Lol.TypeRep.b\", haskellPrefix' = [MName \"Crypto\",MName \"Proto\"], parentModule' = [MName \"Lol\",MName \"TypeRep\"], baseName' = FName \"b\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 2}, wireTag = WireTag {getWireTag = 16}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 4}, typeName = Nothing, hsRawDefault = Nothing, hsDefault = Nothing}], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False}"
+      "DescriptorInfo {descName = ProtoName {protobufName = FIName \".crypto.proto.lol.TypeRep\", haskellPrefix = [], parentModule = [MName \"Crypto\",MName \"Proto\",MName \"Lol\"], baseName = MName \"TypeRep\"}, descFilePath = [\"Crypto\",\"Proto\",\"Lol\",\"TypeRep.hs\"], isGroup = False, fields = fromList [FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".crypto.proto.lol.TypeRep.a\", haskellPrefix' = [], parentModule' = [MName \"Crypto\",MName \"Proto\",MName \"Lol\",MName \"TypeRep\"], baseName' = FName \"a\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 1}, wireTag = WireTag {getWireTag = 8}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 4}, typeName = Nothing, hsRawDefault = Nothing, hsDefault = Nothing},FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".crypto.proto.lol.TypeRep.b\", haskellPrefix' = [], parentModule' = [MName \"Crypto\",MName \"Proto\",MName \"Lol\",MName \"TypeRep\"], baseName' = FName \"b\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 2}, wireTag = WireTag {getWireTag = 16}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 4}, typeName = Nothing, hsRawDefault = Nothing, hsDefault = Nothing}], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False}"
 
 instance P'.TextType TypeRep where
   tellT = P'.tellSubMessage
diff --git a/Crypto/Proto/RLWE.hs b/Crypto/Proto/RLWE.hs
--- a/Crypto/Proto/RLWE.hs
+++ b/Crypto/Proto/RLWE.hs
@@ -14,10 +14,10 @@
 protoInfo :: ProtoInfo
 protoInfo
  = Prelude'.read
-    "ProtoInfo {protoMod = ProtoName {protobufName = FIName \".RLWE\", haskellPrefix = [MName \"Crypto\",MName \"Proto\"], parentModule = [], baseName = MName \"RLWE\"}, protoFilePath = [\"Crypto\",\"Proto\",\"RLWE.hs\"], protoSource = \"RLWE.proto\", extensionKeys = fromList [], messages = [DescriptorInfo {descName = ProtoName {protobufName = FIName \".RLWE.SampleCont1\", haskellPrefix = [MName \"Crypto\",MName \"Proto\"], parentModule = [MName \"RLWE\"], baseName = MName \"SampleCont1\"}, descFilePath = [\"Crypto\",\"Proto\",\"RLWE\",\"SampleCont1.hs\"], isGroup = False, fields = fromList [FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".RLWE.SampleCont1.a\", haskellPrefix' = [MName \"Crypto\",MName \"Proto\"], parentModule' = [MName \"RLWE\",MName \"SampleCont1\"], baseName' = FName \"a\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 1}, wireTag = WireTag {getWireTag = 10}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 11}, typeName = Just (ProtoName {protobufName = FIName \".Lol.Rq1\", haskellPrefix = [MName \"Crypto\",MName \"Proto\"], parentModule = [MName \"Lol\"], baseName = MName \"Rq1\"}), hsRawDefault = Nothing, hsDefault = Nothing},FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".RLWE.SampleCont1.b\", haskellPrefix' = [MName \"Crypto\",MName \"Proto\"], parentModule' = [MName \"RLWE\",MName \"SampleCont1\"], baseName' = FName \"b\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 2}, wireTag = WireTag {getWireTag = 18}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 11}, typeName = Just (ProtoName {protobufName = FIName \".Lol.Kq1\", haskellPrefix = [MName \"Crypto\",MName \"Proto\"], parentModule = [MName \"Lol\"], baseName = MName \"Kq1\"}), hsRawDefault = Nothing, hsDefault = Nothing}], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False},DescriptorInfo {descName = ProtoName {protobufName = FIName \".RLWE.SampleDisc1\", haskellPrefix = [MName \"Crypto\",MName \"Proto\"], parentModule = [MName \"RLWE\"], baseName = MName \"SampleDisc1\"}, descFilePath = [\"Crypto\",\"Proto\",\"RLWE\",\"SampleDisc1.hs\"], isGroup = False, fields = fromList [FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".RLWE.SampleDisc1.a\", haskellPrefix' = [MName \"Crypto\",MName \"Proto\"], parentModule' = [MName \"RLWE\",MName \"SampleDisc1\"], baseName' = FName \"a\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 1}, wireTag = WireTag {getWireTag = 10}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 11}, typeName = Just (ProtoName {protobufName = FIName \".Lol.Rq1\", haskellPrefix = [MName \"Crypto\",MName \"Proto\"], parentModule = [MName \"Lol\"], baseName = MName \"Rq1\"}), hsRawDefault = Nothing, hsDefault = Nothing},FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".RLWE.SampleDisc1.b\", haskellPrefix' = [MName \"Crypto\",MName \"Proto\"], parentModule' = [MName \"RLWE\",MName \"SampleDisc1\"], baseName' = FName \"b\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 2}, wireTag = WireTag {getWireTag = 18}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 11}, typeName = Just (ProtoName {protobufName = FIName \".Lol.Rq1\", haskellPrefix = [MName \"Crypto\",MName \"Proto\"], parentModule = [MName \"Lol\"], baseName = MName \"Rq1\"}), hsRawDefault = Nothing, hsDefault = Nothing}], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False},DescriptorInfo {descName = ProtoName {protobufName = FIName \".RLWE.SampleRLWR1\", haskellPrefix = [MName \"Crypto\",MName \"Proto\"], parentModule = [MName \"RLWE\"], baseName = MName \"SampleRLWR1\"}, descFilePath = [\"Crypto\",\"Proto\",\"RLWE\",\"SampleRLWR1.hs\"], isGroup = False, fields = fromList [FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".RLWE.SampleRLWR1.a\", haskellPrefix' = [MName \"Crypto\",MName \"Proto\"], parentModule' = [MName \"RLWE\",MName \"SampleRLWR1\"], baseName' = FName \"a\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 1}, wireTag = WireTag {getWireTag = 10}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 11}, typeName = Just (ProtoName {protobufName = FIName \".Lol.Rq1\", haskellPrefix = [MName \"Crypto\",MName \"Proto\"], parentModule = [MName \"Lol\"], baseName = MName \"Rq1\"}), hsRawDefault = Nothing, hsDefault = Nothing},FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".RLWE.SampleRLWR1.b\", haskellPrefix' = [MName \"Crypto\",MName \"Proto\"], parentModule' = [MName \"RLWE\",MName \"SampleRLWR1\"], baseName' = FName \"b\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 2}, wireTag = WireTag {getWireTag = 18}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 11}, typeName = Just (ProtoName {protobufName = FIName \".Lol.Rq1\", haskellPrefix = [MName \"Crypto\",MName \"Proto\"], parentModule = [MName \"Lol\"], baseName = MName \"Rq1\"}), hsRawDefault = Nothing, hsDefault = Nothing}], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False},DescriptorInfo {descName = ProtoName {protobufName = FIName \".RLWE.SampleCont\", haskellPrefix = [MName \"Crypto\",MName \"Proto\"], parentModule = [MName \"RLWE\"], baseName = MName \"SampleCont\"}, descFilePath = [\"Crypto\",\"Proto\",\"RLWE\",\"SampleCont.hs\"], isGroup = False, fields = fromList [FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".RLWE.SampleCont.a\", haskellPrefix' = [MName \"Crypto\",MName \"Proto\"], parentModule' = [MName \"RLWE\",MName \"SampleCont\"], baseName' = FName \"a\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 1}, wireTag = WireTag {getWireTag = 10}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 11}, typeName = Just (ProtoName {protobufName = FIName \".Lol.RqProduct\", haskellPrefix = [MName \"Crypto\",MName \"Proto\"], parentModule = [MName \"Lol\"], baseName = MName \"RqProduct\"}), hsRawDefault = Nothing, hsDefault = Nothing},FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".RLWE.SampleCont.b\", haskellPrefix' = [MName \"Crypto\",MName \"Proto\"], parentModule' = [MName \"RLWE\",MName \"SampleCont\"], baseName' = FName \"b\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 2}, wireTag = WireTag {getWireTag = 18}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 11}, typeName = Just (ProtoName {protobufName = FIName \".Lol.KqProduct\", haskellPrefix = [MName \"Crypto\",MName \"Proto\"], parentModule = [MName \"Lol\"], baseName = MName \"KqProduct\"}), hsRawDefault = Nothing, hsDefault = Nothing}], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False},DescriptorInfo {descName = ProtoName {protobufName = FIName \".RLWE.SampleDisc\", haskellPrefix = [MName \"Crypto\",MName \"Proto\"], parentModule = [MName \"RLWE\"], baseName = MName \"SampleDisc\"}, descFilePath = [\"Crypto\",\"Proto\",\"RLWE\",\"SampleDisc.hs\"], isGroup = False, fields = fromList [FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".RLWE.SampleDisc.a\", haskellPrefix' = [MName \"Crypto\",MName \"Proto\"], parentModule' = [MName \"RLWE\",MName \"SampleDisc\"], baseName' = FName \"a\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 1}, wireTag = WireTag {getWireTag = 10}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 11}, typeName = Just (ProtoName {protobufName = FIName \".Lol.RqProduct\", haskellPrefix = [MName \"Crypto\",MName \"Proto\"], parentModule = [MName \"Lol\"], baseName = MName \"RqProduct\"}), hsRawDefault = Nothing, hsDefault = Nothing},FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".RLWE.SampleDisc.b\", haskellPrefix' = [MName \"Crypto\",MName \"Proto\"], parentModule' = [MName \"RLWE\",MName \"SampleDisc\"], baseName' = FName \"b\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 2}, wireTag = WireTag {getWireTag = 18}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 11}, typeName = Just (ProtoName {protobufName = FIName \".Lol.RqProduct\", haskellPrefix = [MName \"Crypto\",MName \"Proto\"], parentModule = [MName \"Lol\"], baseName = MName \"RqProduct\"}), hsRawDefault = Nothing, hsDefault = Nothing}], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False},DescriptorInfo {descName = ProtoName {protobufName = FIName \".RLWE.SampleRLWR\", haskellPrefix = [MName \"Crypto\",MName \"Proto\"], parentModule = [MName \"RLWE\"], baseName = MName \"SampleRLWR\"}, descFilePath = [\"Crypto\",\"Proto\",\"RLWE\",\"SampleRLWR.hs\"], isGroup = False, fields = fromList [FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".RLWE.SampleRLWR.a\", haskellPrefix' = [MName \"Crypto\",MName \"Proto\"], parentModule' = [MName \"RLWE\",MName \"SampleRLWR\"], baseName' = FName \"a\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 1}, wireTag = WireTag {getWireTag = 10}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 11}, typeName = Just (ProtoName {protobufName = FIName \".Lol.RqProduct\", haskellPrefix = [MName \"Crypto\",MName \"Proto\"], parentModule = [MName \"Lol\"], baseName = MName \"RqProduct\"}), hsRawDefault = Nothing, hsDefault = Nothing},FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".RLWE.SampleRLWR.b\", haskellPrefix' = [MName \"Crypto\",MName \"Proto\"], parentModule' = [MName \"RLWE\",MName \"SampleRLWR\"], baseName' = FName \"b\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 2}, wireTag = WireTag {getWireTag = 18}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 11}, typeName = Just (ProtoName {protobufName = FIName \".Lol.RqProduct\", haskellPrefix = [MName \"Crypto\",MName \"Proto\"], parentModule = [MName \"Lol\"], baseName = MName \"RqProduct\"}), hsRawDefault = Nothing, hsDefault = Nothing}], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False}], enums = [], oneofs = [], knownKeyMap = fromList []}"
+    "ProtoInfo {protoMod = ProtoName {protobufName = FIName \".crypto.proto.RLWE\", haskellPrefix = [], parentModule = [MName \"Crypto\",MName \"Proto\"], baseName = MName \"RLWE\"}, protoFilePath = [\"Crypto\",\"Proto\",\"RLWE.hs\"], protoSource = \"RLWE.proto\", extensionKeys = fromList [], messages = [DescriptorInfo {descName = ProtoName {protobufName = FIName \".crypto.proto.RLWE.SampleCont\", haskellPrefix = [], parentModule = [MName \"Crypto\",MName \"Proto\",MName \"RLWE\"], baseName = MName \"SampleCont\"}, descFilePath = [\"Crypto\",\"Proto\",\"RLWE\",\"SampleCont.hs\"], isGroup = False, fields = fromList [FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".crypto.proto.RLWE.SampleCont.a\", haskellPrefix' = [], parentModule' = [MName \"Crypto\",MName \"Proto\",MName \"RLWE\",MName \"SampleCont\"], baseName' = FName \"a\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 1}, wireTag = WireTag {getWireTag = 10}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 11}, typeName = Just (ProtoName {protobufName = FIName \".crypto.proto.lol.Rq\", haskellPrefix = [], parentModule = [MName \"Crypto\",MName \"Proto\",MName \"Lol\"], baseName = MName \"Rq\"}), hsRawDefault = Nothing, hsDefault = Nothing},FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".crypto.proto.RLWE.SampleCont.b\", haskellPrefix' = [], parentModule' = [MName \"Crypto\",MName \"Proto\",MName \"RLWE\",MName \"SampleCont\"], baseName' = FName \"b\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 2}, wireTag = WireTag {getWireTag = 18}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 11}, typeName = Just (ProtoName {protobufName = FIName \".crypto.proto.lol.Kq\", haskellPrefix = [], parentModule = [MName \"Crypto\",MName \"Proto\",MName \"Lol\"], baseName = MName \"Kq\"}), hsRawDefault = Nothing, hsDefault = Nothing}], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False},DescriptorInfo {descName = ProtoName {protobufName = FIName \".crypto.proto.RLWE.SampleDisc\", haskellPrefix = [], parentModule = [MName \"Crypto\",MName \"Proto\",MName \"RLWE\"], baseName = MName \"SampleDisc\"}, descFilePath = [\"Crypto\",\"Proto\",\"RLWE\",\"SampleDisc.hs\"], isGroup = False, fields = fromList [FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".crypto.proto.RLWE.SampleDisc.a\", haskellPrefix' = [], parentModule' = [MName \"Crypto\",MName \"Proto\",MName \"RLWE\",MName \"SampleDisc\"], baseName' = FName \"a\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 1}, wireTag = WireTag {getWireTag = 10}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 11}, typeName = Just (ProtoName {protobufName = FIName \".crypto.proto.lol.Rq\", haskellPrefix = [], parentModule = [MName \"Crypto\",MName \"Proto\",MName \"Lol\"], baseName = MName \"Rq\"}), hsRawDefault = Nothing, hsDefault = Nothing},FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".crypto.proto.RLWE.SampleDisc.b\", haskellPrefix' = [], parentModule' = [MName \"Crypto\",MName \"Proto\",MName \"RLWE\",MName \"SampleDisc\"], baseName' = FName \"b\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 2}, wireTag = WireTag {getWireTag = 18}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 11}, typeName = Just (ProtoName {protobufName = FIName \".crypto.proto.lol.Rq\", haskellPrefix = [], parentModule = [MName \"Crypto\",MName \"Proto\",MName \"Lol\"], baseName = MName \"Rq\"}), hsRawDefault = Nothing, hsDefault = Nothing}], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False},DescriptorInfo {descName = ProtoName {protobufName = FIName \".crypto.proto.RLWE.SampleRLWR\", haskellPrefix = [], parentModule = [MName \"Crypto\",MName \"Proto\",MName \"RLWE\"], baseName = MName \"SampleRLWR\"}, descFilePath = [\"Crypto\",\"Proto\",\"RLWE\",\"SampleRLWR.hs\"], isGroup = False, fields = fromList [FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".crypto.proto.RLWE.SampleRLWR.a\", haskellPrefix' = [], parentModule' = [MName \"Crypto\",MName \"Proto\",MName \"RLWE\",MName \"SampleRLWR\"], baseName' = FName \"a\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 1}, wireTag = WireTag {getWireTag = 10}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 11}, typeName = Just (ProtoName {protobufName = FIName \".crypto.proto.lol.Rq\", haskellPrefix = [], parentModule = [MName \"Crypto\",MName \"Proto\",MName \"Lol\"], baseName = MName \"Rq\"}), hsRawDefault = Nothing, hsDefault = Nothing},FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".crypto.proto.RLWE.SampleRLWR.b\", haskellPrefix' = [], parentModule' = [MName \"Crypto\",MName \"Proto\",MName \"RLWE\",MName \"SampleRLWR\"], baseName' = FName \"b\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 2}, wireTag = WireTag {getWireTag = 18}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 11}, typeName = Just (ProtoName {protobufName = FIName \".crypto.proto.lol.Rq\", haskellPrefix = [], parentModule = [MName \"Crypto\",MName \"Proto\",MName \"Lol\"], baseName = MName \"Rq\"}), hsRawDefault = Nothing, hsDefault = Nothing}], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False},DescriptorInfo {descName = ProtoName {protobufName = FIName \".crypto.proto.RLWE.SampleContProduct\", haskellPrefix = [], parentModule = [MName \"Crypto\",MName \"Proto\",MName \"RLWE\"], baseName = MName \"SampleContProduct\"}, descFilePath = [\"Crypto\",\"Proto\",\"RLWE\",\"SampleContProduct.hs\"], isGroup = False, fields = fromList [FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".crypto.proto.RLWE.SampleContProduct.a\", haskellPrefix' = [], parentModule' = [MName \"Crypto\",MName \"Proto\",MName \"RLWE\",MName \"SampleContProduct\"], baseName' = FName \"a\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 1}, wireTag = WireTag {getWireTag = 10}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 11}, typeName = Just (ProtoName {protobufName = FIName \".crypto.proto.lol.RqProduct\", haskellPrefix = [], parentModule = [MName \"Crypto\",MName \"Proto\",MName \"Lol\"], baseName = MName \"RqProduct\"}), hsRawDefault = Nothing, hsDefault = Nothing},FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".crypto.proto.RLWE.SampleContProduct.b\", haskellPrefix' = [], parentModule' = [MName \"Crypto\",MName \"Proto\",MName \"RLWE\",MName \"SampleContProduct\"], baseName' = FName \"b\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 2}, wireTag = WireTag {getWireTag = 18}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 11}, typeName = Just (ProtoName {protobufName = FIName \".crypto.proto.lol.KqProduct\", haskellPrefix = [], parentModule = [MName \"Crypto\",MName \"Proto\",MName \"Lol\"], baseName = MName \"KqProduct\"}), hsRawDefault = Nothing, hsDefault = Nothing}], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False},DescriptorInfo {descName = ProtoName {protobufName = FIName \".crypto.proto.RLWE.SampleDiscProduct\", haskellPrefix = [], parentModule = [MName \"Crypto\",MName \"Proto\",MName \"RLWE\"], baseName = MName \"SampleDiscProduct\"}, descFilePath = [\"Crypto\",\"Proto\",\"RLWE\",\"SampleDiscProduct.hs\"], isGroup = False, fields = fromList [FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".crypto.proto.RLWE.SampleDiscProduct.a\", haskellPrefix' = [], parentModule' = [MName \"Crypto\",MName \"Proto\",MName \"RLWE\",MName \"SampleDiscProduct\"], baseName' = FName \"a\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 1}, wireTag = WireTag {getWireTag = 10}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 11}, typeName = Just (ProtoName {protobufName = FIName \".crypto.proto.lol.RqProduct\", haskellPrefix = [], parentModule = [MName \"Crypto\",MName \"Proto\",MName \"Lol\"], baseName = MName \"RqProduct\"}), hsRawDefault = Nothing, hsDefault = Nothing},FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".crypto.proto.RLWE.SampleDiscProduct.b\", haskellPrefix' = [], parentModule' = [MName \"Crypto\",MName \"Proto\",MName \"RLWE\",MName \"SampleDiscProduct\"], baseName' = FName \"b\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 2}, wireTag = WireTag {getWireTag = 18}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 11}, typeName = Just (ProtoName {protobufName = FIName \".crypto.proto.lol.RqProduct\", haskellPrefix = [], parentModule = [MName \"Crypto\",MName \"Proto\",MName \"Lol\"], baseName = MName \"RqProduct\"}), hsRawDefault = Nothing, hsDefault = Nothing}], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False},DescriptorInfo {descName = ProtoName {protobufName = FIName \".crypto.proto.RLWE.SampleRLWRProduct\", haskellPrefix = [], parentModule = [MName \"Crypto\",MName \"Proto\",MName \"RLWE\"], baseName = MName \"SampleRLWRProduct\"}, descFilePath = [\"Crypto\",\"Proto\",\"RLWE\",\"SampleRLWRProduct.hs\"], isGroup = False, fields = fromList [FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".crypto.proto.RLWE.SampleRLWRProduct.a\", haskellPrefix' = [], parentModule' = [MName \"Crypto\",MName \"Proto\",MName \"RLWE\",MName \"SampleRLWRProduct\"], baseName' = FName \"a\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 1}, wireTag = WireTag {getWireTag = 10}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 11}, typeName = Just (ProtoName {protobufName = FIName \".crypto.proto.lol.RqProduct\", haskellPrefix = [], parentModule = [MName \"Crypto\",MName \"Proto\",MName \"Lol\"], baseName = MName \"RqProduct\"}), hsRawDefault = Nothing, hsDefault = Nothing},FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".crypto.proto.RLWE.SampleRLWRProduct.b\", haskellPrefix' = [], parentModule' = [MName \"Crypto\",MName \"Proto\",MName \"RLWE\",MName \"SampleRLWRProduct\"], baseName' = FName \"b\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 2}, wireTag = WireTag {getWireTag = 18}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 11}, typeName = Just (ProtoName {protobufName = FIName \".crypto.proto.lol.RqProduct\", haskellPrefix = [], parentModule = [MName \"Crypto\",MName \"Proto\",MName \"Lol\"], baseName = MName \"RqProduct\"}), hsRawDefault = Nothing, hsDefault = Nothing}], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False}], enums = [], oneofs = [], knownKeyMap = fromList []}"
 
 fileDescriptorProto :: FileDescriptorProto
 fileDescriptorProto
  = P'.getFromBS (P'.wireGet 11)
     (P'.pack
-      "\142\ETX\n\nRLWE.proto\SUB\tLol.proto\"7\n\vSampleCont1\DC2\DC3\n\SOHa\CAN\SOH \STX(\v2\b.Lol.Rq1\DC2\DC3\n\SOHb\CAN\STX \STX(\v2\b.Lol.Kq1\"7\n\vSampleDisc1\DC2\DC3\n\SOHa\CAN\SOH \STX(\v2\b.Lol.Rq1\DC2\DC3\n\SOHb\CAN\STX \STX(\v2\b.Lol.Rq1\"7\n\vSampleRLWR1\DC2\DC3\n\SOHa\CAN\SOH \STX(\v2\b.Lol.Rq1\DC2\DC3\n\SOHb\CAN\STX \STX(\v2\b.Lol.Rq1\"B\n\nSampleCont\DC2\EM\n\SOHa\CAN\SOH \STX(\v2\SO.Lol.RqProduct\DC2\EM\n\SOHb\CAN\STX \STX(\v2\SO.Lol.KqProduct\"B\n\nSampleDisc\DC2\EM\n\SOHa\CAN\SOH \STX(\v2\SO.Lol.RqProduct\DC2\EM\n\SOHb\CAN\STX \STX(\v2\SO.Lol.RqProduct\"B\n\nSampleRLWR\DC2\EM\n\SOHa\CAN\SOH \STX(\v2\SO.Lol.RqProduct\DC2\EM\n\SOHb\CAN\STX \STX(\v2\SO.Lol.RqProduct")
+      "\201\EOT\n\nRLWE.proto\DC2\DC1crypto.proto.RLWE\SUB\tLol.proto\"N\n\nSampleCont\DC2\US\n\SOHa\CAN\SOH \STX(\v2\DC4.crypto.proto.lol.Rq\DC2\US\n\SOHb\CAN\STX \STX(\v2\DC4.crypto.proto.lol.Kq\"N\n\nSampleDisc\DC2\US\n\SOHa\CAN\SOH \STX(\v2\DC4.crypto.proto.lol.Rq\DC2\US\n\SOHb\CAN\STX \STX(\v2\DC4.crypto.proto.lol.Rq\"N\n\nSampleRLWR\DC2\US\n\SOHa\CAN\SOH \STX(\v2\DC4.crypto.proto.lol.Rq\DC2\US\n\SOHb\CAN\STX \STX(\v2\DC4.crypto.proto.lol.Rq\"c\n\DC1SampleContProduct\DC2&\n\SOHa\CAN\SOH \STX(\v2\ESC.crypto.proto.lol.RqProduct\DC2&\n\SOHb\CAN\STX \STX(\v2\ESC.crypto.proto.lol.KqProduct\"c\n\DC1SampleDiscProduct\DC2&\n\SOHa\CAN\SOH \STX(\v2\ESC.crypto.proto.lol.RqProduct\DC2&\n\SOHb\CAN\STX \STX(\v2\ESC.crypto.proto.lol.RqProduct\"c\n\DC1SampleRLWRProduct\DC2&\n\SOHa\CAN\SOH \STX(\v2\ESC.crypto.proto.lol.RqProduct\DC2&\n\SOHb\CAN\STX \STX(\v2\ESC.crypto.proto.lol.RqProduct")
diff --git a/Crypto/Proto/RLWE/SampleCont.hs b/Crypto/Proto/RLWE/SampleCont.hs
--- a/Crypto/Proto/RLWE/SampleCont.hs
+++ b/Crypto/Proto/RLWE/SampleCont.hs
@@ -7,10 +7,10 @@
 import qualified GHC.Generics as Prelude'
 import qualified Data.Data as Prelude'
 import qualified Text.ProtocolBuffers.Header as P'
-import qualified Crypto.Proto.Lol.KqProduct as Lol (KqProduct)
-import qualified Crypto.Proto.Lol.RqProduct as Lol (RqProduct)
+import qualified Crypto.Proto.Lol.Kq as Crypto.Proto.Lol (Kq)
+import qualified Crypto.Proto.Lol.Rq as Crypto.Proto.Lol (Rq)
 
-data SampleCont = SampleCont{a :: !(Lol.RqProduct), b :: !(Lol.KqProduct)}
+data SampleCont = SampleCont{a :: !(Crypto.Proto.Lol.Rq), b :: !(Crypto.Proto.Lol.Kq)}
                 deriving (Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable, Prelude'.Data, Prelude'.Generic)
 
 instance P'.Mergeable SampleCont where
@@ -60,7 +60,7 @@
   getMessageInfo _ = P'.GetMessageInfo (P'.fromDistinctAscList [10, 18]) (P'.fromDistinctAscList [10, 18])
   reflectDescriptorInfo _
    = Prelude'.read
-      "DescriptorInfo {descName = ProtoName {protobufName = FIName \".RLWE.SampleCont\", haskellPrefix = [MName \"Crypto\",MName \"Proto\"], parentModule = [MName \"RLWE\"], baseName = MName \"SampleCont\"}, descFilePath = [\"Crypto\",\"Proto\",\"RLWE\",\"SampleCont.hs\"], isGroup = False, fields = fromList [FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".RLWE.SampleCont.a\", haskellPrefix' = [MName \"Crypto\",MName \"Proto\"], parentModule' = [MName \"RLWE\",MName \"SampleCont\"], baseName' = FName \"a\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 1}, wireTag = WireTag {getWireTag = 10}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 11}, typeName = Just (ProtoName {protobufName = FIName \".Lol.RqProduct\", haskellPrefix = [MName \"Crypto\",MName \"Proto\"], parentModule = [MName \"Lol\"], baseName = MName \"RqProduct\"}), hsRawDefault = Nothing, hsDefault = Nothing},FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".RLWE.SampleCont.b\", haskellPrefix' = [MName \"Crypto\",MName \"Proto\"], parentModule' = [MName \"RLWE\",MName \"SampleCont\"], baseName' = FName \"b\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 2}, wireTag = WireTag {getWireTag = 18}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 11}, typeName = Just (ProtoName {protobufName = FIName \".Lol.KqProduct\", haskellPrefix = [MName \"Crypto\",MName \"Proto\"], parentModule = [MName \"Lol\"], baseName = MName \"KqProduct\"}), hsRawDefault = Nothing, hsDefault = Nothing}], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False}"
+      "DescriptorInfo {descName = ProtoName {protobufName = FIName \".crypto.proto.RLWE.SampleCont\", haskellPrefix = [], parentModule = [MName \"Crypto\",MName \"Proto\",MName \"RLWE\"], baseName = MName \"SampleCont\"}, descFilePath = [\"Crypto\",\"Proto\",\"RLWE\",\"SampleCont.hs\"], isGroup = False, fields = fromList [FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".crypto.proto.RLWE.SampleCont.a\", haskellPrefix' = [], parentModule' = [MName \"Crypto\",MName \"Proto\",MName \"RLWE\",MName \"SampleCont\"], baseName' = FName \"a\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 1}, wireTag = WireTag {getWireTag = 10}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 11}, typeName = Just (ProtoName {protobufName = FIName \".crypto.proto.lol.Rq\", haskellPrefix = [], parentModule = [MName \"Crypto\",MName \"Proto\",MName \"Lol\"], baseName = MName \"Rq\"}), hsRawDefault = Nothing, hsDefault = Nothing},FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".crypto.proto.RLWE.SampleCont.b\", haskellPrefix' = [], parentModule' = [MName \"Crypto\",MName \"Proto\",MName \"RLWE\",MName \"SampleCont\"], baseName' = FName \"b\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 2}, wireTag = WireTag {getWireTag = 18}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 11}, typeName = Just (ProtoName {protobufName = FIName \".crypto.proto.lol.Kq\", haskellPrefix = [], parentModule = [MName \"Crypto\",MName \"Proto\",MName \"Lol\"], baseName = MName \"Kq\"}), hsRawDefault = Nothing, hsDefault = Nothing}], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False}"
 
 instance P'.TextType SampleCont where
   tellT = P'.tellSubMessage
diff --git a/Crypto/Proto/RLWE/SampleCont1.hs b/Crypto/Proto/RLWE/SampleCont1.hs
deleted file mode 100644
--- a/Crypto/Proto/RLWE/SampleCont1.hs
+++ /dev/null
@@ -1,88 +0,0 @@
-{-# LANGUAGE BangPatterns, DeriveDataTypeable, DeriveGeneric, FlexibleInstances, MultiParamTypeClasses #-}
-{-# OPTIONS_GHC  -fno-warn-unused-imports #-}
-module Crypto.Proto.RLWE.SampleCont1 (SampleCont1(..)) where
-import Prelude ((+), (/))
-import qualified Prelude as Prelude'
-import qualified Data.Typeable as Prelude'
-import qualified GHC.Generics as Prelude'
-import qualified Data.Data as Prelude'
-import qualified Text.ProtocolBuffers.Header as P'
-import qualified Crypto.Proto.Lol.Kq1 as Lol (Kq1)
-import qualified Crypto.Proto.Lol.Rq1 as Lol (Rq1)
-
-data SampleCont1 = SampleCont1{a :: !(Lol.Rq1), b :: !(Lol.Kq1)}
-                 deriving (Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable, Prelude'.Data, Prelude'.Generic)
-
-instance P'.Mergeable SampleCont1 where
-  mergeAppend (SampleCont1 x'1 x'2) (SampleCont1 y'1 y'2) = SampleCont1 (P'.mergeAppend x'1 y'1) (P'.mergeAppend x'2 y'2)
-
-instance P'.Default SampleCont1 where
-  defaultValue = SampleCont1 P'.defaultValue P'.defaultValue
-
-instance P'.Wire SampleCont1 where
-  wireSize ft' self'@(SampleCont1 x'1 x'2)
-   = case ft' of
-       10 -> calc'Size
-       11 -> P'.prependMessageSize calc'Size
-       _ -> P'.wireSizeErr ft' self'
-    where
-        calc'Size = (P'.wireSizeReq 1 11 x'1 + P'.wireSizeReq 1 11 x'2)
-  wirePut ft' self'@(SampleCont1 x'1 x'2)
-   = case ft' of
-       10 -> put'Fields
-       11 -> do
-               P'.putSize (P'.wireSize 10 self')
-               put'Fields
-       _ -> P'.wirePutErr ft' self'
-    where
-        put'Fields
-         = do
-             P'.wirePutReq 10 11 x'1
-             P'.wirePutReq 18 11 x'2
-  wireGet ft'
-   = case ft' of
-       10 -> P'.getBareMessageWith update'Self
-       11 -> P'.getMessageWith update'Self
-       _ -> P'.wireGetErr ft'
-    where
-        update'Self wire'Tag old'Self
-         = case wire'Tag of
-             10 -> Prelude'.fmap (\ !new'Field -> old'Self{a = P'.mergeAppend (a old'Self) (new'Field)}) (P'.wireGet 11)
-             18 -> Prelude'.fmap (\ !new'Field -> old'Self{b = P'.mergeAppend (b old'Self) (new'Field)}) (P'.wireGet 11)
-             _ -> let (field'Number, wire'Type) = P'.splitWireTag wire'Tag in P'.unknown field'Number wire'Type old'Self
-
-instance P'.MessageAPI msg' (msg' -> SampleCont1) SampleCont1 where
-  getVal m' f' = f' m'
-
-instance P'.GPB SampleCont1
-
-instance P'.ReflectDescriptor SampleCont1 where
-  getMessageInfo _ = P'.GetMessageInfo (P'.fromDistinctAscList [10, 18]) (P'.fromDistinctAscList [10, 18])
-  reflectDescriptorInfo _
-   = Prelude'.read
-      "DescriptorInfo {descName = ProtoName {protobufName = FIName \".RLWE.SampleCont1\", haskellPrefix = [MName \"Crypto\",MName \"Proto\"], parentModule = [MName \"RLWE\"], baseName = MName \"SampleCont1\"}, descFilePath = [\"Crypto\",\"Proto\",\"RLWE\",\"SampleCont1.hs\"], isGroup = False, fields = fromList [FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".RLWE.SampleCont1.a\", haskellPrefix' = [MName \"Crypto\",MName \"Proto\"], parentModule' = [MName \"RLWE\",MName \"SampleCont1\"], baseName' = FName \"a\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 1}, wireTag = WireTag {getWireTag = 10}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 11}, typeName = Just (ProtoName {protobufName = FIName \".Lol.Rq1\", haskellPrefix = [MName \"Crypto\",MName \"Proto\"], parentModule = [MName \"Lol\"], baseName = MName \"Rq1\"}), hsRawDefault = Nothing, hsDefault = Nothing},FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".RLWE.SampleCont1.b\", haskellPrefix' = [MName \"Crypto\",MName \"Proto\"], parentModule' = [MName \"RLWE\",MName \"SampleCont1\"], baseName' = FName \"b\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 2}, wireTag = WireTag {getWireTag = 18}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 11}, typeName = Just (ProtoName {protobufName = FIName \".Lol.Kq1\", haskellPrefix = [MName \"Crypto\",MName \"Proto\"], parentModule = [MName \"Lol\"], baseName = MName \"Kq1\"}), hsRawDefault = Nothing, hsDefault = Nothing}], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False}"
-
-instance P'.TextType SampleCont1 where
-  tellT = P'.tellSubMessage
-  getT = P'.getSubMessage
-
-instance P'.TextMsg SampleCont1 where
-  textPut msg
-   = do
-       P'.tellT "a" (a msg)
-       P'.tellT "b" (b msg)
-  textGet
-   = do
-       mods <- P'.sepEndBy (P'.choice [parse'a, parse'b]) P'.spaces
-       Prelude'.return (Prelude'.foldl (\ v f -> f v) P'.defaultValue mods)
-    where
-        parse'a
-         = P'.try
-            (do
-               v <- P'.getT "a"
-               Prelude'.return (\ o -> o{a = v}))
-        parse'b
-         = P'.try
-            (do
-               v <- P'.getT "b"
-               Prelude'.return (\ o -> o{b = v}))
diff --git a/Crypto/Proto/RLWE/SampleContProduct.hs b/Crypto/Proto/RLWE/SampleContProduct.hs
new file mode 100644
--- /dev/null
+++ b/Crypto/Proto/RLWE/SampleContProduct.hs
@@ -0,0 +1,89 @@
+{-# LANGUAGE BangPatterns, DeriveDataTypeable, DeriveGeneric, FlexibleInstances, MultiParamTypeClasses #-}
+{-# OPTIONS_GHC  -fno-warn-unused-imports #-}
+module Crypto.Proto.RLWE.SampleContProduct (SampleContProduct(..)) where
+import Prelude ((+), (/))
+import qualified Prelude as Prelude'
+import qualified Data.Typeable as Prelude'
+import qualified GHC.Generics as Prelude'
+import qualified Data.Data as Prelude'
+import qualified Text.ProtocolBuffers.Header as P'
+import qualified Crypto.Proto.Lol.KqProduct as Crypto.Proto.Lol (KqProduct)
+import qualified Crypto.Proto.Lol.RqProduct as Crypto.Proto.Lol (RqProduct)
+
+data SampleContProduct = SampleContProduct{a :: !(Crypto.Proto.Lol.RqProduct), b :: !(Crypto.Proto.Lol.KqProduct)}
+                       deriving (Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable, Prelude'.Data, Prelude'.Generic)
+
+instance P'.Mergeable SampleContProduct where
+  mergeAppend (SampleContProduct x'1 x'2) (SampleContProduct y'1 y'2)
+   = SampleContProduct (P'.mergeAppend x'1 y'1) (P'.mergeAppend x'2 y'2)
+
+instance P'.Default SampleContProduct where
+  defaultValue = SampleContProduct P'.defaultValue P'.defaultValue
+
+instance P'.Wire SampleContProduct where
+  wireSize ft' self'@(SampleContProduct x'1 x'2)
+   = case ft' of
+       10 -> calc'Size
+       11 -> P'.prependMessageSize calc'Size
+       _ -> P'.wireSizeErr ft' self'
+    where
+        calc'Size = (P'.wireSizeReq 1 11 x'1 + P'.wireSizeReq 1 11 x'2)
+  wirePut ft' self'@(SampleContProduct x'1 x'2)
+   = case ft' of
+       10 -> put'Fields
+       11 -> do
+               P'.putSize (P'.wireSize 10 self')
+               put'Fields
+       _ -> P'.wirePutErr ft' self'
+    where
+        put'Fields
+         = do
+             P'.wirePutReq 10 11 x'1
+             P'.wirePutReq 18 11 x'2
+  wireGet ft'
+   = case ft' of
+       10 -> P'.getBareMessageWith update'Self
+       11 -> P'.getMessageWith update'Self
+       _ -> P'.wireGetErr ft'
+    where
+        update'Self wire'Tag old'Self
+         = case wire'Tag of
+             10 -> Prelude'.fmap (\ !new'Field -> old'Self{a = P'.mergeAppend (a old'Self) (new'Field)}) (P'.wireGet 11)
+             18 -> Prelude'.fmap (\ !new'Field -> old'Self{b = P'.mergeAppend (b old'Self) (new'Field)}) (P'.wireGet 11)
+             _ -> let (field'Number, wire'Type) = P'.splitWireTag wire'Tag in P'.unknown field'Number wire'Type old'Self
+
+instance P'.MessageAPI msg' (msg' -> SampleContProduct) SampleContProduct where
+  getVal m' f' = f' m'
+
+instance P'.GPB SampleContProduct
+
+instance P'.ReflectDescriptor SampleContProduct where
+  getMessageInfo _ = P'.GetMessageInfo (P'.fromDistinctAscList [10, 18]) (P'.fromDistinctAscList [10, 18])
+  reflectDescriptorInfo _
+   = Prelude'.read
+      "DescriptorInfo {descName = ProtoName {protobufName = FIName \".crypto.proto.RLWE.SampleContProduct\", haskellPrefix = [], parentModule = [MName \"Crypto\",MName \"Proto\",MName \"RLWE\"], baseName = MName \"SampleContProduct\"}, descFilePath = [\"Crypto\",\"Proto\",\"RLWE\",\"SampleContProduct.hs\"], isGroup = False, fields = fromList [FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".crypto.proto.RLWE.SampleContProduct.a\", haskellPrefix' = [], parentModule' = [MName \"Crypto\",MName \"Proto\",MName \"RLWE\",MName \"SampleContProduct\"], baseName' = FName \"a\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 1}, wireTag = WireTag {getWireTag = 10}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 11}, typeName = Just (ProtoName {protobufName = FIName \".crypto.proto.lol.RqProduct\", haskellPrefix = [], parentModule = [MName \"Crypto\",MName \"Proto\",MName \"Lol\"], baseName = MName \"RqProduct\"}), hsRawDefault = Nothing, hsDefault = Nothing},FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".crypto.proto.RLWE.SampleContProduct.b\", haskellPrefix' = [], parentModule' = [MName \"Crypto\",MName \"Proto\",MName \"RLWE\",MName \"SampleContProduct\"], baseName' = FName \"b\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 2}, wireTag = WireTag {getWireTag = 18}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 11}, typeName = Just (ProtoName {protobufName = FIName \".crypto.proto.lol.KqProduct\", haskellPrefix = [], parentModule = [MName \"Crypto\",MName \"Proto\",MName \"Lol\"], baseName = MName \"KqProduct\"}), hsRawDefault = Nothing, hsDefault = Nothing}], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False}"
+
+instance P'.TextType SampleContProduct where
+  tellT = P'.tellSubMessage
+  getT = P'.getSubMessage
+
+instance P'.TextMsg SampleContProduct where
+  textPut msg
+   = do
+       P'.tellT "a" (a msg)
+       P'.tellT "b" (b msg)
+  textGet
+   = do
+       mods <- P'.sepEndBy (P'.choice [parse'a, parse'b]) P'.spaces
+       Prelude'.return (Prelude'.foldl (\ v f -> f v) P'.defaultValue mods)
+    where
+        parse'a
+         = P'.try
+            (do
+               v <- P'.getT "a"
+               Prelude'.return (\ o -> o{a = v}))
+        parse'b
+         = P'.try
+            (do
+               v <- P'.getT "b"
+               Prelude'.return (\ o -> o{b = v}))
diff --git a/Crypto/Proto/RLWE/SampleDisc.hs b/Crypto/Proto/RLWE/SampleDisc.hs
--- a/Crypto/Proto/RLWE/SampleDisc.hs
+++ b/Crypto/Proto/RLWE/SampleDisc.hs
@@ -7,9 +7,9 @@
 import qualified GHC.Generics as Prelude'
 import qualified Data.Data as Prelude'
 import qualified Text.ProtocolBuffers.Header as P'
-import qualified Crypto.Proto.Lol.RqProduct as Lol (RqProduct)
+import qualified Crypto.Proto.Lol.Rq as Crypto.Proto.Lol (Rq)
 
-data SampleDisc = SampleDisc{a :: !(Lol.RqProduct), b :: !(Lol.RqProduct)}
+data SampleDisc = SampleDisc{a :: !(Crypto.Proto.Lol.Rq), b :: !(Crypto.Proto.Lol.Rq)}
                 deriving (Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable, Prelude'.Data, Prelude'.Generic)
 
 instance P'.Mergeable SampleDisc where
@@ -59,7 +59,7 @@
   getMessageInfo _ = P'.GetMessageInfo (P'.fromDistinctAscList [10, 18]) (P'.fromDistinctAscList [10, 18])
   reflectDescriptorInfo _
    = Prelude'.read
-      "DescriptorInfo {descName = ProtoName {protobufName = FIName \".RLWE.SampleDisc\", haskellPrefix = [MName \"Crypto\",MName \"Proto\"], parentModule = [MName \"RLWE\"], baseName = MName \"SampleDisc\"}, descFilePath = [\"Crypto\",\"Proto\",\"RLWE\",\"SampleDisc.hs\"], isGroup = False, fields = fromList [FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".RLWE.SampleDisc.a\", haskellPrefix' = [MName \"Crypto\",MName \"Proto\"], parentModule' = [MName \"RLWE\",MName \"SampleDisc\"], baseName' = FName \"a\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 1}, wireTag = WireTag {getWireTag = 10}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 11}, typeName = Just (ProtoName {protobufName = FIName \".Lol.RqProduct\", haskellPrefix = [MName \"Crypto\",MName \"Proto\"], parentModule = [MName \"Lol\"], baseName = MName \"RqProduct\"}), hsRawDefault = Nothing, hsDefault = Nothing},FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".RLWE.SampleDisc.b\", haskellPrefix' = [MName \"Crypto\",MName \"Proto\"], parentModule' = [MName \"RLWE\",MName \"SampleDisc\"], baseName' = FName \"b\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 2}, wireTag = WireTag {getWireTag = 18}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 11}, typeName = Just (ProtoName {protobufName = FIName \".Lol.RqProduct\", haskellPrefix = [MName \"Crypto\",MName \"Proto\"], parentModule = [MName \"Lol\"], baseName = MName \"RqProduct\"}), hsRawDefault = Nothing, hsDefault = Nothing}], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False}"
+      "DescriptorInfo {descName = ProtoName {protobufName = FIName \".crypto.proto.RLWE.SampleDisc\", haskellPrefix = [], parentModule = [MName \"Crypto\",MName \"Proto\",MName \"RLWE\"], baseName = MName \"SampleDisc\"}, descFilePath = [\"Crypto\",\"Proto\",\"RLWE\",\"SampleDisc.hs\"], isGroup = False, fields = fromList [FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".crypto.proto.RLWE.SampleDisc.a\", haskellPrefix' = [], parentModule' = [MName \"Crypto\",MName \"Proto\",MName \"RLWE\",MName \"SampleDisc\"], baseName' = FName \"a\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 1}, wireTag = WireTag {getWireTag = 10}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 11}, typeName = Just (ProtoName {protobufName = FIName \".crypto.proto.lol.Rq\", haskellPrefix = [], parentModule = [MName \"Crypto\",MName \"Proto\",MName \"Lol\"], baseName = MName \"Rq\"}), hsRawDefault = Nothing, hsDefault = Nothing},FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".crypto.proto.RLWE.SampleDisc.b\", haskellPrefix' = [], parentModule' = [MName \"Crypto\",MName \"Proto\",MName \"RLWE\",MName \"SampleDisc\"], baseName' = FName \"b\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 2}, wireTag = WireTag {getWireTag = 18}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 11}, typeName = Just (ProtoName {protobufName = FIName \".crypto.proto.lol.Rq\", haskellPrefix = [], parentModule = [MName \"Crypto\",MName \"Proto\",MName \"Lol\"], baseName = MName \"Rq\"}), hsRawDefault = Nothing, hsDefault = Nothing}], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False}"
 
 instance P'.TextType SampleDisc where
   tellT = P'.tellSubMessage
diff --git a/Crypto/Proto/RLWE/SampleDisc1.hs b/Crypto/Proto/RLWE/SampleDisc1.hs
deleted file mode 100644
--- a/Crypto/Proto/RLWE/SampleDisc1.hs
+++ /dev/null
@@ -1,87 +0,0 @@
-{-# LANGUAGE BangPatterns, DeriveDataTypeable, DeriveGeneric, FlexibleInstances, MultiParamTypeClasses #-}
-{-# OPTIONS_GHC  -fno-warn-unused-imports #-}
-module Crypto.Proto.RLWE.SampleDisc1 (SampleDisc1(..)) where
-import Prelude ((+), (/))
-import qualified Prelude as Prelude'
-import qualified Data.Typeable as Prelude'
-import qualified GHC.Generics as Prelude'
-import qualified Data.Data as Prelude'
-import qualified Text.ProtocolBuffers.Header as P'
-import qualified Crypto.Proto.Lol.Rq1 as Lol (Rq1)
-
-data SampleDisc1 = SampleDisc1{a :: !(Lol.Rq1), b :: !(Lol.Rq1)}
-                 deriving (Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable, Prelude'.Data, Prelude'.Generic)
-
-instance P'.Mergeable SampleDisc1 where
-  mergeAppend (SampleDisc1 x'1 x'2) (SampleDisc1 y'1 y'2) = SampleDisc1 (P'.mergeAppend x'1 y'1) (P'.mergeAppend x'2 y'2)
-
-instance P'.Default SampleDisc1 where
-  defaultValue = SampleDisc1 P'.defaultValue P'.defaultValue
-
-instance P'.Wire SampleDisc1 where
-  wireSize ft' self'@(SampleDisc1 x'1 x'2)
-   = case ft' of
-       10 -> calc'Size
-       11 -> P'.prependMessageSize calc'Size
-       _ -> P'.wireSizeErr ft' self'
-    where
-        calc'Size = (P'.wireSizeReq 1 11 x'1 + P'.wireSizeReq 1 11 x'2)
-  wirePut ft' self'@(SampleDisc1 x'1 x'2)
-   = case ft' of
-       10 -> put'Fields
-       11 -> do
-               P'.putSize (P'.wireSize 10 self')
-               put'Fields
-       _ -> P'.wirePutErr ft' self'
-    where
-        put'Fields
-         = do
-             P'.wirePutReq 10 11 x'1
-             P'.wirePutReq 18 11 x'2
-  wireGet ft'
-   = case ft' of
-       10 -> P'.getBareMessageWith update'Self
-       11 -> P'.getMessageWith update'Self
-       _ -> P'.wireGetErr ft'
-    where
-        update'Self wire'Tag old'Self
-         = case wire'Tag of
-             10 -> Prelude'.fmap (\ !new'Field -> old'Self{a = P'.mergeAppend (a old'Self) (new'Field)}) (P'.wireGet 11)
-             18 -> Prelude'.fmap (\ !new'Field -> old'Self{b = P'.mergeAppend (b old'Self) (new'Field)}) (P'.wireGet 11)
-             _ -> let (field'Number, wire'Type) = P'.splitWireTag wire'Tag in P'.unknown field'Number wire'Type old'Self
-
-instance P'.MessageAPI msg' (msg' -> SampleDisc1) SampleDisc1 where
-  getVal m' f' = f' m'
-
-instance P'.GPB SampleDisc1
-
-instance P'.ReflectDescriptor SampleDisc1 where
-  getMessageInfo _ = P'.GetMessageInfo (P'.fromDistinctAscList [10, 18]) (P'.fromDistinctAscList [10, 18])
-  reflectDescriptorInfo _
-   = Prelude'.read
-      "DescriptorInfo {descName = ProtoName {protobufName = FIName \".RLWE.SampleDisc1\", haskellPrefix = [MName \"Crypto\",MName \"Proto\"], parentModule = [MName \"RLWE\"], baseName = MName \"SampleDisc1\"}, descFilePath = [\"Crypto\",\"Proto\",\"RLWE\",\"SampleDisc1.hs\"], isGroup = False, fields = fromList [FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".RLWE.SampleDisc1.a\", haskellPrefix' = [MName \"Crypto\",MName \"Proto\"], parentModule' = [MName \"RLWE\",MName \"SampleDisc1\"], baseName' = FName \"a\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 1}, wireTag = WireTag {getWireTag = 10}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 11}, typeName = Just (ProtoName {protobufName = FIName \".Lol.Rq1\", haskellPrefix = [MName \"Crypto\",MName \"Proto\"], parentModule = [MName \"Lol\"], baseName = MName \"Rq1\"}), hsRawDefault = Nothing, hsDefault = Nothing},FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".RLWE.SampleDisc1.b\", haskellPrefix' = [MName \"Crypto\",MName \"Proto\"], parentModule' = [MName \"RLWE\",MName \"SampleDisc1\"], baseName' = FName \"b\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 2}, wireTag = WireTag {getWireTag = 18}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 11}, typeName = Just (ProtoName {protobufName = FIName \".Lol.Rq1\", haskellPrefix = [MName \"Crypto\",MName \"Proto\"], parentModule = [MName \"Lol\"], baseName = MName \"Rq1\"}), hsRawDefault = Nothing, hsDefault = Nothing}], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False}"
-
-instance P'.TextType SampleDisc1 where
-  tellT = P'.tellSubMessage
-  getT = P'.getSubMessage
-
-instance P'.TextMsg SampleDisc1 where
-  textPut msg
-   = do
-       P'.tellT "a" (a msg)
-       P'.tellT "b" (b msg)
-  textGet
-   = do
-       mods <- P'.sepEndBy (P'.choice [parse'a, parse'b]) P'.spaces
-       Prelude'.return (Prelude'.foldl (\ v f -> f v) P'.defaultValue mods)
-    where
-        parse'a
-         = P'.try
-            (do
-               v <- P'.getT "a"
-               Prelude'.return (\ o -> o{a = v}))
-        parse'b
-         = P'.try
-            (do
-               v <- P'.getT "b"
-               Prelude'.return (\ o -> o{b = v}))
diff --git a/Crypto/Proto/RLWE/SampleDiscProduct.hs b/Crypto/Proto/RLWE/SampleDiscProduct.hs
new file mode 100644
--- /dev/null
+++ b/Crypto/Proto/RLWE/SampleDiscProduct.hs
@@ -0,0 +1,88 @@
+{-# LANGUAGE BangPatterns, DeriveDataTypeable, DeriveGeneric, FlexibleInstances, MultiParamTypeClasses #-}
+{-# OPTIONS_GHC  -fno-warn-unused-imports #-}
+module Crypto.Proto.RLWE.SampleDiscProduct (SampleDiscProduct(..)) where
+import Prelude ((+), (/))
+import qualified Prelude as Prelude'
+import qualified Data.Typeable as Prelude'
+import qualified GHC.Generics as Prelude'
+import qualified Data.Data as Prelude'
+import qualified Text.ProtocolBuffers.Header as P'
+import qualified Crypto.Proto.Lol.RqProduct as Crypto.Proto.Lol (RqProduct)
+
+data SampleDiscProduct = SampleDiscProduct{a :: !(Crypto.Proto.Lol.RqProduct), b :: !(Crypto.Proto.Lol.RqProduct)}
+                       deriving (Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable, Prelude'.Data, Prelude'.Generic)
+
+instance P'.Mergeable SampleDiscProduct where
+  mergeAppend (SampleDiscProduct x'1 x'2) (SampleDiscProduct y'1 y'2)
+   = SampleDiscProduct (P'.mergeAppend x'1 y'1) (P'.mergeAppend x'2 y'2)
+
+instance P'.Default SampleDiscProduct where
+  defaultValue = SampleDiscProduct P'.defaultValue P'.defaultValue
+
+instance P'.Wire SampleDiscProduct where
+  wireSize ft' self'@(SampleDiscProduct x'1 x'2)
+   = case ft' of
+       10 -> calc'Size
+       11 -> P'.prependMessageSize calc'Size
+       _ -> P'.wireSizeErr ft' self'
+    where
+        calc'Size = (P'.wireSizeReq 1 11 x'1 + P'.wireSizeReq 1 11 x'2)
+  wirePut ft' self'@(SampleDiscProduct x'1 x'2)
+   = case ft' of
+       10 -> put'Fields
+       11 -> do
+               P'.putSize (P'.wireSize 10 self')
+               put'Fields
+       _ -> P'.wirePutErr ft' self'
+    where
+        put'Fields
+         = do
+             P'.wirePutReq 10 11 x'1
+             P'.wirePutReq 18 11 x'2
+  wireGet ft'
+   = case ft' of
+       10 -> P'.getBareMessageWith update'Self
+       11 -> P'.getMessageWith update'Self
+       _ -> P'.wireGetErr ft'
+    where
+        update'Self wire'Tag old'Self
+         = case wire'Tag of
+             10 -> Prelude'.fmap (\ !new'Field -> old'Self{a = P'.mergeAppend (a old'Self) (new'Field)}) (P'.wireGet 11)
+             18 -> Prelude'.fmap (\ !new'Field -> old'Self{b = P'.mergeAppend (b old'Self) (new'Field)}) (P'.wireGet 11)
+             _ -> let (field'Number, wire'Type) = P'.splitWireTag wire'Tag in P'.unknown field'Number wire'Type old'Self
+
+instance P'.MessageAPI msg' (msg' -> SampleDiscProduct) SampleDiscProduct where
+  getVal m' f' = f' m'
+
+instance P'.GPB SampleDiscProduct
+
+instance P'.ReflectDescriptor SampleDiscProduct where
+  getMessageInfo _ = P'.GetMessageInfo (P'.fromDistinctAscList [10, 18]) (P'.fromDistinctAscList [10, 18])
+  reflectDescriptorInfo _
+   = Prelude'.read
+      "DescriptorInfo {descName = ProtoName {protobufName = FIName \".crypto.proto.RLWE.SampleDiscProduct\", haskellPrefix = [], parentModule = [MName \"Crypto\",MName \"Proto\",MName \"RLWE\"], baseName = MName \"SampleDiscProduct\"}, descFilePath = [\"Crypto\",\"Proto\",\"RLWE\",\"SampleDiscProduct.hs\"], isGroup = False, fields = fromList [FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".crypto.proto.RLWE.SampleDiscProduct.a\", haskellPrefix' = [], parentModule' = [MName \"Crypto\",MName \"Proto\",MName \"RLWE\",MName \"SampleDiscProduct\"], baseName' = FName \"a\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 1}, wireTag = WireTag {getWireTag = 10}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 11}, typeName = Just (ProtoName {protobufName = FIName \".crypto.proto.lol.RqProduct\", haskellPrefix = [], parentModule = [MName \"Crypto\",MName \"Proto\",MName \"Lol\"], baseName = MName \"RqProduct\"}), hsRawDefault = Nothing, hsDefault = Nothing},FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".crypto.proto.RLWE.SampleDiscProduct.b\", haskellPrefix' = [], parentModule' = [MName \"Crypto\",MName \"Proto\",MName \"RLWE\",MName \"SampleDiscProduct\"], baseName' = FName \"b\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 2}, wireTag = WireTag {getWireTag = 18}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 11}, typeName = Just (ProtoName {protobufName = FIName \".crypto.proto.lol.RqProduct\", haskellPrefix = [], parentModule = [MName \"Crypto\",MName \"Proto\",MName \"Lol\"], baseName = MName \"RqProduct\"}), hsRawDefault = Nothing, hsDefault = Nothing}], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False}"
+
+instance P'.TextType SampleDiscProduct where
+  tellT = P'.tellSubMessage
+  getT = P'.getSubMessage
+
+instance P'.TextMsg SampleDiscProduct where
+  textPut msg
+   = do
+       P'.tellT "a" (a msg)
+       P'.tellT "b" (b msg)
+  textGet
+   = do
+       mods <- P'.sepEndBy (P'.choice [parse'a, parse'b]) P'.spaces
+       Prelude'.return (Prelude'.foldl (\ v f -> f v) P'.defaultValue mods)
+    where
+        parse'a
+         = P'.try
+            (do
+               v <- P'.getT "a"
+               Prelude'.return (\ o -> o{a = v}))
+        parse'b
+         = P'.try
+            (do
+               v <- P'.getT "b"
+               Prelude'.return (\ o -> o{b = v}))
diff --git a/Crypto/Proto/RLWE/SampleRLWR.hs b/Crypto/Proto/RLWE/SampleRLWR.hs
--- a/Crypto/Proto/RLWE/SampleRLWR.hs
+++ b/Crypto/Proto/RLWE/SampleRLWR.hs
@@ -7,9 +7,9 @@
 import qualified GHC.Generics as Prelude'
 import qualified Data.Data as Prelude'
 import qualified Text.ProtocolBuffers.Header as P'
-import qualified Crypto.Proto.Lol.RqProduct as Lol (RqProduct)
+import qualified Crypto.Proto.Lol.Rq as Crypto.Proto.Lol (Rq)
 
-data SampleRLWR = SampleRLWR{a :: !(Lol.RqProduct), b :: !(Lol.RqProduct)}
+data SampleRLWR = SampleRLWR{a :: !(Crypto.Proto.Lol.Rq), b :: !(Crypto.Proto.Lol.Rq)}
                 deriving (Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable, Prelude'.Data, Prelude'.Generic)
 
 instance P'.Mergeable SampleRLWR where
@@ -59,7 +59,7 @@
   getMessageInfo _ = P'.GetMessageInfo (P'.fromDistinctAscList [10, 18]) (P'.fromDistinctAscList [10, 18])
   reflectDescriptorInfo _
    = Prelude'.read
-      "DescriptorInfo {descName = ProtoName {protobufName = FIName \".RLWE.SampleRLWR\", haskellPrefix = [MName \"Crypto\",MName \"Proto\"], parentModule = [MName \"RLWE\"], baseName = MName \"SampleRLWR\"}, descFilePath = [\"Crypto\",\"Proto\",\"RLWE\",\"SampleRLWR.hs\"], isGroup = False, fields = fromList [FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".RLWE.SampleRLWR.a\", haskellPrefix' = [MName \"Crypto\",MName \"Proto\"], parentModule' = [MName \"RLWE\",MName \"SampleRLWR\"], baseName' = FName \"a\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 1}, wireTag = WireTag {getWireTag = 10}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 11}, typeName = Just (ProtoName {protobufName = FIName \".Lol.RqProduct\", haskellPrefix = [MName \"Crypto\",MName \"Proto\"], parentModule = [MName \"Lol\"], baseName = MName \"RqProduct\"}), hsRawDefault = Nothing, hsDefault = Nothing},FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".RLWE.SampleRLWR.b\", haskellPrefix' = [MName \"Crypto\",MName \"Proto\"], parentModule' = [MName \"RLWE\",MName \"SampleRLWR\"], baseName' = FName \"b\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 2}, wireTag = WireTag {getWireTag = 18}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 11}, typeName = Just (ProtoName {protobufName = FIName \".Lol.RqProduct\", haskellPrefix = [MName \"Crypto\",MName \"Proto\"], parentModule = [MName \"Lol\"], baseName = MName \"RqProduct\"}), hsRawDefault = Nothing, hsDefault = Nothing}], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False}"
+      "DescriptorInfo {descName = ProtoName {protobufName = FIName \".crypto.proto.RLWE.SampleRLWR\", haskellPrefix = [], parentModule = [MName \"Crypto\",MName \"Proto\",MName \"RLWE\"], baseName = MName \"SampleRLWR\"}, descFilePath = [\"Crypto\",\"Proto\",\"RLWE\",\"SampleRLWR.hs\"], isGroup = False, fields = fromList [FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".crypto.proto.RLWE.SampleRLWR.a\", haskellPrefix' = [], parentModule' = [MName \"Crypto\",MName \"Proto\",MName \"RLWE\",MName \"SampleRLWR\"], baseName' = FName \"a\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 1}, wireTag = WireTag {getWireTag = 10}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 11}, typeName = Just (ProtoName {protobufName = FIName \".crypto.proto.lol.Rq\", haskellPrefix = [], parentModule = [MName \"Crypto\",MName \"Proto\",MName \"Lol\"], baseName = MName \"Rq\"}), hsRawDefault = Nothing, hsDefault = Nothing},FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".crypto.proto.RLWE.SampleRLWR.b\", haskellPrefix' = [], parentModule' = [MName \"Crypto\",MName \"Proto\",MName \"RLWE\",MName \"SampleRLWR\"], baseName' = FName \"b\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 2}, wireTag = WireTag {getWireTag = 18}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 11}, typeName = Just (ProtoName {protobufName = FIName \".crypto.proto.lol.Rq\", haskellPrefix = [], parentModule = [MName \"Crypto\",MName \"Proto\",MName \"Lol\"], baseName = MName \"Rq\"}), hsRawDefault = Nothing, hsDefault = Nothing}], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False}"
 
 instance P'.TextType SampleRLWR where
   tellT = P'.tellSubMessage
diff --git a/Crypto/Proto/RLWE/SampleRLWR1.hs b/Crypto/Proto/RLWE/SampleRLWR1.hs
deleted file mode 100644
--- a/Crypto/Proto/RLWE/SampleRLWR1.hs
+++ /dev/null
@@ -1,87 +0,0 @@
-{-# LANGUAGE BangPatterns, DeriveDataTypeable, DeriveGeneric, FlexibleInstances, MultiParamTypeClasses #-}
-{-# OPTIONS_GHC  -fno-warn-unused-imports #-}
-module Crypto.Proto.RLWE.SampleRLWR1 (SampleRLWR1(..)) where
-import Prelude ((+), (/))
-import qualified Prelude as Prelude'
-import qualified Data.Typeable as Prelude'
-import qualified GHC.Generics as Prelude'
-import qualified Data.Data as Prelude'
-import qualified Text.ProtocolBuffers.Header as P'
-import qualified Crypto.Proto.Lol.Rq1 as Lol (Rq1)
-
-data SampleRLWR1 = SampleRLWR1{a :: !(Lol.Rq1), b :: !(Lol.Rq1)}
-                 deriving (Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable, Prelude'.Data, Prelude'.Generic)
-
-instance P'.Mergeable SampleRLWR1 where
-  mergeAppend (SampleRLWR1 x'1 x'2) (SampleRLWR1 y'1 y'2) = SampleRLWR1 (P'.mergeAppend x'1 y'1) (P'.mergeAppend x'2 y'2)
-
-instance P'.Default SampleRLWR1 where
-  defaultValue = SampleRLWR1 P'.defaultValue P'.defaultValue
-
-instance P'.Wire SampleRLWR1 where
-  wireSize ft' self'@(SampleRLWR1 x'1 x'2)
-   = case ft' of
-       10 -> calc'Size
-       11 -> P'.prependMessageSize calc'Size
-       _ -> P'.wireSizeErr ft' self'
-    where
-        calc'Size = (P'.wireSizeReq 1 11 x'1 + P'.wireSizeReq 1 11 x'2)
-  wirePut ft' self'@(SampleRLWR1 x'1 x'2)
-   = case ft' of
-       10 -> put'Fields
-       11 -> do
-               P'.putSize (P'.wireSize 10 self')
-               put'Fields
-       _ -> P'.wirePutErr ft' self'
-    where
-        put'Fields
-         = do
-             P'.wirePutReq 10 11 x'1
-             P'.wirePutReq 18 11 x'2
-  wireGet ft'
-   = case ft' of
-       10 -> P'.getBareMessageWith update'Self
-       11 -> P'.getMessageWith update'Self
-       _ -> P'.wireGetErr ft'
-    where
-        update'Self wire'Tag old'Self
-         = case wire'Tag of
-             10 -> Prelude'.fmap (\ !new'Field -> old'Self{a = P'.mergeAppend (a old'Self) (new'Field)}) (P'.wireGet 11)
-             18 -> Prelude'.fmap (\ !new'Field -> old'Self{b = P'.mergeAppend (b old'Self) (new'Field)}) (P'.wireGet 11)
-             _ -> let (field'Number, wire'Type) = P'.splitWireTag wire'Tag in P'.unknown field'Number wire'Type old'Self
-
-instance P'.MessageAPI msg' (msg' -> SampleRLWR1) SampleRLWR1 where
-  getVal m' f' = f' m'
-
-instance P'.GPB SampleRLWR1
-
-instance P'.ReflectDescriptor SampleRLWR1 where
-  getMessageInfo _ = P'.GetMessageInfo (P'.fromDistinctAscList [10, 18]) (P'.fromDistinctAscList [10, 18])
-  reflectDescriptorInfo _
-   = Prelude'.read
-      "DescriptorInfo {descName = ProtoName {protobufName = FIName \".RLWE.SampleRLWR1\", haskellPrefix = [MName \"Crypto\",MName \"Proto\"], parentModule = [MName \"RLWE\"], baseName = MName \"SampleRLWR1\"}, descFilePath = [\"Crypto\",\"Proto\",\"RLWE\",\"SampleRLWR1.hs\"], isGroup = False, fields = fromList [FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".RLWE.SampleRLWR1.a\", haskellPrefix' = [MName \"Crypto\",MName \"Proto\"], parentModule' = [MName \"RLWE\",MName \"SampleRLWR1\"], baseName' = FName \"a\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 1}, wireTag = WireTag {getWireTag = 10}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 11}, typeName = Just (ProtoName {protobufName = FIName \".Lol.Rq1\", haskellPrefix = [MName \"Crypto\",MName \"Proto\"], parentModule = [MName \"Lol\"], baseName = MName \"Rq1\"}), hsRawDefault = Nothing, hsDefault = Nothing},FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".RLWE.SampleRLWR1.b\", haskellPrefix' = [MName \"Crypto\",MName \"Proto\"], parentModule' = [MName \"RLWE\",MName \"SampleRLWR1\"], baseName' = FName \"b\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 2}, wireTag = WireTag {getWireTag = 18}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 11}, typeName = Just (ProtoName {protobufName = FIName \".Lol.Rq1\", haskellPrefix = [MName \"Crypto\",MName \"Proto\"], parentModule = [MName \"Lol\"], baseName = MName \"Rq1\"}), hsRawDefault = Nothing, hsDefault = Nothing}], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False}"
-
-instance P'.TextType SampleRLWR1 where
-  tellT = P'.tellSubMessage
-  getT = P'.getSubMessage
-
-instance P'.TextMsg SampleRLWR1 where
-  textPut msg
-   = do
-       P'.tellT "a" (a msg)
-       P'.tellT "b" (b msg)
-  textGet
-   = do
-       mods <- P'.sepEndBy (P'.choice [parse'a, parse'b]) P'.spaces
-       Prelude'.return (Prelude'.foldl (\ v f -> f v) P'.defaultValue mods)
-    where
-        parse'a
-         = P'.try
-            (do
-               v <- P'.getT "a"
-               Prelude'.return (\ o -> o{a = v}))
-        parse'b
-         = P'.try
-            (do
-               v <- P'.getT "b"
-               Prelude'.return (\ o -> o{b = v}))
diff --git a/Crypto/Proto/RLWE/SampleRLWRProduct.hs b/Crypto/Proto/RLWE/SampleRLWRProduct.hs
new file mode 100644
--- /dev/null
+++ b/Crypto/Proto/RLWE/SampleRLWRProduct.hs
@@ -0,0 +1,88 @@
+{-# LANGUAGE BangPatterns, DeriveDataTypeable, DeriveGeneric, FlexibleInstances, MultiParamTypeClasses #-}
+{-# OPTIONS_GHC  -fno-warn-unused-imports #-}
+module Crypto.Proto.RLWE.SampleRLWRProduct (SampleRLWRProduct(..)) where
+import Prelude ((+), (/))
+import qualified Prelude as Prelude'
+import qualified Data.Typeable as Prelude'
+import qualified GHC.Generics as Prelude'
+import qualified Data.Data as Prelude'
+import qualified Text.ProtocolBuffers.Header as P'
+import qualified Crypto.Proto.Lol.RqProduct as Crypto.Proto.Lol (RqProduct)
+
+data SampleRLWRProduct = SampleRLWRProduct{a :: !(Crypto.Proto.Lol.RqProduct), b :: !(Crypto.Proto.Lol.RqProduct)}
+                       deriving (Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable, Prelude'.Data, Prelude'.Generic)
+
+instance P'.Mergeable SampleRLWRProduct where
+  mergeAppend (SampleRLWRProduct x'1 x'2) (SampleRLWRProduct y'1 y'2)
+   = SampleRLWRProduct (P'.mergeAppend x'1 y'1) (P'.mergeAppend x'2 y'2)
+
+instance P'.Default SampleRLWRProduct where
+  defaultValue = SampleRLWRProduct P'.defaultValue P'.defaultValue
+
+instance P'.Wire SampleRLWRProduct where
+  wireSize ft' self'@(SampleRLWRProduct x'1 x'2)
+   = case ft' of
+       10 -> calc'Size
+       11 -> P'.prependMessageSize calc'Size
+       _ -> P'.wireSizeErr ft' self'
+    where
+        calc'Size = (P'.wireSizeReq 1 11 x'1 + P'.wireSizeReq 1 11 x'2)
+  wirePut ft' self'@(SampleRLWRProduct x'1 x'2)
+   = case ft' of
+       10 -> put'Fields
+       11 -> do
+               P'.putSize (P'.wireSize 10 self')
+               put'Fields
+       _ -> P'.wirePutErr ft' self'
+    where
+        put'Fields
+         = do
+             P'.wirePutReq 10 11 x'1
+             P'.wirePutReq 18 11 x'2
+  wireGet ft'
+   = case ft' of
+       10 -> P'.getBareMessageWith update'Self
+       11 -> P'.getMessageWith update'Self
+       _ -> P'.wireGetErr ft'
+    where
+        update'Self wire'Tag old'Self
+         = case wire'Tag of
+             10 -> Prelude'.fmap (\ !new'Field -> old'Self{a = P'.mergeAppend (a old'Self) (new'Field)}) (P'.wireGet 11)
+             18 -> Prelude'.fmap (\ !new'Field -> old'Self{b = P'.mergeAppend (b old'Self) (new'Field)}) (P'.wireGet 11)
+             _ -> let (field'Number, wire'Type) = P'.splitWireTag wire'Tag in P'.unknown field'Number wire'Type old'Self
+
+instance P'.MessageAPI msg' (msg' -> SampleRLWRProduct) SampleRLWRProduct where
+  getVal m' f' = f' m'
+
+instance P'.GPB SampleRLWRProduct
+
+instance P'.ReflectDescriptor SampleRLWRProduct where
+  getMessageInfo _ = P'.GetMessageInfo (P'.fromDistinctAscList [10, 18]) (P'.fromDistinctAscList [10, 18])
+  reflectDescriptorInfo _
+   = Prelude'.read
+      "DescriptorInfo {descName = ProtoName {protobufName = FIName \".crypto.proto.RLWE.SampleRLWRProduct\", haskellPrefix = [], parentModule = [MName \"Crypto\",MName \"Proto\",MName \"RLWE\"], baseName = MName \"SampleRLWRProduct\"}, descFilePath = [\"Crypto\",\"Proto\",\"RLWE\",\"SampleRLWRProduct.hs\"], isGroup = False, fields = fromList [FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".crypto.proto.RLWE.SampleRLWRProduct.a\", haskellPrefix' = [], parentModule' = [MName \"Crypto\",MName \"Proto\",MName \"RLWE\",MName \"SampleRLWRProduct\"], baseName' = FName \"a\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 1}, wireTag = WireTag {getWireTag = 10}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 11}, typeName = Just (ProtoName {protobufName = FIName \".crypto.proto.lol.RqProduct\", haskellPrefix = [], parentModule = [MName \"Crypto\",MName \"Proto\",MName \"Lol\"], baseName = MName \"RqProduct\"}), hsRawDefault = Nothing, hsDefault = Nothing},FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".crypto.proto.RLWE.SampleRLWRProduct.b\", haskellPrefix' = [], parentModule' = [MName \"Crypto\",MName \"Proto\",MName \"RLWE\",MName \"SampleRLWRProduct\"], baseName' = FName \"b\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 2}, wireTag = WireTag {getWireTag = 18}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = True, canRepeat = False, mightPack = False, typeCode = FieldType {getFieldType = 11}, typeName = Just (ProtoName {protobufName = FIName \".crypto.proto.lol.RqProduct\", haskellPrefix = [], parentModule = [MName \"Crypto\",MName \"Proto\",MName \"Lol\"], baseName = MName \"RqProduct\"}), hsRawDefault = Nothing, hsDefault = Nothing}], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False}"
+
+instance P'.TextType SampleRLWRProduct where
+  tellT = P'.tellSubMessage
+  getT = P'.getSubMessage
+
+instance P'.TextMsg SampleRLWRProduct where
+  textPut msg
+   = do
+       P'.tellT "a" (a msg)
+       P'.tellT "b" (b msg)
+  textGet
+   = do
+       mods <- P'.sepEndBy (P'.choice [parse'a, parse'b]) P'.spaces
+       Prelude'.return (Prelude'.foldl (\ v f -> f v) P'.defaultValue mods)
+    where
+        parse'a
+         = P'.try
+            (do
+               v <- P'.getT "a"
+               Prelude'.return (\ o -> o{a = v}))
+        parse'b
+         = P'.try
+            (do
+               v <- P'.getT "b"
+               Prelude'.return (\ o -> o{b = v}))
diff --git a/LICENSE b/LICENSE
--- a/LICENSE
+++ b/LICENSE
@@ -1,282 +1,623 @@
-             GNU GENERAL PUBLIC LICENSE
-                Version 2, June 1991
+              GNU GENERAL PUBLIC LICENSE
+                Version 3, 29 June 2007
 
- Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
  Everyone is permitted to copy and distribute verbatim copies
  of this license document, but changing it is not allowed.
 
                      Preamble
 
-  The licenses for most software are designed to take away your
-freedom to share and change it.  By contrast, the GNU General Public
-License is intended to guarantee your freedom to share and change free
-software--to make sure the software is free for all its users.  This
-General Public License applies to most of the Free Software
-Foundation's software and to any other program whose authors commit to
-using it.  (Some other Free Software Foundation software is covered by
-the GNU Lesser General Public License instead.)  You can apply it to
+  The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+  The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works.  By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.  We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors.  You can apply it to
 your programs, too.
 
   When we speak of free software, we are referring to freedom, not
 price.  Our General Public Licenses are designed to make sure that you
 have the freedom to distribute copies of free software (and charge for
-this service if you wish), that you receive source code or can get it
-if you want it, that you can change the software or use pieces of it
-in new free programs; and that you know you can do these things.
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
 
-  To protect your rights, we need to make restrictions that forbid
-anyone to deny you these rights or to ask you to surrender the rights.
-These restrictions translate to certain responsibilities for you if you
-distribute copies of the software, or if you modify it.
+  To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights.  Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
 
   For example, if you distribute copies of such a program, whether
-gratis or for a fee, you must give the recipients all the rights that
-you have.  You must make sure that they, too, receive or can get the
-source code.  And you must show them these terms so they know their
-rights.
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received.  You must make sure that they, too, receive
+or can get the source code.  And you must show them these terms so they
+know their rights.
 
-  We protect your rights with two steps: (1) copyright the software, and
-(2) offer you this license which gives you legal permission to copy,
-distribute and/or modify the software.
+  Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
 
-  Also, for each author's protection and ours, we want to make certain
-that everyone understands that there is no warranty for this free
-software.  If the software is modified by someone else and passed on, we
-want its recipients to know that what they have is not the original, so
-that any problems introduced by others will not reflect on the original
-authors' reputations.
+  For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software.  For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
 
-  Finally, any free program is threatened constantly by software
-patents.  We wish to avoid the danger that redistributors of a free
-program will individually obtain patent licenses, in effect making the
-program proprietary.  To prevent this, we have made it clear that any
-patent must be licensed for everyone's free use or not licensed at all.
+  Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so.  This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software.  The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable.  Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products.  If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
 
+  Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary.  To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
   The precise terms and conditions for copying, distribution and
 modification follow.
 
-             GNU GENERAL PUBLIC LICENSE
-   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+                TERMS AND CONDITIONS
 
-  0. This License applies to any program or other work which contains
-a notice placed by the copyright holder saying it may be distributed
-under the terms of this General Public License.  The "Program", below,
-refers to any such program or work, and a "work based on the Program"
-means either the Program or any derivative work under copyright law:
-that is to say, a work containing the Program or a portion of it,
-either verbatim or with modifications and/or translated into another
-language.  (Hereinafter, translation is included without limitation in
-the term "modification".)  Each licensee is addressed as "you".
+  0. Definitions.
 
-Activities other than copying, distribution and modification are not
-covered by this License; they are outside its scope.  The act of
-running the Program is not restricted, and the output from the Program
-is covered only if its contents constitute a work based on the
-Program (independent of having been made by running the Program).
-Whether that is true depends on what the Program does.
+  "This License" refers to version 3 of the GNU General Public License.
 
-  1. You may copy and distribute verbatim copies of the Program's
-source code as you receive it, in any medium, provided that you
-conspicuously and appropriately publish on each copy an appropriate
-copyright notice and disclaimer of warranty; keep intact all the
-notices that refer to this License and to the absence of any warranty;
-and give any other recipients of the Program a copy of this License
-along with the Program.
+  "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
 
-You may charge a fee for the physical act of transferring a copy, and
-you may at your option offer warranty protection in exchange for a fee.
+  "The Program" refers to any copyrightable work licensed under this
+License.  Each licensee is addressed as "you".  "Licensees" and
+"recipients" may be individuals or organizations.
 
-  2. You may modify your copy or copies of the Program or any portion
-of it, thus forming a work based on the Program, and copy and
-distribute such modifications or work under the terms of Section 1
-above, provided that you also meet all of these conditions:
+  To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy.  The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
 
-    a) You must cause the modified files to carry prominent notices
-    stating that you changed the files and the date of any change.
+  A "covered work" means either the unmodified Program or a work based
+on the Program.
 
-    b) You must cause any work that you distribute or publish, that in
-    whole or in part contains or is derived from the Program or any
-    part thereof, to be licensed as a whole at no charge to all third
-    parties under the terms of this License.
+  To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy.  Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
 
-    c) If the modified program normally reads commands interactively
-    when run, you must cause it, when started running for such
-    interactive use in the most ordinary way, to print or display an
-    announcement including an appropriate copyright notice and a
-    notice that there is no warranty (or else, saying that you provide
-    a warranty) and that users may redistribute the program under
-    these conditions, and telling the user how to view a copy of this
-    License.  (Exception: if the Program itself is interactive but
-    does not normally print such an announcement, your work based on
-    the Program is not required to print an announcement.)
+  To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies.  Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
 
-These requirements apply to the modified work as a whole.  If
-identifiable sections of that work are not derived from the Program,
-and can be reasonably considered independent and separate works in
-themselves, then this License, and its terms, do not apply to those
-sections when you distribute them as separate works.  But when you
-distribute the same sections as part of a whole which is a work based
-on the Program, the distribution of the whole must be on the terms of
-this License, whose permissions for other licensees extend to the
-entire whole, and thus to each and every part regardless of who wrote it.
+  An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License.  If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
 
-Thus, it is not the intent of this section to claim rights or contest
-your rights to work written entirely by you; rather, the intent is to
-exercise the right to control the distribution of derivative or
-collective works based on the Program.
+  1. Source Code.
 
-In addition, mere aggregation of another work not based on the Program
-with the Program (or with a work based on the Program) on a volume of
-a storage or distribution medium does not bring the other work under
-the scope of this License.
+  The "source code" for a work means the preferred form of the work
+for making modifications to it.  "Object code" means any non-source
+form of a work.
 
-  3. You may copy and distribute the Program (or a work based on it,
-under Section 2) in object code or executable form under the terms of
-Sections 1 and 2 above provided that you also do one of the following:
+  A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
 
-    a) Accompany it with the complete corresponding machine-readable
-    source code, which must be distributed under the terms of Sections
-    1 and 2 above on a medium customarily used for software interchange; or,
+  The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form.  A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
 
-    b) Accompany it with a written offer, valid for at least three
-    years, to give any third party, for a charge no more than your
-    cost of physically performing source distribution, a complete
-    machine-readable copy of the corresponding source code, to be
-    distributed under the terms of Sections 1 and 2 above on a medium
-    customarily used for software interchange; or,
+  The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities.  However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work.  For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
 
-    c) Accompany it with the information you received as to the offer
-    to distribute corresponding source code.  (This alternative is
-    allowed only for noncommercial distribution and only if you
-    received the program in object code or executable form with such
-    an offer, in accord with Subsection b above.)
+  The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
 
-The source code for a work means the preferred form of the work for
-making modifications to it.  For an executable work, complete source
-code means all the source code for all modules it contains, plus any
-associated interface definition files, plus the scripts used to
-control compilation and installation of the executable.  However, as a
-special exception, the source code distributed need not include
-anything that is normally distributed (in either source or binary
-form) with the major components (compiler, kernel, and so on) of the
-operating system on which the executable runs, unless that component
-itself accompanies the executable.
+  The Corresponding Source for a work in source code form is that
+same work.
 
-If distribution of executable or object code is made by offering
-access to copy from a designated place, then offering equivalent
-access to copy the source code from the same place counts as
-distribution of the source code, even though third parties are not
-compelled to copy the source along with the object code.
+  2. Basic Permissions.
 
-  4. You may not copy, modify, sublicense, or distribute the Program
-except as expressly provided under this License.  Any attempt
-otherwise to copy, modify, sublicense or distribute the Program is
-void, and will automatically terminate your rights under this License.
-However, parties who have received copies, or rights, from you under
-this License will not have their licenses terminated so long as such
-parties remain in full compliance.
+  All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met.  This License explicitly affirms your unlimited
+permission to run the unmodified Program.  The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work.  This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
 
-  5. You are not required to accept this License, since you have not
-signed it.  However, nothing else grants you permission to modify or
-distribute the Program or its derivative works.  These actions are
-prohibited by law if you do not accept this License.  Therefore, by
-modifying or distributing the Program (or any work based on the
-Program), you indicate your acceptance of this License to do so, and
-all its terms and conditions for copying, distributing or modifying
-the Program or works based on it.
+  You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force.  You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright.  Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
 
-  6. Each time you redistribute the Program (or any work based on the
-Program), the recipient automatically receives a license from the
-original licensor to copy, distribute or modify the Program subject to
-these terms and conditions.  You may not impose any further
-restrictions on the recipients' exercise of the rights granted herein.
-You are not responsible for enforcing compliance by third parties to
+  Conveying under any other circumstances is permitted solely under
+the conditions stated below.  Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+  3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+  No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+  When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+  4. Conveying Verbatim Copies.
+
+  You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+  You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+  5. Conveying Modified Source Versions.
+
+  You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+    a) The work must carry prominent notices stating that you modified
+    it, and giving a relevant date.
+
+    b) The work must carry prominent notices stating that it is
+    released under this License and any conditions added under section
+    7.  This requirement modifies the requirement in section 4 to
+    "keep intact all notices".
+
+    c) You must license the entire work, as a whole, under this
+    License to anyone who comes into possession of a copy.  This
+    License will therefore apply, along with any applicable section 7
+    additional terms, to the whole of the work, and all its parts,
+    regardless of how they are packaged.  This License gives no
+    permission to license the work in any other way, but it does not
+    invalidate such permission if you have separately received it.
+
+    d) If the work has interactive user interfaces, each must display
+    Appropriate Legal Notices; however, if the Program has interactive
+    interfaces that do not display Appropriate Legal Notices, your
+    work need not make them do so.
+
+  A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit.  Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+  6. Conveying Non-Source Forms.
+
+  You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+    a) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by the
+    Corresponding Source fixed on a durable physical medium
+    customarily used for software interchange.
+
+    b) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by a
+    written offer, valid for at least three years and valid for as
+    long as you offer spare parts or customer support for that product
+    model, to give anyone who possesses the object code either (1) a
+    copy of the Corresponding Source for all the software in the
+    product that is covered by this License, on a durable physical
+    medium customarily used for software interchange, for a price no
+    more than your reasonable cost of physically performing this
+    conveying of source, or (2) access to copy the
+    Corresponding Source from a network server at no charge.
+
+    c) Convey individual copies of the object code with a copy of the
+    written offer to provide the Corresponding Source.  This
+    alternative is allowed only occasionally and noncommercially, and
+    only if you received the object code with such an offer, in accord
+    with subsection 6b.
+
+    d) Convey the object code by offering access from a designated
+    place (gratis or for a charge), and offer equivalent access to the
+    Corresponding Source in the same way through the same place at no
+    further charge.  You need not require recipients to copy the
+    Corresponding Source along with the object code.  If the place to
+    copy the object code is a network server, the Corresponding Source
+    may be on a different server (operated by you or a third party)
+    that supports equivalent copying facilities, provided you maintain
+    clear directions next to the object code saying where to find the
+    Corresponding Source.  Regardless of what server hosts the
+    Corresponding Source, you remain obligated to ensure that it is
+    available for as long as needed to satisfy these requirements.
+
+    e) Convey the object code using peer-to-peer transmission, provided
+    you inform other peers where the object code and Corresponding
+    Source of the work are being offered to the general public at no
+    charge under subsection 6d.
+
+  A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+  A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling.  In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage.  For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product.  A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+  "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source.  The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+  If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information.  But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+  The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed.  Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+  Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+  7. Additional Terms.
+
+  "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law.  If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+  When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it.  (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.)  You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+  Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+    a) Disclaiming warranty or limiting liability differently from the
+    terms of sections 15 and 16 of this License; or
+
+    b) Requiring preservation of specified reasonable legal notices or
+    author attributions in that material or in the Appropriate Legal
+    Notices displayed by works containing it; or
+
+    c) Prohibiting misrepresentation of the origin of that material, or
+    requiring that modified versions of such material be marked in
+    reasonable ways as different from the original version; or
+
+    d) Limiting the use for publicity purposes of names of licensors or
+    authors of the material; or
+
+    e) Declining to grant rights under trademark law for use of some
+    trade names, trademarks, or service marks; or
+
+    f) Requiring indemnification of licensors and authors of that
+    material by anyone who conveys the material (or modified versions of
+    it) with contractual assumptions of liability to the recipient, for
+    any liability that these contractual assumptions directly impose on
+    those licensors and authors.
+
+  All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10.  If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term.  If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+  If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+  Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+  8. Termination.
+
+  You may not propagate or modify a covered work except as expressly
+provided under this License.  Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+  However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+  Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+  Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License.  If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+  9. Acceptance Not Required for Having Copies.
+
+  You are not required to accept this License in order to receive or
+run a copy of the Program.  Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance.  However,
+nothing other than this License grants you permission to propagate or
+modify any covered work.  These actions infringe copyright if you do
+not accept this License.  Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+  10. Automatic Licensing of Downstream Recipients.
+
+  Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License.  You are not responsible
+for enforcing compliance by third parties with this License.
+
+  An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations.  If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+  You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License.  For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+  11. Patents.
+
+  A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based.  The
+work thus licensed is called the contributor's "contributor version".
+
+  A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version.  For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
 this License.
 
-  7. If, as a consequence of a court judgment or allegation of patent
-infringement or for any other reason (not limited to patent issues),
-conditions are imposed on you (whether by court order, agreement or
-otherwise) that contradict the conditions of this License, they do not
-excuse you from the conditions of this License.  If you cannot
-distribute so as to satisfy simultaneously your obligations under this
-License and any other pertinent obligations, then as a consequence you
-may not distribute the Program at all.  For example, if a patent
-license would not permit royalty-free redistribution of the Program by
-all those who receive copies directly or indirectly through you, then
-the only way you could satisfy both it and this License would be to
-refrain entirely from distribution of the Program.
+  Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
 
-If any portion of this section is held invalid or unenforceable under
-any particular circumstance, the balance of the section is intended to
-apply and the section as a whole is intended to apply in other
-circumstances.
+  In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement).  To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
 
-It is not the purpose of this section to induce you to infringe any
-patents or other property right claims or to contest validity of any
-such claims; this section has the sole purpose of protecting the
-integrity of the free software distribution system, which is
-implemented by public license practices.  Many people have made
-generous contributions to the wide range of software distributed
-through that system in reliance on consistent application of that
-system; it is up to the author/donor to decide if he or she is willing
-to distribute software through any other system and a licensee cannot
-impose that choice.
+  If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients.  "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
 
-This section is intended to make thoroughly clear what is believed to
-be a consequence of the rest of this License.
+  If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
 
-  8. If the distribution and/or use of the Program is restricted in
-certain countries either by patents or by copyrighted interfaces, the
-original copyright holder who places the Program under this License
-may add an explicit geographical distribution limitation excluding
-those countries, so that distribution is permitted only in or among
-countries not thus excluded.  In such case, this License incorporates
-the limitation as if written in the body of this License.
+  A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License.  You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
 
-  9. The Free Software Foundation may publish revised and/or new versions
-of the General Public License from time to time.  Such new versions will
+  Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+  12. No Surrender of Others' Freedom.
+
+  If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all.  For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+  13. Use with the GNU Affero General Public License.
+
+  Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work.  The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+  14. Revised Versions of this License.
+
+  The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time.  Such new versions will
 be similar in spirit to the present version, but may differ in detail to
 address new problems or concerns.
 
-Each version is given a distinguishing version number.  If the Program
-specifies a version number of this License which applies to it and "any
-later version", you have the option of following the terms and conditions
-either of that version or of any later version published by the Free
-Software Foundation.  If the Program does not specify a version number of
-this License, you may choose any version ever published by the Free Software
-Foundation.
+  Each version is given a distinguishing version number.  If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation.  If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
 
-  10. If you wish to incorporate parts of the Program into other free
-programs whose distribution conditions are different, write to the author
-to ask for permission.  For software which is copyrighted by the Free
-Software Foundation, write to the Free Software Foundation; we sometimes
-make exceptions for this.  Our decision will be guided by the two goals
-of preserving the free status of all derivatives of our free software and
-of promoting the sharing and reuse of software generally.
+  If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
 
-                     NO WARRANTY
+  Later license versions may give you additional or different
+permissions.  However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
 
-  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
-FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
-OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
-PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
-OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
-MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
-TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
-PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
-REPAIR OR CORRECTION.
+  15. Disclaimer of Warranty.
 
-  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
-WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
-REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
-INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
-OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
-TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
-YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
-PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
-POSSIBILITY OF SUCH DAMAGES.
+  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
 
+  16. Limitation of Liability.
+
+  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+  17. Interpretation of Sections 15 and 16.
+
+  If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
               END OF TERMS AND CONDITIONS
 
      How to Apply These Terms to Your New Programs
@@ -287,15 +628,15 @@
 
   To do so, attach the following notices to the program.  It is safest
 to attach them to the start of each source file to most effectively
-convey the exclusion of warranty; and each file should have at least
+state the exclusion of warranty; and each file should have at least
 the "copyright" line and a pointer to where the full notice is found.
 
     <one line to give the program's name and a brief idea of what it does.>
     Copyright (C) <year>  <name of author>
 
-    This program is free software; you can redistribute it and/or modify
+    This program is free software: you can redistribute it and/or modify
     it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 2 of the License, or
+    the Free Software Foundation, either version 3 of the License, or
     (at your option) any later version.
 
     This program is distributed in the hope that it will be useful,
@@ -303,37 +644,31 @@
     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     GNU General Public License for more details.
 
-    You should have received a copy of the GNU General Public License along
-    with this program; if not, write to the Free Software Foundation, Inc.,
-    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
 Also add information on how to contact you by electronic and paper mail.
 
-If the program is interactive, make it output a short notice like this
-when it starts in an interactive mode:
+  If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
 
-    Gnomovision version 69, Copyright (C) year name of author
-    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+    <program>  Copyright (C) <year>  <name of author>
+    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
     This is free software, and you are welcome to redistribute it
     under certain conditions; type `show c' for details.
 
 The hypothetical commands `show w' and `show c' should show the appropriate
-parts of the General Public License.  Of course, the commands you use may
-be called something other than `show w' and `show c'; they could even be
-mouse-clicks or menu items--whatever suits your program.
-
-You should also get your employer (if you work as a programmer) or your
-school, if any, to sign a "copyright disclaimer" for the program, if
-necessary.  Here is a sample; alter the names:
-
-  Yoyodyne, Inc., hereby disclaims all copyright interest in the program
-  `Gnomovision' (which makes passes at compilers) written by James Hacker.
+parts of the General Public License.  Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
 
-  <signature of Ty Coon>, 1 April 1989
-  Ty Coon, President of Vice
+  You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<http://www.gnu.org/licenses/>.
 
-This General Public License does not permit incorporating your program into
-proprietary programs.  If your program is a subroutine library, you may
-consider it more useful to permit linking proprietary applications with the
-library.  If this is what you want to do, use the GNU Lesser General
-Public License instead of this License.
+  The GNU General Public License does not permit incorporating your program
+into proprietary programs.  If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library.  If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.  But first, please read
+<http://www.gnu.org/philosophy/why-not-lgpl.html>.
diff --git a/Lol.proto b/Lol.proto
--- a/Lol.proto
+++ b/Lol.proto
@@ -1,10 +1,15 @@
+package crypto.proto.lol;
+
 // Proto messages for cyclotomic rings and other basic types in Lol
 
 // run this:
 
-// hprotoc -p Crypto.Proto Lol.proto
+// hprotoc Lol.proto
+// protoc Lol.proto [-cpp_out=path/to/cpp/parser] [--java_out=path/to/java/parser] [--python_out=path/to/python/parser]
 
-// coeffs contains the function output corresponding to the decoding basis in R
+// a linear function from one cyclotomic ring to another, over a
+// common subring. 'coeffs' contains the function outputs on the
+// relative decoding basis of the domain ring.
 message LinearRq {
   required uint32 e         = 1;
   required uint32 r         = 2;
@@ -14,39 +19,44 @@
 // For each of the following, the "xs" array is with respect to the
 // decoding basis.
 
+// cyclotomic ring over the integers
 message R {
   required uint32 m  = 1;
   repeated sint64 xs = 2;
 }
 
-// only holds a single modulus. This type was used to serialize cyclotomic ring
-// elements in the RLWE/RLWR challenges.
-message Rq1 {
+// cyclotomic ring modulo a single modulus
+message Rq {
   required uint32 m  = 1;
   required uint64 q  = 2;
   repeated sint64 xs = 3;
 }
 
-// only holds a single modulus. This type was used to serialize cyclotomic ring
-// elements in the RLWE challenges.
-message Kq1 {
+// Cyclotomic field
+message K {
   required uint32 m  = 1;
+  repeated double xs = 2;
+}
+
+// cyclotomic field modulo a single modulus
+message Kq {
+  required uint32 m  = 1;
   required uint64 q  = 2;
   repeated double xs = 3;
 }
 
-// cyclotomic ring mod the product of one or more moduli
+// cyclotomic ring modulo the product of one or more moduli
 message RqProduct {
-  repeated Rq1 rqlist = 1;
+  repeated Rq rqs = 1;
 }
 
-// cyclotomic ring mod the product of one or more moduli
+// cyclotomic field modulo the product of one or more moduli
 message KqProduct {
-  repeated Kq1 kqlist = 1;
+  repeated Kq kqs = 1;
 }
 
-// used to serialize GHC.Fingerprint.Fingerprint. Obviously not intended to be
-// platform independent.
+// used to serialize GHC.Fingerprint.Fingerprint. Obviously not
+// intended to be platform independent.
 message TypeRep {
   required uint64 a = 1;
   required uint64 b = 2;
diff --git a/README b/README
--- a/README
+++ b/README
@@ -1,64 +1,74 @@
-
-This package is primarily a library providing interfaces for lattice cryptography
-primitives. There are two main interfaces: 'Cyclotomic' and 'Tensor'. The
-Cyclotomic interface is the outward-facing API that is used to build cryptographic
-applications like pseudo-random functions, encryption, etc. The Tensor interface allows
-multiple backends to implement the functionality used by the Cyclotomic interface.
-Unless you are writing a new backend implementation, you shouldn't need to
-understand the Tensor interface. However, you *will* need an implementation of the
-Tensor interface in order to test, benchmark, and run applications.
+This package is primarily a library providing high-level interfaces
+for lattice cryptography primitives. There are two main collections of
+interfaces: 'Cyclotomic' and 'Tensor'. The Cyclotomic interface can be
+used to build cryptographic primitives like encryption, pseudorandom
+functions, etc. The lower-level Tensor interface allows multiple
+backends to implement the functionality used by the Cyclotomic
+interface.  Unless you are writing a new backend implementation, you
+do not need to understand the Tensor interface. However, you *will*
+need an implementation of the Tensor interface in order to test,
+benchmark, and run applications.
 
 Most of the functionality in Lol is exported by two modules:
 
-* 'Crypto.Lol' exports the primary *interfaces* of Lol
+* 'Crypto.Lol' exports the primary *interfaces* of Lol.
 
-* 'Crypto.Lol.Types' exports concrete types that would be used by most
-  instantiations.
+* 'Crypto.Lol.Types' exports concrete types that would tend to be used
+  by most instantiations.
 
-For a brief introduction to relevant mathematical notation, see 'Crypto.Lol'.
+For a brief introduction to the relevant mathematical notation, see
+'Crypto.Lol'.
 
 Overview of key modules, roughly from highest- to lowest-level:
 
 Cyclotomic layer:
-* 'Crypto.Lol.Cyclotomic.Cyc', which defines an interface for using cyclotomic
-  fields, rings \( R \), and quotient rings \( R_q=R/qR \); as well as many
-  other commonly used operations, e.g., converting
-  between rings, decoding and decomposing elements, modulus
-  reduction/rounding, etc. 'Cyc' is a safe wrapper around the
-  'UCyc' type, which exposes some representation-dependent operations.
-  'UCyc' (and hence 'Cyc') is implemented using a generic 'Tensor'
-  (described below).
 
+* 'Crypto.Lol.Cyclotomic.Cyc' defines an interface for using
+  cyclotomic fields \( K \), rings \( R \), and quotient rings \(
+  R_q=R/qR \); as well as many other commonly used operations, e.g.,
+  converting between rings; reducing, lifting, and decomposing
+  elements; modulus reduction/rounding; etc. 'Cyc' is a safe wrapper
+  around the 'CycRep' type, which exposes some
+  representation-dependent operations.  'CycRep' (and hence 'Cyc') is
+  implemented using a generic 'Tensor' (described below).
 
 Tensor layer:
-* 'Crypto.Lol.Cyclotomic.Tensor', which defines a class that encapsulates all
-  the necessary linear transformations for operating on representations of
-  \( R \)- and \( R_q \)-elements, e.g., the CRT transform, converting between
-  the powerful and decoding bases, generating error terms, etc.
 
-* You will need an implementation of the 'Tensor' interface in order to use Lol.
-  Two implementations can be found at
+* 'Crypto.Lol.Cyclotomic.Tensor' defines interfaces that encapsulate
+  all the necessary linear transformations for operating on
+  representations of \( R \)- and \( R_q \)-elements, e.g., the CRT
+  transform, converting between the powerful and decoding bases,
+  generating error terms, etc.
+
+* You will need an implementation of the 'Tensor' interface in order
+  to use Lol. The main up-to-date implementation is
   <https://hackage.haskell.org/package/lol-cpp lol-cpp>
-  and <https://hackage.haskell.org/package/lol-repa lol-repa>.
+  (<https://hackage.haskell.org/package/lol-repa lol-repa> is out of
+  date).
 
+Base-ring layer:
 
-Base ring layer:
-* 'Crypto.Lol.Types.FiniteField', which gives an unoptimized implementation of
-  finite field arithmetic. To use this module, you will need an instance of
-  'IrreduciblePoly'. These instances provide irreducible polynomials
-  for various degrees and base fields.  One (orphan) instance is provided for
-  characteristic 2 fields of size up to 2^128 in
-  'Crypto.Lol.Types.IrreducibleChar2', and is exported by 'Crypto.Lol.Types'.
-  If you need to use an unsupported finite field,  define your own
-  instance of 'IrreduciblePoly' and do **not** import 'IrreducibleChar2'.
+* 'Crypto.Lol.Types.FiniteField' gives an unoptimized implementation
+  of finite-field arithmetic. To use this module, you will need an
+  instance of 'IrreduciblePoly', which provides irreducible
+  polynomials for various degrees and base fields. One (orphan)
+  instance is provided for characteristic-2 fields of size up to 2^128
+  in 'Crypto.Lol.Types.IrreducibleChar2', and is exported by
+  'Crypto.Lol.Types'.  If you need to use an unsupported finite field,
+  define your own instance of 'IrreduciblePoly' and do **not** import
+  'IrreducibleChar2'.
 
-* 'Crypto.Lol.Types.Unsafe.ZqBasic', which is a basic implementation of
-  \( \Z_q=\Z/q\Z \) arithmetic.
+* 'Crypto.Lol.Types.Unsafe.ZqBasic', which is a basic implementation
+  of \( \Z_q=\Z/q\Z \) arithmetic.
 
 * 'Crypto.Lol.Factored', which contains type-level support code for
-  factored integers. It also supports "reifying" 'Int's at runtime as static
-  types and "reflecting" those types as integers back to the code..
-  'Factored' types are mainly used to represent cyclotomic indices.
+  factored integers. It also supports "reifying" 'Int's at runtime as
+  static types and "reflecting" those types as integer
+  values. 'Factored' types are mainly used to represent cyclotomic
+  indices.
 
-Tests and benchmarks can be found in the packages <https://hackage.haskell.org/package/lol-tests lol-tests> and <https://hackage.haskell.org/package/lol-benches lol-benches>,
-respectively, though they are instantiated in individual tensors.
+A collection of polymorphic tests and benchmarks can be found in the
+packages <https://hackage.haskell.org/package/lol-tests lol-tests> and
+<https://hackage.haskell.org/package/lol-benches lol-benches>,
+respectively. These tests should be (and are) instantiated for
+specific 'Tensor' backends by the corresponding tensor packages.
diff --git a/RLWE.proto b/RLWE.proto
--- a/RLWE.proto
+++ b/RLWE.proto
@@ -1,44 +1,46 @@
+package crypto.proto.RLWE;
+
 // proto messages for the RLWE/RLWR problems
 
 import "Lol.proto";
 
 // Proto messages for RLWE/RLWR samples
 
-// run this:
+// run this: hprotoc RLWE.proto
 
-// hprotoc -a Lol.proto=Crypto.Proto -p Crypto.Proto RLWE.proto
+// protoc RLWE.proto [-cpp_out=path/to/cpp/parser] [--java_out=path/to/java/parser] [--python_out=path/to/python/parser]
 
 // the Sample*1 messages were used to serialize RLWE/RLWR samples in the
 // RLWE/RLWR challenges, and only support cyclotomic rings mod a single modulus
-message SampleCont1 {
-  required Rq1 a      = 1;
-  required Kq1 b      = 2;
+message SampleCont {
+  required crypto.proto.lol.Rq a      = 1;
+  required crypto.proto.lol.Kq b      = 2;
 }
 
-message SampleDisc1 {
-  required Rq1 a      = 1;
-  required Rq1 b      = 2;
+message SampleDisc {
+  required crypto.proto.lol.Rq a      = 1;
+  required crypto.proto.lol.Rq b      = 2;
 }
 
-message SampleRLWR1 {
-  required Rq1 a      = 1;
-  required Rq1 b      = 2;  // for some modulus p < q
+message SampleRLWR {
+  required crypto.proto.lol.Rq a      = 1;
+  required crypto.proto.lol.Rq b      = 2;  // for some modulus p < q
 }
 
 // continuous RLWE sample, possibly with mutliple moduli
-message SampleCont {
-  required RqProduct a = 1;
-  required KqProduct b = 2;
+message SampleContProduct {
+  required crypto.proto.lol.RqProduct a = 1;
+  required crypto.proto.lol.KqProduct b = 2;
 }
 
 // discrete RLWE sample, possibly with multiple moduli
-message SampleDisc {
-  required RqProduct a = 1;
-  required RqProduct b = 2;
+message SampleDiscProduct {
+  required crypto.proto.lol.RqProduct a = 1;
+  required crypto.proto.lol.RqProduct b = 2;
 }
 
 // RLWR sample, possibly with multiple moduli
-message SampleRLWR {
-  required RqProduct a = 1;
-  required RqProduct b = 2;  // for some modulus p < q
+message SampleRLWRProduct {
+  required crypto.proto.lol.RqProduct a = 1;
+  required crypto.proto.lol.RqProduct b = 2;  // for some modulus p < q
 }
diff --git a/lol.cabal b/lol.cabal
--- a/lol.cabal
+++ b/lol.cabal
@@ -1,137 +1,158 @@
-name:                lol
--- The package version.  See the Haskell package versioning policy (PVP)
--- for standards guiding when and how versions should be incremented.
--- http://www.haskell.org/haskellwiki/Package_versioning_policy
--- PVP summary:      +-+------- breaking API changes
---                   | | +----- non-breaking API additions
---                   | | | +--- code changes with no API change
-version:             0.6.0.0
-synopsis:            A library for lattice cryptography.
-homepage:            https://github.com/cpeikert/Lol
-Bug-Reports:         https://github.com/cpeikert/Lol/issues
-license:             GPL-2
-license-file:        LICENSE
-author:              Eric Crockett <ecrockett0@gmail.com>, Chris Peikert <cpeikert@alum.mit.edu>
-maintainer:          Eric Crockett <ecrockett0@gmail.com>
-copyright:           Eric Crockett, Chris Peikert
-category:            Crypto
-stability:           experimental
-build-type:          Simple
-extra-source-files:  README, CHANGES.md, Lol.proto, RLWE.proto
-cabal-version:       >= 1.10
-description:
-    Λ ∘ λ (Lol) is a general-purpose library for ring-based lattice cryptography.
-    For a detailed description of interfaces and functionality, see
-    <https://eprint.iacr.org/2015/1134 Λ ∘ λ: Functional Lattice Cryptography>.
-    Backends for the library include <https://hackage.haskell.org/package/lol-cpp lol-cpp>
-    and <https://hackage.haskell.org/package/lol-repa lol-repa>.
-    For example cryptographic applications, see <https://hackage.haskell.org/package/lol-apps lol-apps>.
+cabal-version: 1.12
 
+-- This file has been generated from package.yaml by hpack version 0.31.2.
+--
+-- see: https://github.com/sol/hpack
+--
+-- hash: 37ba6dd1789e989016b1defa6b3a75ece53b8fd687960365d1a3e3ad133e2732
+
+name:           lol
+version:        0.7.0.0
+synopsis:       A library for lattice cryptography.
+description:    Λ ⚬ λ (Lol) is a general-purpose library for ring-based lattice cryptography.  For a detailed description of interfaces and functionality, see <https://eprint.iacr.org/2015/1134 Λ ⚬ λ: Functional Lattice Cryptography>. The main backend for the library is <https://hackage.haskell.org/package/lol-cpp lol-cpp> (<https://hackage.haskell.org/package/lol-repa lol-repa> is currently out of date). For example cryptographic applications, see <https://hackage.haskell.org/package/lol-apps lol-apps>.
+category:       Crypto
+stability:      experimental
+homepage:       https://github.com/cpeikert/lol#readme
+bug-reports:    https://github.com/cpeikert/lol/issues
+author:         Eric Crockett <ecrockett0@gmail.com>,
+                Chris Peikert <cpeikert@alum.mit.edu>
+maintainer:     Eric Crockett <ecrockett@gmail.com>,
+                Chad Sharp <cmlsharp@umich.edu>
+copyright:      Eric Crockett,
+                Chris Peikert
+license:        GPL-3
+license-file:   LICENSE
+build-type:     Simple
+extra-source-files:
+    README
+    CHANGES.md
+    Lol.proto
+    RLWE.proto
+
 source-repository head
   type: git
-  location: https://github.com/cpeikert/Lol
-
--- For information on compiling C with cabal: http://blog.ezyang.com/2010/06/setting-up-cabal-the-ffi-and-c2hs/
+  location: https://github.com/cpeikert/lol
 
-Flag llvm
-  Description:  Compile via LLVM. This produces much better object code,
-                but you need to have the LLVM compiler installed.
-  -- If you enable this and get errors like "Error: can't resolve `.rodata' {.rodata section}"
-  -- then GHC doesn't like your version of LLVM!
-  Default:      False
+flag llvm
+  description: Compile via LLVM. This produces much better object code, but you need to have the LLVM compiler installed.
+  manual: False
+  default: False
 
-Flag opt
-  Description: Turn on library optimizations
-  Default:     True
+flag opt
+  description: Turn on library optimizations
+  manual: False
+  default: True
 
 library
-  default-language:   Haskell2010
-  ghc-options: -fwarn-dodgy-imports
-
-  if flag(llvm)
-    ghc-options: -fllvm -optlo-O3
-
-  -- ghc optimizations
-  if flag(opt)
-    -- makes lift much faster!
-    ghc-options: -funfolding-use-threshold1000
   exposed-modules:
-    Crypto.Lol
-    Crypto.Lol.Types
-    Crypto.Lol.Factored
-    Crypto.Lol.Reflects
-    Crypto.Lol.CRTrans
-    Crypto.Lol.Gadget
-    Crypto.Lol.Prelude
-
-    Crypto.Lol.Cyclotomic.Cyc
-    Crypto.Lol.Cyclotomic.UCyc
-    Crypto.Lol.Cyclotomic.RescaleCyc
-    Crypto.Lol.Cyclotomic.Linear
-
-    Crypto.Lol.RLWE.Continuous
-    Crypto.Lol.RLWE.Discrete
-    Crypto.Lol.RLWE.RLWR
-
-    Crypto.Lol.Cyclotomic.Tensor
-    Crypto.Lol.GaussRandom
-    Crypto.Lol.Types.Unsafe.Complex
-    Crypto.Lol.Types.FiniteField
-    Crypto.Lol.Types.IrreducibleChar2
-    Crypto.Lol.Types.IZipVector
-    Crypto.Lol.Types.Proto
-    Crypto.Lol.Types.Random
-    Crypto.Lol.Types.Unsafe.RRq
-    Crypto.Lol.Types.ZmStar
-    Crypto.Lol.Types.ZPP
-    Crypto.Lol.Types.Unsafe.ZqBasic
-
-    Crypto.Proto.Lol
-    Crypto.Proto.Lol.LinearRq
-    Crypto.Proto.Lol.R
-    Crypto.Proto.Lol.Rq1
-    Crypto.Proto.Lol.RqProduct
-    Crypto.Proto.Lol.Kq1
-    Crypto.Proto.Lol.KqProduct
-    Crypto.Proto.Lol.TypeRep
-    Crypto.Proto.RLWE
-    Crypto.Proto.RLWE.SampleCont
-    Crypto.Proto.RLWE.SampleDisc
-    Crypto.Proto.RLWE.SampleRLWR
-    Crypto.Proto.RLWE.SampleCont1
-    Crypto.Proto.RLWE.SampleDisc1
-    Crypto.Proto.RLWE.SampleRLWR1
-
-    Crypto.Lol.Utils.GenArgs
-    Crypto.Lol.Utils.ShowType
-
+      Crypto.Lol
+      Crypto.Lol.Types
+      Crypto.Lol.Factored
+      Crypto.Lol.Reflects
+      Crypto.Lol.CRTrans
+      Crypto.Lol.Gadget
+      Crypto.Lol.Prelude
+      Crypto.Lol.Cyclotomic.Cyc
+      Crypto.Lol.Cyclotomic.CycRep
+      Crypto.Lol.Cyclotomic.Language
+      Crypto.Lol.Cyclotomic.Linear
+      Crypto.Lol.RLWE.Continuous
+      Crypto.Lol.RLWE.Discrete
+      Crypto.Lol.RLWE.RLWR
+      Crypto.Lol.Cyclotomic.Tensor
+      Crypto.Lol.GaussRandom
+      Crypto.Lol.Types.Unsafe.Complex
+      Crypto.Lol.Types.FiniteField
+      Crypto.Lol.Types.IrreducibleChar2
+      Crypto.Lol.Types.IFunctor
+      Crypto.Lol.Types.IZipVector
+      Crypto.Lol.Types.Proto
+      Crypto.Lol.Types.Random
+      Crypto.Lol.Types.Unsafe.RRq
+      Crypto.Lol.Types.ZmStar
+      Crypto.Lol.Types.Unsafe.ZqBasic
+      Crypto.Proto.Lol
+      Crypto.Proto.Lol.LinearRq
+      Crypto.Proto.Lol.R
+      Crypto.Proto.Lol.Rq
+      Crypto.Proto.Lol.RqProduct
+      Crypto.Proto.Lol.K
+      Crypto.Proto.Lol.Kq
+      Crypto.Proto.Lol.KqProduct
+      Crypto.Proto.Lol.TypeRep
+      Crypto.Proto.RLWE
+      Crypto.Proto.RLWE.SampleContProduct
+      Crypto.Proto.RLWE.SampleDiscProduct
+      Crypto.Proto.RLWE.SampleRLWRProduct
+      Crypto.Proto.RLWE.SampleCont
+      Crypto.Proto.RLWE.SampleDisc
+      Crypto.Proto.RLWE.SampleRLWR
+      Crypto.Lol.Utils.ShowType
+      Crypto.Lol.Tests
+      Crypto.Lol.Benchmarks
   other-modules:
-    Crypto.Lol.Cyclotomic.CRTSentinel
-    Crypto.Lol.FactoredDefs
-    Crypto.Lol.Types.Numeric
-    Crypto.Lol.PosBin
-    Crypto.Lol.PosBinDefs
+      Crypto.Lol.Cyclotomic.CRTSentinel
+      Crypto.Lol.FactoredDefs
+      Crypto.Lol.Types.Numeric
+      Crypto.Lol.PosBin
+      Crypto.Lol.PosBinDefs
+      Crypto.Lol.Utils.Tests
+      Crypto.Lol.Utils.Benchmarks
+      Crypto.Lol.Utils.PrettyPrint
+      Crypto.Lol.Utils.PrettyPrint.Diagnostic
+      Crypto.Lol.Utils.PrettyPrint.Table
+      Crypto.Lol.Tests.CycTests
+      Crypto.Lol.Tests.Default
+      Crypto.Lol.Tests.TensorTests
+      Crypto.Lol.Tests.ZqTests
+      Crypto.Lol.Benchmarks.CycBenches
+      Crypto.Lol.Benchmarks.Default
+      Crypto.Lol.Benchmarks.TensorBenches
+      Crypto.Lol.Benchmarks.CycRepBenches
+  build-depends:
+      MonadRandom >=0.5.1 && <0.6
+    , QuickCheck >=2.13.2 && <2.14
+    , ansi-terminal >=0.9.1 && <0.10.0
+    , arithmoi >=0.9.0 && <0.10
+    , base >=4.12.0 && <4.13
+    , bytestring >=0.10.8 && <0.11
+    , constraints >=0.10.1 && <0.11.0
+    , containers >=0.6.0 && <0.7
+    , criterion >=1.5.6 && <1.6
+    , criterion-measurement >=0.1.2 && <0.2
+    , crypto-api >=0.13.3 && <0.14
+    , data-default >=0.7.1 && <0.8
+    , deepseq >=1.4.4 && <1.5
+    , directory >=1.3.3 && <1.4
+    , monadcryptorandom >=0.7.2 && <0.8
+    , mtl >=2.2.2 && <2.3
+    , numeric-prelude >=0.4.3 && <0.5
+    , protocol-buffers >=2.4.12 && <2.5
+    , protocol-buffers-descriptor >=2.4.12 && <2.5
+    , random >=1.1 && <1.2
+    , reflection >=2.1.5 && <2.2
+    , singletons >=2.5.1 && <2.6
+    , statistics >=0.15.1 && <0.16
+    , tagged-transformer >=0.8.1 && <0.9
+    , template-haskell >=2.14.0 && <2.15
+    , test-framework >=0.8.2 && <0.9
+    , test-framework-quickcheck2 >=0.3.0 && <0.4
+    , vector >=0.12.0 && <0.13
+    , vector-th-unbox >=0.2.1 && <0.3
+  if flag(llvm)
+    ghc-options: -fllvm -optlo-O3 -pgmlo opt
+  default-language: Haskell2010
 
+test-suite test-lol
+  type: exitcode-stdio-1.0
+  main-is: LolTestsMain.hs
+  other-modules:
+      Paths_lol
+  hs-source-dirs:
+      tests
+  ghc-options: -main-is LolTestsMain
   build-depends:
-    arithmoi >= 0.4.1.3,
-    base >= 4.9 && < 5,
-    bytestring,
-    constraints,
-    containers >= 0.5.6.2,
-    crypto-api,
-    data-default >= 0.3.0,
-    deepseq >= 1.4.1.1,
-    directory,
-    monadcryptorandom,
-    MonadRandom >= 0.2,
-    mtl >= 2.2.1,
-    numeric-prelude >= 0.4.2,
-    protocol-buffers,
-    protocol-buffers-descriptor,
-    random >= 1.1,
-    reflection >= 1.5.1,
-    singletons >= 1.1.2.1,
-    tagged-transformer >= 0.7,
-    template-haskell >=  2.2.0.0,
-    vector >=0.11,
-    vector-th-unbox >= 0.2.1.0
+      base
+    , lol
+    , test-framework
+  default-language: Haskell2010
diff --git a/tests/LolTestsMain.hs b/tests/LolTestsMain.hs
new file mode 100644
--- /dev/null
+++ b/tests/LolTestsMain.hs
@@ -0,0 +1,21 @@
+{-|
+Module      : LolTestsMain
+Description : Main driver for Lol tests.
+Copyright   : (c) Eric Crockett, 2011-2017
+                  Chris Peikert, 2011-2017
+License     : GPL-3
+Maintainer  : ecrockett0@email.com
+Stability   : experimental
+Portability : POSIX
+
+Main driver for Lol tests.
+-}
+
+module LolTestsMain where
+
+import Crypto.Lol.Tests
+import Test.Framework
+
+main :: IO ()
+main = defaultMainWithArgs
+  [defaultZqTests] ["--threads=1","--maximum-generated-tests=20"]
