Examine the following code and tell me if there are any errors and how to fix them:   import requests
import os.path

class BookCatalogue:
    def __init__(self):
        self.books = []

    def add_book(self, title, author, genres, pages, status, start_date, finish_date, rating):
        book = {
            'title': title,
            'author': author,
            'genres': genres,
            'pages': pages,
            'status': status,
            'start_date': start_date,
            'finish_date': finish_date,
            'rating': rating
        }

        if finish_date:
            book['status'] = 'read'

        self.books.append(book)
        self._write_to_file()
        print(f'Book "{title}" added to the catalogue.')

    def view_books(self):
        if not self.books:
            print('No books in the catalogue.')
        else:
            for i, book in enumerate(self.books, start=1):
                print(f"{i}. {book['title']} by {book['author']}")
    
    def view_book_details(self, search_book):
        matching_books = [book for book in self.books if book['title'].lower() == search_book.lower()]
        if not matching_books:
            print('No books under that title in the catalogue.')
        else:
            for i, book in enumerate(matching_books, start=1):
                print(f"{i}. {book['title']} by {book['author']}")
                print(f"Genre(s): {book['genres']}")
                print(f"Pages: {book['pages']}")
                print(f"Status: {book['status']}")
                print(f"Started Reading: {book['start_date']}")
                print(f"Finished Reading: {book['finish_date']}")
                print(f"Rating: {book['rating']}")

    def view_books_by_genre(self, genre):
        genre_books = [book for book in self.books if genre in book['genres']]
        if not genre_books:
            print(f'No books found in the genre: {genre}.')
        else:
            print(f'Books in the genre "{genre}":')
            for i, book in enumerate(genre_books, start=1):
                print(f"{i}. {book['title']} by {book['author']}, Pages: {book['pages']}")
                if book['start_date']:
                    print(f"   Started Reading: {book['start_date']}")
                if book['finish_date']:
                    print(f"   Finished Reading: {book['finish_date']}")
                if book['rating']:
                    print(f"   Rating: {book['rating']}/5")
                print()

    def view_books_by_author(self, author):
        author_books = [book for book in self.books if author.lower() in book['author'].lower()]
        if not author_books:
            print(f'No books found by the author: {author}.')
        else:
            print(f'Books by the author "{author}":')
            for i, book in enumerate(author_books, start=1):
                print(f"{i}. {book['title']}, Genre(s): {book['genres']}, Pages: {book['pages']}")
                if book['start_date']:
                    print(f"   Started Reading: {book['start_date']}")
                if book['finish_date']:
                    print(f"   Finished Reading: {book['finish_date']}")
                if book['rating']:
                    print(f"   Rating: {book['rating']}/5")
                print()
    
    def view_read_books(self):
        read_books = [book for book in self.books if book['status'] == 'read']
        if not read_books:
            print("Yikes! Seems like you haven't read any books yet. Sorry about that")
        else:
            print('Read Books:')
            for i, book in enumerate(read_books, start=1):
                print(f"{i}. {book['title']} by {book['author']}, Genre(s)): {book['genres']}, Pages: {book['pages']}")
                if book['start_date']:
                    print(f"   Started Reading: {book['start_date']}")
                if book['finish_date']:
                    print(f"   Finished Reading: {book['finish_date']}")
                if book['rating']:
                    print(f"   Rating: {book['rating']}/5")
                print()

    def view_TBR_books(self):
        TBR_books = [book for book in self.books if book['status'] == 'to be read']
        if not TBR_books:
            print("Well that's unfortunate... No books with 'To Be Read' status.")
        else:
            print('To Be Read Books:')
            for i, book in enumerate(TBR_books, start=1):
                print(f"{i}. {book['title']} by {book['author']}, Genre(s): {book['genres']}, Pages: {book['pages']}")
                if book['start_date']:
                    print(f"   Started Reading: {book['start_date']}")
                if book['finish_date']:
                    print(f"   Finished Reading: {book['finish_date']}")
                if book['rating']:
                    print(f"   Rating: {book['rating']}/5")
                print()       
    
    def edit_book(self, title):
        matching_books = [book for book in self.books if book['title'].lower() == title.lower()]

        if not matching_books:
            print(f'No book found with the title: {title}.')
        elif len(matching_books) == 1:
            book_to_edit = matching_books[0]
            print(f'Editing book with title: {title}. Leave input blank to keep current information.')
            
            new_author = input(f'Enter new author (current: {book_to_edit["author"]}): ')
            new_genres = input(f'Enter new genres (comma-separated) (current: {", ".join(book_to_edit["genres"])}): ')
            new_pages = input(f'Enter new number of pages (current: {book_to_edit["pages"]}): ')
            new_status = input(f'Enter new status (read/To Be Read) (current: {book_to_edit["status"]}): ').lower()
            new_start_date = input(f'Enter new start date (DD/MM/YYYY)(current: {book_to_edit["start_date"]}): ')
            new_finish_date = input(f'Enter new finish date (DD/MM/YYYY)(current: {book_to_edit["finish_date"]}): ')
            new_rating = input(f'Enter new rating (leave blank if not rated) (current: {book_to_edit["rating"]}): ')

            if new_author:
                book_to_edit['author'] = new_author
            if new_genres:
                book_to_edit['genres'] = [genres.strip() for genres in new_genres.split(',')]
            if new_pages:
                book_to_edit['pages'] = new_pages
            if new_status:
                book_to_edit['status'] = new_status
            if new_start_date:
                book_to_edit['start_date'] = new_start_date
            if new_finish_date:
                book_to_edit['finish_date'] = new_finish_date
                book_to_edit['status'] = 'read' # Automatically set status to 'read' if finish_date is provided
            if new_rating:
                book_to_edit['rating'] = new_rating
            
            self._write_to_file()
            print(f'Book "{title}" edited successfully.')
        else:
            print(f'Multiple books found with the title: {title}. Please try deleting repeated titles.')

    def delete_book(self, title):
        matching_books = [book for book in self.books if book['title'].lower() == title.lower()]

        if not matching_books:
            print(f'No book found with the title: {title}.')
        elif len(matching_books) == 1:
            self.books.remove(matching_books[0])
            print(f'Book "{title}" deleted from the catalogue.')
        else:
            print(f'Multiple books found with the title: {title}.')
            delete_all = input('Do you wish to delete all books matching that title? (Y/N)')
            if delete_all == 'Y':
                self.books.remove(matching_books)
            elif delete_all == 'N':
                print('No books were deleted')

    def get_google_books_data(self, title):
        api_url = 'https://www.googleapis.com/books/v1/volumes'
        params = {'q': title}

        response = requests.get(api_url, params=params)

        if response.status_code == 200:
            data = response.json()
            if 'items' in data:
                book_id = data['items'][0]['id']
                return self.get_book_details(book_id)
            else:
                print(f'Book "{title}" not found on Google Books.')
        else:
            print(f'Error accessing Google Books API. Status code: {response.status_code}')

    def get_book_details(self, book_id):
        api_url = f'https://www.googleapis.com/books/v1/volumes/{book_id}'

        response = requests.get(api_url)

        if response.status_code == 200:
            book_data = response.json()['volumeInfo']
            return {
                'title': book_data.get('title', ''),
                'author': ', '.join(book_data.get('authors', [])),
                'rating': book_data.get('averageRating', ''),
                'rating_count': book_data.get('ratingsCount', '')
            }
        else:
            print(f'Error accessing Google Books API. Status code: {response.status_code}')
    
    def _write_to_file(self):
        with open('books.txt', 'w', encoding='utf-8') as file:
            for book in self.books:
                genres_str = ', '.join(book['genres'])
                file.write(f"{book['title']}|{book['author']}|{genres_str}|{book['pages']}|{book['status']}|{book['start_date']}|{book['finish_date']}|{book['rating']}\n")

