 SYMBOL: n-registered-colors
 
 MEMO: register-color ( fg bg -- n )
-    [ n-registered-colors get ] 2dip ffi:init_pair curses-error
-    n-registered-colors [ get ] [ inc ] bi ;
+    [ n-registered-colors get dup ] 2dip ffi:init_pair curses-error
+    n-registered-colors inc ;
 
 : init-colors ( -- )
     ffi:has_colors [

        ] [ ffi:endwin curses-error ] [ ] cleanup
    ] with-destructors ; inline

TUPLE: curses-terminal < disposable
    infd outfd ptr ;

: <curses-terminal> ( infd outfd ptr -- curses-terminal )
    curses-terminal new-disposable
        swap >>ptr
        swap >>outfd
        swap >>infd ;

M: curses-terminal dispose
    [ outfd>> fclose ] [ infd>> fclose ]
    [ ptr>> ffi:delscreen ] tri ;

: init-terminal ( terminal -- curses-terminal )
    "xterm-color" swap [ "rb" fopen ] [ "wb" fopen ] bi
    [ ffi:newterm curses-pointer-error ] 2keep <curses-terminal> ;

: start-remote-curses ( terminal window -- curses-terminal )
    [
        init-terminal
        ffi:initscr curses-pointer-error drop
        dup ptr>> ffi:set_term curses-pointer-error drop
    ] dip [ apply-global-options ] [ apply-window-options ] bi ;
    
<PRIVATE

: (wcrefresh) ( window-ptr -- ) ffi:wrefresh curses-error ; inline
: (wcwrite) ( string window-ptr -- ) swap ffi:waddstr curses-error ; inline

:: (wcread) ( n encoding window-ptr -- string )
    [


: wcread ( n window -- string )
    [ encoding>> ] [ ptr>> ] bi (wcread) ;
: cread ( n -- string ) current-window get wcread ;

: wgetch ( window -- key ) ptr>> (wgetch) ;
: getch ( -- key ) current-window get wgetch ;
