-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.hs
More file actions
68 lines (55 loc) · 2.13 KB
/
Main.hs
File metadata and controls
68 lines (55 loc) · 2.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
module Main where
import System.Environment (getArgs)
import System.Exit (exitFailure, exitSuccess)
import System.IO
import DataTypes
import Processing
import IOHandler
import Utils
-- | Entry point: Parses command line arguments
main :: IO ()
main = do
args <- getArgs
case args of
["-c", inFile, outFile] -> runCompression inFile outFile
["-d", inFile, outFile] -> runDecompression inFile outFile
["-h"] -> printUsage
_ -> printUsage
-- | Prints help message if arguments are wrong
printUsage :: IO ()
printUsage = do
putStrLn "Usage:"
putStrLn " Compress: ./compressor -c <input_file> <output_file>"
putStrLn " Decompress: ./compressor -d <input_file> <output_file>"
putStrLn "Examples:"
putStrLn " ./compressor -c song.txt song.huff"
putStrLn " ./compressor -d song.huff restored.txt"
exitFailure
-- | Compression Logic
runCompression :: FilePath -> FilePath -> IO ()
runCompression inFile outFile = do
putStrLn $ "Reading " ++ inFile ++ "..."
content <- readFileContent inFile
putStrLn "Analyzing frequencies (parallel)..."
let freqs = frequencyCountParallel content
putStrLn "Building Canonical Huffman Tree..."
let rawTree = createTree freqs
let lenTable = getBitLengths rawTree
let canonTable = canonicalCodes lenTable
putStrLn "Encoding and Bit-Packing..."
let (packedBytes, validBits) = encode canonTable content
writeBinary outFile lenTable packedBytes validBits
putStrLn "Compression Complete."
-- | Decompression Logic
runDecompression :: FilePath -> FilePath -> IO ()
runDecompression inFile outFile = do
putStrLn $ "Reading " ++ inFile ++ "..."
(lenTable, packedBytes, validBits) <- readBinary inFile
putStrLn "Reconstructing Tree from Canonical Lengths..."
let canonTable = canonicalCodes lenTable
let tree = rebuildTreeFromCodes canonTable
putStrLn "Decoding..."
let decoded = decode tree packedBytes validBits
putStrLn $ "Writing to " ++ outFile ++ "..."
writeFile outFile decoded
putStrLn "Decompression Complete."