const breakparse [ parsebreak = 1 ]

const doparse [
  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) [
    strtoparse = $arg1
    charcontainer = $arg2
    parsecode = $arg3
    if (> $numargs 3) [
      parsebackwards = $arg4
    ] [ parsebackwards = 0 ]
    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
  addListOnQuit (at $CHARACTERTESTS $cel)
]

// trimAllUnnecessaryWhitespace - Returns a modified string after removing any unnecessary leading and trailing whitespace from the original.
const trimAllUnnecessaryWhitespace [
  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)) [
    return (substr $strtotrim $charsbegin (- (+ $charsend 1) $charsbegin))
  ] [ return $strtotrim ]
]
// trimAllWhitespace - Returns a modified string after removing any whitespace characters from the original.
const trimAllWhitespace [
  strtotrim = $arg1
  trimmedstr = []
  parsestring $strtotrim twh [
    if (! (testchar $twh $ISWHITESPACE)) [
      trimmedstr = (concatword $trimmedstr $twh)
    ]
  ]
  return $trimmedstr
]

addListOnQuit [parsebreak parselen strtoparse parsebackwards charcontainer dpl parsecode cel strtotrim charsbegin charsend tch __tch thc __thc twh trimmedstr]
