#!/usr/bin/perl -i.bak

use English;

## get input
undef $INPUT_RECORD_SEPARATOR;
$file = <>;

## transform it
$lineBeginningWithParensRE = '^\(.*?\)\W*\w+.*$';
$wordOrDot = '(?:\w|\.)';
$lineBeginningWithNumberedHalfParensRE = "^$wordOrDot+?\\).*\$";
$lineBeginningWithStarRE = '^\*+ .*$';
$lineBeginningWithNumberSignRE = '^#+ .*$';

#TODO: Embedded lists

$file =~ s/($lineBeginningWithParensRE\n($lineBeginningWithParensRE\n)+)/itemizeParens($1)/mge;

$file =~ s/($lineBeginningWithNumberedHalfParensRE\n($lineBeginningWithNumberedHalfParensRE\n)+)/itemizeNumberedHalfParens($1)/mge;

$file =~ s/($lineBeginningWithStarRE\n($lineBeginningWithStarRE\n)+)/itemizeStar($1)/mge;

$file =~ s/($lineBeginningWithNumberSignRE\n($lineBeginningWithNumberSignRE\n)+)/itemizeNumberSign($1)/mge;





# print output
print $file; 





############
# END OF MAIN
############




sub itemizeParens {
    my $expr = $_[0];

    $expr =~ s/^(\(.*?\))/\\item[$1]/mg;

    $expr = "\\begin{itemize}\n".$expr."\\end{itemize}\n";

    return $expr;
}


sub itemizeStar {
  # this is essential the same as "itemizeNumberSign"

    my $expr = $_[0];

    $expr =~ s/^\* /\\item /mg;
    $expr =~ s/^\*\*/*/mg;

    $expr = "\\begin{itemize}\n".$expr."\\end{itemize}\n";

    # recurse
    $expr =~ s/(($lineBeginningWithStarRE\n)+)/itemizeStar($1)/mge;

    return $expr;
}

sub itemizeNumberSign {
  # this is essentially the same as "itemizeStar"

    my $expr = $_[0];

    $expr =~ s/^\# /\\item /mg;
    $expr =~ s/^\#\#/#/mg;

    $expr = "\\begin{enumerate}\n".$expr."\\end{enumerate}\n";

    # recurse
    $expr =~ s/(($lineBeginningWithNumberSignRE\n)+)/itemizeNumberSign($1)/mge;

    return $expr;
}



sub itemizeNumberedHalfParens {
    my $expr = $_[0];

    $expr =~ s/^(.*?\))/\\item[$1]/mg;

    $expr = "\\begin{itemize}\n".$expr."\\end{itemize}\n";

    return $expr;
}


