#!/usr/bin/python

# tidbits from booklistgen-0.3.4/src/OpenLibrie/LRFLib/LRFFile.cs

WORD_SIZE = 2
DWORD_SIZE = 4
# Offset of length of compressed info block in LRF file
LRF_OFFSET_CINFOBLOCK_LEN = 0x4C
# Offset of length of uncompressed info block in LRF file
LRF_OFFSET_UINFOBLOCK_LEN = 0x54
# Offset of compressed info block data in LRF file
LRF_OFFSET_CINFOBLOCK_DATA = LRF_OFFSET_UINFOBLOCK_LEN + DWORD_SIZE;
# Offset of length of GIF data in LRF file
LRF_OFFSET_GIF_LEN = 0x50

import struct
import zlib

def get_word_from(bytes, offset):
    return struct.unpack("<H", bytes[offset:offset+2])[0]
def get_dword_from(bytes, offset):
    return struct.unpack("<L", bytes[offset:offset+4])[0]

class LrfFile:
    def __init__(self, path):
        self.path = path
        self.bytes = open(path,"r").read()

        self.cinfoLength = get_word_from(self.bytes, LRF_OFFSET_CINFOBLOCK_LEN)
        self.cinfo = self.bytes[LRF_OFFSET_CINFOBLOCK_DATA:
                                LRF_OFFSET_CINFOBLOCK_DATA + self.cinfoLength]
        self.gifLength = get_dword_from(self.bytes, LRF_OFFSET_GIF_LEN)
        self.gif = self.bytes[LRF_OFFSET_UINFOBLOCK_LEN + self.cinfoLength:
                              LRF_OFFSET_UINFOBLOCK_LEN + self.cinfoLength + self.gifLength]

        self.uinfoLength = get_dword_from(self.bytes, LRF_OFFSET_UINFOBLOCK_LEN)
        self.uinfo = zlib.decompress(self.cinfo)

# Sample value of uinfo:
## <?xml version="1.0" ?>  
## <Info version="1.0" >
## <BookInfo>
## 	<Title>Lady Chatterly's Lover</Title>
## 	<Author>D H Lawrence</Author>
## 	<BookID>zdVnISprTxmeHKjx</BookID>
## 	<Publisher>manybooks.net</Publisher>
## 	<Label>LIBRIe Books</Label>
## 	<Category>\xe5\xad\xa6</Category>
## 	<Classification>\xe5\xa3\xb0</Classification>
## 	<FreeText>This book was generated by a preliminary version of makelrf.</FreeText>
## </BookInfo>
## <DocInfo>
## 	<Language>en</Language>
## 	<Creator>makelrf v0.3</Creator>
## 	<CreationDate>09.04.2005</CreationDate>
## 	<Producer>makelrf 0.3</Producer>
## 	<Page>0</Page>
## </DocInfo>
## </Info>
## \x00