#!/usr/bin/python

import sys, string, re

# a Filist is a list of strings that contains the contents of
# a file.  All the usual list operations can be applied to a
# Filist.

class Filist(list):
    def __init__(self, file=None, t=None):
        # if a file is provided, read the contents
        if file:
            self.file = file
            lines = [line for line in open(file)]
            self.extend(lines)
        # add any lines that are provided
        if t:
            self.extend(t)

    def __str__(self):
        return string.join(self, '')

    def join(self):
        # collapse the list of strings into a single long string
        self[:] = [str(self)]

    def search_lines(self, pattern):
        # traverse lines in order until one of them matches,
        # return the index and the match object
        pat = re.compile(pattern)
        for i in range(0, len(self)):
            match = pat.search(self[i])
            if match:
                return i, match

    def decapitate(self, pattern='<BODY >\n'):
        # find the first line that matches the pattern;
        # remove it and all the previous lines
        i = self.index(pattern)
        del self[:i+1]

    def depeditate(self, pattern='</BODY>\n'):
        # find the first line that matches the pattern;
        # remove it and all the following lines
        i = self.index(pattern)
        del self[i:]

    def prefile(self, file):
        # prepend the contents of the given file
        ft = Filist(file)
        self.insert(0, ft)

    def suffile(self, file):
        # append the contents of the given file
        ft = Filist(file)
        self.extend(ft)

    def writeto(self, file):
        # write the contents of the Filist to a file
        fp = open(file, 'w')
        for line in self:
            fp.write(line)

    def writeback(self):
        # write the contents of the Filist back to the file it came from
        self.writeto(self.file)

def change_suffix(file, suffix):
    # replace the file extension with the given suffix
    t = string.split(file, '.')
    t[-1] = suffix
    return string.join(t, '.')

def cp(source, dest):
    # copy a file from source to destination, returning a Filist
    ft = Filist(source)
    ft.writeto(dest)
    return ft

def main(name, file, *argv):
    # print the contents of the given file
    ft = Filist(file)
    print ft

if __name__ == '__main__':
    main(*sys.argv)
