#!/usr/local/bin/perl

# 
# memo2mgp: memo 形式から MagicPoint 形式への変換
# 
#     [1999/03/08] OSHIRO Naoki. link2html をコピー
#     [1999/03/15] OSHIRO Naoki. １段階層の違いしか考慮してなかったものを修正
# 
#     $Log:$
#

require "getopts.pl";

print "\%include \"default.mgp\"\n";
print "\%default 1 bgrad";

if (0) {
print "\%\%\%\%\%\%\%\%\%\%\%\%\%\%\%\%\%\%\%\%\n";
print "\%page\n";
print "\%nodefault\n";
print "\%center, size 7, font \"standard\", fore \"white\", vgap 20\n";
print "\n";
print "メモ形式から MagicPoint への変換テスト\n\n";
}

$spc[0]="";
while (<>) {
    last if /^-+\s*$/;
}
$newpage=1;
$indent=0;
$|=1;
while (<>) {
    chop;
    s/\t/        /g;
    s/\[..:..\]\s*$//;
    &imgtag;

    if (/^-+\s*$/) {
	$newpage=1;
	$indent=0;
	$spc[0]="";
	$opt="";
	next;
    }
    #
    # 表題処理
    #
    next if (m#^\s*\[\d{4}/\d{2}/\d{2}\]#); # 日付は無視
    next if (/^\s*#/);                      # 行頭 '#' はコメントで無視

    $newitem=1 if (s/^(\s*)-->/\1   /);
    $pre_hang=0 if /^\%/;
    /^(\s*)(.*)\s*$/;
    ($spc, $label)=($1, $2);

    if ($newpage==1)  {
	if ($label=~/^%/) {
	    $opt.="$label\n";
	    next;
	}
        print "\n\%\%\%\%\%\%\%\%\%\%\%\%\%\%\%\%\%\%\%\%\n";
	print "\%page\n";
	print "$opt";
	print "\n";
	print "$label\n";
	$newpage=0;
	$newitem=1;
	next;
    }
    &indent_check($spc, *spc);
    $item="\t" x ($indent);
    if ($label=~s/^\|\%/\%/) {
        print "\n$label";
        $pre_hang=0;
    } elsif ($label=~/^\|/ || $newitem==0) {
	$pre_hang=0 if ($label=~s/^\|//);
	print "\\" if ($pre_hang);
	if ($label=~/^(http|ftp|img):/) {
	    print "\n";
	    $pre_hang=0;
	} else {
	    $pre_hang=1;
	}
        print "\n$label";
    } else {
	$pre_hang=0 if ($label=~s/^\|//);
	print "\n$item$label";
	$pre_hang=1;
    }
    $newitem=0;
}

sub indent_check {
    local($spc, *spc_pre)=@_;
    $indent=(length($spc)-3)/2;
}

sub imgtag {
    local($spc, $file, $label);
    if (/(\s*)\|?img:(.+)(\s(.*))?\s*$/) {
	($spc, $file, $opt)=($1, $2, $4);
	$_=$`;
	$_.="|\%center, image \"$file\" $opt\n";
    }
}

# major-mode: perl