#--------------THE MAGIC SAUCE FOR TESTING PURPOSES---------------------
def load_books_from_file(path, catalogue):
    try:
        with open(path, 'r', encoding='utf-8') as file:
            for line in file:
                book_details = line.strip().split('|')
                title, author, genres, pages, status, start_date, finish_date, rating = book_details
                catalogue.add_book(title, author, genres, pages, status, start_date, finish_date, rating)
        print(f'Books loaded from file: {path}')
    except FileNotFoundError:
        print(f'File not found: {path}. No books added to the catalogue.')

def main():
    catalogue = BookCatalogue()
    view_books_option = None
    filtered_genre = None
    filtered_author = None
    
    # I wish I could say this was ChatGPT or ourselves, the logic below for path formation was in fact obtained from stackoverflow :)
    my_path = os.path.abspath(os.path.dirname(os.path.abspath(__file__)))
    path = os.path.join(my_path, "books.txt")
    load_books_from_file(path, catalogue)

    while True:
        print('\nBook Catalogue CLI Menu:')
        print('1. Add Book')
        print('2. View Books')
        print('3. Delete Book')
        print('4. Edit Book')
        print('5. Get Google Books Data')
        print('6. Exit')

        choice = input('Enter your choice (1-6): ')

        if choice == '1':
            print('entries with * are necessary, everything else is optional but highly encouraged :)')
            title = input('Enter book title *: ')
            author = input('Enter author *: ')
            genres = input('Enter genre(s): ')
            pages = input('Enter number of pages: ')
            status = input('Enter status (read/To Be Read): ').lower()
            start_date = input('Enter start date (DD/MM/YYYY): ')
            finish_date = input('Enter finish date (DD/MM/YYYY): ')
            rating = input('Enter rating: ')
            catalogue.add_book(title, author, genres, pages, status, start_date, finish_date, rating)
        elif choice == '2':
            print('\nView Books Options:')
            print('1. View All Books')
            print('2. View Books by Genre')
            print('3. View Books by Author')
            print('4. View Books you have read')
            print('5. View Books you want to read (TBR list)')
            print('6. View Details of a Book')
            print('7. Back to Main Menu')

            view_books_option = input('Enter your choice (1-7): ')

            if view_books_option == '1':
                catalogue.view_books()
            elif view_books_option == '2':
                filtered_genre = input('Enter genre to view books: ')
                catalogue.view_books_by_genre(filtered_genre)
            elif view_books_option == '3':
                filtered_author = input('Enter author to view books: ')
                catalogue.view_books_by_author(filtered_author)
            elif view_books_option == '4':
                catalogue.view_read_books()
            elif view_books_option == '5':
                catalogue.view_TBR_books()
            elif view_books_option == '6':
                search_book = input('Enter the title of the book to be searched:')
                catalogue.view_book_details(search_book)
            elif view_books_option == '7':
                view_books_option = None
                filtered_genre = None
                filtered_author = None
                continue
            else:
                print('Invalid choice. Please enter a number between 1 and 4.')
        elif choice == '3':
            title_to_delete = input('Enter the title of the book to delete: ')
            catalogue.delete_book(title_to_delete)
            continue
        elif choice == '4':
            title_to_edit = input('Enter the title of the book to edit: ')
            catalogue.edit_book(title_to_edit)
        elif choice == '5':
            title = input('Enter the title of the book to get Google Books data: ')
            book_data = catalogue.get_google_books_data(title)
            if book_data:
                print(f'\nGoogle Books Data for "{title}":')
                print(f'Title: {book_data["title"]}')
                print(f'Author: {book_data["author"]}')
                print(f'Rating: {book_data["rating"]}')
                print(f'Rating Count: {book_data["rating_count"]}')
        elif choice == '6':
            print('Exiting the program. Goodbye!')
            break
        else:
            print('Invalid choice. Please enter a number between 1 and 5.')

if __name__ == "__main__":
    main()