added error and memory handlings