#include "stdio.h"
#include "types.h"
#include "stat.h"
#include "dir.h"

_main(argc,argv)
int argc;
char *argv[];
{
    int j;
    if (argc == 1)
	ls(".");
    else
        for (j=1; j < argc; ++j)
        {
	    ls(argv[j]);
        }

    exit(0);

}



ls(path)
char *path;
{
    struct direct buf;
    struct stat statbuf;
    char dname[128];
    int d;

    
    d = open(path,0);
    if (d < 0)
    {
	perror(path);
	return;
    }

    fstat(d,&statbuf);
    if ((statbuf.st_mode & F_MASK) != F_DIR)
    {
	describe(path);
    }
    else
    {

        while (read(d,(char *)&buf,16) == 16)
        {
	    if (buf.d_name[0] == '\0')
	        continue;

	    if (path[0] != '.' || path[1] )
	    {
	        strcpy(dname,path);
	        strcat(dname,"/");
	    }
	    else
	        dname[0] = '\0';
	    strcat(dname,buf.d_name);

	    describe(dname);
        }
        close(d);
    }
}


describe(name)
char *name;
{
    char line[64];
    char *ctime();
    struct stat statbuf;

	if (stat(name,&statbuf) != 0)
	{
	    sprintf(line,"ll: can't stat %s",name);
	    perror(line);
	    return;
	}

	if ((statbuf.st_mode & F_MASK) == F_DIR)
	    strcat(name,"/");

	printf("%-6d %-15s",
		(statbuf.st_mode & F_CDEV) ?
		    statbuf.st_rdev :
		    512*statbuf.st_size.o_blkno + statbuf.st_size.o_offset,
		name);

	printf("  0%-6o %-2d %-5d %s\n", statbuf.st_mode, statbuf.st_nlink,
		statbuf.st_ino,ctime(&statbuf.st_mtime));
}
