let next_counter (l:int list) (m:int list) = 
  let rec next_rec (first:int) (toread:int list) (result:int list) = 
    match toread with 
      | []   -> begin
          match next_value l first with 
            | Some t -> result@[t]
            | None   -> Array.to_list (Array.make ((List.length result)+2) (List.hd l))
        end;
      | y::d -> if (first<y) then match next_value l first with 
          | Some t -> result@(t::toread)
          | None   -> y::d (* Impossible case *)
        else
          next_rec y d (result@[first])
  in match m with 
    | []   -> [ List.hd l ]
    | x::c -> next_rec x c []