added more type checking; created separated functions for different tasks