{-# LANGUAGE CPP #-}

module Bio.FASTA
  ( module T
  , WritableFastaToken (..)
  , fromFile
  , toFile
  , fastaP
  , fastaLine
  , modificationP
  , Parser
  ) where

import Control.Monad.IO.Class (MonadIO, liftIO)
import Data.Text.IO           (readFile, writeFile)
import System.FilePath        (takeBaseName)
import Text.Megaparsec        (errorBundlePretty, parse)
#if !MIN_VERSION_base(4,13,0)
import Control.Monad.Fail (MonadFail (..))
import Prelude            hiding (fail, readFile, writeFile)
#else
import Prelude hiding (readFile, writeFile)
#endif

import Bio.FASTA.Parser
import Bio.FASTA.Type   as T
import Bio.FASTA.Writer (WritableFastaToken (..), fastaToText)

-- | Reads 'FastaSequence' from given file.
--
fromFile :: (MonadFail m, MonadIO m) => FilePath -> m (Fasta Char)
fromFile :: forall (m :: * -> *).
(MonadFail m, MonadIO m) =>
FilePath -> m (Fasta Char)
fromFile FilePath
f = forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (FilePath -> IO Text
readFile FilePath
f) forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (forall (m :: * -> *) a. MonadFail m => FilePath -> m a
fail forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall s e.
(VisualStream s, TraversableStream s, ShowErrorComponent e) =>
ParseErrorBundle s e -> FilePath
errorBundlePretty) forall (f :: * -> *) a. Applicative f => a -> f a
pure forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall e s a.
Parsec e s a -> FilePath -> s -> Either (ParseErrorBundle s e) a
parse forall a. ParsableFastaToken a => Parser (Fasta a)
fastaP (FilePath -> FilePath
takeBaseName FilePath
f)

-- | Writes 'FastaSequence' to file.
--
toFile :: MonadIO m => Fasta Char -> FilePath -> m ()
toFile :: forall (m :: * -> *). MonadIO m => Fasta Char -> FilePath -> m ()
toFile Fasta Char
s FilePath
f = forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO forall a b. (a -> b) -> a -> b
$ FilePath -> Text -> IO ()
writeFile FilePath
f forall a b. (a -> b) -> a -> b
$ forall a. WritableFastaToken a => Fasta a -> Text
fastaToText Fasta Char
s