#!/usr/bin/perl

my $version = "20190222";

sub print_help(){
print "\033[33m\nnana2tex.pl ( $version )\n\n";
print "NanaTerry からエキスポートした階層テキストファイルを\n";
print "latex beamer ソースに変換 .（ドット）の数で階層の深さがを表現、\n";
print "以下の整形指定文字を埋め込むことができる\033[0m\n";
print "\n";
print ". は \section または Title コントロールページ（Title で始まるブロックは Title Control）\n";
print ".. は子孫がいれば \subsection、いなければ単独ページの生成\n";
print "... も子孫がいれば \subsection 、いなければ単独ページの生成\n";
print ".... は無条件でページの生成、ページタイトルの自動挿入\n";
print "..... 以上の深さは強制的に .... に格上げする\n";
print "\n";
print "section が4つ以上ある時には、最初（＝概要）、最後（＝サマリー） のセクションは生成しない\n";
print "\n";
print "\033[33m------------------------------------------------------------------------\n";
print "  Title Page Control\n";
print "------------------------------------------------------------------------\033[0m\n";
print "title =: で始まるトップレベルセクションは Title Control として以下の特定文字を指定する\n";
print "\n";
print "sub =:サブタイトル\n";
print "date =:日付\n";
print "seminar =:セミナー名\n";
print "auth =:著者名\n";
print "inst =:組織名\n";
print "lang =:JP/US (指定なければ JP として扱う)\n";
print "\n";
print "\033[33m------------------------------------------------------------------------\n";
print "    Frame Page Control\n";
print "------------------------------------------------------------------------\033[0m\n";
print "\n";
print "先頭行が \033[33msplit_left =:\033[0m で始まる場合、画面の左右に分割となる\n";
print "split_left =: 60 のように明示的に左パートの割合を指定することができる\n";
print "有効な左右分割の比率は 30〜70 の範囲とする。\n";
print "引数が指定されない場合、無効な比率が設定された場合は自動的に 50:50 の分割となる\n";
print "右パートの開始は \033[33msplit_right =:\033[0m で指定する（引数を指定は不要、自動計算）\n";
print "以下で説明する title, image などの設定は左右独立で指定することができる\n";
print "\n";
print "先頭行が \033[33mtitle =:\033[0m で始まる場合には、ブロック要素タイトルを指定することができる\n";
print "\n";
print "文字サイズを明示的に指定したい場合には \033[33m22font22=:\033[0m で指定する。\n";
print "一行目、Title 指定のある場合のみ二行目に書く\n";
print "設定できるのは tiny|scriptsize|footnotesize|small|normalsize|large|Large|huge|Huge の何れか\n";
print "\n";
print "行が \033[33m1111\033[0m で始まる行は、\033[33m9999\033[0m で始まる行が出るまで段差げになる\n";
print "行が \033[33m1111\033[0m で始まった一行が \033[33m8888\033[0m で終わった場合には段差げはその一行だけとする\n";
print "行に \033[33m<feed>\033[0m と書いた場合には行間をあける\n";
print "\n";
print "行が \033[33mimage =:\033[0m で始まる場合には、二行目で指定された画像ファイル（.jpg .eps ）が全面に貼り付けられ\n";
print "三行目に \033[33morigin=:\033[0m で引用元（URL） が記載されている場合は画像の下に引用元が記載される\n";
print "注）svg サポートを試みたが課題が多いので svg は eps に変換して利用することとする\n";
print "\n";
print "\033[33mhttp(s)://\033[0m で始まる行は URL として扱う\n";
print "URL 表記は リンカブル な文字列として登録\n";
print "\n";
print "最終行が \033[33msumb =:\033[0m(青色)、 \033[33msumr =:\033[0m（赤色） で始まるとその文字列が独立したサマリーブロック\n";
print "\n";
print "文字列の中で文字色を指定したい場合には \033[33m00red00\033[0m と \033[33m0000\033[0m で対象文字列を囲む。\n";
print "現在サポートしているのは赤（red）、青（blue）、緑（green）、黄色（yellow） の４色\n";
print "一行中に複数箇所の文字色指定を行うことができる。\n\n";
}

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

