#!/usr/bin/perl
#
#NanaTerry からエキスポートした階層付きテキストファイル（.（ドット） の数で階層の深さがを表現） を
#latex beamer のソースファイルに変換するスクリプト。 整形ルールは以下の仕様による
#
#	. は ¥section または Title コントロールページ （Title で始まるブロックは Title Control）
#	.. は子孫がいれば ¥subsection、いなければ単独ページの生成
#	... も子孫がいれば ¥subsection 、いなければ単独ページの生成
#	.... は無条件でページの生成、ページタイトルの自動挿入
#	..... 以上の深さは強制的に .... に格上げする
#
#	section が4つ以上ある時には、最初（＝概要）、最後（＝サマリー） のセクションは生成しない
#
# ------------------------------------------------------------------------
#   Title Page Control
# ------------------------------------------------------------------------
#	title =: で始まるトップレベルセクションは Title Control として以下の特定文字を指定する
#
#		sub =:サブタイトル
#		date =:日付
#		seminar =:セミナー名
#		auth =:著者名
#		inst =:組織名
#
#		lang =:JP/US (指定なければ JP として扱う)
#
# ------------------------------------------------------------------------
#    Frame Page Control
# ------------------------------------------------------------------------
#
#		先頭行が title =: で始まる場合には、ブロック要素が生成されその文字列がブロックタイトルになる
#
#		文字サイズを明示的に指定したい場合には 22font22=: で指定する。一行目、Title 指定のある場合のみ二行目に書く
#		設定できるのは tiny|scriptsize|footnotesize|small|normalsize|large|Large|huge|Huge の何れか
#
#		行が 1111 で始まる行は、9999 で始まる行が出るまで段差げになる
#		行が 1111 で始まった一行が 8888 で終わった場合には段差げはその一行だけとする
#
#		行が image =: で始まる場合には、二行目で指定された画像ファイル（.jpg .eps ）が全面に貼り付けられ
#		三行目に origin=: で引用元（URL） が記載されている場合は画像の下に引用元が記載される
#		注）svg サポートを試みたが課題が多いので svg は eps に変換して利用することとする
#
#		http(s):// で始まる行は URL として扱う
#
#		最終行が sumb =:(青色)、 sumr =:（赤色） で始まるとその文字列が独立したサマリーブロック
#
#		文字列の中で文字色を指定したい場合には 00red00 と 0000 で対象文字列を囲む。
#		現在サポートしているのは赤（red）、青（blue）、緑（green）、黄色（yellow） の４色
#		一行中に複数箇所の文字色指定を行うことができる。
#
#		URL 表記は リンカブル な文字列として登録
#		latex の予約文字にはエスケープを追加
#


use		strict;
use		warnings;
use		utf8;
use		File::Copy;
use		File::Basename;

my $source_file;
my $output_file;

my $version = "20181215B";

my $line;                   # file read buffer
my @read_line;              # file read buffer (structured)
my $pos;                    # file read pointer
my $item_count;             # itemized line counter
my $item_count_max;         # itemized line counter
my @item_lines;             # catch itemized item buffer (structured)'
my $title_def = 0;          # title definition section flag
my $slide_pages = 0;        # generated page counter
my $section_cnt = 0;
my $first_section_pos = 0;
my $last_section_pos = 0;
my $color_def = "red|blue|green|yellow";
my $font_set;
my $font_config="tiny|scriptsize|footnotesize|small|normalsize|large|Large|huge|Huge";

my $debug_flag = 0;         # debug message control
my $line_cnt = 0;           # debug line counter
my $page_cnt = 0;           # debug page counter

my $session_title = "";
my $session_sub_titile = "";
my $session_date = "";
my $session_seminar = "";
my $session_author = "";
my $session_inst = "";

my $lang_jp = 1;			# default language = Japanese

