#include"e1e-e5e.h"
#include<sys/stat.h>
#include<sys/types.h>
#include<pwd.h>
#include<grp.h>
#include<time.h>

void print_ls(int nfiles, struct dirent **showfiles, int m0de){
	struct stat file;
	struct tm *machinetime;

	/* Each field of 'ls -l' [long format] */
	char permstring[11];	permstring[10]= '\0';
	nlink_t nlinks;
	struct passwd *userdata;
	struct group *groupdata;
	off_t fsize;
	char *dateformat= "%04d-%02d-%02d %02d:%02d ";
	char *name;

	int k, totalkb;
	if( (m0de == 2) || (m0de == 6) ){	/* Long Formats */
		totalkb= get_kilobytes(nfiles, showfiles);
		printf("total %d\n", totalkb);

		for(k=0; k < nfiles; k++){
			name= showfiles[k]->d_name;

			/* Getting current file's information */
			stat(name, &file);
			nlinks= file.st_nlink;
			fsize= file.st_size;

			userdata= getpwuid(file.st_uid);
			groupdata= getgrgid(file.st_gid);

			machinetime= localtime(&file.st_mtime);

			mode_string(file.st_mode, permstring);	/* filemode.c from GNU/fileutils-4.1 */

			/*** PRINTING LS LONG FORMAT ***/

			fprintf(stdout, "%s ", permstring);
			fprintf(stdout, "%4u ", (unsigned int) nlinks);
			fprintf(stdout, "%s\t", userdata->pw_name);
			fprintf(stdout, "%s\t", groupdata->gr_name);
			fprintf(stdout, "%9u ", (unsigned int) fsize);
			fprintf(stdout, dateformat,
				machinetime->tm_year+YEARS_UTC,
				machinetime->tm_mon+1,
				machinetime->tm_mday,
				machinetime->tm_hour,
				machinetime->tm_min);
			fprintf(stdout, "%s\n", name);

			/*** END PRINTING LS LONG FORMAT***/

			memset(&file, 0x00, sizeof(file));
		}
	}
	else{	/* Normal format */
		for(k=0; k < nfiles; k++){
			if( (k != 0) && ((k % 7) == 0) )
				fprintf(stdout, "\n");

			name= showfiles[k]->d_name;
			fprintf(stdout, "%s\t", name);
		}

		fprintf(stdout, "\n");
	}
}
