# basic_frame for console prog, gui_frame for awt prog
#   Single class library don't need use frame [$list ...]

subcode: basic_frame
    $function main
        $call main

#---- containers --------------------
subcode: iter(L, item)
    $import java.util.*
    $temp Iterator it = $(L).iterator()
    $while $(it).hasNext()
        $my $(item) = $(it).next()
        BLOCK

subcode: map_iter(M)
    $import java.util.*
    $temp Set set = $(M).entrySet()
    $temp Iterator it = $(set).iterator()
    $while $(it).hasNext()
        $my Map.Entry entry = (Map.Entry)$(it).next()
        $(set:key=entry.getKey())
        $(set:value=entry.getValue())
        BLOCK

#---- BufferedReader ----
subcode: input(file)
    $import java.io.*
    $(if:file=-)
        # InputStreamReader wraps byte stream into char stream
        $(set:in=new InputStreamReader(System.in))
    $(else)
        $throws IOException
        $(set:in=new FileReader($(file)))
    BufferedReader In = new BufferedReader($(in));
    BLOCK
    In.close();

    subcode: get_s(v)
        $(v) = In.readLine()

#---- Scanner ----
subcode: scanner(file)
    $import java.io.*
    $import java.util.Scanner
    $(if:file=-)
        $(set:in=System.in)
    $(else)
        $throws IOException
        $(set:in=new File($(file)))
    scanner = new Scanner($(in))
    BLOCK

    subcode: get_s(v)
        $(v) = scanner.nextLine()

    subcode: get_word(v)
        $(v) = scanner.next()

    subcode: get_int(v)
        $(v) = scanner.nextInt()

    subcode: get_double(v)
        $(v) = scanner.nextDouble()

#---------------------------------------- 
subcode: open_r(file)
    &call input, $(file)
        $while true
            String s = In.readLine();
            $if s==null
                break
            BLOCK

subcode: open_w(file)
    out = new PrintWriter(new File($(file)))
    BLOCK
    out.close()

subcode: open_W(file)
    &call open_w, $(file)
        $(set:print_to=out)
        BLOCK
# ----
subcode: load_img(file)
    $import java.io.*
    $import java.awt.image.*
    $import javax.imageio.*
    BufferedImage img = null;
    try {
        img = ImageIO.read(new File("$(file)"));
    } catch (IOException e) {
        $print IOException
    }

#---- timing ------------------------------------ 
subcode: start_time
    $local long time_start
    time_start = System.nanoTime()

subcode: print_time(msg)
    $local long time_diff
    time_diff = System.nanoTime()-time_start
    $print "$(msg): %f sec", time_diff / 1.0e9

#---- random ---------------------------------- 
subcode: init_random
    $private rand = new Random()

macros:
    irand: rand.nextInt($1)
    rand: rand.nextFloat()
#----------------------------------------
macros:
    atoi: Integer.parseInt($1)
    atof: Double.parseDouble($1)

    itoa: Integer.toString($1)

#---------------------------------------- 
subcode: try
    try {
        BLOCK
    }
    catch(Exception e){
        $print Got exception
    }
