organized the code for better readability. Also handled badlink scenario better