Calculate the bounded cumulative sum of a vector The cumulative sum of a vector is calculated by simply taking the sum of all previous elements. For instance:

vec =     [1  1  1 -1 -1 -1 -1 -1  1  1  1  1 -1]
cum_vec = [1  2  3  2  1  0 -1 -2 -1  0  1  2  1]


Now, impose an upper and a lower limit, meaning that you stop increasing the cumulative sum if it's at the upper limit, and stop decreasing the cumulative sum if it's at the lower limit. A simple example:

upper_lim = 2
lower_lim = -1
vec =     [1  1  1 -1 -1 -1 -1 -1  1  1  1  1 -1]
cum_vec = [1  2  2  1  0 -1 -1 -1  0  1  2  2  1]


The input vector consists of integers, not necessarily only 1 and -1, both positive and negative. Assume that upper_lim &gt;= lower_lim. If the first element of the vector is outside the boundary, jump directly to the boundary (see last example).

Write a function that takes a vector of integers as input, and two integers that represent the upper and lower limits. Output the bounded cumulative vector, as defined above. The input can be as either function arguments or from STDIN. 

Standard code golf rules apply.

Examples:

upper_lim = 6
lower_lim = -2
vec =     [1  4  3 -10  3  2  2  5 -4]
cum_vec = [1  5  6  -2  1  3  5  6  2]

upper_lim = 100
lower_lim = -100
vec =     [1  1  1  1  1  1]
cum_vec = [1  2  3  4  5  6]

upper_lim = 5
lower_lim = 0
vec =     [10 -4 -3  2]
cum_vec = [5   1  0  2]

upper_lim = 0
lower_lim = 0
vec =     [3  5 -2  1]
cum_vec = [0  0  0  0]

upper_lim = 10
lower_lim = 5
vec =     [1  4  6]
cum_vec = [5  9 10]
           |
           Note, jumped to 5, because 5 is the lower bound.
CJam, 16 15 bytes

l~f{\T++$1=:T}`


Try it online

This takes the list as first argument, and the pair of upper/lower limit as a second 2-element list. Example input:

[1 4 3 -10 3 2 2 5 -4] [6 -2]


The latest version saves 1 byte by sorting the 3 values, and taking the middle value, instead of using a max and min operation. This was also used in Jakube's solution, as well as suggested by Martin.

Explanation:

l~    Get and parse input. This leaves the value and bounds lists on the stack.
f{    Apply block with value (the bounds list).
  \     Swap new value to top.
  T     Get previous value from variable T (which is default initialized to 0).
  +     Add new value and previous value.
  +     Append new value to bounds list, producing a 3 value list.
  $     Sort it...
  1=    And take the middle value.
  :T    Store in variable T for next iteration.
}     End of apply loop.
`     Convert list to string.