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
69
70
71
72
73
74
75
76
77
78
79
80
81
| module Main where
import Data.Array
import Data.Bits
import Data.List
import Data.Word
import qualified Codec.Compression.Zlib as Z
import qualified Data.ByteString.Lazy as B
be8 :: Word8 -> B.ByteString
be8 x = B.singleton x
be32 :: Word32 -> B.ByteString
be32 x = B.pack [fromIntegral (x `shiftR` sh) | sh <- [24,16,8,0]]
pack :: String -> B.ByteString
pack xs = B.pack $ map (fromIntegral.fromEnum) xs
unpack :: B.ByteString -> String
unpack xs = map (toEnum.fromIntegral) (B.unpack xs)
hdr, iHDR, iDAT, iEND :: B.ByteString
hdr = pack "\137\80\78\71\13\10\26\10"
iHDR = pack "IHDR"
iDAT = pack "IDAT"
iEND = pack "IEND"
chunk :: B.ByteString -> B.ByteString -> [B.ByteString]
chunk tag xs = [be32 (fromIntegral $ B.length xs), dat, be32 (crc dat)]
where dat = B.append tag xs
png :: [[(Int,Int,Int,Int)]] -> B.ByteString
png dat = B.concat $ hdr : concat [ihdr, imgdat ,iend]
where height = fromIntegral $ length dat
width = fromIntegral $ length (head dat)
ihdr = chunk iHDR $ B.concat
[ be32 height
, be32 width
, be8 8
, be8 6
, be8 0
, be8 0
, be8 0 ]
imgdat = chunk iDAT (Z.compress imagedata)
imagedata = B.concat $ map scanline dat
iend = chunk iEND B.empty
scanline :: [(Int,Int,Int,Int)] -> B.ByteString
scanline dat = B.pack (0 : (map fromIntegral $ concatMap (\(r,g,b,a) -> [r,g,b,a]) dat))
crc :: B.ByteString -> Word32
crc xs = updateCrc 0xffffffff xs `xor` 0xffffffff
updateCrc :: Word32 -> B.ByteString -> Word32
updateCrc = B.foldl' crcStep
crcStep :: Word32 -> Word8 -> Word32
crcStep crc ch = (crcTab ! n) `xor` (crc `shiftR` 8)
where n = fromIntegral (crc `xor` fromIntegral ch)
crcTab :: Array Word8 Word32
crcTab = listArray (0,255) $ flip map [0..255] (\n ->
foldl' (\c k -> if c .&. 1 == 1
then 0xedb88320 `xor` (c `shiftR` 1)
else c `shiftR` 1) n [0..7])
eat :: B.ByteString -> (Int,Int,Int,Int)
eat seq = (process . B.head $ seq, process . B.head . B.drop 1 $ seq, process . B.head . B.drop 2 $ seq, process . B.head . B.drop 3 $ seq)
where process x = ((fromIntegral x)65)*6
main = do
seq <- B.readFile "/home/bana/Downloads/rm2.fa"
let xsiz = 800
ysiz = 800
dat = loop xsiz ysiz [[]] seq
where loop 0 0 img rseq = img
loop 0 y img rseq = loop xsiz (y1) ([]:img) (B.drop 4 rseq)
loop x y (z:img) rseq = loop (x1) y ((eat rseq:z):img) (B.drop 4 rseq)
bsdat = png dat
B.writeFile "testimg.png" bsdat |