{-
   ReadALot.lhs
   Read a lot of files

   2003-10-06

   History:
   03....  ...
-}

> import IO
> import Monad

> inputSet   :: String
> inputSet   = "dir.dat"

> outputFile :: String
> outputFile = "result.dat"

===============================================================================
main
===============================================================================

> main :: IO ()
> main = 
>   do 
>     hInputSet   <- openFile inputSet   ReadMode
>     hOutputFile <- openFile outputFile WriteMode
>     fileNames   <- hGetContents hInputSet
>     allData     <- collectAllData $ lines fileNames 
>     hPutStrLn hOutputFile $ unlines allData   
>     hClose hInputSet
>     hClose hOutputFile


===============================================================================
collectAllData 
Read a list of file names and return file name, first line and last line
of each file in a list
===============================================================================

> collectAllData :: [String] ->      -- A list of filenames
>                   IO [String]      -- A list of results
> 
> collectAllData []                     = return []
> collectAllData (fileName : fileNames) = 
>   do
>     putStrLn $ "Reading: " ++ fileName
>     h <- openFile fileName ReadMode
> 
>     contents <- hGetContents h
>
>     dataFromFile <- 
>       return           $! 
>         parseFile      $ 
>         filter (/= "") $ 
>         lines contents 
>
>     let (firstLine, lastLine) = dataFromFile 

      To force reading of the file before closing, we add a "when" (from 
      the Monad library), with a boolean expression that uses lastLine
      and will always be true:

>     when (length lastLine >= 0) $
>       hClose h
>
>     rest  <- collectAllData fileNames
>
>     return $ fileName : firstLine : lastLine : "" : rest


===============================================================================
parseFile 
Returns the first and the last string of a list of strings, as a tuple
===============================================================================

> parseFile :: [String] -> (String, String)
> parseFile []       = ("", "")
> parseFile [x]      = (x,  "")
> parseFile (x : xs) = (x,  last xs)


