module Encoding.LetterToNumber ( encltn , decltn ) where import Data.Char (ord, chr, isAscii, isAlpha, isSpace, isDigit, toUpper, isLatin1) import Data.List (intercalate) import Data.ByteString (ByteString) import qualified Data.ByteString.Char8 as BC charToNumber :: Char -> ByteString charToNumber c | isAlpha c = BC.pack $ show $ ord (toUpper c) - ord 'A' + 1 | isSpace c = BC.pack "0" | otherwise = BC.singleton c -- | isAlpha c = show $ ord (toUpper c) - ord 'A' + 1 -- | isSpace c = "0" -- -- | isLatin1 c = [c] -- | otherwise = [c] numberToChar :: String -> Char numberToChar s | s == "0" = ' ' | all isDigit s = chr $ read s + ord 'A' -1 | otherwise = head s -- | otherwise = chr $ read s + ord 'A' - 1 encltn :: ByteString -> ByteString encltn input = go (BC.unpack input) [] where go :: String -> [ByteString] -> ByteString go [] acc = BC.intercalate (BC.pack "-") (reverse acc) go (x:xs) acc -- | not (isAscii x) = go xs (BC.singleton x : acc) | not (isAscii x) = error "Non-ASCII character detected" | otherwise = go xs (charToNumber x : acc) -- encltn input = BC.intercalate (BC.pack "-") $ map charToNumber' $ BC.unpack input -- where -- charToNumber' c -- | not (isAscii c)= BC.singleton c -- | otherwise = charToNumber c decltn :: ByteString -> ByteString decltn input = BC.pack $ concatMap (processSegment . BC.unpack) $ BC.split '-' input where processSegment :: String -> String processSegment s | all isDigit s = [numberToChar s] | otherwise = s -- decltn input = BC.pack $ go $ BC.split '-' input -- where -- go :: [ByteString] -> String -- go [] = [] -- go (x:xs) = -- let str = BC.unpack x -- in numberToChar str ++ go xs -- in case all isDigit str of -- True -> numberToChar str : go xs -- False -> str ++ go xs