#!/usr/bin/perl

#*******************************************
##Student name: Davina Chin Lee Yien
##Student Id: 7D2A1001
##SPD251 Assignment 2 Question 1
##*******************************************

#Declaring the local variable
my(@source,@width,@height,@alt);

#initialize the value for the variable $count, $looping, and $args
$count=0;
$looping=0;
$args=@ARGV;

#to check whether the argument is passed in or not
if ($args==0){
	die "No arguments passed in. Please specify the filename\n";
}
else{
	#when there  is some argument passed in 
	my($files)=$ARGV[0];
	#checking to see whether the files exist or not 
	if (-e $files){
		#check to see whether the files is an html file or not
		if ($files=~ /[\W]*.html/i){
			#open the files specified 
			open(IN, $files);
			while(<IN>){
				#to check whether the files contain any images or not by tracing for the image tag
				while (s/\<img(([^\>]+)\>|([\n\w\W]*))//i){
					my ($inside)=$2;
					#later, get the source of the files
					if ($inside =~ /src\s*=\s*(\"([^\"]+)\"|[^\s]+)/i){
						if (defined($2)){
							#push is use to store the value in an array source
							push(@source,$2);
						}
						else{
							#push the value into an array source is $2 is not defined
							push(@source,$1);
						}
					}
					#capture the width of the images traced
					if ($inside =~ /width\s*=\s*(\"([^\"]+)\"|[^\s]+)/i){
						if (defined($2)){
							#push the value $2 into an array width
							push(@width,$2);
						}
						else{
							#push the value $1  into an array 
							push(@width,$1);
						}
					}
					#traced for the height, if specifiy 
					if ($inside =~ /height\s*=\s*(\"([^\"]+)\"|[^\s]+)/i){
						if (defined($2)){
							#push the valueof $2 into an array height
							push(@height,$2);
						}
						else{
							#push the value of $1 into an array height
							push(@height,$1);
						}
					}
					#traced for the alt if specify
					if ($inside =~ /alt\s*=\s*(\"([^\"]+)\"|[^\s]+)/i){
						if (defined($2)){
							#push the value of $1 into an array alt
							push(@alt,$2);
						}
						else{
							#push the value of $2 into an array alt
							push(@alt,$1);
						}
					}
					
					#increment the value count
					$count++;

				}
			}
			#print out the images in the specify files into stdout
			print "The image files in $files are as below:\n\n";
			while ($looping != $count){
				#printing the source, width height and alt
				print "Source: $source[$looping]\n";
				print "Width: $width[$looping]\n";
				print "Height: $height[$looping]\n";
				print "Alt name: $alt[$looping]\n\n";
				$looping++;
			}
			close(IN);
		}
		else{
			#error message when the files 
			die "Files is not HTML files.\n";
		}
	}
	else{
		#no such files, so error message
		die "File does not exist\n";
	}
}