my $source_file;
my $output_file;
my $tmp_file;


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";

		# ----------------------------------------------------------------------
		#  read source formatted-text file (and delete original source file)
		# ----------------------------------------------------------------------
		open(NANAFILE, $source_file) or die ("\n","\033[33mERROR : file ( $source_file ) does not exit\033[0m\n\n");
		@read_line = <NANAFILE>;
		close(NANAFILE);
		unlink($source_file);

		# ----------------------------------------------------------------------
		#  check if 1st line of souce file contains .Title
		# ----------------------------------------------------------------------
		if( $read_line[0] !~ /^\.(t|T)itle/){
			die ("\n","\033[33mERROR : File format error (seems Nanaterry export missing)\033[0m\n\n");
		}

		# -----------------------------------
		#  remove blank or space only lines
		# -----------------------------------
		@read_line = grep { !/^\s*$/ } @read_line;
		open(NANAFILE, "> $source_file");
		foreach(@read_line){
			print NANAFILE "$_";
		}
		close(NANAFILE);

		# ----------------------------------------------------------------------
		#  check if source file contains at least one line starting with dot
		# ----------------------------------------------------------------------
		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","\033[33mERROR : Please specify formatted fext file name (3)\033[0m\n\n"); }
		} else {
		# not a text file
		die ("\n","\033[33mERROR : Please specify formatted fext file name (2)\033[35m\n\n");
	}
} else {
	# source file not correctly set (none or more than two files)
	#die ("\n","\033[33mERROR : Please specify formatted text file name (1)\033[0m\n\n");
	&print_help();
	exit(-1);
}
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 =~ /^(t|T)itle/ ){
				$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\n";
		}
	}
}

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

close( NANAFILE );
close( MIDFILE );

if(1 || $debug_flag){
print "\n******************************************\n";
print "\$version = $version\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,ja=standard]{beamer}\n";
	print TEXFILE "\\usepackage{mypreamble_en}\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 $side_by_side = 0;
	my $left_portion = 0;
	my $stmp;
	my $block_set;
	my $right_block_start = 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 = ();

	#------------------------------------------------------
	# pre-scan (check how many lines exist in this page)
	#------------------------------------------------------
	# read line untill next .(is the start sign of new page) appears
	while( $line = <SRC_FP> ){
		if( $line =~ /^\./){
			# abort line reads when dot catched
			last;
		}

		# detect page horizontal sprit ratio is correctly defined
		# check left part propotion (should be 25% to 75%)
		if( $line =~ /^\s*split_left\s*=:/ ){
			$line =~ /(?<=\=:)(.*)/;
			$stmp = $1;
			if( $stmp =~ /^[0-9]+$/ && 24 < $stmp && $stmp < 76 ){
				$left_portion = $stmp;
			} else {
				$left_portion = 50;
			}
		}
		# check right portion is defined (as well as left setting)
		if( $line =~ /^\s*split_right\s*=:/ && $left_portion ){
			$side_by_side = 1;
			if(1||$debug_flag){print "side_by_side setting detected [",$left_portion,":",100-$left_portion,"]\n"};
		}

		# 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;

		# convert URL plane statement to latex url definition (to support click and go)
		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 (debug only)
	if($debug_flag>1){
		my $a = 0;
		while( $a < $item_count ){
			print "---> [$a] $item_lines[$a]\n";
			++$a;
		}
		print "\n";
	}

	#--------------------------------------------
	# generate item stuff (real page creation)
	#--------------------------------------------
	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 = "";
		$block_set = 0;

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

			# ================================================
			#   page first line OR right side start line
			# ================================================
			if( $item_count == 0 || $right_block_start ){

				# -------------------------------------------
				#   check if side-by-side left side start
				# -------------------------------------------
				if( !$right_block_start ){
					if( $side_by_side && $item_lines[$item_count] =~ /^\s*split\\_left\s*=:/ ){
						print MID_FP "\t\\begin\{acolumns\}\[T\]\n";
						print MID_FP "\t\\begin\{column\}\{",$left_portion/100,"\\linewidth\}\n";
						print MID_FP "\t\\vspace{-0.2cm}\n";
						$item_count = $item_count + 1;
					}
				}
				$right_block_start = 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]);
					$block_set = 1;
					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);
					}

				# ------------------------------------------------------------
				#   check if first line described as image ( image =: )
				# ------------------------------------------------------------
				} elsif( $item_lines[$item_count] =~ /^image\s*=:/){
					$item_lines[$item_count] =~ s/^image\s*=:\s*//;

					# check if image file really xist
					my $image_file = $item_lines[$item_count];
					my $image_dir = "figure";
					&check_file_exist( $image_dir, $image_file );

					# check if image url defined
					my $image_url ="";
					my $image_height = "6.0cm";

					# check if image origin URL defined in the following line
					if($item_count < $item_count_max-1){
						if($item_lines[$item_count+1] =~ /^origin\s*=:.*http/ ){
							$image_url = $item_lines[$item_count+1];
							$image_url =~ s/^origin\s*=:\s*//;
							$image_height = "5.6cm";
						}
					}

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

				# ----------------------------------------------------------------------
				#   check if first line described as font size setting ( 22font22=: )
				# ----------------------------------------------------------------------
				} 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]);
						$block_set = 1;
						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]);
					}

				# ----------------------------------------------------------------------
				#   Normal first line contents = start block (wo/title) element
				# ----------------------------------------------------------------------
				} else {
				$item_lines[$item_count]= &color_check($item_lines[$item_count]);
				$block_set = 1;
				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)
				# =============================================

				# check if right part start
				if( $side_by_side && $item_lines[$item_count] =~ /^\s*split\\_right\s*=:/ ){
					print ">>>> right start : $block_set \n";
					if( $block_set ){
						print MID_FP "\t\t\\end{itemize}\n";
						&block_close(*MID_FP, $font_set);
						$block_set = 0;
					}
					print MID_FP "\t\\end\{column\}\n";
					print MID_FP "\t\\begin\{column\}\{",1-$left_portion/100,"\\linewidth\}\n";
					print MID_FP "\t\\vspace{-0.2cm}\n";
					$right_block_start = 1;
					$block_set = 0;

				} else {

				if( $item_lines[$item_count] =~ /^\s*1111/ && &term_check(\@item_lines,$item_count, $item_count_max) && $item_count != 1){
					# 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]);
					print MID_FP "\t\t\t\\begin{itemize}\n";
					if(length($font_set)){print MID_FP "\t\t\t\\$font_set\{\n"};
					&item_create(*MID_FP, $item_lines[$item_count]);
					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]);
							&item_create(*MID_FP, $item_lines[$item_count]);
							# if duplicate font size exist in nested item block
							if(length($font_set)){ print MID_FP "\t\t\t}\n"};
						} else {
							# detect one line indent (1111 to 8888)
							$item_count = $item_count -1;
						}
						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 summary block
					#---------------------
					$item_lines[$item_count] =~ s/^sumb\s*=://;
					if( $block_set ){
						print MID_FP "\t\t\\end{itemize}\n";
						&block_close(*MID_FP, $font_set);
						$block_set = 0;
					}
					if( $side_by_side ){ &split_close(*MID_FP); }
					$side_by_side = 0;
					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";
					++$item_count;
				} elsif ( $item_lines[$item_count] =~ /^sumr\s*=:/){
					#---------------------
					#  red summary block
					#---------------------
					$item_lines[$item_count] =~ s/^sumr\s*=://;
					if( $block_set ){
						print MID_FP "\t\t\\end{itemize}\n";
						&block_close(*MID_FP, $font_set);
						$block_set = 0;
					}
					if( $side_by_side ){ &split_close(*MID_FP); }
					$side_by_side = 0;
					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";
					++$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";
						&item_create(*MID_FP, $item_lines[$item_count]);
						print MID_FP "\t\t\t\\end{itemize}\n";
					} else {
						$item_lines[$item_count] = &color_check($item_lines[$item_count]);
						&item_create(*MID_FP, $item_lines[$item_count]);
					}
					++$item_count;
				}
			}
		}
		if($block_set){
			print ">> block closed <<\n";
			print MID_FP "\t\t\\end{itemize}\n";
			&block_close(*MID_FP, $font_set);
			$block_set = 0;
		}
	}

	#close side_by_silde settings
	if( $side_by_side ){ &split_close(*MID_FP); }

	# frame close
	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";
	}
}

