1#! gawk -f
2
3BEGIN {
4	isError = 0;
5
6	if (ARGC != 2){
7		print "packnlf [sample.nlf]" > "/dev/stderr";
8		isError = 1;
9		exit isError;
10	}
11
12	arcdir = "./package";
13	FS  = ",";
14	OFS = ",";
15	fcount = 0;
16
17	system("rm -rf "arcdir);
18	system("mkdir -p "arcdir);
19
20	oldnlf = ARGV[1];
21	gsub(/^.*\//,"",oldnlf);
22	newnlf = arcdir"/"oldnlf;
23}
24
25/^T,/{
26	root = dequote($2);
27	$2 = enquote(".");
28}
29
30/^H,/{
31	$2 = enquote(get_new_entry(dequote($2)));
32	$3 = enquote(get_new_entry(dequote($3)));
33}
34
35/^[97],/{
36	$2 = enquote(get_new_entry(dequote($2)));
37	$3 = enquote(get_new_entry(dequote($3)));
38	$4 = enquote(get_new_entry(dequote($4)));
39	$5 = enquote(get_new_entry(dequote($5)));
40	$6 = enquote(get_new_entry(dequote($6)));
41}
42
43/^F,/{
44	$7 = enquote(get_new_entry(dequote($7)));
45}
46
47{
48	print $0 >> newnlf;
49}
50
51
52END {
53	if (!isError){
54		arcname = arcdir strftime("-%y%m%d-%H%M.zip");
55		system("zip -r "arcname" "arcdir);
56	}
57	exit isError;
58}
59
60function get_new_entry(t)
61{
62	entry = t;
63
64	# Entries starting with * are pseudo-files, so they are not converted
65	if (entry ~/^[*]/){
66		return entry;
67	}
68
69	new_entry = "./"entry;
70	gsub(/:/,"_",   new_entry);
71	gsub(/\/\//,"/",new_entry);
72
73	# If : is included in the path, it is an absolute path.
74	# This is made into a relative path by changing ":" to "_"
75	if (entry !~/:/){
76		entry = root"/"entry;
77		gsub(/\/\//,"/",entry);
78	}
79
80	# Copying Files
81	cmd = "install -D "enquote(entry)" "enquote(arcdir"/"new_entry);
82	system(cmd);
83
84	return new_entry;
85}
86
87function dequote(t)
88{
89	# Remove "" (quotation marks)
90	entry = t;
91	sub(/^\"/, "", entry);
92	sub(/\"$/, "", entry);
93	return entry;
94}
95
96function enquote(t)
97{
98	# Enclose with "" (quotation marks)
99	entry = "\""t"\"";
100	return entry;
101}
102