# Chick if correct source file is set
if (@ARGV == 1){
	# check file extention is .txt
	my ($basename, $dirname, $ext) = fileparse($ARGV[0], qr/\..*$/);
	if($ext eq ".txt"){
		$source_file = $ARGV[0];
		$output_file = "$basename.tex";

		#check if source file contains at least one line starting with dot
		open(NANAFILE, $source_file) or die "$!";
		@read_line = <NANAFILE>;
		close(NANAFILE);

		my $no_dot_found = 1;
		foreach(@read_line){
			# count slide pages
			if( $_ =~ /^\./){
				$no_dot_found = 0;
				last;
			}
		}
		# not a formatted text file
		if($no_dot_found){ die ("\n","Please specify formatted fext file name (3)\n\n"); }
		} else {
		# not a text file
		die ("\n","Please specify formatted fext file name (2)\n\n");
	}
} else {
	# source file not correctly set (none or more than two files)
	die ("\n","version = $version\n","Please specify formatted text file name (1)\n\n");
}
print "\n";

# open source / output file
open(NANAFILE, $source_file) or die "$!";
open(MIDFILE, ">", "temp_conv.txt") or die "$!";

# generate Tex initial static section
print MIDFILE "\\begin{document}\n\n";
print MIDFILE "\\begin{frame}\n";
print MIDFILE "\t\\titlepage{}\n";
print MIDFILE "\\end{frame}\n\n";

# read source file
while (my $line = <NANAFILE>){
	if($debug_flag) {print "---> : [",++$line_cnt,"] $line"};

	# remove line termination code
	$line =~ s/(\r\n|\r|\n)$//g;

	# remove [OBJ] (0xEF,0xBF,0xBC,0xOA) that inserted as an image file index
	$line =~ s/\xef\xbf\xbc//;

	# check if line start with dot
	if($line =~ /^\./){

		# if exceed five dots, force limit to four dots
		if( $line =~ /^\.{5,}/){
			$line =~ s/^\.{5,}/\.\.\.\./;
			print "\033[35mtoo deep section (>4) , force limit to 4 dots";
			print "\033[31m$line";
			print "\033[0m\n";
		}

		if($line =~ /^\.\.\.\./){
			# four-dots force page generation
			if($debug_flag > 1) {print "Hit four-dots line $line \n"};
			$line =~ s/^\.\.\.\.//g;
			$title_def =0;  # reset special title control section
			&frame_gen(*NANAFILE, *MIDFILE, $line);

		} elsif ($line =~ /^\.\.\./){
			# three dot case, check if following line exists
			if($debug_flag > 1) {print "Hit three-dots line $line \n"};
			$line =~ s/^\.\.\.//g;
			$title_def =0;  # reset special title control section
			if( &check_child3(*NANAFILE)){
				# if has child, three-dots generates subsection
				$line = &remove_color_setting($line);
				print MIDFILE "\\subsection{$line}\n";
				print MIDFILE "\n";
			} else {
				&frame_gen(*NANAFILE, *MIDFILE, $line);
			}

		} elsif ($line =~ /^\.\./){
			# double dots case, force section
			$line =~ s/^\.\.//g;
			if($debug_flag > 1) {print "Hit double-dots line as $line \n"};
			$title_def =0;  # reset special title control section
			if(&check_child2(*NANAFILE)){
				# if has child, double dots generates section
				print MIDFILE "\\section{$line}\n";
				print MIDFILE "\n";
			} else {
				&frame_gen(*NANAFILE, *MIDFILE, $line);
			}

		} else {
			#single dot case, check special title control block
			if($debug_flag > 1) {print "Hit single-dot line --> $line \n"};
			$line =~ s/^\.//g;
			if( $line =~ /^Title/ ){
				$title_def = 1;
			} else {
				# This case does not exist
				$title_def =0;  # reset special title control section
				#print MIDFILE "\\section{$line}\n";
				#print MIDFILE "\n";
			}
		}

	} elsif ($title_def){
		# context line (not start with dot)
		# Title page
		# title =:		セッションタイトル
		# sub =:		サブタイトル
		# date =:		日付
		# seminar =:	セミナー名
		# auth =:		著者名
		# inst =:		組織名

		if ($line =~ /^title\s*=:/){
			if($debug_flag) {print "Hit title-control special line\n"};
			$line =~ s/^title\s*=:\s*//g;
			$session_title = $line;
		} elsif ($line =~ /^sub\s*=:/){
			$line =~ s/^sub\s*=:\s*//g;
			$session_sub_titile = $line;
		} elsif ($line =~ /^date\s*=:/){
			$line =~ s/^date\s*=:\s*//g;
			$session_date = $line;
		} elsif ($line =~ /^seminar\s*=:/){
			$line =~ s/^seminar\s*=:\s*//g;
			$session_seminar = $line;
		} elsif ( $line =~ /^auth\s*=:/){
			$line =~ s/^auth\s*=:\s*//g;
			$session_author = $line;
		} elsif ( $line =~ /^inst\s*=:/){
			$line =~ s/^inst\s*=:\s*//g;
			$session_inst = $line;
		} elsif ( $line =~ /^lang\s*=:(us|US)/){
			$lang_jp = 0;
			print "US lanuage setting detected\n";
		}
	}
}

