<?php
Class CSV {
	var $file;
	var $size=0;
	var $count=0;
	var $row=array();
	var $rows=array();
	var $delim;
	var $enclos;
	var $type;
	var $error;
	var $error_list=array(
		-1	=> "{rs:ERROR_FILE_NOT_FOUND}",
	);

	function CSV($delim=";", $enclos="\"", $type="to_array") {
		$this->delim=$delim;
		$this->enclos=$enclos;
		$this->type=$type;
	}

	function add_to_row($val) {
		if (($this->count and count($this->row)<$this->count) or (!$this->count)) $this->row[]=$this->enclos.$val.$this->enclos;
	}

	function add_row() {
		if (!$this->count) $this->count=count($this->row);
		$res=implode($this->delim, $this->row);
		if ($this->type=="to_array") $rows[]=$res;
		else print $res."\n";
		$this->row=array();
	}

	function save_row() {
		if (!$this->count) $this->count=count($this->row);
		$res=implode($this->delim, $this->row);
		if ($this->file) fwrite($this->file, $res."\n");
		$this->row=array();
	}

	function open($filename="", $type='r') {
		if ($this->file=fopen($filename, $type)) {
			$this->error=0;
			if ($type=='r') $this->size=filesize($filename);
		} else {
			$this->error=-1;
			$this->size=0;
		}
		return ($this->error<0 ? false : true);
	}

	function get_row() {
		if ($this->size) {
			return fgetcsv($this->file, $this->size, $this->delim, $this->enclos);
		} else return false;
	}

	function close() {
		if ($this->file) fclose($this->file);
	}

	function get_error() {
		return $this->error_list[$this->error];
	}

	function show() {
		print "<pre>".implode("\n", $this->rows)."</pre>";
	}
}
?>