# close block-element sub (w/check font size definition)
sub block_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";
	}
}

# convert blank line to vertical space
# Now blank line is deleted at the bigging of process
# Alternatively, defined <feed> for setting line space
sub item_interval{
	local	*MFP	= $_[0];
	my		$LN		= $_[1];
	

	if($LN =~ /^\s*\\<feed\\>/ ){
		print MFP "\t\t\t\\vspace{0.3cm}\n";
	} else {
		print MFP "\t\t\t\\item $LN\n";
	}
}

# item contents generation w/image wrong definition check
sub item_create{
	local	*MFP	= $_[0];
	my		$ITM	= $_[1];

	if($ITM =~ /^image\s*=:/){
		#item contains image file definition (failure)
		$ITM =~ /(?<=\=:)(.*)/;
		print "\n\033[31mYou cannot set image file [ \033[33m$1 \033[31m] in block element\n";
		print "\033[0m\n";
		exit(-1);
	} else {
		print MFP "\t\t\t\t\\item $ITM\n";
	}
}

# close side-by-split (at the end of right portion)
sub split_close{
	local	*MFP	= $_[0];

	print MFP "\t\\end\{column\}\n";
	print MFP "\t\\end\{acolumns\}\n";
}

# check if identified file exist 
sub check_file_exist{
	my	$dir_name	= $_[0];
	my	$file_name	= $_[1];

	chdir $dir_name or die "033[31m Can not fine image file sub-directory named figure\n\n";
	if( -f $file_name ){
		# file exist
		chdir '..';
	} else {
		# if not exist, force quit with error
		print "\n\033[31mImage file [ \033[33m$file_name \033[31m] does not exist in [ \033[33m$dir_name \033[31m] directory!\n";
		print "\033[0m\n";
		exit(-1);
	}
}

