module Biobase.Secondary.Pseudoknots where
import           Data.List
import qualified Data.Vector.Unboxed as VU
import Biobase.Secondary.Basepair
class RemovePseudoKnots a where
  removeByCounting :: a -> a
instance RemovePseudoKnots (VU.Vector PairIdx) where
  removeByCounting = VU.force . wrapRemove where
    wrapRemove !ps
      | VU.null cnts = ps 
      | mmx == 0     = ps 
      | otherwise    = wrapRemove $ VU.take pos ps VU.++ VU.drop (pos+1) ps
      where
        cnts = VU.map incomp ps
        mmx = VU.maximum cnts
        Just pos = VU.elemIndex mmx cnts
        incomp (i,j) = VU.length $ VU.filter (\(k,l) -> i<k&&k<j&&j<l || k<i&&i<l&&l<j) ps
instance RemovePseudoKnots [PairIdx] where
  removeByCounting = VU.toList . removeByCounting . VU.fromList
instance RemovePseudoKnots (VU.Vector ExtPairIdx) where
  removeByCounting = VU.force . wrapRemove where
    wrapRemove !ps
      | VU.null cnts = ps 
      | mmx == 0     = ps 
      | otherwise    = wrapRemove $ VU.take pos ps VU.++ VU.drop (pos+1) ps
      where
        cnts = VU.map incomp ps
        mmx = VU.maximum cnts
        Just pos = VU.elemIndex mmx cnts
        incomp ((i,j),_) = VU.length $ VU.filter (\((k,l),_) -> i<k&&k<j&&j<l || k<i&&i<l&&l<j) ps
instance RemovePseudoKnots [ExtPairIdx] where
  removeByCounting = VU.toList . removeByCounting . VU.fromList