merged code from Matt Lepinski