const breakparse [ parsebreak = 1 ]

const doparse [
  tempalias parselen (strlen $strtoparse)
  loop dpl $parselen [
    if $parsebreak break [
      if $parsebackwards [
        $charcontainer = (substr $strtoparse (- (- $parselen $dpl) 1) 1)
        (format __%1 $charcontainer) = (- (- $parselen $dpl) 1)
      ] [
        $charcontainer = (substr $strtoparse $dpl 1)
        (format __%1 $charcontainer) = $dpl
      ]
      execute $parsecode
    ]
  ]
]

const parsestring [
  if (> $numargs 2) [
    tempalias strtoparse $arg1
    tempalias charcontainer $arg2
    tempalias parsecode $arg3
    if (> $numargs 3) [
      tempalias parsebackwards $arg4
    ] [ tempalias parsebackwards 0 ]
    tempalias parsebreak 0
    doparse
  ]
]

// make helpful consts for use with (testchar)
const CHARACTERTESTS [ISDIGIT ISALPHA ISALNUM ISLOWERCASE ISUPPERCASE ISCHAR ISPUNCT ISWHITESPACE]
loop cel (listlen $CHARACTERTESTS) [
  const (at $CHARACTERTESTS $cel) $cel
]

// trimAllUnnecessaryWhitespace - Returns a modified string after removing any unnecessary leading and trailing whitespace from the original.
const trimAllUnnecessaryWhitespace [
  tempalias strtotrim $arg1
  forceinit [charsbegin charsend] -1
  parsestring $strtotrim tch [
    if (! (testchar $tch $ISWHITESPACE)) [
      charsbegin = $__tch
      breakparse
    ]
  ]
  parsestring $strtotrim thc [
    if (! (testchar $thc $ISWHITESPACE)) [
      charsend = $__thc
      breakparse
    ]
  ] 1
  if (&& (&& (!= $charsbegin -1) (!= $charsend -1)) (!= $charsbegin $charsend)) [
    result (substr $strtotrim $charsbegin (- (+ $charsend 1) $charsbegin))
  ] [ result $strtotrim ]
]
// trimAllWhitespace - Returns a modified string after removing any whitespace characters from the original.
const trimAllWhitespace [
  tempalias strtotrim $arg1
  trimmedstr = []
  parsestring $strtotrim twh [
    if (! (testchar $twh $ISWHITESPACE)) [
      trimmedstr = (concatword $trimmedstr $twh)
    ]
  ]
  result $trimmedstr
]