# Add document termination line
print MIDFILE "\\end{document}\n";

close( NANAFILE );
close( MIDFILE );

if(1 || $debug_flag){
print "\n******************************************\n";
print "\$session_title = $session_title \n";
print "\$session_sub_titile = $session_sub_titile \n";
print "\$session_date = $session_date \n";
print "\$session_seminar = $session_seminar \n";
print "\$session_author = $session_author \n";
print "\$session_inst = $session_inst \n";
print "******************************************\n\n";
}

#set session title section
open( MIDFILE, "<","temp_conv.txt" ) or die "$!";
open( TEXFILE, "+>", $output_file ) or die "$!";

# latex header insert
if( $lang_jp ){
	print TEXFILE "\\documentclass[xcolor=dvipsnames,table,dvipdfmx,aspectratio=169]{beamer}\n";
	print TEXFILE "\\usepackage{mypreamble_jp}\n";
	print TEXFILE "\n";
} else {
	print TEXFILE "\\documentclass[aspectratio=169]{beamer}\n";
	print TEXFILE "\\usepackage{mypreamble_us}\n";
	print TEXFILE "\n";
}

# Add title control section (if defined)
if( $session_title ne "" ){
	print TEXFILE "\\title{$session_title}\n";
}
if( $session_sub_titile ne "" ){
	print TEXFILE "\\subtitle{$session_sub_titile}\n";
}
if( $session_date ne "" ){
	print TEXFILE "\\date[$session_date]{$session_date}\n";
}
if( $session_seminar ne "" ){
	print TEXFILE "\\subtitle{$session_seminar}\n";
}
if( $session_author ne "" ){
	print TEXFILE "\\author[$session_author]{$session_author}\n";
}
if( $session_inst ne "" ){
	print TEXFILE "\\institute[$session_inst]{$session_inst}\n";
}

