;==================== begin output-wrap.nls ====================================
; output-wrap - Same as output-print but wraps printed output.
;
; By Rik Blok, 2013 <http://www.zoology.ubc.ca/~rikblok/wiki/doku.php>
;
; This is free and unencumbered software released into the public domain.
;
; Anyone is free to copy, modify, publish, use, compile, sell, or
; distribute this software, either in source code form or as a compiled
; binary, for any purpose, commercial or non-commercial, and by any
; means.
;
; Provides:
;  
;   output-wrap
;     Wrap string into lines that fit at specified column.
;
; Usage:
;
;   ; two ways to instruct output-wrap to wrap lines at _column_
;   set output-wrap-at _column_ 
;   output-wrap _column_
;
;   ; write _string_ to output, wrapping at/before indicated column
;   output-wrap _string_        
;
; Example:
;
;   to setup
;     output-wrap 26
;     reset-timer
;   end
;   to go
;     output-wrap ( word timer " seconds elapsed." )
;   end
;
; Known limitations:
;
;   2013-07-31 - doesn't recognize "\n" line breaks
; 
; Revisions:
;
;   2013-07-31 - initial release by Rik Blok
;-------------------------------------------------------------------------------


; To discover the number of characters that will fit on one line (the best 
; column to wrap at), in Command Center enter something like
;   output-print "123456789a123456789b123456789c123456789d123456789e123456789"
; and count the number of characters before the output box first breaks the line.
globals 
[ output-wrap-at	; column to wrap at.  Set directly or call 'output-wrap _column_' to set.
]


to output-wrap
; Wrap string into lines that fit at specified column.
; Parameters:
[ string ; String to wrap or number of column to wrap at.
]  
  ; set column to wrap at?
  if (is-number? string and string > 0)
  [ set output-wrap-at string
    stop
  ]
  ; error trap
  if (output-wrap-at = 0)
  [ output-print "Error: first call 'output-wrap _column_' to set wrapping column."
    stop
  ]

  ; if string too long, break into separate lines
  while [length string > output-wrap-at]
  [ ; TODO: detect and handle "\n" line breaks
    ; find last space character
    let cut-at position " " reverse substring string 0 ( output-wrap-at - 1 )
    ; if no spaces, fill whole line
    if cut-at = false [ set cut-at -1 ]
    set cut-at output-wrap-at - cut-at - 1
    ; print this line
    output-print substring string 0 cut-at
    ; remove from string
    set string substring string cut-at ( length string )
    ; trim leading spaces
    while [first string = " "] [ set string but-first string ]
  ]
  while [first string = " "] [ set string but-first string ]
  output-print string
end
;==================== end output-wrap.nls ======================================