Your only problem is that you aren't updating the totwei
variable when you create a voxel.You will need to subtract the value of the voxel from the remaining desired weight, and add it to the total weight.
totwei = totwei + voxel
valleft = valleft - voxel