@read_line = <MIDFILE>;
foreach( @read_line ){
	# count slide pages
	if( $_ =~ /^\\begin\{frame\}/){
		++$slide_pages;
	}
	if( $_ =~ /^\\section\{/){
		++$section_cnt;
		if($debug_flag >1){print "section detect [$section_cnt] ",$_};
	}
    print TEXFILE $_;
}

# If more than 4 section exist, delete the first and the last section
if( $section_cnt > 4){
	seek(TEXFILE,0,0);
	my $section_cnt2 =0;
	while( my $sec_line = <TEXFILE>){
		if( $sec_line =~ /^\\section\{/){
			++$section_cnt2;
			if($section_cnt2 == 1){
				seek(TEXFILE, -length($sec_line),1);
				$sec_line =~ s/\\section\{/\%section\{/;
				print TEXFILE $sec_line;
			} elsif($section_cnt2 == $section_cnt){
				seek(TEXFILE, -length($sec_line),1);
				$sec_line =~ s/\\section\{/\%section\{/;
				print TEXFILE $sec_line;
			}
		}
	}
}

close(MIDFILE);
close(TEXFILE);
unlink("temp_conv.txt");

print "---------------------------\n";
print " Total ",$slide_pages -1," page generated\n";
print "---------------------------\n\n";

# beamer page generation sub-routine
sub frame_gen{
	local *SRC_FP = $_[0];
	local *MID_FP = $_[1];
	$line = $_[2];
	my $skip = 0;

	if($debug_flag){print "new beamer page generation [",++$page_cnt,"] \n"};
	print MID_FP "\\begin{frame}\n";
	$line = &color_check($line);
	print MID_FP "\t\\frametitle{$line}\n";

	# check itemize item defined
	$pos = tell(SRC_FP);   #save current position
	$item_count = 0;
	@item_lines = ();

	# count itemized line
	while( $line = <SRC_FP> ){
		if( $line =~ /^\./){
			last;
		}

		# remove line termination code
		$line =~ s/(\r\n|\r|\n)$//g;

		# Add escape for latex special character (is #$%&_{}<>\^|~))
		$line =~ s/\#/\\#/g;
		$line =~ s/\$/\\\$/g;
		$line =~ s/\%/\\%/g;
		$line =~ s/\&/\\&/g;
		if($line =~ /\_/ && $line !~ /^\s*image\s*=:/){$line =~ s/\_/\\_/g;};
		$line =~ s/\{/\\{/g;
		$line =~ s/\}/\\}/g;
		$line =~ s/\</\\</g;
		$line =~ s/\>/\\>/g;
		$line =~ s/\^/\\^/g;
		$line =~ s/\|/\\|/g;
		$line =~ s/\~/\\~/g;

		# add \\url to URI
		if($line =~ /^https?:\/\// ){
			if( $debug_flag > 1){ print "Hit URL\n",$line,"\n"};
			$line =~ s/^http/\\small\\textcolor{blue}{\\url\{http/;
			$line = $line."}}";
			if( $debug_flag > 1){print $line,"\n"};
		}

		# load line buffer till next dot-started line captured
		$item_lines[$item_count] = $line;
		++$item_count;
	}

	# check @item_lines contents
	if($debug_flag>1){
		my $a = 0;
		while( $a < $item_count ){
			print "---> [$a] $item_lines[$a]\n";
			++$a;
		}
		print "\n";
	}

	# generate item stuff
	seek(SRC_FP, $pos, 0);    # resume file pointer
	if($item_count != 0){
			if($debug_flag>1){print "Initial item count ---> $item_count\n"};
		$item_count_max = $item_count;
		$item_count = 0;
		$font_set = "";

		while( $item_count < $item_count_max ){
			if($debug_flag>1){print "Item count ---> ",$item_count+1,"\n"};
			if( $item_count == 0){

				# check if first line described as title ( title =: )
				if( $item_lines[$item_count] =~ /^(t|T)itle\s*=:/){
					$item_lines[$item_count] =~ s/^(t|T)itle\s*=://;
					$item_lines[$item_count]= &color_check($item_lines[$item_count]);
					print MID_FP "\t\\begin{block}{$item_lines[$item_count]}\n";

					# if font setting follows title setting (exception)
					if($item_lines[$item_count+1] =~ /^22font22\s*=:/){
						# check if font size setting exist
						$item_lines[$item_count+1] =~ s/^22font22\s*=:\s*//;
						if($item_lines[$item_count+1] =~ /($font_config)/){
							$font_set = $&;
							++$item_count;
							if($debug_flag>1){print ">> Detect font size setting (in the first line) as $font_set\n"};
							$item_lines[$item_count+1]= &color_check($item_lines[$item_count+1]);
							print MID_FP "\t\t\\$font_set\{\n";
							print MID_FP "\t\t\\begin{itemize}\n";
							&item_interval(*MID_FP, $item_lines[$item_count+1]);
							++$item_count;
						} else {
							# wrong font size defined w/22font22=: (tricky case)
							&item_start(*MID_FP, $font_set);
						}
					} else {
						# if font definiton not exist after titile=: config (normal case)
						&item_start(*MID_FP, $font_set);
					}

				} elsif( $item_lines[$item_count] =~ /^image\s*=:/){
				# check image page defined
					$item_lines[$item_count] =~ s/^image\s*=:\s*//;

					# check if image url defined
					my $wo_origin = 1;
					my $image_url ="";
					if($item_count < $item_count_max-1){

						if($item_lines[$item_count+1] =~ /^origin\s*=:.*http/ ){
							$wo_origin = 0;
							$image_url = $item_lines[$item_count+1];
							$image_url =~ s/^origin\s*=:\s*//;
							if($debug_flag>1){print "image url = $image_url [$wo_origin]\n"};
						}
					}

					print MID_FP "\t\\begin{figure}[tb]\n";
					print MID_FP "\t\t\\vspace{-0.3cm}\n";
					if($wo_origin){
						if( $item_lines[$item_count] =~ /\.(svg|SVG)$/){
							print MID_FP "\t\t\\centering{\\includesvg[height=6.0cm]{figure/$item_lines[$item_count]}}\n";
						} else {
							print MID_FP "\t\t\\centering{\\includegraphics[clip, height=6.0cm]{figure/$item_lines[$item_count]}}\n";
						}
					} else {
						if( $item_lines[$item_count] =~ /\.(svg|SVG)$/){
							print MID_FP "\t\t\\centering{\\includesvg[height=5.6cm]{figure/$item_lines[$item_count]}}\n";
						} else {
							print MID_FP "\t\t\\centering{\\includegraphics[clip, height=5.6cm]{figure/$item_lines[$item_count]}}\n";
						}
						print MID_FP "\t\t\\leftline{\\scriptsize{\\textcolor{blue}{\\url{$image_url}}}}\n";
					}
					print MID_FP "\t\\end\{figure\}\n";
					$skip = 1;
					++$item_count;
					last;

				} elsif($item_lines[$item_count] =~ /^22font22\s*=:/){
					# check if font size setting exist
					$item_lines[$item_count] =~ s/^22font22\s*=:\s*//;
					if($item_lines[$item_count] =~ /($font_config)/){
						$font_set = $&;
						++$item_count;
						if($debug_flag>1){print ">> Detect font size setting as $font_set\n"};
						$item_lines[$item_count]= &color_check($item_lines[$item_count]);
						print MID_FP "\t\\begin{block}{}\n";
						print MID_FP "\t\t\\$font_set\{\n";
						print MID_FP "\t\t\\begin{itemize}\n";
						&item_interval(*MID_FP, $item_lines[$item_count]);
					}
				} else {
					# Normal item contents
					$item_lines[$item_count]= &color_check($item_lines[$item_count]);
					print MID_FP "\t\\begin{block}{}\n";
					print MID_FP "\t\t\\begin{itemize}\n";
					&item_interval(*MID_FP, $item_lines[$item_count]);
				}
				++$item_count;
			} elsif ( $item_count != ($item_count_max - 1)){
			# following lines (except last line)

				if ( $item_lines[$item_count] =~ /^\s*1111/ && &term_check(\@item_lines,$item_count, $item_count_max) && $item_count != 1){
				if(0){print "1111 detected ===> $item_lines[$item_count] \n"};
				# check sub-item definition
					my $line_break = 0;
					if( $item_lines[$item_count] =~ /.*8888s*$/ ){
						$line_break = 1;
						$item_lines[$item_count] =~ s/8888s*$//g;
					}
					$item_lines[$item_count] =~ s/\s*1111//g;
					$item_lines[$item_count]= &color_check($item_lines[$item_count]);
					# if font size set in parent item block, follow the same setting. However, it seems not take effect:w
					#&item_start(*MID_FP, $font_set);
					print MID_FP "\t\t\t\\begin{itemize}\n";
					if(length($font_set)){print MID_FP "\t\t\t\\$font_set\{\n"};
					print MID_FP "\t\t\t\t\\item $item_lines[$item_count]\n";
					if(++$item_count < $item_count_max){
						while( $item_lines[$item_count] !~ /^\s*9999/ && !$line_break ){
							$item_lines[$item_count]= &color_check($item_lines[$item_count]);
							&item_interval(*MID_FP, $item_lines[$item_count]);
							++$item_count;
						}
						if ( !$line_break ){
							$item_lines[$item_count] =~ s/\s*9999//g;
							$item_lines[$item_count]= &color_check($item_lines[$item_count]);
							print MID_FP "\t\t\t\t\\item $item_lines[$item_count]\n";
							# if duplicate font size exist in nested item block
							if(length($font_set)){ print MID_FP "\t\t\t}\n"};
						}
						print MID_FP "\t\t\t\\end{itemize}\n";
					}
				} else {
					$item_lines[$item_count] = &color_check($item_lines[$item_count]);
					&item_interval(*MID_FP, $item_lines[$item_count]);
				}
				++$item_count;
			} else {

				# check last line : if item has special sammary flag (sumb =: / sumr =:)
				if( $item_lines[$item_count] =~ /^sumb\s*=:/){
					# blue block
					$item_lines[$item_count] =~ s/^sumb\s*=://;
					print MID_FP "\t\t\\end{itemize}\n";
					#print MID_FP "\t\\end{block}\n";
					&item_close(*MID_FP, $font_set);
					print MID_FP "\t\\begin{block}{}\n";
					$item_lines[$item_count] = &color_check($item_lines[$item_count]);
					print MID_FP "\t\t\\centering\\textcolor{blue}{\\bf $item_lines[$item_count]}\n";
					print MID_FP "\t\\end{block}\n";
					$skip = 1;
					++$item_count;
				} elsif ( $item_lines[$item_count] =~ /^sumr\s*=:/){
					# red block
					$item_lines[$item_count] =~ s/^sumr\s*=://;
					print MID_FP "\t\t\\end{itemize}\n";
					#print MID_FP "\t\\end{block}\n";
					&item_close(*MID_FP, $font_set);
					print MID_FP "\t\\begin{alertblock}{}\n";
					$item_lines[$item_count] = &color_check($item_lines[$item_count]);
					print MID_FP "\t\t\\centering\\textcolor{red}{\\bf $item_lines[$item_count]}\n";
					print MID_FP "\t\\end{alertblock}\n";
					$skip = 1;
					++$item_count;
				} else {
					if($debug_flag>1){print "Last item = $item_lines[$item_count]\n"};
					if( $item_lines[$item_count] =~ /^\s*1111/ && $item_lines[$item_count] =~ /8888s*$/ ){
						# check if the last line indented
						$item_lines[$item_count] =~ s/\s*1111//g;
						$item_lines[$item_count] =~ s/8888s*$//g;
						$item_lines[$item_count] = &color_check($item_lines[$item_count]);
						print MID_FP "\t\t\t\\begin{itemize}\n";
						print MID_FP "\t\t\t\t\\item $item_lines[$item_count]\n";
						print MID_FP "\t\t\t\\end{itemize}\n";
					} else {
						$item_lines[$item_count] = &color_check($item_lines[$item_count]);
					print MID_FP "\t\t\t\\item $item_lines[$item_count]\n";
					}
					++$item_count;
				}
			}
		}
		if(!$skip){print MID_FP "\t\t\\end{itemize}\n"};
		#if(!$skip){ print MID_FP "\t\\end{block}\n"};
		if(!$skip){ &item_close(*MID_FP, $font_set)};
	}
		print MID_FP "\\end{frame}\n";
		print MID_FP "\n";
}

# check if this line has a child (has retuens 1)
sub check_child2{
	local *CHK_FP = $_[0];
	my $lpos = tell(CHK_FP);
	my $rtn_val;

	seek(CHK_FP,-1,1);
	while( my $next = <CHK_FP> ){
		# scan till meet the line starting with dot
		if( $next =~ /^\.\.\./){
			$rtn_val = 1;
			last;
		} elsif ($next =~ /^\.\./ || $next =~ /^\./){
			$rtn_val = 0;
			last;
		}
	}
	seek(CHK_FP, $lpos, 0);
	if($debug_flag > 1) { print "check-child2 return = [$rtn_val]\n"};
	return( $rtn_val );
}

# check if this line has a child (has retuens 1)
sub check_child3{
	local *CHK_FP = $_[0];
	my $lpos2 = tell(CHK_FP);
	my $rtn_val2;

	seek(CHK_FP,-1,1);
	while( my $next = <CHK_FP> ){
		# scan till meet the line starting with dot
		if( $next =~ /^\.\.\.\./){
			$rtn_val2 = 1;
			last;
		} elsif ($next =~ /^\.\.\./ || $next =~ /^\.\./ || $next =~ /^\./){
			$rtn_val2 = 0;
			last;
		}
	}
	seek(CHK_FP, $lpos2, 0);
	if($debug_flag > 1) { print "check-child3 return = [$rtn_val2]\n"};
	return( $rtn_val2 );
}

# check if font color is defined
sub color_check{
	my $testline = $_[0];

	if( $testline =~ /00($color_def)00/){
		my $open_array  = scalar(()=$testline =~ /00($color_def)00/g);
		my $close_array = scalar(()=$testline =~ /0000/g);
		if( $open_array == $close_array ){
			$testline =~ s/00red00/\\textcolor\{red\}\{/g;
			$testline =~ s/00blue00/\\textcolor\{blue\}\{/g;
			$testline =~ s/00green00/\\textcolor\{green\}\{/g;
			$testline =~ s/00yellow00/\\textcolor\{yellow\}\{/g;
			$testline =~ s/\s*0000/\}/g;
			if($debug_flag>1){print "Hit color -> : $testline\n"};
		} else {
			print "\033[31mdetect incorrect color setting (pair miss match !)\n";
			print "\033[33m$testline\n";
			print "\033[0m\n";
			exit(-1);
		}
	}
	return($testline);	
}

# check indented items has correct termination
sub term_check{
	my	$c_line		= $_[0];
	my	$chk		= $_[1];
	my	$btm		= $_[2]-1;
	my	$rtn_result	= 0;

	if($debug_flag>1){
		print "=================\n";
		print "in = $chk : botom = $btm : line = @$c_line[$chk]\n";
		print "=================\n\n";
	}

	if( @$c_line[$chk] =~ /.*8888s*$/ ){
			$rtn_result = 1;
	} else {
			while( $chk < $btm ){
			++$chk;
			if( @$c_line[$chk] =~ /^\s*9999/ ){
				$rtn_result = 1;
				last;
			}
		}
	}
	if(!$rtn_result){
		print "\033[31mError : incorrect item indent (no closure)\n";
		print "\033[33m@$c_line[$chk]\n";
		print "\033[0m\n";
		exit(-1);
	}
	return($rtn_result);
}

#remove color setting (for subsection)
sub remove_color_setting{
	my $c_line		= $_[0];

	if( $c_line =~ /00($color_def)00/){
		my $open_array  = scalar(()=$c_line=~ /00($color_def)00/g);
		my $close_array = scalar(()=$c_line=~ /0000/g);
		if( $open_array == $close_array ){
			$c_line =~ s/00red00//g;
			$c_line =~ s/00blue00//g;
			$c_line =~ s/00green00//g;
			$c_line =~ s/00yellow00//g;
			$c_line =~ s/0000//g;
		}
	}
	return($c_line);
}

# itemize block gegeration sub (check font size definition)
sub item_start{
	local	*MFP	= $_[0];
	my 		$FSZ	= $_[1];

	if(length($FSZ)){
		print MFP "\t\t\\$FSZ\{\n";
		print MFP "\t\t\\begin{itemize}\n";
	} else {
		print MFP "\t\t\\begin{itemize}\n";
	}
}

# itemized block close sub (check font size definition)
sub item_close{
	local	*MFP	= $_[0];
	my		$FSZ	= $_[1];

	if(length($FSZ)){
		print MFP "\t\t}\n";
		print MFP "\t\\end{block}\n";
	} else {
		print MFP "\t\\end{block}\n";
	}
}

# blank line does not make item, but virtical interval
sub item_interval{
	local	*MFP	= $_[0];
	my		$LN		= $_[1];
	

	if(length($LN)){
		print MFP "\t\t\t\\item $LN\n";
	} else {
		print MFP "\t\t\t\\vspace{0.3cm}\n";
	}
}
