
	#syscall numbers
	.set n_ioctl, 54

        #file descriptors.
        .set stdin, 0
        .set stdout, 1
        .set stderr, 2

	#ioctl numbers.
	.set TCGETS, 0x402c7413  #get terminal info (termios struct).
	.set TCSETS, 0x802c7414  #set terminal info (also termios struct).
	.set TIOCGWINSZ, 0x40087468  #get terminal size.

        #structure defines.

        #termios:
        .set iflag, 0
        .set oflag, 4
        .set cflag, 8
        .set lflag, 12
                .set ECHO, 0x08
                .set ISIG, 0x80
                .set ICANON, 0x100
        .set cc, 16
                .set VINTR, 0
                .set VQUIT, 1
                .set VSUSP, 12
                .set VMIN, 5
                .set VTIME, 7

        #term_size:
        .set t_rows, 0
        .set t_cols, 2
        .set t_w, 4
        .set t_h, 6

	#a couple of useful macros...
	.macro prolog
	mflr r0
	stwu r0,-4(r1)
	.endm

	.macro epilog
	lwz r0,0(r1)
	addi r1,r1,4
	mtlr r0
	blr
	.endm

	#allocate structures
        .comm termios_old, 44  #structure to hold old termios settings
        .comm termios_new, 44  #and new termios settings
        .comm termsize, 8      #and terminal size


#code.....
        .text

#takes a pointer to termios struct (44 bytes) in r5.
        .global get_termios
get_termios:
        li r3,stdin
        lis r4,TCGETS@ha
        addi r4,r4,TCGETS@l
        li r0,n_ioctl
        sc
        blr

#takes a pointer to termios struct (44 bytes) in r5.
        .global set_termios
set_termios:
        li r3,stdin
        lis r4,TCSETS@ha
        addi r4,r4,TCSETS@l
        li r0,n_ioctl
        sc
        blr

#takes a pointer to term_size struct (8 bytes) in r5.
        .global get_term_size
get_term_size:
        li r3,stdin
        lis r4,TIOCGWINSZ@ha
        ori r4,r4,TIOCGWINSZ@l
        li r0,n_ioctl
        sc
        blr

        .global init_termios
init_termios:
        prolog
        lis r5,termsize@ha             #get terminal size
        addi r5,r5,termsize@l
        bl get_term_size
        lis r5,termios_old@ha          #save old term options
        addi r5,r5,termios_old@l
        bl get_termios
        lis r5,termios_new@ha          #get another copy of term options,
        addi r5,r5,termios_new@l
        bl get_termios
        lis r5,termios_new@ha          #clear ECHO, ISIG, and ICANON,
        ori r5,r5,termios_new@l
        lwz r3,lflag(r5)
        li r4,~(ECHO | ISIG | ICANON)
        and r3,r3,r4
        stw r3,lflag(r5)
        bl set_termios                 #and set our new options
        epilog

        .global cleanup_termios
cleanup_termios:
        lis r5,termios_old@ha          #restore old term options
        ori r5,r5,termios_old@l
        b set_termios
