#include <sys/types.h>
#include <dirent.h>
#include <sys/time.h> 
#include <unistd.h>
#include <sys/stat.h>
#include <errno.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
#include <sys/socket.h>

#define NODEFINE
#include <u.h>
#include <libc.h>
#include <fcall.h>
#include "fd.h"

long
pm_pread(int fd, void *a, long n, vlong offset)
{
	off_t off;
	File *f;

	if(offset == -1)
		return pm_read(fd, a, n);
		
	if(offset < 0){
		pm_werrstr("negative pread offset");
		return -1;
	}
	off = offset;
	if((vlong)off != offset){
		pm_werrstr("pread offset does not fit in off_t");
		return -1;
	}
	if((f = pm_lockfile(fd, 0)) == nil)
		return -1;
	switch(f->type){
	default:
		pm_werrstr("unknown file type in pm_pread");
		n = -1;
		break;
	case Tdir:
		pm_werrstr("no pread in directory");
		n = -1;
		break;
	case Tfile:
		n = pread(f->ufd, a, n, off);
		if(n < 0){
			pm_oserror();
			n = -1;
		}
		break;
	}
	pm_qunlock(&f->lk);
	return n;
}
