<?
// Evgeny Stepanischev (BOLK) http://bolknote.ru/ 3 Sep 2006

class Archive_LZF {

    /**
     * LZF decompress function
     *
     * @access public
     * @param str $str string for decompressing
     * @return mixed decompressed string or false on fails
     */
    function decompress($str) {
        $out = '';
        $l   = strlen($str);

        for ($i = 0; $i<$l;)
        {
            $c = ord($str{$i++});

            if ($i >= $l) {
                return false;
            }

            // literal run
            if ($c < 32) {
                $out .= substr($str, $i, ++$c);
                $i += $c;
            } else {
                $cnt = strlen($out);

                $len = $c >> 5;
                $ref = $cnt - (($c & 0x1f) << 8) - 1;

                if ($len == 7) {
                    $len += ord($str{$i++});
                }

                if ($ref >= $cnt) {
                    return false;
                }
                
                $ref -= ord($str{$i++});
                $out = str_pad($out, $cnt + $len + 2, substr($out, $ref), STR_PAD_RIGHT);
            }
        }

        return $out;
    }
}
?>