diff --git a/Biobase/Types/Accession.hs b/Biobase/Types/Accession.hs
new file mode 100644
--- /dev/null
+++ b/Biobase/Types/Accession.hs
@@ -0,0 +1,128 @@
+
+-- | Accession numbers. These /numbers/ are not really numbers because they
+-- they are made up of alphanumeric characters.
+
+module Biobase.Types.Accession where
+
+import Control.DeepSeq
+import Data.Aeson
+import Data.Binary
+import Data.Char (isLetter)
+import Data.Hashable (Hashable)
+import Data.Ix (Ix)
+import Data.Serialize
+import Data.Serialize.Text
+import Data.String
+import Data.String.Conversions (ConvertibleStrings(..), cs)
+import Data.String.Conversions.Monomorphic (toST, fromST)
+import Data.Text.Binary
+import Data.Text (Text, span, length)
+import GHC.Generics (Generic)
+import Prelude hiding (length,span)
+
+
+
+-- * 'Accession' with phantom types.
+--
+-- <http://www.ncbi.nlm.nih.gov/Sequin/acc.html>
+--
+-- <http://www.uniprot.org/help/accession_numbers>
+--
+-- <http://en.wikipedia.org/wiki/Accession_number_%28bioinformatics%29>
+
+-- | The accession number is a unique identifier in bioinformatics.
+--
+-- Depending on the source, accession numbers follow different alphanumeric
+-- formats! While letters-than-numbers is quite common, swissprot uses
+-- a mix. Hence, we just use a text string as accession.
+--
+-- A phantom type is provided to enable type safety annotations. Helper
+-- functions provide smart construction from the @Accession@ tagged generic
+-- type.
+
+newtype Accession t = Accession { _getAccession :: Text }
+  deriving (Eq,Ord,Read,Show,Generic)
+
+-- | Generate an accession with an explicit phantom type: @accession'
+-- Nucleotide "Bla"@ has type @:: Accession Nucleotide@.
+
+accession' :: ConvertibleStrings s Text => t -> s -> Accession t
+accession' t = Accession . toST
+
+-- | Generate an accession when the type @Accession t@ is clear from the
+-- context.
+
+accession :: ConvertibleStrings s Text => s -> Accession t
+accession = Accession . toST
+{-# Inline accession #-}
+
+-- | Retag an accession
+
+retagAccession :: Accession f -> Accession t
+retagAccession = Accession . _getAccession
+{-# Inline retagAccession #-}
+
+instance IsString (Accession t) where
+  fromString = accession
+  {-# Inline fromString #-}
+
+instance Binary    (Accession t)
+instance FromJSON  (Accession t)
+instance Hashable  (Accession t)
+instance Serialize (Accession t)
+instance ToJSON    (Accession t)
+instance NFData    (Accession t)
+
+
+
+-- * Phantom types. All with an excliti data constructor to guide
+-- 'accession''.
+
+-- ** NCBI phantom types
+
+-- | nucleotide sequence
+
+data Nucleotide = Nucleotide
+
+-- | protein sequence
+
+data Protein = Protein
+
+-- ** Rfam phantom types
+--
+-- The format is RFxxxxx, PFxxxxx, or CLxxxxx.
+
+-- | Tag as being a clan.
+
+data Clan = Clan
+
+-- | Tag as being a Pfam model.
+
+data Pfam = Pfam
+
+-- | Tag as being an Rfam model. Used for Stockholm and CM files.
+
+data Rfam = Rfam
+
+-- | Species have an accession number, too.
+
+data Species = Species
+
+
+
+-- * Helper functions
+
+-- | Guess the type of accession number. Returns @Nothing@ if unknown
+-- structure.
+
+guessAccessionType :: Accession t -> Maybe Text
+guessAccessionType (Accession a) = case (length l, length d) of
+  (1,5)                   -> Just "Nucleotide"
+  (2,6)                   -> Just "Nucleotide"
+  (3,5)                   -> Just "Protein"
+  (3,k) | 8<= k && k<= 10 -> Just "WGS"
+  (5,7)                   -> Just "MGA"
+  _                       -> Nothing
+  where (l,d) = span isLetter a
+
+
diff --git a/Biobase/Types/BioSequence.hs b/Biobase/Types/BioSequence.hs
new file mode 100644
--- /dev/null
+++ b/Biobase/Types/BioSequence.hs
@@ -0,0 +1,409 @@
+
+-- | Abstraction over bio sequences encoded as one-ascii character as one
+-- symbol. We phantom-type the exact bio-sequence type and provide type classes
+-- that act on known types.
+--
+-- Unknown bio sequences should be tagged with @Void@.
+--
+-- TODO give (lens) usage examples
+
+module Biobase.Types.BioSequence where
+
+import           Control.DeepSeq
+import           Control.Lens
+import           Data.ByteString.Char8 (ByteString)
+import           Data.Char (ord,chr,toUpper)
+import           Data.Data (Data)
+import           Data.Hashable
+import           Data.Typeable (Typeable)
+import           Data.Void
+import           GHC.Exts (IsString(..))
+import           GHC.Generics (Generic)
+import qualified Data.ByteString.Char8 as BS
+import qualified Data.ByteString.UTF8 as BSU
+import qualified Streaming.Prelude as SP
+import qualified Streaming as S
+import qualified Streaming.Internal as SI
+import qualified Test.QuickCheck as TQ
+import           Test.QuickCheck (Arbitrary(..))
+import Data.Coerce
+import Debug.Trace
+
+import Biobase.Types.Strand
+import qualified Biobase.Types.Index as BTI
+import Data.Info
+
+
+
+-- * Lens operations on biosequences
+
+{-
+class BioSeqLenses b where
+  -- | Lens into the first @k@ characters.
+  bsTake :: Int -> Lens' b b
+  -- | Lens into the last @k@ characters
+  bsTakeEnd :: Int -> Lens' b b
+  -- | Lens into all but the first @k@ characters
+  bsDrop :: Int -> Lens' b b
+  -- | Lens into all but the last @k@ characters
+  bsDropEnd :: Int -> Lens' b b
+  -- | Lens that splits at a position
+  bsSplitAt :: Int -> Lens' b (b,b)
+  -- | length of this biosequence
+  bsLength :: Getter b Int
+-}
+
+-- * Sequence identifiers
+
+newtype SequenceIdentifier (which :: k) = SequenceIdentifier { _sequenceIdentifier :: ByteString }
+  deriving stock (Data, Typeable, Generic, Eq, Ord, Read, Show)
+makeWrapped ''SequenceIdentifier
+makePrisms ''SequenceIdentifier
+
+instance NFData (SequenceIdentifier w)
+
+instance IsString (SequenceIdentifier w) where
+  fromString = SequenceIdentifier . BSU.fromString
+
+
+
+-- * Bio-Sequences
+
+data RNA
+
+data DNA
+
+data XNA
+
+data AA
+
+
+
+-- |
+-- TODO provide extended annotation information on biosequences, too!
+
+newtype BioSequence (which :: k) = BioSequence {_bioSequence :: ByteString}
+  deriving stock (Data, Typeable, Generic, Eq, Ord, Read, Show)
+  deriving newtype (Semigroup)
+makeWrapped ''BioSequence
+makePrisms ''BioSequence
+makeLenses ''BioSequence
+
+instance Hashable (BioSequence (which :: k))
+
+instance NFData (BioSequence w)
+
+type instance Index (BioSequence w) = Int
+
+type instance IxValue (BioSequence w) = Char
+
+instance Ixed (BioSequence w) where
+  ix k = _BioSequence . ix k . iso (chr . fromIntegral) (fromIntegral . ord)
+  {-# Inline ix #-}
+
+deriving newtype instance Reversing (BioSequence w)
+
+instance IsString (BioSequence Void) where
+  fromString = BioSequence . BS.pack
+
+instance Info (BioSequence w) where
+  info (BioSequence s)
+    | BS.length s <= 18 = BS.unpack s
+    | otherwise         = BS.unpack h ++ ".." ++ BS.unpack l
+    where (h,tl) = BS.splitAt 9 s
+          (_,l ) = BS.splitAt (BS.length tl-9) tl
+
+{-
+instance BioSeqLenses (BioSequence w) where
+  {-# Inline bsTake #-}
+  bsTake k = lens (over _BioSequence (BS.take k)) (\old new -> new <> over _BioSequence (BS.drop k) old)
+  {-# Inline bsTakeEnd #-}
+  bsTakeEnd k = lens (over _BioSequence (\s -> BS.drop (BS.length s -k) s)) (\old new -> over _BioSequence (\s -> BS.take (BS.length s-k) s) old <> new)
+  {-# Inline bsLength #-}
+  bsLength = _BioSequence.to BS.length
+  {-# Inline bsDrop #-}
+  bsDrop k = lens (over _BioSequence (BS.drop k)) (\old new -> over _BioSequence (BS.take k) old <> new)
+  {-# Inline bsDropEnd #-}
+  bsDropEnd k = lens (over _BioSequence (\s -> BS.take (BS.length s -k) s)) (\old new -> over _BioSequence (\s -> BS.take (BS.length s-k) s) old <> new)
+  {-# Inline bsSplitAt #-}
+  bsSplitAt k = lens (\b -> (view (bsTake k) b, view (bsDrop k) b)) (\old (h,t) -> h <> t)
+-}
+
+
+
+-- * RNA
+
+-- |
+--
+-- TODO write that converts explicitly
+
+mkRNAseq :: ByteString -> BioSequence RNA
+mkRNAseq = BioSequence . BS.map go . BS.map toUpper
+  where go x | x `elem` acgu = x
+             | otherwise     = 'N'
+        acgu :: String
+        acgu = "ACGU"
+
+instance IsString (BioSequence RNA) where
+  fromString = mkRNAseq . BS.pack
+
+instance Arbitrary (BioSequence RNA) where
+  arbitrary = do
+    k ← TQ.choose (0,30)
+    xs ← TQ.vectorOf k $ TQ.elements "ACGU"
+    return . BioSequence $ BS.pack xs
+  shrink = shrinkBioSequence
+
+shrinkBioSequence (BioSequence b) = fmap BioSequence
+  [ let (l,BS.drop 1 -> r) = BS.splitAt k b
+    in BS.append l r | k <- [0 .. BS.length b -1] ]
+
+
+-- * DNA
+
+mkDNAseq :: ByteString -> (BioSequence DNA)
+mkDNAseq = BioSequence . BS.map go . BS.map toUpper
+  where go x | x `elem` acgt = x
+             | otherwise     = 'N'
+        acgt :: String
+        acgt = "ACGT"
+
+instance IsString (BioSequence DNA) where
+  fromString = mkDNAseq . BS.pack
+
+instance Arbitrary (BioSequence DNA) where
+  arbitrary = do
+    k ← TQ.choose (0,100)
+    xs ← TQ.vectorOf k $ TQ.elements "ACGT"
+    return . BioSequence $ BS.pack xs
+  shrink = view (to shrink)
+
+
+
+-- * XNA
+
+mkXNAseq :: ByteString -> (BioSequence XNA)
+mkXNAseq = BioSequence . BS.map go . BS.map toUpper
+  where go x | x `elem` acgtu = x
+             | otherwise      = 'N'
+        acgtu :: String
+        acgtu = "ACGTU"
+
+instance IsString (BioSequence XNA) where
+  fromString = mkXNAseq . BS.pack
+
+instance Arbitrary (BioSequence XNA) where
+  arbitrary = do
+    k ← TQ.choose (0,100)
+    xs ← TQ.vectorOf k $ TQ.elements "ACGTU"
+    return . BioSequence $ BS.pack xs
+  shrink = view (to shrink)
+
+
+
+-- * Amino acid sequences
+
+mkAAseq :: ByteString -> (BioSequence AA)
+mkAAseq = BioSequence . BS.map go . BS.map toUpper
+  where go x | x `elem` aas = x
+             | otherwise    = 'X'
+        aas :: String
+        aas = "ARNDCEQGHILKMFPSTWYVUO"
+
+instance IsString (BioSequence AA) where
+  fromString = mkAAseq . BS.pack
+
+instance Arbitrary (BioSequence AA) where
+  arbitrary = do
+    k ← TQ.choose (0,100)
+    xs ← TQ.vectorOf k $ TQ.elements "ARNDCEQGHILKMFPSTWYVUO"
+    return . BioSequence $ BS.pack xs
+  shrink = view (to shrink)
+
+
+
+{-
+
+-- * A window into a longer sequence with prefix/suffix information.
+
+-- | Phantom-typed over two types, the type @w@ of the identifier, which can be
+-- descriptive ("FirstInput") and the second type, identifying what kind of
+-- sequence types we are dealing with. Finally, the third type provides
+-- location information and should be location or streamed location.
+
+data BioSequenceWindow w ty loc = BioSequenceWindow
+  { _bswIdentifier    :: !(SequenceIdentifier w)
+    -- ^ Identifier for this window. Typically some fasta identifier
+  , _bswPrefix        :: !(BioSequence ty)
+  , _bswInfix         :: !(BioSequence ty)
+  , _bswSuffix        :: !(BioSequence ty)
+  , _bswInfixLocation :: !loc
+    -- ^ Location of the infix sequence
+  }
+  deriving (Data, Typeable, Generic, Eq, Ord, Read, Show)
+makeLenses ''BioSequenceWindow
+
+-- | Lens into the full sequence. May not change the sequence length
+
+bswSequence :: Lens (BioSequenceWindow w ty loc) (BioSequenceWindow w ty' loc) (BioSequence ty) (BioSequence ty')
+{-# Inlinable bswSequence #-}
+bswSequence = lens (\w -> _bswPrefix w <> _bswInfix w <> _bswSuffix w)
+                   (\w bs -> let (p,is) = bs^.bsSplitAt (w^.bswPrefix.bsLength)
+                                 (i,s ) = is^.bsSplitAt (w^.bswInfix.bsLength)
+                             in w { _bswPrefix = p, _bswInfix = i, _bswSuffix = s } )
+
+-- | Get the position of the whole sequence
+
+bswLocation :: ModifyLocation loc => Getter (BioSequenceWindow w ty loc) loc
+{-# Inlinable bswLocation #-}
+bswLocation = to $ \w -> locMoveLeftEnd (w^.bswPrefix.bsLength.to negate)
+                 . locMoveRightEnd (w^.bswSuffix.bsLength) $ w^.bswInfixLocation
+
+bswRetagW :: BioSequenceWindow w ty loc -> BioSequenceWindow v ty loc
+{-# Inlinable bswRetagW #-}
+bswRetagW = over bswIdentifier coerce
+
+instance NFData loc => NFData (BioSequenceWindow w ty loc)
+
+instance (Reversing loc) => Reversing (BioSequenceWindow w ty loc) where
+  {-# Inlinable reversing #-}
+  reversing bsw = bsw
+                & bswPrefix .~ (bsw^.bswSuffix.reversed)
+                & bswSuffix .~ (bsw^.bswPrefix.reversed)
+                & bswInfix  .~ (bsw^.bswInfix.reversed)
+                & bswInfixLocation .~ (bsw^.bswInfixLocation.reversed)
+
+
+
+-- | Provides an informative string indicating the current window being worked on. Requires length
+-- of pretty string requested. Not for computers, but for logging what is being worked on. Should be
+-- one line at most, not produce line breaks.
+--
+-- @...PFX [Start] IFX...IFX [End] SFX ...@
+--
+-- TODO possibly be better as a @Doc@ for prettier printing.
+
+instance Info (BioSequenceWindow w ty loc) where
+  info bsw = "todo: info bsw"
+
+-}
+
+
+
+-- * DNA/RNA
+
+-- | Simple case translation from @U@ to @T@. with upper and lower-case
+-- awareness.
+
+rna2dna :: Char -> Char
+rna2dna = \case
+  'U' -> 'T'
+  'u' -> 't'
+  x   -> x
+{-# Inline rna2dna #-}
+
+-- | Single character RNA complement.
+
+rnaComplement :: Char -> Char
+rnaComplement = \case
+  'A' -> 'U'
+  'a' -> 'u'
+  'C' -> 'G'
+  'c' -> 'g'
+  'G' -> 'C'
+  'g' -> 'c'
+  'U' -> 'A'
+  'u' -> 'a'
+  x   -> x
+{-# Inline rnaComplement #-}
+
+-- | Simple case translation from @T@ to @U@ with upper- and lower-case
+-- awareness.
+
+dna2rna :: Char -> Char
+dna2rna = \case
+  'T' -> 'U'
+  't' -> 'u'
+  x   -> x
+{-# Inline dna2rna #-}
+
+-- | Single character DNA complement.
+
+dnaComplement :: Char -> Char
+dnaComplement = \case
+  'A' -> 'T'
+  'a' -> 't'
+  'C' -> 'G'
+  'c' -> 'g'
+  'G' -> 'C'
+  'g' -> 'c'
+  'T' -> 'A'
+  't' -> 'a'
+  x   -> x
+{-# Inline dnaComplement #-}
+
+
+
+-- | Transcribes a DNA sequence into an RNA sequence. Note that 'transcribe' is
+-- actually very generic. We just define its semantics to be that of
+-- biomolecular transcription.
+--
+-- 'transcribe' makes the assumption that, given @DNA -> RNA@, we transcribe
+-- the coding strand.
+-- <http://hyperphysics.phy-astr.gsu.edu/hbase/Organic/transcription.html>
+--
+-- @@ DNAseq "ACGT" ^. transcribe == RNAseq "ACGU" RNAseq "ACGU" ^. transcribe
+-- == DNAseq "ACGT" RNAseq "ACGU" ^. from transcribe :: DNAseq == DNAseq "ACGT"
+-- @@
+
+class Transcribe f where
+  type TranscribeTo f :: *
+  transcribe :: Iso' f (TranscribeTo f)
+
+-- | Transcribe a DNA sequence into an RNA sequence. This does not @reverse@
+-- the sequence!
+
+instance Transcribe (BioSequence DNA) where
+  type TranscribeTo (BioSequence DNA) = (BioSequence RNA)
+  transcribe = iso (over _BioSequence (BS.map dna2rna)) (over _BioSequence (BS.map rna2dna))
+  {-# Inline transcribe #-}
+
+-- | Transcribe a RNA sequence into an DNA sequence. This does not @reverse@
+-- the sequence!
+
+instance Transcribe (BioSequence RNA) where
+  type TranscribeTo (BioSequence RNA) = (BioSequence DNA)
+  transcribe = from transcribe
+  {-# Inline transcribe #-}
+
+
+
+-- | The complement of a biosequence.
+
+class Complement f where
+  complement :: Iso' f f
+
+instance Complement (BioSequence DNA) where
+  {-# Inline complement #-}
+  complement = let f = (over _BioSequence (BS.map dnaComplement))
+                   {-# Inline f #-}
+               in  iso f f
+
+instance Complement (BioSequence RNA) where
+  {-# Inline complement #-}
+  complement = let f = (over _BioSequence (BS.map rnaComplement))
+                   {-# Inline f #-}
+               in  iso f f
+
+{-
+instance (Complement (BioSequence ty)) => Complement (BioSequenceWindow w ty k) where
+  {-# Inline complement #-}
+  complement = let f = over bswPrefix (view complement) . over bswInfix (view complement) . over bswSuffix (view complement)
+                   {-# Inline f #-}
+               in  iso f f
+-}
+
+reverseComplement :: (Complement f, Reversing f) => Iso' f f
+{-# Inline reverseComplement #-}
+reverseComplement = reversed . complement
+
diff --git a/Biobase/Types/Bitscore.hs b/Biobase/Types/Bitscore.hs
new file mode 100644
--- /dev/null
+++ b/Biobase/Types/Bitscore.hs
@@ -0,0 +1,94 @@
+
+-- | Bit scores as used by different algorithms in bioinformatics,
+-- linguistics, and probably elsewhere.
+--
+-- Basically, the base-2 logarithm of the probability of the input given
+-- the model vs the probability of the input given the null model.
+--
+-- @
+-- S = log_2 (P(seq|model) / P(seq|null))
+-- @
+--
+
+module Biobase.Types.Bitscore where
+
+import           Control.DeepSeq
+import           Data.Aeson
+import           Data.Binary
+import           Data.Default
+import           Data.Hashable (Hashable)
+import           Data.Primitive.Types
+import           Data.Serialize
+import           Data.Vector.Unboxed.Base
+import           Data.Vector.Unboxed.Deriving
+import           GHC.Generics (Generic)
+import qualified Data.Vector.Generic as VG
+import qualified Data.Vector.Generic.Mutable as VGM
+import qualified Data.Vector.Unboxed as VU
+
+import           Algebra.Structure.Semiring
+import           Numeric.Limits
+
+
+
+-- | Bit score; behaves like a double (deriving Num). In particular, the
+-- algebraic operations behave as expected @Bitscore a + Bitscore b ==
+-- Bitscore (a+b)@.
+--
+-- Currently geared towards use as in @Infernal@ and @HMMER@.
+--
+-- Infernal users guide, p.42: log-odds score in log_2 (aka bits).
+
+newtype Bitscore = Bitscore { getBitscore :: Double }
+  deriving stock (Eq,Ord,Read,Show,Generic)
+  deriving newtype (Num,Fractional)
+
+instance Semiring Bitscore where
+  plus = (+)
+  times = (*)
+  zero = 0
+  one = 1
+  {-# Inline plus  #-}
+  {-# Inline times #-}
+  {-# Inline zero  #-}
+  {-# Inline one   #-}
+
+instance Binary    Bitscore
+instance FromJSON  Bitscore
+instance Hashable  Bitscore
+instance Serialize Bitscore
+instance ToJSON    Bitscore
+instance NFData    Bitscore
+
+deriving newtype instance NumericLimits Bitscore
+
+derivingUnbox "Bitscore"
+  [t| Bitscore -> Double |] [| getBitscore |] [| Bitscore |]
+
+-- | A default bitscore of "-infinity", but with @10-1@ wiggle room.
+--
+-- TODO Check out the different "defaults" Infernal uses
+
+instance Default Bitscore where
+  def = Bitscore minFinite / 100
+  {-# Inline def #-}
+
+-- | Given a null model and a probability, calculate the corresponding
+-- 'BitScore'.
+--
+-- TODO @x<=epsilon@ ?
+
+prob2Score :: Double -> Double -> Bitscore
+prob2Score null x
+  | x==0      = minFinite / 100
+  | otherwise = Bitscore $ log (x/null) / log 2
+{-# Inline prob2Score #-}
+
+-- | Given a null model and a 'BitScore' return the corresponding probability.
+
+score2Prob :: Double -> Bitscore -> Double
+score2Prob null (Bitscore x)
+  | x <= minFinite / 100 = 0
+  | otherwise     = null * exp (x * log 2)
+{-# Inline score2Prob #-}
+
diff --git a/Biobase/Types/Codon.hs b/Biobase/Types/Codon.hs
new file mode 100644
--- /dev/null
+++ b/Biobase/Types/Codon.hs
@@ -0,0 +1,20 @@
+
+module Biobase.Types.Codon where
+
+import Control.Lens
+import GHC.Generics (Generic)
+
+
+
+-- | A single codon.
+--
+-- TODO needs to go into its own place
+
+data Codon c = Codon !c !c !c
+  deriving (Eq,Ord,Read,Show,Generic,Functor,Foldable,Traversable)
+
+instance Field1 (Codon c) (Codon c) c c
+instance Field2 (Codon c) (Codon c) c c
+instance Field3 (Codon c) (Codon c) c c
+instance Each (Codon c) (Codon c') c c'
+
diff --git a/Biobase/Types/Convert.hs b/Biobase/Types/Convert.hs
deleted file mode 100644
--- a/Biobase/Types/Convert.hs
+++ /dev/null
@@ -1,36 +0,0 @@
-{-# LANGUAGE MultiParamTypeClasses #-}
-
--- | Provides a converting function between different types. Most useful
--- conversions are instanced here.
-
-module Biobase.Types.Convert where
-
-import Biobase.Types.Ring
-import Biobase.Types.Energy
-import Biobase.Types.Score
-import Biobase.Types.Partition
-
-
-
--- | How to convert between different values.
-
-class Convert a b c where
-  convert :: a -> b -> c
-
-
-
--- | From (Gibbs free) energy to partition function values.
---
--- TODO temperature is running around here: move to some library later on
-
-newtype Kelvin = Kelvin {unKelvin :: Double}
-
-constR = undefined
-
-instance Convert Kelvin Energy Partition where
-  convert (Kelvin k) (Energy a) = Partition . exp $ (fromIntegral $ negate a) / (constR * k)
-
--- | From log-odd scores to partition function.
-
--- instance Convert Temperature Score Partition where
---   convert (Score a) = Partition . exp $ (fromIntegral $ neg a) / (constR * constT)
diff --git a/Biobase/Types/Energy.hs b/Biobase/Types/Energy.hs
--- a/Biobase/Types/Energy.hs
+++ b/Biobase/Types/Energy.hs
@@ -1,51 +1,95 @@
-{-# LANGUAGE StandaloneDeriving #-}
-{-# LANGUAGE MultiParamTypeClasses #-}
-{-# LANGUAGE GeneralizedNewtypeDeriving #-}
 
+-- | Different types of energies and conversion between.
+--
+-- TODO enthalpy
+-- TODO entropy
+
 module Biobase.Types.Energy where
 
-import qualified Data.Vector.Unboxed as VU
-import qualified Data.Vector.Generic as VG
-import qualified Data.Vector.Generic.Mutable as VGM
-import Data.Primitive.Types
+import Control.DeepSeq
+import Control.Lens
+import Data.Aeson (FromJSON, ToJSON)
+import Data.Binary (Binary)
+import Data.Data
+import Data.Default
+import Data.Hashable
+import GHC.Real
+import Data.Serialize (Serialize)
+import Data.Vector.Unboxed.Deriving
+import GHC.Generics
 
-import Biobase.Types.Ring
+import Algebra.Structure.Semiring
+import Numeric.Discretized
+import Numeric.Limits
 
 
 
--- | Some default instances. Left out the Num one, so that you have to
--- explicitly instanciate if you want to go around the Ring structure.
+-- | Gibbs free energy change.
+--
+-- For RNA structure, the change in energy from the unfolded structure to
+-- the given structure.
+--
+-- In units of @kcal / mol@.
+--
+-- TODO shall we phantom-type the actual units?
 
-newtype Energy = Energy {unEnergy :: Int}
-  deriving (Show, Read, Eq, Ord)
+newtype DG = DG { dG :: Double }
+  deriving (Eq,Ord,Num,Fractional,Read,Show,Generic,Data,Typeable)
+makeLenses ''DG
 
+derivingUnbox "DG"
+  [t| DG -> Double |]  [| dG |]  [| DG |]
 
+instance Hashable  DG
+instance Binary    DG
+instance Serialize DG
+instance FromJSON  DG
+instance ToJSON    DG
+instance NFData    DG
 
--- | Ring operations over Energy values.
+deriving instance NumericLimits DG
+deriving instance NumericEpsilon  DG
 
-instance Ring Energy where
-  (Energy a) .+. (Energy b) = Energy $ a `min` b
-  {-# INLINE (.+.) #-}
-  (Energy a) .*. (Energy b) = Energy $ a + b
-  {-# INLINE (.*.) #-}
-  (Energy a) .^. k = Energy $ a * k
-  {-# INLINE (.^.) #-}
-  (Energy a) .^^. k = Energy . round $ fromIntegral a * k
-  {-# INLINE (.^^.) #-}
-  neg (Energy a) = Energy $ negate a
-  {-# INLINE neg #-}
-  one = Energy 0
-  {-# INLINE one #-}
-  zero = Energy 10000000
-  {-# INLINE zero #-}
-  isZero (Energy a) = a >= 1000000
-  {-# INLINE isZero #-}
+instance Default DG where
+  def = maxFinite / 100
+  {-# Inline def #-}
 
 
 
--- * Vector instances.
+-- | Discretized @DG@.
 
-deriving instance VGM.MVector VU.MVector Energy
-deriving instance VG.Vector VU.Vector Energy
-deriving instance VU.Unbox Energy
-deriving instance Prim Energy
+newtype DDG = DDG { dDG ∷ Discretized (1 :% 100) }
+  deriving (Eq,Ord,Num,Read,Generic,Real,Enum)
+
+instance Show DDG where
+  show (DDG e) = show e
+
+ddg2Int :: DDG -> Int
+ddg2Int (DDG (Discretized e)) = e
+
+derivingUnbox "DDG"
+  [t| DDG -> Int |]  [| getDiscretized . dDG |]  [| DDG . Discretized |]
+
+instance Semiring DDG where
+  plus  (DDG x) (DDG y) = DDG $ min x y
+  times (DDG x) (DDG y) = DDG $ x `plus` y
+  zero = DDG maxFinite
+  one  = DDG zero
+  {-# Inline plus  #-}
+  {-# Inline times #-}
+  {-# Inline zero  #-}
+  {-# Inline one   #-}
+
+--instance Hashable  DeltaDekaGibbs
+--instance Binary    DeltaDekaGibbs
+--instance Serialize DeltaDekaGibbs
+--instance FromJSON  DeltaDekaGibbs
+--instance ToJSON    DeltaDekaGibbs
+--instance NFData    DeltaDekaGibbs
+--
+--deriving instance NumericLimits DeltaDekaGibbs
+--
+--instance Default DeltaDekaGibbs where
+--  def = maxFinite `div` 100
+--  {-# Inline def #-}
+--
diff --git a/Biobase/Types/Evalue.hs b/Biobase/Types/Evalue.hs
new file mode 100644
--- /dev/null
+++ b/Biobase/Types/Evalue.hs
@@ -0,0 +1,56 @@
+
+-- | Encode the number of hits to expect. This is typically dependent on
+-- some "database size". Evalues are bounded by @[0,infinity)@.
+--
+-- TODO Evalues close to zero are more interesting. We should strongly
+-- consider log-conversion here.
+
+module Biobase.Types.Evalue where
+
+import           Control.DeepSeq
+import           Control.Lens
+import           Data.Aeson
+import           Data.Binary
+import           Data.Default
+import           Data.Hashable (Hashable)
+import           Data.Primitive.Types
+import           Data.Serialize
+import           Data.Vector.Unboxed.Base
+import           Data.Vector.Unboxed.Deriving
+import           GHC.Generics (Generic)
+import qualified Data.Vector.Generic as VG
+import qualified Data.Vector.Generic.Mutable as VGM
+import qualified Data.Vector.Unboxed as VU
+
+import           Numeric.Limits
+
+
+
+-- | Type-safe wrapper for e-values.
+
+newtype Evalue = Evalue { getEvalue :: Double }
+  deriving (Eq,Ord,Read,Show,Num,Generic)
+makeWrapped ''Evalue
+
+instance Binary    Evalue
+instance FromJSON  Evalue
+instance Hashable  Evalue
+instance Serialize Evalue
+instance ToJSON    Evalue
+instance NFData    Evalue
+
+derivingUnbox "Evalue"
+  [t| Evalue -> Double |] [| getEvalue |] [| Evalue |]
+
+-- | By default, we expect no hits.
+
+instance Default Evalue where
+  def = Evalue 0
+  {-# Inline def #-}
+
+instance NumericLimits Evalue where
+  maxFinite   = Evalue maxFinite
+  minFinite   = Evalue 0
+  {-# Inline maxFinite  #-}
+  {-# Inline minFinite  #-}
+
diff --git a/Biobase/Types/Index.hs b/Biobase/Types/Index.hs
new file mode 100644
--- /dev/null
+++ b/Biobase/Types/Index.hs
@@ -0,0 +1,116 @@
+
+-- | Biological sequence data is oftentimes indexed either @0-@ or
+-- @1-@based. The @Index@ type developed provides static guarantees that
+-- there is no confusion what index is in use.
+--
+-- This module does not export the ctor @Index@. If you want to (unsafely)
+-- use it, import @Biobase.Types.Index.Type@ directly. Use @fromInt0@ to
+-- make clear that you count from 0 and transform to an @Index t@. I.e.
+-- @fromInt0 0 :: Index 1@ yields the lowest 1-base index.
+--
+-- Note that internally, every lowest index starts at @0 :: Int@.
+
+module Biobase.Types.Index
+  ( module Biobase.Types.Index
+  , getIndex
+  , index
+  , maybeIndex
+  , Index
+  ) where
+
+import Data.Coerce
+import Data.Proxy
+import GHC.TypeLits
+import Text.Printf
+
+import Biobase.Types.Index.Type -- hiding (getIndex)
+import qualified Biobase.Types.Index.Type as IT
+
+
+
+-- | Uses 'index' to guarantee that the 'Index' is ok.
+
+checkIndex :: forall t . KnownNat t => Index t -> Index t
+checkIndex i@(Index z)
+  | z >= 0    = i
+  | otherwise = error $ printf "%d < Index %d\n" (z+n) n
+  where n :: Int = fromIntegral $ natVal (Proxy :: Proxy t)
+{-# Inline checkIndex #-}
+
+-- | Re-Index an index of type @Index n@ as @Index m@. This is always safe,
+-- as @0 :: Index 0@ gives @1 :: Index 1@ for example. I.e. valid indices
+-- become valid indices.
+
+reIndex ∷ Index n → Index m
+{-# Inline reIndex #-}
+reIndex = coerce
+--reIndex :: forall n m . (KnownNat n, KnownNat m) => Index n -> Index m
+--reIndex (Index i) = Index $ i - n + m
+--  where n = fromIntegral $ natVal (Proxy :: Proxy n)
+--        m = fromIntegral $ natVal (Proxy :: Proxy m)
+
+-- | Helper function that allows @addition@ of an 'Index' and an 'Int',
+-- with the 'Int' on the right.
+
+(+.) :: forall t . KnownNat t => Index t -> Int -> Index t
+(+.) i n = checkIndex $ unsafePlus i n
+{-# Inline (+.) #-}
+
+-- | Helper function that allows @subtraction@ of an 'Index' and an 'Int',
+-- with the 'Int' on the right.
+
+(-.) :: forall t . KnownNat t => Index t -> Int -> Index t
+(-.) i n = checkIndex $ unsafePlus i (negate n)
+{-# Inline (-.) #-}
+
+-- | Unsafe plus.
+
+unsafePlus :: forall t . KnownNat t => Index t -> Int -> Index t
+unsafePlus i n = Index $ IT.getIndex i + n
+{-# Inline unsafePlus #-}
+
+-- | Delta between two 'Index' points.
+
+delta :: forall t . KnownNat t => Index t -> Index t -> Int
+delta (Index i) (Index j) = abs $ i - j
+{-# Inline delta #-}
+
+toInt ∷ forall t . KnownNat t ⇒ Index t → Int
+{-# Inline toInt #-}
+toInt i = IT.getIndex i + (fromIntegral $ natVal (Proxy ∷ Proxy t))
+
+-- | Return the index as an @Int@-style index that is zero-based.
+
+toInt0 :: forall t . KnownNat t => Index t -> Int
+toInt0 = IT.getIndex
+{-# Inline toInt0 #-}
+
+-- | Return the index as an @Int@-style index that is one-based.
+
+toInt1 ∷ forall t . KnownNat t ⇒ Index t → Int
+{-# Inline toInt1 #-}
+toInt1 = (+1) . toInt0
+
+fromInt1 ∷ forall t . KnownNat t ⇒ Int → Index t
+{-# Inline fromInt1 #-}
+fromInt1 = fromInt0 . (subtract 1)
+
+-- | As an index from an @Int@-style zero-based one.
+--
+-- TODO We might want to check that the argument is @[0..]@.
+
+fromInt0 :: forall t . KnownNat t => Int -> Index t
+fromInt0 i
+  | i >= 0    = Index i
+  | otherwise = error "fromInt0 needs an Int >= 0"
+  where t = fromIntegral $ natVal (Proxy :: Proxy t)
+{-# Inline fromInt0 #-}
+
+-- | Zero-based indices.
+
+type I0 = Index 0
+
+-- | One-based indices.
+
+type I1 = Index 1
+
diff --git a/Biobase/Types/Index/Type.hs b/Biobase/Types/Index/Type.hs
new file mode 100644
--- /dev/null
+++ b/Biobase/Types/Index/Type.hs
@@ -0,0 +1,117 @@
+
+module Biobase.Types.Index.Type where
+
+import           Control.Applicative ((<$>))
+import           Control.DeepSeq
+import           Data.Aeson
+import           Data.Binary
+import           Data.Data (Data)
+import           Data.Hashable (Hashable)
+import           Data.Proxy
+import           Data.Serialize (Serialize)
+import           Data.Typeable (Typeable)
+import           Data.Vector.Fusion.Stream.Monadic (Step(..), flatten)
+import           Data.Vector.Unboxed.Deriving
+import           GHC.Generics
+import           GHC.TypeLits
+import qualified Data.Ix as Ix
+import qualified Data.Vector.Fusion.Stream.Monadic as SM
+import           Test.QuickCheck
+import           Text.Printf
+
+import           Data.PrimitiveArray.Index.Class hiding (Index)
+import qualified Data.PrimitiveArray.Index.Class as PA
+
+
+
+-- | A linear @Int@-based index type.
+
+newtype Index (t :: Nat) = Index { getIndex :: Int }
+  deriving (Show,Read,Eq,Ord,Generic,Ix.Ix,Data,Typeable)
+
+-- | Turn an 'Int' into an 'Index' safely.
+
+index :: forall t . KnownNat t => Int -> Index t
+index i = maybe (error $ printf "%d < Index %d\n" i n) id $ maybeIndex i
+  where n = natVal (Proxy :: Proxy t)
+{-# Inline index #-}
+
+-- | Produce 'Just' and 'Index' or 'Nothing'.
+
+maybeIndex :: forall t . KnownNat t => Int -> Maybe (Index t)
+maybeIndex i
+  | i >= n    = Just . Index $ i - n
+  | otherwise = Nothing
+  where n = fromIntegral $ natVal (Proxy :: Proxy t)
+{-# Inline maybeIndex #-}
+
+instance KnownNat t => Num (Index t) where
+  Index a + Index b = error $ show (" Index.(+) not implemented, use (+.)",a,b) -- index $ a + b
+  Index a - Index b = error $ show (" Index.(-) not implemented, use (-.)",a,b) -- index $ a - b
+  Index a * Index b = error $ show (" Index.(*) not implemented", a,b) -- index $ a * b
+  negate = error "Indices are natural numbers"
+  abs = id
+  signum = index . signum . getIndex
+  fromInteger = index . fromIntegral
+  {-# Inline fromInteger #-}
+
+instance NFData (Index t) where
+  rnf = rnf . getIndex
+  {-# Inline rnf #-}
+
+instance Binary    (Index t)
+instance Serialize (Index t)
+instance ToJSON    (Index t)
+instance FromJSON  (Index t)
+instance Hashable  (Index t)
+
+derivingUnbox "Index"
+  [t| forall t . Index t -> Int |]  [| getIndex |]  [| Index |]
+
+instance forall t . KnownNat t => PA.Index (Index t) where
+  newtype LimitType (Index t) = LtIndex Int
+  linearIndex (LtIndex k) (Index z) = z
+  {-# INLINE linearIndex #-}
+  size (LtIndex h) = h + 1
+  {-# INLINE size #-}
+  inBounds (LtIndex h) (Index x) = 0<=x && x<=h
+  {-# INLINE inBounds #-}
+  zeroBound = Index 0
+  {-# Inline zeroBound #-}
+  zeroBound' = LtIndex 0
+  {-# Inline zeroBound' #-}
+  totalSize (LtIndex k) = [fromIntegral k]
+  {-# Inline totalSize #-}
+  fromLinearIndex _ = Index
+  {-# Inline [0] fromLinearIndex #-}
+  showBound (LtIndex k) = ["LtIndex " ++ show k]
+  showIndex (Index k) = ["Index " ++ show k]
+
+instance (KnownNat t, IndexStream z) ⇒ IndexStream (z:.Index t) where
+  streamUp (ls:..LtIndex lf) (hs:..LtIndex ht) = flatten mk step $ streamUp ls hs
+    where mk z = return (z,lf)
+          step (z,k)
+            | k > ht    = return $ Done
+            | otherwise = return $ Yield (z:.Index k) (z,k+1)
+          {-# Inline [0] mk   #-}
+          {-# Inline [0] step #-}
+  {-# Inline streamUp #-}
+  streamDown (ls:..LtIndex lf) (hs:..LtIndex ht) = flatten mk step $ streamDown ls hs
+    where mk z = return (z,ht)
+          step (z,k)
+            | k < lf    = return $ Done
+            | otherwise = return $ Yield (z:.Index k) (z,k-1)
+          {-# Inline [0] mk   #-}
+          {-# Inline [0] step #-}
+  {-# Inline streamDown #-}
+
+instance (KnownNat t) ⇒ IndexStream (Index t) where
+  streamUp l h = SM.map (\(Z:.i) -> i) $ streamUp (ZZ:..l) (ZZ:..h)
+  {-# INLINE streamUp #-}
+  streamDown l h = SM.map (\(Z:.i) -> i) $ streamDown (ZZ:..l) (ZZ:..h)
+  {-# INLINE streamDown #-}
+
+instance Arbitrary (Index t) where
+  arbitrary = Index <$> arbitrary
+  shrink (Index j) = map Index $ shrink j
+
diff --git a/Biobase/Types/Location.hs b/Biobase/Types/Location.hs
new file mode 100644
--- /dev/null
+++ b/Biobase/Types/Location.hs
@@ -0,0 +1,253 @@
+
+-- | Annotate the genomic @Location@ of features or elements. A @Location@ is
+-- always contiguous, using strand, 0-based position, and length.
+-- Transformation to different systems of annotation is made possible.
+
+module Biobase.Types.Location where
+
+import Control.DeepSeq
+import Control.Lens hiding (Index, index)
+import Data.Coerce
+import Data.Data
+import Data.Data.Lens
+import GHC.Generics (Generic)
+import GHC.TypeNats
+import Prelude hiding (length)
+import qualified Data.ByteString as BS
+import qualified Streaming.Internal as SI
+import qualified Streaming.Prelude as SP
+import Text.Printf
+
+import Biobase.Types.BioSequence
+import Biobase.Types.Index
+import Biobase.Types.Position
+import Biobase.Types.Strand
+import Data.Info
+
+
+
+
+-- | Operations on locations.
+
+class ModifyLocation posTy seqTy where
+  -- | Append to the left.
+  locAppendLeft  :: seqTy -> Location i posTy seqTy -> Location i posTy seqTy
+  -- | Append to the right.
+  locAppendRight :: seqTy -> Location i posTy seqTy -> Location i posTy seqTy
+  -- | Split a location.
+  locSplitAt  :: Int -> Location i posTy seqTy -> (Location i posTy seqTy, Location i posTy seqTy)
+  -- | Length of location
+  locLength :: Location i posTy seqTy -> Int
+
+locTake k = fst . locSplitAt k
+
+locTakeEnd k loc = let l = locLength loc in snd $ locSplitAt (l-k) loc
+
+locDrop k = snd . locSplitAt k
+
+locDropEnd k loc = let l = locLength loc in fst $ locSplitAt (l-k) loc
+
+locSplitEndAt k loc = let l = locLength loc in locSplitAt (l-k) loc
+
+
+
+data Location ident posTy seqTy = Location
+  { _locIdentifier  :: !(SequenceIdentifier ident)
+  , _locPosition    :: !posTy
+  , _locSequence    :: !seqTy
+  }
+  deriving stock (Show,Data,Typeable,Generic)
+makeLenses ''Location
+
+instance (NFData p, NFData s) => NFData (Location i p s)
+
+retagLocation :: Location i posTy seqTy -> Location j posTy seqTy
+{-# Inline retagLocation #-}
+retagLocation = over locIdentifier coerce
+
+instance ModifyLocation FwdPosition (BioSequence w) where
+  {-# Inline locAppendLeft #-}
+  locAppendLeft s loc = let l = s^._BioSequence.to BS.length
+    in loc & locSequence %~ (s <>) & locPosition %~ (\p -> if p^.fwdStrand == PlusStrand then p & fwdStart %~ (-. l) else p)
+  {-# Inline locAppendRight #-}
+  locAppendRight s loc = let l = s^._BioSequence.to BS.length
+    in loc & locSequence %~ (<> s) & locPosition %~ (\p -> if p^.fwdStrand == MinusStrand then p & fwdStart %~ (-. l) else p)
+  {-# Inline locSplitAt #-}
+  locSplitAt k loc =
+    let (h',t') = loc^.locSequence._BioSequence.to (BS.splitAt k)
+        hl = BS.length h' ; tl = BS.length t'
+        h = loc & locSequence._BioSequence .~ h' & locPosition %~ (\p -> if p^.fwdStrand == MinusStrand then p & fwdStart %~ (+. tl) else p)
+        t = loc & locSequence._BioSequence .~ t' & locPosition %~ (\p -> if p^.fwdStrand == PlusStrand then p & fwdStart %~ (+. hl) else p)
+    in  (h,t)
+  {-# Inline locLength #-}
+  locLength = view (locSequence._BioSequence.to BS.length)
+
+instance ModifyLocation FwdPosition Int where
+  {-# Inline locAppendLeft #-}
+  locAppendLeft k' loc = let k = max 0 $ min (loc^.locPosition.fwdStart.to toInt0) k' in
+    loc & locSequence %~ (+ k) & locPosition %~ (\p -> if p^.fwdStrand == PlusStrand then p & fwdStart %~ (-. k) else p)
+  {-# Inline locAppendRight #-}
+  locAppendRight k' loc = let k = max 0 $ min (loc^.locPosition.fwdStart.to toInt0) k' in
+    loc & locSequence %~ (+ k) & locPosition %~ (\p -> if p^.fwdStrand == MinusStrand then p & fwdStart %~ (-. k) else p)
+  {-# Inline locSplitAt #-}
+  locSplitAt k loc =
+    let h' = max 0 . min k $ locLength loc
+        t' = locLength loc - h'
+        h = loc & locSequence .~ h' & locPosition %~ (\p -> if p^.fwdStrand == MinusStrand then p & fwdStart %~(+. t') else p)
+        t = loc & locSequence .~ t' & locPosition %~ (\p -> if p^.fwdStrand == PlusStrand then p & fwdStart %~ (+. h') else p)
+    in  (h,t)
+  {-# Inline locLength #-}
+  locLength = view locSequence
+
+instance Reversing (Location i FwdPosition (BioSequence w)) where
+  {-# Inline reversing #-}
+  reversing = over (locSequence._BioSequence) BS.reverse . over (locPosition) reversing
+
+instance Complement (BioSequence w) => Complement (Location i FwdPosition (BioSequence w)) where
+  {-# Inline complement #-}
+  complement = iso f f
+    where f = over locSequence (view complement)
+
+instance (Info (BioSequence w)) => Info (Location i FwdPosition (BioSequence w)) where
+  info loc = printf "%s %s %s" (loc^.locIdentifier^.to show) (show $ loc^.locPosition) (loc^.locSequence.to info)
+
+-- | Will extract a substring for a given biosequence. It is allowed to hand in partially or not at
+-- all overlapping locational information. This will yield empty resulting locations.
+--
+-- This will convert the @FwdPosition@ strand, which in turn allows dealing with reverse-complement
+-- searches.
+--
+-- @
+-- 0123456789
+--    3.3
+-- @
+
+subLocation :: Location i FwdPosition (BioSequence w) -> (FwdPosition, Int) -> Location i FwdPosition (BioSequence w)
+{-# Inline subLocation #-}
+subLocation s (p',l)
+  | ss==PlusStrand = locTake l $ locDrop d s
+  | ss==MinusStrand = locTakeEnd l $ locDropEnd d s
+  where ss = s^.locPosition.fwdStrand
+        p = if ss == p'^.fwdStrand then p' else reversing p'
+        d = delta (s^.locPosition.fwdStart) (p^.fwdStart)
+
+data PIS i p s = PIS
+  { _pisPrefix  :: Maybe (Location i p s)
+  , _pisInfix   :: !(Location i p s)
+  , _pisSuffix  :: Maybe (Location i p s)
+  }
+  deriving stock (Show, Data)
+makeLenses ''PIS
+
+pis ifx = PIS Nothing ifx Nothing
+
+retagPis :: PIS i p s -> PIS j p s
+retagPis (PIS p i s) = PIS (fmap retagLocation p) (retagLocation i) (fmap retagLocation s)
+
+-- | Given a @PIS@, this will return the @substring@ indicated by the location in the 2nd argument.
+-- Allows for easy substring extraction, and retains the system of prefix/infix/suffix.
+--
+-- It is allowed to hand locations that only partially (or not at all) correspond to the @PIS@, but
+-- then the resulting @PIS@ will be empty!
+
+subPisLocation :: PIS i FwdPosition (BioSequence w) -> (FwdPosition, Int) -> PIS i FwdPosition (BioSequence w)
+{-# Inline subPisLocation #-}
+subPisLocation pis loc =
+  let f z = subLocation z loc
+  in  over (pisPrefix._Just) f . over pisInfix f $ over (pisSuffix._Just) f pis
+
+instance (Reversing (Location i FwdPosition (BioSequence w))) => Reversing (PIS i FwdPosition (BioSequence w)) where
+  {-# Inline reversing #-}
+  reversing pis
+    = over (pisPrefix._Just) reversing . over pisInfix reversing . over (pisSuffix._Just) reversing
+    . set pisPrefix (pis^.pisSuffix) . set pisSuffix (pis^.pisPrefix) $ pis
+
+instance Complement (BioSequence w) => Complement (PIS i FwdPosition (BioSequence w)) where
+  {-# Inline complement #-}
+  complement =
+    let f = over pisInfix (view complement) . over (pisPrefix._Just) (view complement) . over (pisSuffix._Just) (view complement)
+    in  iso f f
+
+pisSequence :: Lens (PIS i p (BioSequence s)) (PIS i p (BioSequence t)) (BioSequence s) (BioSequence t)
+{-# Inline pisSequence #-}
+pisSequence = lens f t where
+  v = view (locSequence.bioSequence)
+  f (PIS p i s) = BioSequence $ maybe BS.empty v p `BS.append` v i `BS.append` maybe BS.empty v s
+  t (PIS p i s) (BioSequence str) =
+    let (pfx,ifxsfx) = over _1 BioSequence   $ BS.splitAt (maybe 0 (BS.length . v) p) str
+        (ifx,sfx   ) = over both BioSequence $ BS.splitAt (BS.length $ v i) ifxsfx
+    in  PIS (set (_Just . locSequence) pfx p) (set locSequence ifx i) (set (_Just . locSequence) sfx s)
+
+
+
+-- | Given a @Location@ with a @BioSequence@, replace the sequence with its length.
+
+locAsLength :: Location i FwdPosition (BioSequence w) -> Location i FwdPosition Int
+{-# Inline locAsLength #-}
+locAsLength = over locSequence (view (_BioSequence.to BS.length))
+
+
+
+-- | Provides a range in a notation as used by blast, for example. This
+-- isomorphism can translate back as well. @FwdLocation - 8 4 ^. blastRange1 ==
+-- 9 6 MinusStrand@, since these ranges are 1-based and start and end included.
+
+blastRange1 :: (Location i FwdPosition Int) -> (Int,Int,Strand)
+{-# Inline blastRange1 #-}
+blastRange1 = f -- iso f t
+  where
+    f loc =
+      let s = loc^.locPosition.fwdStart.to toInt1
+          l = loc^.locSequence
+          pm = loc^.locPosition.fwdStrand
+      in  case pm of PlusStrand -> (s,s+l,pm) ; MinusStrand -> (s+l,s,pm)
+--    t (x,y,pm) =
+--      let s = fromInt1 x
+--          l = 1 + abs (x-y)
+--      in  Location (FwdPosition pm s) l
+
+
+
+-- | For each element, attach the prefix as well. The @Int@ indicates the maximal prefix length to
+-- attach.
+--
+-- @1 2 3 4@ -> @01 12 23 34@
+--
+-- TODO are we sure this is correct for @MinusStrand@?
+
+attachPrefixes
+  :: ( Monad m, ModifyLocation p s )
+  => Int
+  -> SP.Stream (SP.Of (PIS i p s)) m r
+  -> SP.Stream (SP.Of (PIS i p s)) m r
+{-# Inlinable attachPrefixes #-}
+attachPrefixes k = SP.map (\(Just w) -> w) . SP.drop 1 . SP.scan go Nothing id
+  where
+    go Nothing = Just
+    go (Just p) = Just . set pisPrefix (Just . locTakeEnd k $ view pisInfix p)
+
+
+
+-- | For each element, attach the suffix as well.
+--
+-- @1 2 3 4@ -> @12 23 34 40@
+
+attachSuffixes
+  :: ( Monad m, ModifyLocation p s )
+  => Int
+  -> SP.Stream (SP.Of (PIS i p s)) m r
+  -> SP.Stream (SP.Of (PIS i p s)) m r
+{-# Inlinable attachSuffixes #-}
+attachSuffixes k = loop Nothing
+  where
+    loop Nothing = \case
+      SI.Return r -> SI.Return r
+      SI.Effect m -> SI.Effect $ fmap (loop Nothing) m
+      SI.Step (a SP.:> rest) -> loop (Just a) rest
+    loop (Just p) = \case
+      SI.Return r -> SI.Step (p SP.:> SI.Return r)
+      SI.Effect m -> SI.Effect $ fmap (loop (Just p)) m
+      SI.Step (a SP.:> rest) ->
+        let p' = p & set pisSuffix (Just . locTake k $ view pisInfix a)
+        in  SI.Step (p' SP.:> loop (Just a) rest)
+
diff --git a/Biobase/Types/Names.hs b/Biobase/Types/Names.hs
new file mode 100644
--- /dev/null
+++ b/Biobase/Types/Names.hs
@@ -0,0 +1,143 @@
+
+-- | Names for biological things.
+--
+-- Species names are internalized and represented as an @Int@. This allows
+-- using them in structures like an @IntMap@.
+--
+-- For other names, we newtype-wrap normal text internalization.
+--
+
+module Biobase.Types.Names where
+
+import Control.Applicative
+import Control.DeepSeq (NFData(..))
+import Data.Aeson as A
+import Data.Binary      as DB
+import Data.Hashable
+import Data.Interned
+import Data.Interned.Text
+import Data.Serialize   as DS
+import Data.Serialize.Text
+import Data.String as IS
+import Data.String.Conversions (ConvertibleStrings(..), cs)
+import Data.String.Conversions.Monomorphic (toST, fromST)
+import Data.Text.Binary
+import Data.Text (Text, pack, unpack)
+import Data.Vector.Unboxed.Deriving
+import GHC.Generics
+
+import Biobase.Types.Names.Internal
+
+
+
+-- * Int-internalized species names.
+
+-- | A species name. Represented with an @Int@, but behaves like a @Text@.
+
+newtype SpeciesName = SpeciesName { getSpeciesNameRep :: Int }
+  deriving (Eq,Generic)
+
+derivingUnbox "SpeciesName"
+  [t| SpeciesName -> Int |]
+  [|  getSpeciesNameRep  |]
+  [|  SpeciesName        |]
+
+instance Ord SpeciesName where
+  SpeciesName l `compare` SpeciesName r = speciesNameBimapLookupInt l `compare` speciesNameBimapLookupInt r
+  {-# Inline compare #-}
+
+-- | Smart constructor that performs the correct internalization.
+
+speciesName :: Text -> SpeciesName
+speciesName = SpeciesName . speciesNameBimapAdd
+{-# Inline speciesName #-}
+
+instance IsString SpeciesName where
+  fromString = speciesName . IS.fromString
+  {-# Inline fromString #-}
+
+instance Show SpeciesName where
+  showsPrec p i r = showsPrec p (unpack $ toST i) r
+  {-# Inline showsPrec #-}
+
+instance Read SpeciesName where
+  readsPrec p str = [ (speciesName $ IS.fromString s, y) | (s,y) <- readsPrec p str ]
+  {-# Inline readsPrec #-}
+
+instance Hashable SpeciesName
+
+instance ConvertibleStrings Text SpeciesName where
+  convertString = speciesName
+
+instance ConvertibleStrings SpeciesName Text where
+  convertString = speciesNameBimapLookupInt . getSpeciesNameRep
+
+instance NFData SpeciesName
+
+instance Binary SpeciesName where
+  put = DB.put . toST
+  get = fromST <$> DB.get
+  {-# Inline put #-}
+  {-# Inline get #-}
+
+instance Serialize SpeciesName where
+  put = DS.put . toST
+  get = fromST <$> DS.get
+  {-# Inline put #-}
+  {-# Inline get #-}
+
+instance FromJSON SpeciesName where
+  parseJSON s = fromST <$> parseJSON s
+  {-# Inline parseJSON #-}
+
+instance ToJSON SpeciesName where
+  toJSON = toJSON . toST
+  {-# Inline toJSON #-}
+
+
+
+-- * Internalize taxonomic rank names
+
+-- | The taxonomic rank. This encodes the name for a given rank.
+
+newtype TaxonomicRank = TaxonomicRank { getTaxonomicRank :: InternedText }
+  deriving (IsString,Eq,Ord,Show,Generic)
+
+instance NFData TaxonomicRank where
+  rnf (TaxonomicRank it) = rnf (internedTextId it)
+  {-# Inline rnf #-}
+
+instance ConvertibleStrings Text TaxonomicRank where
+  convertString = TaxonomicRank . intern
+
+instance ConvertibleStrings TaxonomicRank Text where
+  convertString = unintern . getTaxonomicRank
+
+instance Hashable TaxonomicRank where
+  hashWithSalt s (TaxonomicRank it) = hashWithSalt s (internedTextId it)
+  {-# Inline hashWithSalt #-}
+
+instance Read TaxonomicRank where
+  readsPrec p str = [ (IS.fromString s, y) | (s,y) <- readsPrec p str ]
+  {-# Inline readsPrec #-}
+
+instance Binary TaxonomicRank where
+  put = DB.put . toST
+  get = fromST <$> DB.get
+  {-# Inline put #-}
+  {-# Inline get #-}
+
+instance Serialize TaxonomicRank where
+  put = DS.put . toST
+  get = fromST <$> DS.get
+  {-# Inline put #-}
+  {-# Inline get #-}
+
+instance FromJSON TaxonomicRank where
+  parseJSON s = fromST <$> parseJSON s
+  {-# Inline parseJSON #-}
+
+instance ToJSON TaxonomicRank where
+  toJSON = toJSON . toST
+  {-# Inline toJSON #-}
+
diff --git a/Biobase/Types/Names/Internal.hs b/Biobase/Types/Names/Internal.hs
new file mode 100644
--- /dev/null
+++ b/Biobase/Types/Names/Internal.hs
@@ -0,0 +1,36 @@
+
+module Biobase.Types.Names.Internal where
+
+import Data.IORef (newIORef,IORef,readIORef,atomicWriteIORef,atomicModifyIORef')
+import Data.Text (Text)
+import System.IO.Unsafe (unsafePerformIO,unsafeDupablePerformIO)
+
+import Data.Bijection.HashMap
+import Data.Bijection.Vector
+
+
+
+speciesNameBimap :: IORef (Bimap (HashMap Text Int) (Vector Text))
+speciesNameBimap = unsafePerformIO $ newIORef empty
+{-# NoInline speciesNameBimap #-}
+
+-- | Add @Text@ and return @Int@ key. Will return key for
+-- existing string and thereby serves for lookup in left-to-right
+-- direction.
+
+speciesNameBimapAdd :: Text -> Int
+speciesNameBimapAdd k = unsafeDupablePerformIO $ atomicModifyIORef' speciesNameBimap $ \m ->
+  case lookupL m k of Just i  -> (m,i)
+                      Nothing -> let s = size m
+                                 in  (insert m (k,s) , s)
+{-# Inline speciesNameBimapAdd #-}
+
+-- | Lookup the @InternedMultiChar@ based on an @Int@ key. Unsafe totality
+-- assumption.
+
+speciesNameBimapLookupInt :: Int -> Text
+speciesNameBimapLookupInt r = seq r . unsafeDupablePerformIO $ atomicModifyIORef' speciesNameBimap $ \m ->
+  case lookupR m r of Just l  -> (m,l)
+                      Nothing -> error "speciesNameBimapLookupInt: totality assumption invalidated"
+{-# Inline speciesNameBimapLookupInt #-}
+
diff --git a/Biobase/Types/Partition.hs b/Biobase/Types/Partition.hs
deleted file mode 100644
--- a/Biobase/Types/Partition.hs
+++ /dev/null
@@ -1,84 +0,0 @@
-
-{-# LANGUAGE ForeignFunctionInterface #-}
-{-# LANGUAGE StandaloneDeriving #-}
-{-# LANGUAGE MultiParamTypeClasses #-}
-{-# LANGUAGE GeneralizedNewtypeDeriving #-}
-
-module Biobase.Types.Partition where
-
-import qualified Data.Vector.Unboxed as VU
-import qualified Data.Vector.Generic as VG
-import qualified Data.Vector.Generic.Mutable as VGM
-import Data.Primitive.Types
-
-import Biobase.Types.Ring
-
-
-
--- | Some default instances. Left out the Num one, so that you have to
--- explicitly instanciate if you want to go around the Ring structure.
-
-newtype Partition = Partition {unPartition' :: Double}
-  deriving (Show, Read, Eq, Ord)
-
--- |
-
-mkPartition :: Double -> Partition
-mkPartition x
-  | x < 0     = error $ "mkPartition: prob <0: " ++ show x
-  | x > 1     = error $ "mkPartition: prob >1: " ++ show x
-  | otherwise = Partition $ log x
-
-unPartition :: Partition -> Double
-unPartition (Partition x) = exp x
-
-
--- | Ring operations over Partition values.
-
-instance Ring Partition where
-  (Partition a) .+. (Partition b) = Partition $ logSum a b
-  {-# INLINE (.+.) #-}
-  (Partition a) .*. (Partition b) = Partition $ a + b
-  {-# INLINE (.*.) #-}
-  (Partition a) .^. k = Partition $ a * fromIntegral k
-  {-# INLINE (.^.) #-}
-  (Partition a) .^^. k = error ".^^. not defined for Partition" -- Partition $ a ^^ k
-  {-# INLINE (.^^.) #-}
-  neg (Partition a) = error $ "negate partition? " ++ show a -- Partition $ negate a
-  {-# INLINE neg #-}
-  one = Partition 1
-  {-# INLINE one #-}
-  zero = Partition 0
-  {-# INLINE zero #-}
-  isZero (Partition a) = a == 0 -- TODO use some epsilon?
-  {-# INLINE isZero #-}
-
-logSum :: Double -> Double -> Double
-logSum a b
-  | a>b       = f a b
-  | otherwise = f b a
-  where
-    f x y = x + log1p (exp $ y - x)
-    {-# INLINE f #-}
-{-# INLINE logSum #-}
-
-
-
--- * Vector (and Prim) instances.
-
-deriving instance VGM.MVector VU.MVector Partition
-deriving instance VG.Vector VU.Vector Partition
-deriving instance VU.Unbox Partition
-deriving instance Prim Partition
-
-
-
--- * math.h function for log/exp on pm1 are /much/ more efficient (what is
--- haskell doing?)
-
-foreign import ccall unsafe "math.h log1p"
-    log1p :: Double -> Double
-
-foreign import ccall unsafe "math.h expm1"
-    expm1 :: Double -> Double
-
diff --git a/Biobase/Types/Position.hs b/Biobase/Types/Position.hs
new file mode 100644
--- /dev/null
+++ b/Biobase/Types/Position.hs
@@ -0,0 +1,163 @@
+
+-- | Annotate the genomic @position@ of features or elements. A @position@ has strand information,
+-- and different ways to encode where a feature is located. The @position@ points to the first
+-- element (e.g. nucleotide).
+--
+-- Together with the 'Biobase.Types.Location' module, it becomes possible to annotate substrings.
+
+module Biobase.Types.Position where
+
+import Control.DeepSeq
+import Control.Lens hiding (Index, index)
+import Data.Data
+import GHC.Generics (Generic)
+import GHC.TypeNats
+import Prelude hiding (length)
+import Text.Printf
+
+import Biobase.Types.Index
+import Biobase.Types.Strand
+import Data.Info
+
+{-
+
+-- | Location information.
+
+data Location = Location
+  { _lStrand :: !Strand
+  -- ^ On which strand are we
+  , _lStart  :: !(Index 0)
+  -- ^ Start, 0-based
+  , _lLength :: !Int
+  -- ^ number of characters in this location
+  , _lTotalLength :: !Int
+  -- ^ the total length of the "contig" (or whatever) this location is positioned in.
+  } deriving (Eq,Ord,Read,Show,Generic)
+makeLenses ''Location
+makePrisms ''Location
+
+instance NFData Location
+
+instance Semigroup Location where
+  x <> y = let f z = z { _lLength = _lLength x + _lLength y }
+    in case x^.lStrand of
+      MinusStrand  -> f y
+      _otherStrand -> f x
+  {-# Inline (<>) #-}
+
+--instance Reversing Location where
+--  {-# Inline reversing #-}
+--  reversing = undefined
+
+
+-- | An isomorphism between locations, and triples of @Strand,Start,End@, where
+-- end is inclusive. For @length==0@ locations, this will mean @start<end@ on
+-- the plus strand.
+--
+-- This should hold for all @k@, in @Index k@.
+
+startEndInclusive :: (KnownNat k) => Iso' Location (Strand, (Index k, Index k), Int)
+{-# Inline startEndInclusive #-}
+startEndInclusive = iso l2r r2l
+  where l2r z = let s = z^.lStrand; f = z^.lStart; l = z^.lLength
+                in  (s, (reIndex f, reIndex $ f +. l -. 1), z^.lTotalLength)
+        r2l (s,(f,t),ttl) = Location s (reIndex f) (delta f t + 1) ttl
+
+-}
+
+
+
+-- | During streaming construction, it is possible that we know a feature is on the @-@ strand, but
+-- the length of the contig is not known yet. In that case, 'FwdPosition' allows expressing the hit
+-- in the coordinate system of the plus strand. Tools like blast do something similar, and express
+-- locations on the minus as @y-x@ with @y>x@.
+--
+-- @
+-- 0123456789
+--  >-->
+--      <--<
+-- 9876543210
+-- @
+--
+-- 
+
+data FwdPosition
+  -- | "Plus"-based location.
+  = FwdPosition
+      { _fwdStrand :: !Strand
+      -- ^ Strand we are on
+      , _fwdStart  :: !(Index 0)
+      -- ^ Start of the hit on the plus strand
+      }
+  deriving (Eq,Ord,Read,Show,Data,Typeable,Generic)
+makeLenses ''FwdPosition
+makePrisms ''FwdPosition
+
+instance NFData FwdPosition
+
+instance Info FwdPosition where
+  info (FwdPosition s x) = printf "%s %d" (show s) (toInt0 x)
+
+-- | Reversing a reversible location means moving the start to the end.
+
+instance Reversing FwdPosition where
+  {-# Inline reversing #-}
+  reversing x = case x^.fwdStrand of
+    PlusStrand    -> set fwdStrand MinusStrand $ x
+    MinusStrand   -> set fwdStrand PlusStrand  $ x
+    UnknownStrand -> x
+
+{-
+
+
+-- | Combining two FwdLocations yields the sum of their lengths. This assumes
+-- that @x@ and @y@ are next to each other, or that it is ok if the @y@
+-- @fwdStart@ information may be lost.
+--
+-- TODO provide associativity test in @properties@.
+
+instance Semigroup FwdLocation where
+  x <> y = over fwdLength (+ view fwdLength y) x
+  {-# Inline (<>) #-}
+
+instance ModifyLocation FwdLocation where
+  locMoveLeftEnd k = over fwdStart (+. k) . over fwdLength (subtract k)
+  locMoveRightEnd k = over fwdLength (+k)
+
+-- | Given a location, take at most @k@ elements, and return a location after
+-- this change.
+
+fwdLocationTake :: Int -> FwdLocation -> FwdLocation
+{-# Inline fwdLocationTake #-}
+fwdLocationTake k' x =
+  let l = x^.fwdLength
+      k = max 0 $ min k' l      -- deal with at most the length of the location
+  in case x^.fwdStrand of
+    MinusStrand  -> set fwdLength k $ over fwdStart (+. (l-k)) x
+    _otherStrand -> set fwdLength k $                          x
+
+-- | Given a location, drop at most @k@ elements, and return a location after
+-- this change.
+--
+-- Note that @fwdLocationDrop 4 (FwdLocation PlusStrand 0 4) == FwdLocation 4 0@
+
+fwdLocationDrop :: Int -> FwdLocation -> FwdLocation
+{-# Inline fwdLocationDrop #-}
+fwdLocationDrop k' x =
+  let l = x^.fwdLength
+      k = max 0 $ min k' l
+  in case x^.fwdStrand of
+    MinusStrand  -> set fwdLength (l-k) $                            x
+    _otherStrand -> set fwdLength (l-k) $ over fwdStart (+. min k l) x
+
+-- -- An isomorphism between a 'Location' and the pair @('FwdLocation',Int)@
+-- -- exists.
+-- 
+-- locationPartial :: Iso' Location (FwdLocation,Int)
+-- {-# Inline locationPartial #-}
+-- locationPartial = iso l2r r2l where
+--   l2r l = undefined
+--   r2l (p,z) = undefined
+
+-}
+
diff --git a/Biobase/Types/ReadingFrame.hs b/Biobase/Types/ReadingFrame.hs
new file mode 100644
--- /dev/null
+++ b/Biobase/Types/ReadingFrame.hs
@@ -0,0 +1,54 @@
+
+-- | Stranded reading frames.
+
+module Biobase.Types.ReadingFrame where
+
+import Control.Lens hiding (Index)
+import GHC.Generics hiding (from)
+
+import Biobase.Types.Index (Index, toInt0)
+import Biobase.Types.Strand
+
+
+
+-- | The Reading frame. Sequence indexing starts at position 1, which starts
+-- reading frame 1. Reading frame 2 and 3 start at position 2 and 3
+-- respectively.
+
+newtype ReadingFrame = ReadingFrame { getReadingFrame ∷ Int }
+  deriving (Eq,Ord,Generic,Show)
+makeWrapped ''ReadingFrame
+
+-- | Convert between @+1 ... +3@ and @ReadingFrame@.
+
+rf ∷ Prism' Int ReadingFrame
+{-# Inline rf #-}
+rf = prism' getReadingFrame $ \k → let ak = abs k in
+  if (ak <=  3 && ak >= 1) then Just (ReadingFrame k) else Nothing
+
+-- | A lens for the strand
+
+strandRF ∷ Lens' ReadingFrame Strand
+{-# Inline strandRF #-}
+strandRF = lens (\(ReadingFrame k) → if k < 0 then MinusStrand else PlusStrand)
+                (\(ReadingFrame k) s → ReadingFrame $ if s == PlusStrand then abs k else (negate $ abs k))
+
+-- |
+--
+-- @pred@ and @succ@ are correct, if the input is a legal 'ReadingFrame'.
+
+instance Enum ReadingFrame where
+  {-# Inline toEnum #-}
+  toEnum k = case k^?rf of Just rf → rf ; Nothing → error $ show k ++ " is not a legal reading frame"
+  {-# Inline fromEnum #-}
+  fromEnum = getReadingFrame
+
+-- |
+--
+-- TODO should this be a type class, since we might reasonably want to
+-- construct from a number of possible indices?
+
+fromIndex ∷ Index 1 → ReadingFrame
+{-# Inline fromIndex #-}
+fromIndex i = ReadingFrame $ (toInt0 i `mod` 3) + 1
+
diff --git a/Biobase/Types/Ring.hs b/Biobase/Types/Ring.hs
deleted file mode 100644
--- a/Biobase/Types/Ring.hs
+++ /dev/null
@@ -1,22 +0,0 @@
-
--- | Algebraic ring structure. Very similar to others found throughout hackage.
---
--- TODO maybe use on of the already-written packages?
-
-module Biobase.Types.Ring where
-
-
-
--- | Define the basic operations on a ring.
-
-class (Eq a, Ord a) => Ring a where
-  (.+.), (.*.) :: a -> a -> a
-  (.^.) :: a -> Int -> a
-  (.^^.) :: a -> Double -> a
-  neg :: a -> a
-  one, zero :: a
-  isZero :: a -> Bool -- ^ ==zero does not work well for min-plus
-  infixl 6 .+.
-  infixl 7 .*.
-  infixr 8 .^.
-  infixr 8 .^^.
diff --git a/Biobase/Types/Score.hs b/Biobase/Types/Score.hs
deleted file mode 100644
--- a/Biobase/Types/Score.hs
+++ /dev/null
@@ -1,48 +0,0 @@
-
-{-# LANGUAGE StandaloneDeriving #-}
-{-# LANGUAGE MultiParamTypeClasses #-}
-{-# LANGUAGE GeneralizedNewtypeDeriving #-}
-
-module Biobase.Types.Score where
-
-import qualified Data.Vector.Unboxed as VU
-import qualified Data.Vector.Generic as VG
-import qualified Data.Vector.Generic.Mutable as VGM
-import Data.Primitive.Types
-
-import Biobase.Types.Ring
-
-
-
--- | Some default instances. Left out the Num one, so that you have to
--- explicitly instanciate if you want to go around the Ring structure.
-
-newtype Score = Score {unScore :: Int}
-  deriving (Show, Read, Eq, Ord)
-
-
-
--- | Ring operations over Score values.
-
-instance Ring Score where
-  (Score a) .+. (Score b) = Score $ a `min` b
-  {-# INLINE (.+.) #-}
-  (Score a) .*. (Score b) = Score $ a + b
-  {-# INLINE (.*.) #-}
-  neg (Score a) = Score $ negate a
-  {-# INLINE neg #-}
-  one = Score 0
-  {-# INLINE one #-}
-  zero = Score 10000000
-  {-# INLINE zero #-}
-  isZero (Score a) = a >= 1000000
-  {-# INLINE isZero #-}
-
-
-
--- * Vector instances.
-
-deriving instance VGM.MVector VU.MVector Score
-deriving instance VG.Vector VU.Vector Score
-deriving instance VU.Unbox Score
-deriving instance Prim Score
diff --git a/Biobase/Types/Shape.hs b/Biobase/Types/Shape.hs
new file mode 100644
--- /dev/null
+++ b/Biobase/Types/Shape.hs
@@ -0,0 +1,202 @@
+
+-- | Shape abstractions of structures.
+--
+-- Shapes do not preserve sizes of structures (say unpaired regions or stem
+-- length). As such, distance measures provided here are to be used carefully!
+--
+-- TODO consider how to handle the different shape levels. One option would be
+-- to phantom-type everything.
+
+module Biobase.Types.Shape where
+
+import           Control.DeepSeq
+import           Control.Lens
+import           Control.Monad.Error.Class
+import           Control.Monad (foldM,unless)
+import           Data.ByteString (ByteString)
+import           Data.Data
+import           Data.List (foldl1')
+import           Data.Monoid ((<>))
+import           Data.Set (Set)
+import           GHC.Generics (Generic)
+import qualified Data.ByteString.Char8 as BS8
+import qualified Data.List as L
+import qualified Data.Set as Set
+
+import           Data.Forest.StructuredPaired
+
+import qualified Biobase.Types.Structure as TS
+
+
+
+-- | Shape levels are hardcoded according to their specification.
+--
+-- TODO Allow compile-time check on accepted shape levels?
+
+data ShapeLevel
+  = SL1
+  | SL2
+  | SL3
+  | SL4
+  | SL5
+  deriving (Eq,Ord,Show,Read,Data,Typeable,Generic)
+
+instance NFData ShapeLevel
+
+
+
+-- | The type of RNA shapes. Keeps the type 
+
+data RNAshape
+  = RNAshape
+    { _rnashapelevel  ∷ !ShapeLevel
+    -- ^ The type of shape encoded here.
+    , _rnashape       ∷ !ByteString
+    -- ^ The actual shape as a string.
+    }
+  deriving (Eq,Ord,Show,Read,Data,Typeable,Generic)
+makeLenses ''RNAshape
+
+instance NFData RNAshape
+
+
+
+-- | Given a compactified 'SPForest', creates a shape forest of the given level.
+--
+--
+--
+-- TODO needs newtyping
+
+shapeForest
+  ∷ ShapeLevel
+  → SPForest ByteString ByteString
+  → SPForest Char Char
+shapeForest = preStem
+  where
+    -- | In @preStem@, we aim to close in on the next stem. @SPE@ means that we
+    -- reached an end in a stem.
+    preStem s SPE = SPE
+    -- | The start of a tree structure. The forest is compact, which means that
+    -- the element in @xs@ is, by definition, not a continuation of a stack.
+    preStem s (SPT _ xs _) = SPT '[' (inStem s xs) ']'
+    -- |
+    preStem s spr@(SPR rs) = inStem s spr -- = error $ "preStem/SPR " ++ show rs
+    -- |
+    preStem s (SPJ xs)
+      | [x] ← xs  = preStem s x
+      -- left bulge
+      | [l@SPR{},x@SPT{}] ← xs = if s <= SL2 then (SPJ [SPR '_', preStem s x]) else preStem s x
+      -- right bulge
+      | [x@SPT{},r@SPR{}] ← xs = if s <= SL2 then (SPJ [preStem s x, SPR '_']) else preStem s x
+      | otherwise = SPJ $ map (preStem s) xs -- error $ "preStem/SPJ " ++ show xs
+    --
+    -- | After a stem, there could be an @SPE@ element.
+    inStem s SPE = SPE
+    -- | This case happens when eradicating unstructured regions with high
+    -- abstraction levels.
+    inStem s (SPT _ xs _) = inStem s xs
+    inStem s (SPR rs)
+      | s == SL1  = SPR '_' -- = error $ "inStem / SPR " ++ show rs
+      | otherwise = SPE
+    inStem s (SPJ xs)
+      | [x] ← xs = error "x"
+      -- left bulge
+      | [l@SPR{},x] ← xs = if s <= SL3 then preStem s (SPJ xs) else inStem s x
+      -- right bulge
+      | [x,r@SPR{}] ← xs = if s <= SL3 then preStem s (SPJ xs) else inStem s x
+      -- interior loop
+      | [l@SPR{},x,r@SPR{}] ← xs = if s == SL5 then inStem s x else preStem s (SPJ xs)
+--      | s == SL1  = error $ "inStem / SPJ " ++ show xs
+--      | s == SL2  = error $ "inStem / SPJ " ++ show xs
+      -- multibranched loop
+      | otherwise = SPJ $ map (preStem s) xs
+
+rnass2shape lvl s = shapeForestshape lvl . shapeForest lvl . TS.compactifySPForest
+                . either (\e → error $ show (e,s)) id . TS.rnassSPForest $ s
+
+-- | turn into unit test. also reverse of the input should give reverse shape!
+-- this then gives a quickcheck test, reversing the input should reverse the shape
+--
+-- TODO requires generating secondary structures via @Arbitrary@.
+
+test lvl = shapeForestshape lvl . shapeForest lvl $ TS.compactifySPForest $ either error id $ TS.rnassSPForest $ TS.RNAss "(((((...(((..(((...))))))...(((..((.....))..)))))))).."
+
+{-
+shapeForest SL5 = go
+  where
+    go SPE = SPE
+    go (SPT _ xs _)
+      | SPE ← xs, SPR{} ← xs, [] ← ts = SPT '[' SPE ']'
+      | [t] ← ts = go t
+      | otherwise = SPT '[' (SPJ $ map go ts) ']'
+      where (SPJ ys) = xs
+            ts = [ t | t@SPT{} ← ys ]
+    -- should only happen on a single unfolded structure
+    go (SPR _) = SPR '_'
+    go (SPJ xs)
+      | [] ← ts   = SPR '_'
+      | [t] ← ts  = go t
+      | otherwise = SPJ $ map go ts
+      where ts = [ t | t@SPT{} ← xs ]
+    go xs = error $ show xs ++ " should no be reached"
+-}
+
+-- | 
+
+shapeForestshape
+  ∷ ShapeLevel
+  → SPForest Char Char
+  → RNAshape
+shapeForestshape lvl = RNAshape lvl . go
+  where
+    go SPE = ""
+    go (SPT l x r) = BS8.singleton l <> go x <> BS8.singleton r
+    go (SPJ xs   ) = mconcat $ map go xs
+    go (SPR   x  ) = BS8.singleton x -- error "should not be reached" -- BS8.singleton x
+
+generateShape ∷ ShapeLevel → TS.RNAss → RNAshape
+generateShape = undefined
+
+
+-- * Distance measures on the shape string itself.
+
+-- | Wrapper for string-positional shapes. Intentionally chosen long name.
+
+data RNAshapepset = RNAshapepset { _rnashapepsetlevel ∷ ShapeLevel, _rnashapepset ∷ Set (Int,Int) }
+  deriving (Read,Show,Eq,Ord,Generic)
+makeLenses ''RNAshapepset
+
+instance NFData RNAshapepset
+
+-- | Transform an 'RNAss' into a set of base pairs @(i,j)@. The pairs are
+-- 0-based.
+
+rnashapePairSet
+  ∷ (MonadError String m)
+  ⇒ RNAshape
+  → m RNAshapepset
+rnashapePairSet (RNAshape lvl s2) = do
+  let go (set,ks  ) (i,'[') = return (set,i:ks)
+      go (set,i:is) (j,']') = return (Set.insert (i,j) set, is)
+      go (set,[]  ) (j,']') = throwError $ "unequal brackets in \"" ++ BS8.unpack s2 ++ "\" at position: " ++ show j
+      go (set,ks  ) (_,'_') = return (set,ks)
+  (set,ss) ← foldM go (Set.empty,[]) . L.zip [0..] $ BS8.unpack s2
+  unless (null ss) $ throwError $ "unequal brackets in \"" ++ BS8.unpack s2 ++ "\" with opening bracket(s): " ++ show ss
+  return $ RNAshapepset lvl set
+{-# Inlinable rnashapePairSet #-}
+
+-- | RNA pair set, but a transformation error calls @error@.
+
+rnassPairSet' ∷ RNAshape → RNAshapepset
+rnassPairSet' = either error id . rnashapePairSet
+
+-- | Calculates the number of different base pairs betwwen two structures.
+--
+-- TODO error out on different shape levels
+
+shapePairDist ∷ RNAshapepset → RNAshapepset → Int
+shapePairDist (RNAshapepset lvl1 p1) (RNAshapepset lvl2 p2) = Set.size z1 + Set.size z2
+  where i = Set.intersection p1 p2
+        z1 = p1 `Set.difference` i
+        z2 = p2 `Set.difference` i
+
diff --git a/Biobase/Types/Strand.hs b/Biobase/Types/Strand.hs
new file mode 100644
--- /dev/null
+++ b/Biobase/Types/Strand.hs
@@ -0,0 +1,147 @@
+
+-- | Strand information. A newtyped version, complete with serialization,
+-- pattern synonyms, being a @PrimitiveArray@ index type, etc. The strand
+-- information includes @+@, @-@, as well as the (GFF3) @.@ not stranded, and
+-- @?@ for unknown strand information.
+--
+-- TODO will be expanded to encode biological sense information more clearly:
+-- <http://en.wikipedia.org/wiki/Sense_%28molecular_biology%29>.
+
+module Biobase.Types.Strand where
+
+import Control.DeepSeq
+import Control.Lens hiding (Index)
+import Control.Monad (guard)
+import Data.Aeson
+import Data.Binary
+import Data.Data (Data)
+import Data.Hashable (Hashable)
+import Data.Serialize (Serialize)
+import Data.Typeable (Typeable)
+import Data.Vector.Fusion.Stream.Monadic (Step(..), flatten)
+import Data.Vector.Unboxed.Deriving
+import GHC.Generics
+import Test.QuickCheck
+import Text.Printf
+
+import Data.PrimitiveArray.Index.Class
+
+
+
+-- | Encode strand information. 'PlusStrand' is defined as the strand encoded
+-- in, say, the FASTA file. 'MinusStrand' hence is the reverse complement.
+
+newtype Strand = Strand { getStrand :: Int }
+  deriving (Eq,Ord,Generic,Data,Typeable)
+
+instance Show Strand where
+  show PlusStrand    = "PlusStrand"
+  show MinusStrand   = "MinusStrand"
+  show NotStranded   = "NotStranded"
+  show UnknownStrand = "UnknownStrand"
+
+instance Read Strand where
+  readsPrec _ xs = do
+    (pm,s) <- lex xs
+    case pm of
+      "PlusStrand" -> return (PlusStrand, s)
+      "MinusStrand" -> return (MinusStrand, s)
+      "NotStranded" -> return (NotStranded, s)
+      "UnknownStrand" -> return (UnknownStrand, s)
+      [x] | x `elem` ("+Pp" :: String) -> return (PlusStrand,s)
+          | x `elem` ("-Mm" :: String) -> return (MinusStrand,s)
+          | x `elem` ("."   :: String) -> return (NotStranded,s)
+          | x `elem` ("?"   :: String) -> return (UnknownStrand,s)
+      _ -> []
+
+instance Bounded Strand where
+  minBound = PlusStrand
+  maxBound = UnknownStrand
+
+instance Enum Strand where
+  succ (Strand k)
+    | k <  0 = error "succ undefined strand"
+    | k == 3 = error "succ UnknownStrand"
+    | k >  3 = error "succ undefined strand"
+    | otherwise = Strand (k+1)
+  pred (Strand k)
+    | k <  0 = error "pred undefined strand"
+    | k == 0 = error "pred UnknownStrand"
+    | k >  3 = error "pred undefined strand"
+    | otherwise = Strand (k-1)
+  toEnum i | i>=0 && i<=3 = Strand i
+  toEnum i                = error $ "toEnum (Strand)" ++ show i
+  fromEnum = getStrand
+
+instance Reversing Strand where
+  reversing PlusStrand  = MinusStrand
+  reversing MinusStrand = PlusStrand
+  reversing x           = x
+
+pattern PlusStrand    = Strand 0
+pattern MinusStrand   = Strand 1
+pattern NotStranded   = Strand 2
+pattern UnknownStrand = Strand 3
+
+-- TODO Sense and Antisense are somewhat different
+
+--pattern Sense     = P
+--pattern AntiSense = M
+
+instance Binary    Strand
+instance Serialize Strand
+instance ToJSON    Strand
+instance FromJSON  Strand
+instance Hashable  Strand
+instance NFData    Strand
+
+derivingUnbox "Strand"
+  [t| Strand -> Int |]  [| getStrand |]  [| Strand |]
+
+instance Index Strand where
+  newtype (LimitType Strand) = LtStrand Strand
+  linearIndex _ (Strand z) = z
+  {-# INLINE linearIndex #-}
+  size (LtStrand (Strand h)) = h + 1
+  {-# INLINE size #-}
+  inBounds (LtStrand (Strand h)) (Strand x) = 0<=x && x<=h
+  {-# INLINE inBounds #-}
+  zeroBound = Strand 0
+  {-# Inline zeroBound #-}
+  zeroBound' = LtStrand zeroBound
+  {-# Inline zeroBound' #-}
+  totalSize (LtStrand (Strand k)) = [ fromIntegral (fromEnum k + 1) ]
+  {-# Inline totalSize #-}
+  fromLinearIndex _ = Strand
+  {-# Inline [0] fromLinearIndex #-}
+  showBound (LtStrand k) = ["LtStrand " ++ show k]
+  showIndex (Strand k) = ["Strand " ++ show k]
+
+instance IndexStream z => IndexStream (z:.Strand) where
+  streamUp (ls:..LtStrand (Strand lf)) (hs:..LtStrand (Strand ht)) = flatten mk step $ streamUp ls hs
+    where mk z = return (z,lf)
+          step (z,k)
+            | k > ht    = return $ Done
+            | otherwise = return $ Yield (z:.Strand k) (z,k+1)
+          {-# Inline [0] mk   #-}
+          {-# Inline [0] step #-}
+  {-# Inline streamUp #-}
+  streamDown (ls:..LtStrand (Strand lf)) (hs:..LtStrand (Strand ht)) = flatten mk step $ streamDown ls hs
+    where mk z = return (z,ht)
+          step (z,k)
+            | k < lf    = return $ Done
+            | otherwise = return $ Yield (z:.Strand k) (z,k-1)
+          {-# Inline [0] mk   #-}
+          {-# Inline [0] step #-}
+  {-# Inline streamDown #-}
+
+-- instance IndexStream Strand
+
+instance Arbitrary Strand where
+  arbitrary = do
+    b <- choose (0,3)
+    return $ Strand b
+  shrink (Strand j)
+    | 0<j = [Strand $ j-1]
+    | otherwise = []
+
diff --git a/Biobase/Types/Structure.hs b/Biobase/Types/Structure.hs
new file mode 100644
--- /dev/null
+++ b/Biobase/Types/Structure.hs
@@ -0,0 +1,225 @@
+
+-- | Wrappers for structural data. Encoded as bytestrings. This differs from
+-- @BiobaseXNA@, where specialized encodings are used. These structures are
+-- supposedly "short", they need to fit into a strict bytestring.
+--
+-- TODO Consider where to move each type. There are merge possibilities between
+-- BiobaseXNA and BiobaseTypes.
+--
+-- TODO QuickCheck @Arbitrary@ for @RNAss@.
+
+module Biobase.Types.Structure where
+
+import           Control.Applicative
+import           Control.DeepSeq
+import           Control.Lens
+import           Control.Monad.Error.Class
+import           Control.Monad (foldM,unless)
+import           Data.Attoparsec.ByteString.Char8
+import           Data.Attoparsec.Combinator
+import           Data.Bifunctor (second)
+import           Data.ByteString (ByteString)
+import           Data.Data
+import           Data.List (foldl1',foldl')
+import           Data.Monoid ((<>))
+import           Data.Set (Set)
+import           GHC.Generics (Generic)
+import qualified Data.ByteString.Char8 as BS8
+import qualified Data.List as L
+import qualified Data.Set as S
+import qualified Data.Set as Set
+import qualified Data.Vector.Unboxed as VU
+import qualified Test.QuickCheck as Q
+
+import           Data.Forest.StructuredPaired
+
+
+
+-- | Secondary structure using @()@ for paired elements, and @.@ for unpaired
+-- ones. It is assumed that the @()@ match up. These structures from a Monoid.
+
+newtype RNAss = RNAss { _rnass ∷ ByteString }
+  deriving (Eq,Ord,Show,Read,Data,Typeable,Generic,Semigroup,Monoid)
+makeLenses ''RNAss
+
+instance NFData RNAss
+
+-- | Ensemble structure encoding. *Very* different type ctor name chosen! The
+-- structure of this string makes verification much more complicated.
+--
+-- TODO describe encoding used by RNAfold for the ensemble string.
+
+newtype RNAensembleStructure = RNAes { _rnaes ∷ ByteString }
+  deriving (Eq,Ord,Show,Read,Data,Typeable,Generic)
+makeLenses ''RNAensembleStructure
+
+instance NFData RNAensembleStructure
+
+-- | Cofolded structure.
+
+data RNAds = RNAds
+  { _rnadsL ∷ !ByteString
+  , _rnadsR ∷ !ByteString
+  }
+  deriving (Eq,Ord,Show,Read,Data,Typeable,Generic)
+makeLenses ''RNAds
+
+instance NFData RNAds
+
+-- | A Prism that turns ByteStrings with a single @&@ into @RNAds@.
+
+rnads ∷ Prism' ByteString RNAds
+rnads = prism (\(RNAds l r) → BS8.concat [l, "&", r])
+              (\s → case BS8.split '&' s of [l,r] → Right (RNAds l r) ; _ → Left s)
+{-# Inline rnads #-}
+
+-- | Isomorphism from @RNAds@ to @(RNAss,RNAss)@. The @RNAss@ are only
+-- legal if taken both: @rnassFromDimer . both@.
+
+rnads2rnassPair ∷ Iso' RNAds (RNAss, RNAss)
+rnads2rnassPair = iso (\(RNAds l r) → (RNAss l, RNAss r)) (\(RNAss l, RNAss r) → RNAds l r)
+{-# Inline rnads2rnassPair #-}
+
+-- | Try to create a dimeric structure.
+
+mkRNAds ∷ (Monad m, MonadError RNAStructureError m) ⇒ ByteString → m RNAds
+mkRNAds q = BS8.split '&' q & \case
+    [l,r] → do
+      -- TODO can still fail with unmatched brackets.
+      return $ RNAds
+        { _rnadsL = l
+        , _rnadsR = r
+        }
+    _     → throwError $ RNAStructureError "mkRNAds: not a dimer" q
+{-# Inline mkRNAds #-}
+
+-- | Capture what might be wrong with the RNAss.
+
+data RNAStructureError = RNAStructureError
+  { _rnaStructureError  ∷ String
+  , _rnaOffender        ∷ ByteString
+  }
+  deriving (Show,Generic)
+
+instance NFData RNAStructureError
+
+-- | Verifies that the given RNAss is properly formatted. Otherwise, error out.
+--
+-- TODO Implement! Check with BiobaseXNA and the stack effort in there. This
+-- might influence if the verification goes into BiobaseXNA and happens via an
+-- @Iso'@.
+
+verifyRNAss ∷ (Monad m, MonadError RNAStructureError m) ⇒ RNAss → m RNAss
+verifyRNAss ss = do
+  return ss
+
+-- | The set of nucleotide pairs, together with the sequence length.
+
+data RNApset = RNApset
+  { _rnapset      ∷ !(Set (Int,Int))
+    -- ^ the set of nucleotide pairs.
+  , _rnapsetSLen  ∷ !Int
+    -- ^ length of the underlying nucleotide sequence.
+  }
+  deriving (Read,Show,Eq,Ord,Generic)
+makeLenses ''RNApset
+
+instance NFData RNApset
+
+-- | Transform an 'RNAss' into a set of base pairs @(i,j)@. The pairs are
+-- 0-based.
+
+rnassPairSet
+  ∷ (MonadError String m)
+  ⇒ RNAss
+  → m RNApset
+rnassPairSet (RNAss s2) = do
+  let go (set,ks  ) (i,'(') = return (set,i:ks)
+      go (set,i:is) (j,')') = return (Set.insert (i,j) set, is)
+      go (set,[]  ) (j,')') = throwError $ "unequal brackets in \"" ++ BS8.unpack s2 ++ "\" at position: " ++ show j
+      go (set,ks  ) (_,'.') = return (set,ks)
+  (set,ss) ← foldM go (Set.empty,[]) . L.zip [0..] $ BS8.unpack s2
+  unless (null ss) $ throwError $ "unequal brackets in \"" ++ BS8.unpack s2 ++ "\" with opening bracket(s): " ++ show ss
+  return $ RNApset set (BS8.length s2)
+{-# Inlinable rnassPairSet #-}
+
+-- | Genereate a simple structured/paired forest from a secondary structure string.
+
+rnassSPForest
+  ∷ (MonadError String m)
+  ⇒ RNAss
+  → m (SPForest ByteString Char)
+rnassSPForest (RNAss s2) = either throwError return $ parseOnly (manyElems <* endOfInput) s2
+  where
+    tree = SPT <$> char '(' <*> someElems <*> char ')' <?> "SPT"
+    unpaired  = SPR <$> takeWhile1 (=='.') <?> "SPR"
+    someElems = SPJ <$> many1 (tree <|> unpaired) <?> "many1 SPT / SPR"
+    manyElems = (\case {[] → SPE; xs → SPJ xs}) <$> many  (tree <|> unpaired) <?> "many0 SPT / SPR"
+{-# Inlinable rnassSPForest #-}
+
+-- | Compactify such an SPForest. This means that all stems are now represented
+-- by a single 'SPT' data constructor.
+
+compactifySPForest
+  ∷ SPForest ByteString Char
+  → SPForest ByteString ByteString
+compactifySPForest = go . second BS8.singleton
+  where go SPE      = SPE
+        go (SPR x)  = SPR x
+        go (SPJ xs) = SPJ (map go xs)
+        go (SPT l (SPJ [x]) r) = go $ SPT l x r
+        go (SPT l (SPT l' t r') r) = go $ SPT (l <> l') t (r' <> r)
+        go (SPT l t             r) = SPT l (go t) r
+
+-- | RNA pair set, but a transformation error calls @error@.
+
+rnassPairSet' ∷ RNAss → RNApset
+rnassPairSet' = either error id . rnassPairSet
+
+rnapsetRNAss ∷ RNApset → RNAss
+rnapsetRNAss (RNApset ps l) = RNAss $ BS8.pack $ VU.toList xs
+  where xs = VU.replicate l '.' VU.// ls VU.// rs
+        ls = L.map ((,'(') . fst) $ S.toList ps
+        rs = L.map ((,')') . snd) $ S.toList ps
+
+-- | Calculates the number of different base pairs between two structures. This
+-- ignores the length of the underlying sequences.
+
+pairDist ∷ RNApset → RNApset → Int
+pairDist (RNApset p1 _) (RNApset p2 _) = Set.size z1 + Set.size z2
+  where i = Set.intersection p1 p2
+        z1 = p1 `Set.difference` i
+        z2 = p2 `Set.difference` i
+
+
+
+-- * Arbitrary instances. This only creates legal instances, but does *not*
+-- take into account ViennaRNA rules like three unpaired nucleotides in the
+-- hairpin.
+--
+-- TODO @shrink@ is a bit more complicated, but can be done via a set of pairs.
+
+instance Q.Arbitrary RNApset where
+  arbitrary = do
+    -- Given left and right bounds, create pairs.
+    let go ∷ Int → Int → Q.Gen (Set (Int,Int))
+        go l r
+          | l >= r    = return S.empty
+          | otherwise = do
+            -- right border of stack
+            c ∷ Int ← Q.oneof [ Q.choose (l+1,r)  -- wide jump
+                              , Q.choose (l+1, min r $ l+20)  -- short jump
+                              ]
+            -- with @1..10@ stack length
+            z ∷ Int ← Q.choose (0,5)
+            let stack = S.fromList [(l+k,c-k) | k ← [0..z-1], l+k+1 < c-k]
+            right ← go (c+1) r
+            return $ S.union stack right
+    -- generate RNA structures between 0 and 100 nucleotides.
+    l ∷ Int ← Q.choose (0,199)
+    s ← go 0 l
+    return $ RNApset s (l+1)
+
+instance Q.Arbitrary RNAss where
+  arbitrary = rnapsetRNAss <$> Q.arbitrary
+
diff --git a/Biobase/Types/Taxonomy.hs b/Biobase/Types/Taxonomy.hs
new file mode 100644
--- /dev/null
+++ b/Biobase/Types/Taxonomy.hs
@@ -0,0 +1,71 @@
+
+-- | Biological classification of species.
+
+module Biobase.Types.Taxonomy where
+
+import Control.DeepSeq
+import Data.Aeson
+import Data.Binary
+import Data.Hashable (Hashable, hashWithSalt)
+import Data.Primitive.Types
+import Data.Serialize
+import Data.Text (Text)
+import Data.Vector.Binary
+import Data.Vector.Serialize
+import Data.Vector.Unboxed.Deriving
+import Data.Vector (Vector)
+import GHC.Generics (Generic)
+
+import Biobase.Types.Accession (Accession,Species)
+import Biobase.Types.Names (SpeciesName, TaxonomicRank)
+
+
+
+-- | Taxonomic classification. @Enum@ together with a final @Unknown@ is
+-- somewhat fishy.
+--
+-- TODO What should the order be? Kingdom > Species or Kingdom < Species?
+
+data Classification
+  = Kingdom
+  | Phylum
+  | Class
+  | Order
+  | SubOrder
+  | Family
+  | Genus
+  | Species
+  | Unknown
+  deriving (Eq,Ord,Read,Show,Enum,Generic)
+
+instance Binary    Classification
+instance FromJSON  Classification
+instance Hashable  Classification
+instance Serialize Classification
+instance ToJSON    Classification
+instance NFData    Classification
+
+derivingUnbox "Classification"
+  [t| Classification -> Int |] [| fromEnum |] [| toEnum |]
+
+
+
+-- | A somewhat generic representation of a species within a taxonomic
+-- context.
+
+data Taxon = Taxon
+  { species         :: !SpeciesName                             -- ^ the full, formal name of a species
+  , accession       :: !(Accession Species)                     -- ^ the accession for the species (or @""@ if unknown)
+  , classification  :: !(Vector (TaxonomicRank,Classification)) -- ^ vector with classification information
+  }
+  deriving (Eq,Read,Show,Generic)
+
+instance Binary    Taxon
+instance FromJSON  Taxon
+instance Serialize Taxon
+instance ToJSON    Taxon
+instance NFData    Taxon
+
+instance Hashable Taxon where
+  hashWithSalt h (Taxon s a _) = hashWithSalt h (s,a)
+
diff --git a/BiobaseTypes.cabal b/BiobaseTypes.cabal
--- a/BiobaseTypes.cabal
+++ b/BiobaseTypes.cabal
@@ -1,37 +1,150 @@
+cabal-version:  2.2
 name:           BiobaseTypes
-version:        0.0.2.2
-author:         Christian Hoener zu Siederdissen
-maintainer:     choener@tbi.univie.ac.at
-copyright:      Christian Hoener zu Siederdissen, 2010
-category:       Bioinformatics
-synopsis:       (deprecated) Ring class, with several instances.
-license:        GPL-3
+version:        0.2.1.0
+author:         Christian Hoener zu Siederdissen, 2015 - 2021
+copyright:      Christian Hoener zu Siederdissen, 2015 - 2021
+homepage:       https://github.com/choener/BiobaseTypes
+bug-reports:    https://github.com/choener/BiobaseTypes/issues
+maintainer:     choener@bioinf.uni-leipzig.de
+category:       Data Structures, Bioinformatics
+license:        BSD-3-Clause
 license-file:   LICENSE
 build-type:     Simple
 stability:      experimental
-cabal-version:  >= 1.4.0
+tested-with:    GHC == 8.8, GHC == 8.10, GHC == 9.0
+synopsis:       Collection of types for bioinformatics
 description:
-                Provides an algebraic ring class and instances for Gibbs free
-                energy, partition function probabilities, and scores.
-                Conversion between different entities is provided by a convert
-                function. All entities are ready for the vector library.
+                Types used in a number of bioinformatics libraries.
                 .
-                - Ignore everything except the Ring itself!
+                * linear indices
+                .
+                * energies
+                .
+                * biostring wrappers
 
 
 
-library
-  build-depends:
-    base >=4 && <5,
-    vector >=0.7 && <0.8,
-    primitive >=0.3 && <0.4
+Extra-Source-Files:
+  README.md
+  changelog.md
 
+
+
+common deps
+  build-depends: base                     >= 4.7      &&  < 5.0
+               , aeson                    >= 0.8
+               , attoparsec               >= 0.13
+               , binary                   >= 0.7
+               , bytestring
+               , cereal                   >= 0.4
+               , cereal-text              >= 0.1
+               , cereal-vector            >= 0.2
+               , containers
+               , data-default             >= 0.5
+               , deepseq                  >= 1.4
+               , hashable                 >= 1.2
+               , intern                   >= 0.9
+               , lens                     >= 4.0
+               , mtl
+               , primitive                >= 0.5
+               , QuickCheck               >= 2.7
+               , streaming                >= 0.1
+               , string-conversions       >= 0.4
+               , text                     >= 1.0
+               , text-binary              >= 0.2
+               , utf8-string              >= 1.0
+               , vector                   >= 0.10
+               , vector-binary-instances  >= 0.2
+               , vector-th-unbox          >= 0.2
+               --
+               , bimaps                   == 0.1.0.*
+               , DPutils                  == 0.1.1.*
+               , ForestStructures         == 0.0.1.*
+               , PrimitiveArray           >= 0.10.1.1 && < 0.10.2
+               , SciBaseTypes             == 0.1.1.*
+  default-language:
+    Haskell2010
+  default-extensions: BangPatterns
+                    , DataKinds
+                    , DeriveDataTypeable
+                    , DeriveFoldable
+                    , DeriveGeneric
+                    , DeriveTraversable
+                    , DerivingStrategies
+                    , FlexibleContexts
+                    , FlexibleInstances
+                    , GeneralizedNewtypeDeriving
+                    , KindSignatures
+                    , LambdaCase
+                    , MultiParamTypeClasses
+                    , OverloadedStrings
+                    , PatternSynonyms
+                    , PolyKinds
+                    , RankNTypes
+                    , RecordWildCards
+                    , ScopedTypeVariables
+                    , StandaloneDeriving
+                    , TemplateHaskell
+                    , TypeApplications
+                    , TypeFamilies
+                    , TypeOperators
+                    , TupleSections
+                    , UndecidableInstances
+                    , UnicodeSyntax
+                    , ViewPatterns
+  ghc-options:
+    -O2 -funbox-strict-fields
+
+
+
+library
+  import:
+    deps
   exposed-modules:
-    Biobase.Types.Ring
-    Biobase.Types.Convert
+    Biobase.Types.Accession
+    Biobase.Types.BioSequence
+    Biobase.Types.Bitscore
+    Biobase.Types.Codon
     Biobase.Types.Energy
-    Biobase.Types.Partition
-    Biobase.Types.Score
+    Biobase.Types.Evalue
+    Biobase.Types.Index
+    Biobase.Types.Index.Type
+    Biobase.Types.Location
+    Biobase.Types.Names
+    Biobase.Types.Names.Internal
+    Biobase.Types.Position
+    Biobase.Types.ReadingFrame
+    Biobase.Types.Shape
+    Biobase.Types.Strand
+    Biobase.Types.Structure
+    Biobase.Types.Taxonomy
+    DP.Backtraced.BioSequence
+    DP.Backtraced.Codon
 
-  ghc-options:
-    -O2
+
+
+test-suite properties
+  import:
+    deps
+  type:
+    exitcode-stdio-1.0
+  main-is:
+    properties.hs
+--  ghc-options:
+--    -threaded -rtsopts -with-rtsopts=-N
+  hs-source-dirs:
+    tests
+  build-depends: base
+               , tasty              >= 0.11
+               , tasty-hunit        >= 0.10
+               , tasty-quickcheck   >= 0.8
+               , tasty-th           >= 0.1
+               --
+               , BiobaseTypes
+
+
+
+source-repository head
+  type: git
+  location: git://github.com/choener/BiobaseTypes
+
diff --git a/DP/Backtraced/BioSequence.hs b/DP/Backtraced/BioSequence.hs
new file mode 100644
--- /dev/null
+++ b/DP/Backtraced/BioSequence.hs
@@ -0,0 +1,3 @@
+
+module DP.Backtraced.BioSequence where
+
diff --git a/DP/Backtraced/Codon.hs b/DP/Backtraced/Codon.hs
new file mode 100644
--- /dev/null
+++ b/DP/Backtraced/Codon.hs
@@ -0,0 +1,46 @@
+
+-- | The Backtraced column structure is for codon-based alignments, including
+-- special cases.
+
+module DP.Backtraced.Codon where
+
+import Data.ByteString (ByteString)
+import Data.Vector (Vector)
+import GHC.Generics (Generic)
+
+import Biobase.Types.Codon
+
+
+
+-- | A single 'Backtraced' column. Since such a column will be part of a
+-- @Backtraced (Z:.BtCodon c aa:. ...)@ structure, it is always possible to
+-- extend even further, by having more entries.
+
+data BtCodon c aa
+  -- | A canonical match. A codon and the translated amino acid need to be set.
+  = Match
+    { _codon  ∷ !(Codon c)
+    , _aa     ∷ !aa
+    }
+  -- | A frameshifting match. The vector of frameshifted nucleotides will have
+  -- a number of characters @c@, that encode for a single amino acid.
+  | Frameshift
+    { _frameshift ∷ !(Vector c)
+    , _aa         ∷ !aa
+    }
+  | Insert
+    { _codon  ∷ !(Codon c)
+    , _aa     ∷ !aa
+    }
+  | Shifted
+    { _frameshift ∷ !(Vector c)
+    , _aa         ∷ !aa
+    }
+  | Region
+    { _region     ∷ !(Vector c)
+    , _annotation ∷ !ByteString
+    }
+  | Delete
+    {
+    }
+
diff --git a/LICENSE b/LICENSE
--- a/LICENSE
+++ b/LICENSE
@@ -1,675 +1,30 @@
-              GNU GENERAL PUBLIC LICENSE
-                Version 3, 29 June 2007
-
- 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 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
-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 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 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.
-
-  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.
-
-  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.
-
-  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.
-
-                TERMS AND CONDITIONS
-
-  0. Definitions.
-
-  "This License" refers to version 3 of the GNU General Public License.
-
-  "Copyright" also means copyright-like laws that apply to other kinds of
-works, such as semiconductor masks.
- 
-  "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.
-
-  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 "covered work" means either the unmodified Program or a work based
-on the Program.
-
-  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.
-
-  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.
-
-  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.
-
-  1. Source Code.
-
-  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.
-
-  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.
-
-  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.
-
-  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.
-
-  The Corresponding Source need not include anything that users
-can regenerate automatically from other parts of the Corresponding
-Source.
-
-  The Corresponding Source for a work in source code form is that
-same work.
-
-  2. Basic Permissions.
-
-  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.
-
-  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.
-
-  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.
-
-  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.
-
-  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.
-
-  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.
-  
-  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.
-
-  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.
-
-  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 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.
-
-  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.
-
-  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.
-
-  15. Disclaimer of Warranty.
-
-  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
-
-  If you develop a new program, and you want it to be of the greatest
-possible use to the public, the best way to achieve this is to make it
-free software which everyone can redistribute and change under these terms.
-
-  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
-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
-    it under the terms of the GNU General Public License as published by
-    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,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    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, see <http://www.gnu.org/licenses/>.
-
-Also add information on how to contact you by electronic and paper mail.
+Copyright Christian Hoener zu Siederdissen 2015-2019
 
-  If the program does terminal interaction, make it output a short
-notice like this when it starts in an interactive mode:
+All rights reserved.
 
-    <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.
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
 
-The hypothetical commands `show w' and `show c' should show the appropriate
-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".
+    * Redistributions of source code must retain the above copyright
+      notice, this list of conditions and the following disclaimer.
 
-  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/>.
+    * Redistributions in binary form must reproduce the above
+      copyright notice, this list of conditions and the following
+      disclaimer in the documentation and/or other materials provided
+      with the distribution.
 
-  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>.
+    * Neither the name of Christian Hoener zu Siederdissen nor the names of other
+      contributors may be used to endorse or promote products derived
+      from this software without specific prior written permission.
 
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/README.md b/README.md
new file mode 100644
--- /dev/null
+++ b/README.md
@@ -0,0 +1,21 @@
+![github action: master](https://github.com/choener/BiobaseTypes/actions/workflows/ci.yml/badge.svg?branch=master)
+![github action: hackage](https://github.com/choener/BiobaseTypes/actions/workflows/hackage.yml/badge.svg)
+
+# BiobaseTypes
+
+A bunch of types in use in different modules:
+
+- numerical small and large numbers
+- Gibbs free energy change
+- phantom-typed linear indices: these encode the (rather annoying) habit of
+  computational biology of having both 0-based and 1-based data
+
+
+
+#### Contact
+
+Christian Hoener zu Siederdissen  
+Leipzig University, Leipzig, Germany  
+choener@bioinf.uni-leipzig.de  
+http://www.bioinf.uni-leipzig.de/~choener/  
+
diff --git a/changelog.md b/changelog.md
new file mode 100644
--- /dev/null
+++ b/changelog.md
@@ -0,0 +1,55 @@
+0.2.1.0
+-------
+
+- CI/hackage github actions
+- dependency updates
+
+0.2.0.1
+-------
+
+- minor version bumped due to OrderedBits
+
+0.2.0.0
+-------
+
+- unified treatment of bio sequences with one phantom-typed newtype.
+
+0.1.4.0
+-------
+
+- changes to indexing and others
+- some changes that probably require a bump
+
+0.1.3.0
+-------
+
+- "biostring" wrappers (ByteString based RNA, DNA, ... sequences)
+
+0.1.2.1
+-------
+
+- increased minimal required PrimitiveArray version
+- removed almost all upper bounds
+- removed ghc 7.8.4 as viable compiler
+
+0.1.2.0
+-------
+
+- NFData instances
+
+0.1.1.0
+-------
+
+- added Biobase.Types.Odds module (from the BiobaseBlast package)
+
+0.1.0.0
+-------
+
+- re-introduced the types library for bioinformatics
+- travis-ci integration
+
+0.0.x,y
+-------
+
+- old variant; completely rewritten by now
+
diff --git a/tests/properties.hs b/tests/properties.hs
new file mode 100644
--- /dev/null
+++ b/tests/properties.hs
@@ -0,0 +1,134 @@
+
+module Main where
+
+import           Control.Lens
+import           Debug.Trace
+import qualified Data.ByteString.Char8 as BS8
+import           Test.QuickCheck.Modifiers
+import           Test.QuickCheck.Property ()
+import           Test.Tasty
+import           Test.Tasty.HUnit
+import           Test.Tasty.QuickCheck (testProperty)
+import           Test.Tasty.TH
+
+import           Biobase.Types.BioSequence
+import           Biobase.Types.Bitscore
+import           Biobase.Types.Location
+import           Biobase.Types.Shape
+import           Biobase.Types.Strand
+import           Biobase.Types.Structure
+import           Biobase.Types.Index as I
+
+{-
+
+-- * Bitscore conversions
+
+prop_ProbScore (Positive null) (Positive x) = x ~= score2Prob null (prob2Score null x)
+
+--prop_ScoreProb (Positive null) x = Bitscore x ~= prob2Score null (score2Prob null $ Bitscore x)
+
+
+
+-- * sequence properties
+
+-- complement twice
+
+prop_complement_twice_DNA (dna ∷ BioSequence DNA) = dna == dna^.complement.complement
+
+prop_complement_twice_RNA (rna ∷ BioSequence RNA) = rna == rna^.complement.complement
+
+prop_transcribe_twice_DNA (dna ∷ BioSequence DNA) = dna == dna^.transcribe.transcribe
+
+--prop_transcribe_twice_DNA (rna ∷ RNAseq) = rna == rna^.transcribe.transcribe
+
+-- * shape properties
+
+-- ** unit tests for known rna secondary structures
+
+-- ** quickcheck
+
+-- | reversing a secondary structure means reversing the shape
+
+prop_StructureShape_5_Reverse = fun_StructureShape_k_Reverse SL5
+prop_StructureShape_4_Reverse = fun_StructureShape_k_Reverse SL4
+prop_StructureShape_3_Reverse = fun_StructureShape_k_Reverse SL3
+prop_StructureShape_2_Reverse = fun_StructureShape_k_Reverse SL2
+prop_StructureShape_1_Reverse = fun_StructureShape_k_Reverse SL1
+
+fun_StructureShape_k_Reverse lvl rnass@(RNAss s2)
+  | shp == fshp = True
+  | otherwise = traceShow (s2,shp,rshp,fshp) False
+  where shp  = rnass2shape lvl rnass
+        rshp = rnass2shape lvl $ RNAss $ BS8.map flp $ BS8.reverse s2
+        fshp = over rnashape (BS8.map flp . BS8.reverse) rshp
+        flp '(' = ')'
+        flp ')' = '('
+        flp '[' = ']'
+        flp ']' = '['
+        flp x   = x
+
+prop_FwdLocationPlusTake (NonNegative (p ∷ Int), NonNegative (l ∷ Int), NonNegative (k ∷ Int))
+  | check       = True
+  | otherwise   = traceShow (p,l,k,fwdloc,taken,manual) check
+  where fwdloc  = FwdLocation PlusStrand (I.index p) l
+        check   = taken == manual
+        taken   = fwdLocationTake k fwdloc
+        manual  = FwdLocation PlusStrand (I.index p) (max 0 $ min l k)
+
+prop_FwdLocationPlusDrop (NonNegative (p ∷ Int), NonNegative (l ∷ Int), NonNegative (k ∷ Int))
+  | check       = True
+  | otherwise   = traceShow (p,l,k,fwdloc,dropped,manual) check
+  where fwdloc  = FwdLocation PlusStrand (I.index p) l
+        check   = dropped == manual
+        dropped = fwdLocationDrop k fwdloc
+        manual  = FwdLocation PlusStrand (I.index $ p + min l k) (max 0 $ l-k)
+
+-- | Given a BioSequenceWindow, and different takes and drops, check wether what we have corresponds to what we want
+
+case_bswTakeDrop ∷ Assertion
+case_bswTakeDrop = do
+  let wp = BioSequenceWindow @"DNA" @DNA "test" 1 "ACGTAC" 3 (FwdLocation PlusStrand 0 6)
+      wm = BioSequenceWindow @"DNA" @DNA "test" 3 "CATGCA" 1 (FwdLocation MinusStrand 0 6)
+  --
+  bswTake 0 wp @?= BioSequenceWindow "test" 0 ""       0 (FwdLocation PlusStrand 0 0)
+  bswTake 1 wp @?= BioSequenceWindow "test" 1 "A"      0 (FwdLocation PlusStrand 0 1)
+  bswTake 2 wp @?= BioSequenceWindow "test" 1 "AC"     0 (FwdLocation PlusStrand 0 2)
+  bswTake 6 wp @?= BioSequenceWindow "test" 1 "ACGTAC" 3 (FwdLocation PlusStrand 0 6)
+  --
+  bswDrop 0 wp @?= BioSequenceWindow "test" 1 "ACGTAC" 3 (FwdLocation PlusStrand 0 6)
+  bswDrop 1 wp @?= BioSequenceWindow "test" 0  "CGTAC" 3 (FwdLocation PlusStrand 1 5)
+  bswDrop 6 wp @?= BioSequenceWindow "test" 0       "" 0 (FwdLocation PlusStrand 6 0)
+  --
+  bswTake 0 wm @?= BioSequenceWindow "test" 0 ""       0 (FwdLocation MinusStrand 6 0)
+  bswTake 1 wm @?= BioSequenceWindow "test" 1 "C"      0 (FwdLocation MinusStrand 5 1)
+  bswTake 2 wm @?= BioSequenceWindow "test" 2 "CA"     0 (FwdLocation MinusStrand 4 2)
+  bswTake 3 wm @?= BioSequenceWindow "test" 3 "CAT"    0 (FwdLocation MinusStrand 3 3)
+  bswTake 4 wm @?= BioSequenceWindow "test" 3 "CATG"   0 (FwdLocation MinusStrand 2 4)
+  bswTake 5 wm @?= BioSequenceWindow "test" 3 "CATGC"  0 (FwdLocation MinusStrand 1 5)
+  bswTake 6 wm @?= BioSequenceWindow "test" 3 "CATGCA" 1 (FwdLocation MinusStrand 0 6)
+  --
+  bswDrop 0 wm @?= BioSequenceWindow "test" 3 "CATGCA" 1 (FwdLocation MinusStrand 0 6)
+  bswDrop 1 wm @?= BioSequenceWindow "test" 2  "ATGCA" 1 (FwdLocation MinusStrand 0 5)
+  bswDrop 2 wm @?= BioSequenceWindow "test" 1   "TGCA" 1 (FwdLocation MinusStrand 0 4)
+  bswDrop 5 wm @?= BioSequenceWindow "test" 0      "A" 1 (FwdLocation MinusStrand 0 1)
+  bswDrop 6 wm @?= BioSequenceWindow "test" 0       "" 0 (FwdLocation MinusStrand 0 0)
+  --
+  -- TODO consider having [take,take,drop,drop], generate all permutations;
+  -- they should all yield the same result.
+  --
+
+
+
+
+-- * generic stuff
+
+a ~= b = abs (b-a) <= 10e-6
+
+main :: IO ()
+main = $(defaultMainGenerator)
+
+-}
+
+main :: IO ()
+main = return ()
+
