Added more logic to open connection