def urljoin(*parts):
    '''
    >>> from utils import urljoin
    >>> urljoin('/test', 'this', 'url')
    '/test/this/url'
    >>> urljoin('test', '//this', 'url')
    'test/this/url'
    >>> urljoin('test', '/this//', 'url')
    'test/this/url'
    >>> urljoin('test', '/this', 'url/')
    'test/this/url/'
    '''
    stripped = [parts[0].rstrip('/')]
    stripped.extend(p.strip('/') for p in parts[1:-1])
    stripped.append(parts[-1].lstrip('/'))
    return '/'.join(stripped)
    
def havedir(path):
    'Create directory path if it does not exist already'
    import os
    if not os.path.isdir(path):
        os.mkdir(path)

def subrect(r1, r2, size):
    x1, y1, w1, h1 = r1
    x2, y2, w2, h2 = r2
    w, h = size
    return (x2-x1)*w/w1, (y2-y1)*h/h1, w2*w/w1, h2*h/h1

def pdf2img(pdf_fname, size, id):
    from rlextra.utils.pdf2jpeg import pdfConvert
    from PIL import Image as PILImage

    if not pdfConvert(pdf_fname, scale=(1, 1), outDir='/tmp', outfile='thumb_%s.jpg' % id):
        raise ValueError, 'Could not convert pdf to jpeg...'
    img = PILImage.open('/tmp/thumb_%s.jpg' % id)
    img.thumbnail(size, PILImage.ANTIALIAS)
    # Remove the palette
    return img.convert()
    
def raiseifnot(bool, exc):
	if not bool:
		raise exc
		
def uniq(l):
    'Returns a list containing the unique elements of l with order preserved.'
    s = {}
    return [s.setdefault(e, e) for e in l if e not in s]

def replace_ampersands_ands(s):
    return s.replace('&', 'and')

def replace_dashes_underscores(s):
    return s.replace('-', '_')

if __name__ == "__main__":
    import doctest
    doctest.testmod()
