Added thread-safe implementation; changed API to support two implementations.