//
//
//
define array col_flg  100;
define array col_name 100;
define array col_attr 100;
define array col_val  100;
define n_flg;
proc main;
	option  1 1;
	option 10 1;	// variable is private 

	if (%0 < 1);
		putline('usage: ',SCRIPTNAME,' in_file');
		return -1;
	end if;
	loop %0;
		try;
			fpi = fpo = 0;
			fpi = fopen(%1);
			fgetline(fpi);
			line = fgetline(fpi);
			n = getargs(line,1,,',');
			table_name = $1;
			file = table_name & '_data.sql';
			fpo = fopen(file,'w');

			line = fgetline(fpi);
			n_flg = getargs(line,col_flg,,',');
			fgetline(fpi);
			line = fgetline(fpi);
			n = getargs(line,col_name,,',');
			line = fgetline(fpi);
			n = getargs(line,col_attr,,',');
			fgetline(fpi);
			line = fgetline(fpi);
			col = mk_col();
			line = fgetline(fpi);
			n = getargs(line,col_val,,',');
			h_val = mk_val();

			sql0 = 'insert into ' & table_name & '(' & col &
			        ',' & stm & ')value(' & h_val & ',';
			try;
				loop;
					line = fgetline(fpi);
					n = getargs(line,col_val,,',');
					if col_val[0];
						sql = sql0 & mk_val() &')';
						fputline(fpo,sql);
					end if;
				end loop;
			end try;
			shift;
		catch FILE_READ_END_EXCEPTION;
		catch;
			print /e ERRMSG;
			break;
		finally;
			if (fpi) thenl fclose(fpi);
			if (fpo) thenl fclose(fpo);
		end try;
	end loop;
	return ERROR;
end proc;

func mk_col;
	i = 1;
	stm = '';
	loop n_flg-1;
		if col_flg[i] then
			if stm thenl stm &= ',';
			stm &= col_name[i];
		end if;
		i++;
	end loop;
	return stm;
end func;

func mk_val;
	i = 1;
	stm = '';
	loop n_flg-1;
		if col_flg[i] then
			if stm thenl stm &= ','
			v = col_val[i];
			if v then
				if ilike(col_attr[i],'%CHAR%','%DATE%','%TIME%') then
					v = '''' & v & '''';
				end if;
			else
				v = 'NULL';
			end if;
			stm &= v;
		end if;
		i++;
	end loop;
	return st;
end func;
