improved code for open function