<?php

// error_reporting(E_ALL);
// グローバルコマンドの位置
$global_path = '/usr/local/bin/global';
// GTAGSファイルの場所
$tag_path = '/var/www/htdocs/hazymoon.jp/caspar/OpenBSD4.2/HTML/S';

if (!empty($_REQUEST['filename'])) {
    chdir($tag_path);
    $search_file = escapeshellcmd($_REQUEST['filename']);
    $result = explode("\n", trim(shell_exec("$global_path -P --result=ctags-xid $search_file")));
    if (count($result) > 1) {
        exit('too many file found!');
    }
    if (0 == count($result)) {
        exit('file not found!');
    }
}

$rs = explode(' ', $result[0], 2);
print_r($rs);
if ('' != $rs[0]) {
    $fname = "$rs[0].html";
    $source = file($fname);
    $s_cnt = count($source);

    // xhtmlか判別
    if (false !== strpos($source[0], 'XHTML')) {
        $doctype = 'xhtml';
    } else {
        $doctype = 'html';
    }

    if (!empty($_REQUEST['start'])) {
        // ジャンプポイントを求める(start-5 の場所にロケーションジャンプ)
        $jump = $_REQUEST['start'];
        if ($_REQUEST['start'] > 5) {
            $jump = $_REQUEST['start'] - 5;
        }

        // BODY TAGに追加
        if ($jump > 0) {
            for ($i = 5; $i < 20; ++$i) {
                if (false !== strpos($source[$i], '<body>')) {
                    // javascriptで指定行にジャンプ
                    $source[$i] = "<body OnLoad=\"location.hash = 'L$jump'\">\n";
                    break;
                }
            }
        }

        // ハイライトする範囲のオフセットを求める
        $offset = 1;
        if (is_numeric($_REQUEST['end'])) {
            $offset = $_REQUEST['end'] - $_REQUEST['start'] + 1;
        } elseif (is_numeric($_REQUEST['offset'])) {
            $offset = $_REQUEST['offset'];
        }
        if ($offset <= 0) {
            $offset = 1;
        }

        // 指定行にスタイルを追加
        if ('html' == $doctype) {
            $needle = "<a name='L{$_REQUEST['start']}'>";
            $style = "style='color:#de9ede;background:#5a5d5a;margin-top:10px;width:100%;'";
        } else {
            $needle = "<a id='L{$_REQUEST['start']}' name='L{$_REQUEST['start']}' />";
            $style = "class='reverse'";
        }
        $count = 0;
        for ($i = $_REQUEST['start']; $i < $s_cnt; ++$i) {
            if (false !== strpos($source[$i], $needle)) {
                $source[$i] = "<div $style>{$source[$i]}";
                break;
            }
        }
        for (; $i < $s_cnt; ++$i) {
            ++$count;
            if ($count == $offset) {
                $source[$i] = str_replace("\n", '', $source[$i])."</div>\n";
                break;
            }
        }
    }

    // 表示
    for ($i = 0; $i < $s_cnt; ++$i) {
        echo $source[$i];
    }